如何在单元测试中使用JSON发送请求 [英] How to send requests with JSONs in unit tests

查看:117
本文介绍了如何在单元测试中使用JSON发送请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在应用程序中使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆