我正在使用pytest.我在目录中有两个文件.在其中一个文件中有一个长时间运行的测试用例,它会生成一些输出.在另一个文件中有一个读取该输出的测试用例.如何确保两个测试用例的正确执行顺序?除了以正确的顺序将测试用例放在同一个文件中之外,还有其他选择吗?
Fra*_*k T 25
通常,您可以使用其明确指定的钩子来配置pytest的基本任何部分的行为.
在您的情况下,您需要"pytest_collection_modifyitems"挂钩,它允许您在适当的位置重新排序收集的测试.
也就是说,看起来好像订购你的测试应该更容易 - 毕竟这是Python!所以我写了一个用于订购测试的插件:"pytest-ordering".查看文档或从pypi安装它.现在我建议使用@ pytest.mark.first和@ pytest.mark.second,或@ pytest.mark.order#markers之一,但我对更有用的API有一些想法.建议欢迎:)
swi*_*mer 15
正如@Frank T在接受的答案中所指出的, pytest_collection_modifyitemshook hook 允许修改收集的测试 ( items) 的顺序。这种方法的优点是不需要任何第三方库。
有关如何按测试类强制执行测试用例执行顺序的完整示例已在此答案中提供。
但在这种情况下,您似乎希望通过测试模块(即.py测试所在的文件)强制执行执行顺序。以下调整将允许您这样做:
# conftest.py
def pytest_collection_modifyitems(items):
"""Modifies test items in place to ensure test modules run in a given order."""
MODULE_ORDER = ["tests.test_b", "tests.test_c", "tests.test_a"]
module_mapping = {item: item.module.__name__ for item in items}
sorted_items = items.copy()
# Iteratively move tests of each module to the end of the test queue
for module in MODULE_ORDER:
sorted_items = [it for it in sorted_items if module_mapping[it] != module] + [
it for it in sorted_items if module_mapping[it] == module
]
items[:] = sorted_items
Run Code Online (Sandbox Code Playgroud)
将上面的代码片段替换为-> ->conftest.py默认的字母测试执行顺序-> -> 。模块可以位于不同的测试子目录中,并且模块内的测试顺序保持不变。test_atest_btest_ctest_btest_ctest_a
小智 11
Pytest 的固定装置可用于以类似于排序固定装置创建的方式来排序测试。虽然这是非常规的,但它利用了您可能已经拥有的固定系统知识,它不需要单独的包,并且不太可能被 pytest 插件更改。
@pytest.fixture(scope='session')
def test_A():
pass
@pytest.mark.usefixtures('test_A')
def test_B():
pass
Run Code Online (Sandbox Code Playgroud)
如果有多个测试依赖于 test_A,该作用域会阻止对 test_A 的多次调用。
重要的是要记住,在尝试修复 pytest 排序“问题”时,按照指定的顺序运行测试似乎是 pytest 的默认行为。
事实证明,由于这些软件包之一,我的测试不符合该顺序 - pytest-dependency, pytest-depends, pytest-order。一旦我用 卸载它们pip uninstall package_name,问题就消失了。看起来它们有副作用
小智 5
也许您可以考虑使用pytest 依赖项插件,可以在其中轻松设置测试依赖项:
@pytest.mark.dependency()
def test_long():
pass
@pytest.mark.dependency(depends=['test_long'])
def test_short():
pass
Run Code Online (Sandbox Code Playgroud)
这种方式test_short只有在test_long成功的情况下才会执行,并且也会强制执行顺序。
还有一个插件pytest-ordering,似乎符合您的要求.
| 归档时间: |
|
| 查看次数: |
21484 次 |
| 最近记录: |