Python 如何在单元测试中使用 JSON 发送请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28836893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:48:56  来源:igfitidea点击:

How to send requests with JSONs in unit tests

pythonjsonflaskpython-unittest

提问by Sepehr Nazari

I have code within a Flask application that uses JSONs in the request, and I can get the JSON object like so:

我在 Flask 应用程序中有代码,它在请求中使用 JSON,我可以像这样获取 JSON 对象:

Request = request.get_json()

This has been working fine, however I am trying to create unit tests using Python's unittest module and I'm having difficulty finding a way to send a JSON with the request.

这一直工作正常,但是我正在尝试使用 Python 的 unittest 模块创建单元测试,但我很难找到一种方法来发送带有请求的 JSON。

response=self.app.post('/test_function', 
                       data=json.dumps(dict(foo = 'bar')))

This gives me:

这给了我:

>>> request.get_data()
'{"foo": "bar"}'
>>> request.get_json()
None

Flask seems to have a JSON argument where you can set json=dict(foo='bar') within the post request, but I don't know how to do that with the unittest module.

Flask 似乎有一个 JSON 参数,你可以在 post 请求中设置 json=dict(foo='bar') ,但我不知道如何使用 unittest 模块来做到这一点。

采纳答案by Sepehr Nazari

Changing the post to

将帖子更改为

response=self.app.post('/test_function', 
                       data=json.dumps(dict(foo='bar')),
                       content_type='application/json')

fixed it.

修复。

Thanks to user3012759.

感谢用户 3012759。

回答by Victor Gavro

UPDATE:Since Flask 1.0 released flask.testing.FlaskClientmethods accepts jsonargument and Response.get_jsonmethod added, see example.

更新:由于 Flask 1.0 发布的flask.testing.FlaskClient方法接受添加的json参数和Response.get_json方法,请参见示例

for Flask 0.x you may use receipt below:

对于 Flask 0.x,您可以使用以下收据:

from flask import Flask, Response as BaseResponse, json
from flask.testing import FlaskClient
from werkzeug.utils import cached_property


class Response(BaseResponse):
    @cached_property
    def json(self):
        return json.loads(self.data)


class TestClient(FlaskClient):
    def open(self, *args, **kwargs):
        if 'json' in kwargs:
            kwargs['data'] = json.dumps(kwargs.pop('json'))
            kwargs['content_type'] = 'application/json'
        return super(TestClient, self).open(*args, **kwargs)


app = Flask(__name__)
app.response_class = Response
app.test_client_class = TestClient
app.testing = True