使用py.test程序性地收集或创建测试
我正在写一个pytest插件,目的是在运行测试之前对它们进行排序。我想找到一种更好的方法来为我的插件编写测试。
我使用了pytest的 pytest_collection_modifyitems
钩子,然后根据某些标记直接修改 items
。测试这个功能最简单的方法就是准备一个pytest测试的输入列表,把它们传给我的函数,然后检查输出是否按正确的顺序排列。
我在收集或创建输入测试列表时遇到了困难。输入的测试应该和pytest传入 pytest_collection_modifyitems
钩子的 items
格式相同,也就是说,它们应该是 _pytest.python.Function
的实例,并且要有适当的标记。
我欢迎任何关于如何 1) 从现有的Python模块中收集测试,或者 2) 程序化地创建看起来像会传给 pytest_collection_modifyitems
钩子的 _pytest.python.Function
实例的答案。任何能让生成测试数据变得简单的方法都可以。
1 个回答
5
我建议你使用更高级的测试方法,利用 testdir
这个工具,它在pytest插件中很常见,并且可以通过 pytester
插件获得:
pytest_plugins = "pytester"
def test_something(testdir):
"""Test some thing."""
testdir.makepyfile("""
import pytest
@pytest.mark.some
def test_some():
assert True
@pytest.mark.some_thing_else
def test_some_thing_else():
assert True
""")
result = testdir.runpytest('-vv')
assert result.stdout.lines[-4:-2] == [
u'test_something.py::test_some PASSED',
u'test_something.py::test_some_thing_else PASSED'
]
这样你就可以轻松地在源代码中进行多种测试组合和标记,并通过检查输出的行来验证实际的顺序。