测试Flask响应是否为JSON [英] Test if Flask response is JSON
问题描述
如何测试Flask视图生成的响应是JSON?
How can I test that the response a Flask view generated is JSON?
from flask import jsonify
@app.route('/')
def index():
return jsonify(message='hello world')
c = app.app.test_client()
assert c.get('/').status_code == 200
# assert is json
推荐答案
从Flask 1.0开始,response.get_json()
会将响应数据解析为JSON或引发错误.
As of Flask 1.0, response.get_json()
will parse the response data as JSON or raise an error.
response = c.get("/")
assert response.get_json()["message"] == "hello world"
jsonify
将内容类型设置为application/json
.此外,您可以尝试将响应数据解析为JSON.如果解析失败,则测试将失败.
jsonify
sets the content type to application/json
. Additionally, you can try parsing the response data as JSON. If it fails to parse, your test will fail.
from flask import json
assert response.content_type == 'application/json'
data = json.loads(response.get_data(as_text=True))
assert data['message'] == 'hello world'
通常,单独进行此测试是没有意义的.您知道它是JSON,因为jsonify
返回没有错误,并且Flask已经对jsonify
进行了测试.如果它不是有效的JSON,则在序列化数据时会收到错误消息.
Typically, this test on its own doesn't make sense. You know it's JSON since jsonify
returned without error, and jsonify
is already tested by Flask. If it was not valid JSON, you would have received an error while serializing the data.
这篇关于测试Flask响应是否为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!