我的测试用例很少,如下所述。但我想在每个其他测试用例之后重复test1()。我怎么能做到这一点?
@pytest.mark.test1()
@pytest.mark.parametrize(a,b,c)
def test_test1():
......
......
@pytest.mark.test2()
def test_test2():
......
......
@pytest.mark.test3()
def test_test3():
......
......
run test1() again
答案 0 :(得分:1)
您可以通过实现pytest_collection_modifyitems
挂钩来修改要执行的测试列表。示例:在根目录中,创建一个名为conftest.py
的文件并为其添加挂钩:
def pytest_collection_modifyitems(session, config, items):
test1s = [item for item in items if item.function.__name__ == 'test_test1']
items.extend(test1s)
现在test_test1
将被附加到已经收集的测试列表中,执行两次:
$ pytest -v
============================= test session starts =============================
platform darwin -- Python 3.6.3, pytest-3.4.0, py-1.5.2, pluggy-0.6.0 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-49213392, inifile:
plugins: celery-4.1.0, forked-0.2, cov-2.5.1, asyncio-0.8.0, xdist-1.22.0, mock-1.6.3, hypothesis-3.44.4
collected 5 items
test_spam.py::test_test1[a] PASSED [ 12%]
test_spam.py::test_test1[b] PASSED [ 25%]
test_spam.py::test_test1[c] PASSED [ 37%]
test_spam.py::test_test2 PASSED [ 50%]
test_spam.py::test_test3 PASSED [ 62%]
test_spam.py::test_test1[a] PASSED [ 62%]
test_spam.py::test_test1[b] PASSED [ 62%]
test_spam.py::test_test1[c] PASSED [ 62%]
========================== 8 passed in 0.02 seconds ===========================
更优雅的解决方案是使用自定义标记,我们将其命名为my_repeat
:
@pytest.mark.my_repeat
@pytest.mark.parametrize(a,b,c)
def test_test1():
...
conftest.py
中的自适应挂钩:
def pytest_collection_modifyitems(session, config, items):
repeats = [item for item in items if item.get_marker('my_repeat')]
items.extend(repeats)