user1762571
user1762571

Reputation: 1949

How to repeat a test with pytest after every other test?

I have few test cases as described below. But i want to repeat test1() after every other test case. how can i achieve this?

@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

Upvotes: 0

Views: 859

Answers (1)

hoefling
hoefling

Reputation: 66171

You can modify the list of tests to be executed by implementing the pytest_collection_modifyitems hook. Example: In your root dir, create a file named conftest.py and add the hook to it:

def pytest_collection_modifyitems(session, config, items):
    test1s = [item for item in items if item.function.__name__ == 'test_test1']
    items.extend(test1s)

Now the test_test1 will be appended to the list of already collected tests, being executed twice:

$ 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 ===========================

A more elegant solution would be using a custom marker, let's name it my_repeat:

@pytest.mark.my_repeat
@pytest.mark.parametrize(a,b,c)
def test_test1():
    ...

Adapted hook in conftest.py:

def pytest_collection_modifyitems(session, config, items):
    repeats = [item for item in items if item.get_marker('my_repeat')]
    items.extend(repeats)

Upvotes: 1

Related Questions