Setup your tests once per session while using pytest and xdist

Using pytest along with xdist can be a powerful way to run tests in parallel.
However, one of the caveats one should be aware of is the ‘one time setup’ (or teardown).

Normally, in pytest, when you want to execute something once per test session before running the tests, you could use the very useful pytest_sessionstart hook or a pytest fixture with scope="session". However, use this together with xdist and the setup is executed once per worker, not per test session.

One workaround to this is the following:

def pytest_sessionstart(session):
    # do something once per test session
    if get_xdist_worker_id(session) == "master":
        request_helpers.import_test_data(env)
        print("Test data are imported")


Do you want to run the tests without using xdist at all?
No problem! The function get_xdist_worker_id(session) should be equal with “master” when running in a single thread.


Note: This can be used in any other pytest hook or fixture to achieve the same results.


pytest version: 6.0.0
xdist version: 2.3.0