Flask:使用unittest进行测试 - 如何从响应中获取.post json

yer*_*syl 6 python flask python-unittest

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

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

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

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)
Run Code Online (Sandbox Code Playgroud)

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

Nai*_*shy 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))
Run Code Online (Sandbox Code Playgroud)