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

标签 python json flask python-unittest

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

Request = request.get_json()

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

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

这给了我:

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

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

最佳答案

把帖子改成

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

修复它。

感谢用户 3012759。

关于python - 如何在单元测试中使用 JSON 发送请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28836893/

相关文章:

python - 仅递归调用internal_dep中存在的键值或跳过跳过列表中存在的键值

Python MySQL mysql.connector 使用column_names属性构建返回

javascript - Parse Cloud 代码迭代结果问题

python - 我什么时候会在 monogoengine 的内置 JSON 序列化(from_json 和 to_json)上使用像 marshmallow 这样的外部序列化器?

python - python Flask 中的模块化路线

python - 如何在测试时可靠地终止进程?

python - 使用不同的 python 版本运行多个 CherryPy Web 应用程序

JSON 关联数组到 Dart/Flutter 对象

java - 具有 2 个相同类型嵌套对象的 Json 对象

python - 我如何在 Python/Flask 中干净地做 slugs?