Skip to main content

Python API

The DAGZ pytest plugin exposes a small Python API for three integrations:

  • DB rerouting for parallel database tests (dagz.integ.psycopg, dagz.integ.pymysql, etc.), part of Test Isolation.
  • Early fixtures: session fixtures that run once per node during the collection (dagz.pytest.early_init).
  • OpenTelemetry integration that turns OTel spans into DAGZ sub-spans (dagz.integ.otel).

For the conceptual walkthrough and setup patterns of DB rerouting, see Parallelizing DB Tests. The page below documents the public API surface. The other test isolation APIs (dagz.isolate.guards, dagz.isolate.ports, dagz.isolate.task_state_tracker, dagz.isolate.classes, dagz.isolate.module_globals, dagz.isolate.fields, dagz.isolate.work_lists) are described in Test Isolation.

DB Rerouting​

Each integration exposes a singleton config object: PG_CONFIG, MYSQL_CONFIG, CASSANDRA_CONFIG, etc. All share the same surface, described here in terms of a generic CONFIG.

CONFIG.configure(...)​

Activates rerouting for this database family. Call once from your dagz_autoload.py init() (see Parallelizing DB Tests).

ParameterRequiredPurpose
rewrite_db_name(db_name, session) -> stryesCompute the per-worker name. Use default_rewrite_db_name for the _jw{N} suffix.
should_reroute(db_name) -> boolyesDecide whether to reroute a given DB. Use default_should_reroute to skip system DBs.
prepare(db_name) -> NoneyesPer-test preparation. Pass None for no preparation.
worker_init(worker_num) -> Noneno, default NoneOne-time per-worker setup.
single_worker_disable: boolno, default FalseUnhook entirely when running with one worker.
main_worker_bypass: boolno, default FalseSkip rerouting on the main worker. Used together with the dagz_main_worker mark.

The first three are required positional contract: pass default_rewrite_db_name / default_should_reroute for the standard scheme, and None for prepare if you do not need per-test preparation.

Manual init helpers​

Use these to opt out of the global prepare callback for a single test, typically inside a fixture that pre-loads its own data.

CONFIG.get_manual_init_db_name(name) -> str Resolves name to its per-worker form through the configured rewrite_db_name policy (e.g. myapp → myapp_jw03), and marks the resolved name as already initialized for the current test. The auto-prepare callback then skips it on the first connection of this test. The marker is per-test: cleared at the start of every test via a test_prerun hook.

CONFIG.get_manual_init_db_url(url) -> str Same as above for URL-based connection strings. Parses the URL, rewrites the path component, and reassembles.

CONFIG.bypass()​

Context manager that disables rerouting on the current thread / async task. Backed by contextvars, so it is thread-safe and async-task-local.

with PG_CONFIG.bypass():
conn = psycopg.connect(dbname="postgres") # admin DB, not rerouted

Driver-level helpers​

For wiring a client library that DAGZ does not ship a hook for. Call from your own override of the library's connect function.

Client call shapeHelper
connect(database="myapp", ...)CONFIG.maybe_reroute(name)
connect(dbname="myapp", ...)CONFIG.maybe_reroute(name)
connect("postgresql://user:pw@host/myapp")CONFIG.maybe_reroute_uri(uri)

maybe_reroute(name) -> str returns the rerouted name if the config wants to reroute it, the original name otherwise. maybe_reroute_uri(uri) -> str does the same for a URI string.

For libraries with a custom shape (multi-statement keyspace strings, byte-encoded auth blobs), call CONFIG.should_reroute(name) -> bool and CONFIG.reroute_db(name) -> str directly.

CONFIG.truncate(db_name, **connect_kwargs)​

Connects to the named DB and empties every user table. Suitable as the body of a prepare callback for the common case of clearing all user tables between tests.

def _prepare(db_name):
PG_CONFIG.truncate(db_name, host="localhost", port=5432, user="postgres", password="postgres")

Early fixtures​

dagz.pytest.early_init.dagz_early_init(fixture)​

Turns a session-scoped pytest fixture into an early fixture: DAGZ runs it once per node in the early init process, during the collection, and each test that uses it receives its pickled value. Apply it above @pytest.fixture. Returns the fixture unchanged without a DAGZ session. See Early fixtures for when it runs, the dagz_worker parameter, teardown and an example.

ParameterRequiredPurpose
fixtureyesA pytest fixture, scope="session", without params, defined under the rootdir in an initial conftest, a module dagz_autoload.py imports, or a plugin.

The fixture function's own parameters are other early fixtures, and optionally dagz_worker, which makes it run once per test process with that process's worker number. Raises TypeError for a value that is not a pytest fixture, a scope other than session, params, a module outside the rootdir, or a conftest pytest imports after the initial conftests.

import pytest
from dagz.pytest.early_init import dagz_early_init


@dagz_early_init
@pytest.fixture(scope="session")
def search_index():
return str(build_search_index())

OpenTelemetry​

dagz.integ.otel registers a span processor that mirrors OpenTelemetry spans into DAGZ as sub-spans. Each OTel span becomes a DAGZ sub-span tagged with an otel_type attribute derived from the OTel instrumentation scope and operation, and OK / ERROR status maps to DAGZ's SpanResult.

dagz.integ.otel.configure_otel(...)​

Every DAGZ session configures OpenTelemetry itself: it sets a TracerProvider with the DAGZ span processor and installs the available OTel instrumentations, each when its library is imported (logging, asyncio, threading and sqlalchemy stay off). Metrics are off by default: once the autoloads end, DAGZ sets a no-op MeterProvider, and OTel refuses a MeterProvider the application sets later. Call configure_otel from dagz_autoload.py only to keep metrics, passing the application's MeterProvider. No-op if the DAGZ pytest plugin is not enabled.

ParameterRequiredDefaultPurpose
dd: boolnoFalseMust be False; True is not yet supported and raises.
meter_provider: MeterProvider | NonenoNoneThe application's MeterProvider; without one, DAGZ sets a no-op MeterProvider after the autoloads.
start_provider: boolnoTrueIgnored; kept for callers written before every session configured OTel.
auto_instrument: boolnoTrueIgnored; kept for callers written before every session configured OTel.
# dagz_autoload.py
from dagz.integ.otel import configure_otel
from myapp.telemetry import meter_provider # the application's configured MeterProvider, with its readers and exporters

def init(in_pytest):
configure_otel(meter_provider=meter_provider)

A TracerProvider the application sets later is instrumented too: trace.set_tracer_provider is patched to attach the DAGZ span processor to it.