【发布时间】:2021-06-26 22:41:45
【问题描述】:
基本上,我正在尝试对路由列表的每次迭代进行测试,以检查与特定函数关联的网页是否返回有效状态代码。
我想要一些类似的东西:
import pytest
from flask import url_for
from myflaskapp import get_app
@pytest.yield_fixture
def app():
# App context and specific overrides for test env
yield get_app()
@pytest.yield_fixture
def client(app):
yield app.test_client()
@pytest.yield_fixture
def routes(app):
routes = [
'foo',
'bar',
# There's quite a lot of function names here
]
with app.app_context():
for n, route in enumerate(routes):
routes[n] = url_for(route)
# yield url_for(route) #NOTE: This would be ideal, but not allowed.
# convert the routes from func names to actual routes
yield routes
@pytest.mark.parametrize('route', routes)
def test_page_load(client, route):
assert client.get(route.endpoint).status_code == 200
我了解到,由于解释/加载/执行顺序的某些原因,您不能将参数化与固定装置混合作为参数,但是,如何根据“最佳实践”来解决?
我看到了一个解决方案,您可以直接从函数生成测试,这看起来非常灵活,可能符合我想要的Passing pytest fixture in parametrize(虽然我不能直接使用调用夹具装饰函数,所以可能不会)
虽然,我是 pytest 的新手,但我希望看到更多示例,说明如何在几乎没有限制的情况下生成测试或在迭代中执行多个测试,同时遵守正确的 pytest 样式和 DRY 原则。 (我知道conftest.py)
如果这很重要,我会优先考虑多功能性/实用性而不是适当的样式。 (在合理的范围内,可维护性也是一个高优先级)
我希望能够参考这个问题的解决方案,以帮助指导我在未来如何处理构建我的测试,但我似乎一直遇到障碍/限制或被 pytest 告知我不能做 X 解决方案我也期望/想要的方式。
相关帖子:
- 干:pytest: parameterize fixtures in a DRY way
- 从函数生成测试:Passing pytest fixture in parametrize
- 非常简单的解决方案(不适用于这种情况):Parametrize pytest fixture
- PyTest 中的 Flask 应用上下文:Testing code that requires a Flask app or request context
- 避免使用多个列表装置的边缘情况:Why does Pytest perform a nested loop over fixture parameters
【问题讨论】: