I am doing unit testing in flask with python3. I have method that returns json:
@app.route('/doctor/book_appointment', methods=['POST'])
def some_method():
resp = {
"status": "",
"message": ""
}
return jsonify(resp)
So inside my unittest I try this:
headers = {
'ContentType': 'application/json',
'dataType': 'json'
}
data = {
'key1': 'val1',
'key2': 'val2'
}
response = self.test_app.post('/doctor/book_appointment',
data=json.dumps(data),
content_type='application/json',
follow_redirects=True)
self.assertEqual(response.status_code, 200)
# hot to get json from response here
# I tried this, but doesnt work
json_response = json.loads(resp.data)
My response object is of Response streamed type. How do I get json from it. Since some_method returns jsonified data. BTW it works when some javascript framework consumes my api, i.e I could get json from response. But now I need to test code in python here.
I expect that your code is throwing this exception:
TypeError: the JSON object must be str, not 'bytes'
The code below should return the JSON:
headers = {
'ContentType': 'application/json',
'dataType': 'json'
}
data = {
'key1': 'val1',
'key2': 'val2'
}
response = self.test_app.post('/doctor/book_appointment',
data=json.dumps(data),
content_type='application/json',
follow_redirects=True)
self.assertEqual(response.status_code, 200)
json_response = json.loads(response.get_data(as_text=True))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With