我在jsonify中有一个返回http://127.0.0.1:5000/status响应的方法,所以当点击http://127.0.0.1:5000/status路由时,它应该在浏览器中呈现
[
{
user: "admin"
},
{
result: "OK - Healthy"
}
]方法是:
@app.route('/status')
def health_check():
response = [
{'user': 'admin'},
{'result': 'OK - Healthy'}
]
return jsonify(response)我试图构建一个测试用例来检查返回的jsonify(response)对象的内容:
class HealthStatusCase(unittest.TestCase):
def test_health_check(self):
response = health_check()
self.assertEqual(response, ['200 OK'])但是我不知道如何检查jsonify输出的内容,上面的测试是误导的。当我检查jsonify(response)的值时,我得到
pdb> jsonify(response)
<Response 71 bytes [200 OK]>
ipdb> 但我感兴趣的是访问response列表的内容,例如:
{'result': 'OK - Healthy'}和比较那个键值对。
更新
我遵循了建议的pytest方法,使用一个夹具向/status端点发出请求,因此测试用例现在如下所示:
@pytest.fixture
def test_health_check(client):
response = client.get('/status')
assert response.json == [
{'user': 'admin'},
{'result': 'OK - Healthy'}
]当我执行python -m pytest tests/test_health_check.py时,测试通过:
> python -m pytest tests/test_health_check.py
============================================================== test session starts ===============================================================
platform linux -- Python 3.10.6, pytest-7.2.0, pluggy-1.0.0
rootdir: /home/../../
plugins: flask-1.2.0
collected 1 item
tests/test_health_check.py . [100%]
=============================================================== 1 passed in 0.11s ================================================================但是,我忽略的一点是,如果我修改了assert response.json内容,让我们这样说:
@pytest.fixture
def test_health_check(client):
response = client.get('/status')
assert response.json == [
{'user': 'admin'},
{'result': 'OKdsdsd - Healthy'}
]测试也通过了--我知道一个特性旨在稀释一个行为并在测试中运行它,但是是否有一种方法可以与我的原始response列表中的json的原始值建立关系?我觉得这次考试毫无意义。
发布于 2022-11-17 01:06:35
最好使用pytest库进行测试。有了它,您的代码将非常简单。
def test_health_check(client):
response = client.get('/status')
assert response.json == [
{'user': 'admin'},
{'result': 'OK - Healthy'}
]关于测试的文章:https://flask.palletsprojects.com/en/2.2.x/testing/
pytest的文档:https://docs.pytest.org/
更新:
为了使上面的测试正常工作,您应该将其添加到tests/conftest.py中
import pytest
from my_project import create_app
@pytest.fixture()
def app():
app = create_app()
app.config.update({
"TESTING": True,
})
yield app
@pytest.fixture()
def client(app):
return app.test_client()
@pytest.fixture()
def runner(app):
return app.test_cli_runner()或者如果您没有smth作为create_app函数
import pytest
from my_project import app
@pytest.fixture()
def client(app):
return app.test_client()
@pytest.fixture()
def runner(app):
return app.test_cli_runner()复制自:https://flask.palletsprojects.com/en/2.2.x/testing/#fixtures
https://stackoverflow.com/questions/74468906
复制相似问题