Testing DAGs¶
For a DAG author on a laptop or in CI, with pip install schedr (the wheel includes the binary)
and no cluster. Four levels, from cheapest to fullest.
Static check:
schedr dags check <path>(see Upgrades and compatibility): parses DAG files andschedr.tomlfiles, reports import errors and parse warnings; non-zero exit code on errors.How it works (1.15a):
<path>is a directory (a DAG root named after it, scanned with its.schedrignorelike a configured root) or one file (checked alone, its directory onsys.path). The files are parsed by the real runner (python -m schedr.runner parse, the[dags] interpreter) and then go through the master’s own checks (the samevalidate_files: cron fields, schedules, task references, …), so a DAG that passes here isn’t rejected by the master. One line per file (ok sync.py: sync (2 tasks)orerror broken.py: ModuleNotFoundError: ...with its traceback), then a summary;--jsongives{"files": [{path, dags, error}]}. Exit code 1 if any file has an error.Tracebacks start at the user’s code: the runner drops its own and
importlib’s leading frames from import errors (indags check, the UI and the DB alike), so the first frame shown is the DAG file’s.
Local version vs the workers (2.12b): a DAG written with a newer local
schedrthan a worker may use a feature that worker doesn’t have (an import error in the UI, never silent). Pinning the localschedrto the worker image (schedr==1.4.*in the DAG repository’s dev dependencies) remains how you write against that version.schedr dags check --against <server URL>readsGET /api/v1/workersafter the file report and fails (exit 1) when this schedr is newer, asmajor.minor, than any active worker. A worker drained for maintenance staysactiveand counts;draining,disconnected,offlineandlostdo not take new tasks. The patch is ignored, as everywhere else. The error names the older ones, grouped by version, oldest first:this schedr is 0.3; older active workers at http://sched.example: 0.1: w3; 0.2: w1, w2(the CLI prints it with theerror:prefix). A pass prints one line after the file report:ok: this schedr is 0.3; 2 active workers at https://prod run 0.3 (w1, w2)(one worker saysruns; several versions are oldest first). A version that does not parse is unknown. Dispatch storesparse().ok()(None) andWorker::runsstill offers that worker tasks. The check follows that rule: the worker is listed and does not fail the check, and the passing line names the text asunknown version. No active worker:no active worker at <url> to compare with this schedr (0.3): workers are recorded disconnected right after a master restart until they register again, so retry in a minute. The server unreachable, or refusing the call, is that error after the file report; a different major is the API’s existing refusal (Schedr-Client-Version). The call isconnect_to: the same credentials as the other commands, a 5 s connect timeout and a 30 s request timeout (a handshake that never completes stops).--token/--user(andSCHEDR_TOKEN,SCHEDR_USER,SCHEDR_PASSWORD) are sent;--serveris not the URL.--jsonaddsversion_check: {local, ok, message, workers: [{worker_id, schedr_version}]}when the list was read (workersis every active worker, the version text as reported;messageis theok:orerror:line). A worker on the same or a newer minor does not fail the check.Not chosen: failing only when every active worker is older (one current worker would hide a leftover old one, and that old one still takes tasks); exit 0 with a
warning:line (a green check deploys onto workers that queue the DAG); awarning:line as well as exit 1 (two lines for one fact); ignoring drained workers (resuming one is then a surprise); filtering by the queues the checked files name (a queue added later is not covered); failing before the file report when the server cannot be asked; comparing the patch (patches add no features; see Upgrades and compatibility); treating an unreadable version as its own older group (dispatch stores it as unknown and still assigns the worker); a silent pass (theok:line names the workers that were compared); a separate HTTP client for this flag (the sharedconnect_tokeeps the credentials and the timeouts).
Unit tests of task functions. Outside
with Dag(...)a@taskfunction is the plain function: calling it runs it and returns the real value (inside a DAG the same call returns anOutput[...]). For code reading the run context or registering handles,schedr.testing.task_context(...)setsdag_ctx(planned_for,since,params, …), declared secrets and a handle collector; pure Python, no processes:with task_context(planned_for=datetime(2026, 10, 15, 3, tzinfo=UTC), params=ReportParams(region="us"), secrets={"etl/db#password": "x"}) as ctx: export(date(2026, 10, 15)) assert ctx.handles == [TempDir(...), ExportJob("j-1")]
Outside a task and outside
task_context,dag_ctx/cleanup_handlefail as decided (“must be run inside a schedr task”).How it works (1.15b):
task_context(planned_for=, since=, dag_id=, run_id=, kind=)is a context manager setting the same context variable the runner sets while it calls a task; it yields those values. Defaults:planned_fornow (UTC),since=planned_for(an empty window, as for a run with nothing to go back to),dag_idtest, a new UUIDv7 asrun_id, kindmanual. Times must be aware,sincenot afterplanned_for,kinda run kind.params=andsecrets=raiseNotImplementedErrornaming milestone M4 (likedag_ctx.params); the handle collector comes with handles (M4).dag_ctxfails everywhere else (1.15b): a field read outside a running task and outsidewith Dag(...)raisesRuntimeError(”dag_ctxmust be run inside a schedr task …; in tests, set values withschedr.testing.task_context(...)”), e.g. a module- levelPLANNED = dag_ctx.run.planned_foror a plain call of a task reading it. Insidewith Dag(...)it gives references, while a task runs (or intask_context) values.
One whole run:
schedr dags test <dag> [--for <time>] [-p …] [--secret 'path#key=value'] [--task <id>]. One real run in standalone mode with a temporary SQLite database: every task is its own process, exactly as in production (runner, rendering, quoting, masking, outputs, outcomes, routing, cleanups, resources). The terminal shows each task’s state, outcome and duration, logs streamed with a task-name prefix, outputs as JSON at the end; exit code 0 if the run endedsuccess, 1 iffailed.--task <id>runs that task and its upstream tasks only. Not chosen: running the tasks in one Python process like Airflow’sdag.test()(faster, but skips what differs in production).How it works (1.15a):
schedr standalonein the same process, on 127.0.0.1 with ports chosen by the system (0) and a temporary data directory (SQLite, logs) removed afterwards; the run is amanualrun triggered and followed through the REST API, like the CLI does. The DAG roots are--path <file or dir>if given, else the configured roots, else the current directory. A file is tested alone (decision 117, the user’s, 2026-10-31: A; B118): its directory is the root, but only that file is parsed, by the check and by the worker, so a file beside it isn’t imported (nor its side effects run); what the file imports from beside it still imports, the directory being onsys.path. The selection is internal (Root::only), never from the configuration file. Not chosen: B every file of the directory parsed, documented (a sibling script run by a test of another file). Before starting anything the files are parsed (as indags check): an unknown DAG fails at once, naming the files that didn’t import. Shown while it runs: each task’s state changes; at the end, each task’s log lines prefixedtask |, each failed attempt’s error (task | try 1 failed (task_failed):and the traceback), a table TASK / STATE / OUTCOME / TRIES / DURATION (of the last attempt), the outputs as JSON and the run’s state.--jsongives{"run", "tasks": [{task_id, state, outcome, try_number, output, attempts, log}], "location": {root, path}}(location: the file defining the DAG, used byrun_dagto decode outputs). A run not finished within an hour fails the test.Exit codes: like every CLI command, 0 on success and 1 on any failure (errors found, a run that didn’t succeed, a bad argument); 2 only for wrong usage from the argument parser.
Later:
-pand--secret(run parameters and secrets, M4) and--task(M4) say so with the milestone; they aren’t silently ignored.dags check --againstis 2.12b.
From Python:
schedr.testing.run_dag(path, dag_id, for_=..., params=..., secrets=...)starts the same thing as a subprocess. Every task can be inspected and asserted separately:result = run_dag("dags/sync.py", "sync_orders", for_=datetime(2026, 10, 15, 3, tzinfo=UTC)) assert result.state == "success" fetch = result.tasks["fetch_primary"] assert fetch.outcome == "Rows" and len(fetch.output.rows) == 120 assert result.tasks["report_outage"].skip_reason == "edge not taken: on Unavailable" load = result.tasks["load"] assert [a.status for a in load.attempts] == ["failed", "success"] assert "inserted 120" in load.log and load.cleanup.result == "ok"
Per task:
state,outcome,output(decoded by the task’s annotation, as a downstream task would;output_jsonraw),skip_reason,attempts(status, exit code, duration, peak memory, error summary),log,cleanup(result, attempts, log),handles. Mapped tasks:result.tasks["process"][3],len(...),.outputs(map-index order). Resources:result.resources["cluster"](value, state, cleanup log). The run:state,planned_for,since,params, the one-line reason of its result.How it works (1.15b):
run_dag(path, dag_id, for_=None)runsschedr dags test <dag_id> --path <path> --json [--for ...]and reads the report into aRunResult(run_id,dag_id,kind,state,planned_for,since,tasksby ID) ofTaskResults (state,outcome,try_number,output,output_json,attempts,log) andAttempts (status,exit_code,error_kind,error(the summary),started_at,ended_at,duration). A run that endsfailedorcancelledis a result, not an exception (the test asserts on it);RunDagErroris for a run that couldn’t be made or read (no binary;dags testfailing before a run, e.g. an unknown DAG or a file that doesn’t import), with whatschedrprinted.The binary:
$SCHEDR_BIN, else theschedrinstalled with this Python’sschedrpackage (its scripts directory, so binary and package match), elseschedronPATH; none is an error saying topip install schedror setSCHEDR_BIN.The interpreter: the DAG’s Python tasks run with the test’s own Python:
[interpreters] pythonis set tosys.executablethroughSCHEDR_CONFIG__INTERPRETERS__PYTHON, unless the environment already sets it. A test and its DAG see the same packages; apython3onPATHwithoutschedrdoesn’t get in the way.Decoding outputs:
outputis decoded lazily, by the task’s return annotation (a command’s output as aProcessResult, an empty task’s asNone). The annotation comes from the DAG as the test process already defined it, when the test imported the DAG file (the registry remembers each DAG’s task functions by file), so a dataclass output equals an instance of the class the test imported; otherwiserun_dagimports the file (as the runner does) and its classes come from that import. A file that no longer imports is aRunDagErrorfromoutput(output_jsonstill works).params=,secrets=,step=andreplace=raiseNotImplementedErrornaming milestone M4.
Examples (1.15b):
examples/holds the example DAG of Native API (sync.py, kept identical to the one above by a test) anddaily_report.py(a task readingdag_ctx), each with pytest tests using plain calls,task_contextandrun_dag. They run with the integration tests (make test-integration, CI’sintegrationjob: they need the binary). Ruff checks them like the package (docstrings on their tasks are left to the author), and mypy--strictand basedpyright check the DAG files (not their tests; decision 57, see Native API: typing of calls).Step by step:
with run_dag(..., step=True) as run: for task in run: ...yields each task as it reaches a final state; the master starts no new task until the test continues, so a test sees each result (and outside state, e.g. “the file is in the bucket”) before any downstream task runs. Parallel tasks still start together and are yielded one at a time, in the order they finish. Leaving the loop (break, a failedassert) cancels the run; cleanups and resource cleanups still run. Implemented as a test-only setting of the standalone master (“hold assignments until released”), driven through the command mechanism; no hooks, no user code in the master.Replacing a task’s result:
run_dag(..., replace={"fetch_primary": Unavailable("down")}): the master completes that task with the given value, like anemptytask; the value must match the task’s return type and its outcome follows from the value. Tests routing (.on(...)) without network access. Only inrun_dag, never in a deployed DAG.
Secrets locally:
--secret 'path#key=value'/run_dag(secrets={...})gives values directly (in memory, masked as usual). Standalone, as a dev environment too, has thedbsecret storage (see Secret storage; it replaced afilestorage, which relied on standalone never being production).Airflow:
dag.test()runsrun_dagfor that DAG (conf→params,logical_date→for_).