[英]How to apply integration tests to a Flask RESTful API
[根據https://stackoverflow.com/a/46369945/1021819 ,標題應該指的是集成測試而不是單元測試]
假設我想測試以下 Flask API(來自此處):
import flask
import flask_restful
app = flask.Flask(__name__)
api = flask_restful.Api(app)
class HelloWorld(flask_restful.Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
if __name__ == "__main__":
app.run(debug=True)
將其保存為flaskapi.py
並運行它后,在同一目錄中我運行腳本test_flaskapi.py
:
import unittest
import flaskapi
import requests
class TestFlaskApiUsingRequests(unittest.TestCase):
def test_hello_world(self):
response = requests.get('http://localhost:5000')
self.assertEqual(response.json(), {'hello': 'world'})
class TestFlaskApi(unittest.TestCase):
def setUp(self):
self.app = flaskapi.app.test_client()
def test_hello_world(self):
response = self.app.get('/')
if __name__ == "__main__":
unittest.main()
兩個測試都通過了,但是對於第二個測試(在TestFlaskApi
定義)類,我還沒有弄清楚如何斷言 JSON 響應符合預期(即{'hello': 'world'}
)。 這是因為它是flask.wrappers.Response
一個實例(它可能本質上是一個 Werkzeug Response 對象(參見http://werkzeug.pocoo.org/docs/0.11/wrappers/ )),我還沒有能夠為requests
Response對象找到等效的json()
方法。
如何對第二個response
的 JSON 內容進行斷言?
Flask 提供了一個 test_client 可以在你的測試中使用:
from source.api import app
from unittest import TestCase
class TestIntegrations(TestCase):
def setUp(self):
self.app = app.test_client()
def test_thing(self):
response = self.app.get('/')
assert <make your assertion here>
我發現我可以通過將json.loads()
應用於get_data()
方法的輸出來獲取 JSON 數據:
import unittest
import flaskapi
import requests
import json
import sys
class TestFlaskApiUsingRequests(unittest.TestCase):
def test_hello_world(self):
response = requests.get('http://localhost:5000')
self.assertEqual(response.json(), {'hello': 'world'})
class TestFlaskApi(unittest.TestCase):
def setUp(self):
self.app = flaskapi.app.test_client()
def test_hello_world(self):
response = self.app.get('/')
self.assertEqual(
json.loads(response.get_data().decode(sys.getdefaultencoding())),
{'hello': 'world'}
)
if __name__ == "__main__":
unittest.main()
兩項測試均按預期通過:
..
----------------------------------------------------------------------
Ran 2 tests in 0.019s
OK
[Finished in 0.3s]
你在那里做的不是單元測試。 在每種情況下,在使用請求庫或 Flask 客戶端時,您都是在對端點進行實際 http 調用並測試交互時進行集成測試。
問題的標題或方法都不准確。
使用 Python3,我收到錯誤TypeError: the JSON object must be str, not bytes
。 需要解碼:
# in TestFlaskApi.test_hello_world
self.assertEqual(json.loads(response.get_data().decode()), {'hello': 'world'})
這個問題給出了解釋。
來自test_client
的response
對象有一個get_json
方法。
無需使用json.loads
將響應轉換為 json。
class TestFlaskApi(unittest.TestCase):
def setUp(self):
self.app = flaskapi.app.test_client()
def test_hello_world(self):
response = self.app.get("/")
self.assertEqual(
response.get_json(),
{"hello": "world"},
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.