我有一些测试用例,如下所述。但是我想在其他所有测试用例之后重复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

最佳答案

您可以通过实现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)

09-10 07:33
查看更多