Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: testing with unittest - how to get .post json from response

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.

like image 881
yerassyl Avatar asked Mar 17 '17 10:03

yerassyl


1 Answers

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))
like image 200
Naishy Avatar answered Oct 11 '22 16:10

Naishy