From 61b21e8aaee2e471596db4a64885b76233d1ede3 Mon Sep 17 00:00:00 2001 From: Yota Hamada Date: Mon, 23 Nov 2026 23:23:15 +0900 Subject: [PATCH 01/17] Add a guide to workflow tests dagu test runs a DAG with its step actions mocked and checks run and step statuses, outputs, logs, and notifications. Authors need one page that covers the test file, mocks, the default mock, real steps, assertions, the fail-closed rule and its paste-ready fix, secrets, editor support through the JSON Schema, and running tests in CI. Every example DAG passes dagu validate, and every example test file runs under dagu test with the result the page states. --- .vitepress/config.js | 1 + writing-workflows/index.md | 3 + writing-workflows/workflow-tests.md | 882 ++++++++++++++++++++++++++++ 3 files changed, 886 insertions(+) create mode 100644 writing-workflows/workflow-tests.md diff --git a/.vitepress/config.js b/.vitepress/config.js index b1e5d3b3..df24b3bd 100644 --- a/.vitepress/config.js +++ b/.vitepress/config.js @@ -251,6 +251,7 @@ const fullSidebar = [ { text: "Environment Variables", link: "/writing-workflows/environment-variables" }, { text: "Labels", link: "/writing-workflows/labels" }, { text: "Tags", link: "/writing-workflows/tags" }, + { text: "Workflow Tests", link: "/writing-workflows/workflow-tests" }, ], }, { diff --git a/writing-workflows/index.md b/writing-workflows/index.md index a7ced449..fa9f6c15 100644 --- a/writing-workflows/index.md +++ b/writing-workflows/index.md @@ -84,6 +84,8 @@ dagu start --only report pipeline.yaml # Run one step on its own dagu history pipeline # List recent runs ``` +To check failure branches, retries, and handlers without running commands, write a [workflow test](/writing-workflows/workflow-tests) beside the DAG and run it with `dagu test`. + Start the server to inspect the same workflows in the Web UI: ```bash @@ -254,6 +256,7 @@ Other built-in actions cover [HTTP requests](/step-types/http), [JavaScript tran | Start a run for each file that arrives in a folder | [Watched Folders](/writing-workflows/watched-folders) | | Keep a DAG running like a service | [Services](/writing-workflows/services) | | Configure retries, timeouts, handlers, and failure behavior | [Durable Execution](/writing-workflows/durable-execution) and [Error Handling](/writing-workflows/error-handling) | +| Test how a DAG behaves with its commands mocked | [Workflow Tests](/writing-workflows/workflow-tests) | | Run HTTP, SQL, SSH, Docker, Kubernetes, or other actions | [Built-in Actions](/step-types/shell) | | Start from copyable workflows | [Examples](/writing-workflows/examples) | | Look up every supported field | [YAML Specification](/writing-workflows/yaml-specification) | diff --git a/writing-workflows/workflow-tests.md b/writing-workflows/workflow-tests.md new file mode 100644 index 00000000..d93e3bf8 --- /dev/null +++ b/writing-workflows/workflow-tests.md @@ -0,0 +1,882 @@ +--- +description: Test how a DAG behaves with dagu test. A test file beside the DAG mocks its step actions and asserts run and step statuses, outputs, logs, and notifications, without running commands. +--- + +# Workflow Tests + +A workflow test checks how a DAG behaves without running its commands. A test file sits beside the DAG it tests. It replaces step actions with scripted results and states what each case must end with: the run status, step statuses, attempts, outputs, logs, and the notifications the run would send. + +`dagu test` runs each case through the same runner as `dagu start`. Dependencies, preconditions, routing, retries, repeats, `continue_on`, handlers, and status propagation behave as in a real run. Only the mocked actions differ. The DAG needs no change to be testable. + +A missing mock never reaches a real system. When a step with side effects has no mock and is not listed as real, the case is invalid and nothing runs. + +## Requirements + +- A Dagu release after v2.27.0. + +## Quick Start + +Save a DAG and its test file in one directory: + +```yaml +# workflows/release.yaml +steps: + - id: build + run: ./build.sh + outputs: + - name: image_tag + + - id: deploy + depends: build + run: ./deploy.sh "${steps.build.outputs.image_tag}" +``` + +```yaml +# workflows/release.test.yaml +mocks: + build: + outputs: + image_tag: v1.2.3 + deploy: {} +cases: + - name: deploys the built image + expect: + status: succeeded + - name: a failed build stops the deploy + mocks: + build: + exit_code: 1 + expect: + status: failed + steps: + build: failed + deploy: aborted +``` + +Run the tests: + +```bash +dagu test workflows/ +``` + +```text +PASS workflows/release.test.yaml: deploys the built image (0.17s) +PASS workflows/release.test.yaml: a failed build stops the deploy (0.14s) +2 cases: 2 passed, 0 failed +``` + +Neither `build.sh` nor `deploy.sh` runs. `build` publishes `image_tag` from its mock, and `deploy: {}` succeeds with no output. The second case replaces the file's `build` mock with a failing one. `deploy` then ends `aborted`, not `skipped`, because Dagu aborts the steps that depend on a failed step. + +## Where Test Files Live + +A test file ends in `.test.yaml` or `.test.yml` and sits beside the DAG it tests: + +```text +workflows/ + release.yaml + release.test.yaml + etl/ + daily.yaml + daily.test.yaml +``` + +- `release.test.yaml` and `release.test.yml` test `release.yaml`, or `release.yml` when there is no `release.yaml`. +- `dag` names another DAG file. A relative path resolves from the directory that holds the test file. +- One test file per DAG is the convention. Its scenarios are its `cases`. +- Moving or renaming a DAG together with its test file keeps the test working. + +### Test Files Are Not DAGs + +DAG discovery, the DAGs directory watcher, and DAG name lookup skip every file whose name ends in `.test.yaml` or `.test.yml`. The DAG list does not show a test file, the scheduler never runs one, and a change to one reloads nothing. `dagu start release.test` fails with a message that names `dagu test`. + +A DAG that already has such a name becomes a test file after the upgrade and stops running on its schedule. Rename it, for example from `smoke.test.yaml` to `smoke-test.yaml`. See [Upgrades](/server-admin/upgrades#upgrading-from-2-27-0-or-earlier). `dagu test` reports a file with top-level `steps` and no `cases` as invalid and asks for the rename. + +## Running Tests + +```bash +dagu test [flags] [...] +``` + +- A file argument must be a test file. +- A directory argument runs every test file under it, at any depth. Directories whose names start with `.` are skipped. +- Without an argument, `dagu test` runs every test file under the DAGs directory of the loaded configuration. +- Test files run one at a time, in path order. The cases of a file run one at a time, in file order. +- An invalid test file or case does not stop the others. + +| Flag | Default | Meaning | +|------|---------|---------| +| `--run ` | none | Run only the cases whose `name` the RE2 regular expression matches, anywhere in the name. | +| `--timeout ` | `5m` | Longest a case may run, such as `30s`. A case that runs longer fails with a `timeout` failure. | +| `--format`, `-f` | `text` | `text` or `json`. See [JSON Report](#json-report). | +| `--keep` | off | Keep each case directory, with its logs and redirect files, and print its path. | + +```bash +dagu test workflows/release.test.yaml +dagu test --run 'failed build' workflows/ +dagu test --format json --keep workflows/ +``` + +### Reading the Report + +Each case starts with one line: `PASS`, `FAIL`, or `INVALID`, the test file, the case name, and, for a case that ran, its duration. Lines indented under it give the details, and a summary line ends the report. + +When the second case of the quick start expects `deploy: skipped` and is named `a failed build skips the deploy`, the report reads: + +```text +PASS workflows/release.test.yaml: deploys the built image (0.21s) +FAIL workflows/release.test.yaml: a failed build skips the deploy (0.19s) + step deploy: expected skipped, got aborted +2 cases: 1 passed, 1 failed +``` + +A failed case lists every failed assertion, not only the first. Under each case that ran, the report also lists: + +- `default mock: `, the steps that took the [default mock](#the-default-mock); +- `approved automatically: `, the waits approved with no values (see [Steps that wait for a person](#steps-that-wait-for-a-person)); +- `notification : `, each notification the run would have sent; +- `case directory `, with `--keep`. + +An invalid case lists its errors and ends with the [fix](#the-fix-ready-to-paste). An invalid test file has one `INVALID ` line with its errors, and none of its cases runs. + +## The Test File + +| Field | Required | Meaning | +|-------|----------|---------| +| `dag` | No | Path of the tested DAG file. Defaults to the DAG beside the test file. | +| `params` | No | Run parameters for every case, by name. | +| `env` | No | DAG-level `env` entries for every case, by name. | +| `secrets` | No | Values for DAG `secrets` entries and SSH credential refs. Needed only in a case with a real step. See [Secrets](#secrets). | +| `mocks` | No | Mocks for every case, by step key. | +| `default_mock` | No | A mock for every step that needs one and that `mocks` and `real` do not name. | +| `real` | No | Step keys of the steps that run their real action in every case. | +| `cases` | Yes | The cases. Must not be empty. | + +Each case is one run of the DAG: + +| Field | Required | Meaning | +|-------|----------|---------| +| `name` | Yes | Unique in the file. | +| `params` | No | Merged over the file's `params`, by name. | +| `env` | No | Merged over the file's `env`, by name. | +| `mocks` | No | Replaces the file's mock of each step it names, as a whole. Fields of the two mocks do not merge. | +| `default_mock` | No | Replaces the file's `default_mock`. | +| `real` | No | Added to the file's `real`. | +| `precondition` | No | `met` or `not_met`: the outcome of the DAG-level preconditions that run a command. | +| `trigger` | No | `context.trigger.type` of the run: `manual` (default), `scheduler`, `webhook`, `retry`, `catchup`, `restart`, `backfill`, or `file`. It changes nothing else. | +| `scheduled_at` | No | Schedule slot of the run, in the forms `dagu dry --scheduled-at` takes. | +| `expect` | Yes | The [assertions](#assertions). | + +A test file accepts only these fields. Any other field makes the file invalid. `params` and `env` values are YAML scalars. An `env` value is used as written, without variable expansion. Each `params` entry is one `name=value` assignment, as `dagu start -- name=value` takes it. A param given a value does not run its `eval`. + +### Step Keys + +`mocks`, `real`, and `expect.steps` name steps by step key: + +- the `id` or `name` of a step of the tested DAG; +- `handler_on.` for a lifecycle handler: `init`, `success`, `failure`, `abort`, `exit`, or `wait`, including a handler that the [base configuration](/server-admin/base-config) adds. + +A key that names no step or handler makes the case invalid. Steps of other documents in the DAG file and `foreach` body steps have no key. + +## Mocks + +A mock replaces what a step's action returns. Result fields script one execution. Step fields script what happens around the action, once for the step. + +| Result field | Default | Meaning | +|--------------|---------|---------| +| `exit_code` | `0` | Exit code of the execution. A non-zero code fails the attempt. | +| `stdout` | empty | Written to the step's stdout as given. | +| `stderr` | empty | Written to the step's stderr as given. | +| `outputs` | none | Named outputs the execution publishes. | +| `condition` | none | `met` or `not_met`: the outcome of a command-check `repeat_policy.condition` after this execution. | +| `results` | none | One result per execution. Each item takes the fields above. | + +| Step field | Meaning | +|------------|---------| +| `precondition` | `met` or `not_met`: the outcome of the step's preconditions that run a command. | +| `review` | How each wait of the step is settled. See [Steps that wait for a person](#steps-that-wait-for-a-person). | + +`{}` is a valid mock. On a step with side effects, it succeeds with exit code 0 and no output. + +A mocked step keeps everything around its action. Retries read its exit code, `continue_on` and status propagation apply, string-form `output: VAR` captures its `stdout`, and its `env`, `with`, and `run` fields resolve as in a real run. It starts no process, opens no connection, creates no container, and reads no file. + +### Results per Execution + +`results` scripts each execution in turn: the first attempt takes the first result, and each retry and each repeat iteration takes the next. After the last result, later executions take the last result again. + +```yaml +# workflows/implement.yaml +steps: + - id: implement + run: agent implement + retry_policy: + limit: 2 + interval_sec: 60 +``` + +```yaml +# workflows/implement.test.yaml +cases: + - name: a flaky step passes on the third attempt + mocks: + implement: + results: + - exit_code: 1 + - exit_code: 1 + - exit_code: 0 + expect: + status: succeeded + steps: + implement: + status: succeeded + attempts: 3 +``` + +The case passes at once. Dagu does not wait for the two 60-second retry intervals. + +A mock sets either `results` or inline result fields, not both. Step fields sit beside `results`, never inside an item. + +### Mocked Outputs + +A step that declares outputs, through `outputs`, `output_schema`, object-form `output`, `stdout.outputs`, or its action, has known outputs. + +- A mock under `mocks` with exit code 0 sets every known output and no other name. A missing or extra name makes the case invalid, as a real run would fail the step. +- `outputs` needs a step with an `id`. +- A `type: json` output takes any YAML value and publishes it as JSON. A string output takes a YAML string. +- A step whose output names are known only at run time, such as a `dag.run` step, takes any name. +- A result with a non-zero exit code publishes no outputs. +- Dagu does not parse `stdout` to publish outputs and does not check `output_schema` against mocked values. + +### Steps That Run for Real + +Four actions read only their inputs and write only their stdout, stderr, and outputs. They run for real without a mock: + +- `router.route`, including a router written with the `value` and `routes` step fields +- `outputs.write` +- `log.write` +- `noop` + +A test therefore exercises the routing and outputs the DAG defines, from the mocked outputs of earlier steps. Every other action has side effects, including command steps, `decision.evaluate`, which calls a model provider, and `wait.duration`. + +To run a step with side effects for real, list it under `real`: + +```yaml +real: [lint] +``` + +Only a line in `real` runs such a step. A mock on a real step may set step fields, such as `precondition` or `review`, but no result field. A real `dag.run` or `parallel` step runs its child DAG in the case, and the child takes no mocks, so a child step with side effects makes the case invalid. Mock the parent step instead. `real` takes no `foreach` step. + +### The Default Mock + +`default_mock` covers every step that needs a mock and that `mocks` and `real` do not name. It never runs anything real, so a test keeps the fail-closed guarantee without a line per step. + +```yaml +# workflows/release.test.yaml +default_mock: {} +cases: + - name: every step succeeds by default + expect: + status: succeeded + - name: a failed build stops the deploy + mocks: + build: + exit_code: 1 + expect: + steps: + build: failed + deploy: aborted +``` + +```text +PASS workflows/release.test.yaml: every step succeeds by default (0.16s) + default mock: build, deploy +PASS workflows/release.test.yaml: a failed build stops the deploy (0.13s) + default mock: deploy +2 cases: 2 passed, 0 failed +``` + +- The report lists the steps it applied to, so steps the test never scripted stay visible. +- It sets no `outputs`. A step it replaces publishes each known output as an empty string, or `null` for a `type: json` output. +- Each field applies only where the step needs it: `precondition` to a step with a command precondition, `condition` to a step with a command repeat condition, and `review` to a wait that needs values. +- It does not handle DAG-level preconditions, `params[].eval`, or secrets. +- A step with a side-effect-free action and nothing else to handle runs for real, as without a mock. + +### Preconditions and Repeat Conditions + +A precondition that compares a value, such as `${steps.plan.outputs.risk}` with `expected`, evaluates as in a real run, against mocked outputs and the case's params and env. A precondition that runs a command, or an `eval` with command substitution, never runs under test. The test decides its outcome: + +```yaml +# workflows/migrate.yaml +preconditions: + - condition: test -f /etc/release.lock + negate: true +steps: + - id: migrate + preconditions: + - condition: test -f migrations/pending + run: ./migrate.sh + - id: notify + depends: migrate + run: ./notify.sh +``` + +```yaml +# workflows/migrate.test.yaml +mocks: + migrate: + precondition: not_met + notify: {} +cases: + - name: nothing pending skips the migration + precondition: met + expect: + status: succeeded + steps: + migrate: skipped + notify: skipped + - name: a release lock aborts the run + precondition: not_met + expect: + status: aborted + steps: + migrate: not_started +``` + +- `precondition` in a mock decides the step's command conditions, after `negate` applies. `not_met` skips the step. The step's value conditions still evaluate. +- `precondition` in a case decides the DAG-level command conditions. `not_met` aborts the run before any step starts. +- `condition` in each result of a mock decides a command-check `repeat_policy.condition` after that execution. `met` keeps a `while` step repeating and stops an `until` step. See [Repetition](/writing-workflows/control-flow#repetition). + +A mocked step that repeats without a `limit` runs one execution per result, then stops, since nothing else bounds it under test. + +### Steps That Wait for a Person + +A `human.task` step or a step with `approval` waits as in a real run: the run reaches `waiting`, and `handler_on.wait` runs. The test then settles each wait and the run resumes. Nothing waits for a person. + +- A wait that needs no values is approved automatically, and the report lists it under `approved automatically`. +- A wait that needs values takes `review` in the step's mock: a `human.task` whose form has a `required` property without a `default`, or an `approval` with `required` inputs. + +```yaml +# workflows/gate.yaml +steps: + - id: release + run: ./release.sh + approval: + prompt: Ship it? + - id: announce + depends: release + run: ./announce.sh + approval: + prompt: Announce it? + input: [channel] + required: [channel] +``` + +```yaml +# workflows/gate.test.yaml +mocks: + release: {} + announce: + review: + decision: approve + values: + channel: releases +cases: + - name: an approved release is announced + expect: + status: succeeded + steps: + announce: succeeded + - name: a rejected release ends the run + mocks: + release: + review: + decision: reject + expect: + status: rejected + steps: + release: rejected + announce: not_started +``` + +In the first case, the gate of `release` needs no values, so it is approved automatically, and the report lists `approved automatically: release`. The gate of `announce` takes its `review`. + +| `review` field | Meaning | +|----------------|---------| +| `decision` | `approve` or `reject`. Settles every wait of the step. | +| `values` | The completion input of a `human.task`, or the inputs of an `approval` gate. | + +`reject` on an approval gate ends the step and the run `rejected`. A `human.task` takes only `approve`, and its `values` must pass its form. See [Approval Gates](/writing-workflows/approval) and [Human Tasks](/writing-workflows/human-tasks). + +### Sub-DAG, Parallel, and Foreach Steps + +- A mock of a `dag.run`, `dag.enqueue`, or `parallel` step replaces its child runs. No child starts or is queued. The mock's result and `outputs` are the step's. +- A mock of a `foreach` step replaces the whole construct: items, body, and aggregate status. Individual body steps take no mock. +- A `foreach` step whose body steps are all side-effect free runs for real, over items from mocked upstream outputs. + +## Assertions + +`expect` holds at least one assertion. A step without an assertion is not checked. + +```yaml +expect: + status: failed + attempts: 1 + steps: + test: + status: failed + stderr: + contains: FAIL ./uploader + route: aborted + handler_on.failure: succeeded + notifications: + - kind: mail_on.failure +``` + +| Field | Meaning | +|-------|---------| +| `status` | Run status: `succeeded`, `failed`, `aborted`, `partially_succeeded`, or `rejected`. | +| `attempts` | Run attempts, counting retries of a DAG-level `retry_policy`. | +| `steps.` | A step status, or a map with one or more of `status`, `attempts`, `outputs`, `stdout`, and `stderr`. | +| `steps..status` | `succeeded`, `failed`, `aborted`, `skipped`, `partially_succeeded`, `rejected`, or `not_started`. | +| `steps..attempts` | Executions of the step's action, counting retries and repeat iterations. A skipped step has 0. | +| `steps..outputs` | Expected named outputs. | +| `steps..stdout`, `stderr` | `contains` (text), `matches` (RE2 regular expression), or both, on the last execution's stream. | +| `notifications` | The notifications the run would have sent. | + +A case passes when the run reaches a terminal status and every assertion holds. + +### Outputs, Logs, and Notifications + +```yaml +# workflows/report.yaml +mail_on: + failure: true +error_mail: + from: dagu@example.com + to: oncall@example.com +steps: + - id: count + run: ./count.sh + outputs: + - name: files + - name: stats + type: json + - id: summary + depends: count + action: log.write + with: + message: ${steps.count.outputs.files} files changed + - id: check + depends: summary + run: ./check.sh +``` + +```yaml +# workflows/report.test.yaml +mocks: + count: + outputs: + files: "3" + stats: + files: 3 + lines: 40 + check: {} +cases: + - name: the summary reports the count + expect: + status: succeeded + steps: + summary: + stdout: + contains: 3 files changed + matches: '^\d+ files changed' + notifications: [] + - name: a failed check sends one mail + mocks: + check: + exit_code: 1 + expect: + status: failed + notifications: + - kind: mail_on.failure + to: [oncall@example.com] +``` + +`summary` runs its real `log.write` action with the mocked count. + +- A string output matches a YAML string exactly. A `type: json` output, or any expected value that is not a string, matches when every listed key matches, recursively. Keys it does not list are ignored, and arrays and scalars match exactly. +- An output assertion on a mocked step checks only what the test supplied. It is most useful on side-effect-free steps, which run for real. +- A stream assertion reads the step's log of its last execution, with secrets masked. A step that never ran fails it. +- `notifications` compares without regard to order. Each item has `kind`: `mail_on.failure`, `mail_on.success`, `mail_on.wait`, or `mail_on_error`. It may set `to`, compared as a set, and, for `mail_on_error`, `step`. `notifications: []` asserts that the run would send none. No mail is sent under test. + +## The Fail-Closed Rule + +A case is invalid, and nothing runs, when the DAG has something that would run a command or reach a real system and the case does not handle it. The rule covers every step and handler, reached or not, so the outcome does not depend on the branch a case takes. + +| Error label | Source | What the case adds | +|-------------|----------------|--------------------| +| `step ` | An action with side effects | A mock, `{}` included, or the step under `real` | +| `step ` | A precondition that runs a command | `precondition` in the step's mock, or the step under `real` | +| `step ` | A repeat condition that runs a command | `condition` in every result of the step's mock, or the step under `real` | +| `step ` | An object-form `output` with `from: file` | A mock that replaces the action, or the step under `real` | +| `step ` | A side-effect-free step that repeats without a `limit` | A mock with a result field, or the step under `real` | +| `step , body step ` | A `foreach` body step with side effects | A mock of the `foreach` step | +| `step ` | A wait that needs values | `review` in the step's mock, also for a real step | +| `handler_on.` | Any of the above on a handler | The same, keyed by `handler_on.` | +| `secret ` | A secret, in a case with a real step | A value under the test file's `secrets` | +| `precondition` | A DAG-level precondition that runs a command | The case's `precondition` | +| `param ` | A `params[].eval` with command substitution | A value under `params` | +| `step , child , ...` | Anything above in the child DAG of a real step | Nothing. Mock the parent step | + +`` is the step's `id`, or its `name` when it has none. + +### The Fix, Ready to Paste + +The error of an invalid case lists every unhandled source at once and ends with YAML that handles them: + +```yaml +# workflows/ship.yaml +params: + - name: env + default: prod + - name: build_date + eval: $(date +%F) +steps: + - id: build + run: ./build.sh + - id: deploy + depends: build + action: ssh.run + with: + host: prod.example.com + user: deploy + command: ./deploy.sh +handler_on: + failure: + action: mail.send + with: + from: dagu@example.com + to: oncall@example.com + subject: ship failed + message: ship failed +``` + +```yaml +# workflows/ship.test.yaml +mocks: + build: {} +cases: + - name: ships + expect: + status: succeeded +``` + +```text +INVALID workflows/ship.test.yaml: ships + param build_date: eval runs a command; give it a value under params + step deploy: action ssh.run has side effects; mock it or list it under real + handler_on.failure: action mail.send has side effects; mock it or list it under real + fix, ready to paste: + params: + build_date: "" + mocks: + deploy: {} + handler_on.failure: {} +1 case: 0 passed, 0 failed, 1 invalid +``` + +Paste the lines under `fix, ready to paste:` into the case, merged with the fields it already has, and the case runs. A missing secret value appears under `fix for the test file, ready to paste:`, for the test file's `secrets`. + +The fix uses neutral values: `{}` for an action, `""` for each declared output, `precondition: met`, a `condition` that stops a repeat, and `review` with `decision: approve` and a value for each required input. Edit them into the scenario the case tests. A value that a form constraint such as `pattern` rejects carries the comment `# replace with a value the form accepts`, and the case stays invalid until it is replaced. + +Other mistakes also make a case invalid, each with an error that names the field: a key that names no step, an output the step does not declare, an unknown status, a `matches` value that is not a valid RE2 expression, or a `review` on a step that does not wait. + +## Secrets + +Secrets never resolve through their providers under test. No registry, vault, file, or environment variable is read. + +- A case without a real step needs no secret values. Each DAG `secrets` entry resolves to the placeholder ``, which is masked in logs like a secret value. +- A case with a real step needs a value in the test file's `secrets` for every DAG `secrets` entry and every SSH credential ref, since Dagu cannot tell which of them the real step reads. A missing one makes the case invalid. + +```yaml +# workflows/publish.yaml +secrets: + - name: API_TOKEN + ref: prod/publish-token +steps: + - id: lint + run: echo "lint passed" + - id: publish + depends: lint + run: ./publish.sh +``` + +```yaml +# workflows/publish.test.yaml +secrets: + API_TOKEN: fake-token +mocks: + publish: {} +cases: + - name: publishes with every step mocked + mocks: + lint: {} + expect: + status: succeeded + - name: lint runs for real + real: [lint] + expect: + steps: + lint: + stdout: + contains: lint passed +``` + +The first case would pass without `secrets`: `API_TOKEN` would resolve to its placeholder. The second case runs `lint` for real, so it needs a value for `API_TOKEN`. Without one, it is invalid, and its error starts with `secret API_TOKEN:`. + +Test files are committed with the DAGs, so their `secrets` hold fake values. A step that needs a real credential to pass belongs under a mock, not under `real`. A committed test file never holds a real credential, and a case does not depend on the environment of the host that runs it. + +## What Changes Under Test + +| Behavior | Under test | +|----------|------------| +| Retry and repeat intervals, backoff, and `delay_sec` | Not waited for, except by real steps. The order and count of executions do not change. | +| `timeout_sec` | Applies as in a real run. A mocked action returns at once. | +| Run history, logs, artifacts, and `state` | Kept in a temporary case directory, removed when the case ends unless `--keep` is set. The configured data directory is not read or written. | +| `mail_on` and `mail_on_error` | Not sent. The report lists each notification the run would have sent. | +| OpenTelemetry export | Off. | +| `stdout` and `stderr` redirect files | Written inside the case directory. | +| The DAG's `working_dir`, DAG-level `container` and `ssh`, `tools`, and native resource limits | Set up only when the case has a real step. | +| A DAG-level `retry_policy` | `dagu test` retries the run in the same case without waiting. Mock results keep counting across run attempts. | +| `queue` and `worker_selector` | Ignored. The case runs locally, in the `dagu test` process. | + +A test runs beside live runs of the same DAG. Neither sees the other, and the test's run does not appear in the DAG's history. + +## Writing Tests Faster + +### Start From the Fix + +Write a case with the expectation you want, run it, and paste the fix: + +1. Create the test file with one case and its `expect`. +2. Run `dagu test` on it. The case is invalid and lists every source the DAG has. +3. Paste the fix into the case, or move the mocks to the file level to share them across cases. +4. Change the pasted values into the scenario, such as a failing `exit_code` or a `high` risk output, and run again. + +`default_mock: {}` is a shorter start: every step with side effects succeeds with no output, and the report lists the steps that took it. + +### Generate a Test File + +::: info Coming in a later release +`dagu test --init ` writes the DAG's test file beside it, with a mock for every source the fail-closed rule needs and one case named `initial` whose `expect` holds the result of a run with those mocks. It refuses to replace an existing test file. It ships in a release after `dagu test` itself. +::: + +### Editor Support + +Dagu publishes a JSON Schema for test files, so an editor with YAML schema support validates and completes them. A running Dagu server serves it at `/assets/workflow-test.schema.json`, under the server's base path, and the Dagu repository holds it at `schemas/workflow-test.schema.json`. + +Name the schema in the first line of a test file: + +```yaml +# yaml-language-server: $schema=http://localhost:8080/assets/workflow-test.schema.json +mocks: + deploy: {} +cases: + - name: deploys + expect: + status: succeeded +``` + +Or map every test file to it in VS Code `settings.json`, with the YAML extension: + +```json +{ + "yaml.schemas": { + "http://localhost:8080/assets/workflow-test.schema.json": ["*.test.yaml", "*.test.yml"] + } +} +``` + +The schema rejects unknown fields and wrong types. `dagu test` stays the authority: it also checks what only the DAG can tell, such as a mock for a step the DAG lacks. + +## Running Tests in CI + +`dagu test` runs headless. Its exit status tells the result: + +| Status | Meaning | +|--------|---------| +| `0` | Every selected case passed, or no case was selected. | +| `1` | At least one case failed. | +| `2` | At least one test file or case is invalid, or the arguments are invalid. | + +The highest status that applies wins: a run with a failed case and an invalid case exits 2. + +```yaml +# .github/workflows/dagu-test.yaml +name: Workflow tests +on: [push, pull_request] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install Dagu + run: npm install -g --ignore-scripts=false @dagucloud/dagu + - name: Run workflow tests + run: dagu test workflows/ +``` + +Pass the directory that holds the DAGs. Without an argument, `dagu test` reads the DAGs directory of the loaded configuration, which is usually empty on a CI runner, and selecting no case exits 0. + +A case without a real step needs no credential, container runtime, or network access, so a job that runs only such cases needs no CI secrets. + +### JSON Report + +`--format json` writes exactly one JSON object to stdout once every case has ended. Logs go to stderr. For the failing test file of [Reading the Report](#reading-the-report): + +```bash +dagu test --format json workflows/release.test.yaml +``` + +```json +{"cases":[{"file":"workflows/release.test.yaml","name":"deploys the built image","result":"pass","duration_ms":207},{"file":"workflows/release.test.yaml","name":"a failed build skips the deploy","result":"fail","duration_ms":138,"failures":[{"step":"deploy","field":"status","expected":"skipped","actual":"aborted"}]}]} +``` + +To list only the cases that did not pass: + +```bash +dagu test --format json workflows/ | jq '.cases[] | select(.result != "pass")' +``` + +| Case field | Present | Meaning | +|------------|---------|---------| +| `file` | Always | The test file. | +| `name` | Always | The case name. | +| `result` | Always | `pass`, `fail`, or `invalid`. | +| `duration_ms` | When the case ran | Wall-clock time in milliseconds. | +| `failures` | When `result` is `fail` | One object per failed assertion: `step`, `field`, `expected`, and `actual`. `field` is `status`, `attempts`, `outputs.`, `stdout.contains`, `stdout.matches`, `stderr.contains`, `stderr.matches`, `notifications`, `timeout`, `limit`, or `error`. | +| `errors` | When `result` is `invalid` | One object per error: `source`, the label, and `message`. | +| `fix`, `file_fix` | When an invalid case has a fix | The fix for the case, and for the test file's `secrets`, as YAML text. | +| `default_mocked` | When the default mock applied | Step labels. | +| `auto_approved` | When a wait was approved automatically | Step labels. | +| `notifications` | When the run would have sent one | Objects with `kind`, `to`, and, for `mail_on_error`, `step`. | +| `case_dir` | With `--keep` | Absolute path of the kept case directory. | + +An invalid test file appears under a top-level `invalid_files` list, each with `file` and `errors`. + +## Example: An Agent Pipeline + +A pipeline plans a change with a coding agent, implements it with retries, runs the tests, and routes on the planned risk: + +```yaml +# workflows/change.yaml +params: + - name: task + type: string + required: true +steps: + - id: plan + run: agent plan "${params.task}" + outputs: + - name: risk + - id: implement + depends: plan + run: agent implement + retry_policy: + limit: 2 + interval_sec: 60 + - id: test + depends: implement + run: make test + - id: route + depends: test + action: router.route + with: + value: ${steps.plan.outputs.risk} + routes: + high: [review] + low: [merge] + - id: review + run: agent review + - id: merge + run: gh pr merge --auto +handler_on: + failure: + action: mail.send + with: + from: dagu@example.com + to: oncall@example.com + subject: change failed + message: change failed +``` + +```yaml +# workflows/change.test.yaml +params: + task: Add retries to the uploader +mocks: + plan: + outputs: + risk: low + implement: {} + test: {} + review: {} + merge: {} + handler_on.failure: {} +cases: + - name: low risk merges without review + expect: + status: succeeded + steps: + merge: succeeded + review: skipped + handler_on.failure: not_started + + - name: high risk goes to review + mocks: + plan: + outputs: + risk: high + expect: + steps: + review: succeeded + merge: skipped + + - name: flaky implement passes on the third attempt + mocks: + implement: + results: + - exit_code: 1 + - exit_code: 1 + - exit_code: 0 + expect: + steps: + implement: + status: succeeded + attempts: 3 + + - name: failing tests stop the run + mocks: + test: + exit_code: 2 + stderr: FAIL ./uploader + expect: + status: failed + steps: + test: + status: failed + stderr: + contains: FAIL ./uploader + route: aborted + handler_on.failure: succeeded +``` + +`route` runs its real `router.route` action, so the cases test the routing the DAG defines. No agent, `make`, or `gh` command runs, and the four cases finish without waiting for either 60-second retry interval. Removing the `handler_on.failure` mock makes every case invalid before any step runs. + +## Limits + +- A case runs the DAG locally, in the `dagu test` process. Scheduler, queue, coordinator, and worker behavior, and the restart loop of a [service](/writing-workflows/services), are out of scope. +- `type: agent` DAGs are not covered, and a test of a `type: build` DAG is invalid. +- `foreach` body steps and the steps of a real step's child run take no mocks. +- A mock replaces a whole action. Dagu does not virtualize HTTP or other services, and a test makes no timing assertions. +- Push-back of a waiting step, seeding `state`, and the Web UI, REST API, and MCP are not covered. From 2f71f926cff3f659f81ad72edc1ffbdba8ca9cca Mon Sep 17 00:00:00 2001 From: Yota Hamada Date: Mon, 23 Nov 2026 23:23:15 +0900 Subject: [PATCH 02/17] Document dagu test in the CLI reference Lists the command's arguments, flags, and exit statuses beside dry, and marks it local-only, since it runs each case in the CLI process. --- getting-started/cli.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/getting-started/cli.md b/getting-started/cli.md index 8abd9157..599e9ae1 100644 --- a/getting-started/cli.md +++ b/getting-started/cli.md @@ -5,7 +5,7 @@ Commands accept either DAG names (from YAML `name` field) or file paths. - Both formats: `start`, `stop`, `status`, `retry`, `dry`, `enqueue` - DAG name only: `restart` - History by DAG name or YAML path; definition by filename, stem, or configured path: `rm` -- Local-only commands: `ls`, `rm`, `profile`, `ps`, `human-task complete`, `human-task push-back`, `browser cache clear`, `browser session`, `browser writes`, `computer check`, `computer elements`, `computer cache clear`, `computer cache show`, `xlsx inspect`, `xlsx read`, `xlsx cache clear` +- Local-only commands: `ls`, `rm`, `profile`, `ps`, `test`, `human-task complete`, `human-task push-back`, `browser cache clear`, `browser session`, `browser writes`, `computer check`, `computer elements`, `computer cache clear`, `computer cache show`, `xlsx inspect`, `xlsx read`, `xlsx cache clear` ## Global Options @@ -802,6 +802,30 @@ dagu dry --profile prod my-workflow.yaml dagu dry --no-reuse report-pipeline.yaml ``` +### `test` + +Run [workflow tests](/writing-workflows/workflow-tests). Each case of a test file runs the DAG beside it through the same runner as `start`, with step actions replaced by mocks, in a temporary directory. Requires a Dagu release after v2.27.0. + +```bash +dagu test [options] [TEST_FILE_OR_DIRECTORY...] +``` + +A file argument must end in `.test.yaml` or `.test.yml`. A directory argument runs every test file under it. Without an argument, every test file under the DAGs directory runs. + +**Options:** +- `--run` - Run only the cases whose name this RE2 regular expression matches +- `--timeout` - Longest a case may run, such as `30s` (default: `5m`) +- `--format, -f` - Report format: `text` (default) or `json` +- `--keep` - Keep each case directory and print its path + +```bash +dagu test workflows/ +dagu test --run 'failed build' --timeout 30s workflows/release.test.yaml +dagu test --format json --keep workflows/ +``` + +Exits `0` when every case passed, `1` when a case failed, and `2` when a test file, a case, or the arguments are invalid. See [Running Tests in CI](/writing-workflows/workflow-tests#running-tests-in-ci). + ### `browser cache clear` Clear the recorded `act` and `upload` operations that [browser steps](/step-types/browser#replay-cache) replay, so the next run asks the model again. From 20c3bf59839c2aa8a56f92cbc7f2b967d72b4e94 Mon Sep 17 00:00:00 2001 From: Yota Hamada Date: Mon, 23 Nov 2026 23:23:15 +0900 Subject: [PATCH 03/17] Warn that .test.yaml DAGs become test files After the upgrade, DAG discovery and name lookup skip files ending in .test.yaml or .test.yml, so such a DAG leaves the DAG list and its schedule stops. Operators need to rename those files first. The Japanese upgrade page mirrors the English one and gets the same note. --- ja/server-admin/upgrades.md | 8 ++++++++ server-admin/upgrades.md | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/ja/server-admin/upgrades.md b/ja/server-admin/upgrades.md index a9539e90..70ed0976 100644 --- a/ja/server-admin/upgrades.md +++ b/ja/server-admin/upgrades.md @@ -82,6 +82,14 @@ macOS では、インストーラーが設定する launchd エージェント 各ワーカーホストのバイナリまたはイメージも更新してください。[ワーカーページ](/server-admin/distributed/workers/#web-ui-workers-page)には各ワーカーの Dagu のバージョンが表示され、サーバーより古いワーカーや新しいワーカーには印が付きます。すべてのワーカーの更新が終わったかをここで確認できます。 +## 2.27.0 以前からのアップグレード {#upgrading-from-2-27-0-or-earlier} + +ファイル名が `.test.yaml` または `.test.yml` で終わる DAG ファイルは、[ワークフローテスト](/writing-workflows/workflow-tests)のファイルとして扱われるようになります。DAG 一覧に表示されなくなり、スケジューラも実行せず、`dagu start` も受け付けません。アップグレードの前に DAG ディレクトリ(`paths.dags_dir`)でこのようなファイルを探し、名前を変更してください(例: `smoke.test.yaml` を `smoke-test.yaml` に変更)。デフォルトのディレクトリの場合は次のとおりです。 + +```bash +find ~/.config/dagu/dags -name '*.test.yaml' -o -name '*.test.yml' +``` + ## 2.26.0 以前からのアップグレード {#upgrading-from-2-26-0-or-earlier} それより後のリリースでは、スケジューラの動作が 4 点変更されています。 diff --git a/server-admin/upgrades.md b/server-admin/upgrades.md index e9cf3ad9..e153c786 100644 --- a/server-admin/upgrades.md +++ b/server-admin/upgrades.md @@ -82,6 +82,14 @@ Upgrade the standby first. The upgraded instance then takes over once, and an ol Upgrade the binary or image on each worker host as well. The [Workers page](/server-admin/distributed/workers/#web-ui-workers-page) shows the Dagu version of each worker and marks a worker older or newer than the server, so it shows when every worker is upgraded. +## Upgrading from 2.27.0 or earlier + +A DAG file whose name ends in `.test.yaml` or `.test.yml` becomes a [workflow test](/writing-workflows/workflow-tests) file. It leaves the DAG list, the scheduler stops running it, and `dagu start` refuses it. Before the upgrade, list such files in the DAGs directory, `paths.dags_dir`, and rename them, for example `smoke.test.yaml` to `smoke-test.yaml`. With the default directory: + +```bash +find ~/.config/dagu/dags -name '*.test.yaml' -o -name '*.test.yml' +``` + ## Upgrading from 2.26.0 or earlier Later releases change how the scheduler behaves in four ways: From 7dbfff73938054c28778c4f763e59ec0ade96b83 Mon Sep 17 00:00:00 2001 From: Yota Hamada Date: Mon, 23 Nov 2026 23:30:52 +0900 Subject: [PATCH 04/17] Move workflow test tables to a reference page The guide mixed tutorial examples with every field table, the fail-closed table, and the report formats, which made it hard to scan. The tables now live on Workflow Test Reference, and the guide keeps the examples with links into it. Each scenario now appears once: a repeat-condition example replaces the retry example that the agent pipeline already covers, the default mock example shows one new case, and the assertion fragment that repeated the pipeline's failing case is gone. --- .vitepress/config.js | 10 +- writing-workflows/workflow-test-reference.md | 280 +++++++++++++++++ writing-workflows/workflow-tests.md | 307 ++++--------------- 3 files changed, 355 insertions(+), 242 deletions(-) create mode 100644 writing-workflows/workflow-test-reference.md diff --git a/.vitepress/config.js b/.vitepress/config.js index df24b3bd..643da2ee 100644 --- a/.vitepress/config.js +++ b/.vitepress/config.js @@ -251,7 +251,15 @@ const fullSidebar = [ { text: "Environment Variables", link: "/writing-workflows/environment-variables" }, { text: "Labels", link: "/writing-workflows/labels" }, { text: "Tags", link: "/writing-workflows/tags" }, - { text: "Workflow Tests", link: "/writing-workflows/workflow-tests" }, + { + text: "Workflow Tests", + link: "/writing-workflows/workflow-tests", + collapsed: true, + items: [ + { text: "Overview", link: "/writing-workflows/workflow-tests" }, + { text: "Reference", link: "/writing-workflows/workflow-test-reference" }, + ], + }, ], }, { diff --git a/writing-workflows/workflow-test-reference.md b/writing-workflows/workflow-test-reference.md new file mode 100644 index 00000000..4b423438 --- /dev/null +++ b/writing-workflows/workflow-test-reference.md @@ -0,0 +1,280 @@ +--- +description: Every field of a Dagu workflow test file, the fail-closed sources and fixes, the assertions, and the text and JSON reports of dagu test. +--- + +# Workflow Test Reference + +This page lists every field of a workflow test file, the errors `dagu test` reports, and its report formats. [Workflow Tests](/writing-workflows/workflow-tests) shows how to write and run tests. + +## The Test File + +| Field | Required | Meaning | +|-------|----------|---------| +| `dag` | No | Path of the tested DAG file. A relative path resolves from the directory that holds the test file. Defaults to the DAG beside the test file. | +| `params` | No | Run parameters for every case, by name. | +| `env` | No | DAG-level `env` entries for every case, by name. | +| `secrets` | No | Values for DAG `secrets` entries, by `name`, and for SSH credential refs, by ref. Needed only in a case with a real step. | +| `mocks` | No | Mocks for every case, by step key. | +| `default_mock` | No | A mock for every step and handler that needs one and that `mocks` and `real` do not name. | +| `real` | No | Step keys of the steps that run their real action in every case. | +| `cases` | Yes | The cases. Must not be empty. | + +A test file accepts only the fields on this page, at every level. The keys of `params`, `env`, `secrets`, `mocks`, `outputs`, `expect.steps`, and `review.values` are names, not fields. + +### Cases + +| Field | Required | Meaning | +|-------|----------|---------| +| `name` | Yes | Name of the case. Not empty, and unique in the file. | +| `params` | No | Merged over the file's `params`, by name. | +| `env` | No | Merged over the file's `env`, by name. | +| `scheduled_at` | No | Schedule slot of the run, in the forms `dagu dry --scheduled-at` takes. The run gets that slot's schedule time and window. | +| `trigger` | No | `context.trigger.type` of the run: `manual` (default), `scheduler`, `webhook`, `retry`, `catchup`, `restart`, `backfill`, or `file`. It changes nothing else. | +| `precondition` | No | `met` or `not_met`: the outcome of the DAG-level preconditions that run a command or a substituting `eval`. Valid only when the DAG has one. | +| `mocks` | No | Replaces the file's mock of each step it names, as a whole. | +| `default_mock` | No | Replaces the file's `default_mock`. | +| `real` | No | Added to the file's `real`. | +| `expect` | Yes | [Assertions](#assertions). | + +- `params` and `env` values are YAML scalars. +- Each `params` entry is one `name=value` assignment, as `dagu start -- name=value` takes it. A case whose params `dagu start` would reject is invalid. A param given a value does not run its `eval`. +- An `env` entry replaces the DAG's entry of the same name, or adds one. Its value is used as written, without variable expansion. +- A file key and a case key that name the same step, one by `name` and one by `id`, name one step. + +### Step Keys + +A step key names a step or handler in `mocks`, `real`, and `expect.steps`: + +- the `id` or `name` of a step of the tested DAG's first document; +- `handler_on.` for a lifecycle handler: `init`, `success`, `failure`, `abort`, `exit`, or `wait`, including a handler that the [base configuration](/server-admin/base-config) adds. + +A key that names no step or handler, or two keys of one map or list that name the same step, make the case invalid. Steps of other documents in the DAG file and `foreach` body steps have no key. + +## Mocks + +### Result Fields + +| Field | Default | Meaning | +|-------|---------|---------| +| `exit_code` | `0` | Exit code of the execution. A non-zero code fails the attempt. | +| `stdout` | empty | Written to the step's stdout exactly as given. Dagu adds no newline. | +| `stderr` | empty | Written to the step's stderr exactly as given. | +| `outputs` | none | Named outputs the execution publishes. See [Mocked outputs](#mocked-outputs). | +| `condition` | none | `met` or `not_met`: the outcome of the step's command-check `repeat_policy.condition` after this execution. | +| `results` | none | One result per execution. Each item takes the fields above, except `results`. | + +- A mock with inline result fields is a one-item `results`. A mock sets either, not both, and `results` must not be empty. +- The first attempt takes the first result, and each retry and each repeat iteration takes the next. After the last result, each later execution takes the last result again. A mocked step that repeats without a `limit` stops after its last result instead. +- A result field that a result leaves out takes its default. +- Mock results keep counting across the run attempts of a DAG-level `retry_policy`. + +### Step Fields + +| Field | Meaning | +|-------|---------| +| `precondition` | `met` or `not_met`: the outcome of each of the step's preconditions that runs a command or a substituting `eval`, after `negate` applies, decided once per step start. Valid only on a step that has one. | +| `review` | How each wait of the step is settled. Valid only on a step that waits for a person. | + +Step fields sit beside `results` or the inline result fields, never inside a `results` item. + +### Review + +| Field | Required | Meaning | +|-------|----------|---------| +| `decision` | Yes | `approve` or `reject`. Settles every wait of the step. | +| `values` | No | The completion input of a `human.task`, or the inputs of an `approval` gate. | + +- A `human.task` takes only `approve`. Its `values` are typed as `--inputs-json` types them and must pass its form. Its outputs come from them. +- An `approval` gate takes `approve` or `reject`. `reject` ends the step and the run `rejected`. Each value is a scalar. `values` must give every name `approval.required` lists, and an empty value counts as left out. +- A wait that needs no values is approved automatically when the step's mock sets no `review`. + +### Replaced Actions + +- A mock replaces the step's action when it sets a result field. +- A mock that sets no result field also replaces the action of a step that is not real and whose action has side effects. The step then succeeds with no output. +- A mock that sets only step fields keeps the real action of a step with a side-effect-free action, and of a real step. +- A mock that sets a result field on a real step or on a `human.task` step makes the case invalid. +- A replaced step starts no process, opens no connection, creates no container, and reads no file, including its `stdin` and an `output` entry with `from: file`. + +The side-effect-free actions are `router.route`, `outputs.write`, `log.write`, and `noop`. A `foreach` step is side-effect free when every body step is. + +### Mocked Outputs + +A step has known outputs when its output names are known before the run: the names its `outputs`, `output_schema`, object-form `output`, `stdout.outputs`, and action declare. A step whose output names are known only during a run, such as a `dag.run`, `parallel`, or manifest-resolved action step, has runtime outputs. + +- `outputs` needs a step with an `id`. +- A result with exit code 0 under `mocks` sets every known output and no other name. On a step with runtime outputs, it may set any name that matches `^[A-Za-z][A-Za-z0-9_]*$`. +- A `type: string` output, the default, takes a YAML string. A `type: json` output takes any YAML value, published as JSON. Any other output publishes a YAML string as written and any other value as JSON. +- A result with a non-zero exit code publishes no outputs. +- Dagu does not parse `stdout` or read a file to publish outputs, and it does not check `output_schema` against mocked values. + +### The Default Mock + +`default_mock` takes the fields of a mock and applies to every step and handler that has a [fail-closed source](#fail-closed-sources) and that `mocks` and `real` do not name. + +- On a step whose action has side effects, it replaces the action as `{}` does, with its result fields when it sets any. +- On a step with a side-effect-free action, it replaces the action only when it sets a result field and the step reads a file through `output`, repeats without a limit, or has a command repeat condition that its results decide with `condition`. +- `precondition` applies to a step with a command or substituting `eval` precondition, `condition` to a step with a command repeat condition, and `review` to a wait that needs values. A field that handles none of a step's sources does not apply to it. +- It sets no `outputs`. A step it replaces publishes each known output as an empty string, or `null` for a `type: json` output. +- It does not handle DAG-level preconditions, `params[].eval`, secrets, or the child DAG of a real step. + +## Assertions + +| Field | Meaning | +|-------|---------| +| `status` | Run status: `succeeded`, `failed`, `aborted`, `partially_succeeded`, or `rejected`. | +| `attempts` | Run attempts, counting retries of a DAG-level `retry_policy`. | +| `steps.` | A step status, or a map with one or more of `status`, `attempts`, `outputs`, `stdout`, and `stderr`. | +| `steps..status` | `succeeded`, `failed`, `aborted`, `skipped`, `partially_succeeded`, `rejected`, or `not_started`. | +| `steps..attempts` | Executions of the step's action in every run attempt, counting retries and repeat iterations. | +| `steps..outputs` | Expected named outputs, by name. | +| `steps..stdout`, `steps..stderr` | A map with `contains`, `matches`, or both. | +| `notifications` | The notifications the run would have sent. | + +- `expect` holds at least one assertion. An empty `steps.` map, an unknown step key or status, and a negative `attempts` make the case invalid. +- A step or handler that never started is `not_started`. A step whose action never ran, such as a skipped step, has 0 attempts, and so does a `human.task` step. +- A case passes when the run reaches a terminal status and every assertion holds. The report lists every failed assertion. + +**Outputs.** A string output matches a YAML string when its text equals the string. A `type: json` output, or an expected value that is not a string, matches by the JSON rule: an object matches when every key it lists has a matching value, recursively, and keys it does not list are ignored. Arrays and scalars match only an equal value, and numbers compare by value. An output the step did not publish does not match. On a step with known outputs, an assertion on another name makes the case invalid. + +**Streams.** `contains` holds when the stream contains its text. `matches` holds when its RE2 regular expression matches anywhere in the stream. The stream is the step's stdout or stderr of its last execution, as the step's log holds it, with secrets masked. A step with no execution fails a stream assertion. An invalid `matches` expression makes the case invalid. + +**Notifications.** Each item has `kind`: `mail_on.failure`, `mail_on.success`, `mail_on.wait`, or `mail_on_error`. It may set `to`, a list of recipients compared as a set, and, with `mail_on_error` only, `step`. The list holds when the run would have sent as many notifications as it lists, and each item pairs with a different one, in any order. `notifications: []` asserts that the run would send none. Without `notifications`, notifications are not checked. + +## Fail-Closed Sources + +A case is invalid, and none of its steps runs, while the DAG has a source in this table that the case does not handle. The rule covers every step and handler, reached or not. + +| Error label | Source | Handled by | +|-------------|--------|------------| +| `param ` | A `params[].eval` with command substitution | A value under `params` | +| `secret ` | A DAG `secrets` entry or an SSH credential ref, in a case with a real step | A value under the test file's `secrets` | +| `precondition` | A DAG-level precondition with a command check or a substituting `eval` | The case's `precondition` | +| `step ` | A step action with side effects | A mock, `{}` and the default mock included, or the step under `real` | +| `step ` | A step precondition with a command check or a substituting `eval` | `precondition` in the step's mock, or the step under `real` | +| `step ` | A command-check `repeat_policy.condition` | `condition` in every result of the step's mock, or the step under `real` | +| `step ` | An object-form `output` entry with `from: file` | A mock that replaces the action, or the step under `real` | +| `step ` | A side-effect-free step that repeats without a `limit` | A mock that sets a result field, or the step under `real` | +| `step , body step ` | A `foreach` body step with any source above | A mock of the `foreach` step | +| `step ` | A wait that needs values | `review` in the step's mock, also for a real step | +| `handler_on.` | A source above on a lifecycle handler | The same, keyed by `handler_on.` | +| `step , child , ...` | A source above in the child DAG of a real step | Nothing. Mock the parent step | + +- `` and `` are the step's `id`, or its `name` when it has none. +- The errors list params, secrets, DAG-level preconditions, steps in DAG order, then handlers. +- A wait needs values when completing it with none would fail: a `human.task` whose form has a `required` property without a `default`, or an `approval` with `required` inputs. + +### The Fix + +An invalid case ends with `fix, ready to paste:` and the case fields that handle every listed source, in the order `params`, `precondition`, `mocks`. Missing secrets follow under `fix for the test file, ready to paste:`. Each source adds: + +| Source | Entry | +|--------|-------| +| A step action with side effects, or a `foreach` body step | `{}` on the step or its `foreach` step, with `outputs` set to `""` for each known output, or `null` for a `type: json` one | +| An `output` with `from: file`, or a step that repeats without a limit, on a side-effect-free step | `exit_code: 0`, with `outputs` as above | +| A step precondition | `precondition: met` in the step's mock | +| A command-check repeat condition | A `condition` that stops the step, `not_met` for `while` and `met` for `until`, in each result | +| A wait that needs values | `review` with `decision: approve` and a value for each required name | +| A secret or SSH credential ref | Its name under `secrets` with `""` | +| A DAG-level precondition | The case's `precondition: met` | +| A substituting `params[].eval` | The param's `default`, else its first `enum` value, else `""` | + +A required `human.task` value is its first `enum` or `oneOf` value, else `""`, `0`, or `false` by type. A required `approval` input is `TODO`. A value that another form constraint, such as `pattern`, rejects carries the comment `# replace with a value the form accepts`, and the case stays invalid until it is replaced. + +### Other Invalid Cases + +A case is also invalid when: + +- a mock sets `outputs` that [Mocked outputs](#mocked-outputs) rejects, or the default mock sets `outputs`; +- a mock sets `precondition`, `condition`, or `review` on a step that has no such source; +- `real` lists a `foreach` step; +- a `secrets` key names neither a DAG `secrets` entry nor an SSH credential ref of the DAG; +- `trigger`, `scheduled_at`, `precondition`, `condition`, or `decision` has a value this page does not list; +- `expect` breaks a rule of [Assertions](#assertions), or a `notifications` item has an unknown `kind` or sets `step` without `mail_on_error`. + +The error line names the field, such as `mocks.build.outputs` or `expect.steps.deploy`. The other cases of the file still run. + +### Invalid Test Files + +A test file is invalid, and none of its cases runs, when: + +- it is not valid YAML, or its top level is not a map; +- it has a field this page does not define, or a field of the wrong type; +- `cases` is missing or empty, a case has no `name` or `expect`, or two cases share a `name`; +- it has top-level `steps` and no `cases`, which reads as a DAG. The error asks for a rename; +- the tested DAG file does not exist, `dag` names a test file, or the DAG fails to load as `dagu start` loads it; +- the tested DAG is a `type: build` DAG. + +The other test files still run. + +## What Changes Under Test + +| Behavior | Under test | +|----------|------------| +| Retry and repeat intervals, backoff, and `delay_sec` | Not waited for, except by real steps. The order and count of executions do not change. | +| `timeout_sec` | Applies as in a real run. A replaced action returns at once. | +| A DAG-level `retry_policy` | `dagu test` retries the run in the same case directory, without waiting, with the trigger type `retry`. | +| Run history, logs, artifacts, and `state` | Kept in a new case directory, removed when the case ends unless `--keep` is set. The configured data directory is not read or written, and `state` starts empty. | +| `mail_on` and `mail_on_error` | Not sent. The report lists each notification the run would have sent. | +| OpenTelemetry export | Off. | +| `stdout` and `stderr` redirect files | Written inside the case directory, for every step that is not real. | +| The DAG's `working_dir`, DAG-level `container` and `ssh`, `tools`, and native resource limits | Set up only when the case has a real step. | +| Secrets | Resolved by no provider. A placeholder `` without a real step, the test file's value otherwise. Both are masked. | +| `queue` and `worker_selector` | Ignored. The case runs in the `dagu test` process. | + +A case runs beside the live runs of the same DAG. Neither sees the other, and the case's run does not appear in the DAG's history. An interrupted `dagu test` stops the running case, starts no other, and exits with a non-zero status. + +## Report + +The report goes to stdout. A test file appears by its path relative to the current directory when it is under it, and by its absolute path otherwise. + +### Text Report + +- `PASS : ()`, `FAIL : ()`, or `INVALID : ` starts each case, in run order. +- `INVALID ` starts an invalid test file, whose cases do not appear. +- Under a case that ran, in this order: one line per failed assertion, `default mock: `, `approved automatically: `, one `notification : ` line per notification, and `case directory ` with `--keep`. +- Under an invalid case or file: one `