2017-03-17 5 views
1

私はpython3でフラスコでユニットテストをしています。 フラスコ:unittestでテストする - 応答から.post jsonを得る方法

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

は、だから私のunittestの内側に、私はこれを試してみてください:

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を返すメソッドを持っています。どのように私はそれからjsonを得るのですか? some_methodはjsonifiedデータを返します。 BTWは、いくつかのjavascriptフレームワークが私のapiを消費しているときに動作します。つまり、応答からjsonを得ることができます。しかし、今はPythonでコードをテストする必要があります。

+0

はポスト要求 –

+0

からデータを取得するために 'response.form'をしようと私ができます問題を再現しません。 'json.loads(resp.data)'はJSONデータを読み込みます。 [編集]に[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)) 
関連する問題