2017-03-17 78 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))