[英]Test if Flask response is JSON
如何測試 Flask 視圖生成的響應是否為 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 或引發錯誤。
response = c.get("/")
assert response.get_json()["message"] == "hello world"
jsonify
將內容類型設置為application/json
。 此外,您可以嘗試將響應數據解析為 JSON。 如果解析失敗,您的測試將失敗。
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,您將在序列化數據時收到錯誤。
有一個 python 庫。
import json
#...
def checkJson(s):
try:
json.decode(s)
return True
except json.JSONDecodeError:
return False
如果您還想檢查它是否是有效字符串,請檢查“s”的邊界。您可以在 python 網站https://docs.python.org/3.5/library/json.html上閱讀幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.