Kur*_*eek 22 python integration-testing werkzeug flask flask-restful
[根据/sf/answers/3245896181/,标题应参考集成测试而不是单元测试]
假设我想测试以下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)
Run Code Online (Sandbox Code Playgroud)
将此保存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()
Run Code Online (Sandbox Code Playgroud)
两个测试都通过了,但对于第二个测试(在TestFlaskApi类中定义),我还没有弄清楚如何断言JSON响应是否符合预期(即{'hello': 'world'}).这是因为它是一个实例flask.wrappers.Response(可能基本上是一个Werkzeug响应对象(参见http://werkzeug.pocoo.org/docs/0.11/wrappers/)),但我找不到相应的Response对象的json()方法.requests
如何对第二个JSON内容进行断言response?
The*_*ist 34
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>
Run Code Online (Sandbox Code Playgroud)
Kur*_*eek 25
我发现我可以通过应用于方法json.loads()的输出来获取JSON数据get_data():
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()
Run Code Online (Sandbox Code Playgroud)
两个测试都按照需要通过:
..
----------------------------------------------------------------------
Ran 2 tests in 0.019s
OK
[Finished in 0.3s]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27701 次 |
| 最近记录: |