Section 12.32

pytest-xdist

Full name: pytest-xdist: the name of a plugin for pytest; its documentation describes it as the plugin for distributed testing, and neither part of the name is an abbreviation.

Definition

pytest-xdist is a plugin for pytest §12.31, the Python §12.23 testing framework, that runs one test suite in several worker processes at the same time to shorten the run. A controller process starts the workers, every worker collects the same tests, and the controller hands tests out to the workers and merges their results into one report. Each worker is a separate Python process with its own memory and its own fixtures. Files, network ports, devices and databases outside the processes stay shared, so tests that use them can interfere.

The idea

A suite of 200 tests, each taking 0.5 seconds, runs for 200×0.5=100200 \times 0.5 = 100 seconds in one process. A machine with 4 processor cores could run four tests at a time and finish in about 100/4=25100 / 4 = 25 seconds. pytest-xdist does exactly that: pytest -n 4 starts 4 workers.

Running tests at the same time is safe only for tests that share nothing they change. In one process, tests run one after another, so a file one test writes is complete before the next test reads it. In two worker processes, two tests run at the same moment. Both may write /tmp/out.json, both may try to accept network connections on port 8080, and both may send bytes to the same serial device. Moving tests into separate processes separates their Python objects, not the world outside. A kitchen with several cooks is a fair picture: each cook has a cutting board, as each worker has its own memory, but they share one oven, as workers share a device, and adding cooks does not add ovens. The picture stops at coordination. Cooks see each other; worker processes know nothing of each other unless the test code coordinates them through something they can all see, such as a lock file.

How it works

  1. Start. pytest -n 4 starts 4 worker processes; -n auto lets the plugin pick the number from the processor cores of the machine. The workers are named gw0, gw1 and so on.

  2. Collection. Every worker collects the whole test suite by itself. The controller checks that all workers collected the same tests in the same order, and stops with an error if they did not. A test list built by iterating over a set of strings can differ between workers, because Python randomizes string hashing separately in each process, and with it the iteration order of such a set.

  3. Distribution. The option --dist chooses how tests are assigned to workers:

    • load, the default with -n: each pending test goes to any free worker;

    • loadscope: the tests of one module, or of one test class, go to the same worker;

    • loadfile: the tests of one file go to the same worker;

    • loadgroup: tests marked @pytest.mark.xdist_group(name="radio") with the same group name go to the same worker;

    • worksteal: the suite is split among the workers at the start, and a worker that runs out of tests takes some from another;

    • each: every test runs on every worker.

  4. Execution. Each worker runs its tests one at a time, with the ordinary pytest fixture rules inside its own process. A session-scoped fixture is therefore set up once in every worker that needs it. A test can read its worker’s name from the worker_id fixture or from the environment variable PYTEST_XDIST_WORKER.

  5. Report. The controller merges the results into one summary. If a worker crashes, the test it was running is reported as failed and a new worker is started in its place, up to the limit set by --max-worker-restart.

Doing something once for all workers. The pytest-xdist documentation shows a pattern for work that must happen only once per run. Each worker takes a file lock in a directory that all workers share, tmp_path_factory.getbasetemp().parent. The first worker to get the lock does the work and writes the result to a file; the others find the file and read it. The lock comes from the filelock package, which provides a lock that works across processes.

Removing contention.

Worked example

A suite has 200 tests of 0.5 seconds each and runs on 4 workers. 120 of the tests talk to one radio device, which can serve only one test at a time; the other 80 tests use nothing shared.

  1. In one process the suite takes 200×0.5=100200 \times 0.5 = 100 seconds.

  2. If all tests were independent, 4 workers would need 100/4=25100 / 4 = 25 seconds.

  3. The 120 device tests must run one after another, wherever they run: 120×0.5=60120 \times 0.5 = 60 seconds. No schedule finishes sooner than 60 seconds.

  4. The other 80 tests take 80×0.5=4080 \times 0.5 = 40 seconds of work. With the device tests in one xdist_group on one worker, the other 3 workers share these 40 seconds, about 40/3≈13.340 / 3 \approx 13.3 seconds each, well within the 60 seconds.

  5. The best total is therefore 60 seconds, a speedup §18.1.13 of 100/60≈1.67100 / 60 \approx 1.67, not 4.

Without the group, the scheduler under load sends device tests to all 4 workers. Up to 4 of them use the radio at the same moment and their commands interleave. Whether a test passes then depends on timing, a race condition §9.2, and the device tests become flaky tests §10.38. A session-scoped fixture that opens the device does not prevent this. It runs once in each worker, so the device is opened 4 times. On Linux several processes can usually open one serial port at once, so all 4 opens succeed and the bytes of the 4 workers mix on the line.

Stated precisely

Under load and worksteal, any two tests can run at the same time on different workers; under loadscope, loadfile and loadgroup, tests of one scope, file or group run on one worker, one after another. Let R(t)R(t) be the set of resources a test tt reads and W(t)W(t) the set it changes, counting files, ports, devices, databases and services outside the process. Bernstein’s conditions (1966) [508] state when two tasks t1t_1 and t2t_2 give the same result run at the same time as run one after the other: W(t1)∩R(t2)=∅,R(t1)∩W(t2)=∅,W(t1)∩W(t2)=∅,W(t_1) \cap R(t_2) = \emptyset, \quad R(t_1) \cap W(t_2) = \emptyset, \quad W(t_1) \cap W(t_2) = \emptyset, where ∩\cap is set intersection and ∅\emptyset the empty set. A suite is safe under pytest-xdist when every pair of tests that can run at the same time meets these conditions, or when each pair that does not is placed on one worker or ordered by a lock visible to all workers. In addition, every worker must collect the same tests in the same order.

A lower bound on the run time follows. Let TT be the time the whole suite takes in one process, TxT_x the total time of the tests that need one exclusive resource, and nn the number of workers. Ignoring the time to start workers, no run finishes in less than max(Tx,T/n)\max(T_x, T / n). In the example, max(60,100/4)=max(60,25)=60\max(60, 100 / 4) = \max(60, 25) = 60 seconds.

pytest-xdist guarantees that, in every mode except each, each collected test runs once on some worker and that all results reach one report. It does not guarantee an order of tests, which worker runs a test, or which tests overlap in time.

Limits and common mistakes

A faster passing run is not proof of independence. Interference appears only when the colliding tests happen to overlap in time, so a suite can pass many times and then fail. Rerunning with different worker counts and in a different order exposes it more often.

Session scope is per worker. Expensive global setup runs once in each worker unless it is coordinated, and a fixture that assumes it is alone, for example one that deletes a shared directory at teardown, breaks the other workers.

State inside a process is not shared between workers: module-level variables, environment variables set with monkeypatch, and the current directory belong to one worker. A test that relies on another test having set them was already order-dependent; under pytest-xdist it also depends on which worker it lands on.

Text that tests print is not shown live: the workers’ output does not reach the terminal the way it does with pytest’s -s option in a single process.

Parallel workers multiply the load on the machine. Four workers that each start a server need four times the memory and four free ports.

Record what ran: the worker count and the numbers of tests collected, passed, failed, skipped and errored. A count lower than expected means tests were not collected or not run.

Questions answered

Which tests contend for shared files, ports, devices, or global state?

Tests contend when two of them run at the same time in different worker processes, use the same resource outside their processes, and at least one of them changes it. pytest-xdist, the plugin that runs pytest tests in parallel worker processes, gives each worker its own memory, so the contention comes from what lies outside the processes:

State inside one process, such as module-level variables, environment variables and the current directory, is not shared between workers. It is shared between the tests of one worker, though, and makes results depend on test order and on worker assignment.

To find the contenders, list for each test the paths, ports, devices and services it touches, search the code for hard-coded ones, and rerun the suite with different worker counts and orders. Then give each test its own resource (tmp_path, port 0, a name that includes the worker name), or serialize the tests that share one resource (xdist_group with --dist loadgroup, or a lock that all processes can see).

Related entries: pytest (§12.31), Nondeterministic test (§10.38), Mutex (§9.5), Transitive dependency (§10.43), fcntl and advisory locking (§12.41), Race condition (§9.2). Further reading: [42, 508].