簡體   English   中英

Flask:使用unittest進行測試 - 如何從響應中獲取.post json

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

我正在用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數據。 BTW它可以在一些javascript框架消耗我的api時工作,即我可以從響應中獲取json。 但現在我需要在python中測試代碼。

我希望你的代碼拋出這個異常:

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM