From aacc29482c55b94554be58b93779ee6bbb0d6bc7 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 12:43:14 -0500 Subject: [PATCH 01/10] =?UTF-8?q?harness.layout=20=C2=B7=20docproc=20?= =?UTF-8?q?=C2=B7=20slice=201:=20upgrade=20marathon=200.25.0=20and=20htmd?= =?UTF-8?q?=200.7.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Taken through mise run upgrade. The root mise pin for marathon moves 0.24.1 -> 0.25.0; tools/mail takes htmd 0.7.0, whose two new converter options are opt-in, so nothing adapts. MimeKit 5, MsgKit 3.1.0, and typed-path 0.13.0 stay held in their tools' HOLDS; currency reports only those. The marathon pin is a development toolchain pin outside the base module's contract, so the root CHANGELOG takes no entry (as with the 0.24.1 bump); tools/mail's CHANGELOG records htmd under Unreleased. --- mise.toml | 2 +- tools/mail/CHANGELOG.md | 5 +++++ tools/mail/Cargo.lock | 4 ++-- tools/mail/Cargo.toml | 2 +- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/mise.toml b/mise.toml index e6285e2e..5d5fd010 100644 --- a/mise.toml +++ b/mise.toml @@ -6,7 +6,7 @@ task.run_auto_install = false [tools] "aqua:google/go-containerregistry" = "0.22.1" -"github:standards-lab/claude-plugins" = { version = "0.24.1", version_prefix = "marathon/v" } +"github:standards-lab/claude-plugins" = { version = "0.25.0", version_prefix = "marathon/v" } "github:ip7z/7zip" = "26.06" actionlint = "1.7.12" go = "1.27.4" diff --git a/tools/mail/CHANGELOG.md b/tools/mail/CHANGELOG.md index afd07732..bf6f05cd 100644 --- a/tools/mail/CHANGELOG.md +++ b/tools/mail/CHANGELOG.md @@ -9,6 +9,11 @@ output contract: a change to them is a change here. This changelog covers docpro ## [Unreleased] +### Changed + +- The crate graph takes htmd 0.7.0 in place of 0.6.1. Its new converter options are opt-in, and the + output is unchanged. + ## [v0.2.0] - 2026-11-25 ### Added diff --git a/tools/mail/Cargo.lock b/tools/mail/Cargo.lock index 6a1499c7..d0249d3f 100644 --- a/tools/mail/Cargo.lock +++ b/tools/mail/Cargo.lock @@ -228,9 +228,9 @@ dependencies = [ [[package]] name = "htmd" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87a0116aaabbc2eeaf9b9abd7c88d48acce50c2183fab149880d20f0911cfb39" +checksum = "d70f7abdc99b25529b315f3502e1f169307baa670c606ef1a4fe28967e0ce2bd" dependencies = [ "ego-tree", "html5ever", diff --git a/tools/mail/Cargo.toml b/tools/mail/Cargo.toml index 7308de84..a27eabdc 100644 --- a/tools/mail/Cargo.toml +++ b/tools/mail/Cargo.toml @@ -17,7 +17,7 @@ serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" # Pinned exactly: the CLI works around its panics on short or oversized input (src/rtf.rs). compressed-rtf = "=1.0.1" -htmd = "0.6.0" +htmd = "0.7.0" pulldown-cmark = { version = "0.13.6", default-features = false } cfb = "0.16.0" mail-parser = { version = "1.0.1", features = ["full_encoding"] } From d74518836b1c1f698aa6bb711b2c6144936cfe3d Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 12:50:01 -0500 Subject: [PATCH 02/10] =?UTF-8?q?harness.layout=20=C2=B7=20docproc=20?= =?UTF-8?q?=C2=B7=20slice=202:=20the=20agent=20area=20and=20the=20check's?= =?UTF-8?q?=20steps?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The check runs four step scripts under scripts/check/ directly: the Go gates per module with GOWORK=off, sqlint over the postgres module (with GOWORK=off), each tool's check and notices, then the lints last (shellcheck over *.sh and the extensionless file tasks, actionlint, the tag-routing test, lint-context, lint-references), every lint running before the step fails. The agent profile: mise.agent.toml includes mise-tasks and .agent/mise-tasks, .claude/settings.json sets MISE_ENV=agent, and the agent tasks check:go, check:sqlint, check:tools, check:lints, test, vet, and lint wrap the step scripts. Without MISE_ENV a person sees check, currency, upgrade, build, fmt, tidy, integration, integration:postgres, integration:storage, and test:integration. Multi-line tasks are file tasks; integration is mise-tasks/integration/_default beside its postgres and storage members. The integration tasks' exit traps are functions, since shellcheck now reads them. build is one line, cmd/docproc into the git-ignored bin/. .gitignore lists .agent/state/ in place of .claude/briefs/. CI's go job runs go.sh and sqlint.sh, its lints job (renamed from lint) lints.sh; no job sets MISE_ENV. The tools, go, and integration path filters add mise-tasks/**, .agent/mise-tasks/**, and (tools and go) scripts/check/**. No step writes go.work.sum: every Go step already ran with GOWORK=off, and neither check nor build reproduced the file. --- .agent/mise-tasks/check/go | 5 ++ .agent/mise-tasks/check/lints | 5 ++ .agent/mise-tasks/check/sqlint | 5 ++ .agent/mise-tasks/check/tools | 5 ++ .agent/mise-tasks/lint | 5 ++ .agent/mise-tasks/test | 5 ++ .agent/mise-tasks/vet | 5 ++ .claude/settings.json | 3 + .github/workflows/ci.yml | 26 ++++--- .gitignore | 2 +- STANDARDS.md | 2 + docs/ci.md | 41 +++++----- docs/development.md | 69 ++++++++++------- mise-tasks/check | 11 +++ mise-tasks/integration/_default | 6 ++ mise-tasks/integration/postgres | 13 ++++ mise-tasks/integration/storage | 13 ++++ mise-tasks/test/integration | 23 ++++++ mise-tasks/tidy | 8 ++ mise.agent.toml | 4 + mise.toml | 129 +++----------------------------- scripts/check/go.sh | 28 +++++++ scripts/check/lints.sh | 24 ++++++ scripts/check/sqlint.sh | 10 +++ scripts/check/tools.sh | 17 +++++ 25 files changed, 285 insertions(+), 179 deletions(-) create mode 100755 .agent/mise-tasks/check/go create mode 100755 .agent/mise-tasks/check/lints create mode 100755 .agent/mise-tasks/check/sqlint create mode 100755 .agent/mise-tasks/check/tools create mode 100755 .agent/mise-tasks/lint create mode 100755 .agent/mise-tasks/test create mode 100755 .agent/mise-tasks/vet create mode 100755 mise-tasks/check create mode 100755 mise-tasks/integration/_default create mode 100755 mise-tasks/integration/postgres create mode 100755 mise-tasks/integration/storage create mode 100755 mise-tasks/test/integration create mode 100755 mise-tasks/tidy create mode 100644 mise.agent.toml create mode 100755 scripts/check/go.sh create mode 100755 scripts/check/lints.sh create mode 100755 scripts/check/sqlint.sh create mode 100755 scripts/check/tools.sh diff --git a/.agent/mise-tasks/check/go b/.agent/mise-tasks/check/go new file mode 100755 index 00000000..e1eedb4b --- /dev/null +++ b/.agent/mise-tasks/check/go @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Run the check's Go step, every gate in every module; gate names as arguments run only those" +# Runs scripts/check/go.sh, one step of the check. +set -euo pipefail +exec scripts/check/go.sh "$@" diff --git a/.agent/mise-tasks/check/lints b/.agent/mise-tasks/check/lints new file mode 100755 index 00000000..e7db978e --- /dev/null +++ b/.agent/mise-tasks/check/lints @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Run the check's lints step, shellcheck, actionlint, the tag-routing test, lint-context, and lint-references at the root" +# Runs scripts/check/lints.sh, one step of the check. +set -euo pipefail +exec scripts/check/lints.sh "$@" diff --git a/.agent/mise-tasks/check/sqlint b/.agent/mise-tasks/check/sqlint new file mode 100755 index 00000000..e8ef6b1d --- /dev/null +++ b/.agent/mise-tasks/check/sqlint @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Run the check's sqlint step over the postgres module's statements and migrations" +# Runs scripts/check/sqlint.sh, one step of the check. +set -euo pipefail +exec scripts/check/sqlint.sh "$@" diff --git a/.agent/mise-tasks/check/tools b/.agent/mise-tasks/check/tools new file mode 100755 index 00000000..ead9538b --- /dev/null +++ b/.agent/mise-tasks/check/tools @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Run the check's tools step, each tool's check and its third-party notices" +# Runs scripts/check/tools.sh, one step of the check. +set -euo pipefail +exec scripts/check/tools.sh "$@" diff --git a/.agent/mise-tasks/lint b/.agent/mise-tasks/lint new file mode 100755 index 00000000..bf97d5a6 --- /dev/null +++ b/.agent/mise-tasks/lint @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Run the check's lint gate, golangci-lint, in every module" +# Runs the lint gate of scripts/check/go.sh. +set -euo pipefail +exec scripts/check/go.sh lint diff --git a/.agent/mise-tasks/test b/.agent/mise-tasks/test new file mode 100755 index 00000000..5b4c3be6 --- /dev/null +++ b/.agent/mise-tasks/test @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Run the check's test gate, go test with the race detector, in every module" +# Runs the test gate of scripts/check/go.sh. +set -euo pipefail +exec scripts/check/go.sh test diff --git a/.agent/mise-tasks/vet b/.agent/mise-tasks/vet new file mode 100755 index 00000000..daf78eca --- /dev/null +++ b/.agent/mise-tasks/vet @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Run the check's vet gate, go vet, in every module" +# Runs the vet gate of scripts/check/go.sh. +set -euo pipefail +exec scripts/check/go.sh vet diff --git a/.claude/settings.json b/.claude/settings.json index a2a41acd..cee6c556 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,5 +1,8 @@ { "plansDirectory": "./.claude/plans", + "env": { + "MISE_ENV": "agent" + }, "permissions": { "allow": [ "Bash(mise run:*)", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 566f301d..e40e09ec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,4 @@ -# CI: each system tool's check, the Go modules' check:go, the lint, and the providers' live tiers. +# CI: the check's steps, each tool's check, and the providers' live tiers. # See docs/ci.md name: CI @@ -37,7 +37,7 @@ jobs: with: filters: | ooxml: - - &shared ['.github/workflows/ci.yml', 'mise.toml', 'tools/*.sh', 'tools/envelope/cases.json'] + - &shared ['.github/workflows/ci.yml', 'mise.toml', 'mise-tasks/**', '.agent/mise-tasks/**', 'scripts/check/**', 'tools/*.sh', 'tools/envelope/cases.json'] - 'tools/ooxml/**' mail: - *shared @@ -62,6 +62,9 @@ jobs: - '**/sqlint.toml' - '.github/workflows/ci.yml' - 'mise.toml' + - 'mise-tasks/**' + - '.agent/mise-tasks/**' + - 'scripts/check/**' - 'tools/envelope/cases.json' - 'tools/mail/tests/golden/**' - 'tools/onenote/tests/golden/**' @@ -85,8 +88,10 @@ jobs: - 'compose/**' - '.github/workflows/ci.yml' - 'mise.toml' + - 'mise-tasks/**' + - '.agent/mise-tasks/**' - lint: + lints: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v7.0.1 @@ -95,11 +100,11 @@ jobs: with: install_args: actionlint shellcheck github:standards-lab/claude-plugins - - name: mise run lint - run: mise run lint + - name: The lints step + run: scripts/check/lints.sh go: - name: check:go (${{ matrix.runner }}) + name: go (${{ matrix.runner }}) needs: changes if: needs.changes.outputs.go == 'true' strategy: @@ -122,8 +127,11 @@ jobs: key: go-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }} restore-keys: go-${{ runner.os }}-${{ runner.arch }}- - - name: mise run check:go - run: mise run check:go + - name: The Go step + run: scripts/check/go.sh + + - name: The sqlint step + run: scripts/check/sqlint.sh tool: name: check (${{ matrix.tool }}, ${{ matrix.runner }}) @@ -245,7 +253,7 @@ jobs: ci: if: always() - needs: [changes, lint, go, tool, integration] + needs: [changes, lints, go, tool, integration] runs-on: ubuntu-24.04 steps: - name: Fail if a needed job failed or was cancelled diff --git a/.gitignore b/.gitignore index 44f89603..6cbecf2c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ .claude/plans/ -.claude/briefs/ +.agent/state/ mise.local.toml bin/ diff --git a/STANDARDS.md b/STANDARDS.md index 628eb8bd..82b3a3c1 100644 --- a/STANDARDS.md +++ b/STANDARDS.md @@ -32,6 +32,8 @@ the tools part to the system tools under `tools/`. - `architecture/principles/context-architecture.md`: the `docs/` pages, the tool contract on `docs/tool-contract.md`, and the configuration's reasoning on `docs/development.md`, `docs/ci.md`, and `docs/tool-builds.md`. +- `architecture/principles/agent-separation.md`: the agent area in `.agent/`, the agent profile in + `mise.agent.toml`, and `MISE_ENV=agent` in the Claude settings' `env`. - `architecture/principles/comments.md`: each `.golangci.yml` enables nolintlint with `require-explanation` and `require-specific`. - `architecture/standards/go-elemental/principles/dependencies.md`: the base, `storage`, diff --git a/docs/ci.md b/docs/ci.md index 79711876..125ae147 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -10,17 +10,18 @@ through mise-action or a task's auto-install. ## CI CI runs on every pull request into main, every push to main, and on demand. A newer run on the -same ref cancels the one it supersedes. +same ref cancels the one it supersedes. Its jobs run the check's step scripts under +`scripts/check/` directly, never the agent's tasks. - **changes** decides which of the tool, go, and integration jobs run, through one paths filter each. - **tool**: each system tool's check runs once per runner, natively on x64 and arm64, followed by its third-party notices, but only when the tool's directory or the wiring every tool shares changed. -- **go**: the root's `check:go` on both runners, only when what the Go modules build or read - changed. -- **lint**: the root's `lint`, shellcheck and actionlint, the release workflow's tag-routing test, - and lint-context and lint-references, on every run, since a lint reads the whole tree. +- **go**: the check's Go and sqlint steps on both runners, only when what the Go modules build or + read changed. +- **lints**: the check's lints step, shellcheck and actionlint, the release workflow's tag-routing + test, and lint-context and lint-references, on every run, since a lint reads the whole tree. - **integration**: the provider modules' live tiers against the compose harness, on a push to main when what they build or run against changed and on demand, never on a pull request. - **memory-floor** measures docproc-ooxml's memory floor on both runners, on demand alone @@ -31,33 +32,33 @@ same ref cancels the one it supersedes. ### The paths filters -The tools filter has one filter per tool, named as its directory under `tools/`, so the filters -that match are the matrix's tools. Each begins with the wiring every tool shares, anchored on the -first: the CI workflow, the root mise.toml its check loads, and `tools/`'s scripts and envelope -table. A Rust tool's adds the Rust tools' shared files, anchored on the first Rust tool: the shared -envelope crate's directory, which each Rust tool's check tests against its own lock, and the -standard library's and musl's notices every Rust tool's notices end with. So a change to either -runs every Rust tool, and no .NET one. +The tools filter has one filter per tool, named as its directory under `tools/`, so the filters that +match are the matrix's tools. Each begins with the wiring every tool shares, anchored on the first: +the CI workflow, the root mise.toml its check loads, the root's tasks and step scripts, and +`tools/`'s scripts and envelope table. A Rust tool's adds the Rust tools' shared files, anchored on +the first Rust tool: the shared envelope crate's directory, which each Rust tool's check tests +against its own lock, and the standard library's and musl's notices every Rust tool's notices end +with. So a change to either runs every Rust tool, and no .NET one. The go filter is what the Go modules build or read: their sources, go.mod and go.sum files (the storage, postgres, and cmd/docproc modules', and `tools/go.mod`, the boundary that keeps the tools out of the base module, among them), any testdata, each module's lint config, the postgres module's -SQL and the `sqlint.toml` check:go lints it under, the CI workflow, and the root mise.toml check:go -runs from; and, in the tools' trees, only what the Go tests read in place: the shared envelope cases -and each tool's committed goldens and expected outputs. A change to a tool's code alone doesn't run -it. +SQL and the `sqlint.toml` the sqlint step lints it under, the CI workflow, the root mise.toml the +steps run under, and the root's tasks and step scripts; and, in the tools' trees, only what the Go +tests read in place: the shared envelope cases and each tool's committed goldens and expected +outputs. A change to a tool's code alone doesn't run it. The integration filter is what the provider modules' live tiers build or run against: the storage and postgres modules' sources, go.mod and go.sum, testdata, and the postgres module's SQL, never their docs; each requires the base module at its released version, not this tree's, so a change to -the base alone doesn't run them. Then the compose harness, the CI workflow, and the root mise.toml -that defines the integration tasks and the harness's environment. +the base alone doesn't run them. Then the compose harness, the CI workflow, the root mise.toml that +sets the harness's environment, and the root's tasks, which define the integration tasks. ### The jobs' toolchains and caches -- The lint job needs only the root's shellcheck, actionlint, and marathon pin, which provides +- The lints job needs only the root's shellcheck, actionlint, and marathon pin, which provides lint-context and lint-references, not its Go toolchain; the routing test needs bash alone. -- `check:go` needs only the root's Go toolchain and golangci-lint. Its cache holds the modules +- The go job needs only the root's Go toolchain and golangci-lint. Its cache holds the modules go.sum pins, as downloaded, and the build cache; both are keyed on go.sum, the build cache being only a speedup the go command checks entry by entry. - A tool's job: NativeAOT links with clang against zlib, so a .NET tool (a `.slnx`) alone needs diff --git a/docs/development.md b/docs/development.md index d0e256b2..2e598ccc 100644 --- a/docs/development.md +++ b/docs/development.md @@ -4,12 +4,12 @@ The toolchain, Go, golangci-lint, actionlint, shellcheck, jq, marathon's lint-co lint-references, and the integration tier's 7zz, is pinned in [`mise.toml`](../mise.toml); each tool under `tools/` pins its own. Tasks run from the repository root, `mise run `: -- `check`: shellchecks the scripts, lints the workflows, tests the release workflow's tag - routing, and runs lint-context and lint-references; builds, vets, format-checks, fixes, tidies, - tests under the race detector, and lints every Go module, the base, both providers, and - cmd/docproc, each with the workspace off, then sqlints the postgres module's SQL; then runs each - tool's check. It is the unit tier: each package over its own testdata and a stand-in tool, the - readers replaying the tools' committed goldens in place. It reads no network and runs no real +- `check`: builds, vets, format-checks, fixes, tidies, tests under the race detector, and lints + every Go module, the base, both providers, and cmd/docproc, each with the workspace off, then + sqlints the postgres module's SQL; then runs each tool's check; then shellchecks the scripts and + file tasks, lints the workflows, tests the release workflow's tag routing, and runs lint-context + and lint-references. It is the unit tier: each package over its own testdata and a stand-in tool, + the readers replaying the tools' committed goldens in place. It reads no network and runs no real tool but util-linux's `prlimit`, which the memory-bound tests need on PATH. - `test:integration`: the integration tier, under the `integration` build tag. It builds docproc-ooxml, docproc-mail, and docproc-onenote from this checkout through their publish tasks @@ -29,6 +29,8 @@ tool under `tools/` pins its own. Tasks run from the repository root, `mise run `integration:storage` the storage module's against its SeaweedFS. Each starts only its own service, runs its module's suite, and stops the service whether the suite passes or fails, printing its log on a failure. +- `build`: builds cmd/docproc into the git-ignored `bin/`. `fmt` formats the Go source, and `tidy` + tidies every Go module. - `currency` and `upgrade`: report, then bump, every root pin behind its latest: the root mise pins, each Go module's go directive, direct requirements, and tool modules, the workflows' action pins, the compose image pins, and the image pins in the Go source, then each tool's. A pin the root @@ -50,8 +52,8 @@ installs it either. Its environment: -- `GO_MODULES`: the Go module directories, each with its own go.mod, which `check:go` checks in - turn, kept in sync with go.work's use list: the base module, +- `GO_MODULES`: the Go module directories, each with its own go.mod, which the check's Go step + checks in turn, kept in sync with go.work's use list: the base module, `github.com/standards-lab/docproc`, at the root, then the storage and postgres provider modules and the cmd/docproc command module, which require it. - `TOOLS`: the system tools under `tools/`, each with its own mise.toml that pins its toolchain and @@ -64,23 +66,32 @@ Its environment: - `DOCPROC_DSN`, `DOCPROC_S3_ENDPOINT`, `DOCPROC_S3_ACCESS_KEY`, and `DOCPROC_S3_SECRET_KEY`: the live tiers' servers, below. -Its tasks: - -- `check` is the one check: read-only and deterministic, stopping at the first failing part. It runs - the lint, then `check:go`, then each tool's check, so CI's lint, Go, and tool jobs run its three - parts apart. After each tool's check it writes the notices a release would pack for this - machine to nowhere, so a package the notices script can't give a notice for fails there, not at - the tag. -- `check:go` builds, tests, and lints each module in `GO_MODULES` under the `.golangci.yml` - nearest it, outside any go.work, so each resolves its own pins as a consumer does; then it runs - sqlint over the postgres module's statements and migrations. sqlint is the postgres module's - tool, and resolves the engine `sqlint.toml` names through the module's own requirements. -- `lint`: shellcheck, actionlint, the tag-routing test, then lint-context and lint-references, - each run before the task fails if any failed. A lint missing from PATH fails the task with +Its one-line tasks stay in it; each multi-line task is a file task under +[`mise-tasks/`](../mise-tasks). The agent's tasks are file tasks under `.agent/mise-tasks/`, which +only `MISE_ENV=agent` loads, through [`mise.agent.toml`](../mise.agent.toml); the Claude settings +set it. Its tasks: + +- `check` is the one check: read-only and deterministic. It runs the step scripts under + [`scripts/check/`](../scripts/check) in turn: the Go step, the sqlint step, the tools step, then + the lints step. The first three stop the check at their first failure; CI's go and tool jobs + run them apart, and its lints job the last. +- The Go step, `scripts/check/go.sh`, builds, tests, and lints each module in `GO_MODULES` under + the `.golangci.yml` nearest it, outside any go.work, so each resolves its own pins as a consumer + does. +- The sqlint step, `scripts/check/sqlint.sh`, runs sqlint over the postgres module's statements + and migrations. sqlint is the postgres module's tool, and resolves the engine `sqlint.toml` + names through the module's own requirements, outside any go.work. +- The tools step, `scripts/check/tools.sh`, runs each tool's check, then writes the notices a + release would pack for this machine to nowhere, so a package the notices script can't give a + notice for fails there, not at the tag. +- The lints step, `scripts/check/lints.sh`: shellcheck over the shell scripts and the file tasks, + actionlint, the tag-routing test, then lint-context and lint-references, each run before the + step fails if any failed. A lint missing from PATH fails the step with `FAIL: is not on PATH; run mise install`. actionlint shellchecks each workflow's `run:` blocks too, with the shellcheck pinned in mise.toml. The release workflow's tag routing is a - script, so its test runs here, beside the workflow it routes. CI's lint job runs this task; the - check runs it first. + script, so its test runs here, beside the workflow it routes. +- The agent's tasks run the steps one at a time: `check:go`, `check:sqlint`, `check:tools`, and + `check:lints`, and the Go step's gates `test`, `vet`, and `lint` alone. - `test:integration`: each docproc tool is built from this checkout through its own publish task, and the three binaries alone are linked into a directory put ahead of everything else on PATH. Packages run in parallel, as the unit tier's do: each container test watches only the containers @@ -184,12 +195,12 @@ hold the module to its own requirements. tests add go-core's graphtest, which imports testing and so stays out of the module's own packages. -[`postgres/sqlint.toml`](../postgres/sqlint.toml) holds the postgres module's SQL conventions, -run by `check:go` from that directory. The engine names the native forms a standard-tier file may -not use, and the sources name the pattern catalogs the statements' includes resolve against: -sqlate's own. The base module holds no SQL. The index's statements are named for their operation, -the delimiter kept out of comments and literals, and no native form in a standard-tier file; a -native file is exempt by its tier and carries its port note. The migrations role has no +[`postgres/sqlint.toml`](../postgres/sqlint.toml) holds the postgres module's SQL conventions, run +by the check's sqlint step from that directory. The engine names the native forms a standard-tier +file may not use, and the sources name the pattern catalogs the statements' includes resolve +against: sqlate's own. The base module holds no SQL. The index's statements are named for their +operation, the delimiter kept out of comments and literals, and no native form in a standard-tier +file; a native file is exempt by its tier and carries its port note. The migrations role has no native-forms check; the DDL is PostgreSQL's, the only engine's. ## The compose harness diff --git a/mise-tasks/check b/mise-tasks/check new file mode 100755 index 00000000..c55cb50d --- /dev/null +++ b/mise-tasks/check @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +#MISE description="Build, vet, format, fix, tidy, test, and lint every Go module, then sqlint the postgres module's SQL, then run each tool's check and write its third-party notices to nowhere, then shellcheck the scripts and file tasks, lint the workflows, test the tag routing, and run lint-context and lint-references, running the step scripts under scripts/check/; writes nothing outside the tools' build output" +# The check, as CI runs it: the Go, sqlint, and tools steps stop the check at their first failure; +# the lints step then runs every lint, and the check fails if any fails. +# See architecture/standards/go-elemental/principles/release-and-ci.md +set -eu +scripts/check/go.sh +scripts/check/sqlint.sh +scripts/check/tools.sh +scripts/check/lints.sh +echo "check: ok" diff --git a/mise-tasks/integration/_default b/mise-tasks/integration/_default new file mode 100755 index 00000000..d47aa2bb --- /dev/null +++ b/mise-tasks/integration/_default @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +#MISE description="Run the postgres and storage modules' integration suites, each against a fresh compose service" +rc=0 +mise -C "$MISE_PROJECT_ROOT" run integration:postgres || rc=1 +mise -C "$MISE_PROJECT_ROOT" run integration:storage || rc=1 +exit $rc diff --git a/mise-tasks/integration/postgres b/mise-tasks/integration/postgres new file mode 100755 index 00000000..a33c799a --- /dev/null +++ b/mise-tasks/integration/postgres @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +#MISE description="Run the postgres module's integration suite against a fresh compose PostgreSQL" +set -e +export GOWORK=off +stop() { + rc=$? + [ "$rc" -eq 0 ] || docker compose logs postgres + docker compose down postgres + exit "$rc" +} +trap stop EXIT +docker compose up -d --wait --build postgres +(cd postgres && go test -race -tags integration -count=1 -v ./...) diff --git a/mise-tasks/integration/storage b/mise-tasks/integration/storage new file mode 100755 index 00000000..8cbfcda6 --- /dev/null +++ b/mise-tasks/integration/storage @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +#MISE description="Run the storage module's integration suite against a fresh compose SeaweedFS" +set -e +export GOWORK=off +stop() { + rc=$? + [ "$rc" -eq 0 ] || docker compose logs seaweedfs + docker compose down seaweedfs + exit "$rc" +} +trap stop EXIT +docker compose up -d --wait --build seaweedfs +(cd storage && go test -race -tags integration -count=1 -v ./...) diff --git a/mise-tasks/test/integration b/mise-tasks/test/integration new file mode 100755 index 00000000..c5e45c91 --- /dev/null +++ b/mise-tasks/test/integration @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +#MISE description="Build the three docproc tools from this checkout, put them first on PATH, and run every Go module's integration tier, cmd/docproc's over the built docproc, the provider modules' against the compose harness; writes only the tools' build output and temporary directories" +set -eu +export GOWORK=off +bin=$(mktemp -d) +trap 'rm -rf "$bin"' EXIT +for tool in $TOOLS; do + echo "test:integration: building tools/$tool" + mise -C "$MISE_PROJECT_ROOT/tools/$tool" run publish + ln -s "$MISE_PROJECT_ROOT/tools/$tool/.state/publish/docproc-$tool" "$bin/docproc-$tool" +done +export PATH="$bin:$PATH" +for tool in $TOOLS; do + echo "test:integration: $(command -v "docproc-$tool"): $("docproc-$tool" --version | head -n 1)" +done +echo "test:integration: $(command -v 7zz)" +rc=0 +echo "test:integration: ." +(cd "$MISE_PROJECT_ROOT" && go test -tags integration ./...) || rc=1 +echo "test:integration: cmd/docproc" +(cd "$MISE_PROJECT_ROOT/cmd/docproc" && go test -tags integration -count=1 ./integration/) || rc=1 +mise -C "$MISE_PROJECT_ROOT" run integration || rc=1 +exit $rc diff --git a/mise-tasks/tidy b/mise-tasks/tidy new file mode 100755 index 00000000..441544b4 --- /dev/null +++ b/mise-tasks/tidy @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +#MISE description="Run go mod tidy in every Go module" +set -eu +export GOWORK=off +for mod in $GO_MODULES; do + echo "tidy: $mod" + (cd "$mod" && go mod tidy) +done diff --git a/mise.agent.toml b/mise.agent.toml new file mode 100644 index 00000000..e174a166 --- /dev/null +++ b/mise.agent.toml @@ -0,0 +1,4 @@ +# The agent profile, read only where MISE_ENV=agent is set: it adds the agent tasks. +# See architecture/principles/agent-separation.md +[task_config] +includes = ["mise-tasks", ".agent/mise-tasks"] diff --git a/mise.toml b/mise.toml index 5d5fd010..252ddb01 100644 --- a/mise.toml +++ b/mise.toml @@ -24,126 +24,6 @@ TOOLS = "ooxml mail onenote" HOLDS = ''' ''' -[tasks.check] -description = "Lint the scripts and workflows, test the tag routing, and run lint-context and lint-references; check every Go module; then run each tool's check and write its third-party notices to nowhere; writes nothing outside the tools' build output" -run = ''' -set -eu -mise -C "$MISE_PROJECT_ROOT" run lint -mise -C "$MISE_PROJECT_ROOT" run check:go -case "$(uname -m)" in - x86_64) rid=linux-x64 ;; - aarch64) rid=linux-arm64 ;; - *) echo "check: no runtime identifier for $(uname -m)"; exit 1 ;; -esac -for tool in $TOOLS; do - echo "check: tools/$tool" - mise -C "$MISE_PROJECT_ROOT/tools/$tool" run check - "$MISE_PROJECT_ROOT/tools/notices.sh" "$tool" "$rid" >/dev/null -done -echo "check: ok" -''' - -[tasks."check:go"] -description = "Build, vet, format, fix, tidy, test, and lint every Go module, then sqlint the postgres module's SQL; writes nothing" -run = ''' -set -eu -export GOWORK=off -for mod in $GO_MODULES; do - echo "check: $mod" - cd "$MISE_PROJECT_ROOT/$mod" - go build ./... - go vet ./... - unformatted=$(gofmt -l .) - if [ -n "$unformatted" ]; then echo "gofmt: unformatted files:"; echo "$unformatted"; exit 1; fi - go fix -diff ./... - go mod tidy -diff - go test -race ./... - golangci-lint run ./... -done -echo "check: sqlint" -cd "$MISE_PROJECT_ROOT/postgres" -go tool sqlint . -''' - -[tasks.lint] -description = "Shellcheck every committed shell script, lint the GitHub Actions workflows with actionlint, test the release workflow's tag routing, then run lint-context and lint-references, running every one before failing if any failed; reads no network, writes only a temporary tree" -dir = "{{config_root}}" -run = ''' -set -u -fail=0 -run_lint() { - if ! command -v "$1" >/dev/null; then - echo "FAIL: $1 is not on PATH; run mise install" >&2 - fail=1 - elif ! "$@"; then - fail=1 - fi -} -run_lint shellcheck $(git ls-files '*.sh') -run_lint actionlint -scripts/release-tag-test.sh || fail=1 -run_lint lint-context -run_lint lint-references -exit "$fail" -''' - -[tasks."test:integration"] -description = "Build the three docproc tools from this checkout, put them first on PATH, and run every Go module's integration tier, cmd/docproc's over the built docproc, the provider modules' against the compose harness; writes only the tools' build output and temporary directories" -run = ''' -set -eu -export GOWORK=off -bin=$(mktemp -d) -trap 'rm -rf "$bin"' EXIT -for tool in $TOOLS; do - echo "test:integration: building tools/$tool" - mise -C "$MISE_PROJECT_ROOT/tools/$tool" run publish - ln -s "$MISE_PROJECT_ROOT/tools/$tool/.state/publish/docproc-$tool" "$bin/docproc-$tool" -done -export PATH="$bin:$PATH" -for tool in $TOOLS; do - echo "test:integration: $(command -v "docproc-$tool"): $("docproc-$tool" --version | head -n 1)" -done -echo "test:integration: $(command -v 7zz)" -rc=0 -echo "test:integration: ." -(cd "$MISE_PROJECT_ROOT" && go test -tags integration ./...) || rc=1 -echo "test:integration: cmd/docproc" -(cd "$MISE_PROJECT_ROOT/cmd/docproc" && go test -tags integration -count=1 ./integration/) || rc=1 -mise -C "$MISE_PROJECT_ROOT" run integration || rc=1 -exit $rc -''' - -[tasks."integration:postgres"] -description = "Run the postgres module's integration suite against a fresh compose PostgreSQL" -dir = "{{config_root}}" -env = { GOWORK = "off" } -run = ''' -set -e -trap 'rc=$?; [ $rc -eq 0 ] || docker compose logs postgres; docker compose down postgres; exit $rc' EXIT -docker compose up -d --wait --build postgres -(cd postgres && go test -race -tags integration -count=1 -v ./...) -''' - -[tasks."integration:storage"] -description = "Run the storage module's integration suite against a fresh compose SeaweedFS" -dir = "{{config_root}}" -env = { GOWORK = "off" } -run = ''' -set -e -trap 'rc=$?; [ $rc -eq 0 ] || docker compose logs seaweedfs; docker compose down seaweedfs; exit $rc' EXIT -docker compose up -d --wait --build seaweedfs -(cd storage && go test -race -tags integration -count=1 -v ./...) -''' - -[tasks.integration] -description = "Run the postgres and storage modules' integration suites, each against a fresh compose service" -run = ''' -rc=0 -mise -C "$MISE_PROJECT_ROOT" run integration:postgres || rc=1 -mise -C "$MISE_PROJECT_ROOT" run integration:storage || rc=1 -exit $rc -''' - [tasks.currency] description = "Report every requirement, tool, action pin, compose image pin, and Go source image pin behind its latest, and each tool's own currency; writes nothing outside the tools' obj/" run = "scripts/currency.sh report" @@ -151,3 +31,12 @@ run = "scripts/currency.sh report" [tasks.upgrade] description = "Bump the root mise pins, each Go module's go directive, direct requirements, and tool modules, each workflow action pin, each compose image pin, and each Go source image pin, tag and digest, to their latest, but a held one, then run each tool's upgrade; rewrites mise.toml, go.mod, go.sum, the workflows, the compose Dockerfiles, the Go files holding an image pin, and the tools' pins and lock files" run = "scripts/currency.sh upgrade" + +[tasks.fmt] +description = "Format all Go source" +run = "gofmt -w ." + +[tasks.build] +description = "Build the docproc command into the git-ignored bin/" +dir = "{{config_root}}/cmd/docproc" +run = "go build -o ../../bin/ ./..." diff --git a/scripts/check/go.sh b/scripts/check/go.sh new file mode 100755 index 00000000..e35a1447 --- /dev/null +++ b/scripts/check/go.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# The check's Go step: in each module of $GO_MODULES, with GOWORK=off, the gates in order (build, +# vet, gofmt, fix, tidy, test, lint), stopping at the first that fails; no gate writes. Gate names +# given as arguments run only those gates, in the order given. +# See architecture/standards/go-elemental/principles/release-and-ci.md +set -eu +root=$(cd "$(dirname "$0")/../.." && pwd) +export GOWORK=off +gates=${*:-build vet gofmt fix tidy test lint} +for mod in $GO_MODULES; do + echo "check: $mod" + cd "$root/$mod" + for gate in $gates; do + case $gate in + build) go build ./... ;; + vet) go vet ./... ;; + gofmt) + unformatted=$(gofmt -l .) + if [ -n "$unformatted" ]; then echo "gofmt: unformatted files:"; echo "$unformatted"; exit 1; fi + ;; + fix) go fix -diff ./... ;; + tidy) go mod tidy -diff ;; + test) go test -race ./... ;; + lint) golangci-lint run ./... ;; + *) echo "FAIL: no Go gate named $gate" >&2; exit 2 ;; + esac + done +done diff --git a/scripts/check/lints.sh b/scripts/check/lints.sh new file mode 100755 index 00000000..a9067286 --- /dev/null +++ b/scripts/check/lints.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# The check's lints step, at the repository root: shellcheck over every committed shell script and +# file task, actionlint over the workflows, the release workflow's tag-routing test, then +# lint-context and lint-references. Every lint runs even when one fails, and the step fails if any +# does; a lint missing from PATH fails it too. +# See architecture/standards/go-elemental/principles/release-and-ci.md +set -u +cd "$(dirname "$0")/../.." || exit +fail=0 +run_lint() { + if ! command -v "$1" >/dev/null; then + echo "FAIL: $1 is not on PATH; run mise install" >&2 + fail=1 + elif ! "$@"; then + fail=1 + fi +} +mapfile -t scripts < <(git ls-files '*.sh' mise-tasks .agent/mise-tasks) +run_lint shellcheck "${scripts[@]}" +run_lint actionlint +scripts/release-tag-test.sh || fail=1 +run_lint lint-context +run_lint lint-references +exit "$fail" diff --git a/scripts/check/sqlint.sh b/scripts/check/sqlint.sh new file mode 100755 index 00000000..1db24615 --- /dev/null +++ b/scripts/check/sqlint.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# The check's sqlint step: the postgres module's tool, sqlint, holds its statements and migrations +# to postgres/sqlint.toml, with GOWORK=off, so it resolves the engine through the module's own +# requirements; it writes nothing. +# See docs/development.md +set -eu +cd "$(dirname "$0")/../../postgres" +export GOWORK=off +echo "check: sqlint" +go tool sqlint . diff --git a/scripts/check/tools.sh b/scripts/check/tools.sh new file mode 100755 index 00000000..861a9a77 --- /dev/null +++ b/scripts/check/tools.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# The check's tools step: for each tool of $TOOLS, its own check under its mise.toml, then the +# third-party notices a release would pack for this machine, written to nowhere, stopping at the +# first that fails. It writes only the tools' build output. +# See docs/tool-builds.md +set -eu +root=$(cd "$(dirname "$0")/../.." && pwd) +case "$(uname -m)" in + x86_64) rid=linux-x64 ;; + aarch64) rid=linux-arm64 ;; + *) echo "check: no runtime identifier for $(uname -m)"; exit 1 ;; +esac +for tool in $TOOLS; do + echo "check: tools/$tool" + mise -C "$root/tools/$tool" run check + "$root/tools/notices.sh" "$tool" "$rid" >/dev/null +done From b7f5addc27aba80d0219f03cd82db01350a35983 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 12:55:26 -0500 Subject: [PATCH 03/10] =?UTF-8?q?harness.layout=20=C2=B7=20docproc=20?= =?UTF-8?q?=C2=B7=20slice=203:=20the=20system=20tools'=20tasks=20as=20file?= =?UTF-8?q?=20tasks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each tool's multi-line tasks are file tasks in its own mise-tasks/, under the same names: mail's check, publish, golden, currency, and upgrade; onenote's check, publish, and golden; ooxml's check, publish, currency, golden, and upgrade, which is mise-tasks/upgrade/_default beside the still hidden upgrade:packages. One-line tasks stay inline: mail's mboxrd, onenote's currency and upgrade, ooxml's fixtures. A file task runs in its config root, the tool's directory, as the inline tasks' dir did; each starts set -euo pipefail. tools/envelope has no mise configuration. mail's mise.fixtures.toml is gone: the generator's .NET pin, its env, and its fixtures and tnef tasks (file tasks) live in tools/mail/generator's own mise.toml and mise-tasks/, so mail's check and CI, run from tools/mail, never load .NET. mail's currency and upgrade run the generator's dotnet through mise exec in generator/, and upgrade reads the SDK pin from generator/mise.toml. tools/currency.sh reads the mise tools of the tool's mise.toml and of each subdirectory's mise.toml in place of every mise..toml, naming a pin by its path under the tool (generator/mise.toml), so upgrade rewrites it there. The lints step's shellcheck covers tools/*/mise-tasks/*, the generator's included. The docs and mail's README name generator/mise.toml in place of MISE_ENV=fixtures. --- docs/development.md | 8 +- docs/tool-builds.md | 25 ++-- scripts/check/lints.sh | 2 +- tools/currency.sh | 35 +++--- tools/mail/README.md | 11 +- tools/mail/generator/mise-tasks/fixtures | 5 + tools/mail/generator/mise-tasks/tnef | 5 + tools/mail/generator/mise.toml | 8 ++ tools/mail/mise-tasks/check | 12 ++ tools/mail/mise-tasks/currency | 23 ++++ tools/mail/mise-tasks/golden | 6 + tools/mail/mise-tasks/publish | 9 ++ tools/mail/mise-tasks/upgrade | 30 +++++ tools/mail/mise.fixtures.toml | 26 ---- tools/mail/mise.toml | 99 +-------------- tools/onenote/mise-tasks/check | 11 ++ tools/onenote/mise-tasks/golden | 6 + tools/onenote/mise-tasks/publish | 9 ++ tools/onenote/mise.toml | 40 +----- tools/ooxml/mise-tasks/check | 15 +++ tools/ooxml/mise-tasks/currency | 38 ++++++ tools/ooxml/mise-tasks/golden | 29 +++++ tools/ooxml/mise-tasks/publish | 13 ++ tools/ooxml/mise-tasks/upgrade/_default | 11 ++ tools/ooxml/mise-tasks/upgrade/packages | 21 ++++ tools/ooxml/mise.toml | 153 +---------------------- 26 files changed, 295 insertions(+), 355 deletions(-) create mode 100755 tools/mail/generator/mise-tasks/fixtures create mode 100755 tools/mail/generator/mise-tasks/tnef create mode 100644 tools/mail/generator/mise.toml create mode 100755 tools/mail/mise-tasks/check create mode 100755 tools/mail/mise-tasks/currency create mode 100755 tools/mail/mise-tasks/golden create mode 100755 tools/mail/mise-tasks/publish create mode 100755 tools/mail/mise-tasks/upgrade delete mode 100644 tools/mail/mise.fixtures.toml create mode 100755 tools/onenote/mise-tasks/check create mode 100755 tools/onenote/mise-tasks/golden create mode 100755 tools/onenote/mise-tasks/publish create mode 100755 tools/ooxml/mise-tasks/check create mode 100755 tools/ooxml/mise-tasks/currency create mode 100755 tools/ooxml/mise-tasks/golden create mode 100755 tools/ooxml/mise-tasks/publish create mode 100755 tools/ooxml/mise-tasks/upgrade/_default create mode 100755 tools/ooxml/mise-tasks/upgrade/packages diff --git a/docs/development.md b/docs/development.md index 2e598ccc..28dea407 100644 --- a/docs/development.md +++ b/docs/development.md @@ -56,8 +56,8 @@ Its environment: checks in turn, kept in sync with go.work's use list: the base module, `github.com/standards-lab/docproc`, at the root, then the storage and postgres provider modules and the cmd/docproc command module, which require it. -- `TOOLS`: the system tools under `tools/`, each with its own mise.toml that pins its toolchain and - defines its `check`, `currency`, and `upgrade` tasks, which the root's tasks run in turn: +- `TOOLS`: the system tools under `tools/`, each with its own mise.toml that pins its toolchain, + and its own `check`, `currency`, and `upgrade` tasks, which the root's tasks run in turn: docproc-ooxml (.NET), and docproc-mail and docproc-onenote (Rust). - `HOLDS`: the root's held pins, which currency reports as held and upgrade never moves: one line each, ` : `, the item named as currency names it (a Go module by its path, the @@ -85,8 +85,8 @@ set it. Its tasks: release would pack for this machine to nowhere, so a package the notices script can't give a notice for fails there, not at the tag. - The lints step, `scripts/check/lints.sh`: shellcheck over the shell scripts and the file tasks, - actionlint, the tag-routing test, then lint-context and lint-references, each run before the - step fails if any failed. A lint missing from PATH fails the step with + the tools' among them, actionlint, the tag-routing test, then lint-context and lint-references, + each run before the step fails if any failed. A lint missing from PATH fails the step with `FAIL: is not on PATH; run mise install`. actionlint shellchecks each workflow's `run:` blocks too, with the shellcheck pinned in mise.toml. The release workflow's tag routing is a script, so its test runs here, beside the workflow it routes. diff --git a/docs/tool-builds.md b/docs/tool-builds.md index ad74ab3c..74b8e82d 100644 --- a/docs/tool-builds.md +++ b/docs/tool-builds.md @@ -1,7 +1,8 @@ # The tools' builds Each system tool under `tools/` has its own mise.toml, which pins its toolchain alone and defines -its tasks; each README's "Building and testing" states what the tasks do. docproc's root check, +its one-line tasks; each multi-line task is a file task under the tool's own `mise-tasks/`. Each +README's "Building and testing" states what the tasks do. docproc's root check, currency, and upgrade run each tool's tasks through the root's `TOOLS` list (`mise -C tools/ run check`), and `tools/pack.sh` runs `publish` to build the release binary it packs; the release workflow runs that on each runner, natively ([CI and releases](ci.md)). Each @@ -151,8 +152,9 @@ only a newer release of a crate can clear. Run it, review the diff, and run each mise's `CARGO_HOME` ahead of a host cargo on PATH; mise's `RUSTUP_TOOLCHAIN` picks the toolchain. Each call is a new mise process, so after the upgrade has rewritten the mise files it runs the toolchain just pinned. -- **The mise tools.** Every environment's mise file is loaded, so `mise..toml`'s tools, such - as docproc-mail's fixture generator's SDK, are read with `mise.toml`'s; the root's are its own. +- **The mise tools.** The tool's mise.toml is read, and each of its subdirectories' mise.toml, so + docproc-mail's fixture generator's SDK, in `generator/mise.toml`, is read with the tool's; the + root's are its own. The upgrade rewrites each in place, its version alone, as `mise use` would write rust's table as a bare version. A backend-qualified name, such as `github:EmbarkStudios/cargo-about`, is a quoted key holding a `/`, so the name is matched with its quotes optional and its regex @@ -205,17 +207,18 @@ only a newer release of a crate can clear. Run it, review the diff, and run each ### docproc-mail -- The fixture generator's toolchain is in `mise.fixtures.toml`, loaded only with - `MISE_ENV=fixtures`, so neither the check nor CI installs .NET: `MISE_ENV=fixtures mise run - fixtures` regenerates `tests/fixtures/generated/` from its `.eml` and item sources. The check - never runs it; it reads the committed outputs. The fixtures task runs from `generator/`, so its - `global.json` pins the SDK, with the pinned SDK's directory first on PATH. -- Currency reports the mise tools, `mise.fixtures.toml`'s among them; the fixture generator's +- The fixture generator's toolchain and its `fixtures` and `tnef` tasks are in its own + `generator/mise.toml`. mise reads configuration only from the working directory and its + parents, so neither the check nor CI, run from the tool's directory, installs .NET: `mise -C + generator run fixtures` regenerates `tests/fixtures/generated/` from its `.eml` and item + sources. The check never runs it; it reads the committed outputs. The fixtures task runs from + `generator/`, so its `global.json` pins the SDK, with the pinned SDK's directory first on PATH. +- Currency reports the mise tools, `generator/mise.toml`'s among them; the fixture generator's packages are this tool's own: its NuGet packages with a newer release, run from `generator/` so its `global.json` picks the SDK. A held one is reported, with the hold's reason, and leaves the exit status alone. -- Upgrade moves every mise tool, here and in `mise.fixtures.toml`, and every crate, then the - fixture generator's: the SDK's pin in `global.json`, the one `mise.fixtures.toml` pins, and its +- Upgrade moves every mise tool, here and in `generator/mise.toml`, and every crate, then the + fixture generator's: the SDK's pin in `global.json`, the one `generator/mise.toml` pins, and its packages, each but a held one, each pinned exactly in `Generator.csproj`: each with a newer release is pinned at it in place, then the lock file rewritten from the project and checked in locked mode, as the fixtures task restores it. Each runs in a new mise process, with the SDK just diff --git a/scripts/check/lints.sh b/scripts/check/lints.sh index a9067286..85d82f20 100755 --- a/scripts/check/lints.sh +++ b/scripts/check/lints.sh @@ -15,7 +15,7 @@ run_lint() { fail=1 fi } -mapfile -t scripts < <(git ls-files '*.sh' mise-tasks .agent/mise-tasks) +mapfile -t scripts < <(git ls-files '*.sh' mise-tasks .agent/mise-tasks 'tools/*/mise-tasks/*') run_lint shellcheck "${scripts[@]}" run_lint actionlint scripts/release-tag-test.sh || fail=1 diff --git a/tools/currency.sh b/tools/currency.sh index f8947d99..11dc741c 100755 --- a/tools/currency.sh +++ b/tools/currency.sh @@ -1,9 +1,10 @@ #!/usr/bin/env bash # currency reports, or upgrades, one Rust system tool's pins: its crates, direct and indirect, in # its Cargo.lock and the shared envelope's, the crates of both locked graphs with a RustSec -# advisory, and the mise tools its directory's mise files pin. A pin the tool's HOLDS list names is reported as held and never moved. report prints each -# line prefixed with the tool's directory and exits 1 when it reports any pin that isn't held. Each -# Rust tool's currency and upgrade tasks run it by the tool's name. +# advisory, and the mise tools its mise.toml and its subdirectories' pin. A pin the tool's HOLDS +# list names is reported as held and never moved. report prints each line prefixed with the tool's +# directory and exits 1 when it reports any pin that isn't held. Each Rust tool's currency and +# upgrade tasks run it by the tool's name. # # usage: tools/currency.sh # format the Rust tool's directory under tools/, such as mail @@ -41,27 +42,23 @@ escape_regex() { sed 's/[][\\.*^$|+?(){}]/\\&/g' <<<"$1" } -mise_envs() { +mise_configs() { local file - for file in "$tool"/mise.*.toml; do - if [ ! -e "$file" ]; then - continue - fi - file=${file##*/mise.} - file=${file%.toml} - if [ "$file" != local ]; then - echo "$file" + for file in "$tool"/mise.toml "$tool"/*/mise.toml; do + if [ -e "$file" ]; then + dirname "$file" fi - done | paste -sd, - + done } outdated_mise_tools() { - local envs - envs=$(mise_envs) || return - MISE_ENV=$envs mise -C "$tool" outdated --bump --json | - jq -r --arg dir "$dir" 'to_entries[] | - select(.value.bump != null and (.value.source.path | startswith($dir + "/mise."))) | - "\(.value.source.path | split("/") | last) \(.key) \(.value.requested) \(.value.bump)"' + local config scanned + while read -r config; do + scanned=$(mise -C "$config" outdated --bump --json) || return + jq -r --arg config "$PWD/$config/mise." --arg dir "$dir/" 'to_entries[] | + select(.value.bump != null and (.value.source.path | startswith($config))) | + "\(.value.source.path | ltrimstr($dir)) \(.key) \(.value.requested) \(.value.bump)"' <<<"$scanned" || return + done < <(mise_configs) } outdated_crates() { diff --git a/tools/mail/README.md b/tools/mail/README.md index 35bcf9e0..ffe535cd 100644 --- a/tools/mail/README.md +++ b/tools/mail/README.md @@ -244,9 +244,10 @@ crate, [`tools/envelope`](../envelope). The toolchain (Rust with both musl targets, jq, shellcheck, cargo-deny, cargo-about) is pinned in [`mise.toml`](mise.toml) alone, and the fixture generator's .NET SDK in -[`mise.fixtures.toml`](mise.fixtures.toml). Its tasks run from this directory, `mise run `, or -from the repository root, `mise -C tools/mail run `; docproc's own `mise run check` runs this -tool's check. The reasoning behind its configuration is on +[`generator/mise.toml`](generator/mise.toml), which the tool's own tasks never load. Its tasks run +from this directory, `mise run `, or from the repository root, `mise -C tools/mail run +`; the generator's `fixtures` and `tnef` run from `generator/`, `mise -C generator run +`. docproc's own `mise run check` runs this tool's check. The reasoning behind its configuration is on [`docs/tool-builds.md`](../../docs/tool-builds.md). - `check`: shellchecks the scripts, verifies formatting, lints with warnings as errors, and runs @@ -267,11 +268,11 @@ tool's check. The reasoning behind its configuration is on CI never runs it. - `upgrade`: bumps what `currency` reports as behind to its latest, but a held pin. Review the diff and run `check`; docproc's own `mise run upgrade` runs it. -- `fixtures`, with `MISE_ENV=fixtures`: regenerates the generated `.pst` and `.msg` fixtures and +- `fixtures`, from `generator/`: regenerates the generated `.pst` and `.msg` fixtures and their manifest from their `.eml` and item sources, on .NET 11, MimeKit held at 4.18.2. Each third-party fixture is listed with its source, license, and SHA-256 in its group's `sources.json`. -- `tnef`, with `MISE_ENV=fixtures`: rewrites the TNEF group's `.eml` (`tests/fixtures/tnef/`), +- `tnef`, from `generator/`: rewrites the TNEF group's `.eml` (`tests/fixtures/tnef/`), each wrapping one of Apache POI's TNEF streams as its `winmail.dat` part, as its `layout.json` lists them, and its `truth.json`, what MimeKit's `TnefPart` reads of each stream, which the tests compare the tool's reading with. diff --git a/tools/mail/generator/mise-tasks/fixtures b/tools/mail/generator/mise-tasks/fixtures new file mode 100755 index 00000000..09fbc301 --- /dev/null +++ b/tools/mail/generator/mise-tasks/fixtures @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Regenerate the generated .pst and .msg fixtures and their manifest from the .eml and item sources, reporting any drift from the committed ones; the check never runs it" +set -euo pipefail +export PATH="$DOTNET_ROOT:$PATH" +dotnet run -c Release -- fixtures ../tests/fixtures/generated diff --git a/tools/mail/generator/mise-tasks/tnef b/tools/mail/generator/mise-tasks/tnef new file mode 100755 index 00000000..466d1296 --- /dev/null +++ b/tools/mail/generator/mise-tasks/tnef @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +#MISE description="Rewrite the TNEF group's .eml, each wrapping one of its TNEF streams, and its truth.json, what MimeKit's TnefPart reads of each, from its layout.json; the check never runs it" +set -euo pipefail +export PATH="$DOTNET_ROOT:$PATH" +dotnet run -c Release -- tnef ../tests/fixtures/tnef diff --git a/tools/mail/generator/mise.toml b/tools/mail/generator/mise.toml new file mode 100644 index 00000000..b0cbc42e --- /dev/null +++ b/tools/mail/generator/mise.toml @@ -0,0 +1,8 @@ +# docproc-mail's fixture generator's toolchain and its fixtures and tnef tasks. +# See docs/tool-builds.md +[tools] +dotnet = "11.0.100" + +[env] +DOTNET_CLI_TELEMETRY_OPTOUT = "1" +DOTNET_NOLOGO = "1" diff --git a/tools/mail/mise-tasks/check b/tools/mail/mise-tasks/check new file mode 100755 index 00000000..119fcdb5 --- /dev/null +++ b/tools/mail/mise-tasks/check @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +#MISE description="Shellcheck the scripts, format-check, lint, and test docproc-mail and the shared envelope crate against the static musl release binary, lint the envelope on its own locked graph, then print the binary's version; writes only target/ and tools/envelope/target/" +set -euo pipefail +export PATH="$CARGO_HOME/bin:$PATH" +target="$(uname -m)-unknown-linux-musl" +git ls-files -z '*.sh' | xargs -0 -r shellcheck +cargo fmt --check +cargo fmt --check --manifest-path ../envelope/Cargo.toml +cargo clippy --all-targets --locked --target "$target" -p docproc-mail -p docproc-envelope -- -D warnings +cargo clippy --all-targets --locked --target "$target" --manifest-path ../envelope/Cargo.toml -- -D warnings +cargo test --release --locked --target "$target" -p docproc-mail -p docproc-envelope +"target/$target/release/docproc-mail" --version diff --git a/tools/mail/mise-tasks/currency b/tools/mail/mise-tasks/currency new file mode 100755 index 00000000..d41eebca --- /dev/null +++ b/tools/mail/mise-tasks/currency @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +#MISE description="Report every crate in Cargo.lock and tools/envelope/Cargo.lock behind its latest, within its requirement or beyond it, every crate with a RustSec advisory, every mise tool behind its latest, and every fixture generator package behind its latest, a held one as held; writes only generator/obj/ and cargo-deny's advisory database" +set -euo pipefail +stale=0 +../currency.sh mail report || stale=1 + +# shellcheck disable=SC2016 # $DOTNET_ROOT expands in the generator's mise environment, not this one +packages=$(cd generator && mise exec -- bash -c \ + 'export PATH="$DOTNET_ROOT:$PATH"; dotnet list package --outdated --format json' | + jq -r '.projects[] | .frameworks[]?.topLevelPackages[]? | + "\(.id) \(.requestedVersion | ltrimstr("[") | rtrimstr("]")) \(.latestVersion)"') +while read -r name pinned latest; do + [ -n "$name" ] || continue + reason=$(grep -m1 "^$name $pinned: " <<<"$HOLDS" | cut -d: -f2- | sed 's/^ //' || true) + if [ -n "$reason" ]; then + echo "tools/mail: generator/Generator.csproj: $name $pinned -> $latest held: $reason" + else + echo "tools/mail: generator/Generator.csproj: $name $pinned -> $latest" + stale=1 + fi +done <<<"$packages" + +exit "$stale" diff --git a/tools/mail/mise-tasks/golden b/tools/mail/mise-tasks/golden new file mode 100755 index 00000000..bdd5ebca --- /dev/null +++ b/tools/mail/mise-tasks/golden @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +#MISE description="Re-record the .jsonl and .stderr goldens from the static musl release binary, through the tests' UPDATE_GOLDEN; the check never runs it; writes only target/ and the goldens" +set -euo pipefail +export PATH="$CARGO_HOME/bin:$PATH" +target="$(uname -m)-unknown-linux-musl" +UPDATE_GOLDEN=1 cargo test --release --locked --target "$target" -p docproc-mail diff --git a/tools/mail/mise-tasks/publish b/tools/mail/mise-tasks/publish new file mode 100755 index 00000000..e40455e1 --- /dev/null +++ b/tools/mail/mise-tasks/publish @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +#MISE description="Build the static musl release binary for this machine from the locked crate graph; writes only target/ and .state/publish/" +set -euo pipefail +export PATH="$CARGO_HOME/bin:$PATH" +target="$(uname -m)-unknown-linux-musl" +cargo build --release --locked --target "$target" +rm -rf .state/publish +mkdir -p .state/publish +cp "target/$target/release/docproc-mail" .state/publish/ diff --git a/tools/mail/mise-tasks/upgrade b/tools/mail/mise-tasks/upgrade new file mode 100755 index 00000000..9d8c0531 --- /dev/null +++ b/tools/mail/mise-tasks/upgrade @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +#MISE description="Bump every mise tool here and in generator/mise.toml, every crate, and every fixture generator package to its latest, but a held one, rewriting the mise files, global.json, Cargo.toml, tools/envelope/Cargo.toml, Cargo.lock, tools/envelope/Cargo.lock, Generator.csproj, and its lock file in locked form" +set -euo pipefail +../currency.sh mail upgrade + +sdk=$(sed -nE 's/^dotnet = "([^"]+)"$/\1/p' generator/mise.toml) +sed -i -E "s/(\"version\": \")[^\"]+\"/\1$sdk\"/" generator/global.json + +held() { + grep -q "^$1 $2: " <<<"$HOLDS" +} +cd generator +# shellcheck disable=SC2016 # $DOTNET_ROOT expands in the generator's mise environment, not this one +mise exec -- bash -euo pipefail -c ' +export PATH="$DOTNET_ROOT:$PATH" +dotnet restore --force-evaluate >/dev/null +dotnet list package --outdated --format json | + jq -r ".projects[] | .frameworks[]?.topLevelPackages[]? | + \"\(.id) \(.requestedVersion | ltrimstr(\"[\") | rtrimstr(\"]\")) \(.latestVersion)\"" +' | while read -r name pinned latest; do + [ -n "$name" ] || continue + held "$name" "$pinned" && continue + sed -i "s/Include=\"$name\" Version=\"\\[$pinned\\]\"/Include=\"$name\" Version=\"[$latest]\"/" Generator.csproj +done +# shellcheck disable=SC2016 # $DOTNET_ROOT expands in the generator's mise environment, not this one +mise exec -- bash -euo pipefail -c ' +export PATH="$DOTNET_ROOT:$PATH" +dotnet restore --force-evaluate >/dev/null +dotnet restore --locked-mode >/dev/null +' diff --git a/tools/mail/mise.fixtures.toml b/tools/mail/mise.fixtures.toml deleted file mode 100644 index db5aeccb..00000000 --- a/tools/mail/mise.fixtures.toml +++ /dev/null @@ -1,26 +0,0 @@ -# docproc-mail's fixture generator's toolchain, loaded only with MISE_ENV=fixtures. -# See docs/tool-builds.md -[tools] -dotnet = "11.0.100" - -[env] -DOTNET_CLI_TELEMETRY_OPTOUT = "1" -DOTNET_NOLOGO = "1" - -[tasks.fixtures] -description = "Regenerate the generated .pst and .msg fixtures and their manifest from the .eml and item sources, reporting any drift from the committed ones; the check never runs it" -dir = "{{config_root}}/generator" -run = ''' -set -eu -export PATH="$DOTNET_ROOT:$PATH" -dotnet run -c Release -- fixtures ../tests/fixtures/generated -''' - -[tasks.tnef] -description = "Rewrite the TNEF group's .eml, each wrapping one of its TNEF streams, and its truth.json, what MimeKit's TnefPart reads of each, from its layout.json; the check never runs it" -dir = "{{config_root}}/generator" -run = ''' -set -eu -export PATH="$DOTNET_ROOT:$PATH" -dotnet run -c Release -- tnef ../tests/fixtures/tnef -''' diff --git a/tools/mail/mise.toml b/tools/mail/mise.toml index 4c051d41..5f6ef640 100644 --- a/tools/mail/mise.toml +++ b/tools/mail/mise.toml @@ -1,4 +1,4 @@ -# docproc-mail's toolchain and its check, publish, golden, mboxrd, currency, and upgrade tasks. +# docproc-mail's toolchain and its one-line tasks; mise-tasks/ holds the others. # See docs/tool-builds.md [tools] cargo-deny = "0.22.2" @@ -13,104 +13,7 @@ MimeKit 4.18.2: PstBuilder.Eml 1.3.0, its latest, is built on MimeKit 4 MsgKit 3.0.6: MsgKit 3.1.0 needs MimeKit.Core 5, and PstBuilder.Eml 1.3.0 is built on MimeKit 4 ''' -[tasks.check] -description = "Shellcheck the scripts, format-check, lint, and test docproc-mail and the shared envelope crate against the static musl release binary, lint the envelope on its own locked graph, then print the binary's version; writes only target/ and tools/envelope/target/" -dir = "{{config_root}}" -run = ''' -set -eu -export PATH="$CARGO_HOME/bin:$PATH" -target="$(uname -m)-unknown-linux-musl" -git ls-files -z '*.sh' | xargs -0 -r shellcheck -cargo fmt --check -cargo fmt --check --manifest-path ../envelope/Cargo.toml -cargo clippy --all-targets --locked --target "$target" -p docproc-mail -p docproc-envelope -- -D warnings -cargo clippy --all-targets --locked --target "$target" --manifest-path ../envelope/Cargo.toml -- -D warnings -cargo test --release --locked --target "$target" -p docproc-mail -p docproc-envelope -"target/$target/release/docproc-mail" --version -''' - -[tasks.publish] -description = "Build the static musl release binary for this machine from the locked crate graph; writes only target/ and .state/publish/" -dir = "{{config_root}}" -run = ''' -set -eu -export PATH="$CARGO_HOME/bin:$PATH" -target="$(uname -m)-unknown-linux-musl" -cargo build --release --locked --target "$target" -rm -rf .state/publish -mkdir -p .state/publish -cp "target/$target/release/docproc-mail" .state/publish/ -''' - -[tasks.golden] -description = "Re-record the .jsonl and .stderr goldens from the static musl release binary, through the tests' UPDATE_GOLDEN; the check never runs it; writes only target/ and the goldens" -dir = "{{config_root}}" -run = ''' -set -eu -export PATH="$CARGO_HOME/bin:$PATH" -target="$(uname -m)-unknown-linux-musl" -UPDATE_GOLDEN=1 cargo test --release --locked --target "$target" -p docproc-mail -''' - [tasks.mboxrd] description = "Write the MIME group's mboxrd, tests/fixtures/mime/nine.mboxrd, from its nine .eml; the check rebuilds it and compares it byte for byte" dir = "{{config_root}}" run = "scripts/mboxrd.sh" - -[tasks.currency] -description = "Report every crate in Cargo.lock and tools/envelope/Cargo.lock behind its latest, within its requirement or beyond it, every crate with a RustSec advisory, every mise tool behind its latest, and every fixture generator package behind its latest, a held one as held; writes only generator/obj/ and cargo-deny's advisory database" -dir = "{{config_root}}" -run = ''' -set -euo pipefail -stale=0 -../currency.sh mail report || stale=1 - -packages=$(cd generator && MISE_ENV=fixtures mise exec -- bash -c \ - 'export PATH="$DOTNET_ROOT:$PATH"; dotnet list package --outdated --format json' | - jq -r '.projects[] | .frameworks[]?.topLevelPackages[]? | - "\(.id) \(.requestedVersion | ltrimstr("[") | rtrimstr("]")) \(.latestVersion)"') -while read -r name pinned latest; do - [ -n "$name" ] || continue - reason=$(grep -m1 "^$name $pinned: " <<<"$HOLDS" | cut -d: -f2- | sed 's/^ //' || true) - if [ -n "$reason" ]; then - echo "tools/mail: generator/Generator.csproj: $name $pinned -> $latest held: $reason" - else - echo "tools/mail: generator/Generator.csproj: $name $pinned -> $latest" - stale=1 - fi -done <<<"$packages" - -exit "$stale" -''' - -[tasks.upgrade] -description = "Bump every mise tool here and in mise.fixtures.toml, every crate, and every fixture generator package to its latest, but a held one, rewriting the mise files, global.json, Cargo.toml, tools/envelope/Cargo.toml, Cargo.lock, tools/envelope/Cargo.lock, Generator.csproj, and its lock file in locked form" -dir = "{{config_root}}" -run = ''' -set -euo pipefail -../currency.sh mail upgrade - -sdk=$(sed -nE 's/^dotnet = "([^"]+)"$/\1/p' mise.fixtures.toml) -sed -i -E "s/(\"version\": \")[^\"]+\"/\1$sdk\"/" generator/global.json - -held() { - grep -q "^$1 $2: " <<<"$HOLDS" -} -cd generator -MISE_ENV=fixtures mise exec -- bash -euo pipefail -c ' -export PATH="$DOTNET_ROOT:$PATH" -dotnet restore --force-evaluate >/dev/null -dotnet list package --outdated --format json | - jq -r ".projects[] | .frameworks[]?.topLevelPackages[]? | - \"\(.id) \(.requestedVersion | ltrimstr(\"[\") | rtrimstr(\"]\")) \(.latestVersion)\"" -' | while read -r name pinned latest; do - [ -n "$name" ] || continue - held "$name" "$pinned" && continue - sed -i "s/Include=\"$name\" Version=\"\\[$pinned\\]\"/Include=\"$name\" Version=\"[$latest]\"/" Generator.csproj -done -MISE_ENV=fixtures mise exec -- bash -euo pipefail -c ' -export PATH="$DOTNET_ROOT:$PATH" -dotnet restore --force-evaluate >/dev/null -dotnet restore --locked-mode >/dev/null -' -''' diff --git a/tools/onenote/mise-tasks/check b/tools/onenote/mise-tasks/check new file mode 100755 index 00000000..09898109 --- /dev/null +++ b/tools/onenote/mise-tasks/check @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +#MISE description="Format-check, lint, and test docproc-onenote and the shared envelope crate against the static musl release binary, lint the envelope on its own locked graph, then print the binary's version; writes only target/ and tools/envelope/target/" +set -euo pipefail +export PATH="$CARGO_HOME/bin:$PATH" +target="$(uname -m)-unknown-linux-musl" +cargo fmt --check +cargo fmt --check --manifest-path ../envelope/Cargo.toml +cargo clippy --all-targets --locked --target "$target" -p docproc-onenote -p docproc-envelope -- -D warnings +cargo clippy --all-targets --locked --target "$target" --manifest-path ../envelope/Cargo.toml -- -D warnings +cargo test --release --locked --target "$target" -p docproc-onenote -p docproc-envelope +"target/$target/release/docproc-onenote" --version diff --git a/tools/onenote/mise-tasks/golden b/tools/onenote/mise-tasks/golden new file mode 100755 index 00000000..e5192055 --- /dev/null +++ b/tools/onenote/mise-tasks/golden @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +#MISE description="Re-record the .jsonl and .stderr goldens from the static musl release binary, through the tests' UPDATE_GOLDEN; the check never runs it; writes only target/ and the goldens" +set -euo pipefail +export PATH="$CARGO_HOME/bin:$PATH" +target="$(uname -m)-unknown-linux-musl" +UPDATE_GOLDEN=1 cargo test --release --locked --target "$target" -p docproc-onenote diff --git a/tools/onenote/mise-tasks/publish b/tools/onenote/mise-tasks/publish new file mode 100755 index 00000000..4586ef1f --- /dev/null +++ b/tools/onenote/mise-tasks/publish @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +#MISE description="Build the static musl release binary for this machine from the locked crate graph; writes only target/ and .state/publish/" +set -euo pipefail +export PATH="$CARGO_HOME/bin:$PATH" +target="$(uname -m)-unknown-linux-musl" +cargo build --release --locked --target "$target" +rm -rf .state/publish +mkdir -p .state/publish +cp "target/$target/release/docproc-onenote" .state/publish/ diff --git a/tools/onenote/mise.toml b/tools/onenote/mise.toml index 576836ec..d660be2c 100644 --- a/tools/onenote/mise.toml +++ b/tools/onenote/mise.toml @@ -1,4 +1,4 @@ -# docproc-onenote's toolchain and its check, publish, golden, currency, and upgrade tasks. +# docproc-onenote's toolchain and its one-line tasks; mise-tasks/ holds the others. # See docs/tool-builds.md [tools] cargo-deny = "0.22.2" @@ -12,44 +12,6 @@ HOLDS = ''' typed-path 0.12.4: onenote_parser 2.1.0 requires ^0.12.3; it moves only with onenote_parser ''' -[tasks.check] -description = "Format-check, lint, and test docproc-onenote and the shared envelope crate against the static musl release binary, lint the envelope on its own locked graph, then print the binary's version; writes only target/ and tools/envelope/target/" -dir = "{{config_root}}" -run = ''' -set -eu -export PATH="$CARGO_HOME/bin:$PATH" -target="$(uname -m)-unknown-linux-musl" -cargo fmt --check -cargo fmt --check --manifest-path ../envelope/Cargo.toml -cargo clippy --all-targets --locked --target "$target" -p docproc-onenote -p docproc-envelope -- -D warnings -cargo clippy --all-targets --locked --target "$target" --manifest-path ../envelope/Cargo.toml -- -D warnings -cargo test --release --locked --target "$target" -p docproc-onenote -p docproc-envelope -"target/$target/release/docproc-onenote" --version -''' - -[tasks.publish] -description = "Build the static musl release binary for this machine from the locked crate graph; writes only target/ and .state/publish/" -dir = "{{config_root}}" -run = ''' -set -eu -export PATH="$CARGO_HOME/bin:$PATH" -target="$(uname -m)-unknown-linux-musl" -cargo build --release --locked --target "$target" -rm -rf .state/publish -mkdir -p .state/publish -cp "target/$target/release/docproc-onenote" .state/publish/ -''' - -[tasks.golden] -description = "Re-record the .jsonl and .stderr goldens from the static musl release binary, through the tests' UPDATE_GOLDEN; the check never runs it; writes only target/ and the goldens" -dir = "{{config_root}}" -run = ''' -set -eu -export PATH="$CARGO_HOME/bin:$PATH" -target="$(uname -m)-unknown-linux-musl" -UPDATE_GOLDEN=1 cargo test --release --locked --target "$target" -p docproc-onenote -''' - [tasks.currency] description = "Report every crate in Cargo.lock and tools/envelope/Cargo.lock behind its latest, within its requirement or beyond it, every crate with a RustSec advisory, and every mise tool behind its latest, a held one as held; writes only cargo-deny's advisory database" dir = "{{config_root}}" diff --git a/tools/ooxml/mise-tasks/check b/tools/ooxml/mise-tasks/check new file mode 100755 index 00000000..ef234c97 --- /dev/null +++ b/tools/ooxml/mise-tasks/check @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +#MISE description="Restore the locked package graph, format, build, publish the CLI with NativeAOT, and test, the CLI tests on the published binary, all warnings as errors; writes only bin/, obj/, and .state/" +set -euo pipefail +export PATH="$DOTNET_ROOT:$PATH" +case "$(uname -m)" in + x86_64) rid=linux-x64 ;; + aarch64) rid=linux-arm64 ;; + *) echo "check: no runtime identifier for $(uname -m)"; exit 1 ;; +esac +dotnet restore DocprocOoxml.slnx --locked-mode +dotnet format DocprocOoxml.slnx --verify-no-changes --no-restore +dotnet build DocprocOoxml.slnx --no-restore -warnaserror +dotnet publish src/Docproc.Ooxml --no-restore -c Release -r "$rid" -warnaserror -o .state/aot +dotnet test --solution DocprocOoxml.slnx --no-build +.state/aot/docproc-ooxml --version diff --git a/tools/ooxml/mise-tasks/currency b/tools/ooxml/mise-tasks/currency new file mode 100755 index 00000000..e3c145ab --- /dev/null +++ b/tools/ooxml/mise-tasks/currency @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +#MISE description="Report every NuGet package behind its latest or with a known vulnerability, every fixture generator package and mise tool behind its latest; writes only obj/" +set -euo pipefail +export PATH="$DOTNET_ROOT:$PATH" +stale=0 +report() { + echo "tools/ooxml: $1" + stale=1 +} +dotnet restore DocprocOoxml.slnx --locked-mode >/dev/null + +packages=$(dotnet list DocprocOoxml.slnx package --outdated --format json | + jq -r '.projects[] | .path as $p | .frameworks[]?.topLevelPackages[]? | + "\($p | split("/") | last): \(.id) \(.requestedVersion) -> \(.latestVersion)"') +while read -r line; do + [ -n "$line" ] && report "$line" +done <<<"$packages" + +vulnerable=$(dotnet list DocprocOoxml.slnx package --vulnerable --include-transitive --format json | + jq -r '.projects[] | .path as $p | .frameworks[]? | (.topLevelPackages[]?, .transitivePackages[]?) | + select(.vulnerabilities) | .id as $id | .resolvedVersion as $v | .vulnerabilities[] | + "\($p | split("/") | last): \($id) \($v) vulnerable (\(.severity)): \(.advisoryurl)"') +while read -r line; do + [ -n "$line" ] && report "$line" +done <<<"$vulnerable" + +generator=$(uv tree -q --script fixtures/generate.py --outdated --depth 0 --locked | sed -n '/(latest: /p') +while read -r line; do + [ -n "$line" ] && report "fixtures/generate.py: $line" +done <<<"$generator" + +outdated=$(mise outdated --bump --local --json | + jq -r 'to_entries[] | "mise.toml: \(.key) \(.value.requested) -> \(.value.bump)"') +while read -r line; do + [ -n "$line" ] && report "$line" +done <<<"$outdated" + +exit "$stale" diff --git a/tools/ooxml/mise-tasks/golden b/tools/ooxml/mise-tasks/golden new file mode 100755 index 00000000..74089ed3 --- /dev/null +++ b/tools/ooxml/mise-tasks/golden @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +#MISE description="Publish the CLI with NativeAOT and re-record each fixture's .jsonl and .stderr golden, and a refused fixture's .exit, from it; the check never runs it; writes only bin/, obj/, .state/, and the goldens" +set -euo pipefail +export PATH="$DOTNET_ROOT:$PATH" +case "$(uname -m)" in + x86_64) rid=linux-x64 ;; + aarch64) rid=linux-arm64 ;; + *) echo "golden: no runtime identifier for $(uname -m)"; exit 1 ;; +esac +dotnet restore DocprocOoxml.slnx --locked-mode +dotnet publish src/Docproc.Ooxml --no-restore -c Release -r "$rid" -warnaserror -o .state/aot +golden=test/Docproc.Ooxml.Tests/Expected +rm -rf "$golden" +for fixture in fixtures/generated/*/* fixtures/realworld/*/*; do + case "$fixture" in + *.docx | *.xlsx | *.pptx | *.doc) ;; + *) continue ;; + esac + stem="$golden/${fixture#fixtures/}" + stem="${stem%.*}" + mkdir -p "$(dirname "$stem")" + status=0 + .state/aot/docproc-ooxml "$fixture" >"$stem.jsonl" 2>"$stem.stderr" || status=$? + if [ "$status" -ne 0 ]; then + echo "$status" >"$stem.exit" + echo "golden: $fixture exited $status" + fi +done +echo "golden: $(find "$golden" -name '*.jsonl' | wc -l) fixtures recorded" diff --git a/tools/ooxml/mise-tasks/publish b/tools/ooxml/mise-tasks/publish new file mode 100755 index 00000000..7786953d --- /dev/null +++ b/tools/ooxml/mise-tasks/publish @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +#MISE description="Publish the release binary for this machine's runtime identifier from the locked package graph, its version the csproj's alone; writes only bin/, obj/, and .state/publish/" +set -euo pipefail +export PATH="$DOTNET_ROOT:$PATH" +case "$(uname -m)" in + x86_64) rid=linux-x64 ;; + aarch64) rid=linux-arm64 ;; + *) echo "publish: no runtime identifier for $(uname -m)"; exit 1 ;; +esac +dotnet restore DocprocOoxml.slnx --locked-mode +rm -rf .state/publish +dotnet publish src/Docproc.Ooxml --no-restore -c Release -r "$rid" -warnaserror \ + -p:IncludeSourceRevisionInInformationalVersion=false -o .state/publish diff --git a/tools/ooxml/mise-tasks/upgrade/_default b/tools/ooxml/mise-tasks/upgrade/_default new file mode 100755 index 00000000..1aee3b00 --- /dev/null +++ b/tools/ooxml/mise-tasks/upgrade/_default @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +#MISE description="Bump every mise tool in this file, every direct NuGet package, and every fixture generator package to its latest, rewriting mise.toml, the csproj files, the lock files in locked form, generate.py, and its lock" +set -euo pipefail +config=$(realpath mise.toml) +tools=$(mise outdated --bump --no-global --json | + jq -r --arg config "$config" 'to_entries[] | select(.value.source.path == $config and .value.bump != null) | + "\(.key)@\(.value.bump)"') +for tool in $tools; do + mise use --path mise.toml "$tool" +done +mise run upgrade:packages diff --git a/tools/ooxml/mise-tasks/upgrade/packages b/tools/ooxml/mise-tasks/upgrade/packages new file mode 100755 index 00000000..199a9e0b --- /dev/null +++ b/tools/ooxml/mise-tasks/upgrade/packages @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +#MISE description="Bump every direct NuGet package and fixture generator package to its latest, rewriting the lock files in locked form; upgrade runs it after the mise tools" +#MISE hide=true +set -euo pipefail +export PATH="$DOTNET_ROOT:$PATH" +dotnet restore DocprocOoxml.slnx --force-evaluate >/dev/null +packages=$(dotnet list DocprocOoxml.slnx package --outdated --format json | + jq -r '.projects[] | .path as $p | .frameworks[]?.topLevelPackages[]? | "\($p) \(.id) \(.latestVersion)"') +while read -r project id version; do + [ -n "$project" ] && dotnet package add "$id" --project "$project" --version "$version" --no-restore +done <<<"$packages" +dotnet restore DocprocOoxml.slnx --force-evaluate >/dev/null +dotnet restore DocprocOoxml.slnx --locked-mode >/dev/null + +generator=$(uv tree -q --script fixtures/generate.py --outdated --depth 0 --locked | + sed -n 's/^\([^ ]*\) v\([^ ]*\) (latest: v\([^)]*\))$/\1 \2 \3/p') +while read -r name pinned latest; do + [ -n "$name" ] && sed -i "1,/^# \/\/\/\$/s/\"$name==$pinned\"/\"$name==$latest\"/" fixtures/generate.py +done <<<"$generator" +uv lock -q --script fixtures/generate.py +uv lock -q --script fixtures/generate.py --check diff --git a/tools/ooxml/mise.toml b/tools/ooxml/mise.toml index fd57278d..aac6e159 100644 --- a/tools/ooxml/mise.toml +++ b/tools/ooxml/mise.toml @@ -1,4 +1,4 @@ -# docproc-ooxml's toolchain and its check, publish, currency, upgrade, fixtures, and golden tasks. +# docproc-ooxml's toolchain and its one-line tasks; mise-tasks/ holds the others. # See docs/tool-builds.md [tools] dotnet = "11.0.100" @@ -10,158 +10,7 @@ DOTNET_CLI_TELEMETRY_OPTOUT = "1" DOTNET_NOLOGO = "1" GLIBC_FLOOR = "2.34" -[tasks.check] -description = "Restore the locked package graph, format, build, publish the CLI with NativeAOT, and test, the CLI tests on the published binary, all warnings as errors; writes only bin/, obj/, and .state/" -dir = "{{config_root}}" -run = ''' -set -eu -export PATH="$DOTNET_ROOT:$PATH" -case "$(uname -m)" in - x86_64) rid=linux-x64 ;; - aarch64) rid=linux-arm64 ;; - *) echo "check: no runtime identifier for $(uname -m)"; exit 1 ;; -esac -dotnet restore DocprocOoxml.slnx --locked-mode -dotnet format DocprocOoxml.slnx --verify-no-changes --no-restore -dotnet build DocprocOoxml.slnx --no-restore -warnaserror -dotnet publish src/Docproc.Ooxml --no-restore -c Release -r "$rid" -warnaserror -o .state/aot -dotnet test --solution DocprocOoxml.slnx --no-build -.state/aot/docproc-ooxml --version -''' - -[tasks.publish] -description = "Publish the release binary for this machine's runtime identifier from the locked package graph, its version the csproj's alone; writes only bin/, obj/, and .state/publish/" -dir = "{{config_root}}" -run = ''' -set -eu -export PATH="$DOTNET_ROOT:$PATH" -case "$(uname -m)" in - x86_64) rid=linux-x64 ;; - aarch64) rid=linux-arm64 ;; - *) echo "publish: no runtime identifier for $(uname -m)"; exit 1 ;; -esac -dotnet restore DocprocOoxml.slnx --locked-mode -rm -rf .state/publish -dotnet publish src/Docproc.Ooxml --no-restore -c Release -r "$rid" -warnaserror \ - -p:IncludeSourceRevisionInInformationalVersion=false -o .state/publish -''' - -[tasks.currency] -description = "Report every NuGet package behind its latest or with a known vulnerability, every fixture generator package and mise tool behind its latest; writes only obj/" -dir = "{{config_root}}" -run = ''' -set -euo pipefail -export PATH="$DOTNET_ROOT:$PATH" -stale=0 -report() { - echo "tools/ooxml: $1" - stale=1 -} -dotnet restore DocprocOoxml.slnx --locked-mode >/dev/null - -packages=$(dotnet list DocprocOoxml.slnx package --outdated --format json | - jq -r '.projects[] | .path as $p | .frameworks[]?.topLevelPackages[]? | - "\($p | split("/") | last): \(.id) \(.requestedVersion) -> \(.latestVersion)"') -while read -r line; do - [ -n "$line" ] && report "$line" -done <<<"$packages" - -vulnerable=$(dotnet list DocprocOoxml.slnx package --vulnerable --include-transitive --format json | - jq -r '.projects[] | .path as $p | .frameworks[]? | (.topLevelPackages[]?, .transitivePackages[]?) | - select(.vulnerabilities) | .id as $id | .resolvedVersion as $v | .vulnerabilities[] | - "\($p | split("/") | last): \($id) \($v) vulnerable (\(.severity)): \(.advisoryurl)"') -while read -r line; do - [ -n "$line" ] && report "$line" -done <<<"$vulnerable" - -generator=$(uv tree -q --script fixtures/generate.py --outdated --depth 0 --locked | sed -n '/(latest: /p') -while read -r line; do - [ -n "$line" ] && report "fixtures/generate.py: $line" -done <<<"$generator" - -outdated=$(mise outdated --bump --local --json | - jq -r 'to_entries[] | "mise.toml: \(.key) \(.value.requested) -> \(.value.bump)"') -while read -r line; do - [ -n "$line" ] && report "$line" -done <<<"$outdated" - -exit "$stale" -''' - -[tasks.upgrade] -description = "Bump every mise tool in this file, every direct NuGet package, and every fixture generator package to its latest, rewriting mise.toml, the csproj files, the lock files in locked form, generate.py, and its lock" -dir = "{{config_root}}" -run = ''' -set -euo pipefail -config=$(realpath mise.toml) -tools=$(mise outdated --bump --no-global --json | - jq -r --arg config "$config" 'to_entries[] | select(.value.source.path == $config and .value.bump != null) | - "\(.key)@\(.value.bump)"') -for tool in $tools; do - mise use --path mise.toml "$tool" -done -mise run upgrade:packages -''' - -[tasks."upgrade:packages"] -description = "Bump every direct NuGet package and fixture generator package to its latest, rewriting the lock files in locked form; upgrade runs it after the mise tools" -hide = true -dir = "{{config_root}}" -run = ''' -set -euo pipefail -export PATH="$DOTNET_ROOT:$PATH" -dotnet restore DocprocOoxml.slnx --force-evaluate >/dev/null -packages=$(dotnet list DocprocOoxml.slnx package --outdated --format json | - jq -r '.projects[] | .path as $p | .frameworks[]?.topLevelPackages[]? | "\($p) \(.id) \(.latestVersion)"') -while read -r project id version; do - [ -n "$project" ] && dotnet package add "$id" --project "$project" --version "$version" --no-restore -done <<<"$packages" -dotnet restore DocprocOoxml.slnx --force-evaluate >/dev/null -dotnet restore DocprocOoxml.slnx --locked-mode >/dev/null - -generator=$(uv tree -q --script fixtures/generate.py --outdated --depth 0 --locked | - sed -n 's/^\([^ ]*\) v\([^ ]*\) (latest: v\([^)]*\))$/\1 \2 \3/p') -while read -r name pinned latest; do - [ -n "$name" ] && sed -i "1,/^# \/\/\/\$/s/\"$name==$pinned\"/\"$name==$latest\"/" fixtures/generate.py -done <<<"$generator" -uv lock -q --script fixtures/generate.py -uv lock -q --script fixtures/generate.py --check -''' - [tasks.fixtures] description = "Regenerate the generated fixtures and their ground truth; needs LibreOffice's soffice; the check never runs it" dir = "{{config_root}}" run = "uv run --script fixtures/generate.py" - -[tasks.golden] -description = "Publish the CLI with NativeAOT and re-record each fixture's .jsonl and .stderr golden, and a refused fixture's .exit, from it; the check never runs it; writes only bin/, obj/, .state/, and the goldens" -dir = "{{config_root}}" -run = ''' -set -eu -export PATH="$DOTNET_ROOT:$PATH" -case "$(uname -m)" in - x86_64) rid=linux-x64 ;; - aarch64) rid=linux-arm64 ;; - *) echo "golden: no runtime identifier for $(uname -m)"; exit 1 ;; -esac -dotnet restore DocprocOoxml.slnx --locked-mode -dotnet publish src/Docproc.Ooxml --no-restore -c Release -r "$rid" -warnaserror -o .state/aot -golden=test/Docproc.Ooxml.Tests/Expected -rm -rf "$golden" -for fixture in fixtures/generated/*/* fixtures/realworld/*/*; do - case "$fixture" in - *.docx | *.xlsx | *.pptx | *.doc) ;; - *) continue ;; - esac - stem="$golden/${fixture#fixtures/}" - stem="${stem%.*}" - mkdir -p "$(dirname "$stem")" - status=0 - .state/aot/docproc-ooxml "$fixture" >"$stem.jsonl" 2>"$stem.stderr" || status=$? - if [ "$status" -ne 0 ]; then - echo "$status" >"$stem.exit" - echo "golden: $fixture exited $status" - fi -done -echo "golden: $(find "$golden" -name '*.jsonl' | wc -l) fixtures recorded" -''' From ce4a6ed2da7802b26b93c04a6e03a38a18a8f8d2 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 13:03:09 -0500 Subject: [PATCH 04/10] =?UTF-8?q?harness.layout=20=C2=B7=20docproc=20?= =?UTF-8?q?=C2=B7=20slice=204:=20the=20stage=20adapters=20move=20module-in?= =?UTF-8?q?ternal;=20the=20Go=20media-name=20writer=20goes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The stage adapters and the failure classification move from stages into stages/internal/adapter, whose exported API the stages tests drive; stages.Build wires the stages from there, and stages/export_test.go goes. go doc ./stages declares the same identifiers before and after; only the package comment's lines on where the adapters live change. - The adapter types, configs, constructors, the three PDF tool interfaces, Versions, PartErr, and Classify are exported; textStage, sevenZipReader, and exifReader stay unexported, since nothing outside the package names them, and NewTextStage returns a dispatch.Stage. - classify's fault struct goes: Classify returns (content, reason), which the tests drove through export_test.go's wrapper. - The office and picture stages' converters are reached by a Converter method, in place of export_test.go's PictureConverter and OfficeConverter functions. - Each route's required programs move into adapter.Needs, which stages' table reads, so the identities test and Build share one list. - Error and panic messages keep their "stages:" prefix, which a host reads; the panics now name the exported Config types (DocumentConfig.QPDF). - internal/cli's unexported mediaName and its export_test.go go: the Rust envelope owns the writer. TestMediaNames keeps checking every name through ResolveMedium. Test lists for stages and internal/cli are unchanged: 112 untagged, 155 under the integration tag. No CHANGELOG entry: it covers the exported API only. --- docs/api.md | 6 +- docs/development.md | 2 +- internal/cli/cases_test.go | 3 - internal/cli/export_test.go | 3 - internal/cli/media.go | 9 --- stages/adapter_integration_test.go | 29 ++++----- stages/adapter_test.go | 6 +- stages/archive_sevenzip_integration_test.go | 10 +-- stages/archive_test.go | 6 +- stages/audio_integration_test.go | 10 +-- stages/audio_test.go | 12 ++-- stages/classify_test.go | 7 ++- stages/doc.go | 13 ++-- stages/document_test.go | 14 ++--- stages/email_test.go | 6 +- stages/export_test.go | 68 --------------------- stages/{ => internal/adapter}/adapter.go | 23 ++++++- stages/{ => internal/adapter}/archive.go | 31 ++++++---- stages/{ => internal/adapter}/audio.go | 25 +++++--- stages/{ => internal/adapter}/classify.go | 51 ++++++++-------- stages/internal/adapter/doc.go | 30 +++++++++ stages/{ => internal/adapter}/document.go | 60 +++++++++++------- stages/{ => internal/adapter}/email.go | 25 +++++--- stages/{ => internal/adapter}/office.go | 29 ++++++--- stages/{ => internal/adapter}/onenote.go | 25 +++++--- stages/{ => internal/adapter}/picture.go | 31 +++++++--- stages/{ => internal/adapter}/sevenzip.go | 18 +++--- stages/{ => internal/adapter}/tar.go | 12 ++-- stages/{ => internal/adapter}/text.go | 5 +- stages/{ => internal/adapter}/video.go | 26 +++++--- stages/{ => internal/adapter}/vision.go | 23 ++++--- stages/{ => internal/adapter}/zip.go | 8 +-- stages/office_test.go | 18 +++--- stages/onenote_test.go | 6 +- stages/picture_metadata_test.go | 16 ++--- stages/picture_test.go | 8 +-- stages/sevenzip_standin_test.go | 4 +- stages/sevenzip_test.go | 10 +-- stages/stages.go | 49 ++++++++------- stages/stages_test.go | 31 +++++----- stages/tar_test.go | 4 +- stages/text_test.go | 8 +-- stages/video_containers_integration_test.go | 8 +-- stages/video_integration_test.go | 4 +- stages/video_test.go | 12 ++-- stages/zip_test.go | 16 ++--- 46 files changed, 440 insertions(+), 380 deletions(-) delete mode 100644 internal/cli/export_test.go delete mode 100644 stages/export_test.go rename stages/{ => internal/adapter}/adapter.go (81%) rename stages/{ => internal/adapter}/archive.go (84%) rename stages/{ => internal/adapter}/audio.go (78%) rename stages/{ => internal/adapter}/classify.go (62%) create mode 100644 stages/internal/adapter/doc.go rename stages/{ => internal/adapter}/document.go (77%) rename stages/{ => internal/adapter}/email.go (88%) rename stages/{ => internal/adapter}/office.go (82%) rename stages/{ => internal/adapter}/onenote.go (80%) rename stages/{ => internal/adapter}/picture.go (62%) rename stages/{ => internal/adapter}/sevenzip.go (92%) rename stages/{ => internal/adapter}/tar.go (92%) rename stages/{ => internal/adapter}/text.go (97%) rename stages/{ => internal/adapter}/video.go (79%) rename stages/{ => internal/adapter}/vision.go (70%) rename stages/{ => internal/adapter}/zip.go (93%) diff --git a/docs/api.md b/docs/api.md index a0bc1b11..ebb63687 100644 --- a/docs/api.md +++ b/docs/api.md @@ -59,7 +59,7 @@ dispatch the walk over an input's parts, the Stage contract an imports route and inspect only, any 64-bit platform dispatch/dispatchtest the Index and Content conformance suites and the fixture stage stages Build and its Options, Routes and ParseRoutes, the stage - adapters, unexported, the failure classification, the + adapters, module-internal, the failure classification, the identities settings a run's settings as one JSON object, validated and assembled into stages.Options, dispatch.Limits, and the release and @@ -775,8 +775,8 @@ output without them and nothing clears them. `Tool.Err` stays local beside its t sniffing of an input, which is the host's record's (`rundir/schema`'s `File`). `stages` is docproc's shipped wiring, so `cmd/docproc` and Bunrei wire the same stages from the -tools a host holds. It holds the stage adapters, unexported: a stage has its tools or doesn't -exist, so no adapter has a partial mode. +tools a host holds. It holds the stage adapters, module-internal in `stages/internal/adapter`: a +stage has its tools or doesn't exist, so no adapter has a partial mode. ```go package stages diff --git a/docs/development.md b/docs/development.md index 28dea407..759fd77b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -178,7 +178,7 @@ hold the module to its own requirements. and a test helper out of the production files despite its module's. - The base module depends on nothing but the standard library (`unsafe` among it, which `waitid` in `tool/exec.go` uses) and `golang.org/x/text`'s packages, which the text stage decodes - through (`stages/text.go`), so no package imports a model client. The rule covers every Go + through (`stages/internal/adapter/text.go`), so no package imports a model client. The rule covers every Go file, tests included: they drive the API with the same imports plus the module itself. The deny entries keep the storage, postgres, and cmd/docproc modules, which require the base, out of it. - The storage module requires the standard library, docproc's base packages, whose diff --git a/internal/cli/cases_test.go b/internal/cli/cases_test.go index 4d95795b..b2695725 100644 --- a/internal/cli/cases_test.go +++ b/internal/cli/cases_test.go @@ -60,9 +60,6 @@ func TestMediaNames(t *testing.T) { } sum := sha256.Sum256(content) hash := hex.EncodeToString(sum[:]) - if got := cli.MediaName(hash, c.StoredName); got != c.Name { - t.Errorf("%q stored as %q: name %q, want %q", c.BytesHex, c.StoredName, got, c.Name) - } m, err := cli.ResolveMedium(dir, c.Name) if err != nil || m.Path != filepath.Join(dir, c.Name) || m.SHA256 != hash { t.Errorf("ResolveMedium(%q) = %+v, %v", c.Name, m, err) diff --git a/internal/cli/export_test.go b/internal/cli/export_test.go deleted file mode 100644 index 504e3ffc..00000000 --- a/internal/cli/export_test.go +++ /dev/null @@ -1,3 +0,0 @@ -package cli - -var MediaName = mediaName diff --git a/internal/cli/media.go b/internal/cli/media.go index a1b0136d..09540f03 100644 --- a/internal/cli/media.go +++ b/internal/cli/media.go @@ -2,7 +2,6 @@ package cli import ( "fmt" - "path" "path/filepath" ) @@ -47,14 +46,6 @@ func isMediaName(name string) bool { return rest == "" || rest[0] == '.' && isExtension(rest[1:]) } -func mediaName(sha256, stored string) string { - ext := path.Ext(path.Base("/" + stored)) - if ext == "" || !isExtension(ext[1:]) { - return sha256 - } - return sha256 + ext -} - func isExtension(ext string) bool { if len(ext) == 0 || len(ext) > extensionMax { return false diff --git a/stages/adapter_integration_test.go b/stages/adapter_integration_test.go index 524968f6..f91a8e46 100644 --- a/stages/adapter_integration_test.go +++ b/stages/adapter_integration_test.go @@ -30,6 +30,7 @@ import ( "github.com/standards-lab/docproc/picture" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) @@ -54,7 +55,7 @@ func builtSet(t *testing.T, opts stages.Options) stages.Set { return set } -func pdfStage(t *testing.T, prep *document.Preparer, gs *tool.Tool, opts inspect.Options) *stages.DocumentStage { +func pdfStage(t *testing.T, prep *document.Preparer, gs *tool.Tool, opts inspect.Options) *adapter.DocumentStage { t.Helper() qt, dt, it := pinned(t, document.QPDFSpec()), pinned(t, document.PDFDetachSpec()), pinned(t, document.PDFInfoSpec()) q, err := document.NewQPDF(document.Config{QPDF: qt}) @@ -69,8 +70,8 @@ func pdfStage(t *testing.T, prep *document.Preparer, gs *tool.Tool, opts inspect if err != nil { t.Fatal(err) } - s := stages.NewDocumentStage(stages.DocumentConfig{ - Preparer: prep, Version: stages.Versions(gs, qt, dt, it), Request: document.ImagesRequest{Text: true, Concurrency: 2}, + s := adapter.NewDocumentStage(adapter.DocumentConfig{ + Preparer: prep, Version: adapter.Versions(gs, qt, dt, it), Request: document.ImagesRequest{Text: true, Concurrency: 2}, QPDF: q, PDFDetach: detach, PDFInfo: info, Inspect: opts, }) return s @@ -276,7 +277,7 @@ func TestBuiltIdentities(t *testing.T) { for _, tl := range set.Tools { lines[tl.Program] = tl.Version } - for r, needs := range stages.Needs() { + for r, needs := range adapter.Needs() { row := set.Rows[slices.IndexFunc(set.Rows, func(row dispatch.Row) bool { return row.Route == r })] var want []string for _, program := range needs { @@ -770,7 +771,7 @@ func hostPictures(t *testing.T) (*picture.Converter, *tool.Tool, *tool.Tool) { return c, lo, mg } -func testOfficeStage(t *testing.T) *stages.OfficeStage { +func testOfficeStage(t *testing.T) *adapter.OfficeStage { t.Helper() tl := pinned(t, office.OfficeSpec()) pc, lo, mg := hostPictures(t) @@ -778,14 +779,14 @@ func testOfficeStage(t *testing.T) *stages.OfficeStage { if err != nil { t.Fatal(err) } - s := stages.NewOfficeStage(stages.OfficeConfig{Converter: c, Version: stages.Versions(tl, lo, mg)}) + s := adapter.NewOfficeStage(adapter.OfficeConfig{Converter: c, Version: adapter.Versions(tl, lo, mg)}) return s } -func testPictureStage(t *testing.T) *stages.PictureStage { +func testPictureStage(t *testing.T) *adapter.PictureStage { t.Helper() pc, lo, mg := hostPictures(t) - s := stages.NewPictureStage(stages.PictureConfig{Converter: pc, EXIF: hostEXIF(t, mg), Version: stages.Versions(mg, lo)}) + s := adapter.NewPictureStage(adapter.PictureConfig{Converter: pc, EXIF: hostEXIF(t, mg), Version: adapter.Versions(mg, lo)}) return s } @@ -798,31 +799,31 @@ func hostEXIF(t *testing.T, mg *tool.Tool) *picture.EXIFReader { return r } -func testVisionStage(t *testing.T) *stages.VisionStage { +func testVisionStage(t *testing.T) *adapter.VisionStage { t.Helper() mg := pinned(t, picture.MagickSpec()) - return stages.NewVisionStage(stages.VisionConfig{EXIF: hostEXIF(t, mg), Version: stages.Versions(mg)}) + return adapter.NewVisionStage(adapter.VisionConfig{EXIF: hostEXIF(t, mg), Version: adapter.Versions(mg)}) } -func testEmailStage(t *testing.T) *stages.EmailStage { +func testEmailStage(t *testing.T) *adapter.EmailStage { t.Helper() tl := pinned(t, email.MailSpec()) r, err := email.NewReader(email.Config{Mail: tl}) if err != nil { t.Fatal(err) } - s := stages.NewEmailStage(stages.EmailConfig{Reader: r, Version: stages.Versions(tl)}) + s := adapter.NewEmailStage(adapter.EmailConfig{Reader: r, Version: adapter.Versions(tl)}) return s } -func testOnenoteStage(t *testing.T) *stages.OneNoteStage { +func testOnenoteStage(t *testing.T) *adapter.OneNoteStage { t.Helper() tl := pinned(t, onenote.OneNoteSpec()) r, err := onenote.NewReader(onenote.Config{OneNote: tl}) if err != nil { t.Fatal(err) } - s := stages.NewOneNoteStage(stages.OneNoteConfig{Reader: r, Version: stages.Versions(tl)}) + s := adapter.NewOneNoteStage(adapter.OneNoteConfig{Reader: r, Version: adapter.Versions(tl)}) return s } diff --git a/stages/adapter_test.go b/stages/adapter_test.go index 98f16cc5..28658461 100644 --- a/stages/adapter_test.go +++ b/stages/adapter_test.go @@ -16,7 +16,7 @@ import ( "github.com/standards-lab/docproc/document" "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) @@ -123,9 +123,9 @@ func standinPreparer(t *testing.T, s gsSettings) *document.Preparer { return document.NewPreparer(document.Config{Renderer: g, Text: text}) } -func testDocumentStage(t *testing.T, prep *document.Preparer) *stages.DocumentStage { +func testDocumentStage(t *testing.T, prep *document.Preparer) *adapter.DocumentStage { t.Helper() - return stages.NewDocumentStage(stages.DocumentConfig{ + return adapter.NewDocumentStage(adapter.DocumentConfig{ Preparer: prep, QPDF: &fakeQPDF{}, PDFDetach: &fakeDetach{}, PDFInfo: &fakeInfo{}, Version: "gs 10.08.0", Request: document.ImagesRequest{Text: true, Concurrency: 1}, }) diff --git a/stages/archive_sevenzip_integration_test.go b/stages/archive_sevenzip_integration_test.go index 4a5d16a3..2c156b0e 100644 --- a/stages/archive_sevenzip_integration_test.go +++ b/stages/archive_sevenzip_integration_test.go @@ -16,17 +16,17 @@ import ( "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/sevenzip" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" ) -func sevenZipConfig(t *testing.T, opts inspect.Options) stages.ArchiveConfig { +func sevenZipConfig(t *testing.T, opts inspect.Options) adapter.ArchiveConfig { t.Helper() tl := pinned(t, sevenzip.SevenZipSpec()) r, err := sevenzip.NewReader(sevenzip.Config{SevenZip: tl}) if err != nil { t.Fatal(err) } - return stages.ArchiveConfig{Inspect: opts, SevenZip: r, Version: stages.Versions(tl)} + return adapter.ArchiveConfig{Inspect: opts, SevenZip: r, Version: adapter.Versions(tl)} } func sevenZipDispatcher(t *testing.T, opts inspect.Options) (*dispatch.Dispatcher, *counting, string) { @@ -170,7 +170,7 @@ func TestSevenZipUnsafe(t *testing.T) { if err := os.MkdirAll(work, 0o700); err != nil { t.Fatal(err) } - checkUnsafe(t, stages.NewArchiveStage(sevenZipConfig(t, inspect.Options{})), sevenZipFixture("generated/"+c.fixture), root, work, c.parts, c.children) + checkUnsafe(t, adapter.NewArchiveStage(sevenZipConfig(t, inspect.Options{})), sevenZipFixture("generated/"+c.fixture), root, work, c.parts, c.children) } } @@ -181,7 +181,7 @@ func TestSevenZipQuarantined(t *testing.T) { } strict := inspect.Options{Policy: map[inspect.Check]inspect.Verdict{inspect.ArchiveTraversal: inspect.Quarantine}} cfg := sevenZipConfig(t, strict) - s := stages.NewArchiveStage(cfg) + s := adapter.NewArchiveStage(cfg) index := dispatch.NewMemoryIndex(0) work := t.TempDir() d, err := dispatch.New(dispatch.Config{Content: dispatch.NewMemoryContent(), Puts: 2, Stages: dispatch.Stages{route.Archive: s}, Index: index, Dir: work, Inspect: strict}) diff --git a/stages/archive_test.go b/stages/archive_test.go index 2697e252..5ab3c4a7 100644 --- a/stages/archive_test.go +++ b/stages/archive_test.go @@ -15,12 +15,12 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/sevenzip" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" ) func capDispatcher(t *testing.T, limit int64) (*dispatch.Dispatcher, string) { t.Helper() - d, _, work := archiveDispatcherLimited(t, stages.ArchiveConfig{}, dispatch.Limits{Bytes: limit}) + d, _, work := archiveDispatcherLimited(t, adapter.ArchiveConfig{}, dispatch.Limits{Bytes: limit}) return d, work } @@ -177,7 +177,7 @@ func TestZstdBytesCap(t *testing.T) { } limit := info.Size() + 4*mib seven := &endless{} - d, _, work := archiveDispatcherLimited(t, stages.ArchiveConfig{SevenZip: seven}, dispatch.Limits{Bytes: limit}) + d, _, work := archiveDispatcherLimited(t, adapter.ArchiveConfig{SevenZip: seven}, dispatch.Limits{Bytes: limit}) events := dispatchAll(t, d, stream, noFilesAt(t, work)) wantSteps(t, events, []step{{"endless", 1, dispatch.Limited}, {"endless.zst", 0, dispatch.Prepared}}) wantLimited(t, events[0], "zstd content endless", limit) diff --git a/stages/audio_integration_test.go b/stages/audio_integration_test.go index aac52b76..0df5678e 100644 --- a/stages/audio_integration_test.go +++ b/stages/audio_integration_test.go @@ -15,7 +15,7 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/metadata" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) @@ -48,8 +48,8 @@ func TestAudioStageReal(t *testing.T) { if err != nil { t.Fatal(err) } - stage := stages.NewAudioStage(stages.AudioConfig{ - Splitter: s, Version: stages.Versions(ffmpeg, ffprobe), Request: audio.Request{Concurrency: 2}, + stage := adapter.NewAudioStage(adapter.AudioConfig{ + Splitter: s, Version: adapter.Versions(ffmpeg, ffprobe), Request: audio.Request{Concurrency: 2}, }) path, err := filepath.Abs(speechFixture) if err != nil { @@ -128,8 +128,8 @@ func TestAudioStageMetadataReal(t *testing.T) { if err != nil { t.Fatal(err) } - stage := stages.NewAudioStage(stages.AudioConfig{ - Splitter: s, Version: stages.Versions(ffmpeg, ffprobe), Request: audio.Request{Concurrency: 2}, + stage := adapter.NewAudioStage(adapter.AudioConfig{ + Splitter: s, Version: adapter.Versions(ffmpeg, ffprobe), Request: audio.Request{Concurrency: 2}, }) path, err := filepath.Abs(taggedMP3) if err != nil { diff --git a/stages/audio_test.go b/stages/audio_test.go index b6732239..37e98690 100644 --- a/stages/audio_test.go +++ b/stages/audio_test.go @@ -25,7 +25,7 @@ import ( "github.com/standards-lab/docproc/internal/mediatest" "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) @@ -169,10 +169,10 @@ func standinTools(t *testing.T, probe string) (ffmpeg, ffprobe *tool.Tool, stand return tools[0], tools[1], standins } -func testAudioStage(t *testing.T, probe string) (*stages.AudioStage, *ffStandins) { +func testAudioStage(t *testing.T, probe string) (*adapter.AudioStage, *ffStandins) { t.Helper() splitter, standins := standinSplitter(t, probe) - s := stages.NewAudioStage(stages.AudioConfig{ + s := adapter.NewAudioStage(adapter.AudioConfig{ Splitter: splitter, Version: "ffmpeg 9.0.2, ffprobe 9.0.2", Request: audio.Request{Concurrency: 2}, }) return s, standins @@ -328,8 +328,8 @@ func TestAudioNoProcessor(t *testing.T) { t.Errorf("the video part ran %q", runs) } - wantPanic(t, "stages: audioConfig.Splitter is nil", func() { - stages.NewAudioStage(stages.AudioConfig{Version: "ffmpeg 9.0.2, ffprobe 9.0.2"}) + wantPanic(t, "stages: AudioConfig.Splitter is nil", func() { + adapter.NewAudioStage(adapter.AudioConfig{Version: "ffmpeg 9.0.2, ffprobe 9.0.2"}) }) } @@ -381,7 +381,7 @@ func TestAudioStageIdentity(t *testing.T) { const version = "ffmpeg version 9.0.2, ffprobe version 9.0.2" id := func(req audio.Request) dispatch.Identity { t.Helper() - return stages.NewAudioStage(stages.AudioConfig{Splitter: s, Version: version, Request: req}).Identity() + return adapter.NewAudioStage(adapter.AudioConfig{Splitter: s, Version: version, Request: req}).Identity() } base := id(audio.Request{Concurrency: 1}) if base.Name != "audio" || base.Version != version || len(base.Config) != 64 { diff --git a/stages/classify_test.go b/stages/classify_test.go index dc9f6020..6796332a 100644 --- a/stages/classify_test.go +++ b/stages/classify_test.go @@ -21,6 +21,7 @@ import ( "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/sevenzip" "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) @@ -159,16 +160,16 @@ func TestClassify(t *testing.T) { {"not an archive", t.Context(), fmt.Errorf("sevenzip: %w", sevenzip.ErrNotArchive), 0, true, ""}, {"docproc's side of the pipe", t.Context(), errors.New("write |1: broken pipe"), 0, false, ""}, } { - content, reason := stages.Classify(c.ctx, c.err, c.memory) + content, reason := adapter.Classify(c.ctx, c.err, c.memory) if content != c.content || c.reason != "" && reason != c.reason { t.Errorf("%s: content %t, %q; want %t, %q", c.name, content, reason, c.content, c.reason) } } - if err := stages.PartErr(t.Context(), exit("gs", 1), 0); !errors.Is(err, dispatch.ErrRefused) { + if err := adapter.PartErr(t.Context(), exit("gs", 1), 0); !errors.Is(err, dispatch.ErrRefused) { t.Errorf("partErr of the content's: %v, want ErrRefused", err) } for _, named := range []error{dispatch.ErrEncrypted, dispatch.ErrReadElsewhere, dispatch.ErrNoProcessor} { - if err := stages.PartErr(t.Context(), named, 0); err != named { + if err := adapter.PartErr(t.Context(), named, 0); err != named { t.Errorf("partErr(%v) = %v, want it as it is", named, err) } } diff --git a/stages/doc.go b/stages/doc.go index 875d659a..2ba9cc08 100644 --- a/stages/doc.go +++ b/stages/doc.go @@ -6,8 +6,9 @@ // route; either way the route has no processor yet. Its [Set] holds the stages, and the stage // table a host reports, dispatch's Tool and Row, one row per route. // -// The stage adapters are this package's, unexported, each a dispatch.Stage over its format -// package and the tools it requires, with no partial mode: a stage has its tools, or isn't wired. +// The stage adapters are module-internal, in stages/internal/adapter, each a dispatch.Stage over +// its format package and the tools it requires, with no partial mode: a stage has its tools, or +// isn't wired. // // - document, route.Document: a PDF through gs, qpdf, pdfdetach, and pdftotext: qpdf's finding // that it needs a password raised as the part's flag, then dispatch.ErrEncrypted; its @@ -34,8 +35,8 @@ // - video, route.Video: the plan record, then frames and windows from one ffmpeg run. // - text, route.Text: text decoded to UTF-8. // -// A stage's outcome is classified once, here, from the facts package tool reports, for a unit of -// a part and for a part alike: +// A stage's outcome is classified once, in the adapters, from the facts package tool reports, for +// a unit of a part and for a part alike: // // the content's, recorded the tool exited nonzero by its own code: a docproc tool's 3 and 4, // gs's 1, qpdf's 2, 7zz's 8 (out of memory), and every other tool's @@ -62,9 +63,9 @@ // a permanent gap. A death by a signal under a memory bound names the bound, as in "killed by // SIGABRT under a 256 MiB memory bound". // -// Three rules are each this package's once: +// Three rules are each the adapters' once: // -// - classify reads a unit's or a part's failure by the table above. +// - Classify reads a unit's or a part's failure by the table above. // - Each stage's identity hashes its format package's request resolved, every default filled // and each field that changes no output tagged out of its JSON, with the adapters' version, // and the office stage's own version too, raised when it reads content it ended unread, so diff --git a/stages/document_test.go b/stages/document_test.go index e5b45267..d60b864c 100644 --- a/stages/document_test.go +++ b/stages/document_test.go @@ -28,7 +28,7 @@ import ( "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/metadata" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) @@ -89,15 +89,15 @@ func qpdfFailed(message string) error { return fmt.Errorf("document: qpdf: %w", &tool.ExitError{Program: "qpdf", Code: 2, Message: message}) } -func formsDocumentStage(t *testing.T, q stages.QPDFReader, d stages.PDFDetacher, opts inspect.Options) *stages.DocumentStage { +func formsDocumentStage(t *testing.T, q adapter.QPDFReader, d adapter.PDFDetacher, opts inspect.Options) *adapter.DocumentStage { t.Helper() - return stages.NewDocumentStage(stages.DocumentConfig{ + return adapter.NewDocumentStage(adapter.DocumentConfig{ Preparer: standinPreparer(t, gsSettings{Pages: 3}), QPDF: q, PDFDetach: d, PDFInfo: &fakeInfo{}, Version: "gs 10.08.0", Request: document.ImagesRequest{Text: true, Concurrency: 1}, Inspect: opts, }) } -func documentOrder(t *testing.T, s *stages.DocumentStage, pdf string) ([]dispatched, []string) { +func documentOrder(t *testing.T, s *adapter.DocumentStage, pdf string) ([]dispatched, []string) { t.Helper() d := newDispatcher(t, dispatch.Stages{route.Document: s}, dispatch.NewMemoryIndex(0)) var order []string @@ -316,7 +316,7 @@ func TestDocumentIdentity(t *testing.T) { prep := standinPreparer(t, gsSettings{Pages: 1}) id := func(req document.ImagesRequest, opts inspect.Options) dispatch.Identity { t.Helper() - return stages.NewDocumentStage(stages.DocumentConfig{ + return adapter.NewDocumentStage(adapter.DocumentConfig{ Preparer: prep, QPDF: &fakeQPDF{}, PDFDetach: &fakeDetach{}, PDFInfo: &fakeInfo{}, Version: "gs 10.5 (2025)", Request: req, Inspect: opts, }).Identity() } @@ -403,9 +403,9 @@ func goldenInfo(t *testing.T, name string) pdfinfoSettings { return s } -func metadataStage(t *testing.T, q stages.QPDFReader, info stages.PDFInfoReader) *stages.DocumentStage { +func metadataStage(t *testing.T, q adapter.QPDFReader, info adapter.PDFInfoReader) *adapter.DocumentStage { t.Helper() - return stages.NewDocumentStage(stages.DocumentConfig{ + return adapter.NewDocumentStage(adapter.DocumentConfig{ Preparer: standinPreparer(t, gsSettings{Pages: 3}), QPDF: q, PDFDetach: &fakeDetach{}, PDFInfo: info, Version: "gs 10.08.0", Request: document.ImagesRequest{Text: true, Concurrency: 1}, }) diff --git a/stages/email_test.go b/stages/email_test.go index 19e7e45c..5a9dd2ed 100644 --- a/stages/email_test.go +++ b/stages/email_test.go @@ -10,11 +10,11 @@ import ( "github.com/standards-lab/docproc/email" "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) -func standinEmailStage(t *testing.T, s onenoteSettings) *stages.EmailStage { +func standinEmailStage(t *testing.T, s onenoteSettings) *adapter.EmailStage { t.Helper() spec := email.MailSpec() spec.Program = tooltest.Link(t, t.TempDir(), "docproc-mail", s) @@ -26,7 +26,7 @@ func standinEmailStage(t *testing.T, s onenoteSettings) *stages.EmailStage { if err != nil { t.Fatal(err) } - return stages.NewEmailStage(stages.EmailConfig{Reader: r, Version: stages.Versions(tl)}) + return adapter.NewEmailStage(adapter.EmailConfig{Reader: r, Version: adapter.Versions(tl)}) } func TestEmailStageThreading(t *testing.T) { diff --git a/stages/export_test.go b/stages/export_test.go deleted file mode 100644 index 4fb513a2..00000000 --- a/stages/export_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package stages - -import ( - "context" - - "github.com/standards-lab/docproc/office" - "github.com/standards-lab/docproc/picture" - "github.com/standards-lab/docproc/route" -) - -type ( - DocumentConfig = documentConfig - DocumentStage = documentStage - OfficeConfig = officeConfig - OfficeStage = officeStage - PictureConfig = pictureConfig - PictureStage = pictureStage - EmailConfig = emailConfig - EmailStage = emailStage - OneNoteConfig = onenoteConfig - OneNoteStage = onenoteStage - ArchiveConfig = archiveConfig - ArchiveStage = archiveStage - AudioConfig = audioConfig - AudioStage = audioStage - VideoConfig = videoConfig - VideoStage = videoStage - VisionConfig = visionConfig - VisionStage = visionStage - TextStage = textStage - QPDFReader = qpdfReader - PDFDetacher = pdfDetacher - PDFInfoReader = pdfInfoReader - SevenZipReader = sevenZipReader - EXIFReader = exifReader -) - -var ( - NewDocumentStage = newDocumentStage - NewOfficeStage = newOfficeStage - NewPictureStage = newPictureStage - NewEmailStage = newEmailStage - NewOneNoteStage = newOneNoteStage - NewArchiveStage = newArchiveStage - NewAudioStage = newAudioStage - NewVideoStage = newVideoStage - NewVisionStage = newVisionStage - NewTextStage = newTextStage - Versions = versions - PartErr = partErr -) - -func Classify(ctx context.Context, err error, memory int64) (content bool, reason string) { - f := classify(ctx, err, memory) - return f.content, f.reason -} - -func Needs() map[route.Route][]string { - needs := map[route.Route][]string{} - for _, s := range table { - needs[s.route] = s.needs - } - return needs -} - -func PictureConverter(s *PictureStage) *picture.Converter { return s.converter } - -func OfficeConverter(s *OfficeStage) *office.Converter { return s.converter } diff --git a/stages/adapter.go b/stages/internal/adapter/adapter.go similarity index 81% rename from stages/adapter.go rename to stages/internal/adapter/adapter.go index 4656e5cf..fb219327 100644 --- a/stages/adapter.go +++ b/stages/internal/adapter/adapter.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( jsonv2 "encoding/json/v2" @@ -11,12 +11,31 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/inspect" + "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/tool" ) const adapterVersion = "7" -func versions(tools ...*tool.Tool) string { +// Needs returns the programs each route's stage requires, in the order its Version lists their +// version lines; route.Text's requires none. +func Needs() map[route.Route][]string { + return map[route.Route][]string{ + route.Document: {"gs", "qpdf", "pdfdetach", "pdftotext", "pdfinfo"}, + route.Office: {"docproc-ooxml", "soffice", "magick"}, + route.VisionConverted: {"magick", "soffice"}, + route.Vision: {"magick"}, + route.Nested: {"docproc-mail"}, + route.OneNote: {"docproc-onenote"}, + route.Archive: {"7zz"}, + route.Audio: {"ffmpeg", "ffprobe"}, + route.Video: {"ffmpeg", "ffprobe"}, + route.Text: nil, + } +} + +// Versions joins tools' version lines, a stage's Version. +func Versions(tools ...*tool.Tool) string { lines := make([]string, len(tools)) for i, t := range tools { lines[i] = t.VersionLine() diff --git a/stages/archive.go b/stages/internal/adapter/archive.go similarity index 84% rename from stages/archive.go rename to stages/internal/adapter/archive.go index 13b7b3c4..f7ef736a 100644 --- a/stages/archive.go +++ b/stages/internal/adapter/archive.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "context" @@ -29,14 +29,19 @@ type sevenZipReader interface { Extract(ctx context.Context, req sevenzip.ExtractRequest, w io.Writer) error } -type archiveConfig struct { +// ArchiveConfig is what [NewArchiveStage] builds the archive stage over: SevenZip is required; +// Version is its tool's version line; Inspect gives the bomb rule, Entries, and Policy; and Memory +// is the tool's memory bound in bytes, zero for none. +type ArchiveConfig struct { SevenZip sevenZipReader Version string Inspect inspect.Options Memory int64 } -type archiveStage struct { +// ArchiveStage is the archive stage, route.Archive's: each entry of an archive or compressed +// stream found, or an unread child. +type ArchiveStage struct { bomb inspect.BombRule opts inspect.Options sevenZip sevenZipReader @@ -44,12 +49,13 @@ type archiveStage struct { id dispatch.Identity } -func newArchiveStage(cfg archiveConfig) *archiveStage { +// NewArchiveStage returns the archive stage over cfg, panicking on a nil SevenZip. +func NewArchiveStage(cfg ArchiveConfig) *ArchiveStage { if cfg.SevenZip == nil { - panic("stages: archiveConfig.SevenZip is nil") + panic("stages: ArchiveConfig.SevenZip is nil") } bomb := cfg.Inspect.Bomb() - return &archiveStage{ + return &ArchiveStage{ bomb: bomb, opts: cfg.Inspect, sevenZip: cfg.SevenZip, memory: cfg.Memory, id: identity("archive", cfg.Version, struct { Bomb inspect.BombRule `json:"bomb"` @@ -58,11 +64,14 @@ func newArchiveStage(cfg archiveConfig) *archiveStage { } } -func (s *archiveStage) Identity() dispatch.Identity { return s.id } +// Identity is the stage's identity, its bomb rule and Entries hashed. +func (s *ArchiveStage) Identity() dispatch.Identity { return s.id } -func (s *archiveStage) UntrustedWhere() {} +// UntrustedWhere marks the stage's found parts' Where as named by the content. +func (s *ArchiveStage) UntrustedWhere() {} -func (s *archiveStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { +// Prepare prepares p, an archive or compressed stream, into dir. +func (s *ArchiveStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { return func(yield func(dispatch.Item, error) bool) { ctx := withWriteCap(ctx) switch p.ContentType.Kind { @@ -107,7 +116,7 @@ func flagged(where, name string, typ inspect.EntryType, flags []inspect.Flag) di return unread(where, name, dispatch.Quarantined, reason, flags...) } -func (s *archiveStage) bombChild(where, name, what string, written, whole uint64) dispatch.Item { +func (s *ArchiveStage) bombChild(where, name, what string, written, whole uint64) dispatch.Item { return unread(where, name, dispatch.Quarantined, "past the bomb rule as written", inspect.Flag{ Check: inspect.ArchiveBomb, Class: inspect.Unsafe, Evidence: fmt.Sprintf("%s: %d bytes written from %d, %.0f:1; past %d bytes and %g:1", @@ -147,7 +156,7 @@ func copyFrom(r io.Reader) func(io.Writer) error { } } -func (s *archiveStage) extract(ctx context.Context, fill func(io.Writer) error, dir string, compressed uint64, +func (s *ArchiveStage) extract(ctx context.Context, fill func(io.Writer) error, dir string, compressed uint64, whole func(w *bombWriter, fillErr error) error, ) (path string, written uint64, why, err error) { return writeBySum(ctx, "archive stage", s.bomb, fill, dir, compressed, whole) diff --git a/stages/audio.go b/stages/internal/adapter/audio.go similarity index 78% rename from stages/audio.go rename to stages/internal/adapter/audio.go index 89f42f1b..e4f12be8 100644 --- a/stages/audio.go +++ b/stages/internal/adapter/audio.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "cmp" @@ -15,27 +15,32 @@ import ( const audioVersion = "2" -type audioConfig struct { +// AudioConfig is what [NewAudioStage] builds the audio stage over: Splitter is required; Version is +// its tools' version lines; Request is every part's windows' request; and Memory is the tools' +// memory bound in bytes, zero for none. +type AudioConfig struct { Splitter *audio.Splitter Version string Request audio.Request Memory int64 } -type audioStage struct { +// AudioStage is the audio stage, route.Audio's: windows from one decode, then the plan record. +type AudioStage struct { splitter *audio.Splitter request audio.Request memory int64 id dispatch.Identity } -func newAudioStage(cfg audioConfig) *audioStage { +// NewAudioStage returns the audio stage over cfg, panicking on a nil Splitter. +func NewAudioStage(cfg AudioConfig) *AudioStage { if cfg.Splitter == nil { - panic("stages: audioConfig.Splitter is nil") + panic("stages: AudioConfig.Splitter is nil") } req := cfg.Request req.Dir = "" - return &audioStage{splitter: cfg.Splitter, request: req, memory: cfg.Memory, id: identity("audio", cfg.Version, struct { + return &AudioStage{splitter: cfg.Splitter, request: req, memory: cfg.Memory, id: identity("audio", cfg.Version, struct { Stage string `json:"stage"` Request audio.Request `json:"request"` }{audioVersion, resolvedAudio(req)})} @@ -58,9 +63,11 @@ func resolvedAudio(req audio.Request) audio.Request { return r } -func (s *audioStage) Identity() dispatch.Identity { return s.id } +// Identity is the stage's identity, its request resolved. +func (s *AudioStage) Identity() dispatch.Identity { return s.id } -func (s *audioStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { +// Prepare prepares p, an audio part, into dir. +func (s *AudioStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { return func(yield func(dispatch.Item, error) bool) { req := s.request req.Dir = dir @@ -69,7 +76,7 @@ func (s *audioStage) Prepare(ctx context.Context, p dispatch.Part, dir string) i if err != nil { err = fmt.Errorf("audio stage: %w", err) if cut == 0 { - yield(dispatch.Item{}, partErr(ctx, err, s.memory)) + yield(dispatch.Item{}, PartErr(ctx, err, s.memory)) return } warning, runErr := unitWarning(ctx, "ffmpeg", "window "+strconv.Itoa(cut), err, s.memory) diff --git a/stages/classify.go b/stages/internal/adapter/classify.go similarity index 62% rename from stages/classify.go rename to stages/internal/adapter/classify.go index 234709ba..8beefc2a 100644 --- a/stages/classify.go +++ b/stages/internal/adapter/classify.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "context" @@ -37,59 +37,60 @@ func runCodes(program string) []int { return nil } -type fault struct { - content bool - reason string -} - -func classify(ctx context.Context, err error, memory int64) fault { - f := fault{reason: err.Error()} +// Classify reads err, a unit's or a part's failure under a memory bound of memory bytes, zero for +// none, by the failure table: content reports it the content's, recorded, rather than the run's, +// retried, and reason is the failure as recorded. +func Classify(ctx context.Context, err error, memory int64) (content bool, reason string) { + reason = err.Error() if ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { - return f + return false, reason } if exit, ok := errors.AsType[*tool.ExitError](err); ok { switch { case exit.TimedOut: - f.content = true + content = true case exit.Signal != "": - f.content = cli.OwnFault(exit.Signal) - if f.content && memory > 0 { - f.reason = fmt.Sprintf("%s: killed by %s under a %s memory bound", exit.Program, exit.Signal, bytesOf(memory)) + content = cli.OwnFault(exit.Signal) + if content && memory > 0 { + reason = fmt.Sprintf("%s: killed by %s under a %s memory bound", exit.Program, exit.Signal, bytesOf(memory)) if exit.Message != "" { - f.reason += ": " + exit.Message + reason += ": " + exit.Message } } default: - f.content = !slices.Contains(runCodes(exit.Program), exit.Code) + content = !slices.Contains(runCodes(exit.Program), exit.Code) } - return f + return content, reason } var syntax *jsontext.SyntacticError var semantic *jsonv2.SemanticError - f.content = errors.As(err, &syntax) || errors.As(err, &semantic) || + content = errors.As(err, &syntax) || errors.As(err, &semantic) || slices.ContainsFunc(contentErrors, func(c error) bool { return errors.Is(err, c) }) - return f + return content, reason } -func partErr(ctx context.Context, err error, memory int64) error { +// PartErr is a part's failure err as the stage returns it: a named dispatch error as is, one of +// the run's class unchanged, and one of the content's wrapped with dispatch.ErrRefused, its +// reason the recorded one. +func PartErr(ctx context.Context, err error, memory int64) error { for _, named := range []error{dispatch.ErrEncrypted, dispatch.ErrReadElsewhere, dispatch.ErrNoProcessor, dispatch.ErrRefused} { if errors.Is(err, named) { return err } } - f := classify(ctx, err, memory) - if !f.content { + content, reason := Classify(ctx, err, memory) + if !content { return err } - return &refused{reason: f.reason, err: err} + return &refused{reason: reason, err: err} } func unitWarning(ctx context.Context, program, where string, err error, memory int64) (dispatch.Warning, error) { - f := classify(ctx, err, memory) - if !f.content { + content, reason := Classify(ctx, err, memory) + if !content { return dispatch.Warning{}, err } - return dispatch.Warning{Tool: program, Where: where, What: f.reason}, nil + return dispatch.Warning{Tool: program, Where: where, What: reason}, nil } type refused struct { diff --git a/stages/internal/adapter/doc.go b/stages/internal/adapter/doc.go new file mode 100644 index 00000000..bd300947 --- /dev/null +++ b/stages/internal/adapter/doc.go @@ -0,0 +1,30 @@ +// Package adapter holds docproc's stage adapters, each a dispatch.Stage over its format package +// and the tools it requires, and the failure classification they share. stages.Build wires them, +// and the stages package's tests drive them through this package's exported API; nothing outside +// the module reaches them. What each stage yields, the failure table, and the rules this package +// holds once are on the stages package's documentation. +// +// Every stage's constructor but the text stage's takes its Config, panics by name on a nil +// required field, and returns the stage, its identity hashing its request resolved with the +// adapters' version. +// +// Its exported identifiers: +// +// - [NewDocumentStage] builds a [DocumentStage] from a [DocumentConfig], over a [QPDFReader], a +// [PDFDetacher], and a [PDFInfoReader]. +// - [NewOfficeStage] builds an [OfficeStage] from an [OfficeConfig]; [OfficeStage.Converter] is +// its converter. +// - [NewPictureStage] builds a [PictureStage] from a [PictureConfig]; [PictureStage.Converter] is +// its converter. +// - [NewVisionStage] builds a [VisionStage] from a [VisionConfig]. +// - [NewEmailStage] builds an [EmailStage] from an [EmailConfig]. +// - [NewOneNoteStage] builds a [OneNoteStage] from a [OneNoteConfig]. +// - [NewArchiveStage] builds an [ArchiveStage] from an [ArchiveConfig]. +// - [NewAudioStage] builds an [AudioStage] from an [AudioConfig]. +// - [NewVideoStage] builds a [VideoStage] from a [VideoConfig]. +// - [NewTextStage] builds the text stage, which requires no tool. +// - [Needs] returns the programs each route's stage requires, and [Versions] joins tools' +// version lines into a stage's Version. +// - [Classify] reads a failure by the failure table, and [PartErr] turns a part's failure into +// the error its stage returns. +package adapter diff --git a/stages/document.go b/stages/internal/adapter/document.go similarity index 77% rename from stages/document.go rename to stages/internal/adapter/document.go index bd2d8ed4..482059bc 100644 --- a/stages/document.go +++ b/stages/internal/adapter/document.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "cmp" @@ -17,57 +17,70 @@ import ( const documentVersion = "2" -type qpdfReader interface { +// QPDFReader is what the document stage reads through qpdf: whether a PDF needs a password, and its +// AcroForm; document.QPDF is one. +type QPDFReader interface { RequiresPassword(ctx context.Context, pdf string) (bool, error) Form(ctx context.Context, pdf string) (document.Form, error) } -type pdfDetacher interface { +// PDFDetacher is what the document stage lists and saves a PDF's embedded files through; +// document.Detacher is one. +type PDFDetacher interface { List(ctx context.Context, pdf string) ([]document.Attachment, error) Save(ctx context.Context, pdf string, number int, w io.Writer) error } -type pdfInfoReader interface { +// PDFInfoReader is what the document stage reads a PDF's metadata through; document.InfoReader is +// one. +type PDFInfoReader interface { Metadata(ctx context.Context, pdf string) (metadata.PDF, error) } -type documentConfig struct { +// DocumentConfig is what [NewDocumentStage] builds the document stage over: Preparer, QPDF, +// PDFDetach, and PDFInfo are required; Version is its tools' version lines; Request is every PDF's +// pages' request; Inspect gives the embedded files' bomb rule; and Memory is the tools' memory bound +// in bytes, zero for none. +type DocumentConfig struct { Preparer *document.Preparer - QPDF qpdfReader - PDFDetach pdfDetacher - PDFInfo pdfInfoReader + QPDF QPDFReader + PDFDetach PDFDetacher + PDFInfo PDFInfoReader Version string Request document.ImagesRequest Inspect inspect.Options Memory int64 } -type documentStage struct { +// DocumentStage is the document stage, route.Document's: a PDF's password flag, its forms record, +// its embedded files found, and each page's text and PNG. +type DocumentStage struct { preparer *document.Preparer request document.ImagesRequest - qpdf qpdfReader - detach pdfDetacher - info pdfInfoReader + qpdf QPDFReader + detach PDFDetacher + info PDFInfoReader bomb inspect.BombRule memory int64 id dispatch.Identity } -func newDocumentStage(cfg documentConfig) *documentStage { +// NewDocumentStage returns the document stage over cfg, panicking on a nil required field. +func NewDocumentStage(cfg DocumentConfig) *DocumentStage { switch { case cfg.Preparer == nil: - panic("stages: documentConfig.Preparer is nil") + panic("stages: DocumentConfig.Preparer is nil") case cfg.QPDF == nil: - panic("stages: documentConfig.QPDF is nil") + panic("stages: DocumentConfig.QPDF is nil") case cfg.PDFDetach == nil: - panic("stages: documentConfig.PDFDetach is nil") + panic("stages: DocumentConfig.PDFDetach is nil") case cfg.PDFInfo == nil: - panic("stages: documentConfig.PDFInfo is nil") + panic("stages: DocumentConfig.PDFInfo is nil") } req := cfg.Request req.DPI = cmp.Or(req.DPI, document.DefaultDPI) bomb := cfg.Inspect.Bomb() - return &documentStage{ + return &DocumentStage{ preparer: cfg.Preparer, request: req, qpdf: cfg.QPDF, detach: cfg.PDFDetach, info: cfg.PDFInfo, bomb: bomb, memory: cfg.Memory, id: identity("document", cfg.Version, struct { Stage string `json:"stage"` @@ -77,12 +90,14 @@ func newDocumentStage(cfg documentConfig) *documentStage { } } -func (s *documentStage) Identity() dispatch.Identity { return s.id } +// Identity is the stage's identity, its request resolved and its bomb rule hashed. +func (s *DocumentStage) Identity() dispatch.Identity { return s.id } -func (s *documentStage) UntrustedWhere() {} +// UntrustedWhere marks the stage's found parts' Where as named by the content. +func (s *DocumentStage) UntrustedWhere() {} type documentRun struct { - s *documentStage + s *DocumentStage ctx context.Context p dispatch.Part yield func(dispatch.Item, error) bool @@ -110,7 +125,8 @@ func (r *documentRun) unit(program, where string, err error) bool { return r.emit(dispatch.WarningItem(w)) } -func (s *documentStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { +// Prepare prepares p, a PDF, into dir. +func (s *DocumentStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { return func(yield func(dispatch.Item, error) bool) { ctx := withWriteCap(ctx) r := &documentRun{s: s, ctx: ctx, p: p, yield: yield} diff --git a/stages/email.go b/stages/internal/adapter/email.go similarity index 88% rename from stages/email.go rename to stages/internal/adapter/email.go index 0e0d75f8..fdff8814 100644 --- a/stages/email.go +++ b/stages/internal/adapter/email.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "cmp" @@ -18,32 +18,39 @@ import ( const emailVersion = "2" -type emailConfig struct { +// EmailConfig is what [NewEmailStage] builds the email stage over: Reader is required; Version is +// its tool's version line; and Memory is the tool's memory bound in bytes, zero for none. +type EmailConfig struct { Reader *email.Reader Version string Memory int64 } -type emailStage struct { +// EmailStage is the email stage, route.Nested's: docproc-mail's records, each message's Markdown, +// and its attachments and media found. +type EmailStage struct { reader *email.Reader memory int64 id dispatch.Identity } -func newEmailStage(cfg emailConfig) *emailStage { +// NewEmailStage returns the email stage over cfg, panicking on a nil Reader. +func NewEmailStage(cfg EmailConfig) *EmailStage { if cfg.Reader == nil { - panic("stages: emailConfig.Reader is nil") + panic("stages: EmailConfig.Reader is nil") } - return &emailStage{reader: cfg.Reader, memory: cfg.Memory, id: identity("email", cfg.Version, struct { + return &EmailStage{reader: cfg.Reader, memory: cfg.Memory, id: identity("email", cfg.Version, struct { Stage string `json:"stage"` Schema string `json:"schema"` Request email.Request `json:"request"` }{emailVersion, cli.Schema, email.Request{}})} } -func (s *emailStage) Identity() dispatch.Identity { return s.id } +// Identity is the stage's identity. +func (s *EmailStage) Identity() dispatch.Identity { return s.id } -func (s *emailStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { +// Prepare prepares p, a mailbox or message, into dir. +func (s *EmailStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { return func(yield func(dispatch.Item, error) bool) { media := filepath.Join(dir, "media") if err := os.Mkdir(media, 0o700); err != nil { @@ -53,7 +60,7 @@ func (s *emailStage) Prepare(ctx context.Context, p dispatch.Part, dir string) i w := emailWalk{stash: stash{dir: dir}, folders: map[uint64][]string{}, yield: yield} for rec, err := range s.reader.Read(ctx, email.Request{Input: p.Path, Media: media, After: p.After}) { if err != nil { - yield(dispatch.Item{}, partErr(ctx, fmt.Errorf("email stage: %w", err), s.memory)) + yield(dispatch.Item{}, PartErr(ctx, fmt.Errorf("email stage: %w", err), s.memory)) return } if err := w.record(rec); err != nil { diff --git a/stages/office.go b/stages/internal/adapter/office.go similarity index 82% rename from stages/office.go rename to stages/internal/adapter/office.go index 9608bea6..5dd5d618 100644 --- a/stages/office.go +++ b/stages/internal/adapter/office.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "bufio" @@ -20,35 +20,46 @@ import ( const officeVersion = "3" -type officeConfig struct { +// OfficeConfig is what [NewOfficeStage] builds the office stage over: Converter is required; +// Version is its tools' version lines; MetafileScale is a metafile's scale, zero for the default; +// and Memory is the tools' memory bound in bytes, zero for none. +type OfficeConfig struct { Converter *office.Converter Version string MetafileScale int Memory int64 } -type officeStage struct { +// OfficeStage is the office stage, route.Office's: a document's and each sheet's Markdown, each +// sheet's rows, and each medium found. +type OfficeStage struct { converter *office.Converter scale int memory int64 id dispatch.Identity } -func newOfficeStage(cfg officeConfig) *officeStage { +// NewOfficeStage returns the office stage over cfg, panicking on a nil Converter. +func NewOfficeStage(cfg OfficeConfig) *OfficeStage { if cfg.Converter == nil { - panic("stages: officeConfig.Converter is nil") + panic("stages: OfficeConfig.Converter is nil") } scale := cmp.Or(cfg.MetafileScale, picture.DefaultMetafileScale) - return &officeStage{converter: cfg.Converter, scale: scale, memory: cfg.Memory, id: identity("office", cfg.Version, struct { + return &OfficeStage{converter: cfg.Converter, scale: scale, memory: cfg.Memory, id: identity("office", cfg.Version, struct { Stage string `json:"stage"` Schema string `json:"schema"` Request office.Request `json:"request"` }{officeVersion, cli.Schema, office.Request{MetafileScale: scale}})} } -func (s *officeStage) Identity() dispatch.Identity { return s.id } +// Converter is the converter the stage was built over. +func (s *OfficeStage) Converter() *office.Converter { return s.converter } -func (s *officeStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { +// Identity is the stage's identity. +func (s *OfficeStage) Identity() dispatch.Identity { return s.id } + +// Prepare prepares p, an office document, into dir. +func (s *OfficeStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { return func(yield func(dispatch.Item, error) bool) { w := officeWalk{dir: dir, yield: yield} defer w.close() @@ -59,7 +70,7 @@ func (s *officeStage) Prepare(ctx context.Context, p dispatch.Part, dir string) } if err != nil { if !errors.Is(err, errStopped) { - yield(dispatch.Item{}, partErr(ctx, fmt.Errorf("office stage: %w", err), s.memory)) + yield(dispatch.Item{}, PartErr(ctx, fmt.Errorf("office stage: %w", err), s.memory)) } return } diff --git a/stages/onenote.go b/stages/internal/adapter/onenote.go similarity index 80% rename from stages/onenote.go rename to stages/internal/adapter/onenote.go index 60a260e2..7d36fa9a 100644 --- a/stages/onenote.go +++ b/stages/internal/adapter/onenote.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "cmp" @@ -16,7 +16,9 @@ import ( "github.com/standards-lab/docproc/onenote" ) -type onenoteConfig struct { +// OneNoteConfig is what [NewOneNoteStage] builds the onenote stage over: Reader is required; +// Version is its tool's version line; and Memory is the tool's memory bound in bytes, zero for none. +type OneNoteConfig struct { Reader *onenote.Reader Version string Memory int64 @@ -24,25 +26,30 @@ type onenoteConfig struct { var onenoteRequest = onenote.Request{FileOnly: true} -type onenoteStage struct { +// OneNoteStage is the onenote stage, route.OneNote's: docproc-onenote's records, each page's +// Markdown, and its media found. +type OneNoteStage struct { reader *onenote.Reader memory int64 id dispatch.Identity } -func newOneNoteStage(cfg onenoteConfig) *onenoteStage { +// NewOneNoteStage returns the onenote stage over cfg, panicking on a nil Reader. +func NewOneNoteStage(cfg OneNoteConfig) *OneNoteStage { if cfg.Reader == nil { - panic("stages: onenoteConfig.Reader is nil") + panic("stages: OneNoteConfig.Reader is nil") } - return &onenoteStage{reader: cfg.Reader, memory: cfg.Memory, id: identity("onenote", cfg.Version, struct { + return &OneNoteStage{reader: cfg.Reader, memory: cfg.Memory, id: identity("onenote", cfg.Version, struct { Schema string `json:"schema"` Request onenote.Request `json:"request"` }{cli.Schema, onenoteRequest})} } -func (s *onenoteStage) Identity() dispatch.Identity { return s.id } +// Identity is the stage's identity. +func (s *OneNoteStage) Identity() dispatch.Identity { return s.id } -func (s *onenoteStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { +// Prepare prepares p, a OneNote section, into dir. +func (s *OneNoteStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { return func(yield func(dispatch.Item, error) bool) { media := filepath.Join(dir, "media") if err := os.Mkdir(media, 0o700); err != nil { @@ -54,7 +61,7 @@ func (s *onenoteStage) Prepare(ctx context.Context, p dispatch.Part, dir string) req.Input, req.Media = p.Path, media for rec, err := range s.reader.Read(ctx, req) { if err != nil { - yield(dispatch.Item{}, partErr(ctx, fmt.Errorf("onenote stage: %w", err), s.memory)) + yield(dispatch.Item{}, PartErr(ctx, fmt.Errorf("onenote stage: %w", err), s.memory)) return } if err := w.record(rec); err != nil { diff --git a/stages/picture.go b/stages/internal/adapter/picture.go similarity index 62% rename from stages/picture.go rename to stages/internal/adapter/picture.go index 99d70cb1..be562aec 100644 --- a/stages/picture.go +++ b/stages/internal/adapter/picture.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "cmp" @@ -15,7 +15,10 @@ import ( const pictureVersion = "2" -type pictureConfig struct { +// PictureConfig is what [NewPictureStage] builds the picture stage over: Converter and EXIF are +// required; Version is its tools' version lines; Request is every picture's conversion request; +// and Memory is the tools' memory bound in bytes, zero for none. +type PictureConfig struct { Converter *picture.Converter EXIF exifReader Version string @@ -23,7 +26,9 @@ type pictureConfig struct { Memory int64 } -type pictureStage struct { +// PictureStage is the picture stage, route.VisionConverted's: a picture's metadata record, then +// its pages as PNGs. +type PictureStage struct { converter *picture.Converter exif exifReader request picture.Request @@ -31,26 +36,32 @@ type pictureStage struct { id dispatch.Identity } -func newPictureStage(cfg pictureConfig) *pictureStage { +// NewPictureStage returns the picture stage over cfg, panicking on a nil required field. +func NewPictureStage(cfg PictureConfig) *PictureStage { switch { case cfg.Converter == nil: - panic("stages: pictureConfig.Converter is nil") + panic("stages: PictureConfig.Converter is nil") case cfg.EXIF == nil: - panic("stages: pictureConfig.EXIF is nil") + panic("stages: PictureConfig.EXIF is nil") } req := picture.Request{ MetafileScale: cmp.Or(cfg.Request.MetafileScale, picture.DefaultMetafileScale), Density: cmp.Or(cfg.Request.Density, picture.DefaultDensity), } - return &pictureStage{converter: cfg.Converter, exif: cfg.EXIF, request: req, memory: cfg.Memory, id: identity("picture", cfg.Version, struct { + return &PictureStage{converter: cfg.Converter, exif: cfg.EXIF, request: req, memory: cfg.Memory, id: identity("picture", cfg.Version, struct { Stage string `json:"stage"` Request picture.Request `json:"request"` }{pictureVersion, req})} } -func (s *pictureStage) Identity() dispatch.Identity { return s.id } +// Converter is the converter the stage was built over. +func (s *PictureStage) Converter() *picture.Converter { return s.converter } -func (s *pictureStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { +// Identity is the stage's identity. +func (s *PictureStage) Identity() dispatch.Identity { return s.id } + +// Prepare prepares p, a picture to convert, into dir. +func (s *PictureStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { return func(yield func(dispatch.Item, error) bool) { req := s.request req.Dir, req.Path, req.Kind, req.Stem = dir, p.Path, p.ContentType.Kind, p.SHA256 @@ -60,7 +71,7 @@ func (s *pictureStage) Prepare(ctx context.Context, p dispatch.Part, dir string) yield(dispatch.Item{}, fmt.Errorf("picture stage: %w: %w", dispatch.ErrNoProcessor, err)) return case err != nil: - yield(dispatch.Item{}, partErr(ctx, fmt.Errorf("picture stage: %w", err), s.memory)) + yield(dispatch.Item{}, PartErr(ctx, fmt.Errorf("picture stage: %w", err), s.memory)) return } if !pictureMetadata(ctx, "picture", s.exif, p, s.memory, yield) { diff --git a/stages/sevenzip.go b/stages/internal/adapter/sevenzip.go similarity index 92% rename from stages/sevenzip.go rename to stages/internal/adapter/sevenzip.go index 4ea02649..94538740 100644 --- a/stages/sevenzip.go +++ b/stages/internal/adapter/sevenzip.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "context" @@ -43,7 +43,7 @@ func listedType(e sevenzip.Entry) (inspect.EntryType, string) { return inspect.FileEntry, "" } -func (s *archiveStage) listedChecks(p dispatch.Part, entries []inspect.Listed, yield func(dispatch.Item, error) bool) bool { +func (s *ArchiveStage) listedChecks(p dispatch.Part, entries []inspect.Listed, yield func(dispatch.Item, error) bool) bool { rep, err := inspect.CheckListing(p.ContentType.Kind, p.Size, entries, s.opts) if err != nil { yield(dispatch.Item{}, fmt.Errorf("archive stage: %w", err)) @@ -57,18 +57,18 @@ func (s *archiveStage) listedChecks(p dispatch.Part, entries []inspect.Listed, y return true } -func (s *archiveStage) list(ctx context.Context, p dispatch.Part, k sevenZipKind) (sevenzip.Listing, error) { +func (s *ArchiveStage) list(ctx context.Context, p dispatch.Part, k sevenZipKind) (sevenzip.Listing, error) { l, err := s.sevenZip.List(ctx, sevenzip.ListRequest{Path: p.Path, Kind: p.ContentType.Kind, Entries: s.opts.Entries}) switch { case errors.Is(err, sevenzip.ErrEncrypted): return l, fmt.Errorf("archive stage: %s whose headers are encrypted: %w: %w", k.what, dispatch.ErrEncrypted, err) case err != nil: - return l, partErr(ctx, fmt.Errorf("archive stage: %w", err), s.memory) + return l, PartErr(ctx, fmt.Errorf("archive stage: %w", err), s.memory) } return l, nil } -func (s *archiveStage) listed(ctx context.Context, p dispatch.Part, dir string, k sevenZipKind, yield func(dispatch.Item, error) bool) { +func (s *ArchiveStage) listed(ctx context.Context, p dispatch.Part, dir string, k sevenZipKind, yield func(dispatch.Item, error) bool) { l, err := s.list(ctx, p, k) if err != nil { yield(dispatch.Item{}, err) @@ -85,7 +85,7 @@ func (s *archiveStage) listed(ctx context.Context, p dispatch.Part, dir string, files, encrypted := 0, 0 for read, err := range s.sevenZip.Read(ctx, sevenzip.ReadRequest{Path: p.Path, Kind: p.ContentType.Kind, Listing: l}) { if err != nil { - yield(dispatch.Item{}, partErr(ctx, fmt.Errorf("archive stage: %w", err), s.memory)) + yield(dispatch.Item{}, PartErr(ctx, fmt.Errorf("archive stage: %w", err), s.memory)) return } e := read.Entry @@ -110,7 +110,7 @@ func (s *archiveStage) listed(ctx context.Context, p dispatch.Part, dir string, } } -func (s *archiveStage) listedEntry(ctx context.Context, p dispatch.Part, k sevenZipKind, read sevenzip.Item, dir string) (dispatch.Item, error) { +func (s *ArchiveStage) listedEntry(ctx context.Context, p dispatch.Part, k sevenZipKind, read sevenzip.Item, dir string) (dispatch.Item, error) { e := read.Entry where := k.where + e.Path typ, link := listedType(e) @@ -143,7 +143,7 @@ func (s *archiveStage) listedEntry(ctx context.Context, p dispatch.Part, k seven return dispatch.PartItem(dispatch.Found{Path: path, Name: e.Path, Where: where}), nil } -func (s *archiveStage) rar(ctx context.Context, p dispatch.Part, dir string, yield func(dispatch.Item, error) bool) { +func (s *ArchiveStage) rar(ctx context.Context, p dispatch.Part, dir string, yield func(dispatch.Item, error) bool) { head, err := readHead(p.Path) if err != nil { yield(dispatch.Item{}, fmt.Errorf("archive stage: %w", err)) @@ -170,7 +170,7 @@ func readHead(path string) ([]byte, error) { return head[:n], nil } -func (s *archiveStage) stream(ctx context.Context, p dispatch.Part, dir string, yield func(dispatch.Item, error) bool) { +func (s *ArchiveStage) stream(ctx context.Context, p dispatch.Part, dir string, yield func(dispatch.Item, error) bool) { kind := p.ContentType.Kind k := sevenZipKinds[kind] l, err := s.list(ctx, p, k) diff --git a/stages/tar.go b/stages/internal/adapter/tar.go similarity index 92% rename from stages/tar.go rename to stages/internal/adapter/tar.go index 61359766..36828edc 100644 --- a/stages/tar.go +++ b/stages/internal/adapter/tar.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "archive/tar" @@ -22,7 +22,7 @@ var tarTypes = map[byte]inspect.EntryType{ tar.TypeFifo: inspect.DeviceEntry, } -func (s *archiveStage) tar(ctx context.Context, p dispatch.Part, dir string, yield func(dispatch.Item, error) bool) { +func (s *ArchiveStage) tar(ctx context.Context, p dispatch.Part, dir string, yield func(dispatch.Item, error) bool) { f, err := os.Open(p.Path) if err != nil { yield(dispatch.Item{}, fmt.Errorf("archive stage: %w", err)) @@ -57,7 +57,7 @@ func (s *archiveStage) tar(ctx context.Context, p dispatch.Part, dir string, yie } } -func (s *archiveStage) tarEntry(ctx context.Context, h *tar.Header, r io.Reader, whole uint64, dir string) (dispatch.Item, error) { +func (s *ArchiveStage) tarEntry(ctx context.Context, h *tar.Header, r io.Reader, whole uint64, dir string) (dispatch.Item, error) { where := "tar entry " + h.Name typ, unwritten := tarTypes[h.Typeflag] if !unwritten { @@ -89,7 +89,7 @@ func (s *archiveStage) tarEntry(ctx context.Context, h *tar.Header, r io.Reader, return dispatch.PartItem(dispatch.Found{Path: path, Name: h.Name, Where: where}), nil } -func (s *archiveStage) gzip(ctx context.Context, p dispatch.Part, dir string, yield func(dispatch.Item, error) bool) { +func (s *ArchiveStage) gzip(ctx context.Context, p dispatch.Part, dir string, yield func(dispatch.Item, error) bool) { f, err := os.Open(p.Path) if err != nil { yield(dispatch.Item{}, fmt.Errorf("archive stage: %w", err)) @@ -109,7 +109,7 @@ func (s *archiveStage) gzip(ctx context.Context, p dispatch.Part, dir string, yi s.content(ctx, p, dir, "gzip content "+name, name, zr, yield) } -func (s *archiveStage) bzip2(ctx context.Context, p dispatch.Part, dir string, yield func(dispatch.Item, error) bool) { +func (s *ArchiveStage) bzip2(ctx context.Context, p dispatch.Part, dir string, yield func(dispatch.Item, error) bool) { f, err := os.Open(p.Path) if err != nil { yield(dispatch.Item{}, fmt.Errorf("archive stage: %w", err)) @@ -120,7 +120,7 @@ func (s *archiveStage) bzip2(ctx context.Context, p dispatch.Part, dir string, y s.content(ctx, p, dir, "bzip2 content "+name, name, bzip2.NewReader(f), yield) } -func (s *archiveStage) content(ctx context.Context, p dispatch.Part, dir, where, name string, r io.Reader, yield func(dispatch.Item, error) bool) { +func (s *ArchiveStage) content(ctx context.Context, p dispatch.Part, dir, where, name string, r io.Reader, yield func(dispatch.Item, error) bool) { compressed := uint64(p.Size) path, written, why, err := s.extract(ctx, copyFrom(r), dir, compressed, func(_ *bombWriter, copyErr error) error { if copyErr != nil { diff --git a/stages/text.go b/stages/internal/adapter/text.go similarity index 97% rename from stages/text.go rename to stages/internal/adapter/text.go index f1d746bb..1ed4b70d 100644 --- a/stages/text.go +++ b/stages/internal/adapter/text.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "bufio" @@ -51,7 +51,8 @@ type textStage struct { id dispatch.Identity } -func newTextStage() *textStage { +// NewTextStage returns the text stage, route.Text's: text decoded to UTF-8. +func NewTextStage() dispatch.Stage { hash, err := dispatch.HashConfig(struct { Adapter string `json:"adapter"` }{textVersion}) diff --git a/stages/video.go b/stages/internal/adapter/video.go similarity index 79% rename from stages/video.go rename to stages/internal/adapter/video.go index 83ed119e..26162633 100644 --- a/stages/video.go +++ b/stages/internal/adapter/video.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "context" @@ -15,14 +15,19 @@ import ( const videoVersion = "2" -type videoConfig struct { +// VideoConfig is what [NewVideoStage] builds the video stage over: Streamer is required; Version is +// its tools' version lines; Request is every part's windows' and frames' request; and Memory is the +// tools' memory bound in bytes, zero for none. +type VideoConfig struct { Streamer *media.Streamer Version string Request media.Request Memory int64 } -type videoStage struct { +// VideoStage is the video stage, route.Video's: the plan record, then frames and windows from one +// ffmpeg run. +type VideoStage struct { streamer *media.Streamer request media.Request plan media.VideoPlan @@ -30,9 +35,10 @@ type videoStage struct { id dispatch.Identity } -func newVideoStage(cfg videoConfig) *videoStage { +// NewVideoStage returns the video stage over cfg, panicking on a nil Streamer. +func NewVideoStage(cfg VideoConfig) *VideoStage { if cfg.Streamer == nil { - panic("stages: videoConfig.Streamer is nil") + panic("stages: VideoConfig.Streamer is nil") } req := cfg.Request plan, err := req.Plan() @@ -40,7 +46,7 @@ func newVideoStage(cfg videoConfig) *videoStage { panic(err) } req.Dir = "" - return &videoStage{ + return &VideoStage{ streamer: cfg.Streamer, request: req, plan: plan, memory: cfg.Memory, id: identity("video", cfg.Version, struct { Stage string `json:"stage"` @@ -49,9 +55,11 @@ func newVideoStage(cfg videoConfig) *videoStage { } } -func (s *videoStage) Identity() dispatch.Identity { return s.id } +// Identity is the stage's identity, its request resolved. +func (s *VideoStage) Identity() dispatch.Identity { return s.id } -func (s *videoStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { +// Prepare prepares p, a video part, into dir. +func (s *VideoStage) Prepare(ctx context.Context, p dispatch.Part, dir string) iter.Seq2[dispatch.Item, error] { return func(yield func(dispatch.Item, error) bool) { src := filepath.Join(dir, "source") if err := linkOrCopy(p.Path, src); err != nil { @@ -75,7 +83,7 @@ func (s *videoStage) Prepare(ctx context.Context, p dispatch.Part, dir string) i if err != nil { err = fmt.Errorf("video stage: %w", err) if !planned { - yield(dispatch.Item{}, partErr(ctx, err, s.memory)) + yield(dispatch.Item{}, PartErr(ctx, err, s.memory)) return } warning, runErr := unitWarning(ctx, "ffmpeg", "stream", err, s.memory) diff --git a/stages/vision.go b/stages/internal/adapter/vision.go similarity index 70% rename from stages/vision.go rename to stages/internal/adapter/vision.go index 59ea57a5..d1982314 100644 --- a/stages/vision.go +++ b/stages/internal/adapter/vision.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "context" @@ -23,30 +23,37 @@ type exifReader interface { Metadata(ctx context.Context, path string, kind route.Kind) (*metadata.Picture, error) } -type visionConfig struct { +// VisionConfig is what [NewVisionStage] builds the vision stage over: EXIF is required; Version is +// its tool's version line; and Memory is the tool's memory bound in bytes, zero for none. +type VisionConfig struct { EXIF exifReader Version string Memory int64 } -type visionStage struct { +// VisionStage is the vision stage, route.Vision's: a picture's metadata record, then the picture +// passed through. +type VisionStage struct { exif exifReader memory int64 id dispatch.Identity } -func newVisionStage(cfg visionConfig) *visionStage { +// NewVisionStage returns the vision stage over cfg, panicking on a nil EXIF. +func NewVisionStage(cfg VisionConfig) *VisionStage { if cfg.EXIF == nil { - panic("stages: visionConfig.EXIF is nil") + panic("stages: VisionConfig.EXIF is nil") } - return &visionStage{exif: cfg.EXIF, memory: cfg.Memory, id: identity("vision", cfg.Version, struct { + return &VisionStage{exif: cfg.EXIF, memory: cfg.Memory, id: identity("vision", cfg.Version, struct { Stage string `json:"stage"` }{visionVersion})} } -func (s *visionStage) Identity() dispatch.Identity { return s.id } +// Identity is the stage's identity. +func (s *VisionStage) Identity() dispatch.Identity { return s.id } -func (s *visionStage) Prepare(ctx context.Context, p dispatch.Part, _ string) iter.Seq2[dispatch.Item, error] { +// Prepare passes p, a picture, through. +func (s *VisionStage) Prepare(ctx context.Context, p dispatch.Part, _ string) iter.Seq2[dispatch.Item, error] { return func(yield func(dispatch.Item, error) bool) { mime, ok := visionTypes[p.ContentType.Kind] if !ok { diff --git a/stages/zip.go b/stages/internal/adapter/zip.go similarity index 93% rename from stages/zip.go rename to stages/internal/adapter/zip.go index 4d7ef4b2..6a41f2e3 100644 --- a/stages/zip.go +++ b/stages/internal/adapter/zip.go @@ -1,4 +1,4 @@ -package stages +package adapter import ( "archive/zip" @@ -24,7 +24,7 @@ var zipDecompressors = map[uint16]zip.Decompressor{ zipBzip2: func(r io.Reader) io.ReadCloser { return io.NopCloser(bzip2.NewReader(r)) }, } -func (s *archiveStage) zip(ctx context.Context, p dispatch.Part, dir string, yield func(dispatch.Item, error) bool) { +func (s *ArchiveStage) zip(ctx context.Context, p dispatch.Part, dir string, yield func(dispatch.Item, error) bool) { zr, err := zip.OpenReader(p.Path) if err != nil && !errors.Is(err, zip.ErrInsecurePath) { if _, ok := errors.AsType[*fs.PathError](err); !ok { @@ -61,7 +61,7 @@ func (s *archiveStage) zip(ctx context.Context, p dispatch.Part, dir string, yie } } -func (s *archiveStage) zipEntry(ctx context.Context, archive string, f *zip.File, dir string) (dispatch.Item, error) { +func (s *ArchiveStage) zipEntry(ctx context.Context, archive string, f *zip.File, dir string) (dispatch.Item, error) { where := "zip entry " + f.Name typ := inspect.FileEntry if f.Mode()&fs.ModeSymlink != 0 { @@ -82,7 +82,7 @@ func (s *archiveStage) zipEntry(ctx context.Context, archive string, f *zip.File return dispatch.PartItem(dispatch.Found{Path: path, Name: f.Name, Where: where}), nil } -func (s *archiveStage) zipWrite(ctx context.Context, archive string, f *zip.File, dir string) (path string, written uint64, why, err error) { +func (s *ArchiveStage) zipWrite(ctx context.Context, archive string, f *zip.File, dir string) (path string, written uint64, why, err error) { var fill func(io.Writer) error switch decompress, standard := zipDecompressors[f.Method]; { case f.Method == zip.Store || standard: diff --git a/stages/office_test.go b/stages/office_test.go index 102a92d7..0277962b 100644 --- a/stages/office_test.go +++ b/stages/office_test.go @@ -21,11 +21,11 @@ import ( "github.com/standards-lab/docproc/office" "github.com/standards-lab/docproc/picture" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) -func standinOfficeStage(t *testing.T, s onenoteSettings) *stages.OfficeStage { +func standinOfficeStage(t *testing.T, s onenoteSettings) *adapter.OfficeStage { t.Helper() spec := office.OfficeSpec() spec.Program = tooltest.Link(t, t.TempDir(), "docproc-ooxml", s) @@ -33,12 +33,12 @@ func standinOfficeStage(t *testing.T, s onenoteSettings) *stages.OfficeStage { if err != nil { t.Fatal(err) } - pc := stages.PictureConverter(standinPictureStage(t, pictureListing, 1)) + pc := standinPictureStage(t, pictureListing, 1).Converter() c, err := office.NewConverter(t.Context(), office.Config{Office: of, Pictures: pc}) if err != nil { t.Fatal(err) } - return stages.NewOfficeStage(stages.OfficeConfig{Converter: c, Version: stages.Versions(of)}) + return adapter.NewOfficeStage(adapter.OfficeConfig{Converter: c, Version: adapter.Versions(of)}) } func TestOfficeStageSheets(t *testing.T) { @@ -132,9 +132,9 @@ func TestOfficeStageSheets(t *testing.T) { func TestOfficeStageIdentity(t *testing.T) { t.Parallel() base := standinOfficeStage(t, onenoteSettings{}) - c := stages.OfficeConverter(base) - same := stages.NewOfficeStage(stages.OfficeConfig{Converter: c, Version: base.Identity().Version, MetafileScale: picture.DefaultMetafileScale}) - scaled := stages.NewOfficeStage(stages.OfficeConfig{Converter: c, Version: base.Identity().Version, MetafileScale: 5}) + c := base.Converter() + same := adapter.NewOfficeStage(adapter.OfficeConfig{Converter: c, Version: base.Identity().Version, MetafileScale: picture.DefaultMetafileScale}) + scaled := adapter.NewOfficeStage(adapter.OfficeConfig{Converter: c, Version: base.Identity().Version, MetafileScale: 5}) if same.Identity() != base.Identity() || scaled.Identity().Config == base.Identity().Config { t.Errorf("identities %v, %v, %v", base.Identity(), same.Identity(), scaled.Identity()) } @@ -168,11 +168,11 @@ func TestOfficeStageUnread(t *testing.T) { if err != nil { t.Fatal(err) } - conv, err := office.NewConverter(t.Context(), office.Config{Office: of, Pictures: stages.PictureConverter(standinPictureStage(t, pictureListing, 1))}) + conv, err := office.NewConverter(t.Context(), office.Config{Office: of, Pictures: standinPictureStage(t, pictureListing, 1).Converter()}) if err != nil { t.Fatal(err) } - stage := stages.NewOfficeStage(stages.OfficeConfig{Converter: conv, Version: stages.Versions(of)}) + stage := adapter.NewOfficeStage(adapter.OfficeConfig{Converter: conv, Version: adapter.Versions(of)}) d := newDispatcher(t, dispatch.Stages{route.Office: stage}, dispatch.NewMemoryIndex(0)) events := dispatchAll(t, d, input(t, c.name, c.content), nil) wantSteps(t, events, []step{{c.name, 0, c.outcome}}) diff --git a/stages/onenote_test.go b/stages/onenote_test.go index 64608b8d..01d7ad46 100644 --- a/stages/onenote_test.go +++ b/stages/onenote_test.go @@ -19,7 +19,7 @@ import ( "github.com/standards-lab/docproc/internal/cli" "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/onenote" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) @@ -82,7 +82,7 @@ func envelopeRun(r tooltest.Run, minimum string) int { return s.Exit } -func standinOneNoteStage(t *testing.T, s onenoteSettings) (*stages.OneNoteStage, string) { +func standinOneNoteStage(t *testing.T, s onenoteSettings) (*adapter.OneNoteStage, string) { t.Helper() spec := onenote.OneNoteSpec() link := tooltest.Link(t, t.TempDir(), "docproc-onenote", s) @@ -95,7 +95,7 @@ func standinOneNoteStage(t *testing.T, s onenoteSettings) (*stages.OneNoteStage, if err != nil { t.Fatal(err) } - return stages.NewOneNoteStage(stages.OneNoteConfig{Reader: r, Version: stages.Versions(tl)}), link + return adapter.NewOneNoteStage(adapter.OneNoteConfig{Reader: r, Version: adapter.Versions(tl)}), link } func prepare(t *testing.T, stage dispatch.Stage) ([]dispatch.Item, error) { diff --git a/stages/picture_metadata_test.go b/stages/picture_metadata_test.go index fdbd0247..ea91d4a4 100644 --- a/stages/picture_metadata_test.go +++ b/stages/picture_metadata_test.go @@ -20,7 +20,7 @@ import ( "github.com/standards-lab/docproc/metadata" "github.com/standards-lab/docproc/picture" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) @@ -66,10 +66,10 @@ func standinEXIF(t *testing.T, settings pictureSettings) (*tool.Tool, *picture.E return mg, r } -func standinVisionStage(t *testing.T, settings pictureSettings) *stages.VisionStage { +func standinVisionStage(t *testing.T, settings pictureSettings) *adapter.VisionStage { t.Helper() mg, r := standinEXIF(t, settings) - return stages.NewVisionStage(stages.VisionConfig{EXIF: r, Version: stages.Versions(mg)}) + return adapter.NewVisionStage(adapter.VisionConfig{EXIF: r, Version: adapter.Versions(mg)}) } func magickGoldens(t *testing.T, fixtures ...string) map[string]string { @@ -212,16 +212,16 @@ func TestVisionStagePassesThrough(t *testing.T) { func TestNewVisionStageNil(t *testing.T) { t.Parallel() - wantPanic(t, "stages: visionConfig.EXIF is nil", func() { stages.NewVisionStage(stages.VisionConfig{Version: "magick 7.1.2"}) }) - c := stages.PictureConverter(standinPictureStage(t, pictureListing, 1)) - wantPanic(t, "stages: pictureConfig.EXIF is nil", func() { - stages.NewPictureStage(stages.PictureConfig{Converter: c, Version: "magick 7.1.2"}) + wantPanic(t, "stages: VisionConfig.EXIF is nil", func() { adapter.NewVisionStage(adapter.VisionConfig{Version: "magick 7.1.2"}) }) + c := standinPictureStage(t, pictureListing, 1).Converter() + wantPanic(t, "stages: PictureConfig.EXIF is nil", func() { + adapter.NewPictureStage(adapter.PictureConfig{Converter: c, Version: "magick 7.1.2"}) }) } func TestPictureMetadataContentError(t *testing.T) { t.Parallel() - content, reason := stages.Classify(t.Context(), fmt.Errorf("picture: magick: x.jpg's EXIF: %w", picture.ErrMetadata), 0) + content, reason := adapter.Classify(t.Context(), fmt.Errorf("picture: magick: x.jpg's EXIF: %w", picture.ErrMetadata), 0) if !content || reason == "" { t.Errorf("ErrMetadata: content %t, %q; want a content error", content, reason) } diff --git a/stages/picture_test.go b/stages/picture_test.go index d7f234e6..f3b5df09 100644 --- a/stages/picture_test.go +++ b/stages/picture_test.go @@ -15,7 +15,7 @@ import ( "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/picture" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) @@ -86,12 +86,12 @@ func sofficeStandin(r tooltest.Run) int { return 2 } -func standinPictureStage(t *testing.T, listing string, pages int) *stages.PictureStage { +func standinPictureStage(t *testing.T, listing string, pages int) *adapter.PictureStage { t.Helper() return pictureStageOver(t, pictureSettings{Formats: listing, Pages: pages}) } -func pictureStageOver(t *testing.T, settings pictureSettings) *stages.PictureStage { +func pictureStageOver(t *testing.T, settings pictureSettings) *adapter.PictureStage { t.Helper() mg, r := standinEXIF(t, settings) spec := picture.LibreOfficeSpec() @@ -104,7 +104,7 @@ func pictureStageOver(t *testing.T, settings pictureSettings) *stages.PictureSta if err != nil { t.Fatal(err) } - s := stages.NewPictureStage(stages.PictureConfig{Converter: c, EXIF: r, Version: stages.Versions(mg)}) + s := adapter.NewPictureStage(adapter.PictureConfig{Converter: c, EXIF: r, Version: adapter.Versions(mg)}) return s } diff --git a/stages/sevenzip_standin_test.go b/stages/sevenzip_standin_test.go index 8334494b..57b06068 100644 --- a/stages/sevenzip_standin_test.go +++ b/stages/sevenzip_standin_test.go @@ -14,7 +14,7 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/sevenzip" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) @@ -60,7 +60,7 @@ func standinSevenZip(t *testing.T, settings sevenZipSettings) (*dispatch.Dispatc if err != nil { t.Fatal(err) } - d, _, work := archiveDispatcherWith(t, stages.ArchiveConfig{SevenZip: r, Version: stages.Versions(tl)}) + d, _, work := archiveDispatcherWith(t, adapter.ArchiveConfig{SevenZip: r, Version: adapter.Versions(tl)}) return d, link, work } diff --git a/stages/sevenzip_test.go b/stages/sevenzip_test.go index e2fa7749..e17d92ca 100644 --- a/stages/sevenzip_test.go +++ b/stages/sevenzip_test.go @@ -13,7 +13,7 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/inspect" "github.com/standards-lab/docproc/sevenzip" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" ) const sevenZipSignature = "7z\xbc\xaf\x27\x1c\x00\x04" @@ -84,7 +84,7 @@ func TestListingQuarantine(t *testing.T) { } strict := inspect.Options{Policy: map[inspect.Check]inspect.Verdict{inspect.ArchiveTraversal: inspect.Quarantine}} sz := fake() - d, zs, work := archiveDispatcherWith(t, stages.ArchiveConfig{Inspect: strict, SevenZip: sz, Version: "7zz 26.5"}) + d, zs, work := archiveDispatcherWith(t, adapter.ArchiveConfig{Inspect: strict, SevenZip: sz, Version: "7zz 26.5"}) events := dispatchAll(t, d, input(t, "a.7z", sevenZipSignature), nil) wantSteps(t, events, []step{{"a.7z", 0, dispatch.Quarantined}}) ev := events[0] @@ -99,7 +99,7 @@ func TestListingQuarantine(t *testing.T) { wantEmpty(t, work) sz = fake() - d, _, work = archiveDispatcherWith(t, stages.ArchiveConfig{SevenZip: sz, Version: "7zz 26.5"}) + d, _, work = archiveDispatcherWith(t, adapter.ArchiveConfig{SevenZip: sz, Version: "7zz 26.5"}) events = dispatchAll(t, d, input(t, "a.7z", sevenZipSignature), nil) wantSteps(t, events, []step{ {"notes.txt", 1, dispatch.NoProcessor}, @@ -124,7 +124,7 @@ func TestListedMismatch(t *testing.T) { entries[0].Size = 100 entries[1].CRC, entries[1].HasCRC = 0xdeadbeef, true sz := &fakeSevenZip{listing: sevenzip.Listing{Entries: entries}, contents: contents} - d, _, work := archiveDispatcherWith(t, stages.ArchiveConfig{SevenZip: sz, Version: "7zz 26.5"}) + d, _, work := archiveDispatcherWith(t, adapter.ArchiveConfig{SevenZip: sz, Version: "7zz 26.5"}) events := dispatchAll(t, d, input(t, "a.7z", sevenZipSignature), nil) wantSteps(t, events, []step{{"short.txt", 1, dispatch.Failed}, {"crc.txt", 1, dispatch.Failed}, {"a.7z", 0, dispatch.Prepared}}) for i, want := range []string{"6 bytes written, 100 listed", "CRC-32 "} { @@ -144,7 +144,7 @@ func TestListedFailures(t *testing.T) { {fmt.Errorf("sevenzip: list: %w: Cannot open the file as [7z] archive", sevenzip.ErrNotArchive), dispatch.Failed}, } { sz := &fakeSevenZip{listErr: c.err} - d, _, work := archiveDispatcherWith(t, stages.ArchiveConfig{SevenZip: sz, Version: "7zz 26.5"}) + d, _, work := archiveDispatcherWith(t, adapter.ArchiveConfig{SevenZip: sz, Version: "7zz 26.5"}) events := dispatchAll(t, d, input(t, "a.7z", sevenZipSignature), nil) wantSteps(t, events, []step{{"a.7z", 0, c.outcome}}) if len(sz.extracted) != 0 || !strings.Contains(events[0].Reason, "a 7z archive") && c.outcome == dispatch.Encrypted { diff --git a/stages/stages.go b/stages/stages.go index b08e25f6..a6407580 100644 --- a/stages/stages.go +++ b/stages/stages.go @@ -19,6 +19,7 @@ import ( "github.com/standards-lab/docproc/picture" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/sevenzip" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) @@ -147,17 +148,19 @@ type stage struct { build func(ctx context.Context, t tools, opts Options) (dispatch.Stage, error) } +var needs = adapter.Needs() + var table = []stage{ - {route.Document, []string{"gs", "qpdf", "pdfdetach", "pdftotext", "pdfinfo"}, buildDocument}, - {route.Office, []string{"docproc-ooxml", "soffice", "magick"}, buildOffice}, - {route.VisionConverted, []string{"magick", "soffice"}, buildPicture}, - {route.Vision, []string{"magick"}, buildVision}, - {route.Nested, []string{"docproc-mail"}, buildEmail}, - {route.OneNote, []string{"docproc-onenote"}, buildOneNote}, - {route.Archive, []string{"7zz"}, buildArchive}, - {route.Audio, []string{"ffmpeg", "ffprobe"}, buildAudio}, - {route.Video, []string{"ffmpeg", "ffprobe"}, buildVideo}, - {route.Text, nil, func(context.Context, tools, Options) (dispatch.Stage, error) { return newTextStage(), nil }}, + {route.Document, needs[route.Document], buildDocument}, + {route.Office, needs[route.Office], buildOffice}, + {route.VisionConverted, needs[route.VisionConverted], buildPicture}, + {route.Vision, needs[route.Vision], buildVision}, + {route.Nested, needs[route.Nested], buildEmail}, + {route.OneNote, needs[route.OneNote], buildOneNote}, + {route.Archive, needs[route.Archive], buildArchive}, + {route.Audio, needs[route.Audio], buildAudio}, + {route.Video, needs[route.Video], buildVideo}, + {route.Text, needs[route.Text], func(context.Context, tools, Options) (dispatch.Stage, error) { return adapter.NewTextStage(), nil }}, } // Routes returns the ten routes docproc wires a stage for, in the stage table's order. @@ -264,7 +267,7 @@ func Build(ctx context.Context, lookup Lookup, opts Options) (Set, error) { for _, program := range s.needs { ts = append(ts, built[program]) } - row.Tools = versions(ts...) + row.Tools = adapter.Versions(ts...) set.Stages[s.route] = st } set.Rows = append(set.Rows, row) @@ -316,9 +319,9 @@ func buildDocument(_ context.Context, t tools, opts Options) (dispatch.Stage, er } req := opts.Document req.Concurrency = opts.concurrency() - return newDocumentStage(documentConfig{ + return adapter.NewDocumentStage(adapter.DocumentConfig{ Preparer: document.NewPreparer(cfg), QPDF: q, PDFDetach: detach, PDFInfo: info, - Version: versions(gs, qt, dt, tt, it), Request: req, Inspect: opts.Inspect, Memory: opts.Memory, + Version: adapter.Versions(gs, qt, dt, tt, it), Request: req, Inspect: opts.Inspect, Memory: opts.Memory, }), nil } @@ -336,8 +339,8 @@ func buildOffice(ctx context.Context, t tools, opts Options) (dispatch.Stage, er if err != nil { return nil, err } - return newOfficeStage(officeConfig{ - Converter: c, Version: versions(of, t["soffice"], t["magick"]), + return adapter.NewOfficeStage(adapter.OfficeConfig{ + Converter: c, Version: adapter.Versions(of, t["soffice"], t["magick"]), MetafileScale: opts.Picture.MetafileScale, Memory: opts.Memory, }), nil } @@ -351,8 +354,8 @@ func buildPicture(ctx context.Context, t tools, opts Options) (dispatch.Stage, e if err != nil { return nil, err } - return newPictureStage(pictureConfig{ - Converter: p, EXIF: r, Version: versions(t["magick"], t["soffice"]), Request: opts.Picture, Memory: opts.Memory, + return adapter.NewPictureStage(adapter.PictureConfig{ + Converter: p, EXIF: r, Version: adapter.Versions(t["magick"], t["soffice"]), Request: opts.Picture, Memory: opts.Memory, }), nil } @@ -362,7 +365,7 @@ func buildVision(_ context.Context, t tools, opts Options) (dispatch.Stage, erro if err != nil { return nil, err } - return newVisionStage(visionConfig{EXIF: r, Version: versions(mg), Memory: opts.Memory}), nil + return adapter.NewVisionStage(adapter.VisionConfig{EXIF: r, Version: adapter.Versions(mg), Memory: opts.Memory}), nil } func buildEmail(_ context.Context, t tools, opts Options) (dispatch.Stage, error) { @@ -371,7 +374,7 @@ func buildEmail(_ context.Context, t tools, opts Options) (dispatch.Stage, error if err != nil { return nil, err } - return newEmailStage(emailConfig{Reader: r, Version: versions(mail), Memory: opts.Memory}), nil + return adapter.NewEmailStage(adapter.EmailConfig{Reader: r, Version: adapter.Versions(mail), Memory: opts.Memory}), nil } func buildOneNote(_ context.Context, t tools, opts Options) (dispatch.Stage, error) { @@ -380,7 +383,7 @@ func buildOneNote(_ context.Context, t tools, opts Options) (dispatch.Stage, err if err != nil { return nil, err } - return newOneNoteStage(onenoteConfig{Reader: r, Version: versions(on), Memory: opts.Memory}), nil + return adapter.NewOneNoteStage(adapter.OneNoteConfig{Reader: r, Version: adapter.Versions(on), Memory: opts.Memory}), nil } func buildArchive(_ context.Context, t tools, opts Options) (dispatch.Stage, error) { @@ -389,7 +392,7 @@ func buildArchive(_ context.Context, t tools, opts Options) (dispatch.Stage, err if err != nil { return nil, err } - return newArchiveStage(archiveConfig{SevenZip: r, Version: versions(sz), Inspect: opts.Inspect, Memory: opts.Memory}), nil + return adapter.NewArchiveStage(adapter.ArchiveConfig{SevenZip: r, Version: adapter.Versions(sz), Inspect: opts.Inspect, Memory: opts.Memory}), nil } func buildAudio(_ context.Context, t tools, opts Options) (dispatch.Stage, error) { @@ -400,7 +403,7 @@ func buildAudio(_ context.Context, t tools, opts Options) (dispatch.Stage, error } req := opts.Audio req.Concurrency = opts.concurrency() - return newAudioStage(audioConfig{Splitter: s, Version: versions(ff, fp), Request: req, Memory: opts.Memory}), nil + return adapter.NewAudioStage(adapter.AudioConfig{Splitter: s, Version: adapter.Versions(ff, fp), Request: req, Memory: opts.Memory}), nil } func buildVideo(_ context.Context, t tools, opts Options) (dispatch.Stage, error) { @@ -409,5 +412,5 @@ func buildVideo(_ context.Context, t tools, opts Options) (dispatch.Stage, error if err != nil { return nil, err } - return newVideoStage(videoConfig{Streamer: s, Version: versions(ff, fp), Request: opts.Video, Memory: opts.Memory}), nil + return adapter.NewVideoStage(adapter.VideoConfig{Streamer: s, Version: adapter.Versions(ff, fp), Request: opts.Video, Memory: opts.Memory}), nil } diff --git a/stages/stages_test.go b/stages/stages_test.go index 21b1dc7c..cbbca8f1 100644 --- a/stages/stages_test.go +++ b/stages/stages_test.go @@ -18,6 +18,7 @@ import ( "github.com/standards-lab/docproc/picture" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" ) func TestParseRoutes(t *testing.T) { @@ -213,22 +214,24 @@ func TestBuildRefuses(t *testing.T) { func TestStagesPanic(t *testing.T) { t.Parallel() for want, build := range map[string]func(){ - "stages: documentConfig.Preparer is nil": func() { stages.NewDocumentStage(stages.DocumentConfig{Version: "gs"}) }, - "stages: documentConfig.QPDF is nil": func() { stages.NewDocumentStage(stages.DocumentConfig{Preparer: &document.Preparer{}, Version: "gs"}) }, - "stages: documentConfig.PDFDetach is nil": func() { - stages.NewDocumentStage(stages.DocumentConfig{Preparer: &document.Preparer{}, QPDF: &fakeQPDF{}}) + "stages: DocumentConfig.Preparer is nil": func() { adapter.NewDocumentStage(adapter.DocumentConfig{Version: "gs"}) }, + "stages: DocumentConfig.QPDF is nil": func() { + adapter.NewDocumentStage(adapter.DocumentConfig{Preparer: &document.Preparer{}, Version: "gs"}) }, - "stages: documentConfig.PDFInfo is nil": func() { - stages.NewDocumentStage(stages.DocumentConfig{Preparer: &document.Preparer{}, QPDF: &fakeQPDF{}, PDFDetach: &fakeDetach{}}) + "stages: DocumentConfig.PDFDetach is nil": func() { + adapter.NewDocumentStage(adapter.DocumentConfig{Preparer: &document.Preparer{}, QPDF: &fakeQPDF{}}) }, - "stages: officeConfig.Converter is nil": func() { stages.NewOfficeStage(stages.OfficeConfig{Version: "x"}) }, - "stages: pictureConfig.Converter is nil": func() { stages.NewPictureStage(stages.PictureConfig{Version: "x"}) }, - "stages: emailConfig.Reader is nil": func() { stages.NewEmailStage(stages.EmailConfig{Version: "x"}) }, - "stages: onenoteConfig.Reader is nil": func() { stages.NewOneNoteStage(stages.OneNoteConfig{Version: "x"}) }, - "stages: archiveConfig.SevenZip is nil": func() { stages.NewArchiveStage(stages.ArchiveConfig{Version: "x"}) }, - "stages: audioConfig.Splitter is nil": func() { stages.NewAudioStage(stages.AudioConfig{Version: "x"}) }, - "stages: videoConfig.Streamer is nil": func() { stages.NewVideoStage(stages.VideoConfig{Version: "x"}) }, - "stages: archive stage: no version": func() { stages.NewArchiveStage(stages.ArchiveConfig{SevenZip: &fakeSevenZip{}}) }, + "stages: DocumentConfig.PDFInfo is nil": func() { + adapter.NewDocumentStage(adapter.DocumentConfig{Preparer: &document.Preparer{}, QPDF: &fakeQPDF{}, PDFDetach: &fakeDetach{}}) + }, + "stages: OfficeConfig.Converter is nil": func() { adapter.NewOfficeStage(adapter.OfficeConfig{Version: "x"}) }, + "stages: PictureConfig.Converter is nil": func() { adapter.NewPictureStage(adapter.PictureConfig{Version: "x"}) }, + "stages: EmailConfig.Reader is nil": func() { adapter.NewEmailStage(adapter.EmailConfig{Version: "x"}) }, + "stages: OneNoteConfig.Reader is nil": func() { adapter.NewOneNoteStage(adapter.OneNoteConfig{Version: "x"}) }, + "stages: ArchiveConfig.SevenZip is nil": func() { adapter.NewArchiveStage(adapter.ArchiveConfig{Version: "x"}) }, + "stages: AudioConfig.Splitter is nil": func() { adapter.NewAudioStage(adapter.AudioConfig{Version: "x"}) }, + "stages: VideoConfig.Streamer is nil": func() { adapter.NewVideoStage(adapter.VideoConfig{Version: "x"}) }, + "stages: archive stage: no version": func() { adapter.NewArchiveStage(adapter.ArchiveConfig{SevenZip: &fakeSevenZip{}}) }, } { wantPanic(t, want, build) } diff --git a/stages/tar_test.go b/stages/tar_test.go index 768e968b..b7cf2c03 100644 --- a/stages/tar_test.go +++ b/stages/tar_test.go @@ -14,7 +14,7 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/inspect" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" ) func inspectFixture(name string) string { return filepath.Join(inspectFixtures, name) } @@ -131,7 +131,7 @@ func TestTarUnsafe(t *testing.T) { } } -func checkUnsafe(t *testing.T, stage *stages.ArchiveStage, path, root, work string, parts []string, children map[string]inspect.Check) { +func checkUnsafe(t *testing.T, stage *adapter.ArchiveStage, path, root, work string, parts []string, children map[string]inspect.Check) { t.Helper() fixture := filepath.Base(path) d, err := dispatch.New(dispatch.Config{ diff --git a/stages/text_test.go b/stages/text_test.go index d9b71d38..cb4c793f 100644 --- a/stages/text_test.go +++ b/stages/text_test.go @@ -12,7 +12,7 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" ) func prepareText(t *testing.T, ctx context.Context, name string, content []byte) (dispatch.Output, string, string, []string, error) { @@ -23,7 +23,7 @@ func prepareText(t *testing.T, ctx context.Context, name string, content []byte) } var outputs []dispatch.Output var warnings []string - for item, err := range stages.NewTextStage().Prepare(ctx, dispatch.Part{Path: path, Name: name}, t.TempDir()) { + for item, err := range adapter.NewTextStage().Prepare(ctx, dispatch.Part{Path: path, Name: name}, t.TempDir()) { switch { case err != nil: return dispatch.Output{}, "", path, nil, err @@ -137,7 +137,7 @@ func TestTextDispatch(t *testing.T) { work := t.TempDir() d, err := dispatch.New(dispatch.Config{ Content: dispatch.NewMemoryContent(), Puts: 2, - Stages: dispatch.Stages{route.Text: stages.NewTextStage()}, + Stages: dispatch.Stages{route.Text: adapter.NewTextStage()}, Index: dispatch.NewMemoryIndex(0), Dir: work, }) if err != nil { @@ -161,7 +161,7 @@ func TestTextDispatch(t *testing.T) { } }) ev := events[len(events)-1] - if ev.Part.ContentType.Route != route.Text || ev.Outcome != dispatch.Prepared || ev.Stage != stages.NewTextStage().Identity() || len(ev.Outputs) != 1 { + if ev.Part.ContentType.Route != route.Text || ev.Outcome != dispatch.Prepared || ev.Stage != adapter.NewTextStage().Identity() || len(ev.Outputs) != 1 { t.Fatalf("%s: %s %s by %s, %d outputs", name, ev.Part.ContentType.Route, ev.Outcome, ev.Stage, len(ev.Outputs)) } if want := "café"; !strings.HasPrefix(text, want) { diff --git a/stages/video_containers_integration_test.go b/stages/video_containers_integration_test.go index 928eedf0..59580bad 100644 --- a/stages/video_containers_integration_test.go +++ b/stages/video_containers_integration_test.go @@ -12,7 +12,7 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/media" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) @@ -87,10 +87,10 @@ func TestVideoContainersReal(t *testing.T) { if err != nil { t.Fatal(err) } - version := stages.Versions(ffmpeg, ffprobe) + version := adapter.Versions(ffmpeg, ffprobe) d := newDispatcher(t, dispatch.Stages{ - route.Video: stages.NewVideoStage(stages.VideoConfig{Streamer: streamer, Version: version}), - route.Audio: stages.NewAudioStage(stages.AudioConfig{Splitter: splitter, Version: version, Request: audio.Request{Concurrency: 2}}), + route.Video: adapter.NewVideoStage(adapter.VideoConfig{Streamer: streamer, Version: version}), + route.Audio: adapter.NewAudioStage(adapter.AudioConfig{Splitter: splitter, Version: version, Request: audio.Request{Concurrency: 2}}), }, dispatch.NewMemoryIndex(0)) for _, c := range containerCases { t.Run(c.name, func(t *testing.T) { diff --git a/stages/video_integration_test.go b/stages/video_integration_test.go index 7b9d4b9c..a0814f6f 100644 --- a/stages/video_integration_test.go +++ b/stages/video_integration_test.go @@ -18,7 +18,7 @@ import ( "github.com/standards-lab/docproc/media" "github.com/standards-lab/docproc/metadata" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" "github.com/standards-lab/docproc/tool" ) @@ -127,7 +127,7 @@ func TestVideoStageReal(t *testing.T) { if err != nil { t.Fatal(err) } - stage := stages.NewVideoStage(stages.VideoConfig{Streamer: s, Version: stages.Versions(ffmpeg, ffprobe)}) + stage := adapter.NewVideoStage(adapter.VideoConfig{Streamer: s, Version: adapter.Versions(ffmpeg, ffprobe)}) wantFrames, wantWindows := streamed(t, s, path) d := newDispatcher(t, dispatch.Stages{route.Video: stage}, dispatch.NewMemoryIndex(0)) diff --git a/stages/video_test.go b/stages/video_test.go index 6d0a8c5f..08abc58a 100644 --- a/stages/video_test.go +++ b/stages/video_test.go @@ -28,7 +28,7 @@ import ( "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/media" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" ) func mediaStandin(args []string, settings ffSettings) int { @@ -99,7 +99,7 @@ var videoFrames = []mediatest.Frame{ {MS: 11200, Score: 0.05, Width: 32, Height: 18}, } -func testVideoStage(t *testing.T, probe string, req media.Request) (*stages.VideoStage, *ffStandins) { +func testVideoStage(t *testing.T, probe string, req media.Request) (*adapter.VideoStage, *ffStandins) { t.Helper() ffmpeg, ffprobe, standins := standinTools(t, probe) standins.set(t, func(s *ffSettings) { s.PCMMS, s.Frames = 3000, videoFrames }) @@ -107,7 +107,7 @@ func testVideoStage(t *testing.T, probe string, req media.Request) (*stages.Vide if err != nil { t.Fatal(err) } - st := stages.NewVideoStage(stages.VideoConfig{Streamer: s, Version: "ffmpeg 9.0.2, ffprobe 9.0.2", Request: req}) + st := adapter.NewVideoStage(adapter.VideoConfig{Streamer: s, Version: "ffmpeg 9.0.2, ffprobe 9.0.2", Request: req}) return st, standins } @@ -415,7 +415,7 @@ func TestVideoStageIdentity(t *testing.T) { const version = "ffmpeg 9.0.2, ffprobe 9.0.2" id := func(req media.Request) dispatch.Identity { t.Helper() - st := stages.NewVideoStage(stages.VideoConfig{Streamer: s, Version: version, Request: req}) + st := adapter.NewVideoStage(adapter.VideoConfig{Streamer: s, Version: version, Request: req}) return st.Identity() } base := id(media.Request{}) @@ -446,7 +446,7 @@ func TestVideoStageIdentity(t *testing.T) { t.Errorf("%s left the video identity's config unchanged", name) } } - wantPanic(t, "stages: videoConfig.Streamer is nil", func() { - stages.NewVideoStage(stages.VideoConfig{Version: version}) + wantPanic(t, "stages: VideoConfig.Streamer is nil", func() { + adapter.NewVideoStage(adapter.VideoConfig{Version: version}) }) } diff --git a/stages/zip_test.go b/stages/zip_test.go index 7cc689ef..213eb896 100644 --- a/stages/zip_test.go +++ b/stages/zip_test.go @@ -19,7 +19,7 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/inspect" "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" ) var inspectFixtures = filepath.Join("..", "inspect", "testdata") @@ -96,22 +96,22 @@ func (c *counting) Prepare(ctx context.Context, p dispatch.Part, dir string) ite return c.Stage.Prepare(ctx, p, dir) } -func testArchiveStage(t *testing.T, opts inspect.Options) *stages.ArchiveStage { +func testArchiveStage(t *testing.T, opts inspect.Options) *adapter.ArchiveStage { t.Helper() - return stages.NewArchiveStage(stages.ArchiveConfig{SevenZip: &fakeSevenZip{}, Version: "7-Zip (z) 26.06 (x64)", Inspect: opts}) + return adapter.NewArchiveStage(adapter.ArchiveConfig{SevenZip: &fakeSevenZip{}, Version: "7-Zip (z) 26.06 (x64)", Inspect: opts}) } func archiveDispatcher(t *testing.T, opts inspect.Options) (*dispatch.Dispatcher, *counting, string) { t.Helper() - return archiveDispatcherWith(t, stages.ArchiveConfig{Inspect: opts}) + return archiveDispatcherWith(t, adapter.ArchiveConfig{Inspect: opts}) } -func archiveDispatcherWith(t *testing.T, cfg stages.ArchiveConfig) (*dispatch.Dispatcher, *counting, string) { +func archiveDispatcherWith(t *testing.T, cfg adapter.ArchiveConfig) (*dispatch.Dispatcher, *counting, string) { t.Helper() return archiveDispatcherLimited(t, cfg, dispatch.Limits{}) } -func archiveDispatcherLimited(t *testing.T, cfg stages.ArchiveConfig, limits dispatch.Limits) (*dispatch.Dispatcher, *counting, string) { +func archiveDispatcherLimited(t *testing.T, cfg adapter.ArchiveConfig, limits dispatch.Limits) (*dispatch.Dispatcher, *counting, string) { t.Helper() if cfg.SevenZip == nil { cfg.SevenZip = &fakeSevenZip{} @@ -119,7 +119,7 @@ func archiveDispatcherLimited(t *testing.T, cfg stages.ArchiveConfig, limits dis if cfg.Version == "" { cfg.Version = "7-Zip (z) 26.06 (x64)" } - s := stages.NewArchiveStage(cfg) + s := adapter.NewArchiveStage(cfg) zs := &counting{Stage: s} work := t.TempDir() d, err := dispatch.New(dispatch.Config{ @@ -282,7 +282,7 @@ func TestZipUnsafeNames(t *testing.T) { func TestArchiveIdentity(t *testing.T) { id := func(opts inspect.Options) dispatch.Identity { t.Helper() - return stages.NewArchiveStage(stages.ArchiveConfig{SevenZip: &fakeSevenZip{}, Version: "7-Zip (z) 26.06 (x64)", Inspect: opts}).Identity() + return adapter.NewArchiveStage(adapter.ArchiveConfig{SevenZip: &fakeSevenZip{}, Version: "7-Zip (z) 26.06 (x64)", Inspect: opts}).Identity() } base := id(inspect.Options{}) if base.Name != "archive" || base.Version != "7-Zip (z) 26.06 (x64)" || len(base.Config) != 64 { From e49538d6e4861b7fe319c904a453e851b1403e8b Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 13:31:17 -0500 Subject: [PATCH 05/10] =?UTF-8?q?harness.layout=20=C2=B7=20docproc=20?= =?UTF-8?q?=C2=B7=20slice=205:=20the=20base=20module's=20tests=20into=20te?= =?UTF-8?q?st/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every base-module package's tests move, with git mv, into /test/ as _test, and each package's testdata into /test/testdata: 155 test files, the TestMain and integration-tagged suites among them, and twelve testdata trees. Helper packages (tooltest, goldentest, dispatchtest) stay where they are; their own tests move into their test/ directories. - stages' tests split by the API they drive: the ones over Build, Routes, and ParseRoutes (TestParseRoutes, the TestBuild* tests, TestBuiltConfigs, TestClassification, TestClassificationNoBound, TestBuildBounds, TestEveryFixture, TestBuiltIdentities) sit in stages/test; the adapters' (TestStagesPanic, TestClassify among them) in stages/internal/adapter/test, as adapter_test. - What both need, the stand-in of every program a stage runs, their settings, the stand-in office and picture stages, the dispatch helpers, and BuiltSet, is hoisted into stages/internal/stagestest, per the shared-helper rule; both TestMains pass tooltest.Main stagestest.Programs(). - A package reading another's fixtures names them through tooltest.Testdata(t, pkg, elem...), which finds the base module's root as Tools does and fails the test on a missing fixture, in place of ../ paths; the package-level fixture variables become functions of t, since a stand-in process runs the test binary outside the module. - The tools' goldens still go through tooltest.Tools, unchanged: with tools/ absent, every golden test skips naming the tree. tooltest's own TestTools and TestToolsMissingFile fail then, as they did before. - stages' fixture list moves to stages/test/testdata/fixtures.tsv with every base-module path under test/testdata; cmd/docproc's integration harness and its tests read it there. .gitattributes, the testdata READMEs and generators, docs/acceptance.md, docs/design-review.md, docs/packages.md, docs/api.md, and adapter's package comment follow the move. - document's pdfdetach test keys its Attachment literal: vet's composites check no longer treats document as the test's own package. go test -list . ./... names the same tests per module before and after, with and without -tags integration (565 and 677 in the base module). No CHANGELOG entry: no exported API changes. --- .gitattributes | 16 +- audio/{ => test}/audio_integration_test.go | 0 audio/{ => test}/audio_test.go | 0 audio/{ => test}/fixtures_test.go | 0 audio/{ => test}/floor_test.go | 0 audio/{ => test}/image_integration_test.go | 0 audio/{ => test}/levels_integration_test.go | 0 audio/{ => test}/live_test.go | 0 audio/{ => test}/main_test.go | 0 audio/{ => test}/plan_test.go | 0 audio/{ => test}/runners_test.go | 0 audio/{ => test}/testdata/README.md | 0 audio/{ => test}/testdata/speech-gain.wav | Bin .../testdata/speech-levels.truth.json | 0 audio/{ => test}/testdata/speech-noise.wav | Bin .../testdata/speech-scenes.ffprobe.json | 0 audio/{ => test}/testdata/speech-scenes.mkv | Bin .../testdata/speech-scenes.truth.json | 0 .../testdata/speech-tagged.ffprobe.json | 0 audio/{ => test}/testdata/speech-tagged.mp3 | Bin .../{ => test}/testdata/speech-truncated.mp3 | Bin audio/{ => test}/testdata/speech.flac | Bin audio/{ => test}/testdata/speech.truth.txt | 0 audio/{ => test}/testdata/windows-v0.9.0.txt | 0 audio/{ => test}/windows_integration_test.go | 0 audio/{ => test}/windows_test.go | 0 cmd/docproc/integration/fixtures_test.go | 6 +- cmd/docproc/integration/harness.go | 8 +- .../{ => test}/dispatchtest_test.go | 0 dispatch/dispatchtest/{ => test}/main_test.go | 0 dispatch/{ => test}/dispatch_test.go | 0 dispatch/{ => test}/golden_test.go | 0 dispatch/{ => test}/index_test.go | 0 dispatch/{ => test}/main_test.go | 0 dispatch/{ => test}/pool_test.go | 0 dispatch/{ => test}/release_test.go | 0 dispatch/{ => test}/stage_test.go | 16 +- dispatch/{ => test}/stream_test.go | 0 dispatch/{ => test}/testdata/dispatch.jsonl | 0 dispatch/{ => test}/testdata/log.jsonl | 0 dispatch/{ => test}/walk_test.go | 0 docs/acceptance.md | 2 +- docs/api.md | 2 + docs/design-review.md | 2 +- docs/packages.md | 1 + .../{ => test}/fixtures_integration_test.go | 0 .../ghostscript_integration_test.go | 0 document/{ => test}/ghostscript_test.go | 0 document/{ => test}/main_test.go | 0 document/{ => test}/pdfdetach_test.go | 2 +- document/{ => test}/pdfinfo_test.go | 0 .../{ => test}/pdftools_integration_test.go | 0 document/{ => test}/pdftotext_test.go | 0 .../{ => test}/prepare_integration_test.go | 0 document/{ => test}/prepare_test.go | 0 document/{ => test}/qpdf_test.go | 0 document/{ => test}/renderer_test.go | 0 document/{ => test}/testdata/README.md | 14 +- .../testdata/attachments/attachments.pdf | Bin .../testdata/attachments/generate.go | 6 +- document/{ => test}/testdata/clean.pdf | Bin document/{ => test}/testdata/clean.typ | 0 document/{ => test}/testdata/clean/page-1.txt | 0 document/{ => test}/testdata/clean/page-2.txt | 0 document/{ => test}/testdata/clean/page-3.txt | 0 document/{ => test}/testdata/clean/page-4.txt | 0 document/{ => test}/testdata/clean/page-5.txt | 0 document/{ => test}/testdata/clean/page-6.txt | 0 document/{ => test}/testdata/degraded.pdf | Bin .../{ => test}/testdata/degraded/page-1.txt | 0 .../{ => test}/testdata/degraded/page-2.txt | 0 .../{ => test}/testdata/degraded/page-3.txt | 0 .../{ => test}/testdata/degraded/page-4.txt | 0 .../{ => test}/testdata/degraded/page-5.txt | 0 .../{ => test}/testdata/degraded/page-6.txt | 0 .../{ => test}/testdata/degraded/page-7.txt | 0 .../{ => test}/testdata/degraded/page-8.txt | 0 .../{ => test}/testdata/degraded/page-9.txt | 0 .../{ => test}/testdata/forms/acroform.json | 0 .../{ => test}/testdata/forms/acroform.pdf | Bin .../{ => test}/testdata/forms/generate.go | 6 +- .../{ => test}/testdata/forms/signed.json | 0 document/{ => test}/testdata/forms/signed.pdf | Bin document/{ => test}/testdata/generate.sh | 2 +- .../{ => test}/testdata/info/clean.custom.txt | 0 .../{ => test}/testdata/info/clean.meta.xml | 0 .../testdata/info/clean.summary.txt | 0 document/{ => test}/testdata/info/generate.go | 6 +- .../{ => test}/testdata/info/info.custom.txt | 0 .../{ => test}/testdata/info/info.meta.xml | 0 document/{ => test}/testdata/info/info.pdf | Bin .../{ => test}/testdata/info/info.summary.txt | 0 .../testdata/malformed/compacted-syntax.pdf | Bin .../{ => test}/testdata/portfolio/generate.go | 6 +- .../testdata/portfolio/portfolio.pdf | Bin document/{ => test}/testdata/scanned.pdf | Bin .../{ => test}/testdata/scanned/page-1.txt | 0 .../{ => test}/testdata/scanned/page-2.txt | 0 .../{ => test}/testdata/scanned/page-3.txt | 0 .../{ => test}/testdata/scanned/page-4.txt | 0 .../{ => test}/testdata/scanned/page-5.txt | 0 .../{ => test}/testdata/scanned/page-6.txt | 0 .../{ => test}/testdata/scanned/page-7.txt | 0 .../conversation_integration_test.go | 0 email/{ => test}/conversation_test.go | 0 email/{ => test}/email_test.go | 0 email/{ => test}/main_test.go | 0 email/{ => test}/real_integration_test.go | 13 +- email/{ => test}/replay_test.go | 0 email/{ => test}/resume_integration_test.go | 0 email/{ => test}/testdata/README.md | 20 +- .../testdata/built/eml/office-attachments.eml | 0 .../testdata/built/msg/office-attachments.msg | Bin email/{ => test}/threads_integration_test.go | 0 email/{ => test}/threads_test.go | 0 inspect/clean_test.go | 60 ---- inspect/{ => test}/clean_integration_test.go | 2 +- inspect/test/clean_test.go | 70 +++++ inspect/{ => test}/inspect_test.go | 0 inspect/{ => test}/listing_test.go | 0 inspect/{ => test}/main_test.go | 0 inspect/{ => test}/rules_test.go | 0 inspect/{ => test}/scan_test.go | 0 inspect/{ => test}/testdata/README.md | 0 inspect/{ => test}/testdata/absolute.tar | Bin inspect/{ => test}/testdata/absolute.zip | Bin inspect/{ => test}/testdata/bomb.tar.gz | Bin inspect/{ => test}/testdata/bomb.zip | Bin inspect/{ => test}/testdata/clean.tar | Bin inspect/{ => test}/testdata/clean.tar.gz | Bin inspect/{ => test}/testdata/declared-bomb.zip | Bin inspect/{ => test}/testdata/device.tar | Bin inspect/{ => test}/testdata/encrypted.xlsx | Bin inspect/{ => test}/testdata/encrypted.zip | Bin inspect/{ => test}/testdata/generate.go | 4 +- inspect/{ => test}/testdata/hardlink.tar | Bin inspect/{ => test}/testdata/hyperlink.docx | Bin inspect/{ => test}/testdata/invoice.pdf.exe | Bin inspect/{ => test}/testdata/javascript.pdf | Bin inspect/{ => test}/testdata/macro-latin1.docm | Bin inspect/{ => test}/testdata/macro-utf16.docm | Bin inspect/{ => test}/testdata/macro.docm | Bin inspect/{ => test}/testdata/mismatch.pdf | Bin inspect/{ => test}/testdata/polyglot.jpg | Bin inspect/{ => test}/testdata/polyglot.png | Bin inspect/{ => test}/testdata/script-latin1.svg | 0 inspect/{ => test}/testdata/script-utf16.svg | Bin inspect/{ => test}/testdata/script.svg | 0 inspect/{ => test}/testdata/sparse-bomb.tar | Bin inspect/{ => test}/testdata/symlink.tar | Bin inspect/{ => test}/testdata/symlink.zip | Bin inspect/{ => test}/testdata/traversal.tar | Bin inspect/{ => test}/testdata/traversal.tar.gz | Bin inspect/{ => test}/testdata/traversal.zip | Bin inspect/{ => test}/testdata/unnamed.tgz | Bin internal/cli/{ => test}/cases_test.go | 0 internal/cli/{ => test}/cli_test.go | 0 internal/cli/{ => test}/contract_test.go | 0 internal/cli/{ => test}/envelope_test.go | 0 internal/cli/{ => test}/ffprobe_test.go | 4 +- internal/cli/{ => test}/lines_test.go | 0 internal/cli/{ => test}/main_test.go | 0 internal/cli/{ => test}/utc_test.go | 0 .../goldentest/{ => test}/goldentest_test.go | 0 internal/goldentest/{ => test}/main_test.go | 0 internal/tooltest/doc.go | 9 +- internal/tooltest/{ => test}/tooltest_test.go | 0 internal/tooltest/testdata.go | 36 +++ media/{ => test}/main_test.go | 0 media/{ => test}/media_integration_test.go | 5 +- media/{ => test}/media_test.go | 11 +- media/{ => test}/runners_test.go | 0 metadata/{ => test}/main_test.go | 0 metadata/{ => test}/metadata_test.go | 0 office/{ => test}/golden_integration_test.go | 0 office/{ => test}/legacy_integration_test.go | 0 office/{ => test}/legacy_test.go | 0 office/{ => test}/main_test.go | 0 office/{ => test}/metadata_test.go | 0 office/{ => test}/odf_integration_test.go | 0 office/{ => test}/odf_test.go | 0 office/{ => test}/office_test.go | 0 office/{ => test}/picture_integration_test.go | 0 .../{ => test}/pictures_integration_test.go | 0 office/{ => test}/pictures_test.go | 0 office/{ => test}/real_integration_test.go | 0 office/{ => test}/replay_test.go | 0 office/{ => test}/rtf_integration_test.go | 0 office/{ => test}/testdata/README.md | 0 .../testdata/golden/pictures.sha256 | 0 office/{ => test}/testdata/legacy/generate.sh | 4 +- .../testdata/legacy/generated/MANIFEST | 0 .../legacy/generated/bullets.libreoffice.ppt | Bin .../legacy/generated/cells.libreoffice.xls | Bin .../legacy/generated/charts.libreoffice.doc | Bin .../legacy/generated/comments.libreoffice.doc | Bin .../legacy/generated/drawings.libreoffice.xls | Bin .../legacy/generated/formulas.libreoffice.xls | Bin .../legacy/generated/lists.libreoffice.doc | Bin .../legacy/generated/media.libreoffice.doc | Bin .../legacy/generated/merges.libreoffice.xls | Bin .../legacy/generated/notes.libreoffice.doc | Bin .../legacy/generated/sections.libreoffice.doc | Bin .../generated/slide-objects.libreoffice.ppt | Bin .../legacy/generated/slides.libreoffice.ppt | Bin .../legacy/generated/tables.libreoffice.doc | Bin .../testdata/legacy/real/SampleSS.truth.json | 0 .../testdata/legacy/real/SampleSS.xls | Bin .../legacy/real/basic_test_ppt_file.ppt | Bin .../real/basic_test_ppt_file.truth.json | 0 .../testdata/legacy/real/simple-table.doc | Bin .../legacy/real/simple-table.truth.json | 0 .../{ => test}/testdata/licenses/poi.LICENSE | 0 .../{ => test}/testdata/licenses/poi.NOTICE | 0 office/{ => test}/testdata/odf/drawing.fodg | 0 office/{ => test}/testdata/odf/encrypt.py | 2 +- office/{ => test}/testdata/odf/generate.sh | 4 +- .../testdata/odf/generated/MANIFEST | 0 .../odf/generated/cells.libreoffice.ods | Bin .../odf/generated/cells.libreoffice.ots | Bin .../testdata/odf/generated/drawing.odg | Bin .../testdata/odf/generated/drawing.otg | Bin .../testdata/odf/generated/encrypted.odt | Bin .../odf/generated/slides.libreoffice.odp | Bin .../odf/generated/slides.libreoffice.otp | Bin .../odf/generated/tables.libreoffice.odt | Bin .../odf/generated/tables.libreoffice.ott | Bin .../testdata/ooxml/bullets.libreoffice.pptx | Bin .../testdata/ooxml/cells.libreoffice.xlsx | Bin .../testdata/ooxml/charts.libreoffice.docx | Bin .../testdata/ooxml/comments.libreoffice.docx | Bin .../testdata/ooxml/drawings.libreoffice.xlsx | Bin .../testdata/ooxml/formulas.libreoffice.xlsx | Bin .../testdata/ooxml/lists.libreoffice.docx | Bin .../testdata/ooxml/media.libreoffice.docx | Bin .../testdata/ooxml/merges.libreoffice.xlsx | Bin .../testdata/ooxml/notes.libreoffice.docx | Bin .../testdata/ooxml/sections.libreoffice.docx | Bin .../ooxml/slide-objects.libreoffice.pptx | Bin .../testdata/ooxml/slides.libreoffice.pptx | Bin .../testdata/ooxml/tables.libreoffice.docx | Bin .../testdata/ooxml/with-drawing.xlsx | Bin .../testdata/ooxml/word-with-attachments.docx | Bin .../{ => test}/testdata/pictures/generate.sh | 2 +- office/{ => test}/testdata/pictures/tiff.docx | Bin .../{ => test}/testdata/rtf/hidden-entry.rtf | 0 office/{ => test}/testdata/rtf/memo.rtf | 0 .../wordperfect/testWordPerfect_6_61.wpd | Bin .../testdata/xlsb/protected_passtika.xlsb | Bin .../{ => test}/testdata/xlsb/testVarious.xlsb | Bin onenote/{ => test}/main_test.go | 0 onenote/{ => test}/onenote_test.go | 0 onenote/{ => test}/real_integration_test.go | 0 onenote/{ => test}/replay_test.go | 0 .../{ => test}/convert_integration_test.go | 0 picture/{ => test}/convert_test.go | 0 picture/{ => test}/exif_integration_test.go | 0 picture/{ => test}/exif_test.go | 0 .../libreoffice_integration_test.go | 3 +- picture/{ => test}/main_test.go | 0 picture/{ => test}/pages_integration_test.go | 0 picture/{ => test}/pages_test.go | 0 picture/{ => test}/testdata/README.md | 0 picture/{ => test}/testdata/animated.avif | Bin picture/{ => test}/testdata/animated.webp | Bin picture/{ => test}/testdata/exif-gps.jpg | Bin .../{ => test}/testdata/exif-gps.magick.txt | 0 .../{ => test}/testdata/exif-none.magick.txt | 0 picture/{ => test}/testdata/exif-none.png | Bin .../{ => test}/testdata/exif-zoneless.heic | Bin .../testdata/exif-zoneless.magick.txt | 0 picture/{ => test}/testdata/ink.svg | 0 picture/{ => test}/testdata/lzw-gray.tiff | Bin picture/{ => test}/testdata/oriented.webp | Bin picture/{ => test}/testdata/pages.tiff | Bin picture/{ => test}/testdata/scanned-g4.tiff | Bin .../{ => test}/testdata/script-bearing.svg | 0 picture/{ => test}/testdata/shapes.svg | 0 picture/{ => test}/testdata/two-images.heic | Bin route/{ => test}/at_test.go | 0 route/{ => test}/file_test.go | 3 +- route/{ => test}/identify_test.go | 0 route/{ => test}/main_test.go | 0 route/{ => test}/real_test.go | 3 +- route/{ => test}/route_test.go | 0 rundir/schema/{ => test}/main_test.go | 0 rundir/schema/{ => test}/schema_test.go | 0 rundir/{ => test}/main_test.go | 0 rundir/{ => test}/rundir_test.go | 0 ...960b0c70076ea223eec8dcb9d57d4c51c9c9dd2906 | 0 ...3b8cf20bf3120903467fac751975e0260c8560c6c7 | 0 ...e08aa028a846bdebb78bf4b33c11e959a37b481bca | Bin rundir/{ => test}/testdata/rundir/rundir.json | 0 .../manifest.json | 0 .../record.jsonl | 0 .../manifest.json | 0 .../record.jsonl | 0 .../manifest.json | 0 .../record.jsonl | 0 settings/{ => test}/main_test.go | 0 settings/{ => test}/run_linux_test.go | 0 settings/{ => test}/run_test.go | 0 settings/{ => test}/settings_test.go | 0 sevenzip/{ => test}/listing_test.go | 0 sevenzip/{ => test}/read_test.go | 0 .../{ => test}/sevenzip_integration_test.go | 3 +- sevenzip/{ => test}/sevenzip_test.go | 0 sevenzip/{ => test}/testdata/README.md | 2 +- .../testdata/commons-compress/LICENSE.txt | 0 .../testdata/commons-compress/NOTICE.txt | 0 .../commons-compress/bla.deflate64.7z | Bin .../testdata/commons-compress/bzip2-zip.zip | Bin .../lorem-ipsum-deflate64.zip | Bin .../commons-compress/lorem-ipsum-implode.zip | Bin .../commons-compress/test-method-xz.zip | Bin sevenzip/{ => test}/testdata/generate.go | 6 +- .../{ => test}/testdata/generated/absolute.7z | Bin .../testdata/generated/absolute.cab | Bin .../{ => test}/testdata/generated/bomb.7z | Bin .../{ => test}/testdata/generated/bomb.bz2 | Bin .../{ => test}/testdata/generated/bomb.cab | Bin .../{ => test}/testdata/generated/bomb.xz | Bin .../{ => test}/testdata/generated/bomb.zst | Bin .../{ => test}/testdata/generated/clean.7z | Bin .../testdata/generated/clean.tar.zst | Bin .../{ => test}/testdata/generated/clean.tbz2 | Bin .../{ => test}/testdata/generated/clean.txz | Bin .../testdata/generated/concatenated.txt.bz2 | Bin .../testdata/generated/declared-bomb.zst | Bin .../{ => test}/testdata/generated/device.7z | Bin .../testdata/generated/encrypted-headers.7z | Bin .../testdata/generated/encrypted.7z | Bin .../testdata/generated/linebreak.cab | Bin .../{ => test}/testdata/generated/mixed.7z | Bin .../testdata/generated/multiblock.7z | Bin .../testdata/generated/notebook.cab | Bin .../testdata/generated/notes.txt.bz2 | Bin .../testdata/generated/notes.txt.xz | Bin .../{ => test}/testdata/generated/symlink.7z | Bin .../testdata/generated/traversal.7z | Bin .../testdata/generated/traversal.cab | Bin .../{ => test}/testdata/libarchive/COPYING | 0 .../libarchive/test_read_format_rar.rar | Bin .../test_read_format_rar5_compressed.rar | Bin .../test_read_format_rar5_encrypted.rar | Bin ...t_read_format_rar5_encrypted_filenames.rar | Bin ...t_read_format_rar5_multiarchive.part01.rar | Bin .../test_read_format_rar5_symlink.rar | Bin ...test_read_format_rar_encryption_header.rar | Bin ...t_read_format_rar_encryption_partially.rar | Bin ...t_read_format_rar_multivolume.part0001.rar | Bin .../libarchive/test_read_format_zip_lzma.zipx | Bin .../test_read_format_zip_ppmd8.zipx | Bin .../libarchive/test_read_format_zip_zstd.zipx | Bin stages/classify_test.go | 194 ------------- stages/helpers_test.go | 145 ---------- stages/internal/adapter/doc.go | 6 +- .../adapter/test}/adapter_integration_test.go | 139 +++------- .../adapter/test}/adapter_test.go | 114 +++----- .../archive_sevenzip_integration_test.go | 51 ++-- .../adapter/test}/archive_test.go | 23 +- .../adapter/test}/audio_integration_test.go | 16 +- .../{ => internal/adapter/test}/audio_test.go | 100 ++----- .../{ => internal/adapter/test}/bzip2_test.go | 19 +- stages/internal/adapter/test/classify_test.go | 66 +++++ .../test}/document_integration_test.go | 32 ++- .../adapter/test}/document_test.go | 89 ++---- .../{ => internal/adapter/test}/email_test.go | 9 +- stages/internal/adapter/test/helpers_test.go | 77 ++++++ stages/internal/adapter/test/main_test.go | 25 ++ .../adapter/test}/media_metadata_test.go | 18 +- .../adapter/test}/office_test.go | 46 +--- .../adapter/test}/onenote_test.go | 73 +---- .../picture_metadata_integration_test.go | 11 +- .../adapter/test}/picture_metadata_test.go | 87 ++---- stages/internal/adapter/test/picture_test.go | 100 +++++++ .../test}/release_adapter_integration_test.go | 2 +- .../adapter/test}/resume_integration_test.go | 2 +- .../adapter/test}/sevenzip_standin_test.go | 57 +--- .../adapter/test}/sevenzip_test.go | 11 +- .../{ => internal/adapter/test}/tar_test.go | 40 +-- .../{ => internal/adapter/test}/text_test.go | 5 +- .../video_containers_integration_test.go | 7 +- .../adapter/test}/video_integration_test.go | 23 +- .../{ => internal/adapter/test}/video_test.go | 71 +---- .../{ => internal/adapter/test}/zip_test.go | 30 +- stages/internal/stagestest/build.go | 25 ++ stages/internal/stagestest/dispatch.go | 81 ++++++ stages/internal/stagestest/doc.go | 20 ++ stages/internal/stagestest/envelope.go | 75 +++++ stages/internal/stagestest/media.go | 134 +++++++++ stages/internal/stagestest/office.go | 30 ++ stages/internal/stagestest/pdf.go | 141 ++++++++++ stages/internal/stagestest/picture.go | 146 ++++++++++ stages/internal/stagestest/programs.go | 30 ++ stages/internal/stagestest/sevenzip.go | 42 +++ stages/main_test.go | 61 ----- stages/picture_test.go | 187 ------------- stages/test/classify_test.go | 140 ++++++++++ .../{ => test}/fixtures_integration_test.go | 21 +- stages/test/identity_integration_test.go | 59 ++++ stages/{ => test}/identity_test.go | 23 +- stages/test/main_test.go | 14 + stages/{ => test}/stages_test.go | 36 +-- stages/test/testdata/fixtures.tsv | 257 ++++++++++++++++++ stages/testdata/fixtures.tsv | 257 ------------------ tool/{ => test}/cancel_test.go | 0 tool/{ => test}/container_test.go | 0 tool/{ => test}/docker_test.go | 0 tool/{ => test}/exec_test.go | 0 tool/{ => test}/ffprobe_integration_test.go | 0 tool/{ => test}/lockdown_test.go | 0 tool/{ => test}/main_test.go | 0 tool/{ => test}/stdin_test.go | 0 tool/{ => test}/testdata/README.md | 0 tool/{ => test}/testdata/tone.wav | Bin tool/{ => test}/tmpdir_test.go | 0 tool/{ => test}/usage_test.go | 0 tool/{ => test}/version_test.go | 0 419 files changed, 2057 insertions(+), 1771 deletions(-) rename audio/{ => test}/audio_integration_test.go (100%) rename audio/{ => test}/audio_test.go (100%) rename audio/{ => test}/fixtures_test.go (100%) rename audio/{ => test}/floor_test.go (100%) rename audio/{ => test}/image_integration_test.go (100%) rename audio/{ => test}/levels_integration_test.go (100%) rename audio/{ => test}/live_test.go (100%) rename audio/{ => test}/main_test.go (100%) rename audio/{ => test}/plan_test.go (100%) rename audio/{ => test}/runners_test.go (100%) rename audio/{ => test}/testdata/README.md (100%) rename audio/{ => test}/testdata/speech-gain.wav (100%) rename audio/{ => test}/testdata/speech-levels.truth.json (100%) rename audio/{ => test}/testdata/speech-noise.wav (100%) rename audio/{ => test}/testdata/speech-scenes.ffprobe.json (100%) rename audio/{ => test}/testdata/speech-scenes.mkv (100%) rename audio/{ => test}/testdata/speech-scenes.truth.json (100%) rename audio/{ => test}/testdata/speech-tagged.ffprobe.json (100%) rename audio/{ => test}/testdata/speech-tagged.mp3 (100%) rename audio/{ => test}/testdata/speech-truncated.mp3 (100%) rename audio/{ => test}/testdata/speech.flac (100%) rename audio/{ => test}/testdata/speech.truth.txt (100%) rename audio/{ => test}/testdata/windows-v0.9.0.txt (100%) rename audio/{ => test}/windows_integration_test.go (100%) rename audio/{ => test}/windows_test.go (100%) rename dispatch/dispatchtest/{ => test}/dispatchtest_test.go (100%) rename dispatch/dispatchtest/{ => test}/main_test.go (100%) rename dispatch/{ => test}/dispatch_test.go (100%) rename dispatch/{ => test}/golden_test.go (100%) rename dispatch/{ => test}/index_test.go (100%) rename dispatch/{ => test}/main_test.go (100%) rename dispatch/{ => test}/pool_test.go (100%) rename dispatch/{ => test}/release_test.go (100%) rename dispatch/{ => test}/stage_test.go (94%) rename dispatch/{ => test}/stream_test.go (100%) rename dispatch/{ => test}/testdata/dispatch.jsonl (100%) rename dispatch/{ => test}/testdata/log.jsonl (100%) rename dispatch/{ => test}/walk_test.go (100%) rename document/{ => test}/fixtures_integration_test.go (100%) rename document/{ => test}/ghostscript_integration_test.go (100%) rename document/{ => test}/ghostscript_test.go (100%) rename document/{ => test}/main_test.go (100%) rename document/{ => test}/pdfdetach_test.go (96%) rename document/{ => test}/pdfinfo_test.go (100%) rename document/{ => test}/pdftools_integration_test.go (100%) rename document/{ => test}/pdftotext_test.go (100%) rename document/{ => test}/prepare_integration_test.go (100%) rename document/{ => test}/prepare_test.go (100%) rename document/{ => test}/qpdf_test.go (100%) rename document/{ => test}/renderer_test.go (100%) rename document/{ => test}/testdata/README.md (97%) rename document/{ => test}/testdata/attachments/attachments.pdf (100%) rename document/{ => test}/testdata/attachments/generate.go (92%) rename document/{ => test}/testdata/clean.pdf (100%) rename document/{ => test}/testdata/clean.typ (100%) rename document/{ => test}/testdata/clean/page-1.txt (100%) rename document/{ => test}/testdata/clean/page-2.txt (100%) rename document/{ => test}/testdata/clean/page-3.txt (100%) rename document/{ => test}/testdata/clean/page-4.txt (100%) rename document/{ => test}/testdata/clean/page-5.txt (100%) rename document/{ => test}/testdata/clean/page-6.txt (100%) rename document/{ => test}/testdata/degraded.pdf (100%) rename document/{ => test}/testdata/degraded/page-1.txt (100%) rename document/{ => test}/testdata/degraded/page-2.txt (100%) rename document/{ => test}/testdata/degraded/page-3.txt (100%) rename document/{ => test}/testdata/degraded/page-4.txt (100%) rename document/{ => test}/testdata/degraded/page-5.txt (100%) rename document/{ => test}/testdata/degraded/page-6.txt (100%) rename document/{ => test}/testdata/degraded/page-7.txt (100%) rename document/{ => test}/testdata/degraded/page-8.txt (100%) rename document/{ => test}/testdata/degraded/page-9.txt (100%) rename document/{ => test}/testdata/forms/acroform.json (100%) rename document/{ => test}/testdata/forms/acroform.pdf (100%) rename document/{ => test}/testdata/forms/generate.go (95%) rename document/{ => test}/testdata/forms/signed.json (100%) rename document/{ => test}/testdata/forms/signed.pdf (100%) rename document/{ => test}/testdata/generate.sh (98%) rename document/{ => test}/testdata/info/clean.custom.txt (100%) rename document/{ => test}/testdata/info/clean.meta.xml (100%) rename document/{ => test}/testdata/info/clean.summary.txt (100%) rename document/{ => test}/testdata/info/generate.go (95%) rename document/{ => test}/testdata/info/info.custom.txt (100%) rename document/{ => test}/testdata/info/info.meta.xml (100%) rename document/{ => test}/testdata/info/info.pdf (100%) rename document/{ => test}/testdata/info/info.summary.txt (100%) rename document/{ => test}/testdata/malformed/compacted-syntax.pdf (100%) rename document/{ => test}/testdata/portfolio/generate.go (93%) rename document/{ => test}/testdata/portfolio/portfolio.pdf (100%) rename document/{ => test}/testdata/scanned.pdf (100%) rename document/{ => test}/testdata/scanned/page-1.txt (100%) rename document/{ => test}/testdata/scanned/page-2.txt (100%) rename document/{ => test}/testdata/scanned/page-3.txt (100%) rename document/{ => test}/testdata/scanned/page-4.txt (100%) rename document/{ => test}/testdata/scanned/page-5.txt (100%) rename document/{ => test}/testdata/scanned/page-6.txt (100%) rename document/{ => test}/testdata/scanned/page-7.txt (100%) rename email/{ => test}/conversation_integration_test.go (100%) rename email/{ => test}/conversation_test.go (100%) rename email/{ => test}/email_test.go (100%) rename email/{ => test}/main_test.go (100%) rename email/{ => test}/real_integration_test.go (94%) rename email/{ => test}/replay_test.go (100%) rename email/{ => test}/resume_integration_test.go (100%) rename email/{ => test}/testdata/README.md (53%) rename email/{ => test}/testdata/built/eml/office-attachments.eml (100%) rename email/{ => test}/testdata/built/msg/office-attachments.msg (100%) rename email/{ => test}/threads_integration_test.go (100%) rename email/{ => test}/threads_test.go (100%) delete mode 100644 inspect/clean_test.go rename inspect/{ => test}/clean_integration_test.go (98%) create mode 100644 inspect/test/clean_test.go rename inspect/{ => test}/inspect_test.go (100%) rename inspect/{ => test}/listing_test.go (100%) rename inspect/{ => test}/main_test.go (100%) rename inspect/{ => test}/rules_test.go (100%) rename inspect/{ => test}/scan_test.go (100%) rename inspect/{ => test}/testdata/README.md (100%) rename inspect/{ => test}/testdata/absolute.tar (100%) rename inspect/{ => test}/testdata/absolute.zip (100%) rename inspect/{ => test}/testdata/bomb.tar.gz (100%) rename inspect/{ => test}/testdata/bomb.zip (100%) rename inspect/{ => test}/testdata/clean.tar (100%) rename inspect/{ => test}/testdata/clean.tar.gz (100%) rename inspect/{ => test}/testdata/declared-bomb.zip (100%) rename inspect/{ => test}/testdata/device.tar (100%) rename inspect/{ => test}/testdata/encrypted.xlsx (100%) rename inspect/{ => test}/testdata/encrypted.zip (100%) rename inspect/{ => test}/testdata/generate.go (98%) rename inspect/{ => test}/testdata/hardlink.tar (100%) rename inspect/{ => test}/testdata/hyperlink.docx (100%) rename inspect/{ => test}/testdata/invoice.pdf.exe (100%) rename inspect/{ => test}/testdata/javascript.pdf (100%) rename inspect/{ => test}/testdata/macro-latin1.docm (100%) rename inspect/{ => test}/testdata/macro-utf16.docm (100%) rename inspect/{ => test}/testdata/macro.docm (100%) rename inspect/{ => test}/testdata/mismatch.pdf (100%) rename inspect/{ => test}/testdata/polyglot.jpg (100%) rename inspect/{ => test}/testdata/polyglot.png (100%) rename inspect/{ => test}/testdata/script-latin1.svg (100%) rename inspect/{ => test}/testdata/script-utf16.svg (100%) rename inspect/{ => test}/testdata/script.svg (100%) rename inspect/{ => test}/testdata/sparse-bomb.tar (100%) rename inspect/{ => test}/testdata/symlink.tar (100%) rename inspect/{ => test}/testdata/symlink.zip (100%) rename inspect/{ => test}/testdata/traversal.tar (100%) rename inspect/{ => test}/testdata/traversal.tar.gz (100%) rename inspect/{ => test}/testdata/traversal.zip (100%) rename inspect/{ => test}/testdata/unnamed.tgz (100%) rename internal/cli/{ => test}/cases_test.go (100%) rename internal/cli/{ => test}/cli_test.go (100%) rename internal/cli/{ => test}/contract_test.go (100%) rename internal/cli/{ => test}/envelope_test.go (100%) rename internal/cli/{ => test}/ffprobe_test.go (96%) rename internal/cli/{ => test}/lines_test.go (100%) rename internal/cli/{ => test}/main_test.go (100%) rename internal/cli/{ => test}/utc_test.go (100%) rename internal/goldentest/{ => test}/goldentest_test.go (100%) rename internal/goldentest/{ => test}/main_test.go (100%) rename internal/tooltest/{ => test}/tooltest_test.go (100%) create mode 100644 internal/tooltest/testdata.go rename media/{ => test}/main_test.go (100%) rename media/{ => test}/media_integration_test.go (96%) rename media/{ => test}/media_test.go (98%) rename media/{ => test}/runners_test.go (100%) rename metadata/{ => test}/main_test.go (100%) rename metadata/{ => test}/metadata_test.go (100%) rename office/{ => test}/golden_integration_test.go (100%) rename office/{ => test}/legacy_integration_test.go (100%) rename office/{ => test}/legacy_test.go (100%) rename office/{ => test}/main_test.go (100%) rename office/{ => test}/metadata_test.go (100%) rename office/{ => test}/odf_integration_test.go (100%) rename office/{ => test}/odf_test.go (100%) rename office/{ => test}/office_test.go (100%) rename office/{ => test}/picture_integration_test.go (100%) rename office/{ => test}/pictures_integration_test.go (100%) rename office/{ => test}/pictures_test.go (100%) rename office/{ => test}/real_integration_test.go (100%) rename office/{ => test}/replay_test.go (100%) rename office/{ => test}/rtf_integration_test.go (100%) rename office/{ => test}/testdata/README.md (100%) rename office/{ => test}/testdata/golden/pictures.sha256 (100%) rename office/{ => test}/testdata/legacy/generate.sh (93%) rename office/{ => test}/testdata/legacy/generated/MANIFEST (100%) rename office/{ => test}/testdata/legacy/generated/bullets.libreoffice.ppt (100%) rename office/{ => test}/testdata/legacy/generated/cells.libreoffice.xls (100%) rename office/{ => test}/testdata/legacy/generated/charts.libreoffice.doc (100%) rename office/{ => test}/testdata/legacy/generated/comments.libreoffice.doc (100%) rename office/{ => test}/testdata/legacy/generated/drawings.libreoffice.xls (100%) rename office/{ => test}/testdata/legacy/generated/formulas.libreoffice.xls (100%) rename office/{ => test}/testdata/legacy/generated/lists.libreoffice.doc (100%) rename office/{ => test}/testdata/legacy/generated/media.libreoffice.doc (100%) rename office/{ => test}/testdata/legacy/generated/merges.libreoffice.xls (100%) rename office/{ => test}/testdata/legacy/generated/notes.libreoffice.doc (100%) rename office/{ => test}/testdata/legacy/generated/sections.libreoffice.doc (100%) rename office/{ => test}/testdata/legacy/generated/slide-objects.libreoffice.ppt (100%) rename office/{ => test}/testdata/legacy/generated/slides.libreoffice.ppt (100%) rename office/{ => test}/testdata/legacy/generated/tables.libreoffice.doc (100%) rename office/{ => test}/testdata/legacy/real/SampleSS.truth.json (100%) rename office/{ => test}/testdata/legacy/real/SampleSS.xls (100%) rename office/{ => test}/testdata/legacy/real/basic_test_ppt_file.ppt (100%) rename office/{ => test}/testdata/legacy/real/basic_test_ppt_file.truth.json (100%) rename office/{ => test}/testdata/legacy/real/simple-table.doc (100%) rename office/{ => test}/testdata/legacy/real/simple-table.truth.json (100%) rename office/{ => test}/testdata/licenses/poi.LICENSE (100%) rename office/{ => test}/testdata/licenses/poi.NOTICE (100%) rename office/{ => test}/testdata/odf/drawing.fodg (100%) rename office/{ => test}/testdata/odf/encrypt.py (97%) rename office/{ => test}/testdata/odf/generate.sh (95%) rename office/{ => test}/testdata/odf/generated/MANIFEST (100%) rename office/{ => test}/testdata/odf/generated/cells.libreoffice.ods (100%) rename office/{ => test}/testdata/odf/generated/cells.libreoffice.ots (100%) rename office/{ => test}/testdata/odf/generated/drawing.odg (100%) rename office/{ => test}/testdata/odf/generated/drawing.otg (100%) rename office/{ => test}/testdata/odf/generated/encrypted.odt (100%) rename office/{ => test}/testdata/odf/generated/slides.libreoffice.odp (100%) rename office/{ => test}/testdata/odf/generated/slides.libreoffice.otp (100%) rename office/{ => test}/testdata/odf/generated/tables.libreoffice.odt (100%) rename office/{ => test}/testdata/odf/generated/tables.libreoffice.ott (100%) rename office/{ => test}/testdata/ooxml/bullets.libreoffice.pptx (100%) rename office/{ => test}/testdata/ooxml/cells.libreoffice.xlsx (100%) rename office/{ => test}/testdata/ooxml/charts.libreoffice.docx (100%) rename office/{ => test}/testdata/ooxml/comments.libreoffice.docx (100%) rename office/{ => test}/testdata/ooxml/drawings.libreoffice.xlsx (100%) rename office/{ => test}/testdata/ooxml/formulas.libreoffice.xlsx (100%) rename office/{ => test}/testdata/ooxml/lists.libreoffice.docx (100%) rename office/{ => test}/testdata/ooxml/media.libreoffice.docx (100%) rename office/{ => test}/testdata/ooxml/merges.libreoffice.xlsx (100%) rename office/{ => test}/testdata/ooxml/notes.libreoffice.docx (100%) rename office/{ => test}/testdata/ooxml/sections.libreoffice.docx (100%) rename office/{ => test}/testdata/ooxml/slide-objects.libreoffice.pptx (100%) rename office/{ => test}/testdata/ooxml/slides.libreoffice.pptx (100%) rename office/{ => test}/testdata/ooxml/tables.libreoffice.docx (100%) rename office/{ => test}/testdata/ooxml/with-drawing.xlsx (100%) rename office/{ => test}/testdata/ooxml/word-with-attachments.docx (100%) rename office/{ => test}/testdata/pictures/generate.sh (99%) rename office/{ => test}/testdata/pictures/tiff.docx (100%) rename office/{ => test}/testdata/rtf/hidden-entry.rtf (100%) rename office/{ => test}/testdata/rtf/memo.rtf (100%) rename office/{ => test}/testdata/wordperfect/testWordPerfect_6_61.wpd (100%) rename office/{ => test}/testdata/xlsb/protected_passtika.xlsb (100%) rename office/{ => test}/testdata/xlsb/testVarious.xlsb (100%) rename onenote/{ => test}/main_test.go (100%) rename onenote/{ => test}/onenote_test.go (100%) rename onenote/{ => test}/real_integration_test.go (100%) rename onenote/{ => test}/replay_test.go (100%) rename picture/{ => test}/convert_integration_test.go (100%) rename picture/{ => test}/convert_test.go (100%) rename picture/{ => test}/exif_integration_test.go (100%) rename picture/{ => test}/exif_test.go (100%) rename picture/{ => test}/libreoffice_integration_test.go (92%) rename picture/{ => test}/main_test.go (100%) rename picture/{ => test}/pages_integration_test.go (100%) rename picture/{ => test}/pages_test.go (100%) rename picture/{ => test}/testdata/README.md (100%) rename picture/{ => test}/testdata/animated.avif (100%) rename picture/{ => test}/testdata/animated.webp (100%) rename picture/{ => test}/testdata/exif-gps.jpg (100%) rename picture/{ => test}/testdata/exif-gps.magick.txt (100%) rename picture/{ => test}/testdata/exif-none.magick.txt (100%) rename picture/{ => test}/testdata/exif-none.png (100%) rename picture/{ => test}/testdata/exif-zoneless.heic (100%) rename picture/{ => test}/testdata/exif-zoneless.magick.txt (100%) rename picture/{ => test}/testdata/ink.svg (100%) rename picture/{ => test}/testdata/lzw-gray.tiff (100%) rename picture/{ => test}/testdata/oriented.webp (100%) rename picture/{ => test}/testdata/pages.tiff (100%) rename picture/{ => test}/testdata/scanned-g4.tiff (100%) rename picture/{ => test}/testdata/script-bearing.svg (100%) rename picture/{ => test}/testdata/shapes.svg (100%) rename picture/{ => test}/testdata/two-images.heic (100%) rename route/{ => test}/at_test.go (100%) rename route/{ => test}/file_test.go (99%) rename route/{ => test}/identify_test.go (100%) rename route/{ => test}/main_test.go (100%) rename route/{ => test}/real_test.go (83%) rename route/{ => test}/route_test.go (100%) rename rundir/schema/{ => test}/main_test.go (100%) rename rundir/schema/{ => test}/schema_test.go (100%) rename rundir/{ => test}/main_test.go (100%) rename rundir/{ => test}/rundir_test.go (100%) rename rundir/{ => test}/testdata/rundir/content/b6/b688c8947f876ba9580749960b0c70076ea223eec8dcb9d57d4c51c9c9dd2906 (100%) rename rundir/{ => test}/testdata/rundir/content/d3/d31031c3593a9da13ff7013b8cf20bf3120903467fac751975e0260c8560c6c7 (100%) rename rundir/{ => test}/testdata/rundir/quarantine/4efe525c159bafa28a6ba4e08aa028a846bdebb78bf4b33c11e959a37b481bca (100%) rename rundir/{ => test}/testdata/rundir/rundir.json (100%) rename rundir/{ => test}/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/manifest.json (100%) rename rundir/{ => test}/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/record.jsonl (100%) rename rundir/{ => test}/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/manifest.json (100%) rename rundir/{ => test}/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/record.jsonl (100%) rename rundir/{ => test}/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/manifest.json (100%) rename rundir/{ => test}/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/record.jsonl (100%) rename settings/{ => test}/main_test.go (100%) rename settings/{ => test}/run_linux_test.go (100%) rename settings/{ => test}/run_test.go (100%) rename settings/{ => test}/settings_test.go (100%) rename sevenzip/{ => test}/listing_test.go (100%) rename sevenzip/{ => test}/read_test.go (100%) rename sevenzip/{ => test}/sevenzip_integration_test.go (98%) rename sevenzip/{ => test}/sevenzip_test.go (100%) rename sevenzip/{ => test}/testdata/README.md (99%) rename sevenzip/{ => test}/testdata/commons-compress/LICENSE.txt (100%) rename sevenzip/{ => test}/testdata/commons-compress/NOTICE.txt (100%) rename sevenzip/{ => test}/testdata/commons-compress/bla.deflate64.7z (100%) rename sevenzip/{ => test}/testdata/commons-compress/bzip2-zip.zip (100%) rename sevenzip/{ => test}/testdata/commons-compress/lorem-ipsum-deflate64.zip (100%) rename sevenzip/{ => test}/testdata/commons-compress/lorem-ipsum-implode.zip (100%) rename sevenzip/{ => test}/testdata/commons-compress/test-method-xz.zip (100%) rename sevenzip/{ => test}/testdata/generate.go (97%) rename sevenzip/{ => test}/testdata/generated/absolute.7z (100%) rename sevenzip/{ => test}/testdata/generated/absolute.cab (100%) rename sevenzip/{ => test}/testdata/generated/bomb.7z (100%) rename sevenzip/{ => test}/testdata/generated/bomb.bz2 (100%) rename sevenzip/{ => test}/testdata/generated/bomb.cab (100%) rename sevenzip/{ => test}/testdata/generated/bomb.xz (100%) rename sevenzip/{ => test}/testdata/generated/bomb.zst (100%) rename sevenzip/{ => test}/testdata/generated/clean.7z (100%) rename sevenzip/{ => test}/testdata/generated/clean.tar.zst (100%) rename sevenzip/{ => test}/testdata/generated/clean.tbz2 (100%) rename sevenzip/{ => test}/testdata/generated/clean.txz (100%) rename sevenzip/{ => test}/testdata/generated/concatenated.txt.bz2 (100%) rename sevenzip/{ => test}/testdata/generated/declared-bomb.zst (100%) rename sevenzip/{ => test}/testdata/generated/device.7z (100%) rename sevenzip/{ => test}/testdata/generated/encrypted-headers.7z (100%) rename sevenzip/{ => test}/testdata/generated/encrypted.7z (100%) rename sevenzip/{ => test}/testdata/generated/linebreak.cab (100%) rename sevenzip/{ => test}/testdata/generated/mixed.7z (100%) rename sevenzip/{ => test}/testdata/generated/multiblock.7z (100%) rename sevenzip/{ => test}/testdata/generated/notebook.cab (100%) rename sevenzip/{ => test}/testdata/generated/notes.txt.bz2 (100%) rename sevenzip/{ => test}/testdata/generated/notes.txt.xz (100%) rename sevenzip/{ => test}/testdata/generated/symlink.7z (100%) rename sevenzip/{ => test}/testdata/generated/traversal.7z (100%) rename sevenzip/{ => test}/testdata/generated/traversal.cab (100%) rename sevenzip/{ => test}/testdata/libarchive/COPYING (100%) rename sevenzip/{ => test}/testdata/libarchive/test_read_format_rar.rar (100%) rename sevenzip/{ => test}/testdata/libarchive/test_read_format_rar5_compressed.rar (100%) rename sevenzip/{ => test}/testdata/libarchive/test_read_format_rar5_encrypted.rar (100%) rename sevenzip/{ => test}/testdata/libarchive/test_read_format_rar5_encrypted_filenames.rar (100%) rename sevenzip/{ => test}/testdata/libarchive/test_read_format_rar5_multiarchive.part01.rar (100%) rename sevenzip/{ => test}/testdata/libarchive/test_read_format_rar5_symlink.rar (100%) rename sevenzip/{ => test}/testdata/libarchive/test_read_format_rar_encryption_header.rar (100%) rename sevenzip/{ => test}/testdata/libarchive/test_read_format_rar_encryption_partially.rar (100%) rename sevenzip/{ => test}/testdata/libarchive/test_read_format_rar_multivolume.part0001.rar (100%) rename sevenzip/{ => test}/testdata/libarchive/test_read_format_zip_lzma.zipx (100%) rename sevenzip/{ => test}/testdata/libarchive/test_read_format_zip_ppmd8.zipx (100%) rename sevenzip/{ => test}/testdata/libarchive/test_read_format_zip_zstd.zipx (100%) delete mode 100644 stages/classify_test.go delete mode 100644 stages/helpers_test.go rename stages/{ => internal/adapter/test}/adapter_integration_test.go (85%) rename stages/{ => internal/adapter/test}/adapter_test.go (56%) rename stages/{ => internal/adapter/test}/archive_sevenzip_integration_test.go (87%) rename stages/{ => internal/adapter/test}/archive_test.go (86%) rename stages/{ => internal/adapter/test}/audio_integration_test.go (91%) rename stages/{ => internal/adapter/test}/audio_test.go (82%) rename stages/{ => internal/adapter/test}/bzip2_test.go (84%) create mode 100644 stages/internal/adapter/test/classify_test.go rename stages/{ => internal/adapter/test}/document_integration_test.go (90%) rename stages/{ => internal/adapter/test}/document_test.go (87%) rename stages/{ => internal/adapter/test}/email_test.go (86%) create mode 100644 stages/internal/adapter/test/helpers_test.go create mode 100644 stages/internal/adapter/test/main_test.go rename stages/{ => internal/adapter/test}/media_metadata_test.go (87%) rename stages/{ => internal/adapter/test}/office_test.go (85%) rename stages/{ => internal/adapter/test}/onenote_test.go (69%) rename stages/{ => internal/adapter/test}/picture_metadata_integration_test.go (81%) rename stages/{ => internal/adapter/test}/picture_metadata_test.go (72%) create mode 100644 stages/internal/adapter/test/picture_test.go rename stages/{ => internal/adapter/test}/release_adapter_integration_test.go (99%) rename stages/{ => internal/adapter/test}/resume_integration_test.go (99%) rename stages/{ => internal/adapter/test}/sevenzip_standin_test.go (73%) rename stages/{ => internal/adapter/test}/sevenzip_test.go (92%) rename stages/{ => internal/adapter/test}/tar_test.go (85%) rename stages/{ => internal/adapter/test}/text_test.go (97%) rename stages/{ => internal/adapter/test}/video_containers_integration_test.go (95%) rename stages/{ => internal/adapter/test}/video_integration_test.go (92%) rename stages/{ => internal/adapter/test}/video_test.go (89%) rename stages/{ => internal/adapter/test}/zip_test.go (90%) create mode 100644 stages/internal/stagestest/build.go create mode 100644 stages/internal/stagestest/dispatch.go create mode 100644 stages/internal/stagestest/doc.go create mode 100644 stages/internal/stagestest/envelope.go create mode 100644 stages/internal/stagestest/media.go create mode 100644 stages/internal/stagestest/office.go create mode 100644 stages/internal/stagestest/pdf.go create mode 100644 stages/internal/stagestest/picture.go create mode 100644 stages/internal/stagestest/programs.go create mode 100644 stages/internal/stagestest/sevenzip.go delete mode 100644 stages/main_test.go delete mode 100644 stages/picture_test.go create mode 100644 stages/test/classify_test.go rename stages/{ => test}/fixtures_integration_test.go (80%) create mode 100644 stages/test/identity_integration_test.go rename stages/{ => test}/identity_test.go (80%) create mode 100644 stages/test/main_test.go rename stages/{ => test}/stages_test.go (78%) create mode 100644 stages/test/testdata/fixtures.tsv delete mode 100644 stages/testdata/fixtures.tsv rename tool/{ => test}/cancel_test.go (100%) rename tool/{ => test}/container_test.go (100%) rename tool/{ => test}/docker_test.go (100%) rename tool/{ => test}/exec_test.go (100%) rename tool/{ => test}/ffprobe_integration_test.go (100%) rename tool/{ => test}/lockdown_test.go (100%) rename tool/{ => test}/main_test.go (100%) rename tool/{ => test}/stdin_test.go (100%) rename tool/{ => test}/testdata/README.md (100%) rename tool/{ => test}/testdata/tone.wav (100%) rename tool/{ => test}/tmpdir_test.go (100%) rename tool/{ => test}/usage_test.go (100%) rename tool/{ => test}/version_test.go (100%) diff --git a/.gitattributes b/.gitattributes index 7f261591..a3861ada 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,10 +1,10 @@ # Fixtures pinned byte for byte, which git never converts. # See docs/development.md -audio/testdata/speech.* -text -audio/testdata/speech-tagged.mp3 -text -audio/testdata/*.ffprobe.json -text -office/testdata/rtf/** -text -rundir/testdata/** -text -document/testdata/malformed/** -text -document/testdata/info/** -text -picture/testdata/exif-* -text +audio/test/testdata/speech.* -text +audio/test/testdata/speech-tagged.mp3 -text +audio/test/testdata/*.ffprobe.json -text +office/test/testdata/rtf/** -text +rundir/test/testdata/** -text +document/test/testdata/malformed/** -text +document/test/testdata/info/** -text +picture/test/testdata/exif-* -text diff --git a/audio/audio_integration_test.go b/audio/test/audio_integration_test.go similarity index 100% rename from audio/audio_integration_test.go rename to audio/test/audio_integration_test.go diff --git a/audio/audio_test.go b/audio/test/audio_test.go similarity index 100% rename from audio/audio_test.go rename to audio/test/audio_test.go diff --git a/audio/fixtures_test.go b/audio/test/fixtures_test.go similarity index 100% rename from audio/fixtures_test.go rename to audio/test/fixtures_test.go diff --git a/audio/floor_test.go b/audio/test/floor_test.go similarity index 100% rename from audio/floor_test.go rename to audio/test/floor_test.go diff --git a/audio/image_integration_test.go b/audio/test/image_integration_test.go similarity index 100% rename from audio/image_integration_test.go rename to audio/test/image_integration_test.go diff --git a/audio/levels_integration_test.go b/audio/test/levels_integration_test.go similarity index 100% rename from audio/levels_integration_test.go rename to audio/test/levels_integration_test.go diff --git a/audio/live_test.go b/audio/test/live_test.go similarity index 100% rename from audio/live_test.go rename to audio/test/live_test.go diff --git a/audio/main_test.go b/audio/test/main_test.go similarity index 100% rename from audio/main_test.go rename to audio/test/main_test.go diff --git a/audio/plan_test.go b/audio/test/plan_test.go similarity index 100% rename from audio/plan_test.go rename to audio/test/plan_test.go diff --git a/audio/runners_test.go b/audio/test/runners_test.go similarity index 100% rename from audio/runners_test.go rename to audio/test/runners_test.go diff --git a/audio/testdata/README.md b/audio/test/testdata/README.md similarity index 100% rename from audio/testdata/README.md rename to audio/test/testdata/README.md diff --git a/audio/testdata/speech-gain.wav b/audio/test/testdata/speech-gain.wav similarity index 100% rename from audio/testdata/speech-gain.wav rename to audio/test/testdata/speech-gain.wav diff --git a/audio/testdata/speech-levels.truth.json b/audio/test/testdata/speech-levels.truth.json similarity index 100% rename from audio/testdata/speech-levels.truth.json rename to audio/test/testdata/speech-levels.truth.json diff --git a/audio/testdata/speech-noise.wav b/audio/test/testdata/speech-noise.wav similarity index 100% rename from audio/testdata/speech-noise.wav rename to audio/test/testdata/speech-noise.wav diff --git a/audio/testdata/speech-scenes.ffprobe.json b/audio/test/testdata/speech-scenes.ffprobe.json similarity index 100% rename from audio/testdata/speech-scenes.ffprobe.json rename to audio/test/testdata/speech-scenes.ffprobe.json diff --git a/audio/testdata/speech-scenes.mkv b/audio/test/testdata/speech-scenes.mkv similarity index 100% rename from audio/testdata/speech-scenes.mkv rename to audio/test/testdata/speech-scenes.mkv diff --git a/audio/testdata/speech-scenes.truth.json b/audio/test/testdata/speech-scenes.truth.json similarity index 100% rename from audio/testdata/speech-scenes.truth.json rename to audio/test/testdata/speech-scenes.truth.json diff --git a/audio/testdata/speech-tagged.ffprobe.json b/audio/test/testdata/speech-tagged.ffprobe.json similarity index 100% rename from audio/testdata/speech-tagged.ffprobe.json rename to audio/test/testdata/speech-tagged.ffprobe.json diff --git a/audio/testdata/speech-tagged.mp3 b/audio/test/testdata/speech-tagged.mp3 similarity index 100% rename from audio/testdata/speech-tagged.mp3 rename to audio/test/testdata/speech-tagged.mp3 diff --git a/audio/testdata/speech-truncated.mp3 b/audio/test/testdata/speech-truncated.mp3 similarity index 100% rename from audio/testdata/speech-truncated.mp3 rename to audio/test/testdata/speech-truncated.mp3 diff --git a/audio/testdata/speech.flac b/audio/test/testdata/speech.flac similarity index 100% rename from audio/testdata/speech.flac rename to audio/test/testdata/speech.flac diff --git a/audio/testdata/speech.truth.txt b/audio/test/testdata/speech.truth.txt similarity index 100% rename from audio/testdata/speech.truth.txt rename to audio/test/testdata/speech.truth.txt diff --git a/audio/testdata/windows-v0.9.0.txt b/audio/test/testdata/windows-v0.9.0.txt similarity index 100% rename from audio/testdata/windows-v0.9.0.txt rename to audio/test/testdata/windows-v0.9.0.txt diff --git a/audio/windows_integration_test.go b/audio/test/windows_integration_test.go similarity index 100% rename from audio/windows_integration_test.go rename to audio/test/windows_integration_test.go diff --git a/audio/windows_test.go b/audio/test/windows_test.go similarity index 100% rename from audio/windows_test.go rename to audio/test/windows_test.go diff --git a/cmd/docproc/integration/fixtures_test.go b/cmd/docproc/integration/fixtures_test.go index e3f3d078..1d252435 100644 --- a/cmd/docproc/integration/fixtures_test.go +++ b/cmd/docproc/integration/fixtures_test.go @@ -27,7 +27,7 @@ func writeTree(t *testing.T, dir string, files ...string) { func TestReadFixtures(t *testing.T) { repo := t.TempDir() writeTree(t, repo, - "stages/testdata/fixtures.tsv", "b/testdata/two.txt\ttext\tprepared\na/testdata/one.zip\tarchive\tprepared\n", + "stages/test/testdata/fixtures.tsv", "b/testdata/two.txt\ttext\tprepared\na/testdata/one.zip\tarchive\tprepared\n", "a/testdata/one.zip", "one", "b/testdata/two.txt", "two") got, err := integration.ReadFixtures(repo) @@ -43,7 +43,7 @@ func TestReadFixtures_NoTree(t *testing.T) { _, err := integration.ReadFixtures(repo) - list := filepath.Join(repo, "stages", "testdata", "fixtures.tsv") + list := filepath.Join(repo, "stages", "test", "testdata", "fixtures.tsv") if !errors.Is(err, integration.ErrNoFixtures) || !strings.Contains(err.Error(), list) { t.Errorf("ReadFixtures = %v, want an error matching ErrNoFixtures naming %s", err, list) } @@ -52,7 +52,7 @@ func TestReadFixtures_NoTree(t *testing.T) { func TestReadFixtures_MissingFixture(t *testing.T) { repo := t.TempDir() writeTree(t, repo, - "stages/testdata/fixtures.tsv", "a/testdata/one.zip\tarchive\tprepared\na/testdata/gone.pdf\tdocument\tprepared\n", + "stages/test/testdata/fixtures.tsv", "a/testdata/one.zip\tarchive\tprepared\na/testdata/gone.pdf\tdocument\tprepared\n", "a/testdata/one.zip", "one") _, err := integration.ReadFixtures(repo) diff --git a/cmd/docproc/integration/harness.go b/cmd/docproc/integration/harness.go index 602ae3c6..30030c3d 100644 --- a/cmd/docproc/integration/harness.go +++ b/cmd/docproc/integration/harness.go @@ -30,7 +30,7 @@ var hostBounds = []string{ // run still going after it is a stall, killed, failing its test with its output. const Bound = 10 * processtest.Failsafe -const fixtureList = "stages/testdata/fixtures.tsv" +const fixtureList = "stages/test/testdata/fixtures.tsv" // ErrNoFixtures is what [ReadFixtures] fails with when the fixture tree is absent. var ErrNoFixtures = errors.New("integration: no fixture tree") @@ -232,9 +232,9 @@ func Fixtures(t testing.TB) []string { } // ReadFixtures returns the absolute paths of the committed fixtures of the repository at repo, in -// the order its list, stages/testdata/fixtures.tsv, names them. It fails matching [ErrNoFixtures], -// naming the list, when the list is absent, as it is outside a docproc checkout, and names every -// fixture the list names that is missing from the tree. +// the order its list, stages/test/testdata/fixtures.tsv, names them. It fails matching +// [ErrNoFixtures], naming the list, when the list is absent, as it is outside a docproc checkout, +// and names every fixture the list names that is missing from the tree. func ReadFixtures(repo string) ([]string, error) { repo, err := filepath.Abs(repo) if err != nil { diff --git a/dispatch/dispatchtest/dispatchtest_test.go b/dispatch/dispatchtest/test/dispatchtest_test.go similarity index 100% rename from dispatch/dispatchtest/dispatchtest_test.go rename to dispatch/dispatchtest/test/dispatchtest_test.go diff --git a/dispatch/dispatchtest/main_test.go b/dispatch/dispatchtest/test/main_test.go similarity index 100% rename from dispatch/dispatchtest/main_test.go rename to dispatch/dispatchtest/test/main_test.go diff --git a/dispatch/dispatch_test.go b/dispatch/test/dispatch_test.go similarity index 100% rename from dispatch/dispatch_test.go rename to dispatch/test/dispatch_test.go diff --git a/dispatch/golden_test.go b/dispatch/test/golden_test.go similarity index 100% rename from dispatch/golden_test.go rename to dispatch/test/golden_test.go diff --git a/dispatch/index_test.go b/dispatch/test/index_test.go similarity index 100% rename from dispatch/index_test.go rename to dispatch/test/index_test.go diff --git a/dispatch/main_test.go b/dispatch/test/main_test.go similarity index 100% rename from dispatch/main_test.go rename to dispatch/test/main_test.go diff --git a/dispatch/pool_test.go b/dispatch/test/pool_test.go similarity index 100% rename from dispatch/pool_test.go rename to dispatch/test/pool_test.go diff --git a/dispatch/release_test.go b/dispatch/test/release_test.go similarity index 100% rename from dispatch/release_test.go rename to dispatch/test/release_test.go diff --git a/dispatch/stage_test.go b/dispatch/test/stage_test.go similarity index 94% rename from dispatch/stage_test.go rename to dispatch/test/stage_test.go index 2daa7ff3..72e1a7df 100644 --- a/dispatch/stage_test.go +++ b/dispatch/test/stage_test.go @@ -15,13 +15,15 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/inspect" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" ) type container struct { - world map[string]string - entered chan string - release chan struct{} + world map[string]string + fixtures string + entered chan string + release chan struct{} mu sync.Mutex calls map[string]int @@ -33,8 +35,8 @@ type remaining struct { ok bool } -func newContainer(world map[string]string) *container { - return &container{world: world, calls: map[string]int{}, remaining: map[string]remaining{}} +func newContainer(world map[string]string, fixtures string) *container { + return &container{world: world, fixtures: fixtures, calls: map[string]int{}, remaining: map[string]remaining{}} } func (c *container) remainingOf(name string) (remaining, bool) { @@ -82,7 +84,7 @@ func (c *container) Prepare(ctx context.Context, p dispatch.Part, dir string) it var content []byte if verb == "file" { content = []byte(c.world[arg]) - } else if content, err = os.ReadFile(filepath.Join("..", "inspect", "testdata", arg)); err != nil { + } else if content, err = os.ReadFile(filepath.Join(c.fixtures, arg)); err != nil { yield(dispatch.Item{}, err) return } @@ -176,7 +178,7 @@ func newFixture(t *testing.T, world map[string]string, index dispatch.Index, lim } f := &fixture{ index: index, - text: newContainer(world), + text: newContainer(world, tooltest.Testdata(t, "inspect")), pdf: &leaf{name: "pdf"}, archive: &leaf{name: "archive", err: errors.New("archive: can't read entry")}, dir: t.TempDir(), diff --git a/dispatch/stream_test.go b/dispatch/test/stream_test.go similarity index 100% rename from dispatch/stream_test.go rename to dispatch/test/stream_test.go diff --git a/dispatch/testdata/dispatch.jsonl b/dispatch/test/testdata/dispatch.jsonl similarity index 100% rename from dispatch/testdata/dispatch.jsonl rename to dispatch/test/testdata/dispatch.jsonl diff --git a/dispatch/testdata/log.jsonl b/dispatch/test/testdata/log.jsonl similarity index 100% rename from dispatch/testdata/log.jsonl rename to dispatch/test/testdata/log.jsonl diff --git a/dispatch/walk_test.go b/dispatch/test/walk_test.go similarity index 100% rename from dispatch/walk_test.go rename to dispatch/test/walk_test.go diff --git a/docs/acceptance.md b/docs/acceptance.md index 419e14f0..fe5c6670 100644 --- a/docs/acceptance.md +++ b/docs/acceptance.md @@ -999,7 +999,7 @@ The whole-file run, one process for the 915 pages, is for context. ### What doesn't improve - The paragraphs of columns that line up may alternate between the columns: pdftotext reads - `document/testdata/clean.pdf`'s page 2, two columns of paragraphs side by side, a paragraph + `document/test/testdata/clean.pdf`'s page 2, two columns of paragraphs side by side, a paragraph from each in turn. - A word hyphenated at a line's end is joined, its hyphen dropped: `informa-` and `tion` read as `information`. diff --git a/docs/api.md b/docs/api.md index ebb63687..724a0356 100644 --- a/docs/api.md +++ b/docs/api.md @@ -66,6 +66,8 @@ settings a run's settings as one JSON object, validated and as output-writes bounds internal/tooltest, test helpers: the unit tier's stand-in tool, golden sums, and goldentest, mediatest media's stand-in ffmpeg run +stages/internal/stagestest test helpers the stages and adapter tests share: the stages' + stand-in programs and stages, and the dispatch helpers rundir, rundir/schema cmd/docproc's run directory: its shapes, read and written metadata the metadata records' shapes, one per format; imports dispatch only diff --git a/docs/design-review.md b/docs/design-review.md index 62511820..b71b88e5 100644 --- a/docs/design-review.md +++ b/docs/design-review.md @@ -625,7 +625,7 @@ form. An entry is carried by docproc unless it names another task; `rundir`'s AP `report` under `internal/`. Rejected: slab's layout. The architecture page's nested-command layout is a pending edit for the goal's sync. - **DP-11 · `rundir`'s contract was tested only from the command.** Accepted → docproc. - `rundir/testdata` holds one committed schema "2" run directory that `rundir`'s tests read + `rundir/test/testdata` holds one committed schema "2" run directory that `rundir`'s tests read through the reader's API and write again through the writer's. - **DP-12 · A symbolic link or special file argument yielded nothing, silently.** Accepted → docproc. A named argument that is a link is followed; one that is neither file nor directory, diff --git a/docs/packages.md b/docs/packages.md index 0c5e202e..518da7ac 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -20,6 +20,7 @@ | `metadata` | The metadata records' shapes, one per format, each a JSON value under a versioned media type `dispatch` declares: `Office`, an office package's properties and the format it was converted from; `PDF`, a PDF's information dictionary, XMP metadata, and version; `Media`, an audio or video file's container format, duration, bit rate, and tags, and its streams; and `Picture`, a picture's EXIF capture time, camera, orientation, size, GPS position, and properties. It imports no docproc package but `dispatch`, so a reader decodes a record without compiling the stages. | | `internal/cli` | The envelope reader the three readers share: their lines, stderr warnings, exit codes, and media names; and the ffprobe report audio and media read. | | `internal/goldentest`, `internal/mediatest`, `internal/tooltest` | Test helpers: PNG goldens, media fixtures, and the unit tier's stand-in tool. | +| `stages/internal/stagestest` | Test helpers the tests of `stages` and its adapters share: a stand-in for each program a stage runs, the stand-in stages over them, and the dispatch helpers. | A host registers `stages.Build`'s stages with a `dispatch.Dispatcher` and ranges over its events. No bound, cap, or limit has a library default: the run bounds (`stages.Options`' Timeout, diff --git a/document/fixtures_integration_test.go b/document/test/fixtures_integration_test.go similarity index 100% rename from document/fixtures_integration_test.go rename to document/test/fixtures_integration_test.go diff --git a/document/ghostscript_integration_test.go b/document/test/ghostscript_integration_test.go similarity index 100% rename from document/ghostscript_integration_test.go rename to document/test/ghostscript_integration_test.go diff --git a/document/ghostscript_test.go b/document/test/ghostscript_test.go similarity index 100% rename from document/ghostscript_test.go rename to document/test/ghostscript_test.go diff --git a/document/main_test.go b/document/test/main_test.go similarity index 100% rename from document/main_test.go rename to document/test/main_test.go diff --git a/document/pdfdetach_test.go b/document/test/pdfdetach_test.go similarity index 96% rename from document/pdfdetach_test.go rename to document/test/pdfdetach_test.go index edd88662..ed45ca0b 100644 --- a/document/pdfdetach_test.go +++ b/document/test/pdfdetach_test.go @@ -57,7 +57,7 @@ func TestList(t *testing.T) { if err != nil { t.Fatal(err) } - want := []document.Attachment{{1, "KSBASE.WQ2"}, {2, "two\nlines.txt"}, {3, "../../etc/passwd"}} + want := []document.Attachment{{Number: 1, Name: "KSBASE.WQ2"}, {Number: 2, Name: "two\nlines.txt"}, {Number: 3, Name: "../../etc/passwd"}} if !reflect.DeepEqual(got, want) { t.Errorf("list %+v, want %+v", got, want) } diff --git a/document/pdfinfo_test.go b/document/test/pdfinfo_test.go similarity index 100% rename from document/pdfinfo_test.go rename to document/test/pdfinfo_test.go diff --git a/document/pdftools_integration_test.go b/document/test/pdftools_integration_test.go similarity index 100% rename from document/pdftools_integration_test.go rename to document/test/pdftools_integration_test.go diff --git a/document/pdftotext_test.go b/document/test/pdftotext_test.go similarity index 100% rename from document/pdftotext_test.go rename to document/test/pdftotext_test.go diff --git a/document/prepare_integration_test.go b/document/test/prepare_integration_test.go similarity index 100% rename from document/prepare_integration_test.go rename to document/test/prepare_integration_test.go diff --git a/document/prepare_test.go b/document/test/prepare_test.go similarity index 100% rename from document/prepare_test.go rename to document/test/prepare_test.go diff --git a/document/qpdf_test.go b/document/test/qpdf_test.go similarity index 100% rename from document/qpdf_test.go rename to document/test/qpdf_test.go diff --git a/document/renderer_test.go b/document/test/renderer_test.go similarity index 100% rename from document/renderer_test.go rename to document/test/renderer_test.go diff --git a/document/testdata/README.md b/document/test/testdata/README.md similarity index 97% rename from document/testdata/README.md rename to document/test/testdata/README.md index 800f249d..d2b71961 100644 --- a/document/testdata/README.md +++ b/document/test/testdata/README.md @@ -41,7 +41,7 @@ typst never runs in the check. `generate.sh` regenerates the clean and degraded typst 0.15.1 and ImageMagick 7.1.2 on the laptop, and jq, which mise declares: ```sh -mise exec -- document/testdata/generate.sh +mise exec -- document/test/testdata/generate.sh ``` The outputs are byte-reproducible: typst sets no document date and uses only its embedded fonts, @@ -95,7 +95,7 @@ after the first six, so it comes last rather than in source order: ```sh qpdf --deterministic-id --empty \ --pages ~/code/herald/_project/marked-documents/marked-documents.pdf 2,3,12,13,16,25,19 -- \ - document/testdata/scanned.pdf + document/test/testdata/scanned.pdf ``` Each page's truth was transcribed by reading the source page's image @@ -124,7 +124,7 @@ c78b22d17c06925c3ed829a4d3cf163b61fa4f741ad33625df302aa039321b53 scanned/page-4 `forms/acroform.pdf` is this repository's, Apache-2.0: a one-page PDF whose AcroForm holds seven filled fields, written by hand by `forms/generate.go`, every byte fixed, so a rerun writes the -same bytes. Run it in `document/testdata/forms`: +same bytes. Run it in `document/test/testdata/forms`: ```sh mise exec -- go run generate.go @@ -173,7 +173,7 @@ reader of the form. qpdf 12.4.2 made the cut, one page of about 157 KB; it exits a warning about the source's object count, and `--deterministic-id` makes the output reproducible: ```sh -qpdf --deterministic-id --empty --pages cfr-2024-title32-vol1.pdf 1 -- document/testdata/forms/signed.pdf +qpdf --deterministic-id --empty --pages cfr-2024-title32-vol1.pdf 1 -- document/test/testdata/forms/signed.pdf ``` `forms/signed.json` is qpdf 12.4.2's JSON of its AcroForm, recorded verbatim so the check reads it @@ -195,7 +195,7 @@ dd1dfd83317dd0f5e673da59474f93c686d718fade7f4f145ef4788bd608a31f forms/signed.j `attachments/attachments.pdf` is this repository's, Apache-2.0: a one-page PDF that embeds a file each way a PDF holds one, written by hand by `attachments/generate.go`, every byte fixed, so a -rerun writes the same bytes. Run it in `document/testdata/attachments`: +rerun writes the same bytes. Run it in `document/test/testdata/attachments`: ```sh mise exec -- go run generate.go @@ -217,7 +217,7 @@ Its SHA-256 sum, which `TestFixtureSums` holds it to: `portfolio/portfolio.pdf` is this repository's, Apache-2.0: a PDF portfolio, written by hand by `portfolio/generate.go`, every byte fixed, so a rerun writes the same bytes. Run it in -`document/testdata/portfolio`: +`document/test/testdata/portfolio`: ```sh mise exec -- go run generate.go @@ -243,7 +243,7 @@ c459d50b851ac5fcad70ea49c2b3491d158bc975a70c2a03839c41b53c3d1754 portfolio/port `info/info.pdf` is this repository's, Apache-2.0: a one-page PDF 1.6, written by hand by `info/generate.go`, every byte fixed, so a rerun writes the same bytes. Run it in -`document/testdata/info`: +`document/test/testdata/info`: ```sh mise exec -- go run generate.go diff --git a/document/testdata/attachments/attachments.pdf b/document/test/testdata/attachments/attachments.pdf similarity index 100% rename from document/testdata/attachments/attachments.pdf rename to document/test/testdata/attachments/attachments.pdf diff --git a/document/testdata/attachments/generate.go b/document/test/testdata/attachments/generate.go similarity index 92% rename from document/testdata/attachments/generate.go rename to document/test/testdata/attachments/generate.go index b20de3ac..c8adbd8d 100644 --- a/document/testdata/attachments/generate.go +++ b/document/test/testdata/attachments/generate.go @@ -1,8 +1,8 @@ //go:build ignore -// generate writes attachments.pdf beside this file, which document/testdata/README.md describes. Run it from -// document/testdata/attachments with `mise exec -- go run generate.go`; the check never runs it, -// and reads the committed file. +// generate writes attachments.pdf beside this file, which document/test/testdata/README.md +// describes. Run it from document/test/testdata/attachments with `mise exec -- go run generate.go`; +// the check never runs it, and reads the committed file. package main import ( diff --git a/document/testdata/clean.pdf b/document/test/testdata/clean.pdf similarity index 100% rename from document/testdata/clean.pdf rename to document/test/testdata/clean.pdf diff --git a/document/testdata/clean.typ b/document/test/testdata/clean.typ similarity index 100% rename from document/testdata/clean.typ rename to document/test/testdata/clean.typ diff --git a/document/testdata/clean/page-1.txt b/document/test/testdata/clean/page-1.txt similarity index 100% rename from document/testdata/clean/page-1.txt rename to document/test/testdata/clean/page-1.txt diff --git a/document/testdata/clean/page-2.txt b/document/test/testdata/clean/page-2.txt similarity index 100% rename from document/testdata/clean/page-2.txt rename to document/test/testdata/clean/page-2.txt diff --git a/document/testdata/clean/page-3.txt b/document/test/testdata/clean/page-3.txt similarity index 100% rename from document/testdata/clean/page-3.txt rename to document/test/testdata/clean/page-3.txt diff --git a/document/testdata/clean/page-4.txt b/document/test/testdata/clean/page-4.txt similarity index 100% rename from document/testdata/clean/page-4.txt rename to document/test/testdata/clean/page-4.txt diff --git a/document/testdata/clean/page-5.txt b/document/test/testdata/clean/page-5.txt similarity index 100% rename from document/testdata/clean/page-5.txt rename to document/test/testdata/clean/page-5.txt diff --git a/document/testdata/clean/page-6.txt b/document/test/testdata/clean/page-6.txt similarity index 100% rename from document/testdata/clean/page-6.txt rename to document/test/testdata/clean/page-6.txt diff --git a/document/testdata/degraded.pdf b/document/test/testdata/degraded.pdf similarity index 100% rename from document/testdata/degraded.pdf rename to document/test/testdata/degraded.pdf diff --git a/document/testdata/degraded/page-1.txt b/document/test/testdata/degraded/page-1.txt similarity index 100% rename from document/testdata/degraded/page-1.txt rename to document/test/testdata/degraded/page-1.txt diff --git a/document/testdata/degraded/page-2.txt b/document/test/testdata/degraded/page-2.txt similarity index 100% rename from document/testdata/degraded/page-2.txt rename to document/test/testdata/degraded/page-2.txt diff --git a/document/testdata/degraded/page-3.txt b/document/test/testdata/degraded/page-3.txt similarity index 100% rename from document/testdata/degraded/page-3.txt rename to document/test/testdata/degraded/page-3.txt diff --git a/document/testdata/degraded/page-4.txt b/document/test/testdata/degraded/page-4.txt similarity index 100% rename from document/testdata/degraded/page-4.txt rename to document/test/testdata/degraded/page-4.txt diff --git a/document/testdata/degraded/page-5.txt b/document/test/testdata/degraded/page-5.txt similarity index 100% rename from document/testdata/degraded/page-5.txt rename to document/test/testdata/degraded/page-5.txt diff --git a/document/testdata/degraded/page-6.txt b/document/test/testdata/degraded/page-6.txt similarity index 100% rename from document/testdata/degraded/page-6.txt rename to document/test/testdata/degraded/page-6.txt diff --git a/document/testdata/degraded/page-7.txt b/document/test/testdata/degraded/page-7.txt similarity index 100% rename from document/testdata/degraded/page-7.txt rename to document/test/testdata/degraded/page-7.txt diff --git a/document/testdata/degraded/page-8.txt b/document/test/testdata/degraded/page-8.txt similarity index 100% rename from document/testdata/degraded/page-8.txt rename to document/test/testdata/degraded/page-8.txt diff --git a/document/testdata/degraded/page-9.txt b/document/test/testdata/degraded/page-9.txt similarity index 100% rename from document/testdata/degraded/page-9.txt rename to document/test/testdata/degraded/page-9.txt diff --git a/document/testdata/forms/acroform.json b/document/test/testdata/forms/acroform.json similarity index 100% rename from document/testdata/forms/acroform.json rename to document/test/testdata/forms/acroform.json diff --git a/document/testdata/forms/acroform.pdf b/document/test/testdata/forms/acroform.pdf similarity index 100% rename from document/testdata/forms/acroform.pdf rename to document/test/testdata/forms/acroform.pdf diff --git a/document/testdata/forms/generate.go b/document/test/testdata/forms/generate.go similarity index 95% rename from document/testdata/forms/generate.go rename to document/test/testdata/forms/generate.go index 9c21ead7..1f207d45 100644 --- a/document/testdata/forms/generate.go +++ b/document/test/testdata/forms/generate.go @@ -1,8 +1,8 @@ //go:build ignore -// generate writes acroform.pdf beside this file, which document/testdata/README.md describes. Run it from -// document/testdata/forms with `mise exec -- go run generate.go`; the check never runs it, and -// reads the committed file. +// generate writes acroform.pdf beside this file, which document/test/testdata/README.md describes. +// Run it from document/test/testdata/forms with `mise exec -- go run generate.go`; the check never +// runs it, and reads the committed file. package main import ( diff --git a/document/testdata/forms/signed.json b/document/test/testdata/forms/signed.json similarity index 100% rename from document/testdata/forms/signed.json rename to document/test/testdata/forms/signed.json diff --git a/document/testdata/forms/signed.pdf b/document/test/testdata/forms/signed.pdf similarity index 100% rename from document/testdata/forms/signed.pdf rename to document/test/testdata/forms/signed.pdf diff --git a/document/testdata/generate.sh b/document/test/testdata/generate.sh similarity index 98% rename from document/testdata/generate.sh rename to document/test/testdata/generate.sh index 70059907..880ff037 100755 --- a/document/testdata/generate.sh +++ b/document/test/testdata/generate.sh @@ -2,7 +2,7 @@ # generate regenerates the document fixtures from clean.typ: clean.pdf and its ground truth, then # degraded.pdf and its ground truth, byte-reproducibly, and prints their SHA-256 sums. It needs # typst 0.15.1 and ImageMagick 7.1.2, laptop prerequisites that the check never runs, and jq. -# See document/testdata/README.md +# See document/test/testdata/README.md set -euo pipefail cd "$(dirname "$0")" diff --git a/document/testdata/info/clean.custom.txt b/document/test/testdata/info/clean.custom.txt similarity index 100% rename from document/testdata/info/clean.custom.txt rename to document/test/testdata/info/clean.custom.txt diff --git a/document/testdata/info/clean.meta.xml b/document/test/testdata/info/clean.meta.xml similarity index 100% rename from document/testdata/info/clean.meta.xml rename to document/test/testdata/info/clean.meta.xml diff --git a/document/testdata/info/clean.summary.txt b/document/test/testdata/info/clean.summary.txt similarity index 100% rename from document/testdata/info/clean.summary.txt rename to document/test/testdata/info/clean.summary.txt diff --git a/document/testdata/info/generate.go b/document/test/testdata/info/generate.go similarity index 95% rename from document/testdata/info/generate.go rename to document/test/testdata/info/generate.go index 724e84d8..09638609 100644 --- a/document/testdata/info/generate.go +++ b/document/test/testdata/info/generate.go @@ -1,8 +1,8 @@ //go:build ignore -// generate writes info.pdf beside this file, which document/testdata/README.md describes. Run it -// from document/testdata/info with `mise exec -- go run generate.go`; the check never runs it, and -// reads the committed file. +// generate writes info.pdf beside this file, which document/test/testdata/README.md describes. Run +// it from document/test/testdata/info with `mise exec -- go run generate.go`; the check never runs +// it, and reads the committed file. package main import ( diff --git a/document/testdata/info/info.custom.txt b/document/test/testdata/info/info.custom.txt similarity index 100% rename from document/testdata/info/info.custom.txt rename to document/test/testdata/info/info.custom.txt diff --git a/document/testdata/info/info.meta.xml b/document/test/testdata/info/info.meta.xml similarity index 100% rename from document/testdata/info/info.meta.xml rename to document/test/testdata/info/info.meta.xml diff --git a/document/testdata/info/info.pdf b/document/test/testdata/info/info.pdf similarity index 100% rename from document/testdata/info/info.pdf rename to document/test/testdata/info/info.pdf diff --git a/document/testdata/info/info.summary.txt b/document/test/testdata/info/info.summary.txt similarity index 100% rename from document/testdata/info/info.summary.txt rename to document/test/testdata/info/info.summary.txt diff --git a/document/testdata/malformed/compacted-syntax.pdf b/document/test/testdata/malformed/compacted-syntax.pdf similarity index 100% rename from document/testdata/malformed/compacted-syntax.pdf rename to document/test/testdata/malformed/compacted-syntax.pdf diff --git a/document/testdata/portfolio/generate.go b/document/test/testdata/portfolio/generate.go similarity index 93% rename from document/testdata/portfolio/generate.go rename to document/test/testdata/portfolio/generate.go index 4d72bc41..a5f38067 100644 --- a/document/testdata/portfolio/generate.go +++ b/document/test/testdata/portfolio/generate.go @@ -1,8 +1,8 @@ //go:build ignore -// generate writes portfolio.pdf beside this file, which document/testdata/README.md describes. Run it from -// document/testdata/portfolio with `mise exec -- go run generate.go`; the check never runs it, -// and reads the committed file. +// generate writes portfolio.pdf beside this file, which document/test/testdata/README.md describes. +// Run it from document/test/testdata/portfolio with `mise exec -- go run generate.go`; the check +// never runs it, and reads the committed file. package main import ( diff --git a/document/testdata/portfolio/portfolio.pdf b/document/test/testdata/portfolio/portfolio.pdf similarity index 100% rename from document/testdata/portfolio/portfolio.pdf rename to document/test/testdata/portfolio/portfolio.pdf diff --git a/document/testdata/scanned.pdf b/document/test/testdata/scanned.pdf similarity index 100% rename from document/testdata/scanned.pdf rename to document/test/testdata/scanned.pdf diff --git a/document/testdata/scanned/page-1.txt b/document/test/testdata/scanned/page-1.txt similarity index 100% rename from document/testdata/scanned/page-1.txt rename to document/test/testdata/scanned/page-1.txt diff --git a/document/testdata/scanned/page-2.txt b/document/test/testdata/scanned/page-2.txt similarity index 100% rename from document/testdata/scanned/page-2.txt rename to document/test/testdata/scanned/page-2.txt diff --git a/document/testdata/scanned/page-3.txt b/document/test/testdata/scanned/page-3.txt similarity index 100% rename from document/testdata/scanned/page-3.txt rename to document/test/testdata/scanned/page-3.txt diff --git a/document/testdata/scanned/page-4.txt b/document/test/testdata/scanned/page-4.txt similarity index 100% rename from document/testdata/scanned/page-4.txt rename to document/test/testdata/scanned/page-4.txt diff --git a/document/testdata/scanned/page-5.txt b/document/test/testdata/scanned/page-5.txt similarity index 100% rename from document/testdata/scanned/page-5.txt rename to document/test/testdata/scanned/page-5.txt diff --git a/document/testdata/scanned/page-6.txt b/document/test/testdata/scanned/page-6.txt similarity index 100% rename from document/testdata/scanned/page-6.txt rename to document/test/testdata/scanned/page-6.txt diff --git a/document/testdata/scanned/page-7.txt b/document/test/testdata/scanned/page-7.txt similarity index 100% rename from document/testdata/scanned/page-7.txt rename to document/test/testdata/scanned/page-7.txt diff --git a/email/conversation_integration_test.go b/email/test/conversation_integration_test.go similarity index 100% rename from email/conversation_integration_test.go rename to email/test/conversation_integration_test.go diff --git a/email/conversation_test.go b/email/test/conversation_test.go similarity index 100% rename from email/conversation_test.go rename to email/test/conversation_test.go diff --git a/email/email_test.go b/email/test/email_test.go similarity index 100% rename from email/email_test.go rename to email/test/email_test.go diff --git a/email/main_test.go b/email/test/main_test.go similarity index 100% rename from email/main_test.go rename to email/test/main_test.go diff --git a/email/real_integration_test.go b/email/test/real_integration_test.go similarity index 94% rename from email/real_integration_test.go rename to email/test/real_integration_test.go index 1a8ab22a..cc98c982 100644 --- a/email/real_integration_test.go +++ b/email/test/real_integration_test.go @@ -146,23 +146,24 @@ type builtSource struct { } var builtSources = []builtSource{ - {"minutes.docx", "../office/testdata/ooxml/tables.libreoffice.docx", ""}, - {"budget.xls", "../office/testdata/legacy/generated/formulas.libreoffice.xls", ""}, - {"scan.tif", "../office/testdata/pictures/tiff.docx", "word/media/image1.tiff"}, - {"diagram.emf", "../office/testdata/ooxml/word-with-attachments.docx", "word/media/image4.emf"}, + {"minutes.docx", "ooxml/tables.libreoffice.docx", ""}, + {"budget.xls", "legacy/generated/formulas.libreoffice.xls", ""}, + {"scan.tif", "pictures/tiff.docx", "word/media/image1.tiff"}, + {"diagram.emf", "ooxml/word-with-attachments.docx", "word/media/image4.emf"}, {"forwarded.msg", "", ""}, } func (s builtSource) content(t *testing.T) []byte { t.Helper() + path := tooltest.Testdata(t, "office", s.path) if s.member == "" { - b, err := os.ReadFile(s.path) + b, err := os.ReadFile(path) if err != nil { t.Fatal(err) } return b } - return zipMember(t, s.path, s.member) + return zipMember(t, path, s.member) } func zipMember(t *testing.T, path, member string) []byte { diff --git a/email/replay_test.go b/email/test/replay_test.go similarity index 100% rename from email/replay_test.go rename to email/test/replay_test.go diff --git a/email/resume_integration_test.go b/email/test/resume_integration_test.go similarity index 100% rename from email/resume_integration_test.go rename to email/test/resume_integration_test.go diff --git a/email/testdata/README.md b/email/test/testdata/README.md similarity index 53% rename from email/testdata/README.md rename to email/test/testdata/README.md index e9660e08..9c011e41 100644 --- a/email/testdata/README.md +++ b/email/test/testdata/README.md @@ -6,17 +6,17 @@ tests read them in place under `tools/mail/tests/`, through `internal/tooltest`' ## built `built/` holds one `.msg` built for this package: `msg/office-attachments.msg`, built from -`eml/office-attachments.eml` by spike-ai-pipeline-mail's fixtures generator at its tag `v0.1.0`, -in its fixtures mode, through MsgKit 3.0.6 and MimeKit 4.18.2 on the .NET SDK 10.0.402. The -source attaches five files, byte for byte. Four are this repository's committed office fixtures: -`minutes.docx`, which is `office/testdata/ooxml/tables.libreoffice.docx`; `budget.xls`, which is -`office/testdata/legacy/generated/formulas.libreoffice.xls`; `scan.tif`, the -`word/media/image1.tiff` member of `office/testdata/pictures/tiff.docx`; and `diagram.emf`, the -`word/media/image4.emf` member of `office/testdata/ooxml/word-with-attachments.docx`. Their -licenses are the office fixtures' (`office/testdata/README.md`). The fifth, `forwarded.msg`, is +`eml/office-attachments.eml` by spike-ai-pipeline-mail's fixtures generator at its tag `v0.1.0`, in +its fixtures mode, through MsgKit 3.0.6 and MimeKit 4.18.2 on the .NET SDK 10.0.402. The source +attaches five files, byte for byte. Four are this repository's committed office fixtures: +`minutes.docx`, which is `office/test/testdata/ooxml/tables.libreoffice.docx`; `budget.xls`, which +is `office/test/testdata/legacy/generated/formulas.libreoffice.xls`; `scan.tif`, the +`word/media/image1.tiff` member of `office/test/testdata/pictures/tiff.docx`; and `diagram.emf`, the +`word/media/image4.emf` member of `office/test/testdata/ooxml/word-with-attachments.docx`. Their +licenses are the office fixtures' (`office/test/testdata/README.md`). The fifth, `forwarded.msg`, is spike-ai-pipeline-mail v0.3.1's generated `03-html-inline-image.msg`, attached as a file, which -docproc-mail reads back by value and writes as it is, not as an embedded message; docproc-mail's -own generated fixtures were rebuilt since, so its copy there differs byte for byte. +docproc-mail reads back by value and writes as it is, not as an embedded message; docproc-mail's own +generated fixtures were rebuilt since, so its copy there differs byte for byte. MsgKit's `.msg` isn't byte-stable, so a rebuild changes its SHA-256; the tests pin its content instead, each of the four office attachments docproc-mail writes byte for byte its source. MsgKit diff --git a/email/testdata/built/eml/office-attachments.eml b/email/test/testdata/built/eml/office-attachments.eml similarity index 100% rename from email/testdata/built/eml/office-attachments.eml rename to email/test/testdata/built/eml/office-attachments.eml diff --git a/email/testdata/built/msg/office-attachments.msg b/email/test/testdata/built/msg/office-attachments.msg similarity index 100% rename from email/testdata/built/msg/office-attachments.msg rename to email/test/testdata/built/msg/office-attachments.msg diff --git a/email/threads_integration_test.go b/email/test/threads_integration_test.go similarity index 100% rename from email/threads_integration_test.go rename to email/test/threads_integration_test.go diff --git a/email/threads_test.go b/email/test/threads_test.go similarity index 100% rename from email/threads_test.go rename to email/test/threads_test.go diff --git a/inspect/clean_test.go b/inspect/clean_test.go deleted file mode 100644 index 993d8f86..00000000 --- a/inspect/clean_test.go +++ /dev/null @@ -1,60 +0,0 @@ -//go:build linux - -package inspect_test - -import ( - "io/fs" - "path/filepath" - "slices" - "testing" - - "github.com/standards-lab/docproc/inspect" -) - -var cleanDirs = []string{"../office/testdata", "../document/testdata", "../picture/testdata", "../tool/testdata", "../email/testdata"} - -var cleanSkipped = map[string]bool{"../picture/testdata/script-bearing.svg": true} - -var cleanFlags = map[string][]inspect.Check{ - "../office/testdata/ooxml/media.libreoffice.docx": {inspect.ExternalRelationship}, - "../office/testdata/ooxml/word-with-attachments.docx": {inspect.OLEObject}, - "../office/testdata/xlsb/protected_passtika.xlsb": {inspect.OOXMLEncrypted}, - "../office/testdata/xlsb/testVarious.xlsb": {inspect.VBAProject}, - "../document/testdata/attachments/attachments.pdf": {inspect.PDFEmbeddedFile}, - "../document/testdata/portfolio/portfolio.pdf": {inspect.PDFEmbeddedFile}, - "../document/testdata/malformed/compacted-syntax.pdf": {inspect.PDFAA, inspect.PDFJavaScript, inspect.PDFJS}, -} - -func TestCleanFixtures(t *testing.T) { - n := 0 - seen := map[string]bool{} - for _, dir := range cleanDirs { - err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { - if err != nil || d.IsDir() || filepath.Ext(path) == ".sh" || cleanSkipped[path] { - return err - } - n++ - seen[path] = true - r := mustInspect(t, path, d.Name(), inspect.Options{}) - if got, want := checks(r), cleanFlags[path]; !slices.Equal(got, want) { - t.Errorf("%s: checks %v, want %v (%+v)", path, got, want, r.Flags) - } - if r.Verdict != inspect.Proceed { - t.Errorf("%s: verdict %s", path, r.Verdict) - } - return nil - }) - if err != nil { - t.Fatal(err) - } - } - for path := range cleanFlags { - if !seen[path] { - t.Errorf("%s: no such clean fixture", path) - } - } - if n == 0 { - t.Fatal("no clean fixture inspected") - } - t.Logf("inspected %d clean fixtures", n) -} diff --git a/inspect/clean_integration_test.go b/inspect/test/clean_integration_test.go similarity index 98% rename from inspect/clean_integration_test.go rename to inspect/test/clean_integration_test.go index 444e56b8..fa03495a 100644 --- a/inspect/clean_integration_test.go +++ b/inspect/test/clean_integration_test.go @@ -26,7 +26,7 @@ func TestCleanAttachments(t *testing.T) { t.Fatal(err) } var inputs []string - for _, root := range []string{tooltest.Tools(t, "mail/tests/fixtures"), "../email/testdata"} { + for _, root := range []string{tooltest.Tools(t, "mail/tests/fixtures"), tooltest.Testdata(t, "email")} { err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { if err != nil || d.IsDir() { return err diff --git a/inspect/test/clean_test.go b/inspect/test/clean_test.go new file mode 100644 index 00000000..aba0637e --- /dev/null +++ b/inspect/test/clean_test.go @@ -0,0 +1,70 @@ +//go:build linux + +package inspect_test + +import ( + "io/fs" + "path/filepath" + "slices" + "testing" + + "github.com/standards-lab/docproc/inspect" + "github.com/standards-lab/docproc/internal/tooltest" +) + +var cleanPackages = []string{"office", "document", "picture", "tool", "email"} + +var cleanSkipped = map[string]bool{"picture/script-bearing.svg": true} + +var cleanFlags = map[string][]inspect.Check{ + "office/ooxml/media.libreoffice.docx": {inspect.ExternalRelationship}, + "office/ooxml/word-with-attachments.docx": {inspect.OLEObject}, + "office/xlsb/protected_passtika.xlsb": {inspect.OOXMLEncrypted}, + "office/xlsb/testVarious.xlsb": {inspect.VBAProject}, + "document/attachments/attachments.pdf": {inspect.PDFEmbeddedFile}, + "document/portfolio/portfolio.pdf": {inspect.PDFEmbeddedFile}, + "document/malformed/compacted-syntax.pdf": {inspect.PDFAA, inspect.PDFJavaScript, inspect.PDFJS}, +} + +func TestCleanFixtures(t *testing.T) { + n := 0 + seen := map[string]bool{} + for _, pkg := range cleanPackages { + dir := tooltest.Testdata(t, pkg) + err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + rel, err := filepath.Rel(dir, path) + if err != nil { + return err + } + key := pkg + "/" + filepath.ToSlash(rel) + if filepath.Ext(path) == ".sh" || cleanSkipped[key] { + return nil + } + n++ + seen[key] = true + r := mustInspect(t, path, d.Name(), inspect.Options{}) + if got, want := checks(r), cleanFlags[key]; !slices.Equal(got, want) { + t.Errorf("%s: checks %v, want %v (%+v)", path, got, want, r.Flags) + } + if r.Verdict != inspect.Proceed { + t.Errorf("%s: verdict %s", path, r.Verdict) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + for key := range cleanFlags { + if !seen[key] { + t.Errorf("%s: no such clean fixture", key) + } + } + if n == 0 { + t.Fatal("no clean fixture inspected") + } + t.Logf("inspected %d clean fixtures", n) +} diff --git a/inspect/inspect_test.go b/inspect/test/inspect_test.go similarity index 100% rename from inspect/inspect_test.go rename to inspect/test/inspect_test.go diff --git a/inspect/listing_test.go b/inspect/test/listing_test.go similarity index 100% rename from inspect/listing_test.go rename to inspect/test/listing_test.go diff --git a/inspect/main_test.go b/inspect/test/main_test.go similarity index 100% rename from inspect/main_test.go rename to inspect/test/main_test.go diff --git a/inspect/rules_test.go b/inspect/test/rules_test.go similarity index 100% rename from inspect/rules_test.go rename to inspect/test/rules_test.go diff --git a/inspect/scan_test.go b/inspect/test/scan_test.go similarity index 100% rename from inspect/scan_test.go rename to inspect/test/scan_test.go diff --git a/inspect/testdata/README.md b/inspect/test/testdata/README.md similarity index 100% rename from inspect/testdata/README.md rename to inspect/test/testdata/README.md diff --git a/inspect/testdata/absolute.tar b/inspect/test/testdata/absolute.tar similarity index 100% rename from inspect/testdata/absolute.tar rename to inspect/test/testdata/absolute.tar diff --git a/inspect/testdata/absolute.zip b/inspect/test/testdata/absolute.zip similarity index 100% rename from inspect/testdata/absolute.zip rename to inspect/test/testdata/absolute.zip diff --git a/inspect/testdata/bomb.tar.gz b/inspect/test/testdata/bomb.tar.gz similarity index 100% rename from inspect/testdata/bomb.tar.gz rename to inspect/test/testdata/bomb.tar.gz diff --git a/inspect/testdata/bomb.zip b/inspect/test/testdata/bomb.zip similarity index 100% rename from inspect/testdata/bomb.zip rename to inspect/test/testdata/bomb.zip diff --git a/inspect/testdata/clean.tar b/inspect/test/testdata/clean.tar similarity index 100% rename from inspect/testdata/clean.tar rename to inspect/test/testdata/clean.tar diff --git a/inspect/testdata/clean.tar.gz b/inspect/test/testdata/clean.tar.gz similarity index 100% rename from inspect/testdata/clean.tar.gz rename to inspect/test/testdata/clean.tar.gz diff --git a/inspect/testdata/declared-bomb.zip b/inspect/test/testdata/declared-bomb.zip similarity index 100% rename from inspect/testdata/declared-bomb.zip rename to inspect/test/testdata/declared-bomb.zip diff --git a/inspect/testdata/device.tar b/inspect/test/testdata/device.tar similarity index 100% rename from inspect/testdata/device.tar rename to inspect/test/testdata/device.tar diff --git a/inspect/testdata/encrypted.xlsx b/inspect/test/testdata/encrypted.xlsx similarity index 100% rename from inspect/testdata/encrypted.xlsx rename to inspect/test/testdata/encrypted.xlsx diff --git a/inspect/testdata/encrypted.zip b/inspect/test/testdata/encrypted.zip similarity index 100% rename from inspect/testdata/encrypted.zip rename to inspect/test/testdata/encrypted.zip diff --git a/inspect/testdata/generate.go b/inspect/test/testdata/generate.go similarity index 98% rename from inspect/testdata/generate.go rename to inspect/test/testdata/generate.go index aee6947b..4381b52a 100644 --- a/inspect/testdata/generate.go +++ b/inspect/test/testdata/generate.go @@ -1,8 +1,8 @@ //go:build ignore // generate writes the inspect package's synthesized hazard fixtures, which README.md describes, -// into the directory it runs in. Run it from inspect/testdata with `go run generate.go`; the check -// never runs it, and reads the committed files. +// into the directory it runs in. Run it from inspect/test/testdata with `go run generate.go`; the +// check never runs it, and reads the committed files. package main import ( diff --git a/inspect/testdata/hardlink.tar b/inspect/test/testdata/hardlink.tar similarity index 100% rename from inspect/testdata/hardlink.tar rename to inspect/test/testdata/hardlink.tar diff --git a/inspect/testdata/hyperlink.docx b/inspect/test/testdata/hyperlink.docx similarity index 100% rename from inspect/testdata/hyperlink.docx rename to inspect/test/testdata/hyperlink.docx diff --git a/inspect/testdata/invoice.pdf.exe b/inspect/test/testdata/invoice.pdf.exe similarity index 100% rename from inspect/testdata/invoice.pdf.exe rename to inspect/test/testdata/invoice.pdf.exe diff --git a/inspect/testdata/javascript.pdf b/inspect/test/testdata/javascript.pdf similarity index 100% rename from inspect/testdata/javascript.pdf rename to inspect/test/testdata/javascript.pdf diff --git a/inspect/testdata/macro-latin1.docm b/inspect/test/testdata/macro-latin1.docm similarity index 100% rename from inspect/testdata/macro-latin1.docm rename to inspect/test/testdata/macro-latin1.docm diff --git a/inspect/testdata/macro-utf16.docm b/inspect/test/testdata/macro-utf16.docm similarity index 100% rename from inspect/testdata/macro-utf16.docm rename to inspect/test/testdata/macro-utf16.docm diff --git a/inspect/testdata/macro.docm b/inspect/test/testdata/macro.docm similarity index 100% rename from inspect/testdata/macro.docm rename to inspect/test/testdata/macro.docm diff --git a/inspect/testdata/mismatch.pdf b/inspect/test/testdata/mismatch.pdf similarity index 100% rename from inspect/testdata/mismatch.pdf rename to inspect/test/testdata/mismatch.pdf diff --git a/inspect/testdata/polyglot.jpg b/inspect/test/testdata/polyglot.jpg similarity index 100% rename from inspect/testdata/polyglot.jpg rename to inspect/test/testdata/polyglot.jpg diff --git a/inspect/testdata/polyglot.png b/inspect/test/testdata/polyglot.png similarity index 100% rename from inspect/testdata/polyglot.png rename to inspect/test/testdata/polyglot.png diff --git a/inspect/testdata/script-latin1.svg b/inspect/test/testdata/script-latin1.svg similarity index 100% rename from inspect/testdata/script-latin1.svg rename to inspect/test/testdata/script-latin1.svg diff --git a/inspect/testdata/script-utf16.svg b/inspect/test/testdata/script-utf16.svg similarity index 100% rename from inspect/testdata/script-utf16.svg rename to inspect/test/testdata/script-utf16.svg diff --git a/inspect/testdata/script.svg b/inspect/test/testdata/script.svg similarity index 100% rename from inspect/testdata/script.svg rename to inspect/test/testdata/script.svg diff --git a/inspect/testdata/sparse-bomb.tar b/inspect/test/testdata/sparse-bomb.tar similarity index 100% rename from inspect/testdata/sparse-bomb.tar rename to inspect/test/testdata/sparse-bomb.tar diff --git a/inspect/testdata/symlink.tar b/inspect/test/testdata/symlink.tar similarity index 100% rename from inspect/testdata/symlink.tar rename to inspect/test/testdata/symlink.tar diff --git a/inspect/testdata/symlink.zip b/inspect/test/testdata/symlink.zip similarity index 100% rename from inspect/testdata/symlink.zip rename to inspect/test/testdata/symlink.zip diff --git a/inspect/testdata/traversal.tar b/inspect/test/testdata/traversal.tar similarity index 100% rename from inspect/testdata/traversal.tar rename to inspect/test/testdata/traversal.tar diff --git a/inspect/testdata/traversal.tar.gz b/inspect/test/testdata/traversal.tar.gz similarity index 100% rename from inspect/testdata/traversal.tar.gz rename to inspect/test/testdata/traversal.tar.gz diff --git a/inspect/testdata/traversal.zip b/inspect/test/testdata/traversal.zip similarity index 100% rename from inspect/testdata/traversal.zip rename to inspect/test/testdata/traversal.zip diff --git a/inspect/testdata/unnamed.tgz b/inspect/test/testdata/unnamed.tgz similarity index 100% rename from inspect/testdata/unnamed.tgz rename to inspect/test/testdata/unnamed.tgz diff --git a/internal/cli/cases_test.go b/internal/cli/test/cases_test.go similarity index 100% rename from internal/cli/cases_test.go rename to internal/cli/test/cases_test.go diff --git a/internal/cli/cli_test.go b/internal/cli/test/cli_test.go similarity index 100% rename from internal/cli/cli_test.go rename to internal/cli/test/cli_test.go diff --git a/internal/cli/contract_test.go b/internal/cli/test/contract_test.go similarity index 100% rename from internal/cli/contract_test.go rename to internal/cli/test/contract_test.go diff --git a/internal/cli/envelope_test.go b/internal/cli/test/envelope_test.go similarity index 100% rename from internal/cli/envelope_test.go rename to internal/cli/test/envelope_test.go diff --git a/internal/cli/ffprobe_test.go b/internal/cli/test/ffprobe_test.go similarity index 96% rename from internal/cli/ffprobe_test.go rename to internal/cli/test/ffprobe_test.go index 75e633ac..c9fb9530 100644 --- a/internal/cli/ffprobe_test.go +++ b/internal/cli/test/ffprobe_test.go @@ -2,11 +2,11 @@ package cli_test import ( "os" - "path/filepath" "reflect" "testing" "github.com/standards-lab/docproc/internal/cli" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/metadata" ) @@ -48,7 +48,7 @@ func TestFFprobeMetadataGoldens(t *testing.T) { } { t.Run(c.golden, func(t *testing.T) { t.Parallel() - data, err := os.ReadFile(filepath.Join("..", "..", "audio", "testdata", c.golden)) + data, err := os.ReadFile(tooltest.Testdata(t, "audio", c.golden)) if err != nil { t.Fatal(err) } diff --git a/internal/cli/lines_test.go b/internal/cli/test/lines_test.go similarity index 100% rename from internal/cli/lines_test.go rename to internal/cli/test/lines_test.go diff --git a/internal/cli/main_test.go b/internal/cli/test/main_test.go similarity index 100% rename from internal/cli/main_test.go rename to internal/cli/test/main_test.go diff --git a/internal/cli/utc_test.go b/internal/cli/test/utc_test.go similarity index 100% rename from internal/cli/utc_test.go rename to internal/cli/test/utc_test.go diff --git a/internal/goldentest/goldentest_test.go b/internal/goldentest/test/goldentest_test.go similarity index 100% rename from internal/goldentest/goldentest_test.go rename to internal/goldentest/test/goldentest_test.go diff --git a/internal/goldentest/main_test.go b/internal/goldentest/test/main_test.go similarity index 100% rename from internal/goldentest/main_test.go rename to internal/goldentest/test/main_test.go diff --git a/internal/tooltest/doc.go b/internal/tooltest/doc.go index fa14b3e7..3c3681e2 100644 --- a/internal/tooltest/doc.go +++ b/internal/tooltest/doc.go @@ -1,8 +1,8 @@ // Package tooltest holds the unit tier's stand-in tool, which every test package that runs a -// tool runs in place of the real program, and the one helper that reads the system tools' data -// under tools/ in place. No unit test runs a real program or reads a docs-corpus checkout: a -// package's tests build their Tools over stand-in links, and the integration tier, under the -// integration build tag, runs the real tools. +// tool runs in place of the real program, the one helper that reads the system tools' data under +// tools/ in place, and the one that names another package's fixtures. No unit test runs a real +// program or reads a docs-corpus checkout: a package's tests build their Tools over stand-in links, +// and the integration tier, under the integration build tag, runs the real tools. // // A stand-in is the test binary itself, linked under a program's name. Link makes the link and // writes the stand-in's settings into a file the link names, beside it, so a run of the link finds @@ -33,4 +33,5 @@ // - [GSPages] returns the pages a gs run's arguments name, its page list's or its first page. // - [Tools] returns the path of a file or directory under tools/, skipping when the tree is // absent and failing when the file is. +// - [Testdata] returns the path of another package's fixture, under its test/testdata. package tooltest diff --git a/internal/tooltest/tooltest_test.go b/internal/tooltest/test/tooltest_test.go similarity index 100% rename from internal/tooltest/tooltest_test.go rename to internal/tooltest/test/tooltest_test.go diff --git a/internal/tooltest/testdata.go b/internal/tooltest/testdata.go new file mode 100644 index 00000000..bb0eed1e --- /dev/null +++ b/internal/tooltest/testdata.go @@ -0,0 +1,36 @@ +package tooltest + +import ( + "os" + "path/filepath" + "testing" +) + +// Testdata returns the path, from the working directory, of a fixture under pkg's test/testdata, +// for a test to read another package's fixtures in place: pkg is a package's slash-separated +// directory in the base module, such as "office" or "internal/cli", and elem, joined, the +// fixture's path under the package's test/testdata. The base module's root is the directory of the +// go.mod nearest the working directory, as for [Tools]. A fixture that isn't there fails the test. +func Testdata(t testing.TB, pkg string, elem ...string) string { + t.Helper() + dir, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + root, err := moduleRoot(dir) + if err != nil { + t.Fatal(err) + } + parts := []string{root, filepath.FromSlash(pkg), "test", "testdata"} + for _, e := range elem { + parts = append(parts, filepath.FromSlash(e)) + } + path, err := filepath.Rel(dir, filepath.Join(parts...)) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path); err != nil { + t.Fatalf("tooltest: %v", err) + } + return path +} diff --git a/media/main_test.go b/media/test/main_test.go similarity index 100% rename from media/main_test.go rename to media/test/main_test.go diff --git a/media/media_integration_test.go b/media/test/media_integration_test.go similarity index 96% rename from media/media_integration_test.go rename to media/test/media_integration_test.go index effa828c..4e83d5e8 100644 --- a/media/media_integration_test.go +++ b/media/test/media_integration_test.go @@ -14,6 +14,7 @@ import ( "time" "github.com/standards-lab/docproc/audio" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/media" ) @@ -38,7 +39,7 @@ type scenesTruth struct { func readTruth(t *testing.T) scenesTruth { t.Helper() - b, err := os.ReadFile(filepath.Join("..", "audio", "testdata", "speech-scenes.truth.json")) + b, err := os.ReadFile(tooltest.Testdata(t, "audio", "speech-scenes.truth.json")) if err != nil { t.Fatal(err) } @@ -51,7 +52,7 @@ func readTruth(t *testing.T) scenesTruth { func fixture(t *testing.T) string { t.Helper() - b, err := os.ReadFile(filepath.Join("..", "audio", "testdata", "speech-scenes.mkv")) + b, err := os.ReadFile(tooltest.Testdata(t, "audio", "speech-scenes.mkv")) if err != nil { t.Fatal(err) } diff --git a/media/media_test.go b/media/test/media_test.go similarity index 98% rename from media/media_test.go rename to media/test/media_test.go index b94012ba..83f25793 100644 --- a/media/media_test.go +++ b/media/test/media_test.go @@ -19,6 +19,7 @@ import ( "github.com/standards-lab/docproc/audio" "github.com/standards-lab/docproc/internal/mediatest" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/media" "github.com/standards-lab/docproc/metadata" "github.com/standards-lab/docproc/tool" @@ -47,8 +48,6 @@ var sceneReasons = []media.Reason{ media.ReasonInterval, media.ReasonScene, media.ReasonScene, media.ReasonInterval, } -var gainWAV = filepath.Join("..", "audio", "testdata", "speech-gain.wav") - func source(t *testing.T) string { t.Helper() path := filepath.Join(t.TempDir(), "source.mkv") @@ -60,7 +59,7 @@ func source(t *testing.T) string { func setStandin(t *testing.T, st *standins, probe string, frames []mediatest.Frame) { t.Helper() - pcm, err := filepath.Abs(gainWAV) + pcm, err := filepath.Abs(tooltest.Testdata(t, "audio", "speech-gain.wav")) if err != nil { t.Fatal(err) } @@ -155,7 +154,7 @@ const frameBytes = 2 * audio.SampleRate * int(audio.FrameLength) / int(time.Seco func expectedThresholds(t *testing.T, req audio.Request) ([]audio.Window, [][]byte, []float64) { t.Helper() - data, err := os.ReadFile(gainWAV) + data, err := os.ReadFile(tooltest.Testdata(t, "audio", "speech-gain.wav")) if err != nil { t.Fatal(err) } @@ -305,7 +304,7 @@ func TestEventsNoMedia(t *testing.T) { func TestEventsMetadata(t *testing.T) { t.Parallel() - report, err := os.ReadFile(filepath.Join("..", "audio", "testdata", "speech-scenes.ffprobe.json")) + report, err := os.ReadFile(tooltest.Testdata(t, "audio", "speech-scenes.ffprobe.json")) if err != nil { t.Fatal(err) } @@ -480,7 +479,7 @@ func TestEventsOpenSilence(t *testing.T) { t.Parallel() s, st := standinStreamer(t) setStandin(t, st, probeAudio, nil) - data, err := os.ReadFile(gainWAV) + data, err := os.ReadFile(tooltest.Testdata(t, "audio", "speech-gain.wav")) if err != nil { t.Fatal(err) } diff --git a/media/runners_test.go b/media/test/runners_test.go similarity index 100% rename from media/runners_test.go rename to media/test/runners_test.go diff --git a/metadata/main_test.go b/metadata/test/main_test.go similarity index 100% rename from metadata/main_test.go rename to metadata/test/main_test.go diff --git a/metadata/metadata_test.go b/metadata/test/metadata_test.go similarity index 100% rename from metadata/metadata_test.go rename to metadata/test/metadata_test.go diff --git a/office/golden_integration_test.go b/office/test/golden_integration_test.go similarity index 100% rename from office/golden_integration_test.go rename to office/test/golden_integration_test.go diff --git a/office/legacy_integration_test.go b/office/test/legacy_integration_test.go similarity index 100% rename from office/legacy_integration_test.go rename to office/test/legacy_integration_test.go diff --git a/office/legacy_test.go b/office/test/legacy_test.go similarity index 100% rename from office/legacy_test.go rename to office/test/legacy_test.go diff --git a/office/main_test.go b/office/test/main_test.go similarity index 100% rename from office/main_test.go rename to office/test/main_test.go diff --git a/office/metadata_test.go b/office/test/metadata_test.go similarity index 100% rename from office/metadata_test.go rename to office/test/metadata_test.go diff --git a/office/odf_integration_test.go b/office/test/odf_integration_test.go similarity index 100% rename from office/odf_integration_test.go rename to office/test/odf_integration_test.go diff --git a/office/odf_test.go b/office/test/odf_test.go similarity index 100% rename from office/odf_test.go rename to office/test/odf_test.go diff --git a/office/office_test.go b/office/test/office_test.go similarity index 100% rename from office/office_test.go rename to office/test/office_test.go diff --git a/office/picture_integration_test.go b/office/test/picture_integration_test.go similarity index 100% rename from office/picture_integration_test.go rename to office/test/picture_integration_test.go diff --git a/office/pictures_integration_test.go b/office/test/pictures_integration_test.go similarity index 100% rename from office/pictures_integration_test.go rename to office/test/pictures_integration_test.go diff --git a/office/pictures_test.go b/office/test/pictures_test.go similarity index 100% rename from office/pictures_test.go rename to office/test/pictures_test.go diff --git a/office/real_integration_test.go b/office/test/real_integration_test.go similarity index 100% rename from office/real_integration_test.go rename to office/test/real_integration_test.go diff --git a/office/replay_test.go b/office/test/replay_test.go similarity index 100% rename from office/replay_test.go rename to office/test/replay_test.go diff --git a/office/rtf_integration_test.go b/office/test/rtf_integration_test.go similarity index 100% rename from office/rtf_integration_test.go rename to office/test/rtf_integration_test.go diff --git a/office/testdata/README.md b/office/test/testdata/README.md similarity index 100% rename from office/testdata/README.md rename to office/test/testdata/README.md diff --git a/office/testdata/golden/pictures.sha256 b/office/test/testdata/golden/pictures.sha256 similarity index 100% rename from office/testdata/golden/pictures.sha256 rename to office/test/testdata/golden/pictures.sha256 diff --git a/office/testdata/legacy/generate.sh b/office/test/testdata/legacy/generate.sh similarity index 93% rename from office/testdata/legacy/generate.sh rename to office/test/testdata/legacy/generate.sh index 8558fe58..02309b08 100755 --- a/office/testdata/legacy/generate.sh +++ b/office/test/testdata/legacy/generate.sh @@ -4,12 +4,12 @@ # named as its original with the legacy extension, with LibreOffice run as the office package runs # it. It writes generated/MANIFEST: the image, soffice's --version line, and each file's SHA-256. # It needs docker, a laptop prerequisite that the check never runs. -# See office/testdata/README.md +# See office/test/testdata/README.md set -euo pipefail cd "$(dirname "$0")" picture_libreoffice_image() { - tr '\n' ' ' <../../../picture/spec.go | sed -E 's/"[[:space:]]*\+[[:space:]]*"//g' | + tr '\n' ' ' <../../../../picture/spec.go | sed -E 's/"[[:space:]]*\+[[:space:]]*"//g' | grep -oE 'gotenberg/gotenberg:[^"@]+@sha256:[0-9a-f]{64}' } diff --git a/office/testdata/legacy/generated/MANIFEST b/office/test/testdata/legacy/generated/MANIFEST similarity index 100% rename from office/testdata/legacy/generated/MANIFEST rename to office/test/testdata/legacy/generated/MANIFEST diff --git a/office/testdata/legacy/generated/bullets.libreoffice.ppt b/office/test/testdata/legacy/generated/bullets.libreoffice.ppt similarity index 100% rename from office/testdata/legacy/generated/bullets.libreoffice.ppt rename to office/test/testdata/legacy/generated/bullets.libreoffice.ppt diff --git a/office/testdata/legacy/generated/cells.libreoffice.xls b/office/test/testdata/legacy/generated/cells.libreoffice.xls similarity index 100% rename from office/testdata/legacy/generated/cells.libreoffice.xls rename to office/test/testdata/legacy/generated/cells.libreoffice.xls diff --git a/office/testdata/legacy/generated/charts.libreoffice.doc b/office/test/testdata/legacy/generated/charts.libreoffice.doc similarity index 100% rename from office/testdata/legacy/generated/charts.libreoffice.doc rename to office/test/testdata/legacy/generated/charts.libreoffice.doc diff --git a/office/testdata/legacy/generated/comments.libreoffice.doc b/office/test/testdata/legacy/generated/comments.libreoffice.doc similarity index 100% rename from office/testdata/legacy/generated/comments.libreoffice.doc rename to office/test/testdata/legacy/generated/comments.libreoffice.doc diff --git a/office/testdata/legacy/generated/drawings.libreoffice.xls b/office/test/testdata/legacy/generated/drawings.libreoffice.xls similarity index 100% rename from office/testdata/legacy/generated/drawings.libreoffice.xls rename to office/test/testdata/legacy/generated/drawings.libreoffice.xls diff --git a/office/testdata/legacy/generated/formulas.libreoffice.xls b/office/test/testdata/legacy/generated/formulas.libreoffice.xls similarity index 100% rename from office/testdata/legacy/generated/formulas.libreoffice.xls rename to office/test/testdata/legacy/generated/formulas.libreoffice.xls diff --git a/office/testdata/legacy/generated/lists.libreoffice.doc b/office/test/testdata/legacy/generated/lists.libreoffice.doc similarity index 100% rename from office/testdata/legacy/generated/lists.libreoffice.doc rename to office/test/testdata/legacy/generated/lists.libreoffice.doc diff --git a/office/testdata/legacy/generated/media.libreoffice.doc b/office/test/testdata/legacy/generated/media.libreoffice.doc similarity index 100% rename from office/testdata/legacy/generated/media.libreoffice.doc rename to office/test/testdata/legacy/generated/media.libreoffice.doc diff --git a/office/testdata/legacy/generated/merges.libreoffice.xls b/office/test/testdata/legacy/generated/merges.libreoffice.xls similarity index 100% rename from office/testdata/legacy/generated/merges.libreoffice.xls rename to office/test/testdata/legacy/generated/merges.libreoffice.xls diff --git a/office/testdata/legacy/generated/notes.libreoffice.doc b/office/test/testdata/legacy/generated/notes.libreoffice.doc similarity index 100% rename from office/testdata/legacy/generated/notes.libreoffice.doc rename to office/test/testdata/legacy/generated/notes.libreoffice.doc diff --git a/office/testdata/legacy/generated/sections.libreoffice.doc b/office/test/testdata/legacy/generated/sections.libreoffice.doc similarity index 100% rename from office/testdata/legacy/generated/sections.libreoffice.doc rename to office/test/testdata/legacy/generated/sections.libreoffice.doc diff --git a/office/testdata/legacy/generated/slide-objects.libreoffice.ppt b/office/test/testdata/legacy/generated/slide-objects.libreoffice.ppt similarity index 100% rename from office/testdata/legacy/generated/slide-objects.libreoffice.ppt rename to office/test/testdata/legacy/generated/slide-objects.libreoffice.ppt diff --git a/office/testdata/legacy/generated/slides.libreoffice.ppt b/office/test/testdata/legacy/generated/slides.libreoffice.ppt similarity index 100% rename from office/testdata/legacy/generated/slides.libreoffice.ppt rename to office/test/testdata/legacy/generated/slides.libreoffice.ppt diff --git a/office/testdata/legacy/generated/tables.libreoffice.doc b/office/test/testdata/legacy/generated/tables.libreoffice.doc similarity index 100% rename from office/testdata/legacy/generated/tables.libreoffice.doc rename to office/test/testdata/legacy/generated/tables.libreoffice.doc diff --git a/office/testdata/legacy/real/SampleSS.truth.json b/office/test/testdata/legacy/real/SampleSS.truth.json similarity index 100% rename from office/testdata/legacy/real/SampleSS.truth.json rename to office/test/testdata/legacy/real/SampleSS.truth.json diff --git a/office/testdata/legacy/real/SampleSS.xls b/office/test/testdata/legacy/real/SampleSS.xls similarity index 100% rename from office/testdata/legacy/real/SampleSS.xls rename to office/test/testdata/legacy/real/SampleSS.xls diff --git a/office/testdata/legacy/real/basic_test_ppt_file.ppt b/office/test/testdata/legacy/real/basic_test_ppt_file.ppt similarity index 100% rename from office/testdata/legacy/real/basic_test_ppt_file.ppt rename to office/test/testdata/legacy/real/basic_test_ppt_file.ppt diff --git a/office/testdata/legacy/real/basic_test_ppt_file.truth.json b/office/test/testdata/legacy/real/basic_test_ppt_file.truth.json similarity index 100% rename from office/testdata/legacy/real/basic_test_ppt_file.truth.json rename to office/test/testdata/legacy/real/basic_test_ppt_file.truth.json diff --git a/office/testdata/legacy/real/simple-table.doc b/office/test/testdata/legacy/real/simple-table.doc similarity index 100% rename from office/testdata/legacy/real/simple-table.doc rename to office/test/testdata/legacy/real/simple-table.doc diff --git a/office/testdata/legacy/real/simple-table.truth.json b/office/test/testdata/legacy/real/simple-table.truth.json similarity index 100% rename from office/testdata/legacy/real/simple-table.truth.json rename to office/test/testdata/legacy/real/simple-table.truth.json diff --git a/office/testdata/licenses/poi.LICENSE b/office/test/testdata/licenses/poi.LICENSE similarity index 100% rename from office/testdata/licenses/poi.LICENSE rename to office/test/testdata/licenses/poi.LICENSE diff --git a/office/testdata/licenses/poi.NOTICE b/office/test/testdata/licenses/poi.NOTICE similarity index 100% rename from office/testdata/licenses/poi.NOTICE rename to office/test/testdata/licenses/poi.NOTICE diff --git a/office/testdata/odf/drawing.fodg b/office/test/testdata/odf/drawing.fodg similarity index 100% rename from office/testdata/odf/drawing.fodg rename to office/test/testdata/odf/drawing.fodg diff --git a/office/testdata/odf/encrypt.py b/office/test/testdata/odf/encrypt.py similarity index 97% rename from office/testdata/odf/encrypt.py rename to office/test/testdata/odf/encrypt.py index 938b8040..768cd284 100644 --- a/office/testdata/odf/encrypt.py +++ b/office/test/testdata/odf/encrypt.py @@ -1,6 +1,6 @@ # encrypt saves the document at its first argument as an ODF text document, encrypted with the # password "docproc", at its second, through a soffice of its own, its user profile at the third. -# See office/testdata/README.md +# See office/test/testdata/README.md import os import subprocess import sys diff --git a/office/testdata/odf/generate.sh b/office/test/testdata/odf/generate.sh similarity index 95% rename from office/testdata/odf/generate.sh rename to office/test/testdata/odf/generate.sh index c54cc90d..ff0c58ba 100755 --- a/office/testdata/odf/generate.sh +++ b/office/test/testdata/odf/generate.sh @@ -8,12 +8,12 @@ # and the host's soffice and Python UNO bridge, since soffice's --convert-to sets no password. It # writes generated/MANIFEST: the image, each soffice's --version line, and each file's SHA-256. It # needs docker, soffice, and python3 with uno, laptop prerequisites that the check never runs. -# See office/testdata/README.md +# See office/test/testdata/README.md set -euo pipefail cd "$(dirname "$0")" picture_libreoffice_image() { - tr '\n' ' ' <../../../picture/spec.go | sed -E 's/"[[:space:]]*\+[[:space:]]*"//g' | + tr '\n' ' ' <../../../../picture/spec.go | sed -E 's/"[[:space:]]*\+[[:space:]]*"//g' | grep -oE 'gotenberg/gotenberg:[^"@]+@sha256:[0-9a-f]{64}' } diff --git a/office/testdata/odf/generated/MANIFEST b/office/test/testdata/odf/generated/MANIFEST similarity index 100% rename from office/testdata/odf/generated/MANIFEST rename to office/test/testdata/odf/generated/MANIFEST diff --git a/office/testdata/odf/generated/cells.libreoffice.ods b/office/test/testdata/odf/generated/cells.libreoffice.ods similarity index 100% rename from office/testdata/odf/generated/cells.libreoffice.ods rename to office/test/testdata/odf/generated/cells.libreoffice.ods diff --git a/office/testdata/odf/generated/cells.libreoffice.ots b/office/test/testdata/odf/generated/cells.libreoffice.ots similarity index 100% rename from office/testdata/odf/generated/cells.libreoffice.ots rename to office/test/testdata/odf/generated/cells.libreoffice.ots diff --git a/office/testdata/odf/generated/drawing.odg b/office/test/testdata/odf/generated/drawing.odg similarity index 100% rename from office/testdata/odf/generated/drawing.odg rename to office/test/testdata/odf/generated/drawing.odg diff --git a/office/testdata/odf/generated/drawing.otg b/office/test/testdata/odf/generated/drawing.otg similarity index 100% rename from office/testdata/odf/generated/drawing.otg rename to office/test/testdata/odf/generated/drawing.otg diff --git a/office/testdata/odf/generated/encrypted.odt b/office/test/testdata/odf/generated/encrypted.odt similarity index 100% rename from office/testdata/odf/generated/encrypted.odt rename to office/test/testdata/odf/generated/encrypted.odt diff --git a/office/testdata/odf/generated/slides.libreoffice.odp b/office/test/testdata/odf/generated/slides.libreoffice.odp similarity index 100% rename from office/testdata/odf/generated/slides.libreoffice.odp rename to office/test/testdata/odf/generated/slides.libreoffice.odp diff --git a/office/testdata/odf/generated/slides.libreoffice.otp b/office/test/testdata/odf/generated/slides.libreoffice.otp similarity index 100% rename from office/testdata/odf/generated/slides.libreoffice.otp rename to office/test/testdata/odf/generated/slides.libreoffice.otp diff --git a/office/testdata/odf/generated/tables.libreoffice.odt b/office/test/testdata/odf/generated/tables.libreoffice.odt similarity index 100% rename from office/testdata/odf/generated/tables.libreoffice.odt rename to office/test/testdata/odf/generated/tables.libreoffice.odt diff --git a/office/testdata/odf/generated/tables.libreoffice.ott b/office/test/testdata/odf/generated/tables.libreoffice.ott similarity index 100% rename from office/testdata/odf/generated/tables.libreoffice.ott rename to office/test/testdata/odf/generated/tables.libreoffice.ott diff --git a/office/testdata/ooxml/bullets.libreoffice.pptx b/office/test/testdata/ooxml/bullets.libreoffice.pptx similarity index 100% rename from office/testdata/ooxml/bullets.libreoffice.pptx rename to office/test/testdata/ooxml/bullets.libreoffice.pptx diff --git a/office/testdata/ooxml/cells.libreoffice.xlsx b/office/test/testdata/ooxml/cells.libreoffice.xlsx similarity index 100% rename from office/testdata/ooxml/cells.libreoffice.xlsx rename to office/test/testdata/ooxml/cells.libreoffice.xlsx diff --git a/office/testdata/ooxml/charts.libreoffice.docx b/office/test/testdata/ooxml/charts.libreoffice.docx similarity index 100% rename from office/testdata/ooxml/charts.libreoffice.docx rename to office/test/testdata/ooxml/charts.libreoffice.docx diff --git a/office/testdata/ooxml/comments.libreoffice.docx b/office/test/testdata/ooxml/comments.libreoffice.docx similarity index 100% rename from office/testdata/ooxml/comments.libreoffice.docx rename to office/test/testdata/ooxml/comments.libreoffice.docx diff --git a/office/testdata/ooxml/drawings.libreoffice.xlsx b/office/test/testdata/ooxml/drawings.libreoffice.xlsx similarity index 100% rename from office/testdata/ooxml/drawings.libreoffice.xlsx rename to office/test/testdata/ooxml/drawings.libreoffice.xlsx diff --git a/office/testdata/ooxml/formulas.libreoffice.xlsx b/office/test/testdata/ooxml/formulas.libreoffice.xlsx similarity index 100% rename from office/testdata/ooxml/formulas.libreoffice.xlsx rename to office/test/testdata/ooxml/formulas.libreoffice.xlsx diff --git a/office/testdata/ooxml/lists.libreoffice.docx b/office/test/testdata/ooxml/lists.libreoffice.docx similarity index 100% rename from office/testdata/ooxml/lists.libreoffice.docx rename to office/test/testdata/ooxml/lists.libreoffice.docx diff --git a/office/testdata/ooxml/media.libreoffice.docx b/office/test/testdata/ooxml/media.libreoffice.docx similarity index 100% rename from office/testdata/ooxml/media.libreoffice.docx rename to office/test/testdata/ooxml/media.libreoffice.docx diff --git a/office/testdata/ooxml/merges.libreoffice.xlsx b/office/test/testdata/ooxml/merges.libreoffice.xlsx similarity index 100% rename from office/testdata/ooxml/merges.libreoffice.xlsx rename to office/test/testdata/ooxml/merges.libreoffice.xlsx diff --git a/office/testdata/ooxml/notes.libreoffice.docx b/office/test/testdata/ooxml/notes.libreoffice.docx similarity index 100% rename from office/testdata/ooxml/notes.libreoffice.docx rename to office/test/testdata/ooxml/notes.libreoffice.docx diff --git a/office/testdata/ooxml/sections.libreoffice.docx b/office/test/testdata/ooxml/sections.libreoffice.docx similarity index 100% rename from office/testdata/ooxml/sections.libreoffice.docx rename to office/test/testdata/ooxml/sections.libreoffice.docx diff --git a/office/testdata/ooxml/slide-objects.libreoffice.pptx b/office/test/testdata/ooxml/slide-objects.libreoffice.pptx similarity index 100% rename from office/testdata/ooxml/slide-objects.libreoffice.pptx rename to office/test/testdata/ooxml/slide-objects.libreoffice.pptx diff --git a/office/testdata/ooxml/slides.libreoffice.pptx b/office/test/testdata/ooxml/slides.libreoffice.pptx similarity index 100% rename from office/testdata/ooxml/slides.libreoffice.pptx rename to office/test/testdata/ooxml/slides.libreoffice.pptx diff --git a/office/testdata/ooxml/tables.libreoffice.docx b/office/test/testdata/ooxml/tables.libreoffice.docx similarity index 100% rename from office/testdata/ooxml/tables.libreoffice.docx rename to office/test/testdata/ooxml/tables.libreoffice.docx diff --git a/office/testdata/ooxml/with-drawing.xlsx b/office/test/testdata/ooxml/with-drawing.xlsx similarity index 100% rename from office/testdata/ooxml/with-drawing.xlsx rename to office/test/testdata/ooxml/with-drawing.xlsx diff --git a/office/testdata/ooxml/word-with-attachments.docx b/office/test/testdata/ooxml/word-with-attachments.docx similarity index 100% rename from office/testdata/ooxml/word-with-attachments.docx rename to office/test/testdata/ooxml/word-with-attachments.docx diff --git a/office/testdata/pictures/generate.sh b/office/test/testdata/pictures/generate.sh similarity index 99% rename from office/testdata/pictures/generate.sh rename to office/test/testdata/pictures/generate.sh index 42b2f8f3..fc28dd01 100755 --- a/office/testdata/pictures/generate.sh +++ b/office/test/testdata/pictures/generate.sh @@ -3,7 +3,7 @@ # checked against its SHA-256, packed byte for byte into the smallest WordprocessingML package that # shows it, so a regeneration writes the same bytes. It needs curl and zip, laptop prerequisites # that the check never runs. -# See office/testdata/README.md +# See office/test/testdata/README.md set -euo pipefail cd "$(dirname "$0")" diff --git a/office/testdata/pictures/tiff.docx b/office/test/testdata/pictures/tiff.docx similarity index 100% rename from office/testdata/pictures/tiff.docx rename to office/test/testdata/pictures/tiff.docx diff --git a/office/testdata/rtf/hidden-entry.rtf b/office/test/testdata/rtf/hidden-entry.rtf similarity index 100% rename from office/testdata/rtf/hidden-entry.rtf rename to office/test/testdata/rtf/hidden-entry.rtf diff --git a/office/testdata/rtf/memo.rtf b/office/test/testdata/rtf/memo.rtf similarity index 100% rename from office/testdata/rtf/memo.rtf rename to office/test/testdata/rtf/memo.rtf diff --git a/office/testdata/wordperfect/testWordPerfect_6_61.wpd b/office/test/testdata/wordperfect/testWordPerfect_6_61.wpd similarity index 100% rename from office/testdata/wordperfect/testWordPerfect_6_61.wpd rename to office/test/testdata/wordperfect/testWordPerfect_6_61.wpd diff --git a/office/testdata/xlsb/protected_passtika.xlsb b/office/test/testdata/xlsb/protected_passtika.xlsb similarity index 100% rename from office/testdata/xlsb/protected_passtika.xlsb rename to office/test/testdata/xlsb/protected_passtika.xlsb diff --git a/office/testdata/xlsb/testVarious.xlsb b/office/test/testdata/xlsb/testVarious.xlsb similarity index 100% rename from office/testdata/xlsb/testVarious.xlsb rename to office/test/testdata/xlsb/testVarious.xlsb diff --git a/onenote/main_test.go b/onenote/test/main_test.go similarity index 100% rename from onenote/main_test.go rename to onenote/test/main_test.go diff --git a/onenote/onenote_test.go b/onenote/test/onenote_test.go similarity index 100% rename from onenote/onenote_test.go rename to onenote/test/onenote_test.go diff --git a/onenote/real_integration_test.go b/onenote/test/real_integration_test.go similarity index 100% rename from onenote/real_integration_test.go rename to onenote/test/real_integration_test.go diff --git a/onenote/replay_test.go b/onenote/test/replay_test.go similarity index 100% rename from onenote/replay_test.go rename to onenote/test/replay_test.go diff --git a/picture/convert_integration_test.go b/picture/test/convert_integration_test.go similarity index 100% rename from picture/convert_integration_test.go rename to picture/test/convert_integration_test.go diff --git a/picture/convert_test.go b/picture/test/convert_test.go similarity index 100% rename from picture/convert_test.go rename to picture/test/convert_test.go diff --git a/picture/exif_integration_test.go b/picture/test/exif_integration_test.go similarity index 100% rename from picture/exif_integration_test.go rename to picture/test/exif_integration_test.go diff --git a/picture/exif_test.go b/picture/test/exif_test.go similarity index 100% rename from picture/exif_test.go rename to picture/test/exif_test.go diff --git a/picture/libreoffice_integration_test.go b/picture/test/libreoffice_integration_test.go similarity index 92% rename from picture/libreoffice_integration_test.go rename to picture/test/libreoffice_integration_test.go index 6a00730a..e966dd38 100644 --- a/picture/libreoffice_integration_test.go +++ b/picture/test/libreoffice_integration_test.go @@ -10,6 +10,7 @@ import ( "sync" "testing" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/picture" "github.com/standards-lab/docproc/tool" ) @@ -73,7 +74,7 @@ func convertLegacy(t *testing.T, c *picture.Converter, dir, fixture string) { out, err := c.RunLibreOffice(t.Context(), picture.LibreOfficeRun{ Dir: dir, ConvertTo: to, - Inputs: []picture.LibreOfficeInput{{Path: filepath.Join("..", "office", "testdata", "legacy", "generated", fixture), Name: "document" + ext}}, + Inputs: []picture.LibreOfficeInput{{Path: tooltest.Testdata(t, "office", "legacy", "generated", fixture), Name: "document" + ext}}, }) if err != nil { t.Errorf("%s: %v", fixture, err) diff --git a/picture/main_test.go b/picture/test/main_test.go similarity index 100% rename from picture/main_test.go rename to picture/test/main_test.go diff --git a/picture/pages_integration_test.go b/picture/test/pages_integration_test.go similarity index 100% rename from picture/pages_integration_test.go rename to picture/test/pages_integration_test.go diff --git a/picture/pages_test.go b/picture/test/pages_test.go similarity index 100% rename from picture/pages_test.go rename to picture/test/pages_test.go diff --git a/picture/testdata/README.md b/picture/test/testdata/README.md similarity index 100% rename from picture/testdata/README.md rename to picture/test/testdata/README.md diff --git a/picture/testdata/animated.avif b/picture/test/testdata/animated.avif similarity index 100% rename from picture/testdata/animated.avif rename to picture/test/testdata/animated.avif diff --git a/picture/testdata/animated.webp b/picture/test/testdata/animated.webp similarity index 100% rename from picture/testdata/animated.webp rename to picture/test/testdata/animated.webp diff --git a/picture/testdata/exif-gps.jpg b/picture/test/testdata/exif-gps.jpg similarity index 100% rename from picture/testdata/exif-gps.jpg rename to picture/test/testdata/exif-gps.jpg diff --git a/picture/testdata/exif-gps.magick.txt b/picture/test/testdata/exif-gps.magick.txt similarity index 100% rename from picture/testdata/exif-gps.magick.txt rename to picture/test/testdata/exif-gps.magick.txt diff --git a/picture/testdata/exif-none.magick.txt b/picture/test/testdata/exif-none.magick.txt similarity index 100% rename from picture/testdata/exif-none.magick.txt rename to picture/test/testdata/exif-none.magick.txt diff --git a/picture/testdata/exif-none.png b/picture/test/testdata/exif-none.png similarity index 100% rename from picture/testdata/exif-none.png rename to picture/test/testdata/exif-none.png diff --git a/picture/testdata/exif-zoneless.heic b/picture/test/testdata/exif-zoneless.heic similarity index 100% rename from picture/testdata/exif-zoneless.heic rename to picture/test/testdata/exif-zoneless.heic diff --git a/picture/testdata/exif-zoneless.magick.txt b/picture/test/testdata/exif-zoneless.magick.txt similarity index 100% rename from picture/testdata/exif-zoneless.magick.txt rename to picture/test/testdata/exif-zoneless.magick.txt diff --git a/picture/testdata/ink.svg b/picture/test/testdata/ink.svg similarity index 100% rename from picture/testdata/ink.svg rename to picture/test/testdata/ink.svg diff --git a/picture/testdata/lzw-gray.tiff b/picture/test/testdata/lzw-gray.tiff similarity index 100% rename from picture/testdata/lzw-gray.tiff rename to picture/test/testdata/lzw-gray.tiff diff --git a/picture/testdata/oriented.webp b/picture/test/testdata/oriented.webp similarity index 100% rename from picture/testdata/oriented.webp rename to picture/test/testdata/oriented.webp diff --git a/picture/testdata/pages.tiff b/picture/test/testdata/pages.tiff similarity index 100% rename from picture/testdata/pages.tiff rename to picture/test/testdata/pages.tiff diff --git a/picture/testdata/scanned-g4.tiff b/picture/test/testdata/scanned-g4.tiff similarity index 100% rename from picture/testdata/scanned-g4.tiff rename to picture/test/testdata/scanned-g4.tiff diff --git a/picture/testdata/script-bearing.svg b/picture/test/testdata/script-bearing.svg similarity index 100% rename from picture/testdata/script-bearing.svg rename to picture/test/testdata/script-bearing.svg diff --git a/picture/testdata/shapes.svg b/picture/test/testdata/shapes.svg similarity index 100% rename from picture/testdata/shapes.svg rename to picture/test/testdata/shapes.svg diff --git a/picture/testdata/two-images.heic b/picture/test/testdata/two-images.heic similarity index 100% rename from picture/testdata/two-images.heic rename to picture/test/testdata/two-images.heic diff --git a/route/at_test.go b/route/test/at_test.go similarity index 100% rename from route/at_test.go rename to route/test/at_test.go diff --git a/route/file_test.go b/route/test/file_test.go similarity index 99% rename from route/file_test.go rename to route/test/file_test.go index 637b771c..8d176866 100644 --- a/route/file_test.go +++ b/route/test/file_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" ) @@ -224,7 +225,7 @@ func TestFileEncryptedPackage(t *testing.T) { } }) } - got, why, err := route.File("../inspect/testdata/encrypted.xlsx", "encrypted.xlsx", "") + got, why, err := route.File(tooltest.Testdata(t, "inspect", "encrypted.xlsx"), "encrypted.xlsx", "") if err != nil || got != route.Office || why != fmt.Sprintf(encryptedWhy, ".xlsx") { t.Errorf("inspect's encrypted.xlsx: route %q (%s), %v; want office", got, why, err) } diff --git a/route/identify_test.go b/route/test/identify_test.go similarity index 100% rename from route/identify_test.go rename to route/test/identify_test.go diff --git a/route/main_test.go b/route/test/main_test.go similarity index 100% rename from route/main_test.go rename to route/test/main_test.go diff --git a/route/real_test.go b/route/test/real_test.go similarity index 83% rename from route/real_test.go rename to route/test/real_test.go index f648be0e..cdf649e8 100644 --- a/route/real_test.go +++ b/route/test/real_test.go @@ -5,6 +5,7 @@ import ( "path/filepath" "testing" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" ) @@ -20,7 +21,7 @@ var testdataRoutes = map[string]route.Route{ func TestFileTestdata(t *testing.T) { n := 0 - for _, dir := range []string{"../office/testdata", "../document/testdata", "../picture/testdata", "../tool/testdata"} { + for _, dir := range []string{tooltest.Testdata(t, "office"), tooltest.Testdata(t, "document"), tooltest.Testdata(t, "picture"), tooltest.Testdata(t, "tool")} { err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { if err != nil || d.IsDir() { return err diff --git a/route/route_test.go b/route/test/route_test.go similarity index 100% rename from route/route_test.go rename to route/test/route_test.go diff --git a/rundir/schema/main_test.go b/rundir/schema/test/main_test.go similarity index 100% rename from rundir/schema/main_test.go rename to rundir/schema/test/main_test.go diff --git a/rundir/schema/schema_test.go b/rundir/schema/test/schema_test.go similarity index 100% rename from rundir/schema/schema_test.go rename to rundir/schema/test/schema_test.go diff --git a/rundir/main_test.go b/rundir/test/main_test.go similarity index 100% rename from rundir/main_test.go rename to rundir/test/main_test.go diff --git a/rundir/rundir_test.go b/rundir/test/rundir_test.go similarity index 100% rename from rundir/rundir_test.go rename to rundir/test/rundir_test.go diff --git a/rundir/testdata/rundir/content/b6/b688c8947f876ba9580749960b0c70076ea223eec8dcb9d57d4c51c9c9dd2906 b/rundir/test/testdata/rundir/content/b6/b688c8947f876ba9580749960b0c70076ea223eec8dcb9d57d4c51c9c9dd2906 similarity index 100% rename from rundir/testdata/rundir/content/b6/b688c8947f876ba9580749960b0c70076ea223eec8dcb9d57d4c51c9c9dd2906 rename to rundir/test/testdata/rundir/content/b6/b688c8947f876ba9580749960b0c70076ea223eec8dcb9d57d4c51c9c9dd2906 diff --git a/rundir/testdata/rundir/content/d3/d31031c3593a9da13ff7013b8cf20bf3120903467fac751975e0260c8560c6c7 b/rundir/test/testdata/rundir/content/d3/d31031c3593a9da13ff7013b8cf20bf3120903467fac751975e0260c8560c6c7 similarity index 100% rename from rundir/testdata/rundir/content/d3/d31031c3593a9da13ff7013b8cf20bf3120903467fac751975e0260c8560c6c7 rename to rundir/test/testdata/rundir/content/d3/d31031c3593a9da13ff7013b8cf20bf3120903467fac751975e0260c8560c6c7 diff --git a/rundir/testdata/rundir/quarantine/4efe525c159bafa28a6ba4e08aa028a846bdebb78bf4b33c11e959a37b481bca b/rundir/test/testdata/rundir/quarantine/4efe525c159bafa28a6ba4e08aa028a846bdebb78bf4b33c11e959a37b481bca similarity index 100% rename from rundir/testdata/rundir/quarantine/4efe525c159bafa28a6ba4e08aa028a846bdebb78bf4b33c11e959a37b481bca rename to rundir/test/testdata/rundir/quarantine/4efe525c159bafa28a6ba4e08aa028a846bdebb78bf4b33c11e959a37b481bca diff --git a/rundir/testdata/rundir/rundir.json b/rundir/test/testdata/rundir/rundir.json similarity index 100% rename from rundir/testdata/rundir/rundir.json rename to rundir/test/testdata/rundir/rundir.json diff --git a/rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/manifest.json b/rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/manifest.json similarity index 100% rename from rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/manifest.json rename to rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/manifest.json diff --git a/rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/record.jsonl b/rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/record.jsonl similarity index 100% rename from rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/record.jsonl rename to rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/record.jsonl diff --git a/rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/manifest.json b/rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/manifest.json similarity index 100% rename from rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/manifest.json rename to rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/manifest.json diff --git a/rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/record.jsonl b/rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/record.jsonl similarity index 100% rename from rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/record.jsonl rename to rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/record.jsonl diff --git a/rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/manifest.json b/rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/manifest.json similarity index 100% rename from rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/manifest.json rename to rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/manifest.json diff --git a/rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/record.jsonl b/rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/record.jsonl similarity index 100% rename from rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/record.jsonl rename to rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/record.jsonl diff --git a/settings/main_test.go b/settings/test/main_test.go similarity index 100% rename from settings/main_test.go rename to settings/test/main_test.go diff --git a/settings/run_linux_test.go b/settings/test/run_linux_test.go similarity index 100% rename from settings/run_linux_test.go rename to settings/test/run_linux_test.go diff --git a/settings/run_test.go b/settings/test/run_test.go similarity index 100% rename from settings/run_test.go rename to settings/test/run_test.go diff --git a/settings/settings_test.go b/settings/test/settings_test.go similarity index 100% rename from settings/settings_test.go rename to settings/test/settings_test.go diff --git a/sevenzip/listing_test.go b/sevenzip/test/listing_test.go similarity index 100% rename from sevenzip/listing_test.go rename to sevenzip/test/listing_test.go diff --git a/sevenzip/read_test.go b/sevenzip/test/read_test.go similarity index 100% rename from sevenzip/read_test.go rename to sevenzip/test/read_test.go diff --git a/sevenzip/sevenzip_integration_test.go b/sevenzip/test/sevenzip_integration_test.go similarity index 98% rename from sevenzip/sevenzip_integration_test.go rename to sevenzip/test/sevenzip_integration_test.go index 72311b0c..b508c5b0 100644 --- a/sevenzip/sevenzip_integration_test.go +++ b/sevenzip/test/sevenzip_integration_test.go @@ -15,6 +15,7 @@ import ( "strings" "testing" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/sevenzip" "github.com/standards-lab/docproc/tool" @@ -132,7 +133,7 @@ func TestExtract(t *testing.T) { } } - tar, err := os.ReadFile(filepath.Join("..", "inspect", "testdata", "clean.tar")) + tar, err := os.ReadFile(tooltest.Testdata(t, "inspect", "clean.tar")) if err != nil { t.Fatal(err) } diff --git a/sevenzip/sevenzip_test.go b/sevenzip/test/sevenzip_test.go similarity index 100% rename from sevenzip/sevenzip_test.go rename to sevenzip/test/sevenzip_test.go diff --git a/sevenzip/testdata/README.md b/sevenzip/test/testdata/README.md similarity index 99% rename from sevenzip/testdata/README.md rename to sevenzip/test/testdata/README.md index b2c0f09f..9410ed87 100644 --- a/sevenzip/testdata/README.md +++ b/sevenzip/test/testdata/README.md @@ -148,7 +148,7 @@ What each holds: blocks, Copy being unsolid), each method's two files added to the archive in turn with `-m0=`, so six blocks of mixed methods; beside the LZMA2 files, `empty.txt`, an empty file, and `passwd`, a symbolic link stored as one (`-snl`), which a whole read excludes. -- `clean.tar.zst`: inspect's `clean.tar` (`inspect/testdata/`) as one zstd frame of raw blocks, +- `clean.tar.zst`: inspect's `clean.tar` (`inspect/test/testdata/`) as one zstd frame of raw blocks, declaring no content size. - `bomb.zst`: 8 MiB of zeros in RLE blocks, about 32,000:1, declaring no content size: past the default ratio, under the default size, as written. diff --git a/sevenzip/testdata/commons-compress/LICENSE.txt b/sevenzip/test/testdata/commons-compress/LICENSE.txt similarity index 100% rename from sevenzip/testdata/commons-compress/LICENSE.txt rename to sevenzip/test/testdata/commons-compress/LICENSE.txt diff --git a/sevenzip/testdata/commons-compress/NOTICE.txt b/sevenzip/test/testdata/commons-compress/NOTICE.txt similarity index 100% rename from sevenzip/testdata/commons-compress/NOTICE.txt rename to sevenzip/test/testdata/commons-compress/NOTICE.txt diff --git a/sevenzip/testdata/commons-compress/bla.deflate64.7z b/sevenzip/test/testdata/commons-compress/bla.deflate64.7z similarity index 100% rename from sevenzip/testdata/commons-compress/bla.deflate64.7z rename to sevenzip/test/testdata/commons-compress/bla.deflate64.7z diff --git a/sevenzip/testdata/commons-compress/bzip2-zip.zip b/sevenzip/test/testdata/commons-compress/bzip2-zip.zip similarity index 100% rename from sevenzip/testdata/commons-compress/bzip2-zip.zip rename to sevenzip/test/testdata/commons-compress/bzip2-zip.zip diff --git a/sevenzip/testdata/commons-compress/lorem-ipsum-deflate64.zip b/sevenzip/test/testdata/commons-compress/lorem-ipsum-deflate64.zip similarity index 100% rename from sevenzip/testdata/commons-compress/lorem-ipsum-deflate64.zip rename to sevenzip/test/testdata/commons-compress/lorem-ipsum-deflate64.zip diff --git a/sevenzip/testdata/commons-compress/lorem-ipsum-implode.zip b/sevenzip/test/testdata/commons-compress/lorem-ipsum-implode.zip similarity index 100% rename from sevenzip/testdata/commons-compress/lorem-ipsum-implode.zip rename to sevenzip/test/testdata/commons-compress/lorem-ipsum-implode.zip diff --git a/sevenzip/testdata/commons-compress/test-method-xz.zip b/sevenzip/test/testdata/commons-compress/test-method-xz.zip similarity index 100% rename from sevenzip/testdata/commons-compress/test-method-xz.zip rename to sevenzip/test/testdata/commons-compress/test-method-xz.zip diff --git a/sevenzip/testdata/generate.go b/sevenzip/test/testdata/generate.go similarity index 97% rename from sevenzip/testdata/generate.go rename to sevenzip/test/testdata/generate.go index ceba7b80..a2b30b2f 100644 --- a/sevenzip/testdata/generate.go +++ b/sevenzip/test/testdata/generate.go @@ -1,7 +1,7 @@ //go:build ignore // generate writes the sevenzip package's generated fixtures, which README.md describes, into -// generated/, beside this file. Run it from sevenzip/testdata with +// generated/, beside this file. Run it from sevenzip/test/testdata with // `mise exec -- go run generate.go`; the check never runs it, and reads the committed files. package main @@ -19,7 +19,7 @@ const outDir = "generated" const password = "infected" -const onenoteSectionGroup = "../../tools/onenote/tests/fixtures/onenote-rs/New Section Group" +const onenoteSectionGroup = "../../../tools/onenote/tests/fixtures/onenote-rs/New Section Group" func main() { if err := run(); err != nil { @@ -32,7 +32,7 @@ func run() error { if err := os.MkdirAll(outDir, 0o755); err != nil { return err } - cleanTar, err := os.ReadFile("../../inspect/testdata/clean.tar") + cleanTar, err := os.ReadFile("../../../inspect/test/testdata/clean.tar") if err != nil { return err } diff --git a/sevenzip/testdata/generated/absolute.7z b/sevenzip/test/testdata/generated/absolute.7z similarity index 100% rename from sevenzip/testdata/generated/absolute.7z rename to sevenzip/test/testdata/generated/absolute.7z diff --git a/sevenzip/testdata/generated/absolute.cab b/sevenzip/test/testdata/generated/absolute.cab similarity index 100% rename from sevenzip/testdata/generated/absolute.cab rename to sevenzip/test/testdata/generated/absolute.cab diff --git a/sevenzip/testdata/generated/bomb.7z b/sevenzip/test/testdata/generated/bomb.7z similarity index 100% rename from sevenzip/testdata/generated/bomb.7z rename to sevenzip/test/testdata/generated/bomb.7z diff --git a/sevenzip/testdata/generated/bomb.bz2 b/sevenzip/test/testdata/generated/bomb.bz2 similarity index 100% rename from sevenzip/testdata/generated/bomb.bz2 rename to sevenzip/test/testdata/generated/bomb.bz2 diff --git a/sevenzip/testdata/generated/bomb.cab b/sevenzip/test/testdata/generated/bomb.cab similarity index 100% rename from sevenzip/testdata/generated/bomb.cab rename to sevenzip/test/testdata/generated/bomb.cab diff --git a/sevenzip/testdata/generated/bomb.xz b/sevenzip/test/testdata/generated/bomb.xz similarity index 100% rename from sevenzip/testdata/generated/bomb.xz rename to sevenzip/test/testdata/generated/bomb.xz diff --git a/sevenzip/testdata/generated/bomb.zst b/sevenzip/test/testdata/generated/bomb.zst similarity index 100% rename from sevenzip/testdata/generated/bomb.zst rename to sevenzip/test/testdata/generated/bomb.zst diff --git a/sevenzip/testdata/generated/clean.7z b/sevenzip/test/testdata/generated/clean.7z similarity index 100% rename from sevenzip/testdata/generated/clean.7z rename to sevenzip/test/testdata/generated/clean.7z diff --git a/sevenzip/testdata/generated/clean.tar.zst b/sevenzip/test/testdata/generated/clean.tar.zst similarity index 100% rename from sevenzip/testdata/generated/clean.tar.zst rename to sevenzip/test/testdata/generated/clean.tar.zst diff --git a/sevenzip/testdata/generated/clean.tbz2 b/sevenzip/test/testdata/generated/clean.tbz2 similarity index 100% rename from sevenzip/testdata/generated/clean.tbz2 rename to sevenzip/test/testdata/generated/clean.tbz2 diff --git a/sevenzip/testdata/generated/clean.txz b/sevenzip/test/testdata/generated/clean.txz similarity index 100% rename from sevenzip/testdata/generated/clean.txz rename to sevenzip/test/testdata/generated/clean.txz diff --git a/sevenzip/testdata/generated/concatenated.txt.bz2 b/sevenzip/test/testdata/generated/concatenated.txt.bz2 similarity index 100% rename from sevenzip/testdata/generated/concatenated.txt.bz2 rename to sevenzip/test/testdata/generated/concatenated.txt.bz2 diff --git a/sevenzip/testdata/generated/declared-bomb.zst b/sevenzip/test/testdata/generated/declared-bomb.zst similarity index 100% rename from sevenzip/testdata/generated/declared-bomb.zst rename to sevenzip/test/testdata/generated/declared-bomb.zst diff --git a/sevenzip/testdata/generated/device.7z b/sevenzip/test/testdata/generated/device.7z similarity index 100% rename from sevenzip/testdata/generated/device.7z rename to sevenzip/test/testdata/generated/device.7z diff --git a/sevenzip/testdata/generated/encrypted-headers.7z b/sevenzip/test/testdata/generated/encrypted-headers.7z similarity index 100% rename from sevenzip/testdata/generated/encrypted-headers.7z rename to sevenzip/test/testdata/generated/encrypted-headers.7z diff --git a/sevenzip/testdata/generated/encrypted.7z b/sevenzip/test/testdata/generated/encrypted.7z similarity index 100% rename from sevenzip/testdata/generated/encrypted.7z rename to sevenzip/test/testdata/generated/encrypted.7z diff --git a/sevenzip/testdata/generated/linebreak.cab b/sevenzip/test/testdata/generated/linebreak.cab similarity index 100% rename from sevenzip/testdata/generated/linebreak.cab rename to sevenzip/test/testdata/generated/linebreak.cab diff --git a/sevenzip/testdata/generated/mixed.7z b/sevenzip/test/testdata/generated/mixed.7z similarity index 100% rename from sevenzip/testdata/generated/mixed.7z rename to sevenzip/test/testdata/generated/mixed.7z diff --git a/sevenzip/testdata/generated/multiblock.7z b/sevenzip/test/testdata/generated/multiblock.7z similarity index 100% rename from sevenzip/testdata/generated/multiblock.7z rename to sevenzip/test/testdata/generated/multiblock.7z diff --git a/sevenzip/testdata/generated/notebook.cab b/sevenzip/test/testdata/generated/notebook.cab similarity index 100% rename from sevenzip/testdata/generated/notebook.cab rename to sevenzip/test/testdata/generated/notebook.cab diff --git a/sevenzip/testdata/generated/notes.txt.bz2 b/sevenzip/test/testdata/generated/notes.txt.bz2 similarity index 100% rename from sevenzip/testdata/generated/notes.txt.bz2 rename to sevenzip/test/testdata/generated/notes.txt.bz2 diff --git a/sevenzip/testdata/generated/notes.txt.xz b/sevenzip/test/testdata/generated/notes.txt.xz similarity index 100% rename from sevenzip/testdata/generated/notes.txt.xz rename to sevenzip/test/testdata/generated/notes.txt.xz diff --git a/sevenzip/testdata/generated/symlink.7z b/sevenzip/test/testdata/generated/symlink.7z similarity index 100% rename from sevenzip/testdata/generated/symlink.7z rename to sevenzip/test/testdata/generated/symlink.7z diff --git a/sevenzip/testdata/generated/traversal.7z b/sevenzip/test/testdata/generated/traversal.7z similarity index 100% rename from sevenzip/testdata/generated/traversal.7z rename to sevenzip/test/testdata/generated/traversal.7z diff --git a/sevenzip/testdata/generated/traversal.cab b/sevenzip/test/testdata/generated/traversal.cab similarity index 100% rename from sevenzip/testdata/generated/traversal.cab rename to sevenzip/test/testdata/generated/traversal.cab diff --git a/sevenzip/testdata/libarchive/COPYING b/sevenzip/test/testdata/libarchive/COPYING similarity index 100% rename from sevenzip/testdata/libarchive/COPYING rename to sevenzip/test/testdata/libarchive/COPYING diff --git a/sevenzip/testdata/libarchive/test_read_format_rar.rar b/sevenzip/test/testdata/libarchive/test_read_format_rar.rar similarity index 100% rename from sevenzip/testdata/libarchive/test_read_format_rar.rar rename to sevenzip/test/testdata/libarchive/test_read_format_rar.rar diff --git a/sevenzip/testdata/libarchive/test_read_format_rar5_compressed.rar b/sevenzip/test/testdata/libarchive/test_read_format_rar5_compressed.rar similarity index 100% rename from sevenzip/testdata/libarchive/test_read_format_rar5_compressed.rar rename to sevenzip/test/testdata/libarchive/test_read_format_rar5_compressed.rar diff --git a/sevenzip/testdata/libarchive/test_read_format_rar5_encrypted.rar b/sevenzip/test/testdata/libarchive/test_read_format_rar5_encrypted.rar similarity index 100% rename from sevenzip/testdata/libarchive/test_read_format_rar5_encrypted.rar rename to sevenzip/test/testdata/libarchive/test_read_format_rar5_encrypted.rar diff --git a/sevenzip/testdata/libarchive/test_read_format_rar5_encrypted_filenames.rar b/sevenzip/test/testdata/libarchive/test_read_format_rar5_encrypted_filenames.rar similarity index 100% rename from sevenzip/testdata/libarchive/test_read_format_rar5_encrypted_filenames.rar rename to sevenzip/test/testdata/libarchive/test_read_format_rar5_encrypted_filenames.rar diff --git a/sevenzip/testdata/libarchive/test_read_format_rar5_multiarchive.part01.rar b/sevenzip/test/testdata/libarchive/test_read_format_rar5_multiarchive.part01.rar similarity index 100% rename from sevenzip/testdata/libarchive/test_read_format_rar5_multiarchive.part01.rar rename to sevenzip/test/testdata/libarchive/test_read_format_rar5_multiarchive.part01.rar diff --git a/sevenzip/testdata/libarchive/test_read_format_rar5_symlink.rar b/sevenzip/test/testdata/libarchive/test_read_format_rar5_symlink.rar similarity index 100% rename from sevenzip/testdata/libarchive/test_read_format_rar5_symlink.rar rename to sevenzip/test/testdata/libarchive/test_read_format_rar5_symlink.rar diff --git a/sevenzip/testdata/libarchive/test_read_format_rar_encryption_header.rar b/sevenzip/test/testdata/libarchive/test_read_format_rar_encryption_header.rar similarity index 100% rename from sevenzip/testdata/libarchive/test_read_format_rar_encryption_header.rar rename to sevenzip/test/testdata/libarchive/test_read_format_rar_encryption_header.rar diff --git a/sevenzip/testdata/libarchive/test_read_format_rar_encryption_partially.rar b/sevenzip/test/testdata/libarchive/test_read_format_rar_encryption_partially.rar similarity index 100% rename from sevenzip/testdata/libarchive/test_read_format_rar_encryption_partially.rar rename to sevenzip/test/testdata/libarchive/test_read_format_rar_encryption_partially.rar diff --git a/sevenzip/testdata/libarchive/test_read_format_rar_multivolume.part0001.rar b/sevenzip/test/testdata/libarchive/test_read_format_rar_multivolume.part0001.rar similarity index 100% rename from sevenzip/testdata/libarchive/test_read_format_rar_multivolume.part0001.rar rename to sevenzip/test/testdata/libarchive/test_read_format_rar_multivolume.part0001.rar diff --git a/sevenzip/testdata/libarchive/test_read_format_zip_lzma.zipx b/sevenzip/test/testdata/libarchive/test_read_format_zip_lzma.zipx similarity index 100% rename from sevenzip/testdata/libarchive/test_read_format_zip_lzma.zipx rename to sevenzip/test/testdata/libarchive/test_read_format_zip_lzma.zipx diff --git a/sevenzip/testdata/libarchive/test_read_format_zip_ppmd8.zipx b/sevenzip/test/testdata/libarchive/test_read_format_zip_ppmd8.zipx similarity index 100% rename from sevenzip/testdata/libarchive/test_read_format_zip_ppmd8.zipx rename to sevenzip/test/testdata/libarchive/test_read_format_zip_ppmd8.zipx diff --git a/sevenzip/testdata/libarchive/test_read_format_zip_zstd.zipx b/sevenzip/test/testdata/libarchive/test_read_format_zip_zstd.zipx similarity index 100% rename from sevenzip/testdata/libarchive/test_read_format_zip_zstd.zipx rename to sevenzip/test/testdata/libarchive/test_read_format_zip_zstd.zipx diff --git a/stages/classify_test.go b/stages/classify_test.go deleted file mode 100644 index 6796332a..00000000 --- a/stages/classify_test.go +++ /dev/null @@ -1,194 +0,0 @@ -//go:build linux - -package stages_test - -import ( - "context" - "encoding/json/jsontext" - "errors" - "fmt" - "os" - "slices" - "strconv" - "strings" - "testing" - "time" - - "github.com/standards-lab/docproc/audio" - "github.com/standards-lab/docproc/dispatch" - "github.com/standards-lab/docproc/internal/cli" - "github.com/standards-lab/docproc/internal/tooltest" - "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/sevenzip" - "github.com/standards-lab/docproc/stages" - "github.com/standards-lab/docproc/stages/internal/adapter" - "github.com/standards-lab/docproc/tool" -) - -const oneSection = "\xe4\x52\x5c\x7b\x8c\xd8\xa7\x4d\xae\xb1\x53\x78\xd0\x29\x96\xd3\x00\x00\x00\x00\x00\x00\x00\x00" - -const testMemory = tooltest.Memory - -func onenoteOnly() []route.Route { - return slices.DeleteFunc(stages.Routes(), func(r route.Route) bool { return r == route.OneNote }) -} - -func standinSet(t *testing.T, s onenoteSettings, opts stages.Options) (stages.Set, string) { - t.Helper() - link := tooltest.Link(t, t.TempDir(), "docproc-onenote", s) - lookup := func(program string) (string, error) { - if program == "docproc-onenote" { - return link, nil - } - return "", fmt.Errorf("%s isn't here", program) - } - set, err := stages.Build(t.Context(), lookup, opts) - if err != nil { - t.Fatal(err) - } - for _, tl := range set.Tools { - if tl.Program == "docproc-onenote" && tl.Error != "" { - t.Fatalf("the stand-in docproc-onenote was refused: %s", tl.Error) - } - } - return set, link -} - -func dispatchSet(t *testing.T, set stages.Set) (dispatched, bool) { - t.Helper() - index := dispatch.NewMemoryIndex(0) - d, err := dispatch.New(dispatch.Config{ - Content: dispatch.NewMemoryContent(), Puts: 2, Stages: set.Stages, Inspect: set.Inspect, Index: index, Dir: t.TempDir(), - }) - if err != nil { - t.Fatal(err) - } - events := dispatchAll(t, d, input(t, "in.one", oneSection), nil) - ev := events[len(events)-1] - _, recorded, err := index.Lookup(t.Context(), dispatch.Key{SHA256: ev.Part.SHA256, Stage: ev.Stage}) - if err != nil { - t.Fatal(err) - } - return ev, recorded -} - -func TestClassification(t *testing.T) { - t.Parallel() - const notebook = `{"line":"notebook","schema":"2","input":"section","name":"S"}` + "\n" - refused := func(reason string) onenoteSettings { - return onenoteSettings{Stderr: "docproc-onenote: error: " + reason + "\n", Exit: 3} - } - for _, c := range []struct { - name string - settings onenoteSettings - outcome dispatch.Outcome - recorded bool - reason string - }{ - {"exit 3, refused", refused("not a OneNote section, notebook, or package"), dispatch.Failed, true, "refused"}, - {"exit 4, the tool's fault", onenoteSettings{Stdout: notebook, Stderr: "docproc-onenote: error: internal\n", Exit: 4}, dispatch.Failed, true, "failed: internal"}, - {"SIGSEGV", onenoteSettings{Stdout: notebook, Signal: "SEGV"}, dispatch.Failed, true, "killed by SIGSEGV under a 8 GiB memory bound"}, - {"SIGABRT", onenoteSettings{Stdout: notebook, Signal: "ABRT"}, dispatch.Failed, true, "killed by SIGABRT under a 8 GiB memory bound"}, - {"SIGBUS", onenoteSettings{Signal: "BUS"}, dispatch.Failed, true, "killed by SIGBUS under a 8 GiB memory bound"}, - {"SIGFPE", onenoteSettings{Signal: "FPE"}, dispatch.Failed, true, "killed by SIGFPE under a 8 GiB memory bound"}, - {"SIGILL", onenoteSettings{Signal: "ILL"}, dispatch.Failed, true, "killed by SIGILL under a 8 GiB memory bound"}, - {"its own time bound", onenoteSettings{HoldMS: 60000}, dispatch.Failed, true, "timed out"}, - {"output that doesn't parse", onenoteSettings{Stdout: notebook + `{"line":"page","id":` + "\n"}, dispatch.Failed, true, ""}, - {"exit 1, not written", onenoteSettings{Stderr: "docproc-onenote: error: writing stdout: Broken pipe\n", Exit: 1}, dispatch.Failed, false, "not written"}, - {"exit 2, usage", onenoteSettings{Stderr: "docproc-onenote: error: unknown option\n", Exit: 2}, dispatch.Failed, false, "usage"}, - {"SIGKILL docproc didn't send", onenoteSettings{Stdout: notebook, Signal: "KILL"}, dispatch.Failed, false, "killed by SIGKILL"}, - {"SIGTERM docproc didn't send", onenoteSettings{Signal: "TERM"}, dispatch.Failed, false, "killed by SIGTERM"}, - {"encrypted", refused("encrypted section (a password-protected section); remove its password in OneNote first"), dispatch.Encrypted, true, "encrypted"}, - {"read elsewhere", refused(cli.TableOfContents), dispatch.ReadElsewhere, true, cli.TableOfContents}, - } { - t.Run(c.name, func(t *testing.T) { - t.Parallel() - set, _ := standinSet(t, c.settings, stages.Options{Exclude: onenoteOnly(), Memory: testMemory, Idle: 5 * time.Second}) - ev, recorded := dispatchSet(t, set) - if ev.Outcome != c.outcome || recorded != c.recorded || !strings.Contains(ev.Reason, c.reason) { - t.Errorf("%s, recorded %t, %q; want %s, recorded %t, %q in the reason", ev.Outcome, recorded, ev.Reason, c.outcome, c.recorded, c.reason) - } - if c.outcome == dispatch.Failed && errors.Is(ev.Err, dispatch.ErrRefused) != c.recorded { - t.Errorf("err %v: ErrRefused %t, want %t", ev.Err, errors.Is(ev.Err, dispatch.ErrRefused), c.recorded) - } - }) - } -} - -func TestClassificationNoBound(t *testing.T) { - t.Parallel() - set, link := standinSet(t, onenoteSettings{Signal: "ABRT"}, stages.Options{Exclude: onenoteOnly()}) - ev, recorded := dispatchSet(t, set) - if ev.Outcome != dispatch.Failed || !recorded || !strings.Contains(ev.Reason, "killed by SIGABRT") || strings.Contains(ev.Reason, "memory bound") { - t.Errorf("%s, recorded %t, %q", ev.Outcome, recorded, ev.Reason) - } - if runs := tooltest.Runs(t, link); len(runs) != 2 || runs[1].Program != "docproc-onenote" { - t.Errorf("runs %+v", runs) - } -} - -func TestClassify(t *testing.T) { - t.Parallel() - ended, cancel := context.WithCancel(t.Context()) - cancel() - exit := func(program string, code int) error { return &tool.ExitError{Program: program, Code: code} } - for _, c := range []struct { - name string - ctx context.Context - err error - memory int64 - content bool - reason string - }{ - {"the context ended", ended, exit("gs", 1), 0, false, ""}, - {"a canceled run", t.Context(), fmt.Errorf("tool: gs: %w", context.Canceled), 0, false, ""}, - {"a failed start", t.Context(), &os.PathError{Op: "fork/exec", Path: "/gone", Err: os.ErrNotExist}, 0, false, ""}, - {"timed out after exit 1", t.Context(), &tool.ExitError{Program: "docproc-mail", Code: 1, TimedOut: true}, 0, true, ""}, - {"gs's exit 1", t.Context(), exit("gs", 1), 0, true, ""}, - {"qpdf's exit 2", t.Context(), exit("qpdf", 2), 0, true, ""}, - {"7zz's command line error", t.Context(), exit("7zz", 7), 0, false, ""}, - {"7zz's out of memory", t.Context(), exit("7zz", 8), 0, true, ""}, - {"soffice's fatal error at its start", t.Context(), exit("soffice", 77), 0, false, ""}, - {"soffice's exit 1", t.Context(), exit("soffice", 1), 0, true, ""}, - {"docproc-ooxml's usage", t.Context(), exit("docproc-ooxml", 2), 0, false, ""}, - {"a signal under 512 MiB", t.Context(), &tool.ExitError{Program: "docproc-ooxml", Code: -1, Signal: "SIGABRT", Message: "libssl"}, 512 << 20, - true, "docproc-ooxml: killed by SIGABRT under a 512 MiB memory bound: libssl"}, - {"a signal under an odd bound", t.Context(), &tool.ExitError{Program: "gs", Code: -1, Signal: "SIGSEGV"}, 1000, true, "gs: killed by SIGSEGV under a 1000 bytes memory bound"}, - {"SIGPIPE", t.Context(), &tool.ExitError{Program: "gs", Code: -1, Signal: "SIGPIPE"}, 0, false, ""}, - {"JSON that doesn't parse", t.Context(), fmt.Errorf("document: %w", &jsontext.SyntacticError{}), 0, true, ""}, - {"no audio", t.Context(), fmt.Errorf("audio: %w", audio.ErrNoAudio), 0, true, ""}, - {"not an archive", t.Context(), fmt.Errorf("sevenzip: %w", sevenzip.ErrNotArchive), 0, true, ""}, - {"docproc's side of the pipe", t.Context(), errors.New("write |1: broken pipe"), 0, false, ""}, - } { - content, reason := adapter.Classify(c.ctx, c.err, c.memory) - if content != c.content || c.reason != "" && reason != c.reason { - t.Errorf("%s: content %t, %q; want %t, %q", c.name, content, reason, c.content, c.reason) - } - } - if err := adapter.PartErr(t.Context(), exit("gs", 1), 0); !errors.Is(err, dispatch.ErrRefused) { - t.Errorf("partErr of the content's: %v, want ErrRefused", err) - } - for _, named := range []error{dispatch.ErrEncrypted, dispatch.ErrReadElsewhere, dispatch.ErrNoProcessor} { - if err := adapter.PartErr(t.Context(), named, 0); err != named { - t.Errorf("partErr(%v) = %v, want it as it is", named, err) - } - } -} - -func TestBuildBounds(t *testing.T) { - t.Parallel() - hold := onenoteSettings{HoldMS: 1500, Stdout: `{"line":"notebook","schema":"2","input":"section","name":"S"}` + "\n"} - set, _ := standinSet(t, hold, stages.Options{Exclude: onenoteOnly(), Timeout: 200 * time.Millisecond}) - if ev, _ := dispatchSet(t, set); ev.Outcome != dispatch.Prepared { - t.Errorf("a stream tool under a unit run's Timeout: %s, %q; want prepared", ev.Outcome, ev.Reason) - } - set, _ = standinSet(t, hold, stages.Options{Exclude: onenoteOnly(), Idle: 200 * time.Millisecond}) - if ev, recorded := dispatchSet(t, set); ev.Outcome != dispatch.Failed || !recorded || !strings.Contains(ev.Reason, "timed out") { - t.Errorf("a stream tool under Idle: %s, recorded %t, %q; want failed, recorded, timed out", ev.Outcome, recorded, ev.Reason) - } - set, _ = standinSet(t, onenoteSettings{Limit: true, Stdout: hold.Stdout}, stages.Options{Exclude: onenoteOnly(), Memory: testMemory}) - ev, _ := dispatchSet(t, set) - if want := (dispatch.Warning{Tool: "docproc-onenote", Where: "limit", What: strconv.Itoa(testMemory)}); !slices.Contains(ev.Warnings, want) { - t.Errorf("the bounded stand-in's warnings %+v, want its RLIMIT_AS the bound", ev.Warnings) - } -} diff --git a/stages/helpers_test.go b/stages/helpers_test.go deleted file mode 100644 index 68b470e7..00000000 --- a/stages/helpers_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package stages_test - -import ( - "crypto/sha256" - "encoding/hex" - "fmt" - "iter" - "os" - "path/filepath" - "slices" - "testing" - - "github.com/standards-lab/docproc/dispatch" - "github.com/standards-lab/docproc/inspect" -) - -func input(t *testing.T, name, content string) string { - t.Helper() - path := filepath.Join(t.TempDir(), name) - if err := os.WriteFile(path, []byte(content), 0o644); err != nil { - t.Fatal(err) - } - return path -} - -type step struct { - name string - depth int - outcome dispatch.Outcome -} - -func (s step) String() string { return fmt.Sprintf("%s@%d:%s", s.name, s.depth, s.outcome) } - -type dispatched struct { - dispatch.Event - Outputs []dispatch.Output - Warnings []dispatch.Warning -} - -type gatherer struct { - pending map[string][]dispatch.Output - warnings map[string][]dispatch.Warning -} - -func (g *gatherer) add(t *testing.T, ev dispatch.Event) (dispatched, bool) { - t.Helper() - if g.pending == nil { - g.pending = map[string][]dispatch.Output{} - g.warnings = map[string][]dispatch.Warning{} - } - if ev.Warning != nil { - g.warnings[ev.Part.Path] = append(g.warnings[ev.Part.Path], *ev.Warning) - return dispatched{}, false - } - if ev.Output != nil { - g.pending[ev.Part.Path] = append(g.pending[ev.Part.Path], *ev.Output) - return dispatched{}, false - } - outputs, warnings := g.pending[ev.Part.Path], g.warnings[ev.Part.Path] - delete(g.pending, ev.Part.Path) - delete(g.warnings, ev.Part.Path) - if len(outputs) != ev.Outputs { - t.Errorf("%s: its event counts %d outputs, after %d output events", ev.Part.Name, ev.Outputs, len(outputs)) - } - return dispatched{Event: ev, Outputs: outputs, Warnings: warnings}, true -} - -func collect(t *testing.T, seq iter.Seq2[dispatch.Event, error], each func(*dispatch.Event)) []dispatched { - t.Helper() - var g gatherer - var events []dispatched - for ev, err := range seq { - if err != nil { - t.Fatal(err) - } - if each != nil { - each(&ev) - } - if d, ok := g.add(t, ev); ok { - events = append(events, d) - } - } - return events -} - -func dispatchAll(t *testing.T, d *dispatch.Dispatcher, path string, each func(*dispatch.Event)) []dispatched { - t.Helper() - return collect(t, d.Dispatch(t.Context(), dispatch.Input{Path: path}), each) -} - -func steps(events []dispatched) []step { - out := make([]step, 0, len(events)) - for _, ev := range events { - out = append(out, step{ev.Part.Name, ev.Part.Depth, ev.Outcome}) - } - return out -} - -func wantSteps(t *testing.T, events []dispatched, want []step) { - t.Helper() - if got := steps(events); !slices.Equal(got, want) { - t.Fatalf("events:\n got %v\nwant %v", got, want) - } -} - -func hasFlag(flags []inspect.Flag, c inspect.Check) bool { - return slices.ContainsFunc(flags, func(f inspect.Flag) bool { return f.Check == c }) -} - -func byName(t *testing.T, events []dispatched, name string) dispatched { - t.Helper() - for _, ev := range events { - if ev.Part.Name == name { - return ev - } - } - t.Fatalf("no event for %s", name) - return dispatched{} -} - -func outputNamed(t *testing.T, ev dispatched, kind dispatch.OutputKind, name string) dispatch.Output { - t.Helper() - for _, o := range ev.Outputs { - if o.Kind == kind && o.Name == name { - return o - } - } - t.Fatalf("%s: no %s output named %q among %d", ev.Part.Name, kind, name, len(ev.Outputs)) - return dispatch.Output{} -} - -func wheres(events []dispatched) []string { - var out []string - for _, ev := range events { - if ev.Part.Depth > 0 { - out = append(out, ev.Part.Where) - } - } - return out -} - -func sum(content string) string { - s := sha256.Sum256([]byte(content)) - return hex.EncodeToString(s[:]) -} diff --git a/stages/internal/adapter/doc.go b/stages/internal/adapter/doc.go index bd300947..17d776cd 100644 --- a/stages/internal/adapter/doc.go +++ b/stages/internal/adapter/doc.go @@ -1,8 +1,8 @@ // Package adapter holds docproc's stage adapters, each a dispatch.Stage over its format package // and the tools it requires, and the failure classification they share. stages.Build wires them, -// and the stages package's tests drive them through this package's exported API; nothing outside -// the module reaches them. What each stage yields, the failure table, and the rules this package -// holds once are on the stages package's documentation. +// and this package's tests, in its test directory, drive them through its exported API; nothing +// outside the module reaches them. What each stage yields, the failure table, and the rules this +// package holds once are on the stages package's documentation. // // Every stage's constructor but the text stage's takes its Config, panics by name on a nil // required field, and returns the stage, its identity hashing its request resolved with the diff --git a/stages/adapter_integration_test.go b/stages/internal/adapter/test/adapter_integration_test.go similarity index 85% rename from stages/adapter_integration_test.go rename to stages/internal/adapter/test/adapter_integration_test.go index f91a8e46..735a8098 100644 --- a/stages/adapter_integration_test.go +++ b/stages/internal/adapter/test/adapter_integration_test.go @@ -1,6 +1,6 @@ //go:build linux && integration -package stages_test +package adapter_test import ( "bytes" @@ -9,21 +9,17 @@ import ( "fmt" "maps" "os" - "os/exec" "path/filepath" "slices" "strconv" "strings" "testing" - "time" - "github.com/standards-lab/docproc/audio" "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/document" "github.com/standards-lab/docproc/email" "github.com/standards-lab/docproc/inspect" "github.com/standards-lab/docproc/internal/tooltest" - "github.com/standards-lab/docproc/media" "github.com/standards-lab/docproc/metadata" "github.com/standards-lab/docproc/office" "github.com/standards-lab/docproc/onenote" @@ -31,28 +27,13 @@ import ( "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" "github.com/standards-lab/docproc/tool" ) -var builtMSG = filepath.Join("..", "email", "testdata", "built", "msg", "office-attachments.msg") - func allStages(t *testing.T) dispatch.Stages { t.Helper() - return builtSet(t, stages.Options{Document: document.ImagesRequest{Text: true}, Concurrency: 2}).Stages -} - -func builtSet(t *testing.T, opts stages.Options) stages.Set { - t.Helper() - set, err := stages.Build(t.Context(), exec.LookPath, opts) - if err != nil { - t.Fatal(err) - } - for _, row := range set.Rows { - if row.State == dispatch.Missing { - t.Fatalf("route %s: %s", row.Route, row.Reason) - } - } - return set + return stagestest.BuiltSet(t, stages.Options{Document: document.ImagesRequest{Text: true}, Concurrency: 2}).Stages } func pdfStage(t *testing.T, prep *document.Preparer, gs *tool.Tool, opts inspect.Options) *adapter.DocumentStage { @@ -87,7 +68,7 @@ func wantPNG(t *testing.T, o dispatch.Output) { func TestDocumentStageReal(t *testing.T) { d := newDispatcher(t, allStages(t), dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, documentFixture(t, "clean.pdf"), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, documentFixture(t, "clean.pdf"), func(ev *dispatch.Event) { if o := ev.Output; o != nil && o.Kind == dispatch.ImageOutput { wantPNG(t, *o) } @@ -111,7 +92,7 @@ func TestDocumentStageReal(t *testing.T) { func TestOfficeStageReal(t *testing.T) { d := newDispatcher(t, allStages(t), dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, filepath.Join(officeFixtures, "media.libreoffice.docx"), nil) + events := stagestest.DispatchAll(t, d, filepath.Join(officeFixtures(t), "media.libreoffice.docx"), nil) const emf = "670be6349ed84b27d6ca43d66ba6e9454c632f68de8d9b8fea78a480e90afb31" for _, ev := range events[:len(events)-1] { linked := strings.HasPrefix(ev.Part.Name, "https://") @@ -130,7 +111,7 @@ func TestOfficeStageReal(t *testing.T) { func TestOfficeStageMetadataReal(t *testing.T) { d := newDispatcher(t, allStages(t), dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, tooltest.Tools(t, "ooxml/fixtures/generated/docx/links.libreoffice.docx"), nil) + events := stagestest.DispatchAll(t, d, tooltest.Tools(t, "ooxml/fixtures/generated/docx/links.libreoffice.docx"), nil) ev := events[len(events)-1] o := outputNamed(t, ev, dispatch.RecordOutput, "metadata") if o.MediaType != dispatch.MediaOfficeMetadata { @@ -154,7 +135,7 @@ func TestOfficeStageMetadataReal(t *testing.T) { func TestOfficeStageRTFReal(t *testing.T) { d := newDispatcher(t, allStages(t), dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, filepath.Join("..", "office", "testdata", "rtf", "memo.rtf"), nil) + events := stagestest.DispatchAll(t, d, tooltest.Testdata(t, "office", "rtf", "memo.rtf"), nil) wantSteps(t, events, []step{{"memo.rtf", 0, dispatch.Prepared}}) if ev := events[0]; ev.Part.ContentType.Route != route.Office || ev.Part.ContentType.Kind != route.RTF { t.Errorf("memo.rtf: %s %s", ev.Part.ContentType.Route, ev.Part.ContentType.Kind) @@ -175,7 +156,7 @@ func TestPictureStageReal(t *testing.T) { for name, kind := range map[string]route.Kind{ "shapes.svg": route.SVG, "two-images.heic": route.HEIC, "animated.webp": route.WebP, "animated.avif": route.AVIF, } { - events := dispatchAll(t, d, filepath.Join("..", "picture", "testdata", name), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, tooltest.Testdata(t, "picture", name), func(ev *dispatch.Event) { if ev.Output != nil && ev.Output.Kind != dispatch.RecordOutput { wantPNG(t, *ev.Output) } @@ -196,7 +177,7 @@ func TestPictureStageReal(t *testing.T) { t.Errorf("%s: outputs %+v", name, o) } } - events := dispatchAll(t, d, filepath.Join("..", "picture", "testdata", "pages.tiff"), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, tooltest.Testdata(t, "picture", "pages.tiff"), func(ev *dispatch.Event) { if ev.Output != nil { wantPNG(t, *ev.Output) } @@ -213,7 +194,7 @@ func TestPictureStageReal(t *testing.T) { func TestEmailStageReal(t *testing.T) { d := newDispatcher(t, allStages(t), dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, builtMSG, func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, builtMSG(t), func(ev *dispatch.Event) { if ev.Part.ContentType.Route == route.VisionConverted && ev.Output != nil { wantPNG(t, *ev.Output) } @@ -232,7 +213,7 @@ func TestEmailStageReal(t *testing.T) { } delete(top, ev.Part.Name) } - if ev.Part.Depth > 0 && !slices.ContainsFunc(events[i+1:], func(p dispatched) bool { return p.Part.ID == ev.Part.Parent }) { + if ev.Part.Depth > 0 && !slices.ContainsFunc(events[i+1:], func(p stagestest.Dispatched) bool { return p.Part.ID == ev.Part.Parent }) { t.Errorf("event %d, %s@%d, comes after its parent's", i, ev.Part.Name, ev.Part.Depth) } } @@ -243,7 +224,7 @@ func TestEmailStageReal(t *testing.T) { t.Error("budget.xls wasn't converted from xls") } - events = dispatchAll(t, d, filepath.Join(mailFixtures(t), "msg", "tika", "testMSG_att_msg.msg"), nil) + events = stagestest.DispatchAll(t, d, filepath.Join(mailFixtures(t), "msg", "tika", "testMSG_att_msg.msg"), nil) wantSteps(t, events, []step{ {"smbprn.00009008.KdcPjl.pdf", 1, dispatch.Prepared}, {"testMSG_att_msg.msg", 0, dispatch.Prepared}, @@ -255,12 +236,12 @@ func TestEmailStageReal(t *testing.T) { func TestOneNoteStageReal(t *testing.T) { d := newDispatcher(t, allStages(t), dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, filepath.Join(onenoteFixtures(t), "handwriting_recognition.one"), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, filepath.Join(onenoteFixtures(t), "handwriting_recognition.one"), func(ev *dispatch.Event) { if ev.Part.ContentType.Route == route.VisionConverted && ev.Output != nil { wantPNG(t, *ev.Output) } }) - var ink *dispatched + var ink *stagestest.Dispatched for i := range events { if strings.HasSuffix(events[i].Part.Name, ".svg") { ink = &events[i] @@ -271,48 +252,10 @@ func TestOneNoteStageReal(t *testing.T) { } } -func TestBuiltIdentities(t *testing.T) { - set := builtSet(t, stages.Options{}) - lines := map[string]string{} - for _, tl := range set.Tools { - lines[tl.Program] = tl.Version - } - for r, needs := range adapter.Needs() { - row := set.Rows[slices.IndexFunc(set.Rows, func(row dispatch.Row) bool { return row.Route == r })] - var want []string - for _, program := range needs { - want = append(want, lines[program]) - } - if len(want) > 0 && (row.Stage.Version != strings.Join(want, ", ") || row.Tools != row.Stage.Version) { - t.Errorf("%s: version %q, tools %q; want %q", r, row.Stage.Version, row.Tools, strings.Join(want, ", ")) - } - if row.Stage.Name == "" || len(row.Stage.Config) != 64 || set.Stages[r].Identity() != row.Stage { - t.Errorf("%s: identity %v", r, row.Stage) - } - } - bounded := builtSet(t, stages.Options{Timeout: time.Hour, Idle: time.Hour, Concurrency: 3}) - changed := builtSet(t, stages.Options{ - Document: document.ImagesRequest{DPI: 300}, Picture: picture.Request{Density: 300}, - Audio: audio.Request{Limit: 20 * time.Second}, Video: media.Request{MaxSide: 768}, - Inspect: inspect.Options{BombRatio: 100, BombSize: 1 << 20}, - }) - for i, row := range set.Rows { - if bounded.Rows[i].Stage != row.Stage { - t.Errorf("%s: a run bound changed the identity", row.Route) - } - switch row.Route { - case route.Document, route.VisionConverted, route.Audio, route.Video, route.Archive: - if changed.Rows[i].Stage.Config == row.Stage.Config { - t.Errorf("%s: a request left the identity's config alone", row.Route) - } - } - } -} - func TestOfficeConverted(t *testing.T) { - set := builtSet(t, stages.Options{Exclude: slices.DeleteFunc(stages.Routes(), func(r route.Route) bool { return r == route.Office })}) + set := stagestest.BuiltSet(t, stages.Options{Exclude: slices.DeleteFunc(stages.Routes(), func(r route.Route) bool { return r == route.Office })}) d := newDispatcher(t, dispatch.Stages{route.Office: set.Stages[route.Office]}, dispatch.NewMemoryIndex(0)) - testdata := filepath.Join("..", "office", "testdata") + testdata := tooltest.Testdata(t, "office") for _, c := range []struct{ path, from, text string }{ {filepath.Join(testdata, "odf", "generated", "tables.libreoffice.odt"), "odt", ""}, {filepath.Join(testdata, "odf", "generated", "cells.libreoffice.ots"), "ots", ""}, @@ -322,7 +265,7 @@ func TestOfficeConverted(t *testing.T) { {filepath.Join(testdata, "xlsb", "testVarious.xlsb"), "xlsb", ""}, } { name := filepath.Base(c.path) - events := dispatchAll(t, d, c.path, nil) + events := stagestest.DispatchAll(t, d, c.path, nil) ev := events[len(events)-1] if ev.Part.ContentType.Route != route.Office || ev.Outcome != dispatch.Prepared { t.Errorf("%s: %s %s, %q; want prepared by office", name, ev.Part.ContentType.Route, ev.Outcome, ev.Reason) @@ -337,21 +280,21 @@ func TestOfficeConverted(t *testing.T) { t.Errorf("%s: the metadata record converted from %q, %v; want %s", name, rec.ConvertedFrom, err, c.from) } } - formula := input(t, "x.odf", zipOf(t, "mimetype", "application/vnd.oasis.opendocument.formula", "content.xml", "")) - ev := dispatchAll(t, d, formula, nil)[0] + formula := stagestest.Input(t, "x.odf", zipOf(t, "mimetype", "application/vnd.oasis.opendocument.formula", "content.xml", "")) + ev := stagestest.DispatchAll(t, d, formula, nil)[0] if ev.Part.ContentType.Route != route.Office || ev.Outcome != dispatch.NoProcessor || !strings.Contains(ev.Reason, "no processor yet for an ODF package of type application/vnd.oasis.opendocument.formula") { t.Errorf("x.odf: %s %s, %q; want office's no processor", ev.Part.ContentType.Route, ev.Outcome, ev.Reason) } } func TestOfficeEncryptedFixtures(t *testing.T) { - testdata := filepath.Join("..", "office", "testdata") + testdata := tooltest.Testdata(t, "office") for _, path := range []string{ filepath.Join(testdata, "odf", "generated", "encrypted.odt"), filepath.Join(testdata, "xlsb", "protected_passtika.xlsb"), } { d := newDispatcher(t, dispatch.Stages{route.Office: testOfficeStage(t)}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, path, nil) + events := stagestest.DispatchAll(t, d, path, nil) wantSteps(t, events, []step{{filepath.Base(path), 0, dispatch.Encrypted}}) if ev := events[0]; ev.Part.ContentType.Route != route.Office || !errors.Is(ev.Err, dispatch.ErrEncrypted) { t.Errorf("%s: route %s, %v; want office, ErrEncrypted", filepath.Base(path), ev.Part.ContentType.Route, ev.Err) @@ -367,7 +310,7 @@ func TestOfficeEncrypted(t *testing.T) { } for _, name := range []string{"encrypted.xlsx", "encrypted.xlsb"} { d := newDispatcher(t, dispatch.Stages{route.Office: stage}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, input(t, name, string(content)), nil) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, name, string(content)), nil) wantSteps(t, events, []step{{name, 0, dispatch.Encrypted}}) ev := events[0] if ev.Part.ContentType.Route != route.Office || !strings.Contains(ev.Part.ContentType.RouteReason, "an encrypted OOXML package") { @@ -383,7 +326,7 @@ func TestOfficeStage(t *testing.T) { d := newDispatcher(t, dispatch.Stages{ route.Office: testOfficeStage(t), route.Vision: testVisionStage(t), route.VisionConverted: testPictureStage(t), }, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, filepath.Join(officeFixtures, "media.libreoffice.docx"), nil) + events := stagestest.DispatchAll(t, d, filepath.Join(officeFixtures(t), "media.libreoffice.docx"), nil) const ( red = "0fcca33bb0baf1a0669bd2fcdcaeb34e33d27196f7ffb5294b27aea8a9e46446" blue = "10a86bd779a80e60e5d3314ec1edeab643cb454a4c7dfee671132090878d7aea" @@ -428,7 +371,7 @@ func TestEmailStage(t *testing.T) { csv = "отчёт.csv" note = "note-g.txt" ) - events := dispatchAll(t, d, filepath.Join(mailFixtures(t), "generated", "msg", "03-html-inline-image.msg"), nil) + events := stagestest.DispatchAll(t, d, filepath.Join(mailFixtures(t), "generated", "msg", "03-html-inline-image.msg"), nil) wantSteps(t, events, []step{{moth, 1, dispatch.Prepared}, {"03-html-inline-image.msg", 0, dispatch.Prepared}}) if got := wheres(events); !slices.Equal(got, []string{"message, attachment 1"}) { t.Errorf("wheres %q", got) @@ -443,7 +386,7 @@ func TestEmailStage(t *testing.T) { outputNamed(t, msg, dispatch.RecordOutput, "store") var order []string - events = dispatchAll(t, d, filepath.Join(mailFixtures(t), "generated", "pst", "mailbox.pst"), func(ev *dispatch.Event) { + events = stagestest.DispatchAll(t, d, filepath.Join(mailFixtures(t), "generated", "pst", "mailbox.pst"), func(ev *dispatch.Event) { switch { case ev.Output != nil && ev.Part.Depth == 0: order = append(order, string(ev.Output.Kind)+" "+ev.Output.Name) @@ -490,7 +433,7 @@ func TestEmailResume(t *testing.T) { stage := testEmailStage(t) stages := dispatch.Stages{route.Nested: stage, route.Vision: testVisionStage(t)} path := filepath.Join(mailFixtures(t), "generated", "pst", "mailbox.pst") - whole := dispatchAll(t, newDispatcher(t, stages, dispatch.NewMemoryIndex(0)), path, nil) + whole := stagestest.DispatchAll(t, newDispatcher(t, stages, dispatch.NewMemoryIndex(0)), path, nil) wholeStore := whole[len(whole)-1] var ids []string for _, o := range wholeStore.Outputs { @@ -528,7 +471,7 @@ func TestEmailResume(t *testing.T) { index := dispatch.NewMemoryIndex(0) d := newDispatcher(t, stages, index) - resumed := collect(t, d.Dispatch(t.Context(), dispatch.Input{Path: path, After: after}), nil) + resumed := stagestest.Collect(t, d.Dispatch(t.Context(), dispatch.Input{Path: path, After: after}), nil) store := resumed[len(resumed)-1] if store.Outcome != dispatch.Prepared || store.Part.After != after { t.Fatalf("the resumed store: %s, after %d", store.Outcome, store.Part.After) @@ -552,7 +495,7 @@ func TestEmailResume(t *testing.T) { if _, ok, err := index.Lookup(t.Context(), key); err != nil || ok { t.Errorf("the resumed store recorded: %t, %v", ok, err) } - if again := dispatchAll(t, d, path, nil); again[len(again)-1].Outcome != dispatch.Prepared { + if again := stagestest.DispatchAll(t, d, path, nil); again[len(again)-1].Outcome != dispatch.Prepared { t.Errorf("a whole dispatch after the resumed one: %s, want prepared", again[len(again)-1].Outcome) } for ev, err := range d.Dispatch(t.Context(), dispatch.Input{Path: path, After: after}) { @@ -580,7 +523,7 @@ func TestEmailResume(t *testing.T) { func TestEmailEmbedded(t *testing.T) { d := newDispatcher(t, dispatch.Stages{route.Nested: testEmailStage(t)}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, filepath.Join(mailFixtures(t), "msg", "tika", "testMSG_att_msg.msg"), nil) + events := stagestest.DispatchAll(t, d, filepath.Join(mailFixtures(t), "msg", "tika", "testMSG_att_msg.msg"), nil) wantSteps(t, events, []step{ {"smbprn.00009008.KdcPjl.pdf", 1, dispatch.NoProcessor}, {"testMSG_att_msg.msg", 0, dispatch.Prepared}, @@ -597,7 +540,7 @@ func TestEmailEmbedded(t *testing.T) { } outputNamed(t, events[1], dispatch.MarkdownOutput, "message, attachment 1") - events = dispatchAll(t, d, filepath.Join(mailFixtures(t), "generated", "eml", "08-forward-attached-message.eml"), nil) + events = stagestest.DispatchAll(t, d, filepath.Join(mailFixtures(t), "generated", "eml", "08-forward-attached-message.eml"), nil) wantSteps(t, events, []step{{"note-g.txt", 1, dispatch.NoProcessor}, {"08-forward-attached-message.eml", 0, dispatch.Prepared}}) if m := outputNamed(t, events[1], dispatch.RecordOutput, "message, attachment 2").Meta; m["subject"] != "Notes on the engine (draft)" { t.Errorf("the forwarded message's meta %v", m) @@ -606,12 +549,12 @@ func TestEmailEmbedded(t *testing.T) { func TestEmailThreadingReal(t *testing.T) { d := newDispatcher(t, dispatch.Stages{route.Nested: testEmailStage(t)}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, filepath.Join(mailFixtures(t), "mime", "eml", "09-threading.eml"), nil) + events := stagestest.DispatchAll(t, d, filepath.Join(mailFixtures(t), "mime", "eml", "09-threading.eml"), nil) m := outputNamed(t, events[0], dispatch.RecordOutput, "message").Meta if m[dispatch.MetaInReplyTo] != "" || m[dispatch.MetaReferences] != " " { t.Errorf("the reply's meta %v", m) } - events = dispatchAll(t, d, filepath.Join(mailFixtures(t), "generated", "eml", "01-plain.eml"), nil) + events = stagestest.DispatchAll(t, d, filepath.Join(mailFixtures(t), "generated", "eml", "01-plain.eml"), nil) m = outputNamed(t, events[0], dispatch.RecordOutput, "message").Meta if _, ok := m[dispatch.MetaInReplyTo]; ok { t.Errorf("the first message's meta %v, want no in_reply_to", m) @@ -624,7 +567,7 @@ func TestEmailThreadingReal(t *testing.T) { func TestEmailConversations(t *testing.T) { d := newDispatcher(t, dispatch.Stages{route.Nested: testEmailStage(t)}, dispatch.NewMemoryIndex(0)) generated := filepath.Join(mailFixtures(t), "generated") - events := dispatchAll(t, d, filepath.Join(generated, "pst", "conversations.pst"), nil) + events := stagestest.DispatchAll(t, d, filepath.Join(generated, "pst", "conversations.pst"), nil) wantSteps(t, events, []step{{"conversations.pst", 0, dispatch.Prepared}}) data, err := os.ReadFile(filepath.Join(generated, "truth.json")) if err != nil { @@ -702,7 +645,7 @@ func TestOneNoteStage(t *testing.T) { jpg = "d6d4898c203cbff35fe92e844bbf404064293314a71d1e6b24e907334e5bdff9.jpg" inked = "95c93a747acbbbeeb6d345faf0d17e86669bc7cdd0854155b588c58a7556d194.svg" ) - events := dispatchAll(t, d, filepath.Join(onenoteFixtures(t), "handwriting_recognition.one"), nil) + events := stagestest.DispatchAll(t, d, filepath.Join(onenoteFixtures(t), "handwriting_recognition.one"), nil) var names []string for _, ev := range events { names = append(names, fmt.Sprintf("%s@%d:%s %s", filepath.Ext(ev.Part.Name), ev.Part.Depth, ev.Outcome, ev.Part.ContentType.Route)) @@ -728,7 +671,7 @@ func TestOneNoteStage(t *testing.T) { } recordThenMarkdown(t, section, page) - events = dispatchAll(t, d, filepath.Join(onenoteFixtures(t), "New Section 1.one"), nil) + events = stagestest.DispatchAll(t, d, filepath.Join(onenoteFixtures(t), "New Section 1.one"), nil) img := events[0] if img.Part.SHA256+".jpg" != jpg || img.Outcome != dispatch.Seen || img.Recorded != dispatch.Prepared { t.Errorf("the shared image: %s %s, recorded %s", img.Part.Name, img.Outcome, img.Recorded) @@ -748,10 +691,6 @@ func mailFixtures(t *testing.T) string { return tooltest.Tools(t, "mail/tests/fixtures") } -var ( - officeFixtures = filepath.Join("..", "office", "testdata", "ooxml") -) - func pinned(t *testing.T, spec tool.Spec) *tool.Tool { t.Helper() tl, err := tool.NewExec(t.Context(), spec) @@ -827,7 +766,7 @@ func testOnenoteStage(t *testing.T) *adapter.OneNoteStage { return s } -func recordThenMarkdown(t *testing.T, ev dispatched, name string) { +func recordThenMarkdown(t *testing.T, ev stagestest.Dispatched, name string) { t.Helper() i := slices.IndexFunc(ev.Outputs, func(o dispatch.Output) bool { return o.Name == name }) if i < 0 || i+1 >= len(ev.Outputs) || ev.Outputs[i].Kind != dispatch.RecordOutput || @@ -835,3 +774,9 @@ func recordThenMarkdown(t *testing.T, ev dispatched, name string) { t.Errorf("%s: %q's outputs aren't its record, then its Markdown", ev.Part.Name, name) } } + +func builtMSG(t testing.TB) string { + return tooltest.Testdata(t, "email", "built", "msg", "office-attachments.msg") +} + +func officeFixtures(t testing.TB) string { return tooltest.Testdata(t, "office", "ooxml") } diff --git a/stages/adapter_test.go b/stages/internal/adapter/test/adapter_test.go similarity index 56% rename from stages/adapter_test.go rename to stages/internal/adapter/test/adapter_test.go index 28658461..d85985d9 100644 --- a/stages/adapter_test.go +++ b/stages/internal/adapter/test/adapter_test.go @@ -1,14 +1,12 @@ //go:build linux -package stages_test +package adapter_test import ( "bytes" - "cmp" "fmt" "os" "slices" - "strconv" "strings" "testing" @@ -17,6 +15,7 @@ import ( "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" "github.com/standards-lab/docproc/tool" ) @@ -29,76 +28,7 @@ func newDispatcher(t *testing.T, stages dispatch.Stages, index dispatch.Index) * return d } -type gsSettings struct { - Pages int `json:"pages"` - Empty int `json:"empty,omitzero"` - Fail int `json:"fail,omitzero"` -} - -func gsStandin(r tooltest.Run) int { - var settings gsSettings - if err := r.Settings(&settings); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - args := r.Args - if len(args) == 1 && args[0] == "--version" { - fmt.Println("10.08.0") - return 0 - } - if slices.Contains(args, "-dNODISPLAY") { - fmt.Println(settings.Pages) - if settings.Pages > 0 && strings.Contains(args[len(args)-1], "/Collection") { - fmt.Println(false) - } - return 0 - } - for _, page := range tooltest.GSPages(args) { - if page == settings.Fail { - fmt.Fprint(os.Stderr, "told to fail") - return 1 - } - if _, err := os.Stdout.Write(tooltest.PNG(fmt.Sprintf("page %d", page))); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - } - return 0 -} - -type pdftotextSettings struct { - Empty int `json:"empty,omitzero"` - Version string `json:"version,omitzero"` -} - -func pdftotextStandin(r tooltest.Run) int { - var settings pdftotextSettings - if err := r.Settings(&settings); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - args := r.Args - if len(args) == 1 && args[0] == "-v" { - fmt.Fprintf(os.Stderr, "pdftotext version %s\n", cmp.Or(settings.Version, "26.10.0")) - return 0 - } - page, err := strconv.Atoi(args[slices.Index(args, "-f")+1]) - if err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - text := fmt.Sprintf("page %d\f", page) - if page == settings.Empty { - text = " \n\f" - } - if _, err := os.Stdout.WriteString(text); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - return 0 -} - -func standinPreparer(t *testing.T, s gsSettings) *document.Preparer { +func standinPreparer(t *testing.T, s stagestest.GSSettings) *document.Preparer { t.Helper() spec := document.GhostscriptSpec() spec.Program = tooltest.Link(t, t.TempDir(), "gs", s) @@ -111,7 +41,7 @@ func standinPreparer(t *testing.T, s gsSettings) *document.Preparer { t.Fatal(err) } textSpec := document.PDFToTextSpec() - textSpec.Program = tooltest.Link(t, t.TempDir(), "pdftotext", pdftotextSettings{Empty: s.Empty}) + textSpec.Program = tooltest.Link(t, t.TempDir(), "pdftotext", stagestest.PDFToTextSettings{Empty: s.Empty}) pdftotext, err := tool.NewExec(t.Context(), textSpec) if err != nil { t.Fatal(err) @@ -132,9 +62,9 @@ func testDocumentStage(t *testing.T, prep *document.Preparer) *adapter.DocumentS } func TestDocumentStage(t *testing.T) { - pdf := input(t, "three.pdf", "%PDF-1.7\n%%EOF\n") - d := newDispatcher(t, dispatch.Stages{route.Document: testDocumentStage(t, standinPreparer(t, gsSettings{Pages: 3, Empty: 2}))}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, pdf, func(ev *dispatch.Event) { + pdf := stagestest.Input(t, "three.pdf", "%PDF-1.7\n%%EOF\n") + d := newDispatcher(t, dispatch.Stages{route.Document: testDocumentStage(t, standinPreparer(t, stagestest.GSSettings{Pages: 3, Empty: 2}))}, dispatch.NewMemoryIndex(0)) + events := stagestest.DispatchAll(t, d, pdf, func(ev *dispatch.Event) { if o := ev.Output; o != nil && o.Kind == dispatch.ImageOutput { b, err := os.ReadFile(o.Path) if err != nil || !bytes.HasPrefix(b, []byte(route.PNGSignature)) { @@ -156,9 +86,9 @@ func TestDocumentStage(t *testing.T) { t.Errorf("outputs:\n got %q\nwant %q", got, want) } - d = newDispatcher(t, dispatch.Stages{route.Document: testDocumentStage(t, standinPreparer(t, gsSettings{Pages: 3, Fail: 2}))}, dispatch.NewMemoryIndex(0)) + d = newDispatcher(t, dispatch.Stages{route.Document: testDocumentStage(t, standinPreparer(t, stagestest.GSSettings{Pages: 3, Fail: 2}))}, dispatch.NewMemoryIndex(0)) var warnings []dispatch.Warning - ev := dispatchAll(t, d, pdf, func(ev *dispatch.Event) { + ev := stagestest.DispatchAll(t, d, pdf, func(ev *dispatch.Event) { if ev.Warning != nil { warnings = append(warnings, *ev.Warning) } @@ -170,3 +100,29 @@ func TestDocumentStage(t *testing.T) { t.Errorf("a failing page's warnings: %+v", warnings) } } + +func TestStagesPanic(t *testing.T) { + t.Parallel() + for want, build := range map[string]func(){ + "stages: DocumentConfig.Preparer is nil": func() { adapter.NewDocumentStage(adapter.DocumentConfig{Version: "gs"}) }, + "stages: DocumentConfig.QPDF is nil": func() { + adapter.NewDocumentStage(adapter.DocumentConfig{Preparer: &document.Preparer{}, Version: "gs"}) + }, + "stages: DocumentConfig.PDFDetach is nil": func() { + adapter.NewDocumentStage(adapter.DocumentConfig{Preparer: &document.Preparer{}, QPDF: &fakeQPDF{}}) + }, + "stages: DocumentConfig.PDFInfo is nil": func() { + adapter.NewDocumentStage(adapter.DocumentConfig{Preparer: &document.Preparer{}, QPDF: &fakeQPDF{}, PDFDetach: &fakeDetach{}}) + }, + "stages: OfficeConfig.Converter is nil": func() { adapter.NewOfficeStage(adapter.OfficeConfig{Version: "x"}) }, + "stages: PictureConfig.Converter is nil": func() { adapter.NewPictureStage(adapter.PictureConfig{Version: "x"}) }, + "stages: EmailConfig.Reader is nil": func() { adapter.NewEmailStage(adapter.EmailConfig{Version: "x"}) }, + "stages: OneNoteConfig.Reader is nil": func() { adapter.NewOneNoteStage(adapter.OneNoteConfig{Version: "x"}) }, + "stages: ArchiveConfig.SevenZip is nil": func() { adapter.NewArchiveStage(adapter.ArchiveConfig{Version: "x"}) }, + "stages: AudioConfig.Splitter is nil": func() { adapter.NewAudioStage(adapter.AudioConfig{Version: "x"}) }, + "stages: VideoConfig.Streamer is nil": func() { adapter.NewVideoStage(adapter.VideoConfig{Version: "x"}) }, + "stages: archive stage: no version": func() { adapter.NewArchiveStage(adapter.ArchiveConfig{SevenZip: &fakeSevenZip{}}) }, + } { + wantPanic(t, want, build) + } +} diff --git a/stages/archive_sevenzip_integration_test.go b/stages/internal/adapter/test/archive_sevenzip_integration_test.go similarity index 87% rename from stages/archive_sevenzip_integration_test.go rename to stages/internal/adapter/test/archive_sevenzip_integration_test.go index 2c156b0e..b95785ae 100644 --- a/stages/archive_sevenzip_integration_test.go +++ b/stages/internal/adapter/test/archive_sevenzip_integration_test.go @@ -1,6 +1,6 @@ //go:build linux && integration -package stages_test +package adapter_test import ( "crypto/sha256" @@ -17,6 +17,7 @@ import ( "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/sevenzip" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) func sevenZipConfig(t *testing.T, opts inspect.Options) adapter.ArchiveConfig { @@ -36,7 +37,7 @@ func sevenZipDispatcher(t *testing.T, opts inspect.Options) (*dispatch.Dispatche func TestSevenZipStage(t *testing.T) { d, zs, work := sevenZipDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, sevenZipFixture("generated/clean.7z"), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/clean.7z"), func(ev *dispatch.Event) { if ev.Part.Depth > 0 && (filepath.Base(ev.Part.Path) != ev.Part.SHA256 || !inside(work, ev.Part.Path)) { t.Errorf("%s at %s: want its SHA-256 inside the working directory", ev.Part.Name, ev.Part.Path) } @@ -63,7 +64,7 @@ func TestSevenZipStage(t *testing.T) { func TestSevenZipStreams(t *testing.T) { d, _, work := sevenZipDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, sevenZipFixture("generated/clean.tar.zst"), nil) + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/clean.tar.zst"), nil) wantSteps(t, events, []step{ {"docs/notes.txt", 2, dispatch.NoProcessor}, {"docs/pixel.png", 2, dispatch.Prepared}, @@ -74,7 +75,7 @@ func TestSevenZipStreams(t *testing.T) { t.Errorf("clean.tar.zst: wheres:\n got %q\nwant %q", got, want) } - events = dispatchAll(t, d, sevenZipFixture("generated/notebook.cab"), nil) + events = stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/notebook.cab"), nil) wantSteps(t, events, []step{ {"Open Notebook.onetoc2", 1, dispatch.NoProcessor}, {"New Section 1.one", 1, dispatch.NoProcessor}, @@ -93,7 +94,7 @@ func TestSevenZipStreams(t *testing.T) { t.Errorf("New Section 1.one: SHA-256 %s, want the section's", events[1].Part.SHA256) } - events = dispatchAll(t, d, sevenZipFixture("commons-compress/bla.deflate64.7z"), nil) + events = stagestest.DispatchAll(t, d, sevenZipFixture(t, "commons-compress/bla.deflate64.7z"), nil) wantSteps(t, events, []step{ {"test1.xml", 1, dispatch.NoProcessor}, {"test2.xml", 1, dispatch.NoProcessor}, @@ -123,7 +124,7 @@ func TestZipMethods(t *testing.T) { d, _, work := sevenZipDispatcher(t, inspect.Options{}) sums := map[string]string{} for _, c := range zipMethods { - events := dispatchAll(t, d, sevenZipFixture(c.fixture), nil) + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, c.fixture), nil) if len(events) != 2 || events[0].Part.Name != c.entry || events[0].Part.Size != c.size || events[0].Part.Where != "zip entry "+c.entry || events[1].Outcome != dispatch.Prepared || len(events[1].Outputs) != 0 { t.Errorf("%s: %v, %d bytes, %d records", c.fixture, steps(events), events[0].Part.Size, len(events[len(events)-1].Outputs)) @@ -156,7 +157,7 @@ func TestSevenZipUnsafe(t *testing.T) { {"absolute.cab", inspect.ArchiveAbsolutePath, nil, map[string]inspect.Check{"/tmp/evil.txt": inspect.ArchiveAbsolutePath, "C:/evil.txt": inspect.ArchiveAbsolutePath}}, } { d, zs, work := sevenZipDispatcher(t, strict) - events := dispatchAll(t, d, sevenZipFixture("generated/"+c.fixture), nil) + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/"+c.fixture), nil) ev := events[0] if len(events) != 1 || ev.Outcome != dispatch.Quarantined || zs.calls.Load() != 1 || !slices.ContainsFunc(ev.Part.Flags, func(f inspect.Flag) bool { return f.Check == c.check }) || @@ -170,12 +171,12 @@ func TestSevenZipUnsafe(t *testing.T) { if err := os.MkdirAll(work, 0o700); err != nil { t.Fatal(err) } - checkUnsafe(t, adapter.NewArchiveStage(sevenZipConfig(t, inspect.Options{})), sevenZipFixture("generated/"+c.fixture), root, work, c.parts, c.children) + checkUnsafe(t, adapter.NewArchiveStage(sevenZipConfig(t, inspect.Options{})), sevenZipFixture(t, "generated/"+c.fixture), root, work, c.parts, c.children) } } func TestSevenZipQuarantined(t *testing.T) { - traversal, err := os.ReadFile(sevenZipFixture("generated/traversal.7z")) + traversal, err := os.ReadFile(sevenZipFixture(t, "generated/traversal.7z")) if err != nil { t.Fatal(err) } @@ -188,7 +189,7 @@ func TestSevenZipQuarantined(t *testing.T) { if err != nil { t.Fatal(err) } - events := dispatchAll(t, d, input(t, "outer.zip", zipBytes(t, zent{name: "traversal.7z", body: string(traversal)})), nil) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "outer.zip", zipBytes(t, zent{name: "traversal.7z", body: string(traversal)})), nil) wantSteps(t, events, []step{{"traversal.7z", 1, dispatch.Quarantined}, {"outer.zip", 0, dispatch.Prepared}}) if flags := events[0].Part.Flags; !slices.ContainsFunc(flags, func(f inspect.Flag) bool { return f.Check == inspect.ArchiveTraversal }) { t.Errorf("traversal.7z's flags: %v", flags) @@ -209,7 +210,7 @@ func TestSevenZipBombs(t *testing.T) { {"bomb.xz", lowered, inspect.ArchiveBomb}, } { d, _, work := sevenZipDispatcher(t, c.opts) - events := dispatchAll(t, d, sevenZipFixture("generated/"+c.fixture), nil) + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/"+c.fixture), nil) if len(events) != 1 || events[0].Outcome != dispatch.Quarantined || !strings.Contains(events[0].Reason, string(c.check)+": entry ") { t.Errorf("%s: %v, %q; want quarantined by its listing's %s", c.fixture, steps(events), events[0].Reason, c.check) } @@ -228,7 +229,7 @@ func TestSevenZipBombs(t *testing.T) { opts := lowered opts.Policy = map[inspect.Check]inspect.Verdict{c.check: inspect.Proceed} d, _, work := sevenZipDispatcher(t, opts) - events := dispatchAll(t, d, sevenZipFixture("generated/"+c.fixture), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/"+c.fixture), func(ev *dispatch.Event) { if left := files(t, work); len(left) > 0 { t.Errorf("%s: files at the archive's event: %q, want the partial file removed", c.fixture, left) } @@ -246,7 +247,7 @@ func TestSevenZipBombs(t *testing.T) { func TestSevenZipEncrypted(t *testing.T) { d, _, work := sevenZipDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, sevenZipFixture("generated/encrypted.7z"), nil) + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/encrypted.7z"), nil) wantSteps(t, events, []step{{"notes.txt", 1, dispatch.NoProcessor}, {"secret.txt", 1, dispatch.Encrypted}, {"encrypted.7z", 0, dispatch.Encrypted}}) last := events[2] if ev := events[1]; ev.Part.Where != "7z entry secret.txt" || len(ev.Part.Flags) != 1 || @@ -256,7 +257,7 @@ func TestSevenZipEncrypted(t *testing.T) { if !strings.Contains(last.Reason, "1 of 2 entries") { t.Errorf("encrypted.7z: reason %q", last.Reason) } - events = dispatchAll(t, d, sevenZipFixture("generated/encrypted-headers.7z"), nil) + events = stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/encrypted-headers.7z"), nil) wantSteps(t, events, []step{{"encrypted-headers.7z", 0, dispatch.Encrypted}}) if !strings.Contains(events[0].Reason, "headers are encrypted") || len(events[0].Outputs) != 0 { t.Errorf("encrypted-headers.7z: %q, %d outputs", events[0].Reason, len(events[0].Outputs)) @@ -265,20 +266,20 @@ func TestSevenZipEncrypted(t *testing.T) { } func TestSevenZipDamaged(t *testing.T) { - whole, err := os.ReadFile(sevenZipFixture("generated/clean.7z")) + whole, err := os.ReadFile(sevenZipFixture(t, "generated/clean.7z")) if err != nil { t.Fatal(err) } d, _, work := sevenZipDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, input(t, "cut.7z", string(whole[:100])), nil) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "cut.7z", string(whole[:100])), nil) if ev := events[0]; len(events) != 1 || ev.Outcome != dispatch.Failed || !strings.Contains(ev.Reason, "can't be opened") { t.Errorf("cut.7z: %v, %q; want failed", steps(events), ev.Reason) } - zst, err := os.ReadFile(sevenZipFixture("generated/clean.tar.zst")) + zst, err := os.ReadFile(sevenZipFixture(t, "generated/clean.tar.zst")) if err != nil { t.Fatal(err) } - events = dispatchAll(t, d, input(t, "cut.tar.zst", string(zst[:1000])), nil) + events = stagestest.DispatchAll(t, d, stagestest.Input(t, "cut.tar.zst", string(zst[:1000])), nil) wantSteps(t, events, []step{{"cut.tar", 1, dispatch.Failed}, {"cut.tar.zst", 0, dispatch.Prepared}}) if ev := events[0]; ev.Part.Where != "zstd content cut.tar" || !strings.HasPrefix(ev.Reason, "doesn't decompress") { t.Errorf("cut.tar.zst's content: %q, %q", ev.Part.Where, ev.Reason) @@ -310,7 +311,7 @@ func TestRARStage(t *testing.T) { {"test_read_format_rar5_symlink.rar", 0, dispatch.Prepared}, }, map[string]int64{"file.txt": 5}}, } { - events := dispatchAll(t, d, sevenZipFixture("libarchive/"+c.fixture), nil) + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, "libarchive/"+c.fixture), nil) wantSteps(t, events, c.want) for _, ev := range events[:len(events)-1] { if ev.Part.Where != "RAR entry "+ev.Part.Name { @@ -330,7 +331,7 @@ func TestRARStage(t *testing.T) { func TestRARSplitVolumes(t *testing.T) { d, _, work := sevenZipDispatcher(t, inspect.Options{}) for _, fixture := range []string{"test_read_format_rar_multivolume.part0001.rar", "test_read_format_rar5_multiarchive.part01.rar"} { - events := dispatchAll(t, d, sevenZipFixture("libarchive/"+fixture), nil) + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, "libarchive/"+fixture), nil) wantSteps(t, events, []step{{fixture, 0, dispatch.NoProcessor}}) if events[0].Reason != "archive stage: a split RAR volume: no processor yet" { t.Errorf("%s: reason %q", fixture, events[0].Reason) @@ -365,7 +366,7 @@ func TestRAREncrypted(t *testing.T) { {"test_read_format_rar5_encrypted_filenames.rar", 0, dispatch.Encrypted}, }, "a RAR archive whose headers are encrypted"}, } { - events := dispatchAll(t, d, sevenZipFixture("libarchive/"+c.fixture), nil) + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, "libarchive/"+c.fixture), nil) wantSteps(t, events, c.want) last := events[len(events)-1] if !strings.Contains(last.Reason, c.reason) { @@ -383,13 +384,13 @@ func TestRAREncrypted(t *testing.T) { func TestXZStreams(t *testing.T) { d, _, work := sevenZipDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, sevenZipFixture("generated/notes.txt.xz"), nil) + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/notes.txt.xz"), nil) wantSteps(t, events, []step{{"notes.txt", 1, dispatch.NoProcessor}, {"notes.txt.xz", 0, dispatch.Prepared}}) if ev := events[0]; ev.Part.Where != "xz content notes.txt" || ev.Part.SHA256 != sum("an ordinary entry\n") { t.Errorf("notes.txt: %q, SHA-256 %s", ev.Part.Where, ev.Part.SHA256) } - events = dispatchAll(t, d, sevenZipFixture("generated/clean.txz"), nil) + events = stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/clean.txz"), nil) wantSteps(t, events, []step{ {"docs/notes.txt", 2, dispatch.NoProcessor}, {"docs/pixel.png", 2, dispatch.Prepared}, @@ -403,11 +404,11 @@ func TestXZStreams(t *testing.T) { t.Errorf("clean.tar: %s, %d bytes", ev.Part.ContentType.Kind, ev.Part.Size) } - xz, err := os.ReadFile(sevenZipFixture("generated/clean.txz")) + xz, err := os.ReadFile(sevenZipFixture(t, "generated/clean.txz")) if err != nil { t.Fatal(err) } - events = dispatchAll(t, d, input(t, "cut.txz", string(xz[:len(xz)-40])), nil) + events = stagestest.DispatchAll(t, d, stagestest.Input(t, "cut.txz", string(xz[:len(xz)-40])), nil) wantSteps(t, events, []step{{"cut.tar", 1, dispatch.Failed}, {"cut.txz", 0, dispatch.Prepared}}) if ev := events[0]; ev.Part.Where != "xz content cut.tar" || !strings.HasPrefix(ev.Reason, "doesn't decompress") { t.Errorf("cut.txz's content: %q, %q", ev.Part.Where, ev.Reason) diff --git a/stages/archive_test.go b/stages/internal/adapter/test/archive_test.go similarity index 86% rename from stages/archive_test.go rename to stages/internal/adapter/test/archive_test.go index 5ab3c4a7..17f5fc9c 100644 --- a/stages/archive_test.go +++ b/stages/internal/adapter/test/archive_test.go @@ -1,4 +1,4 @@ -package stages_test +package adapter_test import ( "archive/tar" @@ -16,6 +16,7 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/sevenzip" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) func capDispatcher(t *testing.T, limit int64) (*dispatch.Dispatcher, string) { @@ -35,7 +36,7 @@ func noFilesAt(t *testing.T, work string) func(*dispatch.Event) { } } -func wantLimited(t *testing.T, ev dispatched, where string, limit int64) { +func wantLimited(t *testing.T, ev stagestest.Dispatched, where string, limit int64) { t.Helper() if ev.Part.Where != where || ev.Outcome != dispatch.Limited || ev.Reason != fmt.Sprintf("past the bytes cap, %d", limit) || ev.Part.SHA256 != "" || ev.Part.Size != 0 || len(ev.Part.Flags) != 0 { @@ -51,7 +52,7 @@ func TestZipBytesCap(t *testing.T) { ) limit := int64(len(z)) + 1<<20 d, work := capDispatcher(t, limit) - events := dispatchAll(t, d, input(t, "big.zip", z), noFilesAt(t, work)) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "big.zip", z), noFilesAt(t, work)) wantSteps(t, events, []step{ {"zeros.bin", 1, dispatch.Limited}, {"notes.txt", 1, dispatch.NoProcessor}, {"big.zip", 0, dispatch.Prepared}, }) @@ -59,7 +60,7 @@ func TestZipBytesCap(t *testing.T) { wantEmpty(t, work) d, work = capDispatcher(t, int64(len(z))+8<<20+64) - events = dispatchAll(t, d, input(t, "big.zip", z), nil) + events = stagestest.DispatchAll(t, d, stagestest.Input(t, "big.zip", z), nil) wantSteps(t, events, []step{ {"zeros.bin", 1, dispatch.NoProcessor}, {"notes.txt", 1, dispatch.NoProcessor}, {"big.zip", 0, dispatch.Prepared}, }) @@ -79,7 +80,7 @@ func TestZipBytesCapSum(t *testing.T) { ) limit := int64(len(z)) + 2*mib + mib/2 d, work := capDispatcher(t, limit) - events := dispatchAll(t, d, input(t, "three.zip", z), noFilesAt(t, work)) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "three.zip", z), noFilesAt(t, work)) wantSteps(t, events, []step{ {"a.bin", 1, dispatch.NoProcessor}, {"b.bin", 1, dispatch.NoProcessor}, @@ -114,7 +115,7 @@ func TestTarBytesCap(t *testing.T) { tr := tarBytes(t, "a.bin", strings.Repeat("a", mib), "b.bin", strings.Repeat("b", mib), "c.bin", "c") limit := int64(len(tr)) + mib + mib/2 d, work := capDispatcher(t, limit) - events := dispatchAll(t, d, input(t, "two.tar", tr), noFilesAt(t, work)) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "two.tar", tr), noFilesAt(t, work)) wantSteps(t, events, []step{ {"a.bin", 1, dispatch.NoProcessor}, {"b.bin", 1, dispatch.Limited}, {"c.bin", 1, dispatch.NoProcessor}, {"two.tar", 0, dispatch.Prepared}, @@ -122,21 +123,21 @@ func TestTarBytesCap(t *testing.T) { wantLimited(t, events[1], "tar entry b.bin", limit) wantEmpty(t, work) - gz := inspectFixture("bomb.tar.gz") + gz := inspectFixture(t, "bomb.tar.gz") info, err := os.Stat(gz) if err != nil { t.Fatal(err) } limit = info.Size() + mib d, work = capDispatcher(t, limit) - events = dispatchAll(t, d, gz, noFilesAt(t, work)) + events = stagestest.DispatchAll(t, d, gz, noFilesAt(t, work)) wantSteps(t, events, []step{{"bomb.tar", 1, dispatch.Limited}, {"bomb.tar.gz", 0, dispatch.Prepared}}) wantLimited(t, events[0], "gzip content bomb.tar", limit) wantEmpty(t, work) limit = info.Size() + 9*mib d, work = capDispatcher(t, limit) - events = dispatchAll(t, d, gz, nil) + events = stagestest.DispatchAll(t, d, gz, nil) wantSteps(t, events, []step{ {"zeros.bin", 2, dispatch.Limited}, {"bomb.tar", 1, dispatch.Prepared}, {"bomb.tar.gz", 0, dispatch.Prepared}, }) @@ -170,7 +171,7 @@ func (e *endless) Extract(ctx context.Context, _ sevenzip.ExtractRequest, w io.W func TestZstdBytesCap(t *testing.T) { const mib = 1 << 20 - stream := input(t, "endless.zst", "\x28\xb5\x2f\xfd and a frame that never ends") + stream := stagestest.Input(t, "endless.zst", "\x28\xb5\x2f\xfd and a frame that never ends") info, err := os.Stat(stream) if err != nil { t.Fatal(err) @@ -178,7 +179,7 @@ func TestZstdBytesCap(t *testing.T) { limit := info.Size() + 4*mib seven := &endless{} d, _, work := archiveDispatcherLimited(t, adapter.ArchiveConfig{SevenZip: seven}, dispatch.Limits{Bytes: limit}) - events := dispatchAll(t, d, stream, noFilesAt(t, work)) + events := stagestest.DispatchAll(t, d, stream, noFilesAt(t, work)) wantSteps(t, events, []step{{"endless", 1, dispatch.Limited}, {"endless.zst", 0, dispatch.Prepared}}) wantLimited(t, events[0], "zstd content endless", limit) if n, room := seven.written.Load(), limit-info.Size(); n > room || n < room-32<<10 { diff --git a/stages/audio_integration_test.go b/stages/internal/adapter/test/audio_integration_test.go similarity index 91% rename from stages/audio_integration_test.go rename to stages/internal/adapter/test/audio_integration_test.go index 0df5678e..bedeb71b 100644 --- a/stages/audio_integration_test.go +++ b/stages/internal/adapter/test/audio_integration_test.go @@ -1,6 +1,6 @@ //go:build linux && integration -package stages_test +package adapter_test import ( "encoding/json" @@ -13,14 +13,14 @@ import ( "github.com/standards-lab/docproc/audio" "github.com/standards-lab/docproc/dispatch" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/metadata" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" "github.com/standards-lab/docproc/tool" ) -var speechFixture = filepath.Join("..", "audio", "testdata", "speech.flac") - var audioRunners = map[string]func(t *testing.T, spec tool.Spec) (*tool.Tool, error){ "exec": func(t *testing.T, spec tool.Spec) (*tool.Tool, error) { return tool.NewExec(t.Context(), spec) }, "container": func(t *testing.T, spec tool.Spec) (*tool.Tool, error) { @@ -51,7 +51,7 @@ func TestAudioStageReal(t *testing.T) { stage := adapter.NewAudioStage(adapter.AudioConfig{ Splitter: s, Version: adapter.Versions(ffmpeg, ffprobe), Request: audio.Request{Concurrency: 2}, }) - path, err := filepath.Abs(speechFixture) + path, err := filepath.Abs(speechFixture(t)) if err != nil { t.Fatal(err) } @@ -64,7 +64,7 @@ func TestAudioStageReal(t *testing.T) { } d := newDispatcher(t, dispatch.Stages{route.Audio: stage}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, path, func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, path, func(ev *dispatch.Event) { if o := ev.Output; o != nil && o.Kind == dispatch.AudioOutput { checkWAV(t, *o) t.Logf("recorded: %s %s, %s, Meta %v", o.Name, o.MediaType, filepath.Base(o.Path), o.Meta) @@ -108,7 +108,7 @@ func TestAudioStageReal(t *testing.T) { if e, c := sums["exec"], sums["container"]; len(sums) == 2 && !slices.Equal(e, c) { t.Errorf("the exec runner prepared windows %q, the container runner %q", e, c) } - if _, err := os.Stat(speechFixture); err != nil { + if _, err := os.Stat(speechFixture(t)); err != nil { t.Errorf("the dispatcher removed the input: %v", err) } } @@ -131,7 +131,7 @@ func TestAudioStageMetadataReal(t *testing.T) { stage := adapter.NewAudioStage(adapter.AudioConfig{ Splitter: s, Version: adapter.Versions(ffmpeg, ffprobe), Request: audio.Request{Concurrency: 2}, }) - path, err := filepath.Abs(taggedMP3) + path, err := filepath.Abs(taggedMP3(t)) if err != nil { t.Fatal(err) } @@ -145,3 +145,5 @@ func TestAudioStageMetadataReal(t *testing.T) { }) } } + +func speechFixture(t testing.TB) string { return tooltest.Testdata(t, "audio", "speech.flac") } diff --git a/stages/audio_test.go b/stages/internal/adapter/test/audio_test.go similarity index 82% rename from stages/audio_test.go rename to stages/internal/adapter/test/audio_test.go index 37e98690..6aed86d5 100644 --- a/stages/audio_test.go +++ b/stages/internal/adapter/test/audio_test.go @@ -1,6 +1,6 @@ //go:build linux -package stages_test +package adapter_test import ( "bytes" @@ -9,7 +9,6 @@ import ( "encoding/hex" "encoding/json" "errors" - "fmt" "maps" "os" "path/filepath" @@ -22,29 +21,19 @@ import ( "github.com/standards-lab/docproc/audio" "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/inspect" - "github.com/standards-lab/docproc/internal/mediatest" "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" "github.com/standards-lab/docproc/tool" ) -type ffSettings struct { - Probe string `json:"probe"` - Decode string `json:"decode,omitzero"` - DecodeMS int `json:"decode_ms,omitzero"` - PCMMS int `json:"pcm_ms,omitzero"` - Frames []mediatest.Frame `json:"frames,omitzero"` - Fail string `json:"fail,omitzero"` - HoldMS int `json:"hold_ms,omitzero"` -} - type ffStandins struct { ffmpeg, ffprobe string - settings ffSettings + settings stagestest.FFSettings } -func (s *ffStandins) set(t *testing.T, change func(*ffSettings)) { +func (s *ffStandins) set(t *testing.T, change func(*stagestest.FFSettings)) { t.Helper() change(&s.settings) tooltest.Set(t, s.ffmpeg, s.settings) @@ -72,71 +61,12 @@ const ( audioNoStream = `{"streams":[{"index":0,"codec_name":"h264","codec_type":"video"}],"format":{"duration":"3.000000"}}` ) -var gainWAV = filepath.Join("..", "audio", "testdata", "speech-gain.wav") - const ( flacBytes = "fLaC\x00\x00\x00\x22" + "stand-in FLAC" m4aBytes = "\x00\x00\x00\x14ftypM4A \x00\x00\x00\x00M4A \x00\x00\x00\x08moov" mp4Bytes = "\x00\x00\x00\x14ftypisom\x00\x00\x02\x00isom\x00\x00\x00\x08moov" ) -func ffprobeStandin(r tooltest.Run) int { - if printFFVersion(r) { - return 0 - } - var settings ffSettings - if err := r.Settings(&settings); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - fmt.Print(settings.Probe) - return 0 -} - -func printFFVersion(r tooltest.Run) bool { - if !slices.Equal(r.Args, []string{"-version"}) { - return false - } - fmt.Printf("%s version n9.0.2 Copyright (c) 2000-2026 the FFmpeg developers\n", r.Program) - return true -} - -func ffmpegStandin(r tooltest.Run) int { - if printFFVersion(r) { - return 0 - } - var settings ffSettings - if err := r.Settings(&settings); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - args := r.Args - if slices.Contains(args, "-protocol_whitelist") { - return mediaStandin(args, settings) - } - if filter := args[slices.Index(args, "-af")+1]; filter != "aresample=16000" { - fmt.Fprintf(os.Stderr, "stand-in: filter %q\n", filter) - return 2 - } - data, err := os.ReadFile(settings.Decode) - if err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - pcm := data[44:] - if settings.DecodeMS > 0 { - pcm = pcm[:2*settings.DecodeMS*audio.SampleRate/1000] - } - if _, err := os.Stdout.Write(pcm); err != nil { - return 2 - } - if settings.DecodeMS > 0 { - fmt.Fprintln(os.Stderr, settings.Fail) - return 1 - } - return 0 -} - func standinSplitter(t *testing.T, probe string) (*audio.Splitter, *ffStandins) { t.Helper() ffmpeg, ffprobe, standins := standinTools(t, probe) @@ -150,11 +80,11 @@ func standinSplitter(t *testing.T, probe string) (*audio.Splitter, *ffStandins) func standinTools(t *testing.T, probe string) (ffmpeg, ffprobe *tool.Tool, standins *ffStandins) { t.Helper() dir := t.TempDir() - decode, err := filepath.Abs(gainWAV) + decode, err := filepath.Abs(gainWAV(t)) if err != nil { t.Fatal(err) } - standins = &ffStandins{settings: ffSettings{Probe: probe, Decode: decode}} + standins = &ffStandins{settings: stagestest.FFSettings{Probe: probe, Decode: decode}} standins.ffmpeg = tooltest.Link(t, dir, "ffmpeg", standins.settings) standins.ffprobe = tooltest.Link(t, dir, "ffprobe", standins.settings) var tools []*tool.Tool @@ -218,7 +148,7 @@ func checkWAV(t *testing.T, o dispatch.Output) []byte { func checkGainWAV(t *testing.T, o dispatch.Output) { t.Helper() b := checkWAV(t, o) - data, err := os.ReadFile(gainWAV) + data, err := os.ReadFile(gainWAV(t)) if err != nil { t.Fatal(err) } @@ -233,7 +163,7 @@ func TestAudioStage(t *testing.T) { t.Parallel() stage, standins := testAudioStage(t, audioProbe) d := newDispatcher(t, dispatch.Stages{route.Audio: stage}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, writeInput(t, "speech.flac", flacBytes), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, writeInput(t, "speech.flac", flacBytes), func(ev *dispatch.Event) { if o := ev.Output; o != nil && o.Kind == dispatch.AudioOutput { checkGainWAV(t, *o) } @@ -301,7 +231,7 @@ func TestAudioStageInArchive(t *testing.T) { stages := dispatch.Stages{route.Audio: stage, route.Archive: zs} d := newDispatcher(t, stages, dispatch.NewMemoryIndex(0)) path := writeInput(t, "recordings.zip", zipBytes(t, zent{name: "talks/speech.flac", body: flacBytes})) - events := dispatchAll(t, d, path, nil) + events := stagestest.DispatchAll(t, d, path, nil) wantSteps(t, events, []step{{"talks/speech.flac", 1, dispatch.Prepared}, {"recordings.zip", 0, dispatch.Prepared}}) if n := len(events[0].Outputs); n != 5 { t.Errorf("the FLAC's %d outputs, want its metadata record, three windows, and its plan", n) @@ -311,7 +241,7 @@ func TestAudioStageInArchive(t *testing.T) { func TestAudioNoProcessor(t *testing.T) { t.Parallel() d := newDispatcher(t, dispatch.Stages{}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, writeInput(t, "speech.flac", flacBytes), nil) + events := stagestest.DispatchAll(t, d, writeInput(t, "speech.flac", flacBytes), nil) wantSteps(t, events, []step{{"speech.flac", 0, dispatch.NoProcessor}}) if ev := events[0]; ev.Reason != "no stage for route audio" || len(ev.Outputs) != 0 { t.Errorf("reason %q, %d outputs", ev.Reason, len(ev.Outputs)) @@ -319,7 +249,7 @@ func TestAudioNoProcessor(t *testing.T) { stage, standins := testAudioStage(t, audioProbe) d = newDispatcher(t, dispatch.Stages{route.Audio: stage}, dispatch.NewMemoryIndex(0)) - events = dispatchAll(t, d, writeInput(t, "clip.mp4", mp4Bytes), nil) + events = stagestest.DispatchAll(t, d, writeInput(t, "clip.mp4", mp4Bytes), nil) wantSteps(t, events, []step{{"clip.mp4", 0, dispatch.NoProcessor}}) if ev := events[0]; ev.Part.ContentType.Route != route.Video || ev.Reason != "no stage for route video" { t.Errorf("route %s, reason %q", ev.Part.ContentType.Route, ev.Reason) @@ -338,7 +268,7 @@ func TestAudioNoStream(t *testing.T) { index := dispatch.NewMemoryIndex(0) stage, standins := testAudioStage(t, audioNoStream) d := newDispatcher(t, dispatch.Stages{route.Audio: stage}, index) - events := dispatchAll(t, d, writeInput(t, "silent.m4a", m4aBytes), nil) + events := stagestest.DispatchAll(t, d, writeInput(t, "silent.m4a", m4aBytes), nil) wantSteps(t, events, []step{{"silent.m4a", 0, dispatch.Failed}}) ev := events[0] if ev.Part.ContentType.Route != route.Audio || !errors.Is(ev.Err, audio.ErrNoAudio) || !errors.Is(ev.Err, dispatch.ErrRefused) || len(ev.Outputs) != 0 { @@ -355,11 +285,11 @@ func TestAudioNoStream(t *testing.T) { func TestAudioFailedDecode(t *testing.T) { t.Parallel() stage, standins := testAudioStage(t, audioProbe) - standins.set(t, func(s *ffSettings) { + standins.set(t, func(s *stagestest.FFSettings) { s.DecodeMS, s.Fail = 40000, "[aist#0:1/flac] Error while decoding: Cannot allocate memory" }) d := newDispatcher(t, dispatch.Stages{route.Audio: stage}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, writeInput(t, "speech.flac", flacBytes), nil) + events := stagestest.DispatchAll(t, d, writeInput(t, "speech.flac", flacBytes), nil) wantSteps(t, events, []step{{"speech.flac", 0, dispatch.Prepared}}) ev := events[0] var got []string @@ -410,3 +340,5 @@ func TestAudioStageIdentity(t *testing.T) { } } } + +func gainWAV(t testing.TB) string { return tooltest.Testdata(t, "audio", "speech-gain.wav") } diff --git a/stages/bzip2_test.go b/stages/internal/adapter/test/bzip2_test.go similarity index 84% rename from stages/bzip2_test.go rename to stages/internal/adapter/test/bzip2_test.go index 787c4fb0..faae6b2d 100644 --- a/stages/bzip2_test.go +++ b/stages/internal/adapter/test/bzip2_test.go @@ -1,4 +1,4 @@ -package stages_test +package adapter_test import ( "errors" @@ -10,11 +10,12 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/inspect" "github.com/standards-lab/docproc/route" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) func bzip2Fixture(t *testing.T, name string) []byte { t.Helper() - b, err := os.ReadFile(sevenZipFixture("generated/" + name)) + b, err := os.ReadFile(sevenZipFixture(t, "generated/"+name)) if err != nil { t.Fatal(err) } @@ -23,7 +24,7 @@ func bzip2Fixture(t *testing.T, name string) []byte { func TestBzip2Stage(t *testing.T) { d, zs, work := archiveDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, sevenZipFixture("generated/notes.txt.bz2"), nil) + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/notes.txt.bz2"), nil) wantSteps(t, events, []step{{"notes.txt", 1, dispatch.NoProcessor}, {"notes.txt.bz2", 0, dispatch.Prepared}}) if content, bz := events[0], events[1]; content.Part.Where != "bzip2 content notes.txt" || content.Part.Size != 18 || content.Part.ContentType.Route != route.Text || bz.Part.ContentType.Kind != route.Bzip2 || bz.Children != 1 || len(bz.Outputs) != 0 { @@ -36,7 +37,7 @@ func TestBzip2Stage(t *testing.T) { wantEmpty(t, work) d, _, work = archiveDispatcher(t, inspect.Options{}) - events = dispatchAll(t, d, sevenZipFixture("generated/concatenated.txt.bz2"), nil) + events = stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/concatenated.txt.bz2"), nil) wantSteps(t, events, []step{{"concatenated.txt", 1, dispatch.NoProcessor}, {"concatenated.txt.bz2", 0, dispatch.Prepared}}) if ev := events[0]; ev.Part.Size != 59 { t.Errorf("concatenated.txt: %d bytes, want both streams' 59", ev.Part.Size) @@ -46,7 +47,7 @@ func TestBzip2Stage(t *testing.T) { func TestBzip2Tar(t *testing.T) { d, zs, work := archiveDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, sevenZipFixture("generated/clean.tbz2"), nil) + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/clean.tbz2"), nil) wantSteps(t, events, []step{ {"docs/notes.txt", 2, dispatch.NoProcessor}, {"docs/pixel.png", 2, dispatch.Prepared}, @@ -73,7 +74,7 @@ func TestBzip2Stem(t *testing.T) { "bundle.TBZ2": "bundle.tar", "bundle.tbz": "bundle.tar", "notes": "notes", ".bz2": ".bz2", } { d, _, work := archiveDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, input(t, name, notes), nil) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, name, notes), nil) if len(events) != 2 || events[0].Part.Name != want || events[0].Part.Where != "bzip2 content "+want { t.Errorf("%s: %v, want its content named %q", name, steps(events), want) } @@ -83,7 +84,7 @@ func TestBzip2Stem(t *testing.T) { func TestBzip2BombAsWritten(t *testing.T) { d, _, work := archiveDispatcher(t, inspect.Options{BombSize: 1 << 20, BombRatio: 100}) - events := dispatchAll(t, d, sevenZipFixture("generated/bomb.bz2"), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/bomb.bz2"), func(ev *dispatch.Event) { if left := files(t, work); len(left) > 0 { t.Errorf("files at the stream's event: %q, want the partial file removed", left) } @@ -93,7 +94,7 @@ func TestBzip2BombAsWritten(t *testing.T) { wantEmpty(t, work) d, _, work = archiveDispatcher(t, inspect.Options{}) - events = dispatchAll(t, d, sevenZipFixture("generated/bomb.bz2"), nil) + events = stagestest.DispatchAll(t, d, sevenZipFixture(t, "generated/bomb.bz2"), nil) wantSteps(t, events, []step{{"bomb", 1, dispatch.NoProcessor}, {"bomb.bz2", 0, dispatch.Prepared}}) if events[0].Part.Size != 8<<20 { t.Errorf("bomb: %d bytes, want %d", events[0].Part.Size, 8<<20) @@ -107,7 +108,7 @@ func TestBzip2Damaged(t *testing.T) { flipped[len(flipped)/2] ^= 0xff for name, body := range map[string][]byte{"cut.tbz2": tbz[:len(tbz)-20], "flipped.tbz2": flipped} { d, _, work := archiveDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, input(t, name, string(body)), nil) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, name, string(body)), nil) stem := strings.TrimSuffix(name, ".tbz2") + ".tar" wantSteps(t, events, []step{{stem, 1, dispatch.Failed}, {name, 0, dispatch.Prepared}}) if ev := events[0]; ev.Part.Where != "bzip2 content "+stem || !strings.HasPrefix(ev.Reason, "doesn't decompress") || diff --git a/stages/internal/adapter/test/classify_test.go b/stages/internal/adapter/test/classify_test.go new file mode 100644 index 00000000..4b6870f0 --- /dev/null +++ b/stages/internal/adapter/test/classify_test.go @@ -0,0 +1,66 @@ +//go:build linux + +package adapter_test + +import ( + "context" + "encoding/json/jsontext" + "errors" + "fmt" + "os" + "testing" + + "github.com/standards-lab/docproc/audio" + "github.com/standards-lab/docproc/dispatch" + "github.com/standards-lab/docproc/sevenzip" + "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/tool" +) + +func TestClassify(t *testing.T) { + t.Parallel() + ended, cancel := context.WithCancel(t.Context()) + cancel() + exit := func(program string, code int) error { return &tool.ExitError{Program: program, Code: code} } + for _, c := range []struct { + name string + ctx context.Context + err error + memory int64 + content bool + reason string + }{ + {"the context ended", ended, exit("gs", 1), 0, false, ""}, + {"a canceled run", t.Context(), fmt.Errorf("tool: gs: %w", context.Canceled), 0, false, ""}, + {"a failed start", t.Context(), &os.PathError{Op: "fork/exec", Path: "/gone", Err: os.ErrNotExist}, 0, false, ""}, + {"timed out after exit 1", t.Context(), &tool.ExitError{Program: "docproc-mail", Code: 1, TimedOut: true}, 0, true, ""}, + {"gs's exit 1", t.Context(), exit("gs", 1), 0, true, ""}, + {"qpdf's exit 2", t.Context(), exit("qpdf", 2), 0, true, ""}, + {"7zz's command line error", t.Context(), exit("7zz", 7), 0, false, ""}, + {"7zz's out of memory", t.Context(), exit("7zz", 8), 0, true, ""}, + {"soffice's fatal error at its start", t.Context(), exit("soffice", 77), 0, false, ""}, + {"soffice's exit 1", t.Context(), exit("soffice", 1), 0, true, ""}, + {"docproc-ooxml's usage", t.Context(), exit("docproc-ooxml", 2), 0, false, ""}, + {"a signal under 512 MiB", t.Context(), &tool.ExitError{Program: "docproc-ooxml", Code: -1, Signal: "SIGABRT", Message: "libssl"}, 512 << 20, + true, "docproc-ooxml: killed by SIGABRT under a 512 MiB memory bound: libssl"}, + {"a signal under an odd bound", t.Context(), &tool.ExitError{Program: "gs", Code: -1, Signal: "SIGSEGV"}, 1000, true, "gs: killed by SIGSEGV under a 1000 bytes memory bound"}, + {"SIGPIPE", t.Context(), &tool.ExitError{Program: "gs", Code: -1, Signal: "SIGPIPE"}, 0, false, ""}, + {"JSON that doesn't parse", t.Context(), fmt.Errorf("document: %w", &jsontext.SyntacticError{}), 0, true, ""}, + {"no audio", t.Context(), fmt.Errorf("audio: %w", audio.ErrNoAudio), 0, true, ""}, + {"not an archive", t.Context(), fmt.Errorf("sevenzip: %w", sevenzip.ErrNotArchive), 0, true, ""}, + {"docproc's side of the pipe", t.Context(), errors.New("write |1: broken pipe"), 0, false, ""}, + } { + content, reason := adapter.Classify(c.ctx, c.err, c.memory) + if content != c.content || c.reason != "" && reason != c.reason { + t.Errorf("%s: content %t, %q; want %t, %q", c.name, content, reason, c.content, c.reason) + } + } + if err := adapter.PartErr(t.Context(), exit("gs", 1), 0); !errors.Is(err, dispatch.ErrRefused) { + t.Errorf("partErr of the content's: %v, want ErrRefused", err) + } + for _, named := range []error{dispatch.ErrEncrypted, dispatch.ErrReadElsewhere, dispatch.ErrNoProcessor} { + if err := adapter.PartErr(t.Context(), named, 0); err != named { + t.Errorf("partErr(%v) = %v, want it as it is", named, err) + } + } +} diff --git a/stages/document_integration_test.go b/stages/internal/adapter/test/document_integration_test.go similarity index 90% rename from stages/document_integration_test.go rename to stages/internal/adapter/test/document_integration_test.go index 18e4ce35..cf735f5f 100644 --- a/stages/document_integration_test.go +++ b/stages/internal/adapter/test/document_integration_test.go @@ -1,6 +1,6 @@ //go:build linux && integration -package stages_test +package adapter_test import ( "bytes" @@ -19,16 +19,18 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/document" "github.com/standards-lab/docproc/inspect" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) func documentFixture(t *testing.T, name string) string { t.Helper() - b, err := os.ReadFile(filepath.Join("..", "document", "testdata", filepath.FromSlash(name))) + b, err := os.ReadFile(tooltest.Testdata(t, "document", filepath.FromSlash(name))) if err != nil { t.Fatal(err) } - return input(t, path.Base(name), string(b)) + return stagestest.Input(t, path.Base(name), string(b)) } func encryptedPDF(t *testing.T, name string, args ...string) string { @@ -41,7 +43,7 @@ func encryptedPDF(t *testing.T, name string, args ...string) string { return out } -func outputNames(ev dispatched) []string { +func outputNames(ev stagestest.Dispatched) []string { var names []string for _, o := range ev.Outputs { names = append(names, string(o.Kind)+" "+o.Name) @@ -62,7 +64,7 @@ func TestDocumentStageEncryptedReal(t *testing.T) { {documentFixture(t, "clean.pdf"), dispatch.Prepared, false}, } { name := filepath.Base(c.pdf) - ev := dispatchAll(t, d, c.pdf, nil)[0] + ev := stagestest.DispatchAll(t, d, c.pdf, nil)[0] flagged := slices.ContainsFunc(ev.Part.Flags, func(f inspect.Flag) bool { return f.Check == inspect.PDFEncrypt }) if ev.Outcome != c.outcome || flagged != c.flagged { t.Errorf("%s: %s, %q, /Encrypt %t; want %s, %t", name, ev.Outcome, ev.Reason, flagged, c.outcome, c.flagged) @@ -87,11 +89,11 @@ func TestDocumentStageMetadataReal(t *testing.T) { t.Fatal(err) } for _, name := range []string{"info", "clean"} { - fixture := filepath.Join("..", "document", "testdata", name+".pdf") - if name == "info" { - fixture = filepath.Join("..", "document", "testdata", "info", "info.pdf") + fixture := tooltest.Testdata(t, "document", "info", "info.pdf") + if name != "info" { + fixture = tooltest.Testdata(t, "document", name+".pdf") } - ev := dispatchAll(t, d, fixture, nil)[0] + ev := stagestest.DispatchAll(t, d, fixture, nil)[0] if ev.Outcome != dispatch.Prepared || len(ev.Warnings) != 0 { t.Errorf("%s: %s, warnings %+v", name, ev.Outcome, ev.Warnings) } @@ -122,7 +124,7 @@ func TestDocumentStageFormsReal(t *testing.T) { `{"name":"languages","type":"choice","options":["English","French","German"],"selected":["en","de"]}]}`, "forms/signed.pdf": `{"fields":[{"name":"USGPOSignature","type":"signature","signed":true}]}`, } { - ev := dispatchAll(t, d, documentFixture(t, name), nil)[0] + ev := stagestest.DispatchAll(t, d, documentFixture(t, name), nil)[0] if got := outputNames(ev); ev.Outcome != dispatch.Prepared || len(got) == 0 || got[0] != "record forms" || !slices.Contains(got, "image page 1") { t.Errorf("%s: %s, %q, %q; want the forms record first and page 1's image", name, ev.Outcome, ev.Reason, got) continue @@ -134,7 +136,7 @@ func TestDocumentStageFormsReal(t *testing.T) { t.Logf("%s: %s", name, rec.Value) } - ev := dispatchAll(t, d, documentFixture(t, "clean.pdf"), nil)[0] + ev := stagestest.DispatchAll(t, d, documentFixture(t, "clean.pdf"), nil)[0] if slices.Contains(outputNames(ev), "record forms") { t.Error("clean.pdf, with no AcroForm, has a forms record") } @@ -142,7 +144,7 @@ func TestDocumentStageFormsReal(t *testing.T) { func TestDocumentStageAttachmentsReal(t *testing.T) { d, work := newDispatcherIn(t, allStages(t)) - events := dispatchAll(t, d, documentFixture(t, "attachments/attachments.pdf"), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, documentFixture(t, "attachments/attachments.pdf"), func(ev *dispatch.Event) { if ev.Output == nil && ev.Part.Depth == 1 && filepath.Base(ev.Part.Path) != ev.Part.SHA256 { t.Errorf("%s at %s: want it named by its SHA-256", ev.Part.Name, ev.Part.Path) } @@ -223,17 +225,17 @@ func TestDocumentStageAttachmentBombReal(t *testing.T) { t.Fatal(err) } prep := document.NewPreparer(document.Config{Renderer: render, Text: text}) - pdf := input(t, "zeros.pdf", string(attachedPDF(t, "zeros.bin", make([]byte, 8<<20)))) + pdf := stagestest.Input(t, "zeros.pdf", string(attachedPDF(t, "zeros.bin", make([]byte, 8<<20)))) d, work := newDispatcherIn(t, dispatch.Stages{route.Document: pdfStage(t, prep, gs, inspect.Options{})}) - events := dispatchAll(t, d, pdf, nil) + events := stagestest.DispatchAll(t, d, pdf, nil) if len(events) != 2 || events[0].Part.Name != "zeros.bin" || events[0].Part.Size != 8<<20 || events[0].Part.Where != "attachment zeros.bin" { t.Errorf("no bomb rule: %v", steps(events)) } wantEmpty(t, work) d, work = newDispatcherIn(t, dispatch.Stages{route.Document: pdfStage(t, prep, gs, inspect.Options{BombSize: 1 << 20, BombRatio: 100})}) - events = dispatchAll(t, d, pdf, nil) + events = stagestest.DispatchAll(t, d, pdf, nil) wantSteps(t, events, []step{{"zeros.bin", 1, dispatch.Quarantined}, {"zeros.pdf", 0, dispatch.Prepared}}) wantBomb(t, events[0], "attachment zeros.bin", "bytes written from") evidence := events[0].Part.Flags[0].Evidence diff --git a/stages/document_test.go b/stages/internal/adapter/test/document_test.go similarity index 87% rename from stages/document_test.go rename to stages/internal/adapter/test/document_test.go index d60b864c..1f785b7c 100644 --- a/stages/document_test.go +++ b/stages/internal/adapter/test/document_test.go @@ -1,6 +1,6 @@ //go:build linux -package stages_test +package adapter_test import ( "bytes" @@ -29,6 +29,7 @@ import ( "github.com/standards-lab/docproc/metadata" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" "github.com/standards-lab/docproc/tool" ) @@ -92,16 +93,16 @@ func qpdfFailed(message string) error { func formsDocumentStage(t *testing.T, q adapter.QPDFReader, d adapter.PDFDetacher, opts inspect.Options) *adapter.DocumentStage { t.Helper() return adapter.NewDocumentStage(adapter.DocumentConfig{ - Preparer: standinPreparer(t, gsSettings{Pages: 3}), QPDF: q, PDFDetach: d, PDFInfo: &fakeInfo{}, Version: "gs 10.08.0", + Preparer: standinPreparer(t, stagestest.GSSettings{Pages: 3}), QPDF: q, PDFDetach: d, PDFInfo: &fakeInfo{}, Version: "gs 10.08.0", Request: document.ImagesRequest{Text: true, Concurrency: 1}, Inspect: opts, }) } -func documentOrder(t *testing.T, s *adapter.DocumentStage, pdf string) ([]dispatched, []string) { +func documentOrder(t *testing.T, s *adapter.DocumentStage, pdf string) ([]stagestest.Dispatched, []string) { t.Helper() d := newDispatcher(t, dispatch.Stages{route.Document: s}, dispatch.NewMemoryIndex(0)) var order []string - events := dispatchAll(t, d, pdf, func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, pdf, func(ev *dispatch.Event) { switch { case ev.Warning != nil: order = append(order, "warning "+ev.Warning.Tool+" "+ev.Warning.Where) @@ -117,7 +118,7 @@ func documentOrder(t *testing.T, s *adapter.DocumentStage, pdf string) ([]dispat var pagesOrder = []string{"text page 1", "image page 1", "text page 2", "image page 2", "text page 3", "image page 3"} func TestDocumentStagePassword(t *testing.T) { - pdf := input(t, "locked.pdf", "%PDF-1.7\n%%EOF\n") + pdf := stagestest.Input(t, "locked.pdf", "%PDF-1.7\n%%EOF\n") q := &fakeQPDF{locked: true} events, _ := documentOrder(t, formsDocumentStage(t, q, &fakeDetach{files: []string{"a.txt", "a"}}, inspect.Options{}), pdf) wantSteps(t, events, []step{{"locked.pdf", 0, dispatch.Encrypted}}) @@ -134,7 +135,7 @@ func TestDocumentStagePassword(t *testing.T) { t.Errorf("%d forms read of a PDF that needs a password", n) } - _, order := documentOrder(t, formsDocumentStage(t, &fakeQPDF{}, &fakeDetach{}, inspect.Options{}), input(t, "permissions.pdf", "%PDF-1.7\n%%EOF\n")) + _, order := documentOrder(t, formsDocumentStage(t, &fakeQPDF{}, &fakeDetach{}, inspect.Options{}), stagestest.Input(t, "permissions.pdf", "%PDF-1.7\n%%EOF\n")) if !slices.Equal(order, pagesOrder) { t.Errorf("permissions only:\n got %q\nwant %q", order, pagesOrder) } @@ -149,7 +150,7 @@ func TestDocumentStageForms(t *testing.T) { Options: []string{"Red", "Green"}, Selected: []string{"Green"}, }, }} - pdf := input(t, "form.pdf", "%PDF-1.7\n%%EOF\n") + pdf := stagestest.Input(t, "form.pdf", "%PDF-1.7\n%%EOF\n") events, order := documentOrder(t, formsDocumentStage(t, &fakeQPDF{form: form}, &fakeDetach{}, inspect.Options{}), pdf) wantSteps(t, events, []step{{"form.pdf", 0, dispatch.Prepared}}) if want := append([]string{"record forms"}, pagesOrder...); !slices.Equal(order, want) { @@ -204,13 +205,13 @@ func TestDocumentStageAttachments(t *testing.T) { work := t.TempDir() d, err := dispatch.New(dispatch.Config{ Content: dispatch.NewMemoryContent(), Puts: 2, - Stages: dispatch.Stages{route.Document: s, route.Vision: standinVisionStage(t, pictureSettings{})}, Index: dispatch.NewMemoryIndex(0), Dir: work, + Stages: dispatch.Stages{route.Document: s, route.Vision: standinVisionStage(t, stagestest.PictureSettings{})}, Index: dispatch.NewMemoryIndex(0), Dir: work, }) if err != nil { t.Fatal(err) } var order []string - events := dispatchAll(t, d, input(t, "attached.pdf", "%PDF-1.7\n%%EOF\n"), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "attached.pdf", "%PDF-1.7\n%%EOF\n"), func(ev *dispatch.Event) { switch { case ev.Output != nil && ev.Part.Depth == 0: order = append(order, string(ev.Output.Kind)+" "+ev.Output.Name) @@ -245,7 +246,7 @@ func TestDocumentStageAttachments(t *testing.T) { wantEmpty(t, work) detach.listErr = &tool.ExitError{Program: "pdfdetach", Code: 1, Message: "told to fail the listing"} - events, order = documentOrder(t, formsDocumentStage(t, &fakeQPDF{}, detach, inspect.Options{}), input(t, "unlisted.pdf", "%PDF-1.7\n%%EOF\n")) + events, order = documentOrder(t, formsDocumentStage(t, &fakeQPDF{}, detach, inspect.Options{}), stagestest.Input(t, "unlisted.pdf", "%PDF-1.7\n%%EOF\n")) if want := append([]string{"warning pdfdetach attachments"}, pagesOrder...); events[0].Outcome != dispatch.Prepared || !slices.Equal(order, want) { t.Errorf("a failed listing: %s, %q, %q", events[0].Outcome, events[0].Reason, order) } @@ -268,7 +269,7 @@ func TestDocumentStageAttachmentBomb(t *testing.T) { if err != nil { t.Fatal(err) } - events := dispatchAll(t, d, input(t, "bomb.pdf", "%PDF-1.7\n%%EOF\n"), nil) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "bomb.pdf", "%PDF-1.7\n%%EOF\n"), nil) wantSteps(t, events, []step{{"zeros.bin", 1, dispatch.Quarantined}, {"bomb.pdf", 0, dispatch.Prepared}}) child := events[0] if len(child.Part.Flags) != 1 || child.Part.Flags[0].Check != inspect.ArchiveBomb || child.Part.Flags[0].Class != inspect.Unsafe || @@ -296,7 +297,7 @@ func TestDocumentStageAttachmentBytesCap(t *testing.T) { if err != nil { t.Fatal(err) } - events := dispatchAll(t, d, input(t, "two.pdf", pdf), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "two.pdf", pdf), func(ev *dispatch.Event) { if ev.Part.Name != "b.bin" { return } @@ -313,7 +314,7 @@ func TestDocumentStageAttachmentBytesCap(t *testing.T) { } func TestDocumentIdentity(t *testing.T) { - prep := standinPreparer(t, gsSettings{Pages: 1}) + prep := standinPreparer(t, stagestest.GSSettings{Pages: 1}) id := func(req document.ImagesRequest, opts inspect.Options) dispatch.Identity { t.Helper() return adapter.NewDocumentStage(adapter.DocumentConfig{ @@ -339,43 +340,7 @@ func TestDocumentIdentity(t *testing.T) { } } -type pdfinfoSettings struct { - Info map[string]string `json:"info,omitzero"` - Exit int `json:"exit,omitzero"` - Stderr string `json:"stderr,omitzero"` -} - -func pdfinfoStandin(r tooltest.Run) int { - var settings pdfinfoSettings - if err := r.Settings(&settings); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - if len(r.Args) == 1 && r.Args[0] == "-v" { - fmt.Fprintln(os.Stderr, "pdfinfo version 26.10.0") - return 0 - } - if settings.Exit != 0 { - fmt.Fprint(os.Stderr, settings.Stderr) - return settings.Exit - } - mode := "summary" - switch { - case slices.Contains(r.Args, "-custom"): - mode = "custom" - case slices.Contains(r.Args, "-meta"): - mode = "meta" - } - if _, err := os.Stdout.WriteString(settings.Info[mode]); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - return 0 -} - -var pdfinfoGoldens = filepath.Join("..", "document", "testdata", "info") - -func standinInfo(t *testing.T, s pdfinfoSettings) *document.InfoReader { +func standinInfo(t *testing.T, s stagestest.PDFInfoSettings) *document.InfoReader { t.Helper() spec := document.PDFInfoSpec() spec.Program = tooltest.Link(t, t.TempDir(), "pdfinfo", s) @@ -390,11 +355,11 @@ func standinInfo(t *testing.T, s pdfinfoSettings) *document.InfoReader { return r } -func goldenInfo(t *testing.T, name string) pdfinfoSettings { +func goldenInfo(t *testing.T, name string) stagestest.PDFInfoSettings { t.Helper() - s := pdfinfoSettings{Info: map[string]string{}} + s := stagestest.PDFInfoSettings{Info: map[string]string{}} for mode, ext := range map[string]string{"custom": "custom.txt", "meta": "meta.xml", "summary": "summary.txt"} { - b, err := os.ReadFile(filepath.Join(pdfinfoGoldens, name+"."+ext)) + b, err := os.ReadFile(filepath.Join(pdfinfoGoldens(t), name+"."+ext)) if err != nil { t.Fatal(err) } @@ -406,7 +371,7 @@ func goldenInfo(t *testing.T, name string) pdfinfoSettings { func metadataStage(t *testing.T, q adapter.QPDFReader, info adapter.PDFInfoReader) *adapter.DocumentStage { t.Helper() return adapter.NewDocumentStage(adapter.DocumentConfig{ - Preparer: standinPreparer(t, gsSettings{Pages: 3}), QPDF: q, PDFDetach: &fakeDetach{}, PDFInfo: info, + Preparer: standinPreparer(t, stagestest.GSSettings{Pages: 3}), QPDF: q, PDFDetach: &fakeDetach{}, PDFInfo: info, Version: "gs 10.08.0", Request: document.ImagesRequest{Text: true, Concurrency: 1}, }) } @@ -462,7 +427,7 @@ func TestDocumentStageMetadata(t *testing.T) { want func(packet string) metadata.PDF }{ { - filepath.Join("..", "document", "testdata", "info", "info.pdf"), "info", + tooltest.Testdata(t, "document", "info", "info.pdf"), "info", func(packet string) metadata.PDF { return metadata.PDF{ Version: "1.6", @@ -484,7 +449,7 @@ func TestDocumentStageMetadata(t *testing.T) { }, }, { - filepath.Join("..", "document", "testdata", "clean.pdf"), "clean", + tooltest.Testdata(t, "document", "clean.pdf"), "clean", func(packet string) metadata.PDF { return metadata.PDF{ Version: "1.7", @@ -509,7 +474,7 @@ func TestDocumentStageMetadata(t *testing.T) { t.Fatal(err) } var order []string - events := dispatchAll(t, d, c.fixture, func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, c.fixture, func(ev *dispatch.Event) { if ev.Output != nil { order = append(order, string(ev.Output.Kind)+" "+ev.Output.Name) } @@ -535,7 +500,7 @@ func TestDocumentStageMetadata(t *testing.T) { func TestDocumentStageMetadataUnread(t *testing.T) { t.Parallel() - pdf := input(t, "x.pdf", "%PDF-1.7\n%%EOF\n") + pdf := stagestest.Input(t, "x.pdf", "%PDF-1.7\n%%EOF\n") info := &fakeInfo{} events, order := documentOrder(t, metadataStage(t, &fakeQPDF{locked: true}, info), pdf) @@ -548,7 +513,7 @@ func TestDocumentStageMetadataUnread(t *testing.T) { t.Errorf("a PDF that needs a password: flags %+v, %v, %d reads", events[0].Part.Flags, events[0].Err, info.reads.Load()) } - failing := standinInfo(t, pdfinfoSettings{Exit: 1, Stderr: "Syntax Error: Couldn't find trailer dictionary\n"}) + failing := standinInfo(t, stagestest.PDFInfoSettings{Exit: 1, Stderr: "Syntax Error: Couldn't find trailer dictionary\n"}) events, order = documentOrder(t, metadataStage(t, &fakeQPDF{}, failing), pdf) wantSteps(t, events, []step{{"x.pdf", 0, dispatch.Prepared}}) if want := append([]string{"warning pdfinfo metadata"}, pagesOrder...); !slices.Equal(order, want) { @@ -558,7 +523,7 @@ func TestDocumentStageMetadataUnread(t *testing.T) { t.Errorf("pdfinfo failing: warnings %+v", w) } - unparsed := standinInfo(t, pdfinfoSettings{Info: map[string]string{"custom": "Title: T\n", "meta": ""}}) + unparsed := standinInfo(t, stagestest.PDFInfoSettings{Info: map[string]string{"custom": "Title: T\n", "meta": ""}}) events, order = documentOrder(t, metadataStage(t, &fakeQPDF{}, unparsed), pdf) if want := append([]string{"record metadata", "warning pdfinfo metadata"}, pagesOrder...); !slices.Equal(order, want) || events[0].Outcome != dispatch.Prepared { t.Errorf("an XMP packet that doesn't parse: %s,\n got %q\nwant %q", events[0].Outcome, order, want) @@ -568,8 +533,10 @@ func TestDocumentStageMetadataUnread(t *testing.T) { t.Errorf("an XMP packet that doesn't parse: record %+v, %v", rec, err) } - _, order = documentOrder(t, metadataStage(t, &fakeQPDF{}, standinInfo(t, pdfinfoSettings{Info: map[string]string{"summary": "PDF version: 1.4\n"}})), pdf) + _, order = documentOrder(t, metadataStage(t, &fakeQPDF{}, standinInfo(t, stagestest.PDFInfoSettings{Info: map[string]string{"summary": "PDF version: 1.4\n"}})), pdf) if !slices.Equal(order, pagesOrder) { t.Errorf("no metadata:\n got %q\nwant %q", order, pagesOrder) } } + +func pdfinfoGoldens(t testing.TB) string { return tooltest.Testdata(t, "document", "info") } diff --git a/stages/email_test.go b/stages/internal/adapter/test/email_test.go similarity index 86% rename from stages/email_test.go rename to stages/internal/adapter/test/email_test.go index 5a9dd2ed..5888b677 100644 --- a/stages/email_test.go +++ b/stages/internal/adapter/test/email_test.go @@ -1,6 +1,6 @@ //go:build linux -package stages_test +package adapter_test import ( "os" @@ -11,10 +11,11 @@ import ( "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" "github.com/standards-lab/docproc/tool" ) -func standinEmailStage(t *testing.T, s onenoteSettings) *adapter.EmailStage { +func standinEmailStage(t *testing.T, s stagestest.EnvelopeSettings) *adapter.EmailStage { t.Helper() spec := email.MailSpec() spec.Program = tooltest.Link(t, t.TempDir(), "docproc-mail", s) @@ -44,9 +45,9 @@ func TestEmailStageThreading(t *testing.T) { t.Fatal(err) } fixture := tooltest.Tools(t, "mail/tests/fixtures/"+c.name+".eml") - stage := standinEmailStage(t, onenoteSettings{Stdout: string(lines)}) + stage := standinEmailStage(t, stagestest.EnvelopeSettings{Stdout: string(lines)}) d := newDispatcher(t, dispatch.Stages{route.Nested: stage}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, fixture, nil) + events := stagestest.DispatchAll(t, d, fixture, nil) wantSteps(t, events, []step{{events[0].Part.Name, 0, dispatch.Prepared}}) for _, kind := range []dispatch.OutputKind{dispatch.RecordOutput, dispatch.MarkdownOutput} { meta := outputNamed(t, events[0], kind, "message").Meta diff --git a/stages/internal/adapter/test/helpers_test.go b/stages/internal/adapter/test/helpers_test.go new file mode 100644 index 00000000..c6196f25 --- /dev/null +++ b/stages/internal/adapter/test/helpers_test.go @@ -0,0 +1,77 @@ +package adapter_test + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "slices" + "testing" + + "github.com/standards-lab/docproc/dispatch" + "github.com/standards-lab/docproc/inspect" + "github.com/standards-lab/docproc/stages/internal/stagestest" +) + +type step struct { + name string + depth int + outcome dispatch.Outcome +} + +func (s step) String() string { return fmt.Sprintf("%s@%d:%s", s.name, s.depth, s.outcome) } + +func steps(events []stagestest.Dispatched) []step { + out := make([]step, 0, len(events)) + for _, ev := range events { + out = append(out, step{ev.Part.Name, ev.Part.Depth, ev.Outcome}) + } + return out +} + +func wantSteps(t *testing.T, events []stagestest.Dispatched, want []step) { + t.Helper() + if got := steps(events); !slices.Equal(got, want) { + t.Fatalf("events:\n got %v\nwant %v", got, want) + } +} + +func hasFlag(flags []inspect.Flag, c inspect.Check) bool { + return slices.ContainsFunc(flags, func(f inspect.Flag) bool { return f.Check == c }) +} + +func byName(t *testing.T, events []stagestest.Dispatched, name string) stagestest.Dispatched { + t.Helper() + for _, ev := range events { + if ev.Part.Name == name { + return ev + } + } + t.Fatalf("no event for %s", name) + return stagestest.Dispatched{} +} + +func outputNamed(t *testing.T, ev stagestest.Dispatched, kind dispatch.OutputKind, name string) dispatch.Output { + t.Helper() + for _, o := range ev.Outputs { + if o.Kind == kind && o.Name == name { + return o + } + } + t.Fatalf("%s: no %s output named %q among %d", ev.Part.Name, kind, name, len(ev.Outputs)) + return dispatch.Output{} +} + +func wheres(events []stagestest.Dispatched) []string { + var out []string + for _, ev := range events { + if ev.Part.Depth > 0 { + out = append(out, ev.Part.Where) + } + } + return out +} + +func sum(content string) string { + s := sha256.Sum256([]byte(content)) + return hex.EncodeToString(s[:]) +} diff --git a/stages/internal/adapter/test/main_test.go b/stages/internal/adapter/test/main_test.go new file mode 100644 index 00000000..64d15956 --- /dev/null +++ b/stages/internal/adapter/test/main_test.go @@ -0,0 +1,25 @@ +//go:build linux + +package adapter_test + +import ( + "testing" + + "github.com/standards-lab/docproc/internal/tooltest" + "github.com/standards-lab/docproc/stages/internal/stagestest" +) + +func TestMain(m *testing.M) { + tooltest.Main(m, stagestest.Programs()) +} + +func wantPanic(t *testing.T, want string, build func()) { + t.Helper() + defer func() { + t.Helper() + if got := recover(); got != want { + t.Errorf("panic %v, want %q", got, want) + } + }() + build() +} diff --git a/stages/media_metadata_test.go b/stages/internal/adapter/test/media_metadata_test.go similarity index 87% rename from stages/media_metadata_test.go rename to stages/internal/adapter/test/media_metadata_test.go index b88a29a4..a0f76a23 100644 --- a/stages/media_metadata_test.go +++ b/stages/internal/adapter/test/media_metadata_test.go @@ -1,6 +1,6 @@ //go:build linux -package stages_test +package adapter_test import ( "os" @@ -10,14 +10,14 @@ import ( "testing" "github.com/standards-lab/docproc/dispatch" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/media" "github.com/standards-lab/docproc/metadata" "github.com/standards-lab/docproc/route" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) var ( - taggedMP3 = filepath.Join("..", "audio", "testdata", "speech-tagged.mp3") - scenesMKV = filepath.Join("..", "audio", "testdata", "speech-scenes.mkv") taggedRecord = metadata.Media{ Format: "mp3", Duration: 6.590938, BitRate: 32988, Tags: metadata.Properties{ @@ -45,7 +45,7 @@ var ( func ffprobeGolden(t *testing.T, name string) string { t.Helper() - b, err := os.ReadFile(filepath.Join("..", "audio", "testdata", name)) + b, err := os.ReadFile(tooltest.Testdata(t, "audio", name)) if err != nil { t.Fatal(err) } @@ -62,7 +62,7 @@ func dispatchMediaMetadata(t *testing.T, r route.Route, stage dispatch.Stage, fi t.Fatal(err) } var order []string - events := dispatchAll(t, d, fixture, func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, fixture, func(ev *dispatch.Event) { if ev.Output != nil { order = append(order, string(ev.Output.Kind)+" "+ev.Output.Name) } @@ -82,7 +82,7 @@ func dispatchMediaMetadata(t *testing.T, r route.Route, stage dispatch.Stage, fi func TestAudioStageMediaMetadata(t *testing.T) { t.Parallel() stage, _ := testAudioStage(t, ffprobeGolden(t, "speech-tagged.ffprobe.json")) - got, order := dispatchMediaMetadata(t, route.Audio, stage, taggedMP3) + got, order := dispatchMediaMetadata(t, route.Audio, stage, taggedMP3(t)) want := []string{"record metadata", "audio window 0", "audio window 1", "audio window 2", "record plan"} if !slices.Equal(order, want) { t.Errorf("order %q, want %q", order, want) @@ -95,7 +95,7 @@ func TestAudioStageMediaMetadata(t *testing.T) { func TestVideoStageMediaMetadata(t *testing.T) { t.Parallel() stage, _ := testVideoStage(t, ffprobeGolden(t, "speech-scenes.ffprobe.json"), media.Request{}) - got, order := dispatchMediaMetadata(t, route.Video, stage, scenesMKV) + got, order := dispatchMediaMetadata(t, route.Video, stage, scenesMKV(t)) if len(order) < 2 || order[0] != "record metadata" || order[1] != "record plan" { t.Errorf("order %q, want the metadata record, then the plan", order) } @@ -103,3 +103,7 @@ func TestVideoStageMediaMetadata(t *testing.T) { t.Errorf("record\n %+v\nwant\n %+v", got, scenesRecord) } } + +func taggedMP3(t testing.TB) string { return tooltest.Testdata(t, "audio", "speech-tagged.mp3") } + +func scenesMKV(t testing.TB) string { return tooltest.Testdata(t, "audio", "speech-scenes.mkv") } diff --git a/stages/office_test.go b/stages/internal/adapter/test/office_test.go similarity index 85% rename from stages/office_test.go rename to stages/internal/adapter/test/office_test.go index 0277962b..433fb73f 100644 --- a/stages/office_test.go +++ b/stages/internal/adapter/test/office_test.go @@ -1,6 +1,6 @@ //go:build linux -package stages_test +package adapter_test import ( "bufio" @@ -9,7 +9,6 @@ import ( "encoding/hex" "encoding/json" "os" - "path/filepath" "reflect" "slices" "strings" @@ -22,25 +21,10 @@ import ( "github.com/standards-lab/docproc/picture" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" "github.com/standards-lab/docproc/tool" ) -func standinOfficeStage(t *testing.T, s onenoteSettings) *adapter.OfficeStage { - t.Helper() - spec := office.OfficeSpec() - spec.Program = tooltest.Link(t, t.TempDir(), "docproc-ooxml", s) - of, err := tool.NewExec(t.Context(), spec) - if err != nil { - t.Fatal(err) - } - pc := standinPictureStage(t, pictureListing, 1).Converter() - c, err := office.NewConverter(t.Context(), office.Config{Office: of, Pictures: pc}) - if err != nil { - t.Fatal(err) - } - return adapter.NewOfficeStage(adapter.OfficeConfig{Converter: c, Version: adapter.Versions(of)}) -} - func TestOfficeStageSheets(t *testing.T) { t.Parallel() const stored = "a stored picture's bytes" @@ -55,15 +39,15 @@ func TestOfficeStageSheets(t *testing.T) { `{"line":"rows","markdown":"| 3 | 4 |\n","rows":[{"row":3,"cells":[{"ref":"A3","value_type":"number","value":3}]}]}`, `{"line":"sheet","name":"document","markdown":"## document\n"}`, } - stage := standinOfficeStage(t, onenoteSettings{ + stage := stagestest.StandinOfficeStage(t, stagestest.EnvelopeSettings{ Stdout: strings.Join(lines, "\n") + "\n", Stderr: "docproc-ooxml: warning: sheet 2: notes not read\n", Media: map[string]string{png: stored}, }) - d := newDispatcher(t, dispatch.Stages{route.Office: stage, route.Vision: standinVisionStage(t, pictureSettings{})}, dispatch.NewMemoryIndex(0)) - book := input(t, "book.xlsx", zipBytes(t, zent{name: "[Content_Types].xml", body: ""})) + d := newDispatcher(t, dispatch.Stages{route.Office: stage, route.Vision: standinVisionStage(t, stagestest.PictureSettings{})}, dispatch.NewMemoryIndex(0)) + book := stagestest.Input(t, "book.xlsx", zipBytes(t, zent{name: "[Content_Types].xml", body: ""})) var files []string - events := dispatchAll(t, d, book, func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, book, func(ev *dispatch.Event) { if o := ev.Output; o != nil && ev.Part.Depth == 0 && strings.HasPrefix(o.Name, "sheet/") { b, err := os.ReadFile(o.Path) if err != nil { @@ -131,7 +115,7 @@ func TestOfficeStageSheets(t *testing.T) { func TestOfficeStageIdentity(t *testing.T) { t.Parallel() - base := standinOfficeStage(t, onenoteSettings{}) + base := stagestest.StandinOfficeStage(t, stagestest.EnvelopeSettings{}) c := base.Converter() same := adapter.NewOfficeStage(adapter.OfficeConfig{Converter: c, Version: base.Identity().Version, MetafileScale: picture.DefaultMetafileScale}) scaled := adapter.NewOfficeStage(adapter.OfficeConfig{Converter: c, Version: base.Identity().Version, MetafileScale: 5}) @@ -145,7 +129,7 @@ func TestOfficeStageIdentity(t *testing.T) { func TestOfficeStageUnread(t *testing.T) { t.Parallel() - encrypted, err := os.ReadFile(filepath.Join("..", "office", "testdata", "odf", "generated", "encrypted.odt")) + encrypted, err := os.ReadFile(tooltest.Testdata(t, "office", "odf", "generated", "encrypted.odt")) if err != nil { t.Fatal(err) } @@ -161,20 +145,20 @@ func TestOfficeStageUnread(t *testing.T) { } { t.Run(c.name, func(t *testing.T) { t.Parallel() - link := tooltest.Link(t, t.TempDir(), "docproc-ooxml", onenoteSettings{}) + link := tooltest.Link(t, t.TempDir(), "docproc-ooxml", stagestest.EnvelopeSettings{}) spec := office.OfficeSpec() spec.Program = link of, err := tool.NewExec(t.Context(), spec) if err != nil { t.Fatal(err) } - conv, err := office.NewConverter(t.Context(), office.Config{Office: of, Pictures: standinPictureStage(t, pictureListing, 1).Converter()}) + conv, err := office.NewConverter(t.Context(), office.Config{Office: of, Pictures: stagestest.StandinPictureStage(t, stagestest.PictureListing, 1).Converter()}) if err != nil { t.Fatal(err) } stage := adapter.NewOfficeStage(adapter.OfficeConfig{Converter: conv, Version: adapter.Versions(of)}) d := newDispatcher(t, dispatch.Stages{route.Office: stage}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, input(t, c.name, c.content), nil) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, c.name, c.content), nil) wantSteps(t, events, []step{{c.name, 0, c.outcome}}) if ev := events[0]; ev.Part.ContentType.Route != route.Office || !strings.Contains(ev.Reason, c.reason) { t.Errorf("route %s, reason %q; want office, %q", ev.Part.ContentType.Route, ev.Reason, c.reason) @@ -195,12 +179,12 @@ func TestOfficeStageMetadata(t *testing.T) { } fixture := tooltest.Tools(t, "ooxml/fixtures/generated/docx/links.libreoffice.docx") content := dispatch.NewMemoryContent() - stage := standinOfficeStage(t, onenoteSettings{Stdout: string(lines)}) + stage := stagestest.StandinOfficeStage(t, stagestest.EnvelopeSettings{Stdout: string(lines)}) d, err := dispatch.New(dispatch.Config{Content: content, Puts: 2, Stages: dispatch.Stages{route.Office: stage}, Index: dispatch.NewMemoryIndex(0), Dir: t.TempDir()}) if err != nil { t.Fatal(err) } - events := dispatchAll(t, d, fixture, nil) + events := stagestest.DispatchAll(t, d, fixture, nil) wantSteps(t, events, []step{{"links.libreoffice.docx", 0, dispatch.Prepared}}) var got []string for _, o := range events[0].Outputs { @@ -238,9 +222,9 @@ func TestOfficeStageMetadata(t *testing.T) { func TestOfficeStageNoProperties(t *testing.T) { t.Parallel() - stage := standinOfficeStage(t, onenoteSettings{Stdout: `{"line":"document","schema":"2","format":"docx","markdown":"# Bare\n"}` + "\n"}) + stage := stagestest.StandinOfficeStage(t, stagestest.EnvelopeSettings{Stdout: `{"line":"document","schema":"2","format":"docx","markdown":"# Bare\n"}` + "\n"}) d := newDispatcher(t, dispatch.Stages{route.Office: stage}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, input(t, "bare.docx", zipBytes(t, zent{name: "[Content_Types].xml", body: ""})), nil) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "bare.docx", zipBytes(t, zent{name: "[Content_Types].xml", body: ""})), nil) wantSteps(t, events, []step{{"bare.docx", 0, dispatch.Prepared}}) if outs := events[0].Outputs; len(outs) != 1 || outs[0].Name != "document" { t.Errorf("outputs %+v, want the document's Markdown alone", outs) diff --git a/stages/onenote_test.go b/stages/internal/adapter/test/onenote_test.go similarity index 69% rename from stages/onenote_test.go rename to stages/internal/adapter/test/onenote_test.go index 01d7ad46..6437b835 100644 --- a/stages/onenote_test.go +++ b/stages/internal/adapter/test/onenote_test.go @@ -1,88 +1,25 @@ //go:build linux -package stages_test +package adapter_test import ( - "cmp" "crypto/sha256" "encoding/hex" "errors" - "fmt" - "os" "path/filepath" "slices" - "syscall" "testing" - "time" "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/internal/cli" "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/onenote" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" "github.com/standards-lab/docproc/tool" ) -type onenoteSettings struct { - Stdout string `json:"stdout"` - Stderr string `json:"stderr"` - Exit int `json:"exit"` - Media map[string]string `json:"media"` - HoldMS int `json:"hold_ms,omitzero"` - Signal string `json:"signal,omitzero"` - Limit bool `json:"limit,omitzero"` - Home string `json:"home,omitzero"` -} - -func envelopeStandin(minimum string) tooltest.Program { - return func(r tooltest.Run) int { return envelopeRun(r, minimum) } -} - -func envelopeRun(r tooltest.Run, minimum string) int { - var s onenoteSettings - if err := r.Settings(&s); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - if home := cmp.Or(os.Getenv("HOME"), s.Home); s.Home != "" && home != s.Home { - fmt.Fprintf(os.Stderr, "mise ERROR Config files in %s are not trusted.\n", filepath.Join(s.Home, ".config", "mise", "config.toml")) - return 1 - } - if len(r.Args) == 1 && r.Args[0] == "--version" { - fmt.Printf("%s\nschema 2\n", minimum) - return 0 - } - if s.Limit { - var l syscall.Rlimit - if err := syscall.Getrlimit(syscall.RLIMIT_AS, &l); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - fmt.Fprintf(os.Stderr, "docproc-onenote: warning: limit: %d\n", l.Cur) - } - time.Sleep(time.Duration(s.HoldMS) * time.Millisecond) - for i, arg := range r.Args { - if arg != "--media" || i+1 >= len(r.Args) { - continue - } - for name, content := range s.Media { - if err := os.WriteFile(filepath.Join(r.Args[i+1], name), []byte(content), 0o644); err != nil { - fmt.Fprintln(os.Stderr, err) - return 1 - } - } - } - fmt.Print(s.Stdout) - fmt.Fprint(os.Stderr, s.Stderr) - if s.Signal != "" { - err := syscall.Exec("/bin/sh", []string{"sh", "-c", "kill -s " + s.Signal + " $$"}, nil) - fmt.Fprintln(os.Stderr, err) - return 2 - } - return s.Exit -} - -func standinOneNoteStage(t *testing.T, s onenoteSettings) (*adapter.OneNoteStage, string) { +func standinOneNoteStage(t *testing.T, s stagestest.EnvelopeSettings) (*adapter.OneNoteStage, string) { t.Helper() spec := onenote.OneNoteSpec() link := tooltest.Link(t, t.TempDir(), "docproc-onenote", s) @@ -118,7 +55,7 @@ func TestOneNoteStageRecords(t *testing.T) { svg := hex.EncodeToString(sum[:]) + ".svg" sum = sha256.Sum256([]byte("a recording")) rec := hex.EncodeToString(sum[:]) + ".bin" - stage, link := standinOneNoteStage(t, onenoteSettings{ + stage, link := standinOneNoteStage(t, stagestest.EnvelopeSettings{ Stdout: `{"line":"notebook","schema":"2","input":"package","name":"S"} {"line":"section","id":"s","path":["S"]} {"line":"page","id":"p","section":"s","level":1,"title":"T","modification_time":"2026-01-12T14:15:00Z","markdown":"# T","media":[{"kind":"image","file":"` + jpg + `","filename":"photo.jpg","size":5},{"kind":"embedded_file","filename":"gone.docx"},{"kind":"ink","file":"` + svg + `"},{"kind":"embedded_file","file":"` + rec + `","filename":"memo","size":11,"type":"audio"}]} @@ -186,7 +123,7 @@ func TestOneNoteStageRefusals(t *testing.T) { } { t.Run(reason, func(t *testing.T) { t.Parallel() - stage, _ := standinOneNoteStage(t, onenoteSettings{Stderr: "docproc-onenote: error: " + reason + "\n", Exit: 3}) + stage, _ := standinOneNoteStage(t, stagestest.EnvelopeSettings{Stderr: "docproc-onenote: error: " + reason + "\n", Exit: 3}) items, err := prepare(t, stage) if len(items) != 0 { t.Errorf("items %+v, want none", items) diff --git a/stages/picture_metadata_integration_test.go b/stages/internal/adapter/test/picture_metadata_integration_test.go similarity index 81% rename from stages/picture_metadata_integration_test.go rename to stages/internal/adapter/test/picture_metadata_integration_test.go index b0d2d2ad..c63f78c2 100644 --- a/stages/picture_metadata_integration_test.go +++ b/stages/internal/adapter/test/picture_metadata_integration_test.go @@ -1,6 +1,6 @@ //go:build linux && integration -package stages_test +package adapter_test import ( "math" @@ -13,6 +13,7 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/metadata" "github.com/standards-lab/docproc/route" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) func TestPictureMetadataHost(t *testing.T) { @@ -29,16 +30,16 @@ func TestPictureMetadataHost(t *testing.T) { capture time.Time lat, lon float64 }{ - {exifGPSJPEG, time.Date(2024, 5, 6, 5, 8, 9, 0, time.UTC), -(33 + 51.0/60 + 35.64/3600), 151 + 12.0/60 + 40.2/3600}, - {exifZonelessHEIC, time.Date(2023, 12, 31, 23, 59, 58, 0, time.UTC), 51 + 30.0/60 + 15.48/3600, -(7.0/60 + 39.6/3600)}, - {exifNonePNG, time.Time{}, 0, 0}, + {exifGPSJPEG(t), time.Date(2024, 5, 6, 5, 8, 9, 0, time.UTC), -(33 + 51.0/60 + 35.64/3600), 151 + 12.0/60 + 40.2/3600}, + {exifZonelessHEIC(t), time.Date(2023, 12, 31, 23, 59, 58, 0, time.UTC), 51 + 30.0/60 + 15.48/3600, -(7.0/60 + 39.6/3600)}, + {exifNonePNG(t), time.Time{}, 0, 0}, } { name := filepath.Base(c.fixture) data, err := os.ReadFile(c.fixture) if err != nil { t.Fatal(err) } - events := dispatchAll(t, d, c.fixture, nil) + events := stagestest.DispatchAll(t, d, c.fixture, nil) wantSteps(t, events, []step{{name, 0, dispatch.Prepared}}) ev := events[0] records := slices.DeleteFunc(slices.Clone(ev.Outputs), func(o dispatch.Output) bool { return o.Kind != dispatch.RecordOutput }) diff --git a/stages/picture_metadata_test.go b/stages/internal/adapter/test/picture_metadata_test.go similarity index 72% rename from stages/picture_metadata_test.go rename to stages/internal/adapter/test/picture_metadata_test.go index ea91d4a4..958604b7 100644 --- a/stages/picture_metadata_test.go +++ b/stages/internal/adapter/test/picture_metadata_test.go @@ -1,12 +1,11 @@ //go:build linux -package stages_test +package adapter_test import ( "crypto/sha256" "encoding/hex" "fmt" - "io" "math" "os" "path/filepath" @@ -21,54 +20,12 @@ import ( "github.com/standards-lab/docproc/picture" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages/internal/adapter" - "github.com/standards-lab/docproc/tool" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) -var ( - exifGPSJPEG = filepath.Join("..", "picture", "testdata", "exif-gps.jpg") - exifZonelessHEIC = filepath.Join("..", "picture", "testdata", "exif-zoneless.heic") - exifNonePNG = filepath.Join("..", "picture", "testdata", "exif-none.png") -) - -const noEXIF = "1 1\n" - -func pictureEXIFStandin(settings pictureSettings) int { - input, err := io.ReadAll(os.Stdin) - if err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - if settings.EXIFFail != "" { - fmt.Fprint(os.Stderr, settings.EXIFFail) - return 1 - } - sum := sha256.Sum256(input) - out, ok := settings.EXIF[hex.EncodeToString(sum[:])] - if !ok { - out = noEXIF - } - fmt.Print(out) - return 0 -} - -func standinEXIF(t *testing.T, settings pictureSettings) (*tool.Tool, *picture.EXIFReader) { - t.Helper() - spec := picture.MagickSpec() - spec.Program = tooltest.Link(t, t.TempDir(), "magick", settings) - mg, err := tool.NewExec(t.Context(), spec) - if err != nil { - t.Fatal(err) - } - r, err := picture.NewEXIFReader(picture.Config{Magick: mg}) - if err != nil { - t.Fatal(err) - } - return mg, r -} - -func standinVisionStage(t *testing.T, settings pictureSettings) *adapter.VisionStage { +func standinVisionStage(t *testing.T, settings stagestest.PictureSettings) *adapter.VisionStage { t.Helper() - mg, r := standinEXIF(t, settings) + mg, r := stagestest.StandinEXIF(t, settings) return adapter.NewVisionStage(adapter.VisionConfig{EXIF: r, Version: adapter.Versions(mg)}) } @@ -93,11 +50,11 @@ func magickGoldens(t *testing.T, fixtures ...string) map[string]string { func TestPictureMetadataRecords(t *testing.T) { t.Parallel() - settings := pictureSettings{Formats: pictureListing, EXIF: magickGoldens(t, exifGPSJPEG, exifZonelessHEIC, exifNonePNG)} + settings := stagestest.PictureSettings{Formats: stagestest.PictureListing, EXIF: magickGoldens(t, exifGPSJPEG(t), exifZonelessHEIC(t), exifNonePNG(t))} content := dispatch.NewMemoryContent() d, err := dispatch.New(dispatch.Config{ Content: content, Puts: 2, Index: dispatch.NewMemoryIndex(0), Dir: t.TempDir(), - Stages: dispatch.Stages{route.Vision: standinVisionStage(t, settings), route.VisionConverted: pictureStageOver(t, settings)}, + Stages: dispatch.Stages{route.Vision: standinVisionStage(t, settings), route.VisionConverted: stagestest.PictureStageOver(t, settings)}, }) if err != nil { t.Fatal(err) @@ -110,7 +67,7 @@ func TestPictureMetadataRecords(t *testing.T) { lat, lon float64 }{ { - exifGPSJPEG, route.Vision, "image/jpeg", + exifGPSJPEG(t), route.Vision, "image/jpeg", &metadata.Picture{ CaptureTime: time.Date(2024, 5, 6, 5, 8, 9, 0, time.UTC), Make: "Docproc", Model: "Fixture One", Orientation: 6, Width: 48, Height: 32, @@ -118,18 +75,18 @@ func TestPictureMetadataRecords(t *testing.T) { -(33 + 51.0/60 + 35.64/3600), 151 + 12.0/60 + 40.2/3600, }, { - exifZonelessHEIC, route.VisionConverted, "image/png", + exifZonelessHEIC(t), route.VisionConverted, "image/png", &metadata.Picture{ CaptureTime: time.Date(2023, 12, 31, 23, 59, 58, 0, time.UTC), Make: "Docproc", Model: "Fixture Two", Width: 32, Height: 32, }, 51 + 30.0/60 + 15.48/3600, -(7.0/60 + 39.6/3600), }, - {exifNonePNG, route.Vision, "image/png", nil, 0, 0}, + {exifNonePNG(t), route.Vision, "image/png", nil, 0, 0}, } { name := filepath.Base(c.fixture) var order []string - events := dispatchAll(t, d, c.fixture, func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, c.fixture, func(ev *dispatch.Event) { if ev.Output != nil { order = append(order, string(ev.Output.Kind)+" "+ev.Output.Name) } @@ -171,13 +128,13 @@ func TestPictureMetadataRecords(t *testing.T) { func TestPictureMetadataUnread(t *testing.T) { t.Parallel() - settings := pictureSettings{Formats: pictureListing, EXIFFail: "magick: insufficient image data in file `/tmp/magick-x'\n"} + settings := stagestest.PictureSettings{Formats: stagestest.PictureListing, EXIFFail: "magick: insufficient image data in file `/tmp/magick-x'\n"} d := newDispatcher(t, dispatch.Stages{ - route.Vision: standinVisionStage(t, settings), route.VisionConverted: pictureStageOver(t, settings), + route.Vision: standinVisionStage(t, settings), route.VisionConverted: stagestest.PictureStageOver(t, settings), }, dispatch.NewMemoryIndex(0)) - for _, fixture := range []string{exifGPSJPEG, exifZonelessHEIC} { + for _, fixture := range []string{exifGPSJPEG(t), exifZonelessHEIC(t)} { name := filepath.Base(fixture) - events := dispatchAll(t, d, fixture, nil) + events := stagestest.DispatchAll(t, d, fixture, nil) wantSteps(t, events, []step{{name, 0, dispatch.Prepared}}) ev := events[0] if len(ev.Warnings) != 1 || ev.Warnings[0].Tool != "magick" || ev.Warnings[0].Where != "metadata" { @@ -191,13 +148,13 @@ func TestPictureMetadataUnread(t *testing.T) { func TestVisionStagePassesThrough(t *testing.T) { t.Parallel() - d := newDispatcher(t, dispatch.Stages{route.Vision: standinVisionStage(t, pictureSettings{})}, dispatch.NewMemoryIndex(0)) - data, err := os.ReadFile(exifGPSJPEG) + d := newDispatcher(t, dispatch.Stages{route.Vision: standinVisionStage(t, stagestest.PictureSettings{})}, dispatch.NewMemoryIndex(0)) + data, err := os.ReadFile(exifGPSJPEG(t)) if err != nil { t.Fatal(err) } var held []byte - events := dispatchAll(t, d, exifGPSJPEG, func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, exifGPSJPEG(t), func(ev *dispatch.Event) { if ev.Output != nil && ev.Output.Kind == dispatch.ImageOutput { if held, err = os.ReadFile(ev.Output.Path); err != nil { t.Fatal(err) @@ -213,7 +170,7 @@ func TestVisionStagePassesThrough(t *testing.T) { func TestNewVisionStageNil(t *testing.T) { t.Parallel() wantPanic(t, "stages: VisionConfig.EXIF is nil", func() { adapter.NewVisionStage(adapter.VisionConfig{Version: "magick 7.1.2"}) }) - c := standinPictureStage(t, pictureListing, 1).Converter() + c := stagestest.StandinPictureStage(t, stagestest.PictureListing, 1).Converter() wantPanic(t, "stages: PictureConfig.EXIF is nil", func() { adapter.NewPictureStage(adapter.PictureConfig{Converter: c, Version: "magick 7.1.2"}) }) @@ -226,3 +183,11 @@ func TestPictureMetadataContentError(t *testing.T) { t.Errorf("ErrMetadata: content %t, %q; want a content error", content, reason) } } + +func exifGPSJPEG(t testing.TB) string { return tooltest.Testdata(t, "picture", "exif-gps.jpg") } + +func exifZonelessHEIC(t testing.TB) string { + return tooltest.Testdata(t, "picture", "exif-zoneless.heic") +} + +func exifNonePNG(t testing.TB) string { return tooltest.Testdata(t, "picture", "exif-none.png") } diff --git a/stages/internal/adapter/test/picture_test.go b/stages/internal/adapter/test/picture_test.go new file mode 100644 index 00000000..c146c366 --- /dev/null +++ b/stages/internal/adapter/test/picture_test.go @@ -0,0 +1,100 @@ +//go:build linux + +package adapter_test + +import ( + "maps" + "os" + "strconv" + "strings" + "testing" + + "github.com/standards-lab/docproc/dispatch" + "github.com/standards-lab/docproc/route" + "github.com/standards-lab/docproc/stages/internal/stagestest" +) + +const ( + pictureTIFF = "II*\x00\x08\x00\x00\x00" + "a stand-in TIFF" + pictureHEIC = "\x00\x00\x00\x18ftypheic\x00\x00\x00\x00mif1heic" + pictureWebP = "RIFF\x10\x00\x00\x00WEBPVP8 " + pictureAVIF = "\x00\x00\x00\x18ftypavif\x00\x00\x00\x00mif1avif" +) + +func TestPictureStageTIFFPages(t *testing.T) { + t.Parallel() + d := newDispatcher(t, dispatch.Stages{route.VisionConverted: stagestest.StandinPictureStage(t, stagestest.PictureListing, 3)}, dispatch.NewMemoryIndex(0)) + var held []string + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "scan.tif", pictureTIFF), func(ev *dispatch.Event) { + if ev.Output != nil { + b, err := os.ReadFile(ev.Output.Path) + if err != nil { + t.Fatal(err) + } + held = append(held, string(b)) + } + }) + wantSteps(t, events, []step{{"scan.tif", 0, dispatch.Prepared}}) + outputs := events[0].Outputs + if len(outputs) != 3 { + t.Fatalf("%d outputs, want 3", len(outputs)) + } + for i, o := range outputs { + n := strconv.Itoa(i + 1) + want := map[string]string{"from": "tiff", "page": n, "count": "3"} + if o.Kind != dispatch.ImageOutput || o.Name != "page "+n || o.MediaType != "image/png" || !maps.Equal(o.Meta, want) { + t.Errorf("output %d: %s %q %s %v; want an image named %q, meta %v", i, o.Kind, o.Name, o.MediaType, o.Meta, "page "+n, want) + } + if held[i] != route.PNGSignature+"page "+n { + t.Errorf("output %d holds %q, want page %s", i, held[i], n) + } + } +} + +func TestPictureStageRasters(t *testing.T) { + t.Parallel() + d := newDispatcher(t, dispatch.Stages{route.VisionConverted: stagestest.StandinPictureStage(t, stagestest.PictureListing, 0)}, dispatch.NewMemoryIndex(0)) + for name, c := range map[string]struct { + content string + kind route.Kind + }{ + "x.heic": {pictureHEIC, route.HEIC}, + "x.webp": {pictureWebP, route.WebP}, + "x.avif": {pictureAVIF, route.AVIF}, + } { + var held string + events := stagestest.DispatchAll(t, d, stagestest.Input(t, name, c.content), func(ev *dispatch.Event) { + if ev.Output != nil { + b, err := os.ReadFile(ev.Output.Path) + if err != nil { + t.Fatal(err) + } + held = string(b) + } + }) + wantSteps(t, events, []step{{name, 0, dispatch.Prepared}}) + o := events[0].Outputs + if len(o) != 1 || o[0].Kind != dispatch.ImageOutput || o[0].Name != "picture" || !maps.Equal(o[0].Meta, map[string]string{"from": string(c.kind)}) { + t.Errorf("%s: outputs %+v", name, o) + } + if coder := string(c.kind) + ":"; !strings.HasPrefix(held, route.PNGSignature+coder) || !strings.HasSuffix(held, "[0]") { + t.Errorf("%s: PNG holds %q; want its first image read through %s", name, held, coder) + } + } +} + +func TestPictureNoReader(t *testing.T) { + t.Parallel() + d := newDispatcher(t, dispatch.Stages{route.VisionConverted: stagestest.StandinPictureStage(t, "", 0)}, dispatch.NewMemoryIndex(0)) + for name, c := range map[string]struct{ content, what string }{ + "x.heic": {pictureHEIC, "a HEIC"}, + "x.webp": {pictureWebP, "a WebP"}, + "x.avif": {pictureAVIF, "an AVIF"}, + } { + ev := stagestest.DispatchAll(t, d, stagestest.Input(t, name, c.content), nil)[0] + want := "no processor yet: picture: " + name + " is " + c.what + " picture: no magick reader" + if ev.Outcome != dispatch.NoProcessor || !strings.Contains(ev.Reason, want) { + t.Errorf("%s: %s, %q; want no processor, %q", name, ev.Outcome, ev.Reason, want) + } + } +} diff --git a/stages/release_adapter_integration_test.go b/stages/internal/adapter/test/release_adapter_integration_test.go similarity index 99% rename from stages/release_adapter_integration_test.go rename to stages/internal/adapter/test/release_adapter_integration_test.go index 5b760f58..0b0b5030 100644 --- a/stages/release_adapter_integration_test.go +++ b/stages/internal/adapter/test/release_adapter_integration_test.go @@ -1,6 +1,6 @@ //go:build linux && integration -package stages_test +package adapter_test import ( "bytes" diff --git a/stages/resume_integration_test.go b/stages/internal/adapter/test/resume_integration_test.go similarity index 99% rename from stages/resume_integration_test.go rename to stages/internal/adapter/test/resume_integration_test.go index 5b34b1a8..f9669784 100644 --- a/stages/resume_integration_test.go +++ b/stages/internal/adapter/test/resume_integration_test.go @@ -1,6 +1,6 @@ //go:build linux && integration -package stages_test +package adapter_test import ( "context" diff --git a/stages/sevenzip_standin_test.go b/stages/internal/adapter/test/sevenzip_standin_test.go similarity index 73% rename from stages/sevenzip_standin_test.go rename to stages/internal/adapter/test/sevenzip_standin_test.go index 57b06068..59cbbaae 100644 --- a/stages/sevenzip_standin_test.go +++ b/stages/internal/adapter/test/sevenzip_standin_test.go @@ -1,12 +1,11 @@ //go:build linux -package stages_test +package adapter_test import ( "fmt" "hash/crc32" "os" - "path/filepath" "slices" "strings" "testing" @@ -15,39 +14,11 @@ import ( "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/sevenzip" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" "github.com/standards-lab/docproc/tool" ) -type sevenZipSettings struct { - Listing string `json:"listing"` - Content []byte `json:"content"` - EncryptedHeaders bool `json:"encrypted_headers"` -} - -func sevenZipStandin(r tooltest.Run) int { - var s sevenZipSettings - if err := r.Settings(&s); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - switch { - case len(r.Args) > 0 && r.Args[0] == "l" && s.EncryptedHeaders: - fmt.Fprintf(os.Stderr, "ERROR: %s : Cannot open encrypted archive. Wrong password?\n", r.Args[len(r.Args)-1]) - return 2 - case len(r.Args) > 0 && r.Args[0] == "l": - fmt.Print(s.Listing) - return 0 - case len(r.Args) > 0 && r.Args[0] == "e": - if _, err := os.Stdout.Write(s.Content); err != nil { - return 2 - } - return 0 - } - fmt.Printf("\n7-Zip (z) %s (x64) : Copyright (c) 1999-2026 Igor Pavlov : 2026-11-06\n", sevenzip.SevenZipMinimum) - return 0 -} - -func standinSevenZip(t *testing.T, settings sevenZipSettings) (*dispatch.Dispatcher, string, string) { +func standinSevenZip(t *testing.T, settings stagestest.SevenZipSettings) (*dispatch.Dispatcher, string, string) { t.Helper() spec := sevenzip.SevenZipSpec() link := tooltest.Link(t, t.TempDir(), "7zz", settings) @@ -100,8 +71,8 @@ func TestRARSplitVolume(t *testing.T) { {"a.part1.rar", rar4Head(0x01)}, {"b.part01.rar", rar5Head(0x03, 0x01, 0x00, 0x01)}, } { - d, link, work := standinSevenZip(t, sevenZipSettings{Listing: slt("Path = notes.txt\nSize = 5\n")}) - events := dispatchAll(t, d, input(t, c.name, c.head), nil) + d, link, work := standinSevenZip(t, stagestest.SevenZipSettings{Listing: slt("Path = notes.txt\nSize = 5\n")}) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, c.name, c.head), nil) wantSteps(t, events, []step{{c.name, 0, dispatch.NoProcessor}}) if !strings.Contains(events[0].Reason, "a split RAR volume") { t.Errorf("%s: reason %q", c.name, events[0].Reason) @@ -120,8 +91,8 @@ func TestRARHandlers(t *testing.T) { {"a.rar", rar4Head(0), "-trar"}, {"b.rar", rar5Head(0x03, 0x01, 0x00, 0x00), "-trar5"}, } { - d, link, work := standinSevenZip(t, sevenZipSettings{Listing: listing, Content: []byte(content)}) - events := dispatchAll(t, d, input(t, c.name, c.head), nil) + d, link, work := standinSevenZip(t, stagestest.SevenZipSettings{Listing: listing, Content: []byte(content)}) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, c.name, c.head), nil) wantSteps(t, events, []step{{"notes.txt", 1, dispatch.NoProcessor}, {c.name, 0, dispatch.Prepared}}) if ev := events[0]; ev.Part.Where != "RAR entry notes.txt" || ev.Part.SHA256 != sum(content) { t.Errorf("%s: notes.txt at %q, SHA-256 %s", c.name, ev.Part.Where, ev.Part.SHA256) @@ -138,8 +109,8 @@ func TestRAREncryptedHeaders(t *testing.T) { {"a.rar", rar4Head(0)}, {"b.rar", rar5Head(0x0c, 0x04, 0x00, 0x00, 0x00)}, } { - d, link, work := standinSevenZip(t, sevenZipSettings{EncryptedHeaders: true}) - events := dispatchAll(t, d, input(t, c.name, c.head), nil) + d, link, work := standinSevenZip(t, stagestest.SevenZipSettings{EncryptedHeaders: true}) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, c.name, c.head), nil) wantSteps(t, events, []step{{c.name, 0, dispatch.Encrypted}}) if !strings.Contains(events[0].Reason, "a RAR archive whose headers are encrypted") { t.Errorf("%s: reason %q", c.name, events[0].Reason) @@ -152,7 +123,7 @@ func TestRAREncryptedHeaders(t *testing.T) { } func TestXZNames(t *testing.T) { - cleanTar, err := os.ReadFile(filepath.Join("..", "inspect", "testdata", "clean.tar")) + cleanTar, err := os.ReadFile(tooltest.Testdata(t, "inspect", "clean.tar")) if err != nil { t.Fatal(err) } @@ -172,8 +143,8 @@ func TestXZNames(t *testing.T) { {"stream", notes, []step{{"stream", 1, dispatch.NoProcessor}, {"stream", 0, dispatch.Prepared}}, "xz content stream"}, } { listing := slt(fmt.Sprintf("Size = %d\nMethod = LZMA2:12 CRC32\n", len(c.content))) - d, link, work := standinSevenZip(t, sevenZipSettings{Listing: listing, Content: []byte(c.content)}) - events := dispatchAll(t, d, input(t, c.name, xzHead), nil) + d, link, work := standinSevenZip(t, stagestest.SevenZipSettings{Listing: listing, Content: []byte(c.content)}) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, c.name, xzHead), nil) wantSteps(t, events, c.want) if got := wheres(events); !slices.Contains(got, c.where) { t.Errorf("%s: wheres %q, want %q among them", c.name, got, c.where) @@ -187,8 +158,8 @@ func TestXZNames(t *testing.T) { func TestXZDeclaredSize(t *testing.T) { listing := slt("Size = 100\nMethod = LZMA2:12 CRC32\n") - d, _, work := standinSevenZip(t, sevenZipSettings{Listing: listing, Content: []byte("short\n")}) - events := dispatchAll(t, d, input(t, "short.xz", xzHead), nil) + d, _, work := standinSevenZip(t, stagestest.SevenZipSettings{Listing: listing, Content: []byte("short\n")}) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "short.xz", xzHead), nil) wantSteps(t, events, []step{{"short", 1, dispatch.Failed}, {"short.xz", 0, dispatch.Prepared}}) if ev := events[0]; ev.Reason != "6 bytes written, 100 declared" || ev.Part.Where != "xz content short" { t.Errorf("short: %q at %q", ev.Reason, ev.Part.Where) diff --git a/stages/sevenzip_test.go b/stages/internal/adapter/test/sevenzip_test.go similarity index 92% rename from stages/sevenzip_test.go rename to stages/internal/adapter/test/sevenzip_test.go index e17d92ca..443bf1f7 100644 --- a/stages/sevenzip_test.go +++ b/stages/internal/adapter/test/sevenzip_test.go @@ -1,4 +1,4 @@ -package stages_test +package adapter_test import ( "context" @@ -14,6 +14,7 @@ import ( "github.com/standards-lab/docproc/inspect" "github.com/standards-lab/docproc/sevenzip" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) const sevenZipSignature = "7z\xbc\xaf\x27\x1c\x00\x04" @@ -85,7 +86,7 @@ func TestListingQuarantine(t *testing.T) { strict := inspect.Options{Policy: map[inspect.Check]inspect.Verdict{inspect.ArchiveTraversal: inspect.Quarantine}} sz := fake() d, zs, work := archiveDispatcherWith(t, adapter.ArchiveConfig{Inspect: strict, SevenZip: sz, Version: "7zz 26.5"}) - events := dispatchAll(t, d, input(t, "a.7z", sevenZipSignature), nil) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "a.7z", sevenZipSignature), nil) wantSteps(t, events, []step{{"a.7z", 0, dispatch.Quarantined}}) ev := events[0] if !slices.ContainsFunc(ev.Part.Flags, func(f inspect.Flag) bool { @@ -100,7 +101,7 @@ func TestListingQuarantine(t *testing.T) { sz = fake() d, _, work = archiveDispatcherWith(t, adapter.ArchiveConfig{SevenZip: sz, Version: "7zz 26.5"}) - events = dispatchAll(t, d, input(t, "a.7z", sevenZipSignature), nil) + events = stagestest.DispatchAll(t, d, stagestest.Input(t, "a.7z", sevenZipSignature), nil) wantSteps(t, events, []step{ {"notes.txt", 1, dispatch.NoProcessor}, {"docs/../../evil.txt", 1, dispatch.Quarantined}, @@ -125,7 +126,7 @@ func TestListedMismatch(t *testing.T) { entries[1].CRC, entries[1].HasCRC = 0xdeadbeef, true sz := &fakeSevenZip{listing: sevenzip.Listing{Entries: entries}, contents: contents} d, _, work := archiveDispatcherWith(t, adapter.ArchiveConfig{SevenZip: sz, Version: "7zz 26.5"}) - events := dispatchAll(t, d, input(t, "a.7z", sevenZipSignature), nil) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "a.7z", sevenZipSignature), nil) wantSteps(t, events, []step{{"short.txt", 1, dispatch.Failed}, {"crc.txt", 1, dispatch.Failed}, {"a.7z", 0, dispatch.Prepared}}) for i, want := range []string{"6 bytes written, 100 listed", "CRC-32 "} { if ev := events[i]; !strings.HasPrefix(ev.Reason, want) || ev.Part.Where != "7z entry "+ev.Part.Name { @@ -145,7 +146,7 @@ func TestListedFailures(t *testing.T) { } { sz := &fakeSevenZip{listErr: c.err} d, _, work := archiveDispatcherWith(t, adapter.ArchiveConfig{SevenZip: sz, Version: "7zz 26.5"}) - events := dispatchAll(t, d, input(t, "a.7z", sevenZipSignature), nil) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "a.7z", sevenZipSignature), nil) wantSteps(t, events, []step{{"a.7z", 0, c.outcome}}) if len(sz.extracted) != 0 || !strings.Contains(events[0].Reason, "a 7z archive") && c.outcome == dispatch.Encrypted { t.Errorf("%v: extracted %q, reason %q", c.err, sz.extracted, events[0].Reason) diff --git a/stages/tar_test.go b/stages/internal/adapter/test/tar_test.go similarity index 85% rename from stages/tar_test.go rename to stages/internal/adapter/test/tar_test.go index b7cf2c03..63ebe8e5 100644 --- a/stages/tar_test.go +++ b/stages/internal/adapter/test/tar_test.go @@ -1,4 +1,4 @@ -package stages_test +package adapter_test import ( "bytes" @@ -13,15 +13,17 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/inspect" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) -func inspectFixture(name string) string { return filepath.Join(inspectFixtures, name) } +func inspectFixture(t testing.TB, name string) string { return tooltest.Testdata(t, "inspect", name) } func TestTarStage(t *testing.T) { d, zs, work := archiveDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, inspectFixture("clean.tar"), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, inspectFixture(t, "clean.tar"), func(ev *dispatch.Event) { if ev.Part.Depth == 0 { return } @@ -55,7 +57,7 @@ func TestGzipStage(t *testing.T) { {"unnamed.tgz", "unnamed.tar"}, } { d, zs, work := archiveDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, inspectFixture(c.fixture), nil) + events := stagestest.DispatchAll(t, d, inspectFixture(t, c.fixture), nil) wantSteps(t, events, []step{ {"docs/notes.txt", 2, dispatch.NoProcessor}, {"docs/pixel.png", 2, dispatch.Prepared}, @@ -92,7 +94,7 @@ func TestGzipStem(t *testing.T) { for name, want := range map[string]string{ "notes.txt.gz": "notes.txt", "NOTES.TXT.GZ": "NOTES.TXT", "bundle.TGZ": "bundle.tar", "notes": "notes", } { - events := dispatchAll(t, d, input(t, name, gz("hello "+name+"\n")), nil) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, name, gz("hello "+name+"\n")), nil) if len(events) != 2 || events[0].Part.Name != want || events[0].Part.Where != "gzip content "+want { t.Errorf("%s: %v, want its content named %q", name, steps(events), want) } @@ -119,7 +121,7 @@ func TestTarUnsafe(t *testing.T) { }}, } { d, zs, _ := archiveDispatcher(t, strict) - if ev := dispatchAll(t, d, inspectFixture(c.fixture), nil)[0]; ev.Outcome != dispatch.Quarantined || zs.calls.Load() != 0 { + if ev := stagestest.DispatchAll(t, d, inspectFixture(t, c.fixture), nil)[0]; ev.Outcome != dispatch.Quarantined || zs.calls.Load() != 0 { t.Errorf("%s: %s, the stage called %d times; want quarantined before the stage", c.fixture, ev.Outcome, zs.calls.Load()) } root := t.TempDir() @@ -127,7 +129,7 @@ func TestTarUnsafe(t *testing.T) { if err := os.MkdirAll(work, 0o700); err != nil { t.Fatal(err) } - checkUnsafe(t, testArchiveStage(t, inspect.Options{}), inspectFixture(c.fixture), root, work, c.parts, c.children) + checkUnsafe(t, testArchiveStage(t, inspect.Options{}), inspectFixture(t, c.fixture), root, work, c.parts, c.children) } } @@ -143,7 +145,7 @@ func checkUnsafe(t *testing.T, stage *adapter.ArchiveStage, path, root, work str } var written []string unreadChecks := map[string]inspect.Check{} - events := dispatchAll(t, d, path, func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, path, func(ev *dispatch.Event) { if ev.Part.Depth == 0 || ev.Output != nil { return } @@ -176,7 +178,7 @@ func checkUnsafe(t *testing.T, stage *adapter.ArchiveStage, path, root, work str func TestTarGzipUnsafe(t *testing.T) { d, zs, work := archiveDispatcher(t, inspect.Options{Policy: map[inspect.Check]inspect.Verdict{inspect.ArchiveTraversal: inspect.Quarantine}}) - events := dispatchAll(t, d, inspectFixture("traversal.tar.gz"), nil) + events := stagestest.DispatchAll(t, d, inspectFixture(t, "traversal.tar.gz"), nil) wantSteps(t, events, []step{{"traversal.tar", 1, dispatch.Quarantined}, {"traversal.tar.gz", 0, dispatch.Prepared}}) if ev := events[0]; !slices.ContainsFunc(ev.Part.Flags, func(f inspect.Flag) bool { return f.Check == inspect.ArchiveTraversal }) { t.Errorf("traversal.tar's flags %v", ev.Part.Flags) @@ -190,13 +192,13 @@ func TestTarGzipUnsafe(t *testing.T) { func TestTarBombAsWritten(t *testing.T) { lowered := inspect.Options{BombSize: 1 << 20, BombRatio: 100} d, zs, _ := archiveDispatcher(t, lowered) - if ev := dispatchAll(t, d, inspectFixture("sparse-bomb.tar"), nil)[0]; ev.Outcome != dispatch.Quarantined || zs.calls.Load() != 0 { + if ev := stagestest.DispatchAll(t, d, inspectFixture(t, "sparse-bomb.tar"), nil)[0]; ev.Outcome != dispatch.Quarantined || zs.calls.Load() != 0 { t.Errorf("sparse-bomb.tar: %s, the stage called %d times", ev.Outcome, zs.calls.Load()) } lowered.Policy = map[inspect.Check]inspect.Verdict{inspect.ArchiveBomb: inspect.Proceed} d, _, work := archiveDispatcher(t, lowered) - events := dispatchAll(t, d, inspectFixture("sparse-bomb.tar"), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, inspectFixture(t, "sparse-bomb.tar"), func(ev *dispatch.Event) { if left := files(t, work); len(left) > 0 { t.Errorf("files at the tar's event: %q, want the partial file removed", left) } @@ -208,7 +210,7 @@ func TestTarBombAsWritten(t *testing.T) { func TestGzipBombAsWritten(t *testing.T) { d, _, work := archiveDispatcher(t, inspect.Options{BombSize: 1 << 20, BombRatio: 100}) - events := dispatchAll(t, d, inspectFixture("bomb.tar.gz"), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, inspectFixture(t, "bomb.tar.gz"), func(ev *dispatch.Event) { if left := files(t, work); len(left) > 0 { t.Errorf("files at the stream's event: %q, want the partial file removed", left) } @@ -218,7 +220,7 @@ func TestGzipBombAsWritten(t *testing.T) { wantEmpty(t, work) d, _, work = archiveDispatcher(t, inspect.Options{}) - events = dispatchAll(t, d, inspectFixture("bomb.tar.gz"), nil) + events = stagestest.DispatchAll(t, d, inspectFixture(t, "bomb.tar.gz"), nil) wantSteps(t, events, []step{ {"zeros.bin", 2, dispatch.NoProcessor}, {"bomb.tar", 1, dispatch.Prepared}, @@ -231,29 +233,29 @@ func TestGzipBombAsWritten(t *testing.T) { } func TestArchiveDamaged(t *testing.T) { - gz, err := os.ReadFile(inspectFixture("clean.tar.gz")) + gz, err := os.ReadFile(inspectFixture(t, "clean.tar.gz")) if err != nil { t.Fatal(err) } d, _, work := archiveDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, input(t, "cut.tar.gz", string(gz[:len(gz)-20])), nil) + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "cut.tar.gz", string(gz[:len(gz)-20])), nil) wantSteps(t, events, []step{{"clean.tar", 1, dispatch.Failed}, {"cut.tar.gz", 0, dispatch.Prepared}}) if ev := events[0]; ev.Part.Where != "gzip content clean.tar" || !strings.HasPrefix(ev.Reason, "doesn't decompress") { t.Errorf("cut.tar.gz's content: %q, %q", ev.Part.Where, ev.Reason) } - events = dispatchAll(t, d, input(t, "bad.gz", "\x1f\x8b\x09 not deflate"), nil) + events = stagestest.DispatchAll(t, d, stagestest.Input(t, "bad.gz", "\x1f\x8b\x09 not deflate"), nil) if ev := events[0]; ev.Outcome != dispatch.Failed || !strings.Contains(ev.Reason, "gzip") || !errors.Is(ev.Err, dispatch.ErrRefused) { t.Errorf("bad.gz: %s, %q; want failed, recorded", ev.Outcome, ev.Reason) } wantEmpty(t, work) - whole, err := os.ReadFile(inspectFixture("clean.tar")) + whole, err := os.ReadFile(inspectFixture(t, "clean.tar")) if err != nil { t.Fatal(err) } opts := inspect.Options{Policy: map[inspect.Check]inspect.Verdict{inspect.TarUnreadable: inspect.Proceed}} d, _, work = archiveDispatcher(t, opts) - events = dispatchAll(t, d, input(t, "cut.tar", string(whole[:1030])), nil) + events = stagestest.DispatchAll(t, d, stagestest.Input(t, "cut.tar", string(whole[:1030])), nil) wantSteps(t, events, []step{{"docs/notes.txt", 1, dispatch.Failed}, {"cut.tar", 0, dispatch.Failed}}) if ev := events[0]; !strings.HasPrefix(ev.Reason, "doesn't read") { t.Errorf("docs/notes.txt: %q", ev.Reason) @@ -264,7 +266,7 @@ func TestArchiveDamaged(t *testing.T) { wantEmpty(t, work) } -func wantBomb(t *testing.T, ev dispatched, where string, evidence ...string) { +func wantBomb(t *testing.T, ev stagestest.Dispatched, where string, evidence ...string) { t.Helper() flags := ev.Part.Flags if ev.Part.Where != where || ev.Outcome != dispatch.Quarantined || ev.Part.SHA256 != "" || len(flags) != 1 || diff --git a/stages/text_test.go b/stages/internal/adapter/test/text_test.go similarity index 97% rename from stages/text_test.go rename to stages/internal/adapter/test/text_test.go index cb4c793f..3133a04f 100644 --- a/stages/text_test.go +++ b/stages/internal/adapter/test/text_test.go @@ -1,4 +1,4 @@ -package stages_test +package adapter_test import ( "context" @@ -13,6 +13,7 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) func prepareText(t *testing.T, ctx context.Context, name string, content []byte) (dispatch.Output, string, string, []string, error) { @@ -151,7 +152,7 @@ func TestTextDispatch(t *testing.T) { t.Fatal(err) } var text string - events := dispatchAll(t, d, path, func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, path, func(ev *dispatch.Event) { if ev.Output != nil { b, err := os.ReadFile(ev.Output.Path) if err != nil { diff --git a/stages/video_containers_integration_test.go b/stages/internal/adapter/test/video_containers_integration_test.go similarity index 95% rename from stages/video_containers_integration_test.go rename to stages/internal/adapter/test/video_containers_integration_test.go index 59580bad..be5f9c0a 100644 --- a/stages/video_containers_integration_test.go +++ b/stages/internal/adapter/test/video_containers_integration_test.go @@ -1,6 +1,6 @@ //go:build linux && integration -package stages_test +package adapter_test import ( "bytes" @@ -13,6 +13,7 @@ import ( "github.com/standards-lab/docproc/media" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" "github.com/standards-lab/docproc/tool" ) @@ -65,7 +66,7 @@ func transcode(t *testing.T, ffmpeg *tool.Tool, src, name string, codec []string } func TestVideoContainersReal(t *testing.T) { - src, err := filepath.Abs(scenesFixture) + src, err := filepath.Abs(scenesFixture(t)) if err != nil { t.Fatal(err) } @@ -98,7 +99,7 @@ func TestVideoContainersReal(t *testing.T) { if got := packVersion(t, path); got != c.pack { t.Fatalf("pack header %#x, want %#x", got, c.pack) } - events := dispatchAll(t, d, path, func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, path, func(ev *dispatch.Event) { switch o := ev.Output; { case o == nil: case o.Kind == dispatch.ImageOutput: diff --git a/stages/video_integration_test.go b/stages/internal/adapter/test/video_integration_test.go similarity index 92% rename from stages/video_integration_test.go rename to stages/internal/adapter/test/video_integration_test.go index a0814f6f..6a1a6c58 100644 --- a/stages/video_integration_test.go +++ b/stages/internal/adapter/test/video_integration_test.go @@ -1,6 +1,6 @@ //go:build linux && integration -package stages_test +package adapter_test import ( "encoding/json" @@ -15,24 +15,21 @@ import ( "github.com/standards-lab/docproc/audio" "github.com/standards-lab/docproc/dispatch" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/media" "github.com/standards-lab/docproc/metadata" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" "github.com/standards-lab/docproc/tool" ) -var ( - scenesFixture = filepath.Join("..", "audio", "testdata", "speech-scenes.mkv") - scenesTruth = filepath.Join("..", "audio", "testdata", "speech-scenes.truth.json") -) - func scenesFrames(t *testing.T) []struct { Reason string `json:"reason"` TimeMS int64 `json:"time_ms"` } { t.Helper() - b, err := os.ReadFile(scenesTruth) + b, err := os.ReadFile(scenesTruth(t)) if err != nil { t.Fatal(err) } @@ -104,7 +101,7 @@ func stripAudio(t *testing.T, ffmpeg *tool.Tool, path string) string { func TestVideoStageReal(t *testing.T) { truth := scenesFrames(t) - path, err := filepath.Abs(scenesFixture) + path, err := filepath.Abs(scenesFixture(t)) if err != nil { t.Fatal(err) } @@ -131,7 +128,7 @@ func TestVideoStageReal(t *testing.T) { wantFrames, wantWindows := streamed(t, s, path) d := newDispatcher(t, dispatch.Stages{route.Video: stage}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, path, func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, path, func(ev *dispatch.Event) { o := ev.Output switch { case o == nil: @@ -185,7 +182,7 @@ func TestVideoStageReal(t *testing.T) { sums[name] = append(frames, windows...) only := stripAudio(t, ffmpeg, path) - events = dispatchAll(t, d, only, nil) + events = stagestest.DispatchAll(t, d, only, nil) wantSteps(t, events, []step{{"video-only.mkv", 0, dispatch.Prepared}}) outs = events[0].Outputs if len(outs) < 2 { @@ -225,3 +222,9 @@ func TestVideoStageReal(t *testing.T) { } func secsOf(d time.Duration) string { return strconv.FormatFloat(d.Seconds(), 'f', -1, 64) } + +func scenesFixture(t testing.TB) string { return tooltest.Testdata(t, "audio", "speech-scenes.mkv") } + +func scenesTruth(t testing.TB) string { + return tooltest.Testdata(t, "audio", "speech-scenes.truth.json") +} diff --git a/stages/video_test.go b/stages/internal/adapter/test/video_test.go similarity index 89% rename from stages/video_test.go rename to stages/internal/adapter/test/video_test.go index 08abc58a..f0e038fd 100644 --- a/stages/video_test.go +++ b/stages/internal/adapter/test/video_test.go @@ -1,6 +1,6 @@ //go:build linux -package stages_test +package adapter_test import ( "bytes" @@ -10,7 +10,6 @@ import ( "encoding/hex" "encoding/json" "errors" - "fmt" "image/png" "maps" "os" @@ -29,57 +28,9 @@ import ( "github.com/standards-lab/docproc/media" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) -func mediaStandin(args []string, settings ffSettings) int { - if err := mediaStandinRun(args, settings); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - if settings.Fail != "" { - fmt.Fprintln(os.Stderr, settings.Fail) - return 1 - } - return 0 -} - -func mediaPattern(args []string) string { - if slices.Contains(args, "image2") { - return args[len(args)-1] - } - return "" -} - -func mediaStandinRun(args []string, settings ffSettings) error { - pattern := mediaPattern(args) - var pcm []byte - if slices.Contains(args, "pipe:1") { - n := settings.PCMMS * audio.SampleRate / 1000 - for i := range n { - pcm = binary.LittleEndian.AppendUint16(pcm, uint16(i%30011)) - } - } - var frames []mediatest.Frame - if pattern != "" { - frames = settings.Frames - } - return mediatest.Stream(pcm, frames, - func(at, end int) error { - _, err := os.Stdout.Write(pcm[at:end]) - return err - }, - func(i int) error { - mediatest.Report(i, frames[i]) - if err := mediatest.WritePNG(pattern, i, frames[i]); err != nil { - return err - } - if i == 0 { - time.Sleep(time.Duration(settings.HoldMS) * time.Millisecond) - } - return nil - }) -} - const ( videoProbeBoth = `{"streams":[{"index":0,"codec_type":"video"},{"index":1,"codec_type":"audio"}]}` videoProbeVideo = `{"streams":[{"index":0,"codec_type":"video"}]}` @@ -102,7 +53,7 @@ var videoFrames = []mediatest.Frame{ func testVideoStage(t *testing.T, probe string, req media.Request) (*adapter.VideoStage, *ffStandins) { t.Helper() ffmpeg, ffprobe, standins := standinTools(t, probe) - standins.set(t, func(s *ffSettings) { s.PCMMS, s.Frames = 3000, videoFrames }) + standins.set(t, func(s *stagestest.FFSettings) { s.PCMMS, s.Frames = 3000, videoFrames }) s, err := media.NewStreamer(media.Config{FFmpeg: ffmpeg, FFprobe: ffprobe}) if err != nil { t.Fatal(err) @@ -116,20 +67,20 @@ func videoArgs(t *testing.T, standins *ffStandins) []string { var out []string for _, r := range tooltest.Runs(t, standins.ffmpeg) { if slices.Contains(r.Args, "-protocol_whitelist") { - out = append(out, r.Args[slices.Index(r.Args, "-i")+1], mediaPattern(r.Args)) + out = append(out, r.Args[slices.Index(r.Args, "-i")+1], stagestest.MediaPattern(r.Args)) } } return out } -func videoDispatch(t *testing.T, stages dispatch.Stages, path string) ([]dispatched, string) { +func videoDispatch(t *testing.T, stages dispatch.Stages, path string) ([]stagestest.Dispatched, string) { t.Helper() work := t.TempDir() d, err := dispatch.New(dispatch.Config{Content: dispatch.NewMemoryContent(), Puts: 2, Stages: stages, Index: dispatch.NewMemoryIndex(0), Dir: work}) if err != nil { t.Fatal(err) } - events := collect(t, d.Dispatch(t.Context(), dispatch.Input{Path: path}), func(ev *dispatch.Event) { + events := stagestest.Collect(t, d.Dispatch(t.Context(), dispatch.Input{Path: path}), func(ev *dispatch.Event) { o := ev.Output if o == nil || o.Path == "" { return @@ -311,7 +262,7 @@ func TestVideoNoStream(t *testing.T) { index := dispatch.NewMemoryIndex(0) stage, standins := testVideoStage(t, videoProbeNone, media.Request{}) d := newDispatcher(t, dispatch.Stages{route.Video: stage}, index) - events := dispatchAll(t, d, writeInput(t, "subtitles.mkv", mkvBytes), nil) + events := stagestest.DispatchAll(t, d, writeInput(t, "subtitles.mkv", mkvBytes), nil) wantSteps(t, events, []step{{"subtitles.mkv", 0, dispatch.Failed}}) ev := events[0] if !errors.Is(ev.Err, media.ErrNoMedia) || !errors.Is(ev.Err, dispatch.ErrRefused) || len(ev.Outputs) != 0 { @@ -328,7 +279,9 @@ func TestVideoNoStream(t *testing.T) { func TestVideoFailedRun(t *testing.T) { t.Parallel() stage, standins := testVideoStage(t, videoProbeBoth, media.Request{}) - standins.set(t, func(s *ffSettings) { s.Fail = "[vist#0:0/mpeg4] Error while decoding stream: Invalid data found" }) + standins.set(t, func(s *stagestest.FFSettings) { + s.Fail = "[vist#0:0/mpeg4] Error while decoding stream: Invalid data found" + }) path := writeInput(t, "broken.mkv", mkvBytes) events, work := videoDispatch(t, dispatch.Stages{route.Video: stage}, path) wantSteps(t, events, []step{{"broken.mkv", 0, dispatch.Prepared}}) @@ -344,7 +297,7 @@ func TestVideoFailedRun(t *testing.T) { func TestVideoCancel(t *testing.T) { t.Parallel() stage, standins := testVideoStage(t, videoProbeBoth, media.Request{}) - standins.set(t, func(s *ffSettings) { s.HoldMS = 30000 }) + standins.set(t, func(s *stagestest.FFSettings) { s.HoldMS = 30000 }) path := writeInput(t, "held.mkv", mkvBytes) work := t.TempDir() d, err := dispatch.New(dispatch.Config{Content: dispatch.NewMemoryContent(), Puts: 2, Stages: dispatch.Stages{route.Video: stage}, Index: dispatch.NewMemoryIndex(0), Dir: work}) @@ -395,7 +348,7 @@ func TestVideoNoProcessor(t *testing.T) { t.Parallel() _, standins := testVideoStage(t, videoProbeBoth, media.Request{}) d := newDispatcher(t, dispatch.Stages{}, dispatch.NewMemoryIndex(0)) - events := dispatchAll(t, d, writeInput(t, "talk.webm", webmBytes), nil) + events := stagestest.DispatchAll(t, d, writeInput(t, "talk.webm", webmBytes), nil) wantSteps(t, events, []step{{"talk.webm", 0, dispatch.NoProcessor}}) if ev := events[0]; ev.Part.ContentType.Route != route.Video || ev.Reason != "no stage for route video" { t.Errorf("route %s, reason %q", ev.Part.ContentType.Route, ev.Reason) diff --git a/stages/zip_test.go b/stages/internal/adapter/test/zip_test.go similarity index 90% rename from stages/zip_test.go rename to stages/internal/adapter/test/zip_test.go index 213eb896..8f0c754b 100644 --- a/stages/zip_test.go +++ b/stages/internal/adapter/test/zip_test.go @@ -1,4 +1,4 @@ -package stages_test +package adapter_test import ( "archive/zip" @@ -18,15 +18,13 @@ import ( "github.com/standards-lab/docproc/dispatch" "github.com/standards-lab/docproc/inspect" + "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) -var inspectFixtures = filepath.Join("..", "inspect", "testdata") - -var sevenZipFixtures = filepath.Join("..", "sevenzip", "testdata") - -func sevenZipFixture(name string) string { return filepath.Join(sevenZipFixtures, name) } +func sevenZipFixture(t testing.TB, name string) string { return tooltest.Testdata(t, "sevenzip", name) } const pngBytes = "\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde" @@ -124,7 +122,7 @@ func archiveDispatcherLimited(t *testing.T, cfg adapter.ArchiveConfig, limits di work := t.TempDir() d, err := dispatch.New(dispatch.Config{ Content: dispatch.NewMemoryContent(), Puts: 2, - Stages: dispatch.Stages{route.Archive: zs, route.Vision: standinVisionStage(t, pictureSettings{})}, + Stages: dispatch.Stages{route.Archive: zs, route.Vision: standinVisionStage(t, stagestest.PictureSettings{})}, Index: dispatch.NewMemoryIndex(0), Dir: work, Inspect: cfg.Inspect, @@ -173,7 +171,7 @@ func TestZipStage(t *testing.T) { zent{name: "pictures/again.png", body: pngBytes}, ) d, zs, work := archiveDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, input(t, "bundle.zip", outer), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "bundle.zip", outer), func(ev *dispatch.Event) { if ev.Part.Depth == 0 { return } @@ -207,7 +205,7 @@ func TestZipStage(t *testing.T) { func TestZipEncrypted(t *testing.T) { d, _, work := archiveDispatcher(t, inspect.Options{}) - events := dispatchAll(t, d, filepath.Join(inspectFixtures, "encrypted.zip"), nil) + events := stagestest.DispatchAll(t, d, inspectFixture(t, "encrypted.zip"), nil) wantSteps(t, events, []step{{"notes.txt", 1, dispatch.NoProcessor}, {"secret.txt", 1, dispatch.Encrypted}, {"encrypted.zip", 0, dispatch.Encrypted}}) z := events[2] if !strings.Contains(z.Reason, "1 of 2 entries") || z.Err == nil || z.Children != 2 { @@ -224,7 +222,7 @@ func TestZipBombAsWritten(t *testing.T) { lowered := inspect.Options{BombSize: 1 << 20, BombRatio: 100} d, _, work := archiveDispatcher(t, lowered) - events := dispatchAll(t, d, input(t, "lying.zip", lying), func(ev *dispatch.Event) { + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "lying.zip", lying), func(ev *dispatch.Event) { if left := files(t, work); len(left) > 0 { t.Errorf("files at the ZIP's event: %q, want the partial file removed", left) } @@ -234,21 +232,21 @@ func TestZipBombAsWritten(t *testing.T) { wantEmpty(t, work) d, _, work = archiveDispatcher(t, inspect.Options{}) - events = dispatchAll(t, d, input(t, "lying.zip", lying), nil) + events = stagestest.DispatchAll(t, d, stagestest.Input(t, "lying.zip", lying), nil) wantSteps(t, events, []step{{"zeros.bin", 1, dispatch.Failed}, {"lying.zip", 0, dispatch.Prepared}}) if ev := events[0]; ev.Reason != "8388608 bytes written, 1024 declared" || len(ev.Part.Flags) != 0 { t.Errorf("zeros.bin with no bomb rule: %q, flags %v", ev.Reason, ev.Part.Flags) } wantEmpty(t, work) - bomb := filepath.Join(inspectFixtures, "bomb.zip") + bomb := inspectFixture(t, "bomb.zip") d, zs, _ := archiveDispatcher(t, lowered) - if ev := dispatchAll(t, d, bomb, nil)[0]; ev.Outcome != dispatch.Quarantined || zs.calls.Load() != 0 { + if ev := stagestest.DispatchAll(t, d, bomb, nil)[0]; ev.Outcome != dispatch.Quarantined || zs.calls.Load() != 0 { t.Errorf("bomb.zip at lowered thresholds: %s, the stage called %d times", ev.Outcome, zs.calls.Load()) } lowered.Policy = map[inspect.Check]inspect.Verdict{inspect.ArchiveBomb: inspect.Proceed} d, _, _ = archiveDispatcher(t, lowered) - events = dispatchAll(t, d, bomb, nil) + events = stagestest.DispatchAll(t, d, bomb, nil) wantSteps(t, events, []step{{"zeros.bin", 1, dispatch.Quarantined}, {"bomb.zip", 0, dispatch.Prepared}}) wantBomb(t, events[0], "zip entry zeros.bin") } @@ -267,7 +265,7 @@ func TestZipUnsafeNames(t *testing.T) { {"symlink.zip", []string{"notes.txt"}, map[string]inspect.Check{"passwd": inspect.ArchiveSymlink}}, } { d, zs, _ := archiveDispatcher(t, strict) - if ev := dispatchAll(t, d, filepath.Join(inspectFixtures, c.fixture), nil)[0]; ev.Outcome != dispatch.Quarantined || zs.calls.Load() != 0 { + if ev := stagestest.DispatchAll(t, d, inspectFixture(t, c.fixture), nil)[0]; ev.Outcome != dispatch.Quarantined || zs.calls.Load() != 0 { t.Errorf("%s: %s, the stage called %d times; want quarantined before the stage", c.fixture, ev.Outcome, zs.calls.Load()) } root := t.TempDir() @@ -275,7 +273,7 @@ func TestZipUnsafeNames(t *testing.T) { if err := os.MkdirAll(work, 0o700); err != nil { t.Fatal(err) } - checkUnsafe(t, testArchiveStage(t, inspect.Options{}), filepath.Join(inspectFixtures, c.fixture), root, work, c.parts, c.children) + checkUnsafe(t, testArchiveStage(t, inspect.Options{}), inspectFixture(t, c.fixture), root, work, c.parts, c.children) } } diff --git a/stages/internal/stagestest/build.go b/stages/internal/stagestest/build.go new file mode 100644 index 00000000..429e3dc0 --- /dev/null +++ b/stages/internal/stagestest/build.go @@ -0,0 +1,25 @@ +package stagestest + +import ( + "os/exec" + "testing" + + "github.com/standards-lab/docproc/dispatch" + "github.com/standards-lab/docproc/stages" +) + +// BuiltSet builds the stages over the programs on PATH, failing t on an error or a route missing +// its tools. +func BuiltSet(t *testing.T, opts stages.Options) stages.Set { + t.Helper() + set, err := stages.Build(t.Context(), exec.LookPath, opts) + if err != nil { + t.Fatal(err) + } + for _, row := range set.Rows { + if row.State == dispatch.Missing { + t.Fatalf("route %s: %s", row.Route, row.Reason) + } + } + return set +} diff --git a/stages/internal/stagestest/dispatch.go b/stages/internal/stagestest/dispatch.go new file mode 100644 index 00000000..7ee6e1da --- /dev/null +++ b/stages/internal/stagestest/dispatch.go @@ -0,0 +1,81 @@ +package stagestest + +import ( + "iter" + "os" + "path/filepath" + "testing" + + "github.com/standards-lab/docproc/dispatch" +) + +// Input writes content to a file named name in a temporary directory of t's and returns its path. +func Input(t *testing.T, name, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), name) + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + return path +} + +// Dispatched is a part's final event, with the outputs and warnings that came before it. +type Dispatched struct { + dispatch.Event + Outputs []dispatch.Output + Warnings []dispatch.Warning +} + +type gatherer struct { + pending map[string][]dispatch.Output + warnings map[string][]dispatch.Warning +} + +func (g *gatherer) add(t *testing.T, ev dispatch.Event) (Dispatched, bool) { + t.Helper() + if g.pending == nil { + g.pending = map[string][]dispatch.Output{} + g.warnings = map[string][]dispatch.Warning{} + } + if ev.Warning != nil { + g.warnings[ev.Part.Path] = append(g.warnings[ev.Part.Path], *ev.Warning) + return Dispatched{}, false + } + if ev.Output != nil { + g.pending[ev.Part.Path] = append(g.pending[ev.Part.Path], *ev.Output) + return Dispatched{}, false + } + outputs, warnings := g.pending[ev.Part.Path], g.warnings[ev.Part.Path] + delete(g.pending, ev.Part.Path) + delete(g.warnings, ev.Part.Path) + if len(outputs) != ev.Outputs { + t.Errorf("%s: its event counts %d outputs, after %d output events", ev.Part.Name, ev.Outputs, len(outputs)) + } + return Dispatched{Event: ev, Outputs: outputs, Warnings: warnings}, true +} + +// Collect gathers seq's events into each part's Dispatched, failing t on an error and calling each, +// when it isn't nil, on every event as it comes. +func Collect(t *testing.T, seq iter.Seq2[dispatch.Event, error], each func(*dispatch.Event)) []Dispatched { + t.Helper() + var g gatherer + var events []Dispatched + for ev, err := range seq { + if err != nil { + t.Fatal(err) + } + if each != nil { + each(&ev) + } + if d, ok := g.add(t, ev); ok { + events = append(events, d) + } + } + return events +} + +// DispatchAll dispatches path through d and returns its parts' Dispatched, as [Collect] does. +func DispatchAll(t *testing.T, d *dispatch.Dispatcher, path string, each func(*dispatch.Event)) []Dispatched { + t.Helper() + return Collect(t, d.Dispatch(t.Context(), dispatch.Input{Path: path}), each) +} diff --git a/stages/internal/stagestest/doc.go b/stages/internal/stagestest/doc.go new file mode 100644 index 00000000..18173bfd --- /dev/null +++ b/stages/internal/stagestest/doc.go @@ -0,0 +1,20 @@ +// Package stagestest holds the stand-ins and dispatch helpers that the stages package's tests and +// the adapter package's tests share: the stand-in of every program a stage runs, each over the +// settings its link carries, the stand-in stages built over them, and the helpers that dispatch a +// file and gather each part's events. It builds untagged but for the stand-ins, which build on +// Linux as the tests that run them do, and no released file imports it. +// +// Its exported identifiers: +// +// - [Programs] returns the stand-ins a TestMain passes tooltest.Main. +// - [GSSettings], [PDFToTextSettings], [PDFInfoSettings], [FFSettings], [PictureSettings], +// [SevenZipSettings], and [EnvelopeSettings] are the stand-ins' settings. +// - [MediaPattern] returns the frame pattern of a stand-in ffmpeg's run. +// - [StandinEXIF] returns an EXIF reader over a stand-in magick. +// - [PictureListing] is a stand-in magick's format listing. +// - [StandinPictureStage], [PictureStageOver], and [StandinOfficeStage] return stages over +// stand-ins. +// - [Input] writes a file to dispatch; [DispatchAll] dispatches one and [Collect] gathers a +// sequence of events, each into its part's [Dispatched]. +// - [BuiltSet] builds the stages over the programs on PATH. +package stagestest diff --git a/stages/internal/stagestest/envelope.go b/stages/internal/stagestest/envelope.go new file mode 100644 index 00000000..1311e24f --- /dev/null +++ b/stages/internal/stagestest/envelope.go @@ -0,0 +1,75 @@ +//go:build linux + +package stagestest + +import ( + "cmp" + "fmt" + "os" + "path/filepath" + "syscall" + "time" + + "github.com/standards-lab/docproc/internal/tooltest" +) + +// EnvelopeSettings is a stand-in envelope reader's settings, docproc-onenote's, docproc-mail's, or +// docproc-ooxml's: what it prints, the media it writes, how it exits, and the home it requires. +type EnvelopeSettings struct { + Stdout string `json:"stdout"` + Stderr string `json:"stderr"` + Exit int `json:"exit"` + Media map[string]string `json:"media"` + HoldMS int `json:"hold_ms,omitzero"` + Signal string `json:"signal,omitzero"` + Limit bool `json:"limit,omitzero"` + Home string `json:"home,omitzero"` +} + +func envelopeStandin(minimum string) tooltest.Program { + return func(r tooltest.Run) int { return envelopeRun(r, minimum) } +} + +func envelopeRun(r tooltest.Run, minimum string) int { + var s EnvelopeSettings + if err := r.Settings(&s); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + if home := cmp.Or(os.Getenv("HOME"), s.Home); s.Home != "" && home != s.Home { + fmt.Fprintf(os.Stderr, "mise ERROR Config files in %s are not trusted.\n", filepath.Join(s.Home, ".config", "mise", "config.toml")) + return 1 + } + if len(r.Args) == 1 && r.Args[0] == "--version" { + fmt.Printf("%s\nschema 2\n", minimum) + return 0 + } + if s.Limit { + var l syscall.Rlimit + if err := syscall.Getrlimit(syscall.RLIMIT_AS, &l); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + fmt.Fprintf(os.Stderr, "docproc-onenote: warning: limit: %d\n", l.Cur) + } + time.Sleep(time.Duration(s.HoldMS) * time.Millisecond) + for i, arg := range r.Args { + if arg != "--media" || i+1 >= len(r.Args) { + continue + } + for name, content := range s.Media { + if err := os.WriteFile(filepath.Join(r.Args[i+1], name), []byte(content), 0o644); err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + } + } + fmt.Print(s.Stdout) + fmt.Fprint(os.Stderr, s.Stderr) + if s.Signal != "" { + err := syscall.Exec("/bin/sh", []string{"sh", "-c", "kill -s " + s.Signal + " $$"}, nil) + fmt.Fprintln(os.Stderr, err) + return 2 + } + return s.Exit +} diff --git a/stages/internal/stagestest/media.go b/stages/internal/stagestest/media.go new file mode 100644 index 00000000..353a1ae5 --- /dev/null +++ b/stages/internal/stagestest/media.go @@ -0,0 +1,134 @@ +//go:build linux + +package stagestest + +import ( + "encoding/binary" + "fmt" + "os" + "slices" + "time" + + "github.com/standards-lab/docproc/audio" + "github.com/standards-lab/docproc/internal/mediatest" + "github.com/standards-lab/docproc/internal/tooltest" +) + +// FFSettings is a stand-in ffmpeg's or ffprobe's settings. +type FFSettings struct { + Probe string `json:"probe"` + Decode string `json:"decode,omitzero"` + DecodeMS int `json:"decode_ms,omitzero"` + PCMMS int `json:"pcm_ms,omitzero"` + Frames []mediatest.Frame `json:"frames,omitzero"` + Fail string `json:"fail,omitzero"` + HoldMS int `json:"hold_ms,omitzero"` +} + +func ffprobeStandin(r tooltest.Run) int { + if printFFVersion(r) { + return 0 + } + var settings FFSettings + if err := r.Settings(&settings); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + fmt.Print(settings.Probe) + return 0 +} + +func printFFVersion(r tooltest.Run) bool { + if !slices.Equal(r.Args, []string{"-version"}) { + return false + } + fmt.Printf("%s version n9.0.2 Copyright (c) 2000-2026 the FFmpeg developers\n", r.Program) + return true +} + +func ffmpegStandin(r tooltest.Run) int { + if printFFVersion(r) { + return 0 + } + var settings FFSettings + if err := r.Settings(&settings); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + args := r.Args + if slices.Contains(args, "-protocol_whitelist") { + return mediaStandin(args, settings) + } + if filter := args[slices.Index(args, "-af")+1]; filter != "aresample=16000" { + fmt.Fprintf(os.Stderr, "stand-in: filter %q\n", filter) + return 2 + } + data, err := os.ReadFile(settings.Decode) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + pcm := data[44:] + if settings.DecodeMS > 0 { + pcm = pcm[:2*settings.DecodeMS*audio.SampleRate/1000] + } + if _, err := os.Stdout.Write(pcm); err != nil { + return 2 + } + if settings.DecodeMS > 0 { + fmt.Fprintln(os.Stderr, settings.Fail) + return 1 + } + return 0 +} + +func mediaStandin(args []string, settings FFSettings) int { + if err := mediaStandinRun(args, settings); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + if settings.Fail != "" { + fmt.Fprintln(os.Stderr, settings.Fail) + return 1 + } + return 0 +} + +// MediaPattern returns the frame pattern a stand-in ffmpeg run's args name, or "" for a run +// that writes no frames. +func MediaPattern(args []string) string { + if slices.Contains(args, "image2") { + return args[len(args)-1] + } + return "" +} + +func mediaStandinRun(args []string, settings FFSettings) error { + pattern := MediaPattern(args) + var pcm []byte + if slices.Contains(args, "pipe:1") { + n := settings.PCMMS * audio.SampleRate / 1000 + for i := range n { + pcm = binary.LittleEndian.AppendUint16(pcm, uint16(i%30011)) + } + } + var frames []mediatest.Frame + if pattern != "" { + frames = settings.Frames + } + return mediatest.Stream(pcm, frames, + func(at, end int) error { + _, err := os.Stdout.Write(pcm[at:end]) + return err + }, + func(i int) error { + mediatest.Report(i, frames[i]) + if err := mediatest.WritePNG(pattern, i, frames[i]); err != nil { + return err + } + if i == 0 { + time.Sleep(time.Duration(settings.HoldMS) * time.Millisecond) + } + return nil + }) +} diff --git a/stages/internal/stagestest/office.go b/stages/internal/stagestest/office.go new file mode 100644 index 00000000..b03cc18b --- /dev/null +++ b/stages/internal/stagestest/office.go @@ -0,0 +1,30 @@ +//go:build linux + +package stagestest + +import ( + "testing" + + "github.com/standards-lab/docproc/internal/tooltest" + "github.com/standards-lab/docproc/office" + "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/tool" +) + +// StandinOfficeStage returns an office stage over a stand-in docproc-ooxml with s and a stand-in +// picture stage. +func StandinOfficeStage(t *testing.T, s EnvelopeSettings) *adapter.OfficeStage { + t.Helper() + spec := office.OfficeSpec() + spec.Program = tooltest.Link(t, t.TempDir(), "docproc-ooxml", s) + of, err := tool.NewExec(t.Context(), spec) + if err != nil { + t.Fatal(err) + } + pc := StandinPictureStage(t, PictureListing, 1).Converter() + c, err := office.NewConverter(t.Context(), office.Config{Office: of, Pictures: pc}) + if err != nil { + t.Fatal(err) + } + return adapter.NewOfficeStage(adapter.OfficeConfig{Converter: c, Version: adapter.Versions(of)}) +} diff --git a/stages/internal/stagestest/pdf.go b/stages/internal/stagestest/pdf.go new file mode 100644 index 00000000..a87b5fe9 --- /dev/null +++ b/stages/internal/stagestest/pdf.go @@ -0,0 +1,141 @@ +//go:build linux + +package stagestest + +import ( + "cmp" + "fmt" + "os" + "slices" + "strconv" + "strings" + + "github.com/standards-lab/docproc/internal/tooltest" +) + +// GSSettings is a stand-in gs's settings: the pages it counts, a page it fails on, and one it +// renders empty. +type GSSettings struct { + Pages int `json:"pages"` + Empty int `json:"empty,omitzero"` + Fail int `json:"fail,omitzero"` +} + +func gsStandin(r tooltest.Run) int { + var settings GSSettings + if err := r.Settings(&settings); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + args := r.Args + if len(args) == 1 && args[0] == "--version" { + fmt.Println("10.08.0") + return 0 + } + if slices.Contains(args, "-dNODISPLAY") { + fmt.Println(settings.Pages) + if settings.Pages > 0 && strings.Contains(args[len(args)-1], "/Collection") { + fmt.Println(false) + } + return 0 + } + for _, page := range tooltest.GSPages(args) { + if page == settings.Fail { + fmt.Fprint(os.Stderr, "told to fail") + return 1 + } + if _, err := os.Stdout.Write(tooltest.PNG(fmt.Sprintf("page %d", page))); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + } + return 0 +} + +// PDFToTextSettings is a stand-in pdftotext's settings: a page it reads empty, and the version it +// names. +type PDFToTextSettings struct { + Empty int `json:"empty,omitzero"` + Version string `json:"version,omitzero"` +} + +func pdftotextStandin(r tooltest.Run) int { + var settings PDFToTextSettings + if err := r.Settings(&settings); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + args := r.Args + if len(args) == 1 && args[0] == "-v" { + fmt.Fprintf(os.Stderr, "pdftotext version %s\n", cmp.Or(settings.Version, "26.10.0")) + return 0 + } + page, err := strconv.Atoi(args[slices.Index(args, "-f")+1]) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + text := fmt.Sprintf("page %d\f", page) + if page == settings.Empty { + text = " \n\f" + } + if _, err := os.Stdout.WriteString(text); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + return 0 +} + +// PDFInfoSettings is a stand-in pdfinfo's settings: what it prints for each mode, or the exit and +// stderr it fails with. +type PDFInfoSettings struct { + Info map[string]string `json:"info,omitzero"` + Exit int `json:"exit,omitzero"` + Stderr string `json:"stderr,omitzero"` +} + +func pdfinfoStandin(r tooltest.Run) int { + var settings PDFInfoSettings + if err := r.Settings(&settings); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + if len(r.Args) == 1 && r.Args[0] == "-v" { + fmt.Fprintln(os.Stderr, "pdfinfo version 26.10.0") + return 0 + } + if settings.Exit != 0 { + fmt.Fprint(os.Stderr, settings.Stderr) + return settings.Exit + } + mode := "summary" + switch { + case slices.Contains(r.Args, "-custom"): + mode = "custom" + case slices.Contains(r.Args, "-meta"): + mode = "meta" + } + if _, err := os.Stdout.WriteString(settings.Info[mode]); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + return 0 +} + +func qpdfStandin(r tooltest.Run) int { + if len(r.Args) == 1 && r.Args[0] == "--version" { + fmt.Println("qpdf version 11.9.0") + return 0 + } + fmt.Fprintf(os.Stderr, "qpdf stand-in: unexpected arguments %q\n", r.Args) + return 2 +} + +func pdfdetachStandin(r tooltest.Run) int { + if len(r.Args) == 1 && r.Args[0] == "-v" { + fmt.Fprintln(os.Stderr, "pdfdetach version 26.10.0") + return 99 + } + fmt.Fprintf(os.Stderr, "pdfdetach stand-in: unexpected arguments %q\n", r.Args) + return 2 +} diff --git a/stages/internal/stagestest/picture.go b/stages/internal/stagestest/picture.go new file mode 100644 index 00000000..dc7675db --- /dev/null +++ b/stages/internal/stagestest/picture.go @@ -0,0 +1,146 @@ +//go:build linux + +package stagestest + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "os" + "slices" + "strings" + "testing" + + "github.com/standards-lab/docproc/internal/tooltest" + "github.com/standards-lab/docproc/picture" + "github.com/standards-lab/docproc/route" + "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/tool" +) + +// PictureSettings is a stand-in magick's settings: its format listing, the pages it converts, and +// the EXIF it reports by its input's SHA-256, or fails with. +type PictureSettings struct { + Formats string `json:"formats"` + Pages int `json:"pages"` + EXIF map[string]string `json:"exif,omitzero"` + EXIFFail string `json:"exif_fail,omitzero"` +} + +// PictureListing is a magick format listing that reads AVIF, HEIC, and WebP. +const PictureListing = ` Format Module Mode Description +------------------------------------------------------------------------------- + AVIF HEIC rw+ AV1 Image File Format (1.23.6) + HEIC HEIC rw+ High Efficiency Image Format (1.23.6) + WEBP* WEBP rw+ WebP Image Format (libwebp 1.6.0 [0210]) +` + +func pictureStandin(r tooltest.Run) int { + var settings PictureSettings + if err := r.Settings(&settings); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + args := r.Args + switch { + case len(args) == 1 && args[0] == "-version": + fmt.Println("Version: ImageMagick 7.1.2-34 Q16-HDRI x86_64 https://imagemagick.org") + return 0 + case slices.Equal(args, []string{"-list", "format", "null:"}): + fmt.Print(settings.Formats) + return 0 + case len(args) > 0 && args[len(args)-1] == "info:": + return pictureEXIFStandin(settings) + case len(args) < 2: + fmt.Fprintf(os.Stderr, "stand-in: unexpected arguments %q\n", args) + return 2 + } + _, out, _ := strings.Cut(args[len(args)-1], ":") + if !slices.Contains(args, "+adjoin") { + if err := os.WriteFile(out, []byte(route.PNGSignature+args[0]), 0o644); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + return 0 + } + for i := range settings.Pages { + if err := os.WriteFile(fmt.Sprintf(out, i), []byte(fmt.Sprintf("%spage %d", route.PNGSignature, i+1)), 0o644); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + } + return 0 +} + +func sofficeStandin(r tooltest.Run) int { + if len(r.Args) == 1 && r.Args[0] == "--version" { + fmt.Println("LibreOffice 26.8.1.1 680(Build:1)") + return 0 + } + fmt.Fprintf(os.Stderr, "stand-in: unexpected arguments %q\n", r.Args) + return 2 +} + +const noEXIF = "1 1\n" + +func pictureEXIFStandin(settings PictureSettings) int { + input, err := io.ReadAll(os.Stdin) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + if settings.EXIFFail != "" { + fmt.Fprint(os.Stderr, settings.EXIFFail) + return 1 + } + sum := sha256.Sum256(input) + out, ok := settings.EXIF[hex.EncodeToString(sum[:])] + if !ok { + out = noEXIF + } + fmt.Print(out) + return 0 +} + +// StandinEXIF returns a stand-in magick with settings and an EXIF reader over it. +func StandinEXIF(t *testing.T, settings PictureSettings) (*tool.Tool, *picture.EXIFReader) { + t.Helper() + spec := picture.MagickSpec() + spec.Program = tooltest.Link(t, t.TempDir(), "magick", settings) + mg, err := tool.NewExec(t.Context(), spec) + if err != nil { + t.Fatal(err) + } + r, err := picture.NewEXIFReader(picture.Config{Magick: mg}) + if err != nil { + t.Fatal(err) + } + return mg, r +} + +// StandinPictureStage returns a picture stage over a stand-in magick listing listing and converting +// pages pages. +func StandinPictureStage(t *testing.T, listing string, pages int) *adapter.PictureStage { + t.Helper() + return PictureStageOver(t, PictureSettings{Formats: listing, Pages: pages}) +} + +// PictureStageOver returns a picture stage over a stand-in magick with settings and a stand-in +// soffice. +func PictureStageOver(t *testing.T, settings PictureSettings) *adapter.PictureStage { + t.Helper() + mg, r := StandinEXIF(t, settings) + spec := picture.LibreOfficeSpec() + spec.Program = tooltest.Link(t, t.TempDir(), "soffice", struct{}{}) + lo, err := tool.NewExec(t.Context(), spec) + if err != nil { + t.Fatal(err) + } + c, err := picture.NewConverter(t.Context(), picture.Config{Magick: mg, LibreOffice: lo}) + if err != nil { + t.Fatal(err) + } + s := adapter.NewPictureStage(adapter.PictureConfig{Converter: c, EXIF: r, Version: adapter.Versions(mg)}) + return s +} diff --git a/stages/internal/stagestest/programs.go b/stages/internal/stagestest/programs.go new file mode 100644 index 00000000..26776d1e --- /dev/null +++ b/stages/internal/stagestest/programs.go @@ -0,0 +1,30 @@ +//go:build linux + +package stagestest + +import ( + "github.com/standards-lab/docproc/email" + "github.com/standards-lab/docproc/internal/tooltest" + "github.com/standards-lab/docproc/office" + "github.com/standards-lab/docproc/onenote" +) + +// Programs returns the stand-ins a test package's TestMain passes [tooltest.Main], one for each +// program the stages run. +func Programs() map[string]tooltest.Program { + return map[string]tooltest.Program{ + "gs": gsStandin, + "qpdf": qpdfStandin, + "pdfdetach": pdfdetachStandin, + "pdftotext": pdftotextStandin, + "pdfinfo": pdfinfoStandin, + "ffmpeg": ffmpegStandin, + "ffprobe": ffprobeStandin, + "magick": pictureStandin, + "soffice": sofficeStandin, + "7zz": sevenZipStandin, + "docproc-onenote": envelopeStandin(onenote.OneNoteMinimum), + "docproc-ooxml": envelopeStandin(office.OfficeMinimum), + "docproc-mail": envelopeStandin(email.MailMinimum), + } +} diff --git a/stages/internal/stagestest/sevenzip.go b/stages/internal/stagestest/sevenzip.go new file mode 100644 index 00000000..5cde29cf --- /dev/null +++ b/stages/internal/stagestest/sevenzip.go @@ -0,0 +1,42 @@ +//go:build linux + +package stagestest + +import ( + "fmt" + "os" + + "github.com/standards-lab/docproc/internal/tooltest" + "github.com/standards-lab/docproc/sevenzip" +) + +// SevenZipSettings is a stand-in 7zz's settings: the listing it prints, the content it extracts, +// and whether the archive's headers are encrypted. +type SevenZipSettings struct { + Listing string `json:"listing"` + Content []byte `json:"content"` + EncryptedHeaders bool `json:"encrypted_headers"` +} + +func sevenZipStandin(r tooltest.Run) int { + var s SevenZipSettings + if err := r.Settings(&s); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + switch { + case len(r.Args) > 0 && r.Args[0] == "l" && s.EncryptedHeaders: + fmt.Fprintf(os.Stderr, "ERROR: %s : Cannot open encrypted archive. Wrong password?\n", r.Args[len(r.Args)-1]) + return 2 + case len(r.Args) > 0 && r.Args[0] == "l": + fmt.Print(s.Listing) + return 0 + case len(r.Args) > 0 && r.Args[0] == "e": + if _, err := os.Stdout.Write(s.Content); err != nil { + return 2 + } + return 0 + } + fmt.Printf("\n7-Zip (z) %s (x64) : Copyright (c) 1999-2026 Igor Pavlov : 2026-11-06\n", sevenzip.SevenZipMinimum) + return 0 +} diff --git a/stages/main_test.go b/stages/main_test.go deleted file mode 100644 index 33b4a8f6..00000000 --- a/stages/main_test.go +++ /dev/null @@ -1,61 +0,0 @@ -//go:build linux - -package stages_test - -import ( - "fmt" - "os" - "testing" - - "github.com/standards-lab/docproc/email" - "github.com/standards-lab/docproc/internal/tooltest" - "github.com/standards-lab/docproc/office" - "github.com/standards-lab/docproc/onenote" -) - -func TestMain(m *testing.M) { - tooltest.Main(m, map[string]tooltest.Program{ - "gs": gsStandin, - "qpdf": qpdfStandin, - "pdfdetach": pdfdetachStandin, - "pdftotext": pdftotextStandin, - "pdfinfo": pdfinfoStandin, - "ffmpeg": ffmpegStandin, - "ffprobe": ffprobeStandin, - "magick": pictureStandin, - "soffice": sofficeStandin, - "7zz": sevenZipStandin, - "docproc-onenote": envelopeStandin(onenote.OneNoteMinimum), - "docproc-ooxml": envelopeStandin(office.OfficeMinimum), - "docproc-mail": envelopeStandin(email.MailMinimum), - }) -} - -func qpdfStandin(r tooltest.Run) int { - if len(r.Args) == 1 && r.Args[0] == "--version" { - fmt.Println("qpdf version 11.9.0") - return 0 - } - fmt.Fprintf(os.Stderr, "qpdf stand-in: unexpected arguments %q\n", r.Args) - return 2 -} - -func pdfdetachStandin(r tooltest.Run) int { - if len(r.Args) == 1 && r.Args[0] == "-v" { - fmt.Fprintln(os.Stderr, "pdfdetach version 26.10.0") - return 99 - } - fmt.Fprintf(os.Stderr, "pdfdetach stand-in: unexpected arguments %q\n", r.Args) - return 2 -} - -func wantPanic(t *testing.T, want string, build func()) { - t.Helper() - defer func() { - t.Helper() - if got := recover(); got != want { - t.Errorf("panic %v, want %q", got, want) - } - }() - build() -} diff --git a/stages/picture_test.go b/stages/picture_test.go deleted file mode 100644 index f3b5df09..00000000 --- a/stages/picture_test.go +++ /dev/null @@ -1,187 +0,0 @@ -//go:build linux - -package stages_test - -import ( - "fmt" - "maps" - "os" - "slices" - "strconv" - "strings" - "testing" - - "github.com/standards-lab/docproc/dispatch" - "github.com/standards-lab/docproc/internal/tooltest" - "github.com/standards-lab/docproc/picture" - "github.com/standards-lab/docproc/route" - "github.com/standards-lab/docproc/stages/internal/adapter" - "github.com/standards-lab/docproc/tool" -) - -type pictureSettings struct { - Formats string `json:"formats"` - Pages int `json:"pages"` - EXIF map[string]string `json:"exif,omitzero"` - EXIFFail string `json:"exif_fail,omitzero"` -} - -const pictureListing = ` Format Module Mode Description -------------------------------------------------------------------------------- - AVIF HEIC rw+ AV1 Image File Format (1.23.6) - HEIC HEIC rw+ High Efficiency Image Format (1.23.6) - WEBP* WEBP rw+ WebP Image Format (libwebp 1.6.0 [0210]) -` - -const ( - pictureTIFF = "II*\x00\x08\x00\x00\x00" + "a stand-in TIFF" - pictureHEIC = "\x00\x00\x00\x18ftypheic\x00\x00\x00\x00mif1heic" - pictureWebP = "RIFF\x10\x00\x00\x00WEBPVP8 " - pictureAVIF = "\x00\x00\x00\x18ftypavif\x00\x00\x00\x00mif1avif" -) - -func pictureStandin(r tooltest.Run) int { - var settings pictureSettings - if err := r.Settings(&settings); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - args := r.Args - switch { - case len(args) == 1 && args[0] == "-version": - fmt.Println("Version: ImageMagick 7.1.2-34 Q16-HDRI x86_64 https://imagemagick.org") - return 0 - case slices.Equal(args, []string{"-list", "format", "null:"}): - fmt.Print(settings.Formats) - return 0 - case len(args) > 0 && args[len(args)-1] == "info:": - return pictureEXIFStandin(settings) - case len(args) < 2: - fmt.Fprintf(os.Stderr, "stand-in: unexpected arguments %q\n", args) - return 2 - } - _, out, _ := strings.Cut(args[len(args)-1], ":") - if !slices.Contains(args, "+adjoin") { - if err := os.WriteFile(out, []byte(route.PNGSignature+args[0]), 0o644); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - return 0 - } - for i := range settings.Pages { - if err := os.WriteFile(fmt.Sprintf(out, i), []byte(fmt.Sprintf("%spage %d", route.PNGSignature, i+1)), 0o644); err != nil { - fmt.Fprintln(os.Stderr, err) - return 2 - } - } - return 0 -} - -func sofficeStandin(r tooltest.Run) int { - if len(r.Args) == 1 && r.Args[0] == "--version" { - fmt.Println("LibreOffice 26.8.1.1 680(Build:1)") - return 0 - } - fmt.Fprintf(os.Stderr, "stand-in: unexpected arguments %q\n", r.Args) - return 2 -} - -func standinPictureStage(t *testing.T, listing string, pages int) *adapter.PictureStage { - t.Helper() - return pictureStageOver(t, pictureSettings{Formats: listing, Pages: pages}) -} - -func pictureStageOver(t *testing.T, settings pictureSettings) *adapter.PictureStage { - t.Helper() - mg, r := standinEXIF(t, settings) - spec := picture.LibreOfficeSpec() - spec.Program = tooltest.Link(t, t.TempDir(), "soffice", struct{}{}) - lo, err := tool.NewExec(t.Context(), spec) - if err != nil { - t.Fatal(err) - } - c, err := picture.NewConverter(t.Context(), picture.Config{Magick: mg, LibreOffice: lo}) - if err != nil { - t.Fatal(err) - } - s := adapter.NewPictureStage(adapter.PictureConfig{Converter: c, EXIF: r, Version: adapter.Versions(mg)}) - return s -} - -func TestPictureStageTIFFPages(t *testing.T) { - t.Parallel() - d := newDispatcher(t, dispatch.Stages{route.VisionConverted: standinPictureStage(t, pictureListing, 3)}, dispatch.NewMemoryIndex(0)) - var held []string - events := dispatchAll(t, d, input(t, "scan.tif", pictureTIFF), func(ev *dispatch.Event) { - if ev.Output != nil { - b, err := os.ReadFile(ev.Output.Path) - if err != nil { - t.Fatal(err) - } - held = append(held, string(b)) - } - }) - wantSteps(t, events, []step{{"scan.tif", 0, dispatch.Prepared}}) - outputs := events[0].Outputs - if len(outputs) != 3 { - t.Fatalf("%d outputs, want 3", len(outputs)) - } - for i, o := range outputs { - n := strconv.Itoa(i + 1) - want := map[string]string{"from": "tiff", "page": n, "count": "3"} - if o.Kind != dispatch.ImageOutput || o.Name != "page "+n || o.MediaType != "image/png" || !maps.Equal(o.Meta, want) { - t.Errorf("output %d: %s %q %s %v; want an image named %q, meta %v", i, o.Kind, o.Name, o.MediaType, o.Meta, "page "+n, want) - } - if held[i] != route.PNGSignature+"page "+n { - t.Errorf("output %d holds %q, want page %s", i, held[i], n) - } - } -} - -func TestPictureStageRasters(t *testing.T) { - t.Parallel() - d := newDispatcher(t, dispatch.Stages{route.VisionConverted: standinPictureStage(t, pictureListing, 0)}, dispatch.NewMemoryIndex(0)) - for name, c := range map[string]struct { - content string - kind route.Kind - }{ - "x.heic": {pictureHEIC, route.HEIC}, - "x.webp": {pictureWebP, route.WebP}, - "x.avif": {pictureAVIF, route.AVIF}, - } { - var held string - events := dispatchAll(t, d, input(t, name, c.content), func(ev *dispatch.Event) { - if ev.Output != nil { - b, err := os.ReadFile(ev.Output.Path) - if err != nil { - t.Fatal(err) - } - held = string(b) - } - }) - wantSteps(t, events, []step{{name, 0, dispatch.Prepared}}) - o := events[0].Outputs - if len(o) != 1 || o[0].Kind != dispatch.ImageOutput || o[0].Name != "picture" || !maps.Equal(o[0].Meta, map[string]string{"from": string(c.kind)}) { - t.Errorf("%s: outputs %+v", name, o) - } - if coder := string(c.kind) + ":"; !strings.HasPrefix(held, route.PNGSignature+coder) || !strings.HasSuffix(held, "[0]") { - t.Errorf("%s: PNG holds %q; want its first image read through %s", name, held, coder) - } - } -} - -func TestPictureNoReader(t *testing.T) { - t.Parallel() - d := newDispatcher(t, dispatch.Stages{route.VisionConverted: standinPictureStage(t, "", 0)}, dispatch.NewMemoryIndex(0)) - for name, c := range map[string]struct{ content, what string }{ - "x.heic": {pictureHEIC, "a HEIC"}, - "x.webp": {pictureWebP, "a WebP"}, - "x.avif": {pictureAVIF, "an AVIF"}, - } { - ev := dispatchAll(t, d, input(t, name, c.content), nil)[0] - want := "no processor yet: picture: " + name + " is " + c.what + " picture: no magick reader" - if ev.Outcome != dispatch.NoProcessor || !strings.Contains(ev.Reason, want) { - t.Errorf("%s: %s, %q; want no processor, %q", name, ev.Outcome, ev.Reason, want) - } - } -} diff --git a/stages/test/classify_test.go b/stages/test/classify_test.go new file mode 100644 index 00000000..8c57a89c --- /dev/null +++ b/stages/test/classify_test.go @@ -0,0 +1,140 @@ +//go:build linux + +package stages_test + +import ( + "errors" + "fmt" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/standards-lab/docproc/dispatch" + "github.com/standards-lab/docproc/internal/cli" + "github.com/standards-lab/docproc/internal/tooltest" + "github.com/standards-lab/docproc/route" + "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/stagestest" +) + +const oneSection = "\xe4\x52\x5c\x7b\x8c\xd8\xa7\x4d\xae\xb1\x53\x78\xd0\x29\x96\xd3\x00\x00\x00\x00\x00\x00\x00\x00" + +const testMemory = tooltest.Memory + +func onenoteOnly() []route.Route { + return slices.DeleteFunc(stages.Routes(), func(r route.Route) bool { return r == route.OneNote }) +} + +func standinSet(t *testing.T, s stagestest.EnvelopeSettings, opts stages.Options) (stages.Set, string) { + t.Helper() + link := tooltest.Link(t, t.TempDir(), "docproc-onenote", s) + lookup := func(program string) (string, error) { + if program == "docproc-onenote" { + return link, nil + } + return "", fmt.Errorf("%s isn't here", program) + } + set, err := stages.Build(t.Context(), lookup, opts) + if err != nil { + t.Fatal(err) + } + for _, tl := range set.Tools { + if tl.Program == "docproc-onenote" && tl.Error != "" { + t.Fatalf("the stand-in docproc-onenote was refused: %s", tl.Error) + } + } + return set, link +} + +func dispatchSet(t *testing.T, set stages.Set) (stagestest.Dispatched, bool) { + t.Helper() + index := dispatch.NewMemoryIndex(0) + d, err := dispatch.New(dispatch.Config{ + Content: dispatch.NewMemoryContent(), Puts: 2, Stages: set.Stages, Inspect: set.Inspect, Index: index, Dir: t.TempDir(), + }) + if err != nil { + t.Fatal(err) + } + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "in.one", oneSection), nil) + ev := events[len(events)-1] + _, recorded, err := index.Lookup(t.Context(), dispatch.Key{SHA256: ev.Part.SHA256, Stage: ev.Stage}) + if err != nil { + t.Fatal(err) + } + return ev, recorded +} + +func TestClassification(t *testing.T) { + t.Parallel() + const notebook = `{"line":"notebook","schema":"2","input":"section","name":"S"}` + "\n" + refused := func(reason string) stagestest.EnvelopeSettings { + return stagestest.EnvelopeSettings{Stderr: "docproc-onenote: error: " + reason + "\n", Exit: 3} + } + for _, c := range []struct { + name string + settings stagestest.EnvelopeSettings + outcome dispatch.Outcome + recorded bool + reason string + }{ + {"exit 3, refused", refused("not a OneNote section, notebook, or package"), dispatch.Failed, true, "refused"}, + {"exit 4, the tool's fault", stagestest.EnvelopeSettings{Stdout: notebook, Stderr: "docproc-onenote: error: internal\n", Exit: 4}, dispatch.Failed, true, "failed: internal"}, + {"SIGSEGV", stagestest.EnvelopeSettings{Stdout: notebook, Signal: "SEGV"}, dispatch.Failed, true, "killed by SIGSEGV under a 8 GiB memory bound"}, + {"SIGABRT", stagestest.EnvelopeSettings{Stdout: notebook, Signal: "ABRT"}, dispatch.Failed, true, "killed by SIGABRT under a 8 GiB memory bound"}, + {"SIGBUS", stagestest.EnvelopeSettings{Signal: "BUS"}, dispatch.Failed, true, "killed by SIGBUS under a 8 GiB memory bound"}, + {"SIGFPE", stagestest.EnvelopeSettings{Signal: "FPE"}, dispatch.Failed, true, "killed by SIGFPE under a 8 GiB memory bound"}, + {"SIGILL", stagestest.EnvelopeSettings{Signal: "ILL"}, dispatch.Failed, true, "killed by SIGILL under a 8 GiB memory bound"}, + {"its own time bound", stagestest.EnvelopeSettings{HoldMS: 60000}, dispatch.Failed, true, "timed out"}, + {"output that doesn't parse", stagestest.EnvelopeSettings{Stdout: notebook + `{"line":"page","id":` + "\n"}, dispatch.Failed, true, ""}, + {"exit 1, not written", stagestest.EnvelopeSettings{Stderr: "docproc-onenote: error: writing stdout: Broken pipe\n", Exit: 1}, dispatch.Failed, false, "not written"}, + {"exit 2, usage", stagestest.EnvelopeSettings{Stderr: "docproc-onenote: error: unknown option\n", Exit: 2}, dispatch.Failed, false, "usage"}, + {"SIGKILL docproc didn't send", stagestest.EnvelopeSettings{Stdout: notebook, Signal: "KILL"}, dispatch.Failed, false, "killed by SIGKILL"}, + {"SIGTERM docproc didn't send", stagestest.EnvelopeSettings{Signal: "TERM"}, dispatch.Failed, false, "killed by SIGTERM"}, + {"encrypted", refused("encrypted section (a password-protected section); remove its password in OneNote first"), dispatch.Encrypted, true, "encrypted"}, + {"read elsewhere", refused(cli.TableOfContents), dispatch.ReadElsewhere, true, cli.TableOfContents}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + set, _ := standinSet(t, c.settings, stages.Options{Exclude: onenoteOnly(), Memory: testMemory, Idle: 5 * time.Second}) + ev, recorded := dispatchSet(t, set) + if ev.Outcome != c.outcome || recorded != c.recorded || !strings.Contains(ev.Reason, c.reason) { + t.Errorf("%s, recorded %t, %q; want %s, recorded %t, %q in the reason", ev.Outcome, recorded, ev.Reason, c.outcome, c.recorded, c.reason) + } + if c.outcome == dispatch.Failed && errors.Is(ev.Err, dispatch.ErrRefused) != c.recorded { + t.Errorf("err %v: ErrRefused %t, want %t", ev.Err, errors.Is(ev.Err, dispatch.ErrRefused), c.recorded) + } + }) + } +} + +func TestClassificationNoBound(t *testing.T) { + t.Parallel() + set, link := standinSet(t, stagestest.EnvelopeSettings{Signal: "ABRT"}, stages.Options{Exclude: onenoteOnly()}) + ev, recorded := dispatchSet(t, set) + if ev.Outcome != dispatch.Failed || !recorded || !strings.Contains(ev.Reason, "killed by SIGABRT") || strings.Contains(ev.Reason, "memory bound") { + t.Errorf("%s, recorded %t, %q", ev.Outcome, recorded, ev.Reason) + } + if runs := tooltest.Runs(t, link); len(runs) != 2 || runs[1].Program != "docproc-onenote" { + t.Errorf("runs %+v", runs) + } +} + +func TestBuildBounds(t *testing.T) { + t.Parallel() + hold := stagestest.EnvelopeSettings{HoldMS: 1500, Stdout: `{"line":"notebook","schema":"2","input":"section","name":"S"}` + "\n"} + set, _ := standinSet(t, hold, stages.Options{Exclude: onenoteOnly(), Timeout: 200 * time.Millisecond}) + if ev, _ := dispatchSet(t, set); ev.Outcome != dispatch.Prepared { + t.Errorf("a stream tool under a unit run's Timeout: %s, %q; want prepared", ev.Outcome, ev.Reason) + } + set, _ = standinSet(t, hold, stages.Options{Exclude: onenoteOnly(), Idle: 200 * time.Millisecond}) + if ev, recorded := dispatchSet(t, set); ev.Outcome != dispatch.Failed || !recorded || !strings.Contains(ev.Reason, "timed out") { + t.Errorf("a stream tool under Idle: %s, recorded %t, %q; want failed, recorded, timed out", ev.Outcome, recorded, ev.Reason) + } + set, _ = standinSet(t, stagestest.EnvelopeSettings{Limit: true, Stdout: hold.Stdout}, stages.Options{Exclude: onenoteOnly(), Memory: testMemory}) + ev, _ := dispatchSet(t, set) + if want := (dispatch.Warning{Tool: "docproc-onenote", Where: "limit", What: strconv.Itoa(testMemory)}); !slices.Contains(ev.Warnings, want) { + t.Errorf("the bounded stand-in's warnings %+v, want its RLIMIT_AS the bound", ev.Warnings) + } +} diff --git a/stages/fixtures_integration_test.go b/stages/test/fixtures_integration_test.go similarity index 80% rename from stages/fixtures_integration_test.go rename to stages/test/fixtures_integration_test.go index 650668e6..6cd59e6a 100644 --- a/stages/fixtures_integration_test.go +++ b/stages/test/fixtures_integration_test.go @@ -14,22 +14,30 @@ import ( "github.com/standards-lab/docproc/inspect" "github.com/standards-lab/docproc/internal/goldentest" "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) const fixturesGolden = "testdata/fixtures.tsv" +var moduleRoot = filepath.Join("..", "..") + +func moduleRel(path string) string { + rel, _ := filepath.Rel(moduleRoot, path) + return filepath.ToSlash(rel) +} + func committedFixtures(t *testing.T) []string { t.Helper() var paths []string - err := filepath.WalkDir("..", func(path string, d fs.DirEntry, err error) error { + err := filepath.WalkDir(moduleRoot, func(path string, d fs.DirEntry, err error) error { switch { case err != nil: return err - case d.IsDir() && (path == filepath.Join("..", "tools") || strings.HasPrefix(d.Name(), ".") && path != ".."): + case d.IsDir() && (path == filepath.Join(moduleRoot, "tools") || strings.HasPrefix(d.Name(), ".") && path != moduleRoot): return filepath.SkipDir case d.IsDir() || !slices.Contains(strings.Split(filepath.ToSlash(path), "/"), "testdata"): return nil - case path == filepath.Join("..", "stages", fixturesGolden): + case path == filepath.Join(moduleRoot, "stages", "test", fixturesGolden): return nil } paths = append(paths, path) @@ -51,8 +59,7 @@ func copyFixtures(t *testing.T, fixtures []string) map[string]string { if err != nil { t.Fatal(err) } - rel, _ := strings.CutPrefix(filepath.ToSlash(path), "../") - dst := filepath.Join(root, filepath.FromSlash(rel)) + dst := filepath.Join(root, filepath.FromSlash(moduleRel(path))) if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { t.Fatal(err) } @@ -65,7 +72,7 @@ func copyFixtures(t *testing.T, fixtures []string) map[string]string { } func TestEveryFixture(t *testing.T) { - set := builtSet(t, stages.Options{Inspect: inspect.Options{BombRatio: 100, BombSize: 64 << 20, Entries: 10000}}) + set := stagestest.BuiltSet(t, stages.Options{Inspect: inspect.Options{BombRatio: 100, BombSize: 64 << 20, Entries: 10000}}) d, err := dispatch.New(dispatch.Config{ Stages: set.Stages, Inspect: set.Inspect, Index: dispatch.NewMemoryIndex(0), Content: dispatch.NewMemoryContent(), Puts: 4, Dir: t.TempDir(), @@ -99,7 +106,7 @@ func TestEveryFixture(t *testing.T) { } var b strings.Builder for _, path := range fixtures { - rel, _ := strings.CutPrefix(filepath.ToSlash(path), "../") + rel := moduleRel(path) outcome, ok := got[rel] if !ok { t.Errorf("%s: no event of its own", rel) diff --git a/stages/test/identity_integration_test.go b/stages/test/identity_integration_test.go new file mode 100644 index 00000000..cce22be1 --- /dev/null +++ b/stages/test/identity_integration_test.go @@ -0,0 +1,59 @@ +//go:build linux && integration + +package stages_test + +import ( + "slices" + "strings" + "testing" + "time" + + "github.com/standards-lab/docproc/audio" + "github.com/standards-lab/docproc/dispatch" + "github.com/standards-lab/docproc/document" + "github.com/standards-lab/docproc/inspect" + "github.com/standards-lab/docproc/media" + "github.com/standards-lab/docproc/picture" + "github.com/standards-lab/docproc/route" + "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" +) + +func TestBuiltIdentities(t *testing.T) { + set := stagestest.BuiltSet(t, stages.Options{}) + lines := map[string]string{} + for _, tl := range set.Tools { + lines[tl.Program] = tl.Version + } + for r, needs := range adapter.Needs() { + row := set.Rows[slices.IndexFunc(set.Rows, func(row dispatch.Row) bool { return row.Route == r })] + var want []string + for _, program := range needs { + want = append(want, lines[program]) + } + if len(want) > 0 && (row.Stage.Version != strings.Join(want, ", ") || row.Tools != row.Stage.Version) { + t.Errorf("%s: version %q, tools %q; want %q", r, row.Stage.Version, row.Tools, strings.Join(want, ", ")) + } + if row.Stage.Name == "" || len(row.Stage.Config) != 64 || set.Stages[r].Identity() != row.Stage { + t.Errorf("%s: identity %v", r, row.Stage) + } + } + bounded := stagestest.BuiltSet(t, stages.Options{Timeout: time.Hour, Idle: time.Hour, Concurrency: 3}) + changed := stagestest.BuiltSet(t, stages.Options{ + Document: document.ImagesRequest{DPI: 300}, Picture: picture.Request{Density: 300}, + Audio: audio.Request{Limit: 20 * time.Second}, Video: media.Request{MaxSide: 768}, + Inspect: inspect.Options{BombRatio: 100, BombSize: 1 << 20}, + }) + for i, row := range set.Rows { + if bounded.Rows[i].Stage != row.Stage { + t.Errorf("%s: a run bound changed the identity", row.Route) + } + switch row.Route { + case route.Document, route.VisionConverted, route.Audio, route.Video, route.Archive: + if changed.Rows[i].Stage.Config == row.Stage.Config { + t.Errorf("%s: a request left the identity's config alone", row.Route) + } + } + } +} diff --git a/stages/identity_test.go b/stages/test/identity_test.go similarity index 80% rename from stages/identity_test.go rename to stages/test/identity_test.go index f320ac39..08a134bc 100644 --- a/stages/identity_test.go +++ b/stages/test/identity_test.go @@ -10,22 +10,23 @@ import ( "github.com/standards-lab/docproc/internal/tooltest" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) func TestBuiltConfigs(t *testing.T) { t.Parallel() links := map[string]string{ - "gs": tooltest.Link(t, t.TempDir(), "gs", gsSettings{}), + "gs": tooltest.Link(t, t.TempDir(), "gs", stagestest.GSSettings{}), "qpdf": tooltest.Link(t, t.TempDir(), "qpdf", nil), "pdfdetach": tooltest.Link(t, t.TempDir(), "pdfdetach", nil), - "pdftotext": tooltest.Link(t, t.TempDir(), "pdftotext", pdftotextSettings{}), - "pdfinfo": tooltest.Link(t, t.TempDir(), "pdfinfo", pdfinfoSettings{}), - "docproc-mail": tooltest.Link(t, t.TempDir(), "docproc-mail", onenoteSettings{}), - "docproc-onenote": tooltest.Link(t, t.TempDir(), "docproc-onenote", onenoteSettings{}), - "7zz": tooltest.Link(t, t.TempDir(), "7zz", sevenZipSettings{}), - "ffmpeg": tooltest.Link(t, t.TempDir(), "ffmpeg", ffSettings{}), - "ffprobe": tooltest.Link(t, t.TempDir(), "ffprobe", ffSettings{}), - "magick": tooltest.Link(t, t.TempDir(), "magick", pictureSettings{}), + "pdftotext": tooltest.Link(t, t.TempDir(), "pdftotext", stagestest.PDFToTextSettings{}), + "pdfinfo": tooltest.Link(t, t.TempDir(), "pdfinfo", stagestest.PDFInfoSettings{}), + "docproc-mail": tooltest.Link(t, t.TempDir(), "docproc-mail", stagestest.EnvelopeSettings{}), + "docproc-onenote": tooltest.Link(t, t.TempDir(), "docproc-onenote", stagestest.EnvelopeSettings{}), + "7zz": tooltest.Link(t, t.TempDir(), "7zz", stagestest.SevenZipSettings{}), + "ffmpeg": tooltest.Link(t, t.TempDir(), "ffmpeg", stagestest.FFSettings{}), + "ffprobe": tooltest.Link(t, t.TempDir(), "ffprobe", stagestest.FFSettings{}), + "magick": tooltest.Link(t, t.TempDir(), "magick", stagestest.PictureSettings{}), } lookup := func(program string) (string, error) { if link, ok := links[program]; ok { @@ -38,8 +39,8 @@ func TestBuiltConfigs(t *testing.T) { t.Fatal(err) } got := map[route.Route]string{ - route.Office: standinOfficeStage(t, onenoteSettings{}).Identity().Config, - route.VisionConverted: standinPictureStage(t, pictureListing, 1).Identity().Config, + route.Office: stagestest.StandinOfficeStage(t, stagestest.EnvelopeSettings{}).Identity().Config, + route.VisionConverted: stagestest.StandinPictureStage(t, stagestest.PictureListing, 1).Identity().Config, } for _, row := range set.Rows { if row.State == dispatch.Wired { diff --git a/stages/test/main_test.go b/stages/test/main_test.go new file mode 100644 index 00000000..2772d9dc --- /dev/null +++ b/stages/test/main_test.go @@ -0,0 +1,14 @@ +//go:build linux + +package stages_test + +import ( + "testing" + + "github.com/standards-lab/docproc/internal/tooltest" + "github.com/standards-lab/docproc/stages/internal/stagestest" +) + +func TestMain(m *testing.M) { + tooltest.Main(m, stagestest.Programs()) +} diff --git a/stages/stages_test.go b/stages/test/stages_test.go similarity index 78% rename from stages/stages_test.go rename to stages/test/stages_test.go index cbbca8f1..93f2d203 100644 --- a/stages/stages_test.go +++ b/stages/test/stages_test.go @@ -18,7 +18,7 @@ import ( "github.com/standards-lab/docproc/picture" "github.com/standards-lab/docproc/route" "github.com/standards-lab/docproc/stages" - "github.com/standards-lab/docproc/stages/internal/adapter" + "github.com/standards-lab/docproc/stages/internal/stagestest" ) func TestParseRoutes(t *testing.T) { @@ -99,13 +99,13 @@ func TestBuildDocumentNeedsPDFToText(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() links := map[string]string{ - "gs": tooltest.Link(t, t.TempDir(), "gs", gsSettings{}), + "gs": tooltest.Link(t, t.TempDir(), "gs", stagestest.GSSettings{}), "qpdf": tooltest.Link(t, t.TempDir(), "qpdf", nil), "pdfdetach": tooltest.Link(t, t.TempDir(), "pdfdetach", nil), - "pdfinfo": tooltest.Link(t, t.TempDir(), "pdfinfo", pdfinfoSettings{}), + "pdfinfo": tooltest.Link(t, t.TempDir(), "pdfinfo", stagestest.PDFInfoSettings{}), } if c.version != "" { - links["pdftotext"] = tooltest.Link(t, t.TempDir(), "pdftotext", pdftotextSettings{Version: c.version}) + links["pdftotext"] = tooltest.Link(t, t.TempDir(), "pdftotext", stagestest.PDFToTextSettings{Version: c.version}) } lookup := func(program string) (string, error) { if link, ok := links[program]; ok { @@ -150,7 +150,7 @@ func TestBuildShim(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() home := t.TempDir() - link := tooltest.Link(t, t.TempDir(), "docproc-onenote", onenoteSettings{Home: home}) + link := tooltest.Link(t, t.TempDir(), "docproc-onenote", stagestest.EnvelopeSettings{Home: home}) lookup := func(program string) (string, error) { if program == "docproc-onenote" { return link, nil @@ -210,29 +210,3 @@ func TestBuildRefuses(t *testing.T) { } } } - -func TestStagesPanic(t *testing.T) { - t.Parallel() - for want, build := range map[string]func(){ - "stages: DocumentConfig.Preparer is nil": func() { adapter.NewDocumentStage(adapter.DocumentConfig{Version: "gs"}) }, - "stages: DocumentConfig.QPDF is nil": func() { - adapter.NewDocumentStage(adapter.DocumentConfig{Preparer: &document.Preparer{}, Version: "gs"}) - }, - "stages: DocumentConfig.PDFDetach is nil": func() { - adapter.NewDocumentStage(adapter.DocumentConfig{Preparer: &document.Preparer{}, QPDF: &fakeQPDF{}}) - }, - "stages: DocumentConfig.PDFInfo is nil": func() { - adapter.NewDocumentStage(adapter.DocumentConfig{Preparer: &document.Preparer{}, QPDF: &fakeQPDF{}, PDFDetach: &fakeDetach{}}) - }, - "stages: OfficeConfig.Converter is nil": func() { adapter.NewOfficeStage(adapter.OfficeConfig{Version: "x"}) }, - "stages: PictureConfig.Converter is nil": func() { adapter.NewPictureStage(adapter.PictureConfig{Version: "x"}) }, - "stages: EmailConfig.Reader is nil": func() { adapter.NewEmailStage(adapter.EmailConfig{Version: "x"}) }, - "stages: OneNoteConfig.Reader is nil": func() { adapter.NewOneNoteStage(adapter.OneNoteConfig{Version: "x"}) }, - "stages: ArchiveConfig.SevenZip is nil": func() { adapter.NewArchiveStage(adapter.ArchiveConfig{Version: "x"}) }, - "stages: AudioConfig.Splitter is nil": func() { adapter.NewAudioStage(adapter.AudioConfig{Version: "x"}) }, - "stages: VideoConfig.Streamer is nil": func() { adapter.NewVideoStage(adapter.VideoConfig{Version: "x"}) }, - "stages: archive stage: no version": func() { adapter.NewArchiveStage(adapter.ArchiveConfig{SevenZip: &fakeSevenZip{}}) }, - } { - wantPanic(t, want, build) - } -} diff --git a/stages/test/testdata/fixtures.tsv b/stages/test/testdata/fixtures.tsv new file mode 100644 index 00000000..33a06794 --- /dev/null +++ b/stages/test/testdata/fixtures.tsv @@ -0,0 +1,257 @@ +audio/test/testdata/README.md text prepared +audio/test/testdata/speech-gain.wav audio prepared +audio/test/testdata/speech-levels.truth.json text prepared +audio/test/testdata/speech-noise.wav audio prepared +audio/test/testdata/speech-scenes.ffprobe.json text prepared +audio/test/testdata/speech-scenes.mkv video prepared +audio/test/testdata/speech-scenes.truth.json text prepared +audio/test/testdata/speech-tagged.ffprobe.json text prepared +audio/test/testdata/speech-tagged.mp3 audio prepared +audio/test/testdata/speech-truncated.mp3 audio prepared +audio/test/testdata/speech.flac audio prepared +audio/test/testdata/speech.truth.txt text prepared +audio/test/testdata/windows-v0.9.0.txt text prepared +cmd/docproc/internal/app/testdata/fallback.txt text prepared +cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/956e499b5e521771b3584eaa57b659d9bae2cebed6c9b9a66b1bde9ef33ab03e.html text prepared +cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f04403b02fdd738868d5c683872140987b664d03f8a29aec13ee88f3b271d014.html text prepared +cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f90199938cc629a711b4ce5a349f5606d96acde9ef44abfab0d167826f4b60df.html text prepared +cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/index.html text prepared +cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f.html text prepared +cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/index.html text prepared +cmd/docproc/internal/report/testdata/rundir/content/25/2556d072121b94e2a6cc4cf8e43f73b1b5030ec3ab59d0b2235aa2faa16b4abe text prepared +cmd/docproc/internal/report/testdata/rundir/content/43/4371149be76808ede2e39736bd07c9a9209f1d6207cfb3a530c7a2e84ab1a5a2 vision prepared +cmd/docproc/internal/report/testdata/rundir/content/49/49f0a3b0c2b2a69f7619a5fdb670aec4c66c547ab78d4c13c41bf822a2f63a9d text prepared +cmd/docproc/internal/report/testdata/rundir/content/6a/6aadf10b8e2ff279d1eebcbf84f605f00f4827d82dad47f55b468b8ddf3d44c4 vision prepared +cmd/docproc/internal/report/testdata/rundir/content/6d/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f text prepared +cmd/docproc/internal/report/testdata/rundir/content/91/91f139ca1c19593f32cba1f5a21ceeb556eeeaf3a208c97c5927e7a098878b19 text prepared +cmd/docproc/internal/report/testdata/rundir/content/98/98dc2ca63ef11a81aec72f3f4adbfc46f76775d1bffeb97ea5d95efd53afab36 text prepared +cmd/docproc/internal/report/testdata/rundir/content/a1/a1c904eedaa045e589e7662e41362498fee1eac19cb75247d86187f0e8b829f9 text prepared +cmd/docproc/internal/report/testdata/rundir/content/e5/e5e635c7a7480ef91dd5f6503c2d4f7ed429a7df4f3c80350de6e1c95d7c8d38 text prepared +cmd/docproc/internal/report/testdata/rundir/content/e7/e700dfd0455f7fc65a5847792900801c945226449672700b65e1fa8da633a0e7 audio prepared +cmd/docproc/internal/report/testdata/rundir/quarantine/d9f0fc6ffd4c580cd4bd9f56d16d92f1e74ab539039d33d33ab256c8995b5b9d unrouted no processor yet +cmd/docproc/internal/report/testdata/rundir/rundir.json text prepared +cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/manifest.json text prepared +cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/record.jsonl text prepared +cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/manifest.json text prepared +cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/record.jsonl text prepared +dispatch/test/testdata/dispatch.jsonl text prepared +dispatch/test/testdata/log.jsonl text prepared +document/test/testdata/README.md text prepared +document/test/testdata/attachments/attachments.pdf document prepared +document/test/testdata/attachments/generate.go text prepared +document/test/testdata/clean.pdf document prepared +document/test/testdata/clean.typ text prepared +document/test/testdata/clean/page-1.txt text prepared +document/test/testdata/clean/page-2.txt text prepared +document/test/testdata/clean/page-3.txt text prepared +document/test/testdata/clean/page-4.txt text prepared +document/test/testdata/clean/page-5.txt text prepared +document/test/testdata/clean/page-6.txt text prepared +document/test/testdata/degraded.pdf document prepared +document/test/testdata/degraded/page-1.txt text seen +document/test/testdata/degraded/page-2.txt text seen +document/test/testdata/degraded/page-3.txt text seen +document/test/testdata/degraded/page-4.txt text seen +document/test/testdata/degraded/page-5.txt text seen +document/test/testdata/degraded/page-6.txt text seen +document/test/testdata/degraded/page-7.txt text seen +document/test/testdata/degraded/page-8.txt text seen +document/test/testdata/degraded/page-9.txt text seen +document/test/testdata/forms/acroform.json text prepared +document/test/testdata/forms/acroform.pdf document prepared +document/test/testdata/forms/generate.go text prepared +document/test/testdata/forms/signed.json text prepared +document/test/testdata/forms/signed.pdf document prepared +document/test/testdata/generate.sh text prepared +document/test/testdata/info/clean.custom.txt text prepared +document/test/testdata/info/clean.meta.xml text prepared +document/test/testdata/info/clean.summary.txt text prepared +document/test/testdata/info/generate.go text prepared +document/test/testdata/info/info.custom.txt text prepared +document/test/testdata/info/info.meta.xml text prepared +document/test/testdata/info/info.pdf document prepared +document/test/testdata/info/info.summary.txt text prepared +document/test/testdata/malformed/compacted-syntax.pdf document prepared +document/test/testdata/portfolio/generate.go text prepared +document/test/testdata/portfolio/portfolio.pdf document prepared +document/test/testdata/scanned.pdf document prepared +document/test/testdata/scanned/page-1.txt text prepared +document/test/testdata/scanned/page-2.txt text prepared +document/test/testdata/scanned/page-3.txt text prepared +document/test/testdata/scanned/page-4.txt text prepared +document/test/testdata/scanned/page-5.txt text prepared +document/test/testdata/scanned/page-6.txt text prepared +document/test/testdata/scanned/page-7.txt text prepared +email/test/testdata/README.md text prepared +email/test/testdata/built/eml/office-attachments.eml nested prepared +email/test/testdata/built/msg/office-attachments.msg nested prepared +inspect/test/testdata/README.md text prepared +inspect/test/testdata/absolute.tar archive prepared +inspect/test/testdata/absolute.zip archive prepared +inspect/test/testdata/bomb.tar.gz archive prepared +inspect/test/testdata/bomb.zip archive prepared +inspect/test/testdata/clean.tar archive prepared +inspect/test/testdata/clean.tar.gz archive prepared +inspect/test/testdata/declared-bomb.zip archive quarantined +inspect/test/testdata/device.tar archive prepared +inspect/test/testdata/encrypted.xlsx office failed +inspect/test/testdata/encrypted.zip archive encrypted +inspect/test/testdata/generate.go text prepared +inspect/test/testdata/hardlink.tar archive prepared +inspect/test/testdata/hyperlink.docx office prepared +inspect/test/testdata/invoice.pdf.exe unrouted no processor yet +inspect/test/testdata/javascript.pdf document prepared +inspect/test/testdata/macro-latin1.docm office prepared +inspect/test/testdata/macro-utf16.docm office prepared +inspect/test/testdata/macro.docm office prepared +inspect/test/testdata/mismatch.pdf vision prepared +inspect/test/testdata/polyglot.jpg vision prepared +inspect/test/testdata/polyglot.png vision prepared +inspect/test/testdata/script-latin1.svg vision-converted prepared +inspect/test/testdata/script-utf16.svg vision-converted prepared +inspect/test/testdata/script.svg vision-converted prepared +inspect/test/testdata/sparse-bomb.tar archive quarantined +inspect/test/testdata/symlink.tar archive prepared +inspect/test/testdata/symlink.zip archive prepared +inspect/test/testdata/traversal.tar archive prepared +inspect/test/testdata/traversal.tar.gz archive prepared +inspect/test/testdata/traversal.zip archive prepared +inspect/test/testdata/unnamed.tgz archive prepared +office/test/testdata/README.md text prepared +office/test/testdata/golden/pictures.sha256 text prepared +office/test/testdata/legacy/generate.sh text prepared +office/test/testdata/legacy/generated/MANIFEST text prepared +office/test/testdata/legacy/generated/bullets.libreoffice.ppt office prepared +office/test/testdata/legacy/generated/cells.libreoffice.xls office prepared +office/test/testdata/legacy/generated/charts.libreoffice.doc office prepared +office/test/testdata/legacy/generated/comments.libreoffice.doc office prepared +office/test/testdata/legacy/generated/drawings.libreoffice.xls office prepared +office/test/testdata/legacy/generated/formulas.libreoffice.xls office seen +office/test/testdata/legacy/generated/lists.libreoffice.doc office prepared +office/test/testdata/legacy/generated/media.libreoffice.doc office prepared +office/test/testdata/legacy/generated/merges.libreoffice.xls office prepared +office/test/testdata/legacy/generated/notes.libreoffice.doc office prepared +office/test/testdata/legacy/generated/sections.libreoffice.doc office prepared +office/test/testdata/legacy/generated/slide-objects.libreoffice.ppt office prepared +office/test/testdata/legacy/generated/slides.libreoffice.ppt office prepared +office/test/testdata/legacy/generated/tables.libreoffice.doc office prepared +office/test/testdata/legacy/real/SampleSS.truth.json text prepared +office/test/testdata/legacy/real/SampleSS.xls office prepared +office/test/testdata/legacy/real/basic_test_ppt_file.ppt office prepared +office/test/testdata/legacy/real/basic_test_ppt_file.truth.json text prepared +office/test/testdata/legacy/real/simple-table.doc office prepared +office/test/testdata/legacy/real/simple-table.truth.json text prepared +office/test/testdata/licenses/poi.LICENSE text prepared +office/test/testdata/licenses/poi.NOTICE text prepared +office/test/testdata/odf/drawing.fodg text prepared +office/test/testdata/odf/encrypt.py text prepared +office/test/testdata/odf/generate.sh text prepared +office/test/testdata/odf/generated/MANIFEST text prepared +office/test/testdata/odf/generated/cells.libreoffice.ods office prepared +office/test/testdata/odf/generated/cells.libreoffice.ots office prepared +office/test/testdata/odf/generated/drawing.odg office prepared +office/test/testdata/odf/generated/drawing.otg office prepared +office/test/testdata/odf/generated/encrypted.odt office encrypted +office/test/testdata/odf/generated/slides.libreoffice.odp office prepared +office/test/testdata/odf/generated/slides.libreoffice.otp office prepared +office/test/testdata/odf/generated/tables.libreoffice.odt office prepared +office/test/testdata/odf/generated/tables.libreoffice.ott office prepared +office/test/testdata/ooxml/bullets.libreoffice.pptx office prepared +office/test/testdata/ooxml/cells.libreoffice.xlsx office prepared +office/test/testdata/ooxml/charts.libreoffice.docx office prepared +office/test/testdata/ooxml/comments.libreoffice.docx office prepared +office/test/testdata/ooxml/drawings.libreoffice.xlsx office prepared +office/test/testdata/ooxml/formulas.libreoffice.xlsx office prepared +office/test/testdata/ooxml/lists.libreoffice.docx office prepared +office/test/testdata/ooxml/media.libreoffice.docx office prepared +office/test/testdata/ooxml/merges.libreoffice.xlsx office prepared +office/test/testdata/ooxml/notes.libreoffice.docx office prepared +office/test/testdata/ooxml/sections.libreoffice.docx office prepared +office/test/testdata/ooxml/slide-objects.libreoffice.pptx office prepared +office/test/testdata/ooxml/slides.libreoffice.pptx office prepared +office/test/testdata/ooxml/tables.libreoffice.docx office seen +office/test/testdata/ooxml/with-drawing.xlsx office prepared +office/test/testdata/ooxml/word-with-attachments.docx office prepared +office/test/testdata/pictures/generate.sh text prepared +office/test/testdata/pictures/tiff.docx office prepared +office/test/testdata/rtf/hidden-entry.rtf office prepared +office/test/testdata/rtf/memo.rtf office prepared +office/test/testdata/wordperfect/testWordPerfect_6_61.wpd office prepared +office/test/testdata/xlsb/protected_passtika.xlsb office encrypted +office/test/testdata/xlsb/testVarious.xlsb office prepared +picture/test/testdata/README.md text prepared +picture/test/testdata/animated.avif vision-converted prepared +picture/test/testdata/animated.webp vision-converted prepared +picture/test/testdata/exif-gps.jpg vision prepared +picture/test/testdata/exif-gps.magick.txt text prepared +picture/test/testdata/exif-none.magick.txt text prepared +picture/test/testdata/exif-none.png vision prepared +picture/test/testdata/exif-zoneless.heic vision-converted prepared +picture/test/testdata/exif-zoneless.magick.txt text prepared +picture/test/testdata/ink.svg vision-converted prepared +picture/test/testdata/lzw-gray.tiff vision-converted prepared +picture/test/testdata/oriented.webp vision-converted prepared +picture/test/testdata/pages.tiff vision-converted prepared +picture/test/testdata/scanned-g4.tiff vision-converted prepared +picture/test/testdata/script-bearing.svg vision-converted prepared +picture/test/testdata/shapes.svg vision-converted prepared +picture/test/testdata/two-images.heic vision-converted prepared +rundir/test/testdata/rundir/content/b6/b688c8947f876ba9580749960b0c70076ea223eec8dcb9d57d4c51c9c9dd2906 text prepared +rundir/test/testdata/rundir/content/d3/d31031c3593a9da13ff7013b8cf20bf3120903467fac751975e0260c8560c6c7 text prepared +rundir/test/testdata/rundir/quarantine/4efe525c159bafa28a6ba4e08aa028a846bdebb78bf4b33c11e959a37b481bca unrouted no processor yet +rundir/test/testdata/rundir/rundir.json text seen +rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/manifest.json text prepared +rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/record.jsonl text prepared +rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/manifest.json text prepared +rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/record.jsonl text prepared +rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/manifest.json text prepared +rundir/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/record.jsonl text prepared +sevenzip/test/testdata/README.md text prepared +sevenzip/test/testdata/commons-compress/LICENSE.txt text prepared +sevenzip/test/testdata/commons-compress/NOTICE.txt text prepared +sevenzip/test/testdata/commons-compress/bla.deflate64.7z archive prepared +sevenzip/test/testdata/commons-compress/bzip2-zip.zip archive prepared +sevenzip/test/testdata/commons-compress/lorem-ipsum-deflate64.zip archive prepared +sevenzip/test/testdata/commons-compress/lorem-ipsum-implode.zip archive prepared +sevenzip/test/testdata/commons-compress/test-method-xz.zip archive prepared +sevenzip/test/testdata/generate.go text prepared +sevenzip/test/testdata/generated/absolute.7z archive prepared +sevenzip/test/testdata/generated/absolute.cab archive prepared +sevenzip/test/testdata/generated/bomb.7z archive prepared +sevenzip/test/testdata/generated/bomb.bz2 archive prepared +sevenzip/test/testdata/generated/bomb.cab archive prepared +sevenzip/test/testdata/generated/bomb.xz archive prepared +sevenzip/test/testdata/generated/bomb.zst archive prepared +sevenzip/test/testdata/generated/clean.7z archive prepared +sevenzip/test/testdata/generated/clean.tar.zst archive prepared +sevenzip/test/testdata/generated/clean.tbz2 archive prepared +sevenzip/test/testdata/generated/clean.txz archive prepared +sevenzip/test/testdata/generated/concatenated.txt.bz2 archive prepared +sevenzip/test/testdata/generated/declared-bomb.zst archive quarantined +sevenzip/test/testdata/generated/device.7z archive prepared +sevenzip/test/testdata/generated/encrypted-headers.7z archive encrypted +sevenzip/test/testdata/generated/encrypted.7z archive encrypted +sevenzip/test/testdata/generated/linebreak.cab archive prepared +sevenzip/test/testdata/generated/mixed.7z archive prepared +sevenzip/test/testdata/generated/multiblock.7z archive prepared +sevenzip/test/testdata/generated/notebook.cab archive prepared +sevenzip/test/testdata/generated/notes.txt.bz2 archive prepared +sevenzip/test/testdata/generated/notes.txt.xz archive prepared +sevenzip/test/testdata/generated/symlink.7z archive prepared +sevenzip/test/testdata/generated/traversal.7z archive prepared +sevenzip/test/testdata/generated/traversal.cab archive prepared +sevenzip/test/testdata/libarchive/COPYING text prepared +sevenzip/test/testdata/libarchive/test_read_format_rar.rar archive prepared +sevenzip/test/testdata/libarchive/test_read_format_rar5_compressed.rar archive prepared +sevenzip/test/testdata/libarchive/test_read_format_rar5_encrypted.rar archive encrypted +sevenzip/test/testdata/libarchive/test_read_format_rar5_encrypted_filenames.rar archive encrypted +sevenzip/test/testdata/libarchive/test_read_format_rar5_multiarchive.part01.rar archive no processor yet +sevenzip/test/testdata/libarchive/test_read_format_rar5_symlink.rar archive prepared +sevenzip/test/testdata/libarchive/test_read_format_rar_encryption_header.rar archive encrypted +sevenzip/test/testdata/libarchive/test_read_format_rar_encryption_partially.rar archive encrypted +sevenzip/test/testdata/libarchive/test_read_format_rar_multivolume.part0001.rar archive no processor yet +sevenzip/test/testdata/libarchive/test_read_format_zip_lzma.zipx archive prepared +sevenzip/test/testdata/libarchive/test_read_format_zip_ppmd8.zipx archive prepared +sevenzip/test/testdata/libarchive/test_read_format_zip_zstd.zipx archive prepared +tool/test/testdata/README.md text prepared +tool/test/testdata/tone.wav audio prepared diff --git a/stages/testdata/fixtures.tsv b/stages/testdata/fixtures.tsv deleted file mode 100644 index 28e80f93..00000000 --- a/stages/testdata/fixtures.tsv +++ /dev/null @@ -1,257 +0,0 @@ -audio/testdata/README.md text prepared -audio/testdata/speech-gain.wav audio prepared -audio/testdata/speech-levels.truth.json text prepared -audio/testdata/speech-noise.wav audio prepared -audio/testdata/speech-scenes.ffprobe.json text prepared -audio/testdata/speech-scenes.mkv video prepared -audio/testdata/speech-scenes.truth.json text prepared -audio/testdata/speech-tagged.ffprobe.json text prepared -audio/testdata/speech-tagged.mp3 audio prepared -audio/testdata/speech-truncated.mp3 audio prepared -audio/testdata/speech.flac audio prepared -audio/testdata/speech.truth.txt text prepared -audio/testdata/windows-v0.9.0.txt text prepared -cmd/docproc/internal/app/testdata/fallback.txt text prepared -cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/956e499b5e521771b3584eaa57b659d9bae2cebed6c9b9a66b1bde9ef33ab03e.html text prepared -cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f04403b02fdd738868d5c683872140987b664d03f8a29aec13ee88f3b271d014.html text prepared -cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f90199938cc629a711b4ce5a349f5606d96acde9ef44abfab0d167826f4b60df.html text prepared -cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/index.html text prepared -cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f.html text prepared -cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/index.html text prepared -cmd/docproc/internal/report/testdata/rundir/content/25/2556d072121b94e2a6cc4cf8e43f73b1b5030ec3ab59d0b2235aa2faa16b4abe text prepared -cmd/docproc/internal/report/testdata/rundir/content/43/4371149be76808ede2e39736bd07c9a9209f1d6207cfb3a530c7a2e84ab1a5a2 vision prepared -cmd/docproc/internal/report/testdata/rundir/content/49/49f0a3b0c2b2a69f7619a5fdb670aec4c66c547ab78d4c13c41bf822a2f63a9d text prepared -cmd/docproc/internal/report/testdata/rundir/content/6a/6aadf10b8e2ff279d1eebcbf84f605f00f4827d82dad47f55b468b8ddf3d44c4 vision prepared -cmd/docproc/internal/report/testdata/rundir/content/6d/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f text prepared -cmd/docproc/internal/report/testdata/rundir/content/91/91f139ca1c19593f32cba1f5a21ceeb556eeeaf3a208c97c5927e7a098878b19 text prepared -cmd/docproc/internal/report/testdata/rundir/content/98/98dc2ca63ef11a81aec72f3f4adbfc46f76775d1bffeb97ea5d95efd53afab36 text prepared -cmd/docproc/internal/report/testdata/rundir/content/a1/a1c904eedaa045e589e7662e41362498fee1eac19cb75247d86187f0e8b829f9 text prepared -cmd/docproc/internal/report/testdata/rundir/content/e5/e5e635c7a7480ef91dd5f6503c2d4f7ed429a7df4f3c80350de6e1c95d7c8d38 text prepared -cmd/docproc/internal/report/testdata/rundir/content/e7/e700dfd0455f7fc65a5847792900801c945226449672700b65e1fa8da633a0e7 audio prepared -cmd/docproc/internal/report/testdata/rundir/quarantine/d9f0fc6ffd4c580cd4bd9f56d16d92f1e74ab539039d33d33ab256c8995b5b9d unrouted no processor yet -cmd/docproc/internal/report/testdata/rundir/rundir.json text prepared -cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/manifest.json text prepared -cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/record.jsonl text prepared -cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/manifest.json text prepared -cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/record.jsonl text prepared -dispatch/testdata/dispatch.jsonl text prepared -dispatch/testdata/log.jsonl text prepared -document/testdata/README.md text prepared -document/testdata/attachments/attachments.pdf document prepared -document/testdata/attachments/generate.go text prepared -document/testdata/clean.pdf document prepared -document/testdata/clean.typ text prepared -document/testdata/clean/page-1.txt text prepared -document/testdata/clean/page-2.txt text prepared -document/testdata/clean/page-3.txt text prepared -document/testdata/clean/page-4.txt text prepared -document/testdata/clean/page-5.txt text prepared -document/testdata/clean/page-6.txt text prepared -document/testdata/degraded.pdf document prepared -document/testdata/degraded/page-1.txt text seen -document/testdata/degraded/page-2.txt text seen -document/testdata/degraded/page-3.txt text seen -document/testdata/degraded/page-4.txt text seen -document/testdata/degraded/page-5.txt text seen -document/testdata/degraded/page-6.txt text seen -document/testdata/degraded/page-7.txt text seen -document/testdata/degraded/page-8.txt text seen -document/testdata/degraded/page-9.txt text seen -document/testdata/forms/acroform.json text prepared -document/testdata/forms/acroform.pdf document prepared -document/testdata/forms/generate.go text prepared -document/testdata/forms/signed.json text prepared -document/testdata/forms/signed.pdf document prepared -document/testdata/generate.sh text prepared -document/testdata/info/clean.custom.txt text prepared -document/testdata/info/clean.meta.xml text prepared -document/testdata/info/clean.summary.txt text prepared -document/testdata/info/generate.go text prepared -document/testdata/info/info.custom.txt text prepared -document/testdata/info/info.meta.xml text prepared -document/testdata/info/info.pdf document prepared -document/testdata/info/info.summary.txt text prepared -document/testdata/malformed/compacted-syntax.pdf document prepared -document/testdata/portfolio/generate.go text prepared -document/testdata/portfolio/portfolio.pdf document prepared -document/testdata/scanned.pdf document prepared -document/testdata/scanned/page-1.txt text prepared -document/testdata/scanned/page-2.txt text prepared -document/testdata/scanned/page-3.txt text prepared -document/testdata/scanned/page-4.txt text prepared -document/testdata/scanned/page-5.txt text prepared -document/testdata/scanned/page-6.txt text prepared -document/testdata/scanned/page-7.txt text prepared -email/testdata/README.md text prepared -email/testdata/built/eml/office-attachments.eml nested prepared -email/testdata/built/msg/office-attachments.msg nested prepared -inspect/testdata/README.md text prepared -inspect/testdata/absolute.tar archive prepared -inspect/testdata/absolute.zip archive prepared -inspect/testdata/bomb.tar.gz archive prepared -inspect/testdata/bomb.zip archive prepared -inspect/testdata/clean.tar archive prepared -inspect/testdata/clean.tar.gz archive prepared -inspect/testdata/declared-bomb.zip archive quarantined -inspect/testdata/device.tar archive prepared -inspect/testdata/encrypted.xlsx office failed -inspect/testdata/encrypted.zip archive encrypted -inspect/testdata/generate.go text prepared -inspect/testdata/hardlink.tar archive prepared -inspect/testdata/hyperlink.docx office prepared -inspect/testdata/invoice.pdf.exe unrouted no processor yet -inspect/testdata/javascript.pdf document prepared -inspect/testdata/macro-latin1.docm office prepared -inspect/testdata/macro-utf16.docm office prepared -inspect/testdata/macro.docm office prepared -inspect/testdata/mismatch.pdf vision prepared -inspect/testdata/polyglot.jpg vision prepared -inspect/testdata/polyglot.png vision prepared -inspect/testdata/script-latin1.svg vision-converted prepared -inspect/testdata/script-utf16.svg vision-converted prepared -inspect/testdata/script.svg vision-converted prepared -inspect/testdata/sparse-bomb.tar archive quarantined -inspect/testdata/symlink.tar archive prepared -inspect/testdata/symlink.zip archive prepared -inspect/testdata/traversal.tar archive prepared -inspect/testdata/traversal.tar.gz archive prepared -inspect/testdata/traversal.zip archive prepared -inspect/testdata/unnamed.tgz archive prepared -office/testdata/README.md text prepared -office/testdata/golden/pictures.sha256 text prepared -office/testdata/legacy/generate.sh text prepared -office/testdata/legacy/generated/MANIFEST text prepared -office/testdata/legacy/generated/bullets.libreoffice.ppt office prepared -office/testdata/legacy/generated/cells.libreoffice.xls office prepared -office/testdata/legacy/generated/charts.libreoffice.doc office prepared -office/testdata/legacy/generated/comments.libreoffice.doc office prepared -office/testdata/legacy/generated/drawings.libreoffice.xls office prepared -office/testdata/legacy/generated/formulas.libreoffice.xls office seen -office/testdata/legacy/generated/lists.libreoffice.doc office prepared -office/testdata/legacy/generated/media.libreoffice.doc office prepared -office/testdata/legacy/generated/merges.libreoffice.xls office prepared -office/testdata/legacy/generated/notes.libreoffice.doc office prepared -office/testdata/legacy/generated/sections.libreoffice.doc office prepared -office/testdata/legacy/generated/slide-objects.libreoffice.ppt office prepared -office/testdata/legacy/generated/slides.libreoffice.ppt office prepared -office/testdata/legacy/generated/tables.libreoffice.doc office prepared -office/testdata/legacy/real/SampleSS.truth.json text prepared -office/testdata/legacy/real/SampleSS.xls office prepared -office/testdata/legacy/real/basic_test_ppt_file.ppt office prepared -office/testdata/legacy/real/basic_test_ppt_file.truth.json text prepared -office/testdata/legacy/real/simple-table.doc office prepared -office/testdata/legacy/real/simple-table.truth.json text prepared -office/testdata/licenses/poi.LICENSE text prepared -office/testdata/licenses/poi.NOTICE text prepared -office/testdata/odf/drawing.fodg text prepared -office/testdata/odf/encrypt.py text prepared -office/testdata/odf/generate.sh text prepared -office/testdata/odf/generated/MANIFEST text prepared -office/testdata/odf/generated/cells.libreoffice.ods office prepared -office/testdata/odf/generated/cells.libreoffice.ots office prepared -office/testdata/odf/generated/drawing.odg office prepared -office/testdata/odf/generated/drawing.otg office prepared -office/testdata/odf/generated/encrypted.odt office encrypted -office/testdata/odf/generated/slides.libreoffice.odp office prepared -office/testdata/odf/generated/slides.libreoffice.otp office prepared -office/testdata/odf/generated/tables.libreoffice.odt office prepared -office/testdata/odf/generated/tables.libreoffice.ott office prepared -office/testdata/ooxml/bullets.libreoffice.pptx office prepared -office/testdata/ooxml/cells.libreoffice.xlsx office prepared -office/testdata/ooxml/charts.libreoffice.docx office prepared -office/testdata/ooxml/comments.libreoffice.docx office prepared -office/testdata/ooxml/drawings.libreoffice.xlsx office prepared -office/testdata/ooxml/formulas.libreoffice.xlsx office prepared -office/testdata/ooxml/lists.libreoffice.docx office prepared -office/testdata/ooxml/media.libreoffice.docx office prepared -office/testdata/ooxml/merges.libreoffice.xlsx office prepared -office/testdata/ooxml/notes.libreoffice.docx office prepared -office/testdata/ooxml/sections.libreoffice.docx office prepared -office/testdata/ooxml/slide-objects.libreoffice.pptx office prepared -office/testdata/ooxml/slides.libreoffice.pptx office prepared -office/testdata/ooxml/tables.libreoffice.docx office seen -office/testdata/ooxml/with-drawing.xlsx office prepared -office/testdata/ooxml/word-with-attachments.docx office prepared -office/testdata/pictures/generate.sh text prepared -office/testdata/pictures/tiff.docx office prepared -office/testdata/rtf/hidden-entry.rtf office prepared -office/testdata/rtf/memo.rtf office prepared -office/testdata/wordperfect/testWordPerfect_6_61.wpd office prepared -office/testdata/xlsb/protected_passtika.xlsb office encrypted -office/testdata/xlsb/testVarious.xlsb office prepared -picture/testdata/README.md text prepared -picture/testdata/animated.avif vision-converted prepared -picture/testdata/animated.webp vision-converted prepared -picture/testdata/exif-gps.jpg vision prepared -picture/testdata/exif-gps.magick.txt text prepared -picture/testdata/exif-none.magick.txt text prepared -picture/testdata/exif-none.png vision prepared -picture/testdata/exif-zoneless.heic vision-converted prepared -picture/testdata/exif-zoneless.magick.txt text prepared -picture/testdata/ink.svg vision-converted prepared -picture/testdata/lzw-gray.tiff vision-converted prepared -picture/testdata/oriented.webp vision-converted prepared -picture/testdata/pages.tiff vision-converted prepared -picture/testdata/scanned-g4.tiff vision-converted prepared -picture/testdata/script-bearing.svg vision-converted prepared -picture/testdata/shapes.svg vision-converted prepared -picture/testdata/two-images.heic vision-converted prepared -rundir/testdata/rundir/content/b6/b688c8947f876ba9580749960b0c70076ea223eec8dcb9d57d4c51c9c9dd2906 text prepared -rundir/testdata/rundir/content/d3/d31031c3593a9da13ff7013b8cf20bf3120903467fac751975e0260c8560c6c7 text prepared -rundir/testdata/rundir/quarantine/4efe525c159bafa28a6ba4e08aa028a846bdebb78bf4b33c11e959a37b481bca unrouted no processor yet -rundir/testdata/rundir/rundir.json text seen -rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/manifest.json text prepared -rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000001/record.jsonl text prepared -rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/manifest.json text prepared -rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000002/record.jsonl text prepared -rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/manifest.json text prepared -rundir/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-000000000003/record.jsonl text prepared -sevenzip/testdata/README.md text prepared -sevenzip/testdata/commons-compress/LICENSE.txt text prepared -sevenzip/testdata/commons-compress/NOTICE.txt text prepared -sevenzip/testdata/commons-compress/bla.deflate64.7z archive prepared -sevenzip/testdata/commons-compress/bzip2-zip.zip archive prepared -sevenzip/testdata/commons-compress/lorem-ipsum-deflate64.zip archive prepared -sevenzip/testdata/commons-compress/lorem-ipsum-implode.zip archive prepared -sevenzip/testdata/commons-compress/test-method-xz.zip archive prepared -sevenzip/testdata/generate.go text prepared -sevenzip/testdata/generated/absolute.7z archive prepared -sevenzip/testdata/generated/absolute.cab archive prepared -sevenzip/testdata/generated/bomb.7z archive prepared -sevenzip/testdata/generated/bomb.bz2 archive prepared -sevenzip/testdata/generated/bomb.cab archive prepared -sevenzip/testdata/generated/bomb.xz archive prepared -sevenzip/testdata/generated/bomb.zst archive prepared -sevenzip/testdata/generated/clean.7z archive prepared -sevenzip/testdata/generated/clean.tar.zst archive prepared -sevenzip/testdata/generated/clean.tbz2 archive prepared -sevenzip/testdata/generated/clean.txz archive prepared -sevenzip/testdata/generated/concatenated.txt.bz2 archive prepared -sevenzip/testdata/generated/declared-bomb.zst archive quarantined -sevenzip/testdata/generated/device.7z archive prepared -sevenzip/testdata/generated/encrypted-headers.7z archive encrypted -sevenzip/testdata/generated/encrypted.7z archive encrypted -sevenzip/testdata/generated/linebreak.cab archive prepared -sevenzip/testdata/generated/mixed.7z archive prepared -sevenzip/testdata/generated/multiblock.7z archive prepared -sevenzip/testdata/generated/notebook.cab archive prepared -sevenzip/testdata/generated/notes.txt.bz2 archive prepared -sevenzip/testdata/generated/notes.txt.xz archive prepared -sevenzip/testdata/generated/symlink.7z archive prepared -sevenzip/testdata/generated/traversal.7z archive prepared -sevenzip/testdata/generated/traversal.cab archive prepared -sevenzip/testdata/libarchive/COPYING text prepared -sevenzip/testdata/libarchive/test_read_format_rar.rar archive prepared -sevenzip/testdata/libarchive/test_read_format_rar5_compressed.rar archive prepared -sevenzip/testdata/libarchive/test_read_format_rar5_encrypted.rar archive encrypted -sevenzip/testdata/libarchive/test_read_format_rar5_encrypted_filenames.rar archive encrypted -sevenzip/testdata/libarchive/test_read_format_rar5_multiarchive.part01.rar archive no processor yet -sevenzip/testdata/libarchive/test_read_format_rar5_symlink.rar archive prepared -sevenzip/testdata/libarchive/test_read_format_rar_encryption_header.rar archive encrypted -sevenzip/testdata/libarchive/test_read_format_rar_encryption_partially.rar archive encrypted -sevenzip/testdata/libarchive/test_read_format_rar_multivolume.part0001.rar archive no processor yet -sevenzip/testdata/libarchive/test_read_format_zip_lzma.zipx archive prepared -sevenzip/testdata/libarchive/test_read_format_zip_ppmd8.zipx archive prepared -sevenzip/testdata/libarchive/test_read_format_zip_zstd.zipx archive prepared -tool/testdata/README.md text prepared -tool/testdata/tone.wav audio prepared diff --git a/tool/cancel_test.go b/tool/test/cancel_test.go similarity index 100% rename from tool/cancel_test.go rename to tool/test/cancel_test.go diff --git a/tool/container_test.go b/tool/test/container_test.go similarity index 100% rename from tool/container_test.go rename to tool/test/container_test.go diff --git a/tool/docker_test.go b/tool/test/docker_test.go similarity index 100% rename from tool/docker_test.go rename to tool/test/docker_test.go diff --git a/tool/exec_test.go b/tool/test/exec_test.go similarity index 100% rename from tool/exec_test.go rename to tool/test/exec_test.go diff --git a/tool/ffprobe_integration_test.go b/tool/test/ffprobe_integration_test.go similarity index 100% rename from tool/ffprobe_integration_test.go rename to tool/test/ffprobe_integration_test.go diff --git a/tool/lockdown_test.go b/tool/test/lockdown_test.go similarity index 100% rename from tool/lockdown_test.go rename to tool/test/lockdown_test.go diff --git a/tool/main_test.go b/tool/test/main_test.go similarity index 100% rename from tool/main_test.go rename to tool/test/main_test.go diff --git a/tool/stdin_test.go b/tool/test/stdin_test.go similarity index 100% rename from tool/stdin_test.go rename to tool/test/stdin_test.go diff --git a/tool/testdata/README.md b/tool/test/testdata/README.md similarity index 100% rename from tool/testdata/README.md rename to tool/test/testdata/README.md diff --git a/tool/testdata/tone.wav b/tool/test/testdata/tone.wav similarity index 100% rename from tool/testdata/tone.wav rename to tool/test/testdata/tone.wav diff --git a/tool/tmpdir_test.go b/tool/test/tmpdir_test.go similarity index 100% rename from tool/tmpdir_test.go rename to tool/test/tmpdir_test.go diff --git a/tool/usage_test.go b/tool/test/usage_test.go similarity index 100% rename from tool/usage_test.go rename to tool/test/usage_test.go diff --git a/tool/version_test.go b/tool/test/version_test.go similarity index 100% rename from tool/version_test.go rename to tool/test/version_test.go From a3bd855f6ae485eb287b311e4e6e96bf24023320 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 13:39:59 -0500 Subject: [PATCH 06/10] =?UTF-8?q?harness.layout=20=C2=B7=20docproc=20?= =?UTF-8?q?=C2=B7=20slice=206:=20storage,=20postgres,=20and=20cmd/docproc?= =?UTF-8?q?=20tests=20into=20test/;=20the=20docs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The storage, postgres, and cmd/docproc modules' tests move, with git mv, into /test/ as _test, fixtures into /test/testdata: storage's and postgres's tests with their TestMains and integration-tagged suites, and cmd/docproc's internal/app (with testdata/fallback.txt), internal/apptest, and internal/report (with its golden and rundir testdata). - Left in place: cmd/docproc/integration, the built-binary tier, and cmd/docproc/internal/run's export_test.go (SetBirth, the birth-time probe hook) with file_test.go, the one test using it; run has no other test. git ls-files '*export_test.go' lists only that file. - app's requiredLibrary reads its module's go.mod one directory further up (../../../go.mod); it is the module's own file, not another package's fixture, so it stays a relative path rather than tooltest.Testdata. - stages/test/testdata/fixtures.tsv names cmd/docproc's fixtures at their test/testdata paths. - Docs: docs/development.md gains "Where the tests sit" (test/ placement, the shared helper packages, the module-internal adapters, the two exceptions, the agent's scratch area, pointing to tests-and-docs.md) and states the agent profile and who sees which tasks; docs/packages.md lists stages/internal/adapter and points to the placement; docs/ci.md says which jobs run step scripts and which a person's tasks, none under the agent profile; CLAUDE.md names the agent tasks and the test placement; README's Development line names both; app's package comment names test/graph_test.go; the provider READMEs say test:integration runs them after cmd/docproc's tier too. go test -list . ./... names the same tests per module before and after, GOWORK=off, with and without -tags integration: storage 7/9, postgres 8/28, cmd/docproc 84/88. No CHANGELOG entry: each module's changelog covers its contract alone (exported API, or cmd/docproc's command line, run directory, and exit codes), and none changes. --- CLAUDE.md | 8 ++- README.md | 3 +- cmd/docproc/internal/app/doc.go | 2 +- .../internal/app/{ => test}/app_test.go | 0 .../internal/app/{ => test}/bounds_test.go | 0 .../internal/app/{ => test}/graph_test.go | 0 .../internal/app/{ => test}/report_test.go | 0 .../internal/app/{ => test}/run_test.go | 2 +- .../app/{ => test}/testdata/fallback.txt | 0 .../apptest/{ => test}/apptest_test.go | 0 .../internal/report/{ => test}/main_test.go | 0 .../internal/report/{ => test}/report_test.go | 0 ...659d9bae2cebed6c9b9a66b1bde9ef33ab03e.html | 0 ...140987b664d03f8a29aec13ee88f3b271d014.html | 0 ...f5606d96acde9ef44abfab0d167826f4b60df.html | 0 .../index.html | 0 ...a5500103ca204cecb41a12e69382413f0e08f.html | 0 .../index.html | 0 ...f8e43f73b1b5030ec3ab59d0b2235aa2faa16b4abe | 0 ...36bd07c9a9209f1d6207cfb3a530c7a2e84ab1a5a2 | Bin ...fdb670aec4c66c547ab78d4c13c41bf822a2f63a9d | 0 ...bf84f605f00f4827d82dad47f55b468b8ddf3d44c4 | 0 ...823bea5500103ca204cecb41a12e69382413f0e08f | 0 ...f5a21ceeb556eeeaf3a208c97c5927e7a098878b19 | 0 ...3f4adbfc46f76775d1bffeb97ea5d95efd53afab36 | 0 ...2e41362498fee1eac19cb75247d86187f0e8b829f9 | 0 ...503c2d4f7ed429a7df4f3c80350de6e1c95d7c8d38 | 0 ...792900801c945226449672700b65e1fa8da633a0e7 | Bin ...56d16d92f1e74ab539039d33d33ab256c8995b5b9d | Bin .../{ => test}/testdata/rundir/rundir.json | 0 .../manifest.json | 0 .../record.jsonl | 0 .../manifest.json | 0 .../record.jsonl | 0 docs/ci.md | 5 +- docs/development.md | 33 +++++++++++-- docs/packages.md | 3 ++ postgres/README.md | 2 +- postgres/{ => test}/golden_test.go | 0 postgres/{ => test}/index_integration_test.go | 0 postgres/{ => test}/main_test.go | 0 .../{ => test}/postgres_integration_test.go | 0 postgres/{ => test}/postgres_test.go | 0 .../{ => test}/retention_integration_test.go | 0 postgres/{ => test}/retention_test.go | 0 postgres/{ => test}/wait_integration_test.go | 0 stages/test/testdata/fixtures.tsv | 46 +++++++++--------- storage/README.md | 2 +- storage/{ => test}/content_test.go | 0 storage/{ => test}/main_test.go | 0 .../{ => test}/storage_integration_test.go | 0 51 files changed, 72 insertions(+), 34 deletions(-) rename cmd/docproc/internal/app/{ => test}/app_test.go (100%) rename cmd/docproc/internal/app/{ => test}/bounds_test.go (100%) rename cmd/docproc/internal/app/{ => test}/graph_test.go (100%) rename cmd/docproc/internal/app/{ => test}/report_test.go (100%) rename cmd/docproc/internal/app/{ => test}/run_test.go (99%) rename cmd/docproc/internal/app/{ => test}/testdata/fallback.txt (100%) rename cmd/docproc/internal/apptest/{ => test}/apptest_test.go (100%) rename cmd/docproc/internal/report/{ => test}/main_test.go (100%) rename cmd/docproc/internal/report/{ => test}/report_test.go (100%) rename cmd/docproc/internal/report/{ => test}/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/956e499b5e521771b3584eaa57b659d9bae2cebed6c9b9a66b1bde9ef33ab03e.html (100%) rename cmd/docproc/internal/report/{ => test}/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f04403b02fdd738868d5c683872140987b664d03f8a29aec13ee88f3b271d014.html (100%) rename cmd/docproc/internal/report/{ => test}/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f90199938cc629a711b4ce5a349f5606d96acde9ef44abfab0d167826f4b60df.html (100%) rename cmd/docproc/internal/report/{ => test}/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/index.html (100%) rename cmd/docproc/internal/report/{ => test}/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f.html (100%) rename cmd/docproc/internal/report/{ => test}/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/index.html (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/content/25/2556d072121b94e2a6cc4cf8e43f73b1b5030ec3ab59d0b2235aa2faa16b4abe (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/content/43/4371149be76808ede2e39736bd07c9a9209f1d6207cfb3a530c7a2e84ab1a5a2 (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/content/49/49f0a3b0c2b2a69f7619a5fdb670aec4c66c547ab78d4c13c41bf822a2f63a9d (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/content/6a/6aadf10b8e2ff279d1eebcbf84f605f00f4827d82dad47f55b468b8ddf3d44c4 (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/content/6d/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/content/91/91f139ca1c19593f32cba1f5a21ceeb556eeeaf3a208c97c5927e7a098878b19 (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/content/98/98dc2ca63ef11a81aec72f3f4adbfc46f76775d1bffeb97ea5d95efd53afab36 (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/content/a1/a1c904eedaa045e589e7662e41362498fee1eac19cb75247d86187f0e8b829f9 (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/content/e5/e5e635c7a7480ef91dd5f6503c2d4f7ed429a7df4f3c80350de6e1c95d7c8d38 (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/content/e7/e700dfd0455f7fc65a5847792900801c945226449672700b65e1fa8da633a0e7 (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/quarantine/d9f0fc6ffd4c580cd4bd9f56d16d92f1e74ab539039d33d33ab256c8995b5b9d (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/rundir.json (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/manifest.json (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/record.jsonl (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/manifest.json (100%) rename cmd/docproc/internal/report/{ => test}/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/record.jsonl (100%) rename postgres/{ => test}/golden_test.go (100%) rename postgres/{ => test}/index_integration_test.go (100%) rename postgres/{ => test}/main_test.go (100%) rename postgres/{ => test}/postgres_integration_test.go (100%) rename postgres/{ => test}/postgres_test.go (100%) rename postgres/{ => test}/retention_integration_test.go (100%) rename postgres/{ => test}/retention_test.go (100%) rename postgres/{ => test}/wait_integration_test.go (100%) rename storage/{ => test}/content_test.go (100%) rename storage/{ => test}/main_test.go (100%) rename storage/{ => test}/storage_integration_test.go (100%) diff --git a/CLAUDE.md b/CLAUDE.md index e8d41ed4..3a3c92e4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -27,7 +27,13 @@ The extraction library adjacent to Go Elemental, with the system tools it runs n `tools/onenote`. - [`tools/envelope/src/lib.rs`](tools/envelope/src/lib.rs): docproc-envelope, the Rust tools' shared envelope crate, tested by each Rust tool's check. -- `mise run check`: the check. +- `mise run check`: the check. `.claude/settings.json` sets `MISE_ENV=agent`, the agent profile, + which adds the agent's tasks under `.agent/mise-tasks/`: the check's steps alone (`check:go`, + `check:sqlint`, `check:tools`, `check:lints`) and the Go step's gates (`test`, `vet`, `lint`); + [`docs/development.md`](docs/development.md) states every task, a person's and an agent's. +- Tests: each package's in its `test/` directory, with the one `export_test.go` and the + built-binary `cmd/docproc/integration` package as the exceptions; + [`docs/development.md`](docs/development.md#where-the-tests-sit) states where each sits. - `mise run integration`: the providers' live tiers, `integration:postgres` and `integration:storage`, each against its own compose service; `mise run test:integration`, the pre-tag run, the tools tier and cmd/docproc's built-binary tier over this checkout's tool diff --git a/README.md b/README.md index 1c09aaf8..65585fd7 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,8 @@ the reference for its exported names, and its doc comment lists them. - [The command](docs/command.md): `cmd/docproc`'s commands, exit statuses, and configuration. - [Limits](docs/limits.md): what docproc doesn't read, and the limits each stage inherits from its tool. -- [Development](docs/development.md): the toolchain, the tasks, the compose harness, and releases. +- [Development](docs/development.md): the toolchain, the tasks, a person's and an agent's, where the + tests sit, the compose harness, and releases. ## Providers diff --git a/cmd/docproc/internal/app/doc.go b/cmd/docproc/internal/app/doc.go index ad508fc2..799c3434 100644 --- a/cmd/docproc/internal/app/doc.go +++ b/cmd/docproc/internal/app/doc.go @@ -17,7 +17,7 @@ // // [Nodes] holds one handle per node: each define function fills its own part of one Nodes // value, and its constructors read the lower layers' nodes from it with Use. Each field's node is -// named for the field, so no comment names it; graph_test.go checks that rule with go-core's +// named for the field, so no comment names it; test/graph_test.go checks that rule with go-core's // graphtest.CheckNames, and checks that every leaf of the tree, as Command.Leaves yields it, // builds its nodes without dropping an order between layers. Defining the nodes constructs // nothing. A command declares the nodes it needs with Use; the dispatcher builds them, with the diff --git a/cmd/docproc/internal/app/app_test.go b/cmd/docproc/internal/app/test/app_test.go similarity index 100% rename from cmd/docproc/internal/app/app_test.go rename to cmd/docproc/internal/app/test/app_test.go diff --git a/cmd/docproc/internal/app/bounds_test.go b/cmd/docproc/internal/app/test/bounds_test.go similarity index 100% rename from cmd/docproc/internal/app/bounds_test.go rename to cmd/docproc/internal/app/test/bounds_test.go diff --git a/cmd/docproc/internal/app/graph_test.go b/cmd/docproc/internal/app/test/graph_test.go similarity index 100% rename from cmd/docproc/internal/app/graph_test.go rename to cmd/docproc/internal/app/test/graph_test.go diff --git a/cmd/docproc/internal/app/report_test.go b/cmd/docproc/internal/app/test/report_test.go similarity index 100% rename from cmd/docproc/internal/app/report_test.go rename to cmd/docproc/internal/app/test/report_test.go diff --git a/cmd/docproc/internal/app/run_test.go b/cmd/docproc/internal/app/test/run_test.go similarity index 99% rename from cmd/docproc/internal/app/run_test.go rename to cmd/docproc/internal/app/test/run_test.go index e6dd2965..258eebe8 100644 --- a/cmd/docproc/internal/app/run_test.go +++ b/cmd/docproc/internal/app/test/run_test.go @@ -872,7 +872,7 @@ func requiredLibrary(t *testing.T) string { if os.Getenv("GOWORK") != "off" { return "(devel)" } - mod, err := os.ReadFile(filepath.Join("..", "..", "go.mod")) + mod, err := os.ReadFile(filepath.Join("..", "..", "..", "go.mod")) if err != nil { t.Fatal(err) } diff --git a/cmd/docproc/internal/app/testdata/fallback.txt b/cmd/docproc/internal/app/test/testdata/fallback.txt similarity index 100% rename from cmd/docproc/internal/app/testdata/fallback.txt rename to cmd/docproc/internal/app/test/testdata/fallback.txt diff --git a/cmd/docproc/internal/apptest/apptest_test.go b/cmd/docproc/internal/apptest/test/apptest_test.go similarity index 100% rename from cmd/docproc/internal/apptest/apptest_test.go rename to cmd/docproc/internal/apptest/test/apptest_test.go diff --git a/cmd/docproc/internal/report/main_test.go b/cmd/docproc/internal/report/test/main_test.go similarity index 100% rename from cmd/docproc/internal/report/main_test.go rename to cmd/docproc/internal/report/test/main_test.go diff --git a/cmd/docproc/internal/report/report_test.go b/cmd/docproc/internal/report/test/report_test.go similarity index 100% rename from cmd/docproc/internal/report/report_test.go rename to cmd/docproc/internal/report/test/report_test.go diff --git a/cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/956e499b5e521771b3584eaa57b659d9bae2cebed6c9b9a66b1bde9ef33ab03e.html b/cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/956e499b5e521771b3584eaa57b659d9bae2cebed6c9b9a66b1bde9ef33ab03e.html similarity index 100% rename from cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/956e499b5e521771b3584eaa57b659d9bae2cebed6c9b9a66b1bde9ef33ab03e.html rename to cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/956e499b5e521771b3584eaa57b659d9bae2cebed6c9b9a66b1bde9ef33ab03e.html diff --git a/cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f04403b02fdd738868d5c683872140987b664d03f8a29aec13ee88f3b271d014.html b/cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f04403b02fdd738868d5c683872140987b664d03f8a29aec13ee88f3b271d014.html similarity index 100% rename from cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f04403b02fdd738868d5c683872140987b664d03f8a29aec13ee88f3b271d014.html rename to cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f04403b02fdd738868d5c683872140987b664d03f8a29aec13ee88f3b271d014.html diff --git a/cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f90199938cc629a711b4ce5a349f5606d96acde9ef44abfab0d167826f4b60df.html b/cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f90199938cc629a711b4ce5a349f5606d96acde9ef44abfab0d167826f4b60df.html similarity index 100% rename from cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f90199938cc629a711b4ce5a349f5606d96acde9ef44abfab0d167826f4b60df.html rename to cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f90199938cc629a711b4ce5a349f5606d96acde9ef44abfab0d167826f4b60df.html diff --git a/cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/index.html b/cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/index.html similarity index 100% rename from cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/index.html rename to cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/index.html diff --git a/cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f.html b/cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f.html similarity index 100% rename from cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f.html rename to cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f.html diff --git a/cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/index.html b/cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/index.html similarity index 100% rename from cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/index.html rename to cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/index.html diff --git a/cmd/docproc/internal/report/testdata/rundir/content/25/2556d072121b94e2a6cc4cf8e43f73b1b5030ec3ab59d0b2235aa2faa16b4abe b/cmd/docproc/internal/report/test/testdata/rundir/content/25/2556d072121b94e2a6cc4cf8e43f73b1b5030ec3ab59d0b2235aa2faa16b4abe similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/content/25/2556d072121b94e2a6cc4cf8e43f73b1b5030ec3ab59d0b2235aa2faa16b4abe rename to cmd/docproc/internal/report/test/testdata/rundir/content/25/2556d072121b94e2a6cc4cf8e43f73b1b5030ec3ab59d0b2235aa2faa16b4abe diff --git a/cmd/docproc/internal/report/testdata/rundir/content/43/4371149be76808ede2e39736bd07c9a9209f1d6207cfb3a530c7a2e84ab1a5a2 b/cmd/docproc/internal/report/test/testdata/rundir/content/43/4371149be76808ede2e39736bd07c9a9209f1d6207cfb3a530c7a2e84ab1a5a2 similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/content/43/4371149be76808ede2e39736bd07c9a9209f1d6207cfb3a530c7a2e84ab1a5a2 rename to cmd/docproc/internal/report/test/testdata/rundir/content/43/4371149be76808ede2e39736bd07c9a9209f1d6207cfb3a530c7a2e84ab1a5a2 diff --git a/cmd/docproc/internal/report/testdata/rundir/content/49/49f0a3b0c2b2a69f7619a5fdb670aec4c66c547ab78d4c13c41bf822a2f63a9d b/cmd/docproc/internal/report/test/testdata/rundir/content/49/49f0a3b0c2b2a69f7619a5fdb670aec4c66c547ab78d4c13c41bf822a2f63a9d similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/content/49/49f0a3b0c2b2a69f7619a5fdb670aec4c66c547ab78d4c13c41bf822a2f63a9d rename to cmd/docproc/internal/report/test/testdata/rundir/content/49/49f0a3b0c2b2a69f7619a5fdb670aec4c66c547ab78d4c13c41bf822a2f63a9d diff --git a/cmd/docproc/internal/report/testdata/rundir/content/6a/6aadf10b8e2ff279d1eebcbf84f605f00f4827d82dad47f55b468b8ddf3d44c4 b/cmd/docproc/internal/report/test/testdata/rundir/content/6a/6aadf10b8e2ff279d1eebcbf84f605f00f4827d82dad47f55b468b8ddf3d44c4 similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/content/6a/6aadf10b8e2ff279d1eebcbf84f605f00f4827d82dad47f55b468b8ddf3d44c4 rename to cmd/docproc/internal/report/test/testdata/rundir/content/6a/6aadf10b8e2ff279d1eebcbf84f605f00f4827d82dad47f55b468b8ddf3d44c4 diff --git a/cmd/docproc/internal/report/testdata/rundir/content/6d/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f b/cmd/docproc/internal/report/test/testdata/rundir/content/6d/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/content/6d/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f rename to cmd/docproc/internal/report/test/testdata/rundir/content/6d/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f diff --git a/cmd/docproc/internal/report/testdata/rundir/content/91/91f139ca1c19593f32cba1f5a21ceeb556eeeaf3a208c97c5927e7a098878b19 b/cmd/docproc/internal/report/test/testdata/rundir/content/91/91f139ca1c19593f32cba1f5a21ceeb556eeeaf3a208c97c5927e7a098878b19 similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/content/91/91f139ca1c19593f32cba1f5a21ceeb556eeeaf3a208c97c5927e7a098878b19 rename to cmd/docproc/internal/report/test/testdata/rundir/content/91/91f139ca1c19593f32cba1f5a21ceeb556eeeaf3a208c97c5927e7a098878b19 diff --git a/cmd/docproc/internal/report/testdata/rundir/content/98/98dc2ca63ef11a81aec72f3f4adbfc46f76775d1bffeb97ea5d95efd53afab36 b/cmd/docproc/internal/report/test/testdata/rundir/content/98/98dc2ca63ef11a81aec72f3f4adbfc46f76775d1bffeb97ea5d95efd53afab36 similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/content/98/98dc2ca63ef11a81aec72f3f4adbfc46f76775d1bffeb97ea5d95efd53afab36 rename to cmd/docproc/internal/report/test/testdata/rundir/content/98/98dc2ca63ef11a81aec72f3f4adbfc46f76775d1bffeb97ea5d95efd53afab36 diff --git a/cmd/docproc/internal/report/testdata/rundir/content/a1/a1c904eedaa045e589e7662e41362498fee1eac19cb75247d86187f0e8b829f9 b/cmd/docproc/internal/report/test/testdata/rundir/content/a1/a1c904eedaa045e589e7662e41362498fee1eac19cb75247d86187f0e8b829f9 similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/content/a1/a1c904eedaa045e589e7662e41362498fee1eac19cb75247d86187f0e8b829f9 rename to cmd/docproc/internal/report/test/testdata/rundir/content/a1/a1c904eedaa045e589e7662e41362498fee1eac19cb75247d86187f0e8b829f9 diff --git a/cmd/docproc/internal/report/testdata/rundir/content/e5/e5e635c7a7480ef91dd5f6503c2d4f7ed429a7df4f3c80350de6e1c95d7c8d38 b/cmd/docproc/internal/report/test/testdata/rundir/content/e5/e5e635c7a7480ef91dd5f6503c2d4f7ed429a7df4f3c80350de6e1c95d7c8d38 similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/content/e5/e5e635c7a7480ef91dd5f6503c2d4f7ed429a7df4f3c80350de6e1c95d7c8d38 rename to cmd/docproc/internal/report/test/testdata/rundir/content/e5/e5e635c7a7480ef91dd5f6503c2d4f7ed429a7df4f3c80350de6e1c95d7c8d38 diff --git a/cmd/docproc/internal/report/testdata/rundir/content/e7/e700dfd0455f7fc65a5847792900801c945226449672700b65e1fa8da633a0e7 b/cmd/docproc/internal/report/test/testdata/rundir/content/e7/e700dfd0455f7fc65a5847792900801c945226449672700b65e1fa8da633a0e7 similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/content/e7/e700dfd0455f7fc65a5847792900801c945226449672700b65e1fa8da633a0e7 rename to cmd/docproc/internal/report/test/testdata/rundir/content/e7/e700dfd0455f7fc65a5847792900801c945226449672700b65e1fa8da633a0e7 diff --git a/cmd/docproc/internal/report/testdata/rundir/quarantine/d9f0fc6ffd4c580cd4bd9f56d16d92f1e74ab539039d33d33ab256c8995b5b9d b/cmd/docproc/internal/report/test/testdata/rundir/quarantine/d9f0fc6ffd4c580cd4bd9f56d16d92f1e74ab539039d33d33ab256c8995b5b9d similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/quarantine/d9f0fc6ffd4c580cd4bd9f56d16d92f1e74ab539039d33d33ab256c8995b5b9d rename to cmd/docproc/internal/report/test/testdata/rundir/quarantine/d9f0fc6ffd4c580cd4bd9f56d16d92f1e74ab539039d33d33ab256c8995b5b9d diff --git a/cmd/docproc/internal/report/testdata/rundir/rundir.json b/cmd/docproc/internal/report/test/testdata/rundir/rundir.json similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/rundir.json rename to cmd/docproc/internal/report/test/testdata/rundir/rundir.json diff --git a/cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/manifest.json b/cmd/docproc/internal/report/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/manifest.json similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/manifest.json rename to cmd/docproc/internal/report/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/manifest.json diff --git a/cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/record.jsonl b/cmd/docproc/internal/report/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/record.jsonl similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/record.jsonl rename to cmd/docproc/internal/report/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/record.jsonl diff --git a/cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/manifest.json b/cmd/docproc/internal/report/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/manifest.json similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/manifest.json rename to cmd/docproc/internal/report/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/manifest.json diff --git a/cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/record.jsonl b/cmd/docproc/internal/report/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/record.jsonl similarity index 100% rename from cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/record.jsonl rename to cmd/docproc/internal/report/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/record.jsonl diff --git a/docs/ci.md b/docs/ci.md index 125ae147..abf66ae4 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -10,8 +10,9 @@ through mise-action or a task's auto-install. ## CI CI runs on every pull request into main, every push to main, and on demand. A newer run on the -same ref cancels the one it supersedes. Its jobs run the check's step scripts under -`scripts/check/` directly, never the agent's tasks. +same ref cancels the one it supersedes. The go and lints jobs run the check's step scripts under +`scripts/check/` directly, and the tool and integration jobs a person's tasks; no job runs under +`MISE_ENV=agent` or an agent's task. - **changes** decides which of the tool, go, and integration jobs run, through one paths filter each. diff --git a/docs/development.md b/docs/development.md index 759fd77b..f112c1d4 100644 --- a/docs/development.md +++ b/docs/development.md @@ -41,6 +41,31 @@ A Go module's release is a `vX.Y.Z` tag (`/vX.Y.Z` for a nested module), workflows are described in [CI and releases](ci.md), and each system tool's build configuration in [the tools' builds](tool-builds.md). +## Where the tests sit + +Each package's tests are in its `test/` directory, as the external test package `_test`, +which drives only the package's exported API, with their fixtures in `test/testdata/`; the +integration-tagged suites and each package's TestMain sit there too. A test that reads another +package's fixtures names them through `tooltest.Testdata`, never by a relative path. Test helpers +more than one test package uses are packages of their own: `internal/tooltest`, +`internal/goldentest`, `internal/mediatest`, `dispatch/dispatchtest`, +`stages/internal/stagestest`, and `cmd/docproc/internal/apptest`. The stage adapters are +module-internal, in `stages/internal/adapter`, and their tests drive its exported API from +`stages/internal/adapter/test/`. + +Two packages keep test files beside their source: + +- `cmd/docproc/internal/run`: `export_test.go`, the repository's one white-box file, exports + `SetBirth`, the hook for the birth-time probe, which a test can't reach deterministically + through the API, and `file_test.go`, the one test that uses it, stays beside it, since only a + test file in the package's directory sees the hook. +- `cmd/docproc/integration`: the command's built-binary integration tier, a package at the + module's root, its harness untagged and its suite under the `integration` tag. + +An agent's scratch tests go in the git-ignored `.agent/state/`, never in `test/`. The rules are +`architecture/standards/go-elemental/principles/tests-and-docs.md`'s, "The unit tier" and +"Integration and acceptance suites". + ## The root mise.toml [`mise.toml`](../mise.toml) pins the integration tier's 7-Zip, `7zz`, so currency and upgrade keep @@ -68,8 +93,9 @@ Its environment: Its one-line tasks stay in it; each multi-line task is a file task under [`mise-tasks/`](../mise-tasks). The agent's tasks are file tasks under `.agent/mise-tasks/`, which -only `MISE_ENV=agent` loads, through [`mise.agent.toml`](../mise.agent.toml); the Claude settings -set it. Its tasks: +only `MISE_ENV=agent` loads, through [`mise.agent.toml`](../mise.agent.toml), the agent profile +and the repository's only one; `.claude/settings.json` sets it, so an agent has a person's tasks +and its own, and a person, with no profile set, only theirs. Its tasks: - `check` is the one check: read-only and deterministic. It runs the step scripts under [`scripts/check/`](../scripts/check) in turn: the Go step, the sqlint step, the tools step, then @@ -168,7 +194,8 @@ hold the module to its own requirements. depguard, which holds the module to its allowed imports, nolintlint, which requires each suppression to name its linter and give a reason, and testpackage, which keeps tests black-box. testpackage's skip regexp is narrowed to `export_test.go`: tests live in `_test` and drive - the exported API, and the one white-box file allowed is `export_test.go`. Its `allow-packages` + the exported API, and the one white-box file allowed is `export_test.go` + ([above](#where-the-tests-sit)). Its `allow-packages` is narrowed from its default, `main`, so a command's tests are black-box too, in `main_test`. It names only the empty package name, which no package has: an empty list leaves the default, `main`, in force. diff --git a/docs/packages.md b/docs/packages.md index 518da7ac..161bb7d5 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -20,6 +20,7 @@ | `metadata` | The metadata records' shapes, one per format, each a JSON value under a versioned media type `dispatch` declares: `Office`, an office package's properties and the format it was converted from; `PDF`, a PDF's information dictionary, XMP metadata, and version; `Media`, an audio or video file's container format, duration, bit rate, and tags, and its streams; and `Picture`, a picture's EXIF capture time, camera, orientation, size, GPS position, and properties. It imports no docproc package but `dispatch`, so a reader decodes a record without compiling the stages. | | `internal/cli` | The envelope reader the three readers share: their lines, stderr warnings, exit codes, and media names; and the ffprobe report audio and media read. | | `internal/goldentest`, `internal/mediatest`, `internal/tooltest` | Test helpers: PNG goldens, media fixtures, and the unit tier's stand-in tool. | +| `stages/internal/adapter` | The stage adapters, module-internal: each a `dispatch.Stage` over its format package and the tools it requires, and the failure classification they share, which `stages.Build` wires. | | `stages/internal/stagestest` | Test helpers the tests of `stages` and its adapters share: a stand-in for each program a stage runs, the stand-in stages over them, and the dispatch helpers. | A host registers `stages.Build`'s stages with a `dispatch.Dispatcher` and ranges over its @@ -29,3 +30,5 @@ sets them. `stages.Options.Concurrency`, the pages and windows held at once, is raises it. The packages' exported API, and the boundary other layers build against, is on [`api.md`](api.md). +Each package's tests are in its `test/` directory, as [Development](development.md#where-the-tests-sit) +states. diff --git a/postgres/README.md b/postgres/README.md index 135683f4..b0a9e370 100644 --- a/postgres/README.md +++ b/postgres/README.md @@ -86,7 +86,7 @@ Tasks run from the repository root, `mise run `: connections, and the retention, each test on a database of its own made through `sqlate/postgres/pgtest`, and stops the service whether the suite passes or fails, printing its log on a failure. `integration` runs it before the storage module's, and `test:integration` - after the base module's integration tier. + after the base module's and cmd/docproc's integration tiers. PostgreSQL listens on port 5436; `DOCPROC_POSTGRES_PORT` moves it, and `DOCPROC_DSN` in the root `mise.toml`, the admin DSN the tier reads, follows. A host's own tests make a migrated database diff --git a/postgres/golden_test.go b/postgres/test/golden_test.go similarity index 100% rename from postgres/golden_test.go rename to postgres/test/golden_test.go diff --git a/postgres/index_integration_test.go b/postgres/test/index_integration_test.go similarity index 100% rename from postgres/index_integration_test.go rename to postgres/test/index_integration_test.go diff --git a/postgres/main_test.go b/postgres/test/main_test.go similarity index 100% rename from postgres/main_test.go rename to postgres/test/main_test.go diff --git a/postgres/postgres_integration_test.go b/postgres/test/postgres_integration_test.go similarity index 100% rename from postgres/postgres_integration_test.go rename to postgres/test/postgres_integration_test.go diff --git a/postgres/postgres_test.go b/postgres/test/postgres_test.go similarity index 100% rename from postgres/postgres_test.go rename to postgres/test/postgres_test.go diff --git a/postgres/retention_integration_test.go b/postgres/test/retention_integration_test.go similarity index 100% rename from postgres/retention_integration_test.go rename to postgres/test/retention_integration_test.go diff --git a/postgres/retention_test.go b/postgres/test/retention_test.go similarity index 100% rename from postgres/retention_test.go rename to postgres/test/retention_test.go diff --git a/postgres/wait_integration_test.go b/postgres/test/wait_integration_test.go similarity index 100% rename from postgres/wait_integration_test.go rename to postgres/test/wait_integration_test.go diff --git a/stages/test/testdata/fixtures.tsv b/stages/test/testdata/fixtures.tsv index 33a06794..c6d986c6 100644 --- a/stages/test/testdata/fixtures.tsv +++ b/stages/test/testdata/fixtures.tsv @@ -11,29 +11,29 @@ audio/test/testdata/speech-truncated.mp3 audio prepared audio/test/testdata/speech.flac audio prepared audio/test/testdata/speech.truth.txt text prepared audio/test/testdata/windows-v0.9.0.txt text prepared -cmd/docproc/internal/app/testdata/fallback.txt text prepared -cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/956e499b5e521771b3584eaa57b659d9bae2cebed6c9b9a66b1bde9ef33ab03e.html text prepared -cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f04403b02fdd738868d5c683872140987b664d03f8a29aec13ee88f3b271d014.html text prepared -cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f90199938cc629a711b4ce5a349f5606d96acde9ef44abfab0d167826f4b60df.html text prepared -cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/index.html text prepared -cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f.html text prepared -cmd/docproc/internal/report/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/index.html text prepared -cmd/docproc/internal/report/testdata/rundir/content/25/2556d072121b94e2a6cc4cf8e43f73b1b5030ec3ab59d0b2235aa2faa16b4abe text prepared -cmd/docproc/internal/report/testdata/rundir/content/43/4371149be76808ede2e39736bd07c9a9209f1d6207cfb3a530c7a2e84ab1a5a2 vision prepared -cmd/docproc/internal/report/testdata/rundir/content/49/49f0a3b0c2b2a69f7619a5fdb670aec4c66c547ab78d4c13c41bf822a2f63a9d text prepared -cmd/docproc/internal/report/testdata/rundir/content/6a/6aadf10b8e2ff279d1eebcbf84f605f00f4827d82dad47f55b468b8ddf3d44c4 vision prepared -cmd/docproc/internal/report/testdata/rundir/content/6d/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f text prepared -cmd/docproc/internal/report/testdata/rundir/content/91/91f139ca1c19593f32cba1f5a21ceeb556eeeaf3a208c97c5927e7a098878b19 text prepared -cmd/docproc/internal/report/testdata/rundir/content/98/98dc2ca63ef11a81aec72f3f4adbfc46f76775d1bffeb97ea5d95efd53afab36 text prepared -cmd/docproc/internal/report/testdata/rundir/content/a1/a1c904eedaa045e589e7662e41362498fee1eac19cb75247d86187f0e8b829f9 text prepared -cmd/docproc/internal/report/testdata/rundir/content/e5/e5e635c7a7480ef91dd5f6503c2d4f7ed429a7df4f3c80350de6e1c95d7c8d38 text prepared -cmd/docproc/internal/report/testdata/rundir/content/e7/e700dfd0455f7fc65a5847792900801c945226449672700b65e1fa8da633a0e7 audio prepared -cmd/docproc/internal/report/testdata/rundir/quarantine/d9f0fc6ffd4c580cd4bd9f56d16d92f1e74ab539039d33d33ab256c8995b5b9d unrouted no processor yet -cmd/docproc/internal/report/testdata/rundir/rundir.json text prepared -cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/manifest.json text prepared -cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/record.jsonl text prepared -cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/manifest.json text prepared -cmd/docproc/internal/report/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/record.jsonl text prepared +cmd/docproc/internal/app/test/testdata/fallback.txt text prepared +cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/956e499b5e521771b3584eaa57b659d9bae2cebed6c9b9a66b1bde9ef33ab03e.html text prepared +cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f04403b02fdd738868d5c683872140987b664d03f8a29aec13ee88f3b271d014.html text prepared +cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/f90199938cc629a711b4ce5a349f5606d96acde9ef44abfab0d167826f4b60df.html text prepared +cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a1/index.html text prepared +cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f.html text prepared +cmd/docproc/internal/report/test/testdata/golden/019a5f3c-1d2e-7a10-8b00-0000000000a2/index.html text prepared +cmd/docproc/internal/report/test/testdata/rundir/content/25/2556d072121b94e2a6cc4cf8e43f73b1b5030ec3ab59d0b2235aa2faa16b4abe text prepared +cmd/docproc/internal/report/test/testdata/rundir/content/43/4371149be76808ede2e39736bd07c9a9209f1d6207cfb3a530c7a2e84ab1a5a2 vision prepared +cmd/docproc/internal/report/test/testdata/rundir/content/49/49f0a3b0c2b2a69f7619a5fdb670aec4c66c547ab78d4c13c41bf822a2f63a9d text prepared +cmd/docproc/internal/report/test/testdata/rundir/content/6a/6aadf10b8e2ff279d1eebcbf84f605f00f4827d82dad47f55b468b8ddf3d44c4 vision prepared +cmd/docproc/internal/report/test/testdata/rundir/content/6d/6d5f3ae23fe522077bdacf823bea5500103ca204cecb41a12e69382413f0e08f text prepared +cmd/docproc/internal/report/test/testdata/rundir/content/91/91f139ca1c19593f32cba1f5a21ceeb556eeeaf3a208c97c5927e7a098878b19 text prepared +cmd/docproc/internal/report/test/testdata/rundir/content/98/98dc2ca63ef11a81aec72f3f4adbfc46f76775d1bffeb97ea5d95efd53afab36 text prepared +cmd/docproc/internal/report/test/testdata/rundir/content/a1/a1c904eedaa045e589e7662e41362498fee1eac19cb75247d86187f0e8b829f9 text prepared +cmd/docproc/internal/report/test/testdata/rundir/content/e5/e5e635c7a7480ef91dd5f6503c2d4f7ed429a7df4f3c80350de6e1c95d7c8d38 text prepared +cmd/docproc/internal/report/test/testdata/rundir/content/e7/e700dfd0455f7fc65a5847792900801c945226449672700b65e1fa8da633a0e7 audio prepared +cmd/docproc/internal/report/test/testdata/rundir/quarantine/d9f0fc6ffd4c580cd4bd9f56d16d92f1e74ab539039d33d33ab256c8995b5b9d unrouted no processor yet +cmd/docproc/internal/report/test/testdata/rundir/rundir.json text prepared +cmd/docproc/internal/report/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/manifest.json text prepared +cmd/docproc/internal/report/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a1/record.jsonl text prepared +cmd/docproc/internal/report/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/manifest.json text prepared +cmd/docproc/internal/report/test/testdata/rundir/runs/019a5f3c-1d2e-7a10-8b00-0000000000a2/record.jsonl text prepared dispatch/test/testdata/dispatch.jsonl text prepared dispatch/test/testdata/log.jsonl text prepared document/test/testdata/README.md text prepared diff --git a/storage/README.md b/storage/README.md index 57629d67..041b3221 100644 --- a/storage/README.md +++ b/storage/README.md @@ -63,7 +63,7 @@ Tasks run from the repository root, `mise run `: harness's SeaweedFS alone, runs the `Content` suite over go-storage's `s3` provider against its S3 gateway, each test in a bucket of its own, and stops the service whether the suite passes or fails, printing its log on a failure. `integration` runs it after the postgres module's, and - `test:integration` after the base module's integration tier. + `test:integration` after the base module's and cmd/docproc's integration tiers. SeaweedFS listens on port 8334; `DOCPROC_SEAWEEDFS_PORT` moves it, and `DOCPROC_S3_ENDPOINT` in the root `mise.toml` follows. The tier reads `DOCPROC_S3_ENDPOINT`, `DOCPROC_S3_ACCESS_KEY`, and diff --git a/storage/content_test.go b/storage/test/content_test.go similarity index 100% rename from storage/content_test.go rename to storage/test/content_test.go diff --git a/storage/main_test.go b/storage/test/main_test.go similarity index 100% rename from storage/main_test.go rename to storage/test/main_test.go diff --git a/storage/storage_integration_test.go b/storage/test/storage_integration_test.go similarity index 100% rename from storage/storage_integration_test.go rename to storage/test/storage_integration_test.go From 88ee1c6079215af8c0f88023cf06ce28113e0c70 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 13:45:19 -0500 Subject: [PATCH 07/10] =?UTF-8?q?harness.layout=20=C2=B7=20docproc=20?= =?UTF-8?q?=C2=B7=20standards=20review:=20tests=20that=20lie?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TestAudioStageReal's closing check that the dispatcher kept its input re-resolved the fixture through tooltest.Testdata, which fails the test itself on a missing file, so the assertion's own message could never be reported; the path is now resolved once and the Stat checks it. The classify test's messages name PartErr, the function they call. --- stages/internal/adapter/test/audio_integration_test.go | 5 +++-- stages/internal/adapter/test/classify_test.go | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/stages/internal/adapter/test/audio_integration_test.go b/stages/internal/adapter/test/audio_integration_test.go index bedeb71b..f2a9d16a 100644 --- a/stages/internal/adapter/test/audio_integration_test.go +++ b/stages/internal/adapter/test/audio_integration_test.go @@ -33,6 +33,7 @@ func TestAudioStageReal(t *testing.T) { "e142ddb2f6d968dc33d2858f20ba456718b0335be22f3be7eafba3bd97a8cbd5.wav", "b5f802b375656c7fd2d06b6bc76c6da71b2b67ddab2f72d0ad12f2dd22293af3.wav", } + fixture := speechFixture(t) sums := map[string][]string{} for name, build := range audioRunners { t.Run(name, func(t *testing.T) { @@ -51,7 +52,7 @@ func TestAudioStageReal(t *testing.T) { stage := adapter.NewAudioStage(adapter.AudioConfig{ Splitter: s, Version: adapter.Versions(ffmpeg, ffprobe), Request: audio.Request{Concurrency: 2}, }) - path, err := filepath.Abs(speechFixture(t)) + path, err := filepath.Abs(fixture) if err != nil { t.Fatal(err) } @@ -108,7 +109,7 @@ func TestAudioStageReal(t *testing.T) { if e, c := sums["exec"], sums["container"]; len(sums) == 2 && !slices.Equal(e, c) { t.Errorf("the exec runner prepared windows %q, the container runner %q", e, c) } - if _, err := os.Stat(speechFixture(t)); err != nil { + if _, err := os.Stat(fixture); err != nil { t.Errorf("the dispatcher removed the input: %v", err) } } diff --git a/stages/internal/adapter/test/classify_test.go b/stages/internal/adapter/test/classify_test.go index 4b6870f0..05d576f3 100644 --- a/stages/internal/adapter/test/classify_test.go +++ b/stages/internal/adapter/test/classify_test.go @@ -56,11 +56,11 @@ func TestClassify(t *testing.T) { } } if err := adapter.PartErr(t.Context(), exit("gs", 1), 0); !errors.Is(err, dispatch.ErrRefused) { - t.Errorf("partErr of the content's: %v, want ErrRefused", err) + t.Errorf("PartErr of the content's: %v, want ErrRefused", err) } for _, named := range []error{dispatch.ErrEncrypted, dispatch.ErrReadElsewhere, dispatch.ErrNoProcessor} { if err := adapter.PartErr(t.Context(), named, 0); err != named { - t.Errorf("partErr(%v) = %v, want it as it is", named, err) + t.Errorf("PartErr(%v) = %v, want it as it is", named, err) } } } From 41844e40be0949f72f6353588dcd33726e87ed93 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 13:45:23 -0500 Subject: [PATCH 08/10] =?UTF-8?q?harness.layout=20=C2=B7=20docproc=20?= =?UTF-8?q?=C2=B7=20standards=20review:=20stale=20paths=20and=20agent-sepa?= =?UTF-8?q?ration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The mail fixture generator's notes, in its source and in the committed manifest.json and truth.json it writes, named the removed fixtures profile (MISE_ENV=fixtures); they name mise -C generator now. The mail README said no tool task loads generator/mise.toml, though currency and upgrade run there. docs/development.md put an agent's scratch tests in .agent/state/, which agent-separation reserves for state; they go in the agent area, .agent/. Two paragraphs rewrapped to 100 columns. --- docs/development.md | 10 +++++----- tools/mail/README.md | 10 +++++----- tools/mail/generator/Fixtures.cs | 2 +- tools/mail/generator/Tnef.cs | 2 +- tools/mail/tests/fixtures/generated/manifest.json | 2 +- tools/mail/tests/fixtures/tnef/truth.json | 2 +- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/development.md b/docs/development.md index f112c1d4..6c1c6c3f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -62,7 +62,7 @@ Two packages keep test files beside their source: - `cmd/docproc/integration`: the command's built-binary integration tier, a package at the module's root, its harness untagged and its suite under the `integration` tag. -An agent's scratch tests go in the git-ignored `.agent/state/`, never in `test/`. The rules are +An agent's scratch tests go in the agent area, `.agent/`, never in `test/`. The rules are `architecture/standards/go-elemental/principles/tests-and-docs.md`'s, "The unit tier" and "Integration and acceptance suites". @@ -203,10 +203,10 @@ hold the module to its own requirements. anchored: the module as itself or a package under it (not a sibling like `docproc-extra`). The longest match wins, so the deny entries keep the other modules out despite docproc's prefix, and a test helper out of the production files despite its module's. -- The base module depends on nothing but the standard library (`unsafe` among it, which `waitid` - in `tool/exec.go` uses) and `golang.org/x/text`'s packages, which the text stage decodes - through (`stages/internal/adapter/text.go`), so no package imports a model client. The rule covers every Go - file, tests included: they drive the API with the same imports plus the module itself. The deny +- The base module depends on nothing but the standard library (`unsafe` among it, which `waitid` in + `tool/exec.go` uses) and `golang.org/x/text`'s packages, which the text stage decodes through + (`stages/internal/adapter/text.go`), so no package imports a model client. The rule covers every + Go file, tests included: they drive the API with the same imports plus the module itself. The deny entries keep the storage, postgres, and cmd/docproc modules, which require the base, out of it. - The storage module requires the standard library, docproc's base packages, whose `dispatch.Content` it implements, and go-storage's `Client` it stores through; its tests add diff --git a/tools/mail/README.md b/tools/mail/README.md index ffe535cd..e85ff542 100644 --- a/tools/mail/README.md +++ b/tools/mail/README.md @@ -244,11 +244,11 @@ crate, [`tools/envelope`](../envelope). The toolchain (Rust with both musl targets, jq, shellcheck, cargo-deny, cargo-about) is pinned in [`mise.toml`](mise.toml) alone, and the fixture generator's .NET SDK in -[`generator/mise.toml`](generator/mise.toml), which the tool's own tasks never load. Its tasks run -from this directory, `mise run `, or from the repository root, `mise -C tools/mail run -`; the generator's `fixtures` and `tnef` run from `generator/`, `mise -C generator run -`. docproc's own `mise run check` runs this tool's check. The reasoning behind its configuration is on -[`docs/tool-builds.md`](../../docs/tool-builds.md). +[`generator/mise.toml`](generator/mise.toml), which the tool's check, golden, and publish never +load. Its tasks run from this directory, `mise run `, or from the repository root, `mise -C +tools/mail run `; the generator's `fixtures` and `tnef` run from `generator/`, `mise -C +generator run `. docproc's own `mise run check` runs this tool's check. The reasoning behind +its configuration is on [`docs/tool-builds.md`](../../docs/tool-builds.md). - `check`: shellchecks the scripts, verifies formatting, lints with warnings as errors, and runs the tests of docproc-mail and of the shared crate, [`tools/envelope`](../envelope), against the diff --git a/tools/mail/generator/Fixtures.cs b/tools/mail/generator/Fixtures.cs index 7bfc7592..5e710b38 100644 --- a/tools/mail/generator/Fixtures.cs +++ b/tools/mail/generator/Fixtures.cs @@ -21,7 +21,7 @@ namespace Docproc.Mail.Generator; public static class Fixtures { const string Note = - "Written by the generator (MISE_ENV=fixtures mise run fixtures); edit layout.json, the " + "Written by the generator (mise -C generator run fixtures); edit layout.json, the " + ".eml sources or the item sources, never this file. Each output was built twice in the " + "run, and byte_stable is whether the two builds were identical. Neither format is: PST Builder 1.3.0 writes a " + "random store UID and a random search key per message (Guid.NewGuid), and MsgKit 3.0.6 " diff --git a/tools/mail/generator/Tnef.cs b/tools/mail/generator/Tnef.cs index e3dd9212..88befd10 100644 --- a/tools/mail/generator/Tnef.cs +++ b/tools/mail/generator/Tnef.cs @@ -22,7 +22,7 @@ namespace Docproc.Mail.Generator; public static class Tnef { const string Note = - "Written by the generator (MISE_ENV=fixtures mise run tnef); edit layout.json, never this " + "Written by the generator (mise -C generator run tnef); edit layout.json, never this " + "file or the .eml under eml/. Each entry is what MimeKit's TnefPart reads of its TNEF " + "stream: ConvertToMessage's HTML, text and RTF bodies, the RTF decompressed, and its " + "attachments, with compliance, TnefReader's status for the stream read through in its " diff --git a/tools/mail/tests/fixtures/generated/manifest.json b/tools/mail/tests/fixtures/generated/manifest.json index a5966578..ff6c9665 100644 --- a/tools/mail/tests/fixtures/generated/manifest.json +++ b/tools/mail/tests/fixtures/generated/manifest.json @@ -1,5 +1,5 @@ { - "note": "Written by the generator (MISE_ENV=fixtures mise run fixtures); edit layout.json, the .eml sources or the item sources, never this file. Each output was built twice in the run, and byte_stable is whether the two builds were identical. Neither format is: PST Builder 1.3.0 writes a random store UID and a random search key per message (Guid.NewGuid), and MsgKit 3.0.6 random record keys and entry IDs and the time of conversion as the creation and modification times. So each output's sha256 records the committed file only; a rerun shows drift in an output's size, and the tests show drift in its content.", + "note": "Written by the generator (mise -C generator run fixtures); edit layout.json, the .eml sources or the item sources, never this file. Each output was built twice in the run, and byte_stable is whether the two builds were identical. Neither format is: PST Builder 1.3.0 writes a random store UID and a random search key per message (Guid.NewGuid), and MsgKit 3.0.6 random record keys and entry IDs and the time of conversion as the creation and modification times. So each output's sha256 records the committed file only; a rerun shows drift in an output's size, and the tests show drift in its content.", "tools": { "dotnet-sdk": "11.0.100", "dotnet-runtime": "11.0.0", diff --git a/tools/mail/tests/fixtures/tnef/truth.json b/tools/mail/tests/fixtures/tnef/truth.json index fb2e91d5..65e3fa12 100644 --- a/tools/mail/tests/fixtures/tnef/truth.json +++ b/tools/mail/tests/fixtures/tnef/truth.json @@ -1,5 +1,5 @@ { - "note": "Written by the generator (MISE_ENV=fixtures mise run tnef); edit layout.json, never this file or the .eml under eml/. Each entry is what MimeKit's TnefPart reads of its TNEF stream: ConvertToMessage's HTML, text and RTF bodies, the RTF decompressed, and its attachments, with compliance, TnefReader's status for the stream read through in its loose mode, or, for a stream TnefPart can't read, its exception's message.", + "note": "Written by the generator (mise -C generator run tnef); edit layout.json, never this file or the .eml under eml/. Each entry is what MimeKit's TnefPart reads of its TNEF stream: ConvertToMessage's HTML, text and RTF bodies, the RTF decompressed, and its attachments, with compliance, TnefReader's status for the stream read through in its loose mode, or, for a stream TnefPart can't read, its exception's message.", "tools": { "MimeKit": "4.18.2" }, From 504f465ecea34247af4eb3af8a6a9837f144342e Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 13:57:04 -0500 Subject: [PATCH 09/10] =?UTF-8?q?harness.layout=20=C2=B7=20docproc=20?= =?UTF-8?q?=C2=B7=20gaps=20after=20review:=20the=20changelogs=20and=20mail?= =?UTF-8?q?-parser=201.0.3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each module's changelog records the task under Unreleased, after go-core's and sqlate's: the base module the test/ placement, the module-internal stage adapters, the removed media-name writer, tooltest.Testdata, the check's step scripts, the agent tasks and profile, build, fmt, tidy, and the file tasks; storage and postgres their test/ placement; cmd/docproc its test/ placement with its two exceptions and build's bin/docproc. The marathon pin takes no entry, as neither precedent records one. tools/onenote's and tools/ooxml's changelogs cover their output contract alone, so their file tasks take no entry; nor does tools/mail's generator move. tools/mail locks mail-parser 1.0.3, taken through its upgrade task. Its fixes are to ISO-2022-JP text with consecutive escape sequences and to its own HTML-to-text conversion, which docproc-mail doesn't use (htmd converts HTML); re-recording the goldens, the ISO-2022-JP fixtures among them, changes none. currency now reports only the held MimeKit, MsgKit, and typed-path. --- CHANGELOG.md | 24 ++++++++++++++++++++++++ cmd/docproc/CHANGELOG.md | 9 +++++++++ postgres/CHANGELOG.md | 5 +++++ storage/CHANGELOG.md | 5 +++++ tools/mail/CHANGELOG.md | 3 +++ tools/mail/Cargo.lock | 4 ++-- 6 files changed, 48 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05addd65..b09fdb0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,30 @@ tool under `tools/` keeps its own. ## [Unreleased] +### Changed + +- Each package's unit tests sit in its `test/` directory as an external test package + (`/test/*_test.go`), the helper packages `dispatch/dispatchtest`, `internal/tooltest`, and + `internal/goldentest` included, with each package's fixtures in `/test/testdata/`. A test + reading another package's fixtures names them through `internal/tooltest.Testdata`, which fails + the test on a missing fixture, and the helpers the stages tests share are in the internal package + `stages/internal/stagestest`. No exported API changes. +- The stage adapters and the failure classification sit in the internal package + `stages/internal/adapter`, from which `stages.Build` wires the stages. `stages` declares the same + identifiers as before. No exported API changes. +- `internal/cli` no longer has its own unexported media-name writer, which nothing used: the Rust + envelope owns the writer. +- The repository's check runs as step scripts in `scripts/check/` (`go.sh`, `sqlint.sh`, + `tools.sh`, `lints.sh`), which `mise run check` runs in turn; CI's go and lints jobs run the + scripts themselves. +- Agent tasks live in the agent area, `.agent/mise-tasks/`, which only the `agent` profile + (`mise.agent.toml`, under `MISE_ENV=agent`) loads: one task per check step, plus `test`, `vet`, + and `lint`, which replace the inline `check:go` and `lint` tasks. A person's tasks are `check`, + `currency`, `upgrade`, `build`, `fmt`, `tidy`, and the integration tasks. +- `build` builds the docproc command into the git-ignored `bin/`; `fmt` formats every Go source + file, and `tidy` runs `go mod tidy` in every Go module. +- The repository's multi-line tasks are file tasks in `mise-tasks/`, under the same names. + ## [v0.11.0] - 2026-11-28 This release adds the package `settings`, which holds a run's settings as one flat JSON object, so diff --git a/cmd/docproc/CHANGELOG.md b/cmd/docproc/CHANGELOG.md index d03e63ea..90706f4b 100644 --- a/cmd/docproc/CHANGELOG.md +++ b/cmd/docproc/CHANGELOG.md @@ -10,6 +10,15 @@ postgres modules, and each system tool under `tools/` keep their own. ## [Unreleased] +### Changed + +- Each package's tests sit in its `test/` directory as an external test package + (`/test/*_test.go`), with its fixtures in `/test/testdata/`, except two: the + built-binary tier in `integration/`, and `internal/run`'s test of its birth-time probe hook, which + stays beside its `export_test.go`. The command line, run directory, and exit codes don't change. +- `mise run build` at the repository root writes the docproc command to the git-ignored + `bin/docproc`. + ## [v0.2.9] - 2026-11-28 This release reads its run bounds through the docproc base module's new package `settings`, at diff --git a/postgres/CHANGELOG.md b/postgres/CHANGELOG.md index 86c580d1..19d0d3c6 100644 --- a/postgres/CHANGELOG.md +++ b/postgres/CHANGELOG.md @@ -10,6 +10,11 @@ each system tool under `tools/` keep their own. ## [Unreleased] +### Changed + +- The module's unit tests and integration suite sit in its `test/` directory as an external test + package. No exported API changes. + ## [v0.1.9] - 2026-11-28 This release requires the docproc base module at v0.11.0. Its exported API is unchanged. diff --git a/storage/CHANGELOG.md b/storage/CHANGELOG.md index fe454b4f..a0050025 100644 --- a/storage/CHANGELOG.md +++ b/storage/CHANGELOG.md @@ -10,6 +10,11 @@ each system tool under `tools/` keep their own. ## [Unreleased] +### Changed + +- The module's unit tests and integration suite sit in its `test/` directory as an external test + package. No exported API changes. + ## [v0.1.9] - 2026-11-28 This release requires the docproc base module at v0.11.0. Its exported API is unchanged. diff --git a/tools/mail/CHANGELOG.md b/tools/mail/CHANGELOG.md index bf6f05cd..4ce52ce3 100644 --- a/tools/mail/CHANGELOG.md +++ b/tools/mail/CHANGELOG.md @@ -13,6 +13,9 @@ output contract: a change to them is a change here. This changelog covers docpro - The crate graph takes htmd 0.7.0 in place of 0.6.1. Its new converter options are opt-in, and the output is unchanged. +- The crate graph locks mail-parser 1.0.3, a patch release, in place of 1.0.2. Its fixes are to + ISO-2022-JP text with two escape sequences in a row and to its own HTML-to-text conversion, which + docproc-mail doesn't use; the output is unchanged. ## [v0.2.0] - 2026-11-25 diff --git a/tools/mail/Cargo.lock b/tools/mail/Cargo.lock index d0249d3f..bfab9818 100644 --- a/tools/mail/Cargo.lock +++ b/tools/mail/Cargo.lock @@ -431,9 +431,9 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "mail-parser" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e57f7caaeb0071026b4be388c81e9c253853d9ed072a3061d425ef1c1b1b569" +checksum = "94566d105248e1623dd2310333c897389d3c3fdef8f1339f3f6fcf7b3cc14774" dependencies = [ "encodify", "encoding_rs", From 1fdc07909e0a538623add813bbdc67d30a9ca2fa Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 14:01:42 -0500 Subject: [PATCH 10/10] =?UTF-8?q?harness.layout=20=C2=B7=20docproc=20?= =?UTF-8?q?=C2=B7=20editor=20pass:=20the=20changed=20prose?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 9 ++++++--- CLAUDE.md | 13 +++++++------ README.md | 2 +- docs/ci.md | 4 ++-- docs/development.md | 36 ++++++++++++++++++------------------ docs/tool-builds.md | 17 ++++++++--------- 6 files changed, 42 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b09fdb0a..29921d2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,9 +26,12 @@ tool under `tools/` keeps its own. `tools.sh`, `lints.sh`), which `mise run check` runs in turn; CI's go and lints jobs run the scripts themselves. - Agent tasks live in the agent area, `.agent/mise-tasks/`, which only the `agent` profile - (`mise.agent.toml`, under `MISE_ENV=agent`) loads: one task per check step, plus `test`, `vet`, - and `lint`, which replace the inline `check:go` and `lint` tasks. A person's tasks are `check`, - `currency`, `upgrade`, `build`, `fmt`, `tidy`, and the integration tasks. + (`mise.agent.toml`, under `MISE_ENV=agent`) loads: `check:go`, `check:sqlint`, `check:tools`, + and `check:lints`, one per check step, and `test`, `vet`, and `lint`, one per gate of the Go + step. The inline `check:go` and `lint` tasks a person saw are agent tasks now: `check:go` runs + the Go step alone, its sqlint run is `check:sqlint`, the old `lint`'s lints are `check:lints`, + and `lint` runs golangci-lint. A person's tasks are `check`, `currency`, `upgrade`, `build`, + `fmt`, `tidy`, and the integration tasks. - `build` builds the docproc command into the git-ignored `bin/`; `fmt` formats every Go source file, and `tidy` runs `go mod tidy` in every Go module. - The repository's multi-line tasks are file tasks in `mise-tasks/`, under the same names. diff --git a/CLAUDE.md b/CLAUDE.md index 3a3c92e4..d0e9eccd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -28,12 +28,13 @@ The extraction library adjacent to Go Elemental, with the system tools it runs n - [`tools/envelope/src/lib.rs`](tools/envelope/src/lib.rs): docproc-envelope, the Rust tools' shared envelope crate, tested by each Rust tool's check. - `mise run check`: the check. `.claude/settings.json` sets `MISE_ENV=agent`, the agent profile, - which adds the agent's tasks under `.agent/mise-tasks/`: the check's steps alone (`check:go`, - `check:sqlint`, `check:tools`, `check:lints`) and the Go step's gates (`test`, `vet`, `lint`); - [`docs/development.md`](docs/development.md) states every task, a person's and an agent's. -- Tests: each package's in its `test/` directory, with the one `export_test.go` and the - built-binary `cmd/docproc/integration` package as the exceptions; - [`docs/development.md`](docs/development.md#where-the-tests-sit) states where each sits. + which adds the agent's tasks under `.agent/mise-tasks/`: one per check step (`check:go`, + `check:sqlint`, `check:tools`, `check:lints`) and one per gate of the Go step (`test`, `vet`, + `lint`); [`docs/development.md`](docs/development.md) states every task, a person's and an + agent's. +- Tests: each package's tests sit in its `test/` directory, except `cmd/docproc/internal/run`'s + one `export_test.go` with the test that uses it, and the built-binary `cmd/docproc/integration` + package; [`docs/development.md`](docs/development.md#where-the-tests-sit) states where each sits. - `mise run integration`: the providers' live tiers, `integration:postgres` and `integration:storage`, each against its own compose service; `mise run test:integration`, the pre-tag run, the tools tier and cmd/docproc's built-binary tier over this checkout's tool diff --git a/README.md b/README.md index 65585fd7..117a8bb5 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ the reference for its exported names, and its doc comment lists them. - [The command](docs/command.md): `cmd/docproc`'s commands, exit statuses, and configuration. - [Limits](docs/limits.md): what docproc doesn't read, and the limits each stage inherits from its tool. -- [Development](docs/development.md): the toolchain, the tasks, a person's and an agent's, where the +- [Development](docs/development.md): the toolchain, a person's and an agent's tasks, where the tests sit, the compose harness, and releases. ## Providers diff --git a/docs/ci.md b/docs/ci.md index abf66ae4..7c14cb84 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -11,8 +11,8 @@ through mise-action or a task's auto-install. CI runs on every pull request into main, every push to main, and on demand. A newer run on the same ref cancels the one it supersedes. The go and lints jobs run the check's step scripts under -`scripts/check/` directly, and the tool and integration jobs a person's tasks; no job runs under -`MISE_ENV=agent` or an agent's task. +`scripts/check/` directly, and the tool and integration jobs run a person's tasks; no job sets +`MISE_ENV=agent` or runs an agent's task. - **changes** decides which of the tool, go, and integration jobs run, through one paths filter each. diff --git a/docs/development.md b/docs/development.md index 6c1c6c3f..41bb6c53 100644 --- a/docs/development.md +++ b/docs/development.md @@ -62,8 +62,8 @@ Two packages keep test files beside their source: - `cmd/docproc/integration`: the command's built-binary integration tier, a package at the module's root, its harness untagged and its suite under the `integration` tag. -An agent's scratch tests go in the agent area, `.agent/`, never in `test/`. The rules are -`architecture/standards/go-elemental/principles/tests-and-docs.md`'s, "The unit tier" and +An agent's scratch tests go in the agent area, `.agent/`, never in `test/`. The rules are in +`architecture/standards/go-elemental/principles/tests-and-docs.md`, "The unit tier" and "Integration and acceptance suites". ## The root mise.toml @@ -91,11 +91,11 @@ Its environment: - `DOCPROC_DSN`, `DOCPROC_S3_ENDPOINT`, `DOCPROC_S3_ACCESS_KEY`, and `DOCPROC_S3_SECRET_KEY`: the live tiers' servers, below. -Its one-line tasks stay in it; each multi-line task is a file task under +Its one-line tasks are inline in it; each multi-line task is a file task under [`mise-tasks/`](../mise-tasks). The agent's tasks are file tasks under `.agent/mise-tasks/`, which -only `MISE_ENV=agent` loads, through [`mise.agent.toml`](../mise.agent.toml), the agent profile -and the repository's only one; `.claude/settings.json` sets it, so an agent has a person's tasks -and its own, and a person, with no profile set, only theirs. Its tasks: +only `MISE_ENV=agent` loads, through [`mise.agent.toml`](../mise.agent.toml), the agent profile and +the repository's only mise profile. `.claude/settings.json` sets `MISE_ENV=agent`, so an agent has +a person's tasks and its own, and a person, with no profile set, has only theirs. Its tasks: - `check` is the one check: read-only and deterministic. It runs the step scripts under [`scripts/check/`](../scripts/check) in turn: the Go step, the sqlint step, the tools step, then @@ -110,14 +110,15 @@ and its own, and a person, with no profile set, only theirs. Its tasks: - The tools step, `scripts/check/tools.sh`, runs each tool's check, then writes the notices a release would pack for this machine to nowhere, so a package the notices script can't give a notice for fails there, not at the tag. -- The lints step, `scripts/check/lints.sh`: shellcheck over the shell scripts and the file tasks, - the tools' among them, actionlint, the tag-routing test, then lint-context and lint-references, - each run before the step fails if any failed. A lint missing from PATH fails the step with - `FAIL: is not on PATH; run mise install`. actionlint shellchecks each workflow's `run:` - blocks too, with the shellcheck pinned in mise.toml. The release workflow's tag routing is a - script, so its test runs here, beside the workflow it routes. -- The agent's tasks run the steps one at a time: `check:go`, `check:sqlint`, `check:tools`, and - `check:lints`, and the Go step's gates `test`, `vet`, and `lint` alone. +- The lints step, `scripts/check/lints.sh`, runs shellcheck over the shell scripts and the file + tasks, the tools' among them, actionlint, the tag-routing test, then lint-context and + lint-references, running each before the step fails if any failed. A lint missing from PATH + fails the step with `FAIL: is not on PATH; run mise install`. actionlint shellchecks each + workflow's `run:` blocks too, with the shellcheck pinned in mise.toml. The release workflow's tag + routing is a script, so its test runs here, beside the workflow it routes. +- The agent's tasks each run one part of the check: `check:go`, `check:sqlint`, `check:tools`, and + `check:lints` one step each, and `test`, `vet`, and `lint` one gate of the Go step each, in + every module. - `test:integration`: each docproc tool is built from this checkout through its own publish task, and the three binaries alone are linked into a directory put ahead of everything else on PATH. Packages run in parallel, as the unit tier's do: each container test watches only the containers @@ -195,10 +196,9 @@ hold the module to its own requirements. suppression to name its linter and give a reason, and testpackage, which keeps tests black-box. testpackage's skip regexp is narrowed to `export_test.go`: tests live in `_test` and drive the exported API, and the one white-box file allowed is `export_test.go` - ([above](#where-the-tests-sit)). Its `allow-packages` - is narrowed from its default, `main`, so a command's tests are black-box too, in `main_test`. It - names only the empty package name, which no package has: an empty list leaves the default, - `main`, in force. + ([above](#where-the-tests-sit)). Its `allow-packages` is narrowed from its default, `main`, so a + command's tests are black-box too, in `main_test`. It names only the empty package name, which + no package has: an empty list leaves the default, `main`, in force. - depguard's allow entries match by prefix unless they end in `$`, so each module's entries are anchored: the module as itself or a package under it (not a sibling like `docproc-extra`). The longest match wins, so the deny entries keep the other modules out despite docproc's prefix, diff --git a/docs/tool-builds.md b/docs/tool-builds.md index 74b8e82d..d289068d 100644 --- a/docs/tool-builds.md +++ b/docs/tool-builds.md @@ -2,8 +2,8 @@ Each system tool under `tools/` has its own mise.toml, which pins its toolchain alone and defines its one-line tasks; each multi-line task is a file task under the tool's own `mise-tasks/`. Each -README's "Building and testing" states what the tasks do. docproc's root check, -currency, and upgrade run each tool's tasks through the root's `TOOLS` list (`mise -C +README's "Building and testing" states what the tasks do. docproc's root check, currency, and +upgrade run each tool's tasks through the root's `TOOLS` list (`mise -C tools/ run check`), and `tools/pack.sh` runs `publish` to build the release binary it packs; the release workflow runs that on each runner, natively ([CI and releases](ci.md)). Each task runs in the tool's directory. This page holds the reasoning behind the tools' configuration. @@ -152,13 +152,12 @@ only a newer release of a crate can clear. Run it, review the diff, and run each mise's `CARGO_HOME` ahead of a host cargo on PATH; mise's `RUSTUP_TOOLCHAIN` picks the toolchain. Each call is a new mise process, so after the upgrade has rewritten the mise files it runs the toolchain just pinned. -- **The mise tools.** The tool's mise.toml is read, and each of its subdirectories' mise.toml, so - docproc-mail's fixture generator's SDK, in `generator/mise.toml`, is read with the tool's; the - root's are its own. - The upgrade rewrites each in place, its version alone, as `mise use` would write rust's table - as a bare version. A backend-qualified name, such as `github:EmbarkStudios/cargo-about`, is a - quoted key holding a `/`, so the name is matched with its quotes optional and its regex - characters escaped, under a `|` delimiter. +- **The mise tools.** The script reads the tool's mise.toml and the mise.toml of each directory + directly under it, so docproc-mail's fixture generator's SDK, in `generator/mise.toml`, is read + with the tool's; the root's are its own. The upgrade rewrites each in place, its version alone, + as `mise use` would write rust's table as a bare version. A backend-qualified name, such as + `github:EmbarkStudios/cargo-about`, is a quoted key holding a `/`, so the name is matched with + its quotes optional and its regex characters escaped, under a `|` delimiter. - **The crates.** Direct and indirect: updates within each requirement (cargo's `Updating`) and newer releases beyond it (`Unchanged ... (available: ...)`), read from a `--dry-run` that leaves Cargo.lock as it is. Each scan is captured before it is read, and each capture ends in