schedr.testing

Testing DAGs: task functions with a run context, and whole runs inspected task by task.

Outside with Dag(...) a @task function is the plain function: calling it runs it. task_context(...) gives dag_ctx values to such calls, with no processes. run_dag(...) runs schedr dags test (one real run, every task its own process) and returns its result, every task inspectable on its own (see archive/PROJECT.md, Testing DAGs). Both take run parameters (params=) and secret values (secrets=); handles, step= and replace= come with milestone M4.

schedr.testing.RUN_KINDS = frozenset({'backfill', 'chained', 'event', 'manual', 'scheduled'})

The run kinds task_context(kind=...) accepts.

schedr.testing.BINARY_ENV = 'SCHEDR_BIN'

The environment variable naming the schedr binary run_dag starts.

exception schedr.testing.RunDagError

Bases: Exception

A run that couldn’t be made or read: no binary, or schedr dags test failed early.

class schedr.testing.TestRunValues(dag_id, run_id, kind, planned_for, since, params=<factory>, params_class=None, from_script=False, event=None, handles=<factory>, posted_events=<factory>, notifications=<factory>)

Bases: RunValues

The values of a task_context.

Parameters:
  • dag_id (str)

  • run_id (str)

  • kind (str)

  • planned_for (datetime)

  • since (datetime)

  • params (Mapping[str, Any])

  • params_class (type | None)

  • from_script (bool)

  • event (Mapping[str, Any] | None)

  • handles (list[object])

  • posted_events (list[dict[str, object]])

  • notifications (list[dict[str, object]])

handles

The handles the block registered (cleanup_handle), in order.

Type:

list[object]

posted_events

The events the block posted (schedr.api), in order, as the API gives them (JSON).

Type:

list[dict[str, object]]

notifications

The notifications the block sent (WebhookChannel.send, schedr.api.notify), in order: {"channel": ..., "text": ..., "data": ...}.

Type:

list[dict[str, object]]

schedr.testing.task_context(*, planned_for=None, since=None, dag_id='test', run_id=None, kind='manual', params=None, secrets=None, connections=None, task_id='test', try_number=1, map_index=None, event=None, first_started=None)

Gives dag_ctx values inside the block, as while the runner calls a task.

For unit tests of task functions: with task_context(planned_for=...): extract().

Parameters:
  • planned_for (datetime | None) – dag_ctx.run.planned_for (aware); now (UTC) by default.

  • since (datetime | None) – dag_ctx.run.since (aware, not after planned_for); planned_for by default (an empty window).

  • dag_id (str) – dag_ctx.dag_id.

  • run_id (str | None) – dag_ctx.run.id; a new UUIDv7 by default.

  • kind (str) – dag_ctx.run.kind: manual by default.

  • params (object) – dag_ctx.params: an instance of the DAG’s params class (a dataclass or a Pydantic model); dag_ctx.params(Cls) then takes that class.

  • secrets (Mapping[str, str] | None) – Secret values for task_ctx.secret, by "path#key" (any storage); a whole secret ("path") is its keys’. A @task function called in the block reads only what its secrets= declares, as on a worker (a plain or async function’s reads aren’t checked).

  • connections (Mapping[str, object] | None) – Test doubles for connections, by name: with mongodb_default() as db in the block gives db = connections["mongodb_default"] (the connection’s function isn’t called); a connection without one raises ConnectionNotFoundError.

  • task_id (str) – task_ctx.task_id.

  • try_number (int) – task_ctx.try_number.

  • map_index (int | None) – task_ctx.map_index (None: an unmapped task).

  • event (Event[Any] | None) – dag_ctx.event: the event the run was started by.

  • first_started (datetime | None) – When the step’s first try started, for a wait step tried again (delay counts from it); None: this is its first try.

Yields:

The values dag_ctx gives, and .handles – what cleanup_handle registered.

Raises:
  • TypeError – For a time that isn’t a datetime.

  • ValueError – For a naive time, since after planned_for, or an unknown kind.

Return type:

Iterator[TestRunValues]

class schedr.testing.Cleanup(result, tries, duration, error_kind, error, moves, handles)

Bases: object

The cleanup of an attempt in a run_dag result: what ran on its handles.

Parameters:
  • result (str | None)

  • tries (int | None)

  • duration (timedelta | None)

  • error_kind (str | None)

  • error (Mapping[str, str] | None)

  • moves (int)

  • handles (tuple[Json, ...])

result

How it ended (ok, failed, worker_lost, not_needed); None until it has.

Type:

str | None

tries

The tries it made.

Type:

int | None

duration

How long its tries ran, measured by the worker.

Type:

datetime.timedelta | None

error_kind

The failure kind of a failed cleanup.

Type:

str | None

error

The error summary of a failed cleanup.

Type:

collections.abc.Mapping[str, str] | None

moves

How many times it moved to another worker.

Type:

int

handles

The handles the attempt registered, in order, as stored: {"handle_type": ..., "value": ...} (masked).

Type:

tuple[schedr.types.Json, …]

classmethod from_json(data)

Reads an attempt’s cleanup from schedr dags test --json.

Parameters:

data (Mapping[str, Any]) – The cleanup’s JSON.

Returns:

The cleanup.

Return type:

Cleanup

class schedr.testing.Attempt(attempt_id, try_number, status, exit_code, error_kind, error, started_at, ended_at, duration, cleanup=None)

Bases: object

One attempt of a task in a run_dag result.

Parameters:
  • attempt_id (str)

  • try_number (int)

  • status (str | None)

  • exit_code (int | None)

  • error_kind (str | None)

  • error (Mapping[str, str] | None)

  • started_at (datetime | None)

  • ended_at (datetime | None)

  • duration (timedelta | None)

  • cleanup (Cleanup | None)

attempt_id

Its ID.

Type:

str

try_number

Its try number.

Type:

int

status

How it ended (success, failed, timed_out, …).

Type:

str | None

exit_code

The process’s exit code (none for tasks without a process).

Type:

int | None

error_kind

The failure kind schedr recognised (e.g. input_mismatch), if any.

Type:

str | None

error

The error summary of a failure (exception, message, traceback).

Type:

collections.abc.Mapping[str, str] | None

started_at

When the worker started it.

Type:

datetime.datetime | None

ended_at

When it ended.

Type:

datetime.datetime | None

duration

How long it ran, measured by the worker (None while it runs, or for an attempt the master ended); not ended_at - started_at, which come from the master’s wall clock and can step.

Type:

datetime.timedelta | None

cleanup

What ran on its handles (cleanup_handle), or None if it registered none and its task has no cleanup=.

Type:

schedr.testing.Cleanup | None

classmethod from_json(data)

Reads an attempt from schedr dags test --json.

Parameters:

data (Mapping[str, Any]) – The attempt’s JSON.

Returns:

The attempt.

Return type:

Attempt

class schedr.testing.TaskResult(task_id, state, outcome, try_number, output_json, attempts, log, _decode, map_index=None, instances=None, cleanup=None)

Bases: object

One task in a run_dag result.

Parameters:
  • task_id (str)

  • state (str)

  • outcome (str | None)

  • try_number (int)

  • output_json (Json)

  • attempts (tuple[Attempt, ...])

  • log (str)

  • _decode (Callable[[str, Json, str | None], object])

  • map_index (int | None)

  • instances (tuple[TaskResult, ...] | None)

  • cleanup (str | None)

task_id

The task’s ID.

Type:

str

state

Where it ended (success, failed, upstream_failed, …).

Type:

str

outcome

Its outcome on success (SUCCESS).

Type:

str | None

try_number

Its last try number (0 if it never ran).

Type:

int

output_json

Its output as stored (tagged JSON), or None; a mapped task’s is the list of its instances’ outputs (None for one that didn’t succeed).

Type:

schedr.types.Json

attempts

Its attempts, in order (none for a mapped task as a whole: its instances have them).

Type:

tuple[schedr.testing.Attempt, …]

log

The log of all its attempts.

Type:

str

map_index

Which instance of a mapped task it is, from 0; None for an unmapped task and a mapped one as a whole.

Type:

int | None

instances

A mapped task’s instances, in order (result.tasks["fetch"][1] is one); None for an unmapped task.

Type:

tuple[schedr.testing.TaskResult, …] | None

cleanup

The task’s own cleanup=: how it ended over all its attempts (ok, failed, …); None for a task without one, or until it has ended.

Type:

str | None

property output: object

The output decoded by the task’s return type, as a downstream task would get it.

A command’s output is a ProcessResult; an empty task’s is None.

Raises:

RunDagError – If the DAG file can’t be imported to find the type.

class schedr.testing.ResourceResult(setup, cleanup, users, blocking, state)

Bases: object

A resource of a run in a run_dag result.

Parameters:
  • setup (str)

  • cleanup (str)

  • users (tuple[str, ...])

  • blocking (bool)

  • state (str)

setup

Its setup’s task ID (the resource’s name).

Type:

str

cleanup

Its cleanup’s task ID.

Type:

str

users

The tasks that use it.

Type:

tuple[str, …]

blocking

Whether what follows the resource’s group waits for its cleanup (a failed cleanup fails the run either way).

Type:

bool

state

Where it is: setting_up, waiting_for_users, cleaning_up, cleaned, cleanup_failed, cleanup_cancelled (cancelled by hand: what the setup made may be left) or not_needed.

Type:

str

class schedr.testing.RunResult(run_id, dag_id, kind, state, planned_for, since, tasks, resources=<factory>)

Bases: object

The result of run_dag: the run and each of its tasks.

Parameters:
  • run_id (str)

  • dag_id (str)

  • kind (str)

  • state (str)

  • planned_for (datetime)

  • since (datetime)

  • tasks (Mapping[str, TaskResult])

  • resources (Mapping[str, ResourceResult])

run_id

The run’s ID.

Type:

str

dag_id

The DAG.

Type:

str

kind

The run’s kind (manual).

Type:

str

state

How the run ended: success, failed or cancelled.

Type:

str

planned_for

The moment it was for.

Type:

datetime.datetime

since

The start of its window, (since, planned_for].

Type:

datetime.datetime

tasks

Its tasks by ID.

Type:

collections.abc.Mapping[str, schedr.testing.TaskResult]

resources

Its resources by name (the setup’s task ID).

Type:

collections.abc.Mapping[str, schedr.testing.ResourceResult]

schedr.testing.schedr_binary()

The schedr binary run_dag starts.

In order: $SCHEDR_BIN; the schedr installed with this Python’s schedr package (its scripts directory, so the binary matches the package); schedr on PATH.

Returns:

Its path.

Raises:

RunDagError – If none is found.

Return type:

str

schedr.testing.run_trigger(trigger, *, after=None, take=1, timeout=datetime.timedelta(seconds=30), run=None)

Runs a trigger in this process until it has found take events, and gives them.

For unit tests of a trigger’s function: run_trigger(new_files(prefix="in/"), take=3). Run it inside task_context to give it secrets and connections. An @trigger(wait_for=...) is called once, for run: run_trigger(on_orders(least=5), run=schedr.RunResult(...)) gives the event it returned, as the master gets it, or none. An @trigger.poke(batch=...) gives one event per poke that found items, its data their list: the window isn’t waited for.

Parameters:
  • trigger (TriggerFunction[..., Any] | EventTrigger) – The trigger with its arguments, or its function when it takes none.

  • after (str | None) – What it starts from: the last key acted on.

  • take (int) – How many events to wait for.

  • timeout (timedelta) – How long to wait for them.

  • run (RunResult[Any] | Event[Any] | None) – For an @trigger(wait_for=...), the run it is called for; for one waiting for an EventNamed, the Event.

Returns:

The events it found, in order, fewer than take only when a generator returned.

Raises:
  • TimeoutError – If they don’t come in time.

  • ValueError – For a take below 1, or run given to a trigger without wait_for or missing for one with it.

  • RuntimeError – If a poke’s call failed.

Return type:

list[Event[Any]]

schedr.testing.run_dag(path, dag_id, *, for_=None, params=None, event=None, secrets=None, connections=None, step=False, replace=None)

Runs one real run of a DAG with schedr dags test and returns its result.

Every task runs as its own process, as in production. The DAG’s Python tasks run with this Python ([interpreters] python is set to it unless the environment sets it).

Parameters:
  • path (str | PathLike[str]) – A DAG file, or a directory of DAG files (a DAG root).

  • dag_id (str) – The DAG to run.

  • for – The run’s planned_for (aware); now by default.

  • params (object) – Values for the run’s parameters: an instance of the DAG’s params class, or a mapping of field names to JSON values ({"region": "us"}), over its defaults.

  • event (Event[Any] | None) – For a DAG a trigger starts, the event the run brings; its data encoded as the trigger’s would be.

  • secrets (Mapping[str, str] | None) – Secret values, by "path#key", for every storage (--secret); masked in the logs and outputs as usual.

  • connections (Mapping[str, Mapping[str, object]] | None) – Values for connections, by name, each its parameters’ values (--connection): the real @connection function runs with them instead of its own, which are never rendered. A task still opens only what it declares.

  • step (bool) – Yield each task as it ends (milestone M4).

  • replace (Mapping[str, object] | None) – Results replacing tasks (milestone M4).

  • for_ (datetime | None)

Returns:

The run, whether it succeeded or not.

Raises:
  • RunDagError – If the binary isn’t found, or the run couldn’t be made (e.g. no such DAG, or a file that doesn’t import).

  • TypeError – If for_ isn’t a datetime.

  • ValueError – If for_ is naive.

  • NotImplementedError – For step or replace.

Return type:

RunResult