diff --git a/.vitepress/config.js b/.vitepress/config.js index b1e5d3b..643da2e 100644 --- a/.vitepress/config.js +++ b/.vitepress/config.js @@ -251,6 +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", + collapsed: true, + items: [ + { text: "Overview", link: "/writing-workflows/workflow-tests" }, + { text: "Reference", link: "/writing-workflows/workflow-test-reference" }, + ], + }, ], }, { diff --git a/getting-started/cli.md b/getting-started/cli.md index 8abd915..181a40c 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,38 @@ 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, or the one its `dag` field names, through the same runner as `start`, with step actions replaced by mocks, in a temporary directory. A step the case lists under `real` runs its real action. Requires a Dagu release after v2.27.0. + +```bash +dagu test [options] [TEST_FILE_DAG_FILE_DAG_NAME_OR_DIRECTORY...] +``` + +A test file argument ends in `.test.yaml` or `.test.yml`. A DAG file argument, a `.yaml` or `.yml` file that is not a test file, runs the test files beside it: `release.yaml` runs `release.test.yaml` and `release.test.yml`, whichever exist. An argument that is not an existing path is a DAG name, resolved in the DAGs directory as `start` resolves one. A DAG with no test file exits `2` with an error that names `dagu test --init`. A directory argument runs every test file under it, skipping directories whose names start with `.` and not following symbolic links. Without an argument, every test file under the DAGs directory runs. Selecting no test file is not an error and exits `0`. + +With `--init`, the one argument is a DAG file, and Dagu writes its test file beside it instead of running tests. See [Generate a Test File](/writing-workflows/workflow-tests#generate-a-test-file). + +**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 +- `--init` - Write the test file of the DAG file given as the one argument, with a mock for every step that needs one and one case that expects the result of a run with those mocks. It never replaces a test file and takes no `--update`, `--run`, `--keep`, or `--format json` +- `--update` - Run the selected cases and rewrite each case's `expect` from its run, for review as a diff. It never removes an assertion. It combines with `--run`, `--timeout`, `--keep`, and `--format`, and not with `--init`. See [Update Expectations After a Change](/writing-workflows/workflow-tests#update-expectations-after-a-change) + +```bash +dagu test workflows/ +dagu test workflows/release.yaml +dagu test release +dagu test --run 'failed build' --timeout 30s workflows/release.test.yaml +dagu test --format json --keep workflows/ +dagu test --init workflows/release.yaml +dagu test --update workflows/release.test.yaml +``` + +Exits `0` when every case passed, `1` when a case failed, and `2` when a test file, a case, or the arguments are invalid. With `--update`, a test file edited during the run is left unwritten, and the command exits `1` even when every case passed, or `2` when a test file or case is 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. @@ -1314,7 +1346,7 @@ Values are shown as read from the file, the environment, or the defaults, before ### `schema` -Browse the JSON schema for DAG definitions, server configuration, or calendar files. +Browse the JSON schema for DAG definitions, server configuration, calendar files, or workflow test files. ```bash dagu schema dag @@ -1324,8 +1356,12 @@ dagu schema config dagu schema config server dagu schema calendar dagu schema calendar holidays +dagu schema test +dagu schema test cases.expect ``` +Save the test file schema for an editor with `dagu schema test > workflow-test.schema.json`. See [Editor Support](/writing-workflows/workflow-tests#editor-support). + ### `calendar` Check [business calendars](/writing-workflows/business-calendars) and preview the runs they allow. Calendar files live in `paths.calendars_dir`. diff --git a/ja/server-admin/upgrades.md b/ja/server-admin/upgrades.md index a9539e9..b26d66d 100644 --- a/ja/server-admin/upgrades.md +++ b/ja/server-admin/upgrades.md @@ -82,6 +82,33 @@ 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` も受け付けません。アップグレードの前に、このようなファイルの名前を変更してください(例: `smoke.test.yaml` を `smoke-test.yaml` に変更)。あわせて、古い名前やパスでその DAG を開始しているもの(`dag.run` ステップの `dag` や、`dagu start` を実行するスクリプトなど)もすべて更新してください。 + +対象のファイルを探すには、サーバーと同じ設定と環境で `dagu config` を実行し、`DAGs directory` の行を確認します。スクリプトインストーラーで登録したサービスは、システムサービスでは `/var/lib/dagu`、ユーザーサービスでは `~/.dagu` の下にデータを置きます。確認したディレクトリを検索します。`-H` を付けると、そのディレクトリがシンボリックリンクの場合もリンク先を検索します。 + +```bash +dagu config | grep 'DAGs directory' +find -H /path/to/dags -name '*.test.yaml' -o -name '*.test.yml' +``` + +スクリプトや `dag.run` ステップからパスで開始する DAG ファイルを置いているディレクトリがほかにあれば、それぞれで同じ検索を行ってください。上のコマンドは POSIX シェル用です。Windows の PowerShell では次のとおりです。 + +```powershell +dagu config | Select-String 'DAGs directory' +Get-ChildItem -LiteralPath 'C:\path\to\dags' -Recurse -File -Force | + Where-Object { $_.Name -like '*.test.yaml' -or $_.Name -like '*.test.yml' } +``` + +`-LiteralPath` は、名前に `[` や `]` を含むディレクトリも書いたとおりに読みます。`-Force` を付けると隠しファイルも対象になります。`find` と同じく、`Get-ChildItem` は検索中に見つかったディレクトリへのシンボリックリンクの中は検索しません。 + +アップグレード後、`dagu scheduler`、`dagu server`、`dagu start-all` は起動時に、最初のドキュメントにトップレベルの `steps` があり `cases` がないファイルごとに、そのフルパスを含む警告をログに出力します。 + +```text +/path/to/dags/smoke.test.yaml reads as a DAG, with steps and no cases, but Dagu treats it as a test file and does not run it as a DAG; rename it, for example to smoke-test.yaml +``` + ## 2.26.0 以前からのアップグレード {#upgrading-from-2-26-0-or-earlier} それより後のリリースでは、スケジューラの動作が 4 点変更されています。 diff --git a/server-admin/upgrades.md b/server-admin/upgrades.md index e9cf3ad..3d6f056 100644 --- a/server-admin/upgrades.md +++ b/server-admin/upgrades.md @@ -82,6 +82,33 @@ 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, rename such files, for example `smoke.test.yaml` to `smoke-test.yaml`, and update everything that starts one by its old name or path, such as the `dag` of a `dag.run` step or a script that runs `dagu start`. + +To find them, run `dagu config` as the server runs, with its configuration and environment, and read the `DAGs directory` line. A service installed by the script installer keeps its data under `/var/lib/dagu` for a system service or `~/.dagu` for a user service. Then search that directory. `-H` follows it when it is a symbolic link: + +```bash +dagu config | grep 'DAGs directory' +find -H /path/to/dags -name '*.test.yaml' -o -name '*.test.yml' +``` + +Run the search again in each other directory that holds DAG files started by path, such as from a script or a `dag.run` step. The commands above are for a POSIX shell. In PowerShell on Windows: + +```powershell +dagu config | Select-String 'DAGs directory' +Get-ChildItem -LiteralPath 'C:\path\to\dags' -Recurse -File -Force | + Where-Object { $_.Name -like '*.test.yaml' -or $_.Name -like '*.test.yml' } +``` + +`-LiteralPath` reads the directory as written, even with `[` or `]` in its name, and `-Force` includes hidden files. Like `find`, `Get-ChildItem` does not search inside symbolic links to directories that it finds during the search. + +After the upgrade, `dagu scheduler`, `dagu server`, and `dagu start-all` log a warning at startup for each such file whose first document has top-level `steps` and no `cases`, with its full path: + +```text +/path/to/dags/smoke.test.yaml reads as a DAG, with steps and no cases, but Dagu treats it as a test file and does not run it as a DAG; rename it, for example to smoke-test.yaml +``` + ## Upgrading from 2.26.0 or earlier Later releases change how the scheduler behaves in four ways: diff --git a/writing-workflows/index.md b/writing-workflows/index.md index a7ced44..081b707 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 pipeline.test.yaml`. + 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-test-reference.md b/writing-workflows/workflow-test-reference.md new file mode 100644 index 0000000..001af16 --- /dev/null +++ b/writing-workflows/workflow-test-reference.md @@ -0,0 +1,354 @@ +--- +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. `dagu schema test` prints the JSON Schema of the same fields. + +## 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`, `stderr`, and `called_with`. | +| `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. | +| `steps..called_with` | What the step's last execution was called with: `run`, `with`, `env`, or several. See [Called With](#called-with). | +| `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. + +### Called With + +`called_with` checks the call of a step's last execution: the values Dagu resolved for its action, before the action ran or its mock replaced it. It holds for mocked and real steps alike. + +| Field | Meaning | +|-------|---------| +| `run` | The resolved command or script of a step written with `run`. A string matches it exactly. A map takes `contains`, `matches`, or both, as a stream assertion does. | +| `with` | The resolved inputs of a step written with `action`, by name. | +| `env` | The variables the step's action receives, by name. | + +- The last execution is the latest execution of the step's action in every run attempt. A step with no execution, such as a skipped step or a handler that never ran, fails `called_with` once, whatever it lists. +- `run` is the script of a multi-line `run`, the command of a one-line `run` without leading and trailing whitespace, or the commands of a list-form `run`, one per line, each with its references resolved. +- `with` holds the inputs as the step writes them, each resolved as the action resolves it. For a custom action, they are the inputs the step passes, not the fields of its definition. Only the listed inputs are checked. A string matches an input whose text equals it, and any other value matches by the JSON rule of outputs: listed keys only, recursively. An input the step does not set does not match. +- `env` holds every variable the action receives: the host variables that Dagu [forwards to steps](/server-admin/operations#environment-variable-filtering), such as `PATH` and `HOME` and those `env_passthrough` adds, the DAG's and the step's `env`, and secrets. Only the listed names are checked, each against its exact text. A variable that is not set does not match. +- A secret compares as the step saw it: its placeholder `` in a case without a real step, and its value under `secrets` in a case with one. The report masks it as `*******`. + +These make the case invalid, each with an error under its field: + +| Mistake | Error | +|---------|-------| +| `run` on a step written with `action` | `the step runs action , which takes no run; assert with` | +| `with` on a command step | `the step runs a command, which takes no with; assert run` | +| `with` on another step not written with `action`, such as one written with the deprecated `type` field | `the step is not written with action, so it takes no with` | +| `run` on a step with no command or script, such as one written with `type` | `the step has no command or script` | +| `called_with` on a `human.task` step | `a human.task step has no action to call` | +| `called_with` on a `foreach` step | `a foreach step calls only its body steps, which have no step key` | +| `called_with` on a step with `nodes` | `a step with nodes resolves its command in the child run of each node; assert on the child DAG's steps` | +| An empty `called_with`, `with`, or `env` | `holds no assertion` | +| A `run` map without `contains` or `matches` | `must set contains, matches, or both` | +| A `matches` value that is not RE2 | `is not a valid RE2 expression: ...` | + +## 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 [Called With](#called-with), 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`; +- its first document has top-level `steps` and no `cases`, which reads as a DAG. The error suggests a name, such as `smoke-test.yaml` for `smoke.test.yaml`; +- 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. + +## Updating Expectations + +`dagu test --update` selects test files and cases as `dagu test` does, runs each selected case, and rewrites its `expect` from the run. + +- An asserted run `status` or `attempts`, step `status` or `attempts`, or `notifications` list that does not hold takes the run's value. An assertion that holds stays exactly as written, such as `total: 7.0` against a published `"7"`. +- An asserted output takes its published value. For an object, each key it lists takes its published value, recursively, and no key is added. No output assertion is added. +- A step or handler without an assertion gains its status, and `attempts` when above 1, after the case's last step entry, in DAG order and then handler order. A step entry keeps its form: a status stays a status, and a map keeps its fields. +- A `called_with` value that does not hold takes the step's call: a `run` string takes the resolved text, each listed `with` input takes its resolved value, the listed keys only of an object, and each listed variable takes its text. A secret is written as the step saw it, such as ``. A `with` input or variable that resolves from a host variable, directly or through the DAG's `env`, is written with its value on the host that ran `--update`. Give credentials through `secrets:`, which `--update` never writes as a host value, and review the diff before committing. No `called_with` is added. +- No assertion is removed. These stay as written and still fail when they do not hold: `stdout` and `stderr` assertions, a `called_with` `run` given as `contains` or `matches`, a `with` input or variable that the call lacks, the `called_with` of a step with no execution, an output the step did not publish, a listed key the published object lacks, an object where the published value is not one, and a number that YAML cannot write exactly, such as an integer above 18446744073709551615. +- Only the changed text is rewritten. Comments, quotes, and the other cases stay. A flow-style map or list that gains an entry is rewritten in block style. +- Each rewrite is read back before it is kept, so the file never gets invalid YAML or a value other than the run's. +- A test file is written once its selected cases have run, and only when an `expect` changed, through a temporary file renamed over it. It keeps its mode. + +The last line under each case says what happened to its `expect`, whether or not the case passes: + +| Text report | JSON `update` | Meaning | +|-------------|---------------|---------| +| `expect updated` | `updated` | The run changed its text. | +| `expect unchanged` | `unchanged` | The run left its text as it was. | +| `expect kept: ` | `kept` | It stays as written whatever the run did. | + +The reasons are: + +- `the case is invalid` +- `the run did not finish`, such as a case that ran longer than `--timeout` +- `the case is written in flow style or uses a YAML anchor, alias, or merge key`, since a rewrite could change another part of the file. A flow-style `expect` or list inside a block-style case is rewritten. +- `the expect could not be rewritten in place` + +The report and the exit status are those of the rewritten cases. A rewritten case passes unless an assertion that stays as written fails. + +A test file edited while its cases ran is not written. The other test files still run and the report ends as usual. Then an error goes to stderr, `Error: changed while its cases ran, so its expects were not updated`, with the file's absolute path, and the command exits 1, or 2 when a case or file is invalid. An interrupt leaves the test file whose cases were running as it was. + +## 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, `case directory ` with `--keep`, and, with `--update`, the [update outcome](#updating-expectations). +- Under an invalid case or file: one `