[英]How to fix json decode error in flask test_client().post()?
[英]Flask.test_client().post and JSON encoding
我正在Flask应用程序中为JSON端点编写测试用例。
import unittest
from flask import json
from app import create_app
class TestFooBar(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
def test_ham(self):
resp = self.client.post('/endpoint',
headers={'Content-Type': 'application/json'},
data=json.dumps({'foo': 2,
'bar': 3}))
assert resp.status_code == 200
def test_eggs(self):
resp = self.client.post('/endpoint', data={'foo': 5,
'bar': 7})
assert resp.status_code == 200
def test_ham_and_eggs(self):
with self.app.test_client() as self.client:
self.test_ham()
self.test_eggs()
只是为了了解正在发生的事情,以上代码中发送POST
消息的两种方式都有意义吗? 特别是在第一种情况下,我是否使用双JSON编码?
或者,简短地说, test_ham
和test_eggs
什么test_eggs
? 有没有?
您不是对JSON双重编码,不,因为data
不会对JSON进行任何编码。 test_ham
发布JSON,而test_eggs
不发布。
从Flask 1.0开始,Flask测试客户端支持通过json
关键字参数直接发布JSON,并使用它在此处减少样板代码:
def test_ham(self):
resp = self.client.post('/endpoint', json={'foo': 2, 'bar': 3})
assert resp.status_code == 200
请参阅“烧瓶测试”文档章节的“ 测试JSON API”部分 :
在测试客户端方法中传递
json
参数json
请求数据设置为JSON序列化的对象,并将内容类型设置为application/json
。
将字典传递给data
会产生不同类型的请求, application/x-www-form-urlencoded
编码的请求就像<form method="POST" ...>
表单一样会从您的浏览器中产生,而foo
和bar
值必须通过request.form
对象访问。 需要发布JSON时不要使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.