Flask:使用unittest进行测试 - 如何从响应

时间:2017-03-17 10:32:03

标签: python flask python-unittest

我正在用python3在烧瓶中进行单元测试。 我有返回json的方法:

@app.route('/doctor/book_appointment', methods=['POST'])
def some_method():
  resp = {
          "status": "",
          "message": ""
        }
  return jsonify(resp)

所以在我的单元测试中我试试这个:

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)

我的响应对象是Response流式。我如何从中获取json。由于some_method返回jsonified数据。顺便说一下,当一些javascript框架消耗我的api时,它可以工作,即我可以从响应中获取json。但现在我需要在python中测试代码。

1 个答案:

答案 0 :(得分:6)

我希望您的代码抛出此异常:

  

TypeError:JSON对象必须是str,而不是' bytes'

下面的代码应该返回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))