2017-03-17 73 views
1

我在做單元測試燒瓶python3得到。員額JSON。 我有方法,返回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) 

我響應對象響應流類型。我如何從中獲取json。由於some_method返回jsonified數據。順便說一句,它的工作原理時,一些JavaScript框架消耗我的API,即我可以得到JSON的迴應。但是現在我需要在python中測試代碼。

+0

嘗試'response.form'從POST請求 –

+0

我可以得到的數據不會重現你的問題。 'json.loads(resp.data)'加載JSON數據。請[edit]包含[mcve]。 – davidism

+0

順便說一下,這不是單元測試,這是集成測試。 –

回答

3

我期待你的代碼拋出此異常:

TypeError: the JSON object must be str, not '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))