[根据https://stackoverflow.com/a/46369945/1021819,标题应引用集成测试而不是单元测试]
假设我想测试以下Flask API(来自here):
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响应对象(参见http://werkzeug.pocoo.org/docs/0.11/wrappers/)),我无法找到{{1}的等价物。 } json()
Response对象的方法。
如何对第二个requests
?
答案 0 :(得分:29)
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>
答案 1 :(得分:25)
我发现我可以通过将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]
答案 2 :(得分:17)
你在那里做的不是单元测试。在每种情况下,当使用请求库或烧瓶客户端时,在对端点进行实际的http调用并测试交互时,您正在执行integration testing。
问题的标题或方法都不准确。
答案 3 :(得分:2)
使用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'})
This question给出了解释。
答案 4 :(得分:0)
来自 response
的 test_client
对象有一个 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"},
)