Full name: pytest: a coined name from Python and test; it is not an abbreviation.
Definition
pytest is a testing framework for Python §12.23: a tool that finds test functions, runs them and reports which passed and which failed. A test is an ordinary function whose name begins with test and that checks results with Python’s assert statement. A test obtains a resource, such as a temporary directory, by naming a fixture as a parameter. A fixture is a function that pytest runs to set the resource up before the test and to clean it up afterwards; its scope decides how many tests share one instance.
The idea
Tests need things around them: a temporary directory, a running server, a connection, a file with known content. Writing the setup at the top of each test and the cleanup at the bottom repeats code, and the cleanup is skipped when an assertion fails halfway, because a failed assert raises an exception that leaves the function. A fixture packages setup and cleanup once, under a name. A test that names the fixture as a parameter receives the resource, and pytest runs the cleanup whether the test passed or failed.
The scope of a fixture trades speed against isolation. Suppose starting a database server takes 2 seconds. Started once per test, 50 tests spend seconds on startup; started once for the whole run, they spend 2 seconds. In exchange, the 50 tests share one server, and whatever one test leaves in it, the next test finds. A hotel is a fair picture: a room cleaned between guests is like a fixture with function scope, and a flat shared for a whole stay is like one with session scope. The picture stops at the cleaning. pytest never resets a shared resource between tests; only the fixture’s own cleanup code, run when its scope ends, does anything.
How it works
Collection. pytest searches the given directories for files named
test_*.pyor*_test.py. In them it collects the functions whose names start withtestand the test methods of classes whose names start withTest.Fixture definition. A fixture is a function marked with the decorator
@pytest.fixture. The code before ayieldstatement is the setup, the yielded value is what the test receives, and the code after theyieldis the teardown, the cleanup. Fixtures written in a file namedconftest.pyare available to every test file in that directory and below it.Requests. A test requests a fixture by naming it as a parameter. A fixture can request other fixtures in the same way, so the requests form a graph of dependencies, and pytest sets each fixture up after the fixtures it requests. A fixture marked
autouse=Trueapplies, without being requested, to every test that can see it: the tests of its own file, or of every file below itsconftest.py.Scope. The
scopeargument fixes how long one instance of the fixture lives:"function", the default: one instance per test, torn down when that test ends;"class": one per test class, torn down after the last test of the class;"module": one per test file, torn down after the last test of the file;"package": one per package of test files, torn down after the last test of the package;"session": one per test run, torn down when the run ends.
A fixture may request only fixtures of the same scope or a wider one; otherwise pytest reports a
ScopeMismatcherror.Caching §14.20. pytest creates an instance when the first test in the scope that needs it is about to run, hands the same instance to every later request in that scope, and tears it down when the scope ends. A fixture with
params=[...]is created once per parameter value, and every test that requests it runs once for each value.Teardown order. When several fixtures end at the same time, pytest tears them down in the reverse order of their setup, so a fixture is cleaned up before the fixtures it depends on.
Failures during setup and teardown. If a test fails, its fixtures are still torn down. If a fixture’s setup raises an exception before its yield, pytest reports the test as an error rather than a failure, and the code after that fixture’s yield does not run, because the function never reached the yield. Fixtures set up earlier are still torn down. One fixture should therefore acquire one resource: a fixture that opens a file and then starts a server leaves the file open when the server fails to start.
Built-in fixtures include tmp_path, a new empty directory for each test as a pathlib.Path; tmp_path_factory, with session scope, for directories that several tests share; monkeypatch, which temporarily replaces attributes and environment variables and restores them at teardown; and capsys, which captures what a test prints.
Worked example
A fixture items prints setup, yields an empty list, and prints teardown after the yield. Two tests request it. test_a appends 1 to the list and asserts that the list equals [1]. test_b asserts that the list equals [].
With
scope="function"the run prints setup, thentest_apasses, teardown, setup, thentest_bpasses, teardown. That is 2 setups and 2 teardowns, and both tests pass in either order.With
scope="module"the run prints setup, thentest_apasses,test_bfails because the list is[1], then teardown. That is 1 setup and 1 teardown. Runningtest_balone, withpytest -k test_b, passes. The result oftest_bnow depends on which tests ran before it, a typical cause of a flaky test §10.38.
The cost side, with the database server from above: 50 tests and a 2-second setup cost seconds with function scope and 2 seconds with session scope, a saving of seconds. A common way to keep most of the saving and still isolate the tests is to pair the two scopes: a session-scoped fixture starts the server once, and a function-scoped fixture that requests it empties the server’s tables before each test.
Stated precisely
Call one test, one class, one module (test file), one package or one whole run a span of the scope "function", "class", "module", "package" or "session" respectively, all within a single pytest process. For a fixture with scope , pytest guarantees:
the tests of one span of that request with the same parameter value and run one after another share one instance, and pytest orders the tests to keep such runs together;
the instance is set up before the first of those tests starts;
the instance is torn down after the last test of the span that uses it, in reverse order of setup, whether the tests passed or failed.
The guarantee rests on three named assumptions.
The process survives to the end of the span. A pytest process killed by a signal, ended by
os._exit, crashed in native code or cut off by power loss runs no teardown at all.Setup reached its
yield. Otherwise the fixture’s own teardown code never runs.The resource lives only in the process. Teardown ends the Python objects; anything outside the process, such as a child process, a file or a device state, ends only if the teardown code ends it.
A session is one pytest process. A plugin such as pytest-xdist §12.32, which runs tests in several worker processes, gives each worker its own session and therefore its own instance of every session-scoped fixture.
Limits and common mistakes
Scope controls sharing inside one process, not outside it. Files, ports, devices and databases outside the process are shared by every test and every process that uses them, whatever the fixture scope. The pytest-xdist entry treats tests running in parallel processes.
Finishing teardown does not mean the resource is gone. If a fixture started a child process, for example with the subprocess module §12.40, or a thread, or an operation that completes later, the teardown must stop it and wait for it to end, for example with proc.terminate() followed by proc.wait(timeout=5). Otherwise the work outlives the fixture and can disturb the next test.
A wider scope makes tests depend on order. A test that passes alone and fails in the full run, or the reverse, usually shares state through a module-scoped or session-scoped fixture.
A fixture that returns a list or a dictionary hands every test in its span the same object, and tests that change it affect each other. Return a fresh copy, or reset the object in a function-scoped fixture.
pytest checks only the assertions that run. A test that returns before its assertion passes, and a skipped test is not a passed test; read the counts of passed, failed, skipped and errored tests in the summary.
Questions answered
At what scope is a fixture constructed and cleaned up?
A pytest fixture is constructed when the first test within its scope that needs it is about to run, and it is cleaned up after the last test of that scope finishes; the scope argument of @pytest.fixture sets the scope. pytest is the Python testing framework, and a fixture is a function that sets up a resource for tests and cleans it up afterwards.
"function"(the default): constructed for each test and cleaned up when that test ends."class": once per test class, cleaned up after its last test."module": once per test file, cleaned up after its last test."package": once per package of test files."session": once per pytest process, cleaned up when the run ends.
Setup is the code before yield in the fixture function, and cleanup is the code after it. Cleanup runs whether the test passed or failed, and fixtures that end together are cleaned up in reverse order of setup.
Three refinements matter. A fixture with parameters gets one instance per parameter value. Under pytest-xdist each worker process is a separate session, so a session-scoped fixture is constructed once per worker. And cleanup does not run when setup raised an exception before yield, or when the process dies, for example because it was killed. Anything outside the process, such as a child process or a device, must be stopped and waited for explicitly in the cleanup code.
Related entries: pytest-xdist (§12.32), Unit test (§10.1), Deterministic replay (§10.37), Asynchronous completion (§9.28), Nondeterministic test (§10.38), subprocess (§12.40). Further reading: [27].