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 and schedr.toml files, 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 .schedrignore like a configured root) or one file (checked alone, its directory on sys.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 same validate_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) or error broken.py: ModuleNotFoundError: ... with its traceback), then a summary; --json gives {"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 (in dags 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 schedr than a worker may use a feature that worker doesn’t have (an import error in the UI, never silent). Pinning the local schedr to 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> reads GET /api/v1/workers after the file report and fails (exit 1) when this schedr is newer, as major.minor, than any active worker. A worker drained for maintenance stays active and counts; draining, disconnected, offline and lost do 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 the error: 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 says runs; several versions are oldest first). A version that does not parse is unknown. Dispatch stores parse().ok() (None) and Worker::runs still 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 as unknown 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 is connect_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 (and SCHEDR_TOKEN, SCHEDR_USER, SCHEDR_PASSWORD) are sent; --server is not the URL. --json adds version_check: {local, ok, message, workers: [{worker_id, schedr_version}]} when the list was read (workers is every active worker, the version text as reported; message is the ok: or error: 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); a warning: 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 (the ok: line names the workers that were compared); a separate HTTP client for this flag (the shared connect_to keeps the credentials and the timeouts).

  • Unit tests of task functions. Outside with Dag(...) a @task function is the plain function: calling it runs it and returns the real value (inside a DAG the same call returns an Output[...]). For code reading the run context or registering handles, schedr.testing.task_context(...) sets dag_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_handle fail 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_for now (UTC), since = planned_for (an empty window, as for a run with nothing to go back to), dag_id test, a new UUIDv7 as run_id, kind manual. Times must be aware, since not after planned_for, kind a run kind. params= and secrets= raise NotImplementedError naming milestone M4 (like dag_ctx.params); the handle collector comes with handles (M4).

    • dag_ctx fails everywhere else (1.15b): a field read outside a running task and outside with Dag(...) raises RuntimeError (”dag_ctx must be run inside a schedr task …; in tests, set values with schedr.testing.task_context(...)”), e.g. a module- level PLANNED = dag_ctx.run.planned_for or a plain call of a task reading it. Inside with Dag(...) it gives references, while a task runs (or in task_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 ended success, 1 if failed. --task <id> runs that task and its upstream tasks only. Not chosen: running the tasks in one Python process like Airflow’s dag.test() (faster, but skips what differs in production).

    • How it works (1.15a): schedr standalone in 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 a manual run 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 on sys.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 in dags 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 prefixed task | , 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. --json gives {"run", "tasks": [{task_id, state, outcome, try_number, output, attempts, log}], "location": {root, path}} (location: the file defining the DAG, used by run_dag to 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: -p and --secret (run parameters and secrets, M4) and --task (M4) say so with the milestone; they aren’t silently ignored. dags check --against is 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_json raw), 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) runs schedr dags test <dag_id> --path <path> --json [--for ...] and reads the report into a RunResult (run_id, dag_id, kind, state, planned_for, since, tasks by ID) of TaskResults (state, outcome, try_number, output, output_json, attempts, log) and Attempts (status, exit_code, error_kind, error (the summary), started_at, ended_at, duration). A run that ends failed or cancelled is a result, not an exception (the test asserts on it); RunDagError is for a run that couldn’t be made or read (no binary; dags test failing before a run, e.g. an unknown DAG or a file that doesn’t import), with what schedr printed.

      • The binary: $SCHEDR_BIN, else the schedr installed with this Python’s schedr package (its scripts directory, so binary and package match), else schedr on PATH; none is an error saying to pip install schedr or set SCHEDR_BIN.

      • The interpreter: the DAG’s Python tasks run with the test’s own Python: [interpreters] python is set to sys.executable through SCHEDR_CONFIG__INTERPRETERS__PYTHON, unless the environment already sets it. A test and its DAG see the same packages; a python3 on PATH without schedr doesn’t get in the way.

      • Decoding outputs: output is decoded lazily, by the task’s return annotation (a command’s output as a ProcessResult, an empty task’s as None). 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; otherwise run_dag imports the file (as the runner does) and its classes come from that import. A file that no longer imports is a RunDagError from output (output_json still works).

      • params=, secrets=, step= and replace= raise NotImplementedError naming milestone M4.

    • Examples (1.15b): examples/ holds the example DAG of Native API (sync.py, kept identical to the one above by a test) and daily_report.py (a task reading dag_ctx), each with pytest tests using plain calls, task_context and run_dag. They run with the integration tests (make test-integration, CI’s integration job: they need the binary). Ruff checks them like the package (docstrings on their tasks are left to the author), and mypy --strict and 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 failed assert) 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 an empty task; the value must match the task’s return type and its outcome follows from the value. Tests routing (.on(...)) without network access. Only in run_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 the db secret storage (see Secret storage; it replaced a file storage, which relied on standalone never being production).

  • Airflow: dag.test() runs run_dag for that DAG (conf → params, logical_date → for_).