pythonpytestpytest-xdist

Multiple pytest sessions during tests run


I am writing tests using pytest and pytest-xdist and I want to run pytest_sessionstart before all workers start running and pytest_sessionfinish when they are done.

I found this solution: link, but this is not working as expected. There are multiple sessions starting and finishing during test run. Hence multiple cleanups are done, which cause the tests to fail (it cleans tmp directory and tests fails with FileNotFoundError).

I added code to write to file when session is started and once it is finished. The log looks like this:

init    0x00007f988f5ee120 
worker init gw0 
...
worker init gw7 
init    0x00007f229cdac2e0 
cleanup 0x00007f229cdac2e0 0
init    0x00007f1a31a4e2e0 
cleanup 0x00007f1a31a4e2e0 0
worker done gw0 
...
worker done gw4 
cleanup 0x00007f988f5ee120 1

As you can see there are some session starting after all workers started and before they are done.

My code looks like this:

def pytest_sessionstart(session: pytest.Session):
    if hasattr(session.config, 'workerinput'):
        # log to file 'worker init {id}'
        return
    # log to file 'init {sess id}'
    # do some stuff

def pytest_sessionfinish(session: pytest.Session, exitstatus: int):
    if hasattr(session.config, 'workerinput'):
        # log to file 'worker done {id}'
        return
    # log to file 'cleanup {sess id} {exitstatus}'
    # do some stuff

Solution

  • It turned out that vs-code starts pytest in background with --collect-only argument. Those session were not filtered as they were not worker sessions and they performed init / cleanup.

    The solution is to add checking if argument --collect-only is present.

    Code:

    def pytest_sessionfinish(session: pytest.Session, exitstatus: int):
        if hasattr(session.config, 'workerinput'):
            return
        if '--collect-only' in session.config.invocation_params.args:
            return
        # do some stuff