测试 Flask 响应是否为 JSON [英] Test if Flask response is JSON

查看:28
本文介绍了测试 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.

这篇关于测试 Flask 响应是否为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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