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 seconds in one process. A machine with 4 processor cores could run four tests at a time and finish in about 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
Start.
pytest -n 4starts 4 worker processes;-n autolets the plugin pick the number from the processor cores of the machine. The workers are namedgw0,gw1and so on.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.
Distribution. The option
--distchooses 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.
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_idfixture or from the environment variablePYTEST_XDIST_WORKER.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.
Give each test its own resource.
tmp_pathis a new directory for each test, also across workers. A test server can listen on port 0, which asks the operating system for any free port, and report the port it got. A database name can include the worker name.Serialize access to a resource that cannot be duplicated. Put all tests that use it in one
xdist_groupand run with--dist loadgroup, or guard the resource with a lock that every process can see, such as an advisory file lock, which the fcntl and advisory locking §12.41 entry explains. A lock object inside one process, such as a mutex §9.5 from Python’sthreadingmodule, does not stop another worker.Run the tests that need such a resource in a separate pass without
-n.
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.
In one process the suite takes seconds.
If all tests were independent, 4 workers would need seconds.
The 120 device tests must run one after another, wherever they run: seconds. No schedule finishes sooner than 60 seconds.
The other 80 tests take seconds of work. With the device tests in one
xdist_groupon one worker, the other 3 workers share these 40 seconds, about seconds each, well within the 60 seconds.The best total is therefore 60 seconds, a speedup §18.1.13 of , 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 be the set of resources a test reads and the set it changes, counting files, ports, devices, databases and services outside the process. Bernstein’s conditions (1966) [508] state when two tasks and give the same result run at the same time as run one after the other: where is set intersection and 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 be the time the whole suite takes in one process, the total time of the tests that need one exclusive resource, and the number of workers. Ignoring the time to start workers, no run finishes in less than . In the example, 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:
Files: fixed paths such as
/tmp/out.json, a shared cache or results directory, a configuration file in the home directory, a database file.Ports: servers that listen on a fixed port number such as 8080; the second one fails with an address-in-use error.
Devices: serial ports, radios, debug probes, a board under test. Two workers can open one serial port at once and interleave their bytes.
Global state outside the process: databases, external services and system-wide settings.
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].