Skip to main content

Early fixtures

  • Session-scoped fixtures: an early fixture is a scope="session" pytest fixture, marked with @dagz_early_init.
  • Runs early: DAGZ starts it with the session, in parallel with the loading of the conftests and the collection of the tests.
  • Runs once per node in a dedicated process: DAGZ runs it in the node's early init process, not in the test processes.
  • Runs in parallel while respecting pytest fixture dependencies: early fixtures run concurrently, and each one starts once the early fixtures it takes have finished.
  • Can repeat per test worker: an early fixture that takes dagz_worker runs once for each test worker, in that worker's context.
  • Seamless usage by tests: tests use it as any other fixture: its errors propagate to them, its value is passed to them pickled, and they wait until it is ready.
  • Reusable across test suites: a module of early fixtures that several suites' conftests star-import is one set of fixtures, with one value per test process.

Use an early fixture for setup that is slow and the same for every test: booting a service, loading a database, building a data set.

Declare an early fixture​

Apply @dagz_early_init above @pytest.fixture(scope="session"):

import pytest
from dagz.pytest.early_init import dagz_early_init


@dagz_early_init
@pytest.fixture(scope="session")
def search_index():
path = build_search_index() # 40 s, the same for every test
return str(path)

Without a DAGZ session, dagz_early_init returns the fixture unchanged, and pytest runs it as a plain session fixture. A project that also runs where DAGZ is not installed can fall back to a decorator that does nothing:

try:
from dagz.pytest.early_init import dagz_early_init
except ImportError:
def dagz_early_init(fixture):
return fixture

Where an early fixture is defined​

An early fixture is defined under the rootdir, in one of:

  • an initial conftest: a conftest.py that pytest loads before the collection, in the rootdir or in a directory of a path on the command line;
  • a module that dagz_autoload.py imports;
  • a pytest plugin.

Several conftests can share early fixtures: define them in one module, list them in its __all__, and star-import the module from each conftest (from tests.shared_fixtures import *). DAGZ identifies an early fixture by its module and name, so an early fixture that several conftests import is one fixture, visible below their common directory, with one value in each test process.

Declaration errors​

dagz_early_init raises TypeError when the module that defines the fixture is imported:

CauseMessage
The decorator is applied to something that is not a pytest fixture, or below @pytest.fixturedagz_early_init takes a pytest fixture, not ...: apply @dagz_early_init above @pytest.fixture
The fixture's scope is not sessionearly fixture NAME is function-scoped; an early fixture is session-scoped
The fixture takes paramsearly fixture NAME takes params; an early fixture is not parametrized
The module is outside the rootdirearly fixture NAME is defined in FILE, outside the rootdir ROOT; ...
The module is a conftest pytest imports after the initial conftestsearly fixture NAME is defined in FILE, which pytest imports after the initial conftests; ...

When an early fixture runs​

  • A fixture starts as soon as pytest registers it and the early fixtures it takes have finished.
  • An early fixture defined in the rootdir, or in a directory that contains every path on the command line, runs even when no test uses it. A fixture in a deeper directory runs when the first test that uses it asks for it.
  • A test waits only for the early fixtures it uses. The other tests start before those fixtures finish.
  • An early fixture that no test waits for and that never finishes does not hold up the session.

How a test receives the value​

The early init process pickles the fixture's value and sends it to each test process that asks for it, so the value has to be picklable. Each test process receives its own copy. Return what the tests need to reach the result, such as a URL, a path or a database name, rather than an open connection.

A large value that only other early fixtures read, such as a database dump, can stay in a module variable of the early init process instead of being returned. The fixtures that run in the same process read it there, and no test process receives it.

Dependencies between early fixtures​

An early fixture takes other early fixtures as parameters, as pytest fixtures take fixtures. DAGZ resolves each parameter the way pytest does, from the directory of the fixture that takes it. A parameter that resolves to a fixture that is not early fails the tests that use the fixture:

early fixture tests.conftest::needs_a_test_fixture takes tmp_path_factory, which pytest resolves to no early fixture

Per-test-process early fixtures: dagz_worker​

An early fixture that takes the dagz_worker parameter runs once for each test process, with that process's worker number. It runs in the early init process, in that test process's context: database connections it opens are rerouted to that test process's databases. Use it to set up each test process's own copy of a resource before its first test.

An early fixture without dagz_worker that takes a per-test-process one receives every test process's value, in a dict by worker number, after all of them finished.

Autouse, failures and teardown​

  • autouse=True works as in pytest: every test below the fixture's directory uses the fixture, and waits for it.
  • A fixture that raises fails each test that uses it, with the original traceback under Raised in the early init process. The early fixtures that take it fail with the same error.
  • A generator fixture yields once. The code after its yield runs at the end of the session, after the test processes finished, in the reverse order of the setups, on the thread that ran its setup. A fixture that yields more than once logs an error.
  • A test marked dagz_node_mutex that uses an early fixture waits for every test process's early fixtures before its own setup, since its setup may change state the others still set up from.

Example: one database load, cloned into each test process​

The node loads the database once. Each test process then starts from a copy of it, instead of running the load itself.

# tests/db_fixtures.py, star-imported by tests/conftest.py
import pytest
from dagz.integ.psycopg import PG_CONFIG
from dagz.pytest.early_init import dagz_early_init

__all__ = ["db_dump", "db_clone"]

ADMIN = dict(host="localhost", port=5432, user="postgres", password="postgres")

# The node's dump, read by db_clone in the early init process; no test process receives it.
_dump: list[bytes] = []


@dagz_early_init
@pytest.fixture(scope="session")
def db_dump():
load_schema_and_seed_data("myapp") # the project's own tooling, once per node
_dump.append(PG_CONFIG.dump_db("myapp", schema_only=False, **ADMIN))


@dagz_early_init
@pytest.fixture(scope="session", autouse=True)
def db_clone(dagz_worker, db_dump):
# With main_worker_bypass, the main test process uses "myapp" itself; every other one gets its own copy.
target = PG_CONFIG.get_manual_init_db_name("myapp")
if target != "myapp":
PG_CONFIG.restore_db(_dump[0], target, **ADMIN)
# tests/conftest.py
from tests.db_fixtures import * # noqa: F401,F403