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
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
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'
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.
There is a python-library for it.
import json
#...
def checkJson(s):
try:
json.decode(s)
return True
except json.JSONDecodeError:
return False
If you also want to check if it is a valid string, check the boundaries for "s. You can read the help here on pythons website https://docs.python.org/3.5/library/json.html .