如何在单元测试中使用JSON发送请求 [英] How to send requests with JSONs in unit tests
问题描述
我有一个在应用程序中使用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')在发布请求中,但是我不知道如何使用unittest模块来做到这一点。
response = self.app.post('/ test_function',
data = json.dumps(dict(foo ='bar')),
content_type ='application / json')
固定它。
感谢user3012759。
I have code within a Flask application that uses JSONs in the request, and I can get the JSON object like so:
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.
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.
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.
这篇关于如何在单元测试中使用JSON发送请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!