[英]Flask.test_client().post and JSON encoding
I am writing test cases for JSON endpoints in a Flask app. 我正在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()
Just to understand what's happening, do both ways of sending a POST
message in the code above make sense? 只是为了了解正在发生的事情,以上代码中发送
POST
消息的两种方式都有意义吗? In particular, am I double-JSON encoding in the first case? 特别是在第一种情况下,我是否使用双JSON编码?
Or, briefly, what is the difference between test_ham
and test_eggs
? 或者,简短地说,
test_ham
和test_eggs
什么test_eggs
? Is there any? 有没有?
You are not double-encoding JSON, no, because data
doesn't encode anything to JSON. 您不是对JSON双重编码,不,因为
data
不会对JSON进行任何编码。 test_ham
posts JSON, test_eggs
does not. test_ham
发布JSON,而test_eggs
不发布。
Starting from Flask 1.0, the Flask test client supports posting JSON directly, via the json
keyword argument, use it to cut down on boilerplate code here: 从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
See the Testing JSON APIs section of the Flask Testing documentation chapter: 请参阅“烧瓶测试”文档章节的“ 测试JSON API”部分 :
Passing the
json
argument in the test client methods sets the request data to the JSON-serialized object and sets the content type toapplication/json
.在测试客户端方法中传递
json
参数json
请求数据设置为JSON序列化的对象,并将内容类型设置为application/json
。
Passing a dictionary to data
produces a different kind of request, a application/x-www-form-urlencoded
encoded request just like a <form method="POST" ...>
form would produce from your browser, and the foo
and bar
values would have to be accessed via the request.form
object . 将字典传递给
data
会产生不同类型的请求, application/x-www-form-urlencoded
编码的请求就像<form method="POST" ...>
表单一样会从您的浏览器中产生,而foo
和bar
值必须通过request.form
对象访问。 Do not use it when posting JSON is needed. 需要发布JSON时不要使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.