测试 Flask 响应是否为 JSON

测试 Flask 响应是否为 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 没有错误返回,而且 jsonify 已经被 Flask 测试过.如果它不是有效的 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.