diff --git a/README.md b/README.md index f52a19a..6dae3f6 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Apify Test Tools -Build, test and release Apify Actors from a Git repository or local source code. The package has three parts: +Build, test, and release Apify Actors from a Git repository or local source code. The package has three parts: -1. **A vitest library** for writing platform tests that run your Actors on Apify and check the results: +1. **A Vitest library** for writing platform tests that run your Actors on Apify and check the results: ```ts testActor('myteam/web-scraper', 'scrapes the start URL', async ({ expect, run }) => { @@ -11,8 +11,8 @@ Build, test and release Apify Actors from a Git repository or local source code. }); ``` -2. **A CLI** that finds the Actors a change affects, builds them, and reports the results. It runs anywhere, so you - can build your own pipeline on it in any CI: +2. **A CLI** that finds the Actors a change affects, builds and tests them, and reports the results. It runs anywhere, + so you can build your own pipeline on it in any CI: ```bash npx apify-test-tools get-affected-actors --base origin/master \ @@ -25,7 +25,7 @@ Build, test and release Apify Actors from a Git repository or local source code. ```yaml jobs: - buildDevelAndTest: + buildAndTest: uses: apify/apify-test-tools/.github/workflows/public_pr-build-test.yaml@workflows-v1 secrets: # One entry per secret apify-test-tools.config.json names: each `buildTokenEnvVar` and `testTokenEnvVar` @@ -42,30 +42,32 @@ Builds and platform tests cost time and money, so the tool skips everything a ch - **Only affected Actors.** A changed file counts for Actors whose context contains it, subject to ignore rules, or whose `actor.json` links it. A shared file linked from `actor.json` affects every Actor that uses it. -- **Cosmetic changes skip tests.** Linked README/changelog edits and cosmetic schema changes don't trigger tests on a PR; - they're only rebuilt when released. +- **Cosmetic changes skip tests.** Edits to a linked README or changelog, and cosmetic schema changes, don't trigger + tests on a PR. The Actor only gets a new build when they're released. - **Only new changes on a PR.** Each push to a PR retests only the Actors that changed since its last green run, not the whole PR again. -- **Only their tests.** Only the tests of the Actors that were built run. +- **Only their tests.** Only the tests of the affected Actors run. See [Change detection](docs/cli.md#change-detection) for the exact rules. This README covers what you need to get a repo running. The full reference lives in `docs/`: -- [Vitest library API](docs/lib.md) — `testActor`, `testServerInterfaceActor`, `RunTestResult`, matchers, running tests locally -- [CLI API](docs/cli.md) — every command, change detection, releasing, building locally -- [Workflow API](docs/workflows.md) — every GitHub workflow, its inputs and secrets, versioning -- [Migrating to v1](docs/migrating-to-v1.md) — updating a repository from `@workflows-v0` and a library before 1.0 +- [Vitest library API](docs/lib.md): `testActor`, `testServerInterfaceActor`, `RunTestResult`, matchers, and running + tests locally +- [CLI API](docs/cli.md): every command, change detection, releasing, and building locally +- [Workflow API](docs/workflows.md): every GitHub workflow, its inputs and secrets, and versioning +- [Migrating to v1](docs/migrating-to-v1.md): updating a repository from `@workflows-v0` and a library before 1.0 [Contributing](CONTRIBUTING.md) ## Getting started Your Actors can be written in any programming language, e.g. Python: anything the platform builds from a Dockerfile -works. Only the tests and this tooling run on Node.js, so all a repo needs is a `package.json` at the root with -`apify-test-tools` and `vitest` in its `devDependencies`, and tests written in TypeScript or JavaScript. If you use the -[PR workflow](docs/workflows.md#public_pr-build-testyaml), also define the `build-check`, `lint` and `test` scripts -its static checks run, e.g. with your language's own linter and unit tests. +works. Only the tests and this tooling run on Node.js, so a repo needs a `package.json` at the root with +`apify-test-tools` and `vitest` in its `devDependencies`, and tests written in TypeScript or JavaScript. The +[PR workflow](docs/workflows.md#public_pr-build-testyaml) also runs the `lint` and `test` scripts as static checks, so +define them, e.g. with your language's own linter and unit tests. It runs a `build-check` script too if you define +one, and `tsc --noEmit` otherwise. ### 1. Install the package @@ -73,10 +75,10 @@ its static checks run, e.g. with your language's own linter and unit tests. npm i -D apify-test-tools ``` -- Requires Node.js 22.12+, 24 or 26+ and `vitest` 5 or later (uses [annotate](https://vitest.dev/guide/test-context.html#annotate)) +- Requires Node.js 22.12+, 24, or 26+, and Vitest 5 or later - Make sure `target` and `module` in your `tsconfig.json`'s `compilerOptions` are set to `ES2022` - Every Actor must already have at least one build under its default build tag (usually `latest`), built - from a Git repository version whose URL points to this repository. Build it once manually on the + from a Git repository version whose URL points to your repository. Build it once manually on the platform before CI takes over. See [Repository check](docs/cli.md#repository-check). ### 2. Create the config file @@ -177,15 +179,19 @@ its Actors: } ``` -The group key (`myteam` above) is only a label for readability; it doesn't need to match any folder or username. Each -group needs a `buildTokenEnvVar`, a `testTokenEnvVar` and at least one Actor. Add another group for Actors that need a -different token, e.g. Actors owned by another account. +The orchestrator sets `overrideActorContext` because its tests live outside its own folder: without it, a change to +only `test/platform/orchestrator` wouldn't test it. The other two already have the whole repo, tests included, as +their context. + +The group key (`myteam` above) is only a label. It doesn't need to match any folder or username. Each group needs a +`buildTokenEnvVar`, a `testTokenEnvVar`, and at least one Actor. Add another group for Actors that need a different +token, e.g. Actors owned by another account. `buildTokenEnvVar` names the token that builds the Actors, `testTokenEnvVar` the one their platform tests run them with, so the test runs start in that token's account. The two can name the same env var, as `myteam` does above, or the tests can run with a token that may do less. [Token permissions](#token-permissions) says what each one needs. -Here the tests of the partner's Actors run with a scoped tester token. The search Actor sets its own +For example, a `partner` group can test its Actors with a scoped tester token, while its search Actor sets its own `testTokenEnvVar`, the partner's full token, because its tests call its server interface on the PR build: ```json @@ -203,19 +209,15 @@ Here the tests of the partner's Actors run with a scoped tester token. The searc } ``` -The orchestrator sets `overrideActorContext` because its tests live outside its own folder: without it, a change to -only `test/platform/orchestrator` wouldn't test it. The other two already have the whole repo, tests included, as -their context. - -| Field | Where | Required | Description | -| ---------------------- | -------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `mode` | top level | yes | Always `"grouped"`. | -| `folder` | Actor | yes | Relative path from repo root to the Actor's own project directory — the folder that directly contains `.actor/actor.json` (i.e. `/.actor/actor.json`) and its source. Documentation and schemas may be linked from elsewhere through `actor.json`. Use `"."` for a single-Actor repo where `.actor/` is at the root. | -| `actorFullName` | Actor | yes | Full Actor identifier in `owner/name` format (e.g. `"apify/web-scraper"`). This is the source of truth for the Actor name — the `name` field in `actor.json` is not used. | -| `buildTokenEnvVar` | group or Actor | yes | Name of the environment variable holding the Apify API token that builds the group's Actors. It needs full permissions, see [Token permissions](#token-permissions). No fallback — if the env var is not set at build time, the build fails. | -| `testTokenEnvVar` | group or Actor | yes | Name of the environment variable holding the Apify API token the platform tests run the group's Actors with. Server interface tests need a full-permission token, e.g. the same env var as `buildTokenEnvVar`; other tests can use a scoped token, see [Token permissions](#token-permissions). If the env var is not set, the tests of the Actors that use it fail. | -| `platformTestsGlob` | top level | no | Glob from the repo root of the platform tests and their helpers. Default `test/platform/**`. A changed file that matches it is a test change, also when `.dockerignore` lists it: the PR workflow builds and tests the Actor whose context holds it, and a release skips it. See [Change detection](docs/cli.md#change-detection). | -| `overrideActorContext` | group or Actor | no | Array of paths (relative to repo root) that define which files are relevant to the Actor. When set, replaces the `dockerContextDir` from `actor.json` for change detection. Useful when an Actor depends on shared packages outside its Docker build context. Entries must not be prefixes of one another (e.g. `["", "code"]` or `["actors", "actors/foo"]` are rejected). The Actor's own `folder` is always part of its context — if none of the listed entries reach it, it's added automatically. | +| Field | Where | Required | Description | +| ---------------------- | -------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `mode` | top level | yes | Always `"grouped"`. | +| `folder` | Actor | yes | Relative path from the repo root to the Actor's own folder, the one that directly contains `.actor/actor.json` and its source. Use `"."` for a single-Actor repo where `.actor/` is at the root. | +| `actorFullName` | Actor | yes | The Actor's full name, `owner/name`, e.g. `"apify/web-scraper"`. The tool names the Actor by it, not by the `name` field in `actor.json`. | +| `buildTokenEnvVar` | group or Actor | yes | Name of the environment variable holding the Apify API token that builds the group's Actors. It needs full permissions, see [Token permissions](#token-permissions). If the env var isn't set at build time, the build fails. | +| `testTokenEnvVar` | group or Actor | yes | Name of the environment variable holding the Apify API token the platform tests run the group's Actors with. Server interface tests need a full-permission token, e.g. the same env var as `buildTokenEnvVar`; other tests can use a scoped token, see [Token permissions](#token-permissions). If the env var is not set, the tests of the Actors that use it fail. | +| `platformTestsGlob` | top level | no | Glob from the repo root of the platform tests and their helpers. Default `test/platform/**`. A changed file that matches it is a test change, also when `.dockerignore` lists it: the PR workflow builds and tests the Actor whose context holds it, and a release skips it. See [Change detection](docs/cli.md#change-detection). | +| `overrideActorContext` | group or Actor | no | Paths, relative to the repo root, whose changes count for the Actor. Replaces the `dockerContextDir` from `actor.json` for change detection, e.g. when an Actor depends on shared packages outside its Docker build context. No entry may be a prefix of another, so `["", "code"]` and `["actors", "actors/foo"]` are rejected. The Actor's own `folder` always counts: if no entry contains it, it's added. | A value set on an Actor replaces the group's for that Actor only. Values are replaced, not merged: if the `myteam` group also set `overrideActorContext`, the orchestrator would still get only the two paths it lists. @@ -224,7 +226,7 @@ No two Actors may share a `folder`, and no two entries may point at the same `ac ### Token permissions -- **`buildTokenEnvVar`** needs a token with full permissions, for now. It builds the Actors, creates their versions and +- **`buildTokenEnvVar`** needs a token with full permissions, for now. It builds the Actors, creates their versions, and deletes their old builds. A token that needs less is planned. - **`testTokenEnvVar`** depends on the tests: - **Server interface tests need a full-permission token**, of the Actor's owner or of an account with write access @@ -239,21 +241,20 @@ No two Actors may share a `folder`, and no two entries may point at the same `ac The workflows take every change straight to production, with tests in between: -- **Every push to a PR** builds the Actors the PR changes into a test version (`0.99`) that users never run, and runs - their platform tests against those builds. Only the Actors whose files changed are built and tested, and a later - push only re-tests what changed since the last green run. -- **Every merge to `master`** builds the changed Actors into their default version (`latest`), which is what users - run, and announces the release on Slack. There is no separate release step. +- **Every push to a PR** builds the Actors the PR affects into a test version (`0.99`) that users never run, and runs + their platform tests against those builds. See [Only what changed is retested](#only-what-changed-is-retested). +- **Every merge to `master`** builds the affected Actors into their default version, whose build users run (usually + tagged `latest`), and can announce the release on Slack. There is no separate release step. - **Scheduled runs** (optional) run the tests against the released builds to catch what breaks without a code change, like a website changing its layout. These are GitHub Actions workflows. On another CI platform, build the same flow with the [CLI](docs/cli.md). Add these files to `.github/workflows` in your repo. They call the reusable workflows in this repo, pinned at the -`@workflows-v1` major tag — never at `@master`. Every input, the optional Claude workflows, stale issue closer, and how the tag moves are -in the [Workflow API](docs/workflows.md). +`@workflows-v1` major tag, never at `@master`. The [Workflow API](docs/workflows.md) covers every input, the optional +Claude workflows, the stale issue closer, and how the tag moves. -### `pr-build-devel-test.yaml` +### `pr-test.yaml` ```yaml name: PR Test @@ -263,7 +264,7 @@ on: branches: [master] jobs: - buildDevelAndTest: + buildAndTest: uses: apify/apify-test-tools/.github/workflows/public_pr-build-test.yaml@workflows-v1 secrets: # One entry per secret apify-test-tools.config.json names: each `buildTokenEnvVar` and `testTokenEnvVar` @@ -286,6 +287,9 @@ on: jobs: buildLatest: uses: apify/apify-test-tools/.github/workflows/public_push-build-latest.yaml@workflows-v1 + with: + # Leave it out to skip the announcement + report-slack-channel: '#notif-my-repo' secrets: SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }} # One entry per secret apify-test-tools.config.json names, here each `buildTokenEnvVar` @@ -315,6 +319,8 @@ jobs: uses: apify/apify-test-tools/.github/workflows/public_platform-tests.yaml@workflows-v1 with: test-files-glob: 'test/platform/{daily,daily-without-pr}/**' + # Where failures are reported. Leave it out to skip Slack + report-slack-channel: '#notif-my-repo' secrets: SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }} # One entry per token the tests run with: each `testTokenEnvVar` @@ -341,6 +347,7 @@ jobs: uses: apify/apify-test-tools/.github/workflows/public_platform-tests.yaml@workflows-v1 with: test-files-glob: 'test/platform/{hourly,hourly-without-pr}/**' + report-slack-channel: '#notif-my-repo' secrets: SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }} CONFIG_SECRETS: | @@ -353,12 +360,13 @@ jobs: ### Secrets Set these as repository or organization secrets and pass them in each job's `secrets:` block, as in the examples -above. The Actor tokens go packed in one JSON object, `CONFIG_SECRETS`, because their names differ per repo: +above. The Apify tokens, build and test, go packed in one JSON object, `CONFIG_SECRETS`, because their names differ per +repo: | Secret | Needed for | | ------------------------------------------------------------------------------ | ----------------------------------------------------------------- | -| the Actor tokens named by `buildTokenEnvVar` in `apify-test-tools.config.json` | building Actors and deleting their old builds | -| the test tokens named by `testTokenEnvVar`, which can be the Actor tokens | running the platform tests | +| the build tokens named by `buildTokenEnvVar` in `apify-test-tools.config.json` | building Actors and deleting their old builds | +| the test tokens named by `testTokenEnvVar`, which can be the build tokens | running the platform tests | | `SLACK_BOT_TOKEN` | announcing releases and reporting scheduled test results to Slack | | `NPM_TOKEN` | optional, installing private npm packages. Use a read-only token | @@ -369,8 +377,9 @@ without listing the tokens. ## Writing tests Platform tests use `describe` and `testActor` from `apify-test-tools` instead of the ones from `vitest`. `testActor` -registers a test that only runs when that Actor was built for it (or when you ask for all tests), and gives the -callback an extended `expect` and a `run` function that starts the Actor. +registers a test that runs only when [`test`](docs/cli.md#running-tests-test) passes its Actor: on a PR, with the build +made for it, and otherwise on its default build. Your regular unit test run stays unaffected. The callback gets an +extended `expect` and a `run` function that starts the Actor. ```ts import { describe, testActor } from 'apify-test-tools'; @@ -391,10 +400,7 @@ describe('web-scraper', () => { The failed requests come from the crawler statistics that Crawlee saves. **An Actor without crawler statistics, e.g. one that doesn't use Crawlee, must pass `failedRequests: null`**, or `toFinishWith` fails on the missing statistics. -Platform tests only run on the Actors [`test`](docs/cli.md#running-tests-test) passes to them, each with its -`testTokenEnvVar` token, so your regular unit test run stays unaffected. - -To run them locally against the Actors' current default builds: +To run them locally against the Actors' current default builds, with each Actor's `testTokenEnvVar` set: ```bash npx apify-test-tools get-actor-configs | APIFY_TOKEN_MYTEAM= npx apify-test-tools test diff --git a/docs/cli.md b/docs/cli.md index eff0a9a..bd02306 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1,27 +1,28 @@ # CLI API The package includes the `apify-test-tools` binary. The [reusable workflows](workflows.md) call it to find changed -Actors, build them, and report results, and you can run it locally the same way: +Actors, build them, test them, and report the results. You can run it locally the same way: ```bash npx apify-test-tools [flags] ``` -Run every command from the root of the Actor repository; it reads `apify-test-tools.config.json` from there. -Results are written to stdout as JSON, diagnostics to stderr, so commands can be piped into each other and into `jq`. +Run every command from the root of the Actor repository, where it reads `apify-test-tools.config.json`. Results go to +stdout as JSON and diagnostics to stderr, so commands can be piped into each other and into `jq`. -| Command | Does | Needs | -| --------------------------------------------------------------------- | ------------------------------------------------------- | ------------- | -| [`get-affected-actors`](#finding-affected-actors-get-affected-actors) | Lists the Actors changed in a commit range | git only | -| [`build`](#building-actors-build) | Builds the Actors given on stdin from the pushed branch | Actor tokens | -| [`build-from-local`](#build-from-local-source-build-from-local) | Builds Actors from local files | Actor tokens | -| [`test`](#running-tests-test) | Runs the platform tests on the builds given on stdin | test tokens | -| [`notify`](#notifying-notify) | Posts a test report or a release to Slack | a Slack token | -| [`delete-old-builds`](#deleting-old-builds-delete-old-builds) | Deletes old builds of the Actors | Actor tokens | -| [`get-actor-configs`](#listing-actors-get-actor-configs) | Prints the resolved config | nothing | +| Command | Does | Needs | +| --------------------------------------------------------------------- | ------------------------------------------------------- | ----------------- | +| [`get-affected-actors`](#finding-affected-actors-get-affected-actors) | Lists the Actors changed in a commit range | git only | +| [`build`](#building-actors-build) | Builds the Actors given on stdin from the pushed branch | build tokens | +| [`build-from-local`](#build-from-local-source-build-from-local) | Builds Actors from local files | build tokens | +| [`test`](#running-tests-test) | Runs the platform tests of the Actors given on stdin | test tokens | +| [`notify`](#notifying-notify) | Posts a test report or a release to Slack | `SLACK_BOT_TOKEN` | +| [`delete-old-builds`](#deleting-old-builds-delete-old-builds) | Deletes old builds of the Actors | build tokens | +| [`get-actor-configs`](#listing-actors-get-actor-configs) | Prints the resolved config | nothing | -"Actor tokens" are the environment variables named by each Actor's `buildTokenEnvVar` in the config, "test tokens" those -named by its `testTokenEnvVar`, which can be the same. A command only needs the tokens of the Actors it touches. +Build tokens are the environment variables named by each Actor's `buildTokenEnvVar` in the config, test tokens those +named by its `testTokenEnvVar`. Both can name the same variable. A command only needs the tokens of the Actors it +touches. ## Global flags @@ -29,72 +30,72 @@ named by its `testTokenEnvVar`, which can be the same. A command only needs the | ------------- | ------- | ---------------------------------------------------------------------------------------------------------------- | | `--log-level` | `info` | Minimum level written to stderr: `debug`, `info`, `warn`, `error`, or `silent`. Results on stdout are unaffected | +The CLI is strict: an unknown flag or an extra argument is an error. + ## Selecting Actors (`--actors`, `--ignore`) -Commands that read the config take `--actors` and `--ignore`, each a list of `actorFullName`s (space-separated, -or the flag repeated). `--actors` keeps only the listed Actors, `--ignore` drops them. An unknown -name is an error rather than silently selecting nothing. +`get-affected-actors`, `build-from-local`, `delete-old-builds`, and `get-actor-configs` take `--actors` and `--ignore`. +Each takes a list of Actor full names (`owner/name`), space-separated or with the flag repeated. `--actors` keeps only +the listed Actors, then `--ignore` drops the listed ones. A name that isn't in the config is an error, so a typo never +selects the wrong set. `build` and `test` take their Actors on stdin instead. ## Dry runs (`--dry-run`) -Every command that changes something (`build`, `build-from-local`, `notify`, `delete-old-builds`) takes -`--dry-run`. A dry run: +`build`, `build-from-local`, `notify`, and `delete-old-builds` take `--dry-run`. A dry run: -- **Changes nothing.** No versions or builds are created, nothing is uploaded or deleted, and no Slack message is - posted. +- **Changes nothing.** It creates no versions or builds, uploads and deletes nothing, and posts no Slack message. - **Does every read and check the real run does**, so it fails wherever the real run would: change detection, the - Apify token and Actor lookup, the [repository check](#repository-check), collecting and zipping local sources, and - the Slack token (verified with Slack's read-only `auth.test`). -- **Needs the same tokens as the real run.** Read-only tokens are enough, since nothing is written. A dry run can't - tell whether a token is also allowed to write, because the Apify API has no dry-run mode of its own. -- **Prints a plan, not results.** Logs start with `[DRY RUN] Would …`. `build` and `build-from-local` write - `{ "dryRun": true, "builds": [...] }` to stdout instead of the build array, so the plan can't be passed to tests as - `ACTOR_BUILDS` by mistake. + Apify token and Actor lookup, the [repository check](#repository-check), the [env var check](#env-var-check), + collecting and zipping local sources, and the Slack token (verified with Slack's read-only `auth.test`). +- **Needs the same tokens as the real run.** Read-only tokens are enough. A dry run can't tell whether a token may + also write, because the Apify API has no dry-run mode. +- **Prints a plan, not results.** Log lines start with `[DRY RUN] Would …`. `build` and `build-from-local` write + `{ "dryRun": true, "builds": [...] }` to stdout instead of the build array, and `test` rejects it, so a plan can't + be tested by mistake. ## Change detection -When a PR is opened or code is pushed, the tool determines which Actors need to be built and tested based on the -changed files. - -Paths in `.actor/actor.json` resolve relative to its `.actor/` directory. When omitted, Dockerfile, README, -CHANGELOG, and INPUT_SCHEMA paths use the first existing default file in `.actor/`, then in the Actor's folder, -matching default filenames case insensitively. - -For each changed file, for each Actor: - -1. **Linked files** — the Actor's resolved `readme` and `changelog` files are cosmetic (only trigger a release - build). `actor.json` and linked schema files are checked for cosmetic JSON changes; other changes trigger builds - and tests. This covers `input`/`inputSchema`, `output`/`outputSchema`, `webServerSchema`, `storages.dataset`, - every `storages.datasets.`, and `storages.keyValueStore`. Inline schemas are checked as part of - `actor.json`. Cosmetic changes include formatting, key ordering, and edits to `title`, `description`, `example`, - `enumTitles`, `sectionCaption`, and `sectionDescription`. The resolved `dockerfile` is functional (triggers - builds and tests). These dependencies count even outside the Actor's context, inside a sibling Actor's folder, - or when ignore rules exclude them. A shared file affects every Actor that links it. -2. **Sibling exclusion** — other files inside another Actor's `folder` are excluded. This prevents an Actor with - broad context from being triggered by changes that belong to a sibling Actor. -3. **Context matching** — other files must fall within one of the Actor's context paths (`dockerContextDir` from - `actor.json` by default, or `overrideActorContext` from config if set). Files outside every context path are - skipped. An `overrideActorContext` entry can also be a single file, e.g. a root `package-lock.json`. -4. **Hardcoded ignore list, context-aware** — the file path is first "hoisted" relative to the context path it - matched (e.g. a standalone Actor's own `.eslintrc` is checked as just `.eslintrc`, not the full - repo-root-relative path), then checked against repo-level dev file patterns (`.vscode/`, `.gitignore`, `.husky/`, - `.eslintrc`, `eslint.config.mjs`, `.prettierrc`, `.editorconfig`). Directories like `code/` or `shared/` - get no special treatment: to treat them as top-level, list them in `overrideActorContext`. -5. **`.dockerignore` filtering** — if a `.dockerignore` exists at the root of the Actor's `dockerContextDir`, - matching files are ignored. Patterns are resolved relative to `dockerContextDir`, matching Docker's own behavior. - Platform test files are the exception, see the next step. - **Platform test files** — a file that matches `platformTestsGlob` from the config file (a glob from the repo root, - default `test/platform/**`, helpers included) is a `test` change, also when `.dockerignore` lists it. This is - checked before the `.dockerignore` filtering. A test change puts the Actor in `testChangedActors`, so its tests - run, but it is neither functional nor cosmetic, so a release doesn't build it. Context matching still applies, so - tests outside an Actor's `dockerContextDir` (e.g. a root `test/` with standalone Actors) need to be listed in its - `overrideActorContext`; `get-affected-actors` logs a warning for changed test files outside every Actor's context. -6. **Functional** — everything else triggers both build and tests. +`get-affected-actors` decides which Actors to build and test from the changed files. + +Paths in `.actor/actor.json` resolve relative to its `.actor/` directory. When `dockerfile`, `readme`, `changelog`, or +the input schema is omitted, the first existing default file is used: in `.actor/` first, then in the Actor's folder, +with file names matched case-insensitively. + +Each changed file is checked against each Actor, in this order: + +1. **Linked files.** The Actor's resolved `dockerfile` is functional. Its resolved `readme` and `changelog` are + cosmetic: they only need a release build. `actor.json` and the schema files it links are compared as JSON: + formatting, key order, and edits to `title`, `description`, `example`, `enumTitles`, `sectionCaption`, and + `sectionDescription` are cosmetic, anything else is functional. The linked schemas are `input`/`inputSchema`, + `output`/`outputSchema`, `webServerSchema`, `storages.dataset`, every `storages.datasets.`, and + `storages.keyValueStore`; inline schemas are compared as part of `actor.json`. Linked files count even outside the + Actor's context, inside a sibling Actor's folder, or when ignore rules exclude them. A shared file affects every + Actor that links it. +2. **Sibling exclusion.** Other files inside another Actor's `folder` don't count, so an Actor with a broad context + isn't triggered by a sibling's changes. +3. **Context matching.** Other files must be within one of the Actor's context paths: `overrideActorContext` from the + config if set, otherwise `dockerContextDir` from `actor.json`. The Actor's own folder is always part of its + context. An `overrideActorContext` entry can also be a single file, such as a root `package-lock.json`. Files + outside every context path don't count. +4. **Ignored dev files.** The path is taken relative to the context path it matched, so a standalone Actor's own + `.eslintrc` is checked as `.eslintrc`. Paths starting with `.vscode/`, `.gitignore`, `.husky/`, `.eslintrc`, + `eslint.config.mjs`, `.prettierrc`, or `.editorconfig` don't count. Folders like `code/` or `shared/` get no special + treatment: to treat them as top-level, list them in `overrideActorContext`. +5. **Platform tests.** A file matching `platformTestsGlob` from the config (a glob from the repo root, default + `test/platform/**`, helpers included) is a test change, even when `.dockerignore` lists it. A test change puts the + Actor in `testChangedActors`, so its tests run, but it is neither functional nor cosmetic, so a release doesn't + build it. Step 3 still applies: tests outside an Actor's `dockerContextDir` (for example, a root `test/` with + standalone Actors) must be listed in its `overrideActorContext`. `get-affected-actors` warns about changed test + files outside every Actor's context. +6. **`.dockerignore`.** Files matched by the `.dockerignore` at the root of the Actor's `dockerContextDir` don't + count. Patterns are relative to `dockerContextDir`, as in Docker. Files in the Actor's own `.actor/` directory are + never ignored this way. +7. **Functional.** Everything else is functional: it needs a build and tests. ## Finding affected Actors (`get-affected-actors`) `get-affected-actors` lists the Actors whose context changed in a commit range, using the rules in -[Change detection](#change-detection). It only reads git and the config file, so it needs no tokens. The range always +[Change detection](#change-detection). It reads only git and the config file, so it needs no tokens. The range always ends at the checked-out `HEAD`, so check out the branch you want to inspect first. ```bash @@ -105,36 +106,35 @@ npx apify-test-tools get-affected-actors --base origin/master --since npx apify-test-tools get-affected-actors --since ``` -| Flag | Default | Meaning | -| ----------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- | -| `--base` | | Only what `HEAD` changes compared to this branch counts, like `git diff ...HEAD` | -| `--since` | | Only changes after this commit count (see below) | -| `--stored-builds` | | JSON file with the builds earlier runs of the PR made, as `build` prints them. A missing or invalid file has none, see below | -| `--actors` | all | Only report these Actors | -| `--ignore` | none | Never report these Actors | +| Flag | Default | Meaning | +| ----------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `--base` | | Only what `HEAD` changes compared to this branch counts, like `git diff ...HEAD` | +| `--since` | | Only changes after this commit count (see below). An empty value counts as not passed | +| `--stored-builds` | | JSON file with the builds earlier runs of the PR made, as `build` prints them. A missing file has none, an invalid one none with a warning | +| `--actors` | all | Only report these Actors | +| `--ignore` | none | Never report these Actors | Pass `--base`, `--since`, or both: -- **`--base` only** inspects what the branch changes, the same files GitHub's "Files changed" tab shows: the diff - from where the branch forked from `--base`, or the last commit of `--base` it merged in. What it merged in from +- **`--base` only** inspects what the branch changes, the same files as GitHub's "Files changed" tab: the diff from + where the branch forked from `--base`, or from the last commit of `--base` it merged in. What it merged in from `--base` is already validated there, so it doesn't count. -- **`--base` and `--since`** also inspects what changed after the branch's last validated commit, and reports only - the Actors that changed in both. An Actor in only one of them is already validated, by this branch or on `--base`. - When both changed an Actor, the changes can interact, so it is reported, but as functional only when both changes - are functional. A validated functional change followed by README edits is cosmetic, and so is a functional - change merged in from `--base` that meets only cosmetic changes of the branch. `--since` doesn't have to be on - the branch, so a rebase only re-checks the Actors that `--base` changed too. If `--since` is not in the local - history (a force-push), or it is `HEAD` (a rerun), it is ignored and the whole branch is checked. -- **`--since` only** inspects everything after it up to `HEAD`. It must be an ancestor of `HEAD` and fails - otherwise, see [Releasing Actors](#releasing-actors). If `HEAD` is `--since`, nothing is reported. - -`commits`, `changedFiles` and `changelog` describe the whole range, `--base...HEAD` or `--since..HEAD`: `--since` +- **`--base` and `--since`** also inspects what changed after the branch's last validated commit, and reports only the + Actors that changed in both. An Actor in only one of them is already validated, by this branch or on `--base`. An + Actor changed in both is reported, since the changes can interact, but as functional only when both changes are + functional. So a validated functional change followed by README edits is cosmetic, and so is a functional change + merged in from `--base` that meets only cosmetic changes of the branch. `--since` doesn't have to be on the branch, + so after a rebase only the Actors that `--base` also changed are checked again. If `--since` isn't in the local + history (a force-push) or is `HEAD` (a rerun), it is ignored and the whole branch is checked. +- **`--since` only** inspects everything after it up to `HEAD`. It must be an ancestor of `HEAD`, see + [Releasing Actors](#releasing-actors). If `HEAD` is `--since`, nothing is reported. + +`commits`, `changedFiles`, and `changelog` describe the whole range (`--base...HEAD` or `--since..HEAD`). `--since` together with `--base` only narrows the Actor lists. -`changelog` combines added lines from the selected Actors' resolved changelog files across that range, counting -each shared path once. `--actors` and `--ignore` select which Actors' changelogs are considered. It is `null` when -none of those files changed, and an empty string when they changed without adding lines. Files named -`CHANGELOG.md` are included only when an Actor resolves its changelog to that path. +`changelog` holds the lines added to the selected Actors' resolved changelog files in that range, each shared file +counted once. It is `null` when none of those files changed, and an empty string when they changed without added lines. +A `CHANGELOG.md` counts only when an Actor resolves its changelog to it. The output is a JSON document: @@ -158,49 +158,49 @@ The output is a JSON document: } ``` -`functionallyChangedActors` have at least one functional change, so they need a new build and tests. -`cosmeticallyChangedActors` have cosmetic changes and no functional one (see [Change detection](#change-detection)), so -they need a new build only when released. An Actor is in at most one of these two lists. `testChangedActors` have a -changed platform test (`platformTestsGlob` in the config) in their context and no functional change, so their tests -need to run. A test change alone needs no release. An Actor can be in `cosmeticallyChangedActors` and -`testChangedActors`, but never in `functionallyChangedActors` and `testChangedActors`: a functional change needs a new -build and all the tests anyway. The PR workflow passes `functionallyChangedActors` and `testChangedActors` to -[`build`](#building-actors-build). The release workflow builds `functionallyChangedActors` and -`cosmeticallyChangedActors`. +- `functionallyChangedActors` have at least one functional change, so they need a new build and tests. +- `cosmeticallyChangedActors` have cosmetic changes and no functional one, so they need a new build only when + released. +- `testChangedActors` have a changed platform test in their context and no functional change, so their tests need to + run. A test change alone needs no release. + +An Actor is in at most one of the first two lists. It can be in `cosmeticallyChangedActors` and `testChangedActors`, +but never in `functionallyChangedActors` and `testChangedActors`, since a functional change needs a new build and all +the tests anyway. With `--base` and `--since`, an Actor is in `testChangedActors` when its tests changed on the branch +and again since `--since`, the same rule as for functional changes. -With `--base` and `--since`, an Actor is in `testChangedActors` when its tests changed on the branch and again since -`--since`, the same rule as for functional changes. +The PR workflow passes `functionallyChangedActors` and `testChangedActors` to [`build`](#building-actors-build). The +release workflow builds `functionallyChangedActors` and `cosmeticallyChangedActors`. -An Actor in `testChangedActors` gets the existing `build` that can run its tests, so `build` doesn't build it again: +An Actor in `testChangedActors` comes with the existing `build` that can run its tests, so `build` doesn't build it +again: - `"default"`: the branch didn't change the Actor's code compared to `--base` (whatever `--since` is), so its default build has the same code. -- A stored build from `--stored-builds`: the branch changed the code, and an earlier run of the PR built it. That build - has the current code, because a functional change after it would have built the Actor again. - The file has the entries `build` printed in earlier runs. Entries without a `buildId`, the default builds `build` - passes through, are skipped. +- A stored build from `--stored-builds`: the branch changed the code, and an earlier run of the PR built it. That + build has the current code, because a later functional change would have built the Actor again. Entries without a + `buildId` (the default builds `build` passes through) are skipped. - No `build`: the branch changed the code and no build of it is stored, so `build` builds the Actor. ## Building Actors (`build`) -`build` builds exactly the Actors it is given on stdin, from the checked-out branch as it is on the remote, and -prints the builds as the same JSON array `build-from-local` prints. An Actor listed twice is built once, so the lists -of `get-affected-actors` can be joined without removing duplicates first. A detached HEAD is an error, since there is -no branch to build from. It doesn't look at git history: which Actors to build is up to you, usually picked from the -output of [`get-affected-actors`](#finding-affected-actors-get-affected-actors). +`build` builds exactly the Actors given on stdin, from the checked-out branch as it is on the remote, and prints the +builds. It doesn't look at git history: you pick the Actors, usually from the output of +[`get-affected-actors`](#finding-affected-actors-get-affected-actors). An Actor listed twice is built once, so the +lists of `get-affected-actors` can be joined without removing duplicates. A detached `HEAD` is an error, since there is +no branch to build from. -An Actor listed with a `build`, as `testChangedActors` of -[`get-affected-actors`](#finding-affected-actors-get-affected-actors) gives it, is not built: +An Actor listed with a `build`, as `testChangedActors` gives it, is not built: - `"build": "default"` passes through as `{ "actorFullName": … }`, which [`test`](#running-tests-test) runs on the default build. -- A build object passes through while the build still exists, succeeded and belongs to the Actor. Otherwise the - Actor is built as usual, and the log says why. `delete-old-builds` deletes builds after 30 days, so an old stored - build is replaced this way. Which build to pass is up to the caller. -- An Actor listed several times with different builds, e.g. once without one, is built from scratch. Entries that - name the same build count as one. +- A build object passes through while the build still exists, succeeded, and belongs to the Actor. Otherwise the Actor + is built, and the log says why. `delete-old-builds` deletes builds after 30 days, so an old stored build gets + replaced this way. +- An Actor listed several times with different builds (for example, once without one) is built from scratch. Entries + that name the same build count as one. -The output then lists every build to test, new and reused, so it goes straight to `test`. +The output lists every build to test, new and reused, so it goes straight to `test`. ```bash # A PR: the Actors whose code or platform tests the branch changed, built into the test version, or reused @@ -217,21 +217,20 @@ npx apify-test-tools get-affected-actors --since \ echo '{ "actors": [{ "actorFullName": "john.doe/my-actor" }] }' | npx apify-test-tools build --version-number 0.99 ``` -The input is `{ "actors": [{ "actorFullName": "" }] }`, each Actor with an optional `build` (see above); -other fields are ignored. An empty `actors` list -builds nothing and prints `[]`. Empty or invalid input is an error, so a failed command earlier in the pipe can't turn +The input is `{ "actors": [{ "actorFullName": "" }] }`, each Actor with an optional `build` (see above). +Other fields are ignored, and every Actor must be in the config. An empty `actors` list builds nothing and prints `[]` +(or an empty plan in a dry run). Empty or invalid input is an error, so a failed command earlier in the pipe can't turn into a successful run that built nothing. In GitHub Actions, give such a step `shell: bash` so the pipe also fails on its own (the default shell has no `pipefail`). -| Flag | Default | Meaning | -| ---------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------- | -| `--version-number` | required | Version to build, like `0.99`, or `default` for each Actor's default version (the one its default build tag points to) | -| `--repo-url` | the `origin` remote | Repository to build from, see [Repository check](#repository-check) | -| `--require-env-vars-in-sync` | `false` | Fail unless the built version's env var names match the default version's, see [Env var check](#env-var-check) | -| `--dry-run` | `false` | See [Dry runs](#dry-runs---dry-run) | +| Flag | Default | Meaning | +| ---------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | +| `--version-number` | required | Version to build, as `.` like `0.99`, or `default` for each Actor's default version (the one its default build tag points to) | +| `--repo-url` | the `origin` remote | Repository to build from, see [Repository check](#repository-check) | +| `--require-env-vars-in-sync` | `false` | Fail unless the built version's env var names match the default version's, see [Env var check](#env-var-check) | +| `--dry-run` | `false` | See [Dry runs](#dry-runs---dry-run) | -The output is the build array the vitest library reads from `ACTOR_BUILDS`. A reused default build is the Actor's -name alone: +The output is the build array the library reads from `ACTOR_BUILDS`. A reused default build is the Actor's name alone: ```json [ @@ -240,38 +239,43 @@ name alone: ] ``` -`build` never sets or changes build tags. A build gets the tag its version is configured with on the platform, so -building the default version moves its tag (usually `latest`) to the new build, and building a version without a -tag leaves every tag where it is. Builds always use the Docker cache. +`build` never sets or changes build tags. A build gets the tag its version has on the platform, so building the default +version moves its tag (usually `latest`) to the new build, and building a version without a tag leaves every tag where +it is. When the default version doesn't have the default build tag, `build --version-number default` warns that users +keep running the previous build. Builds always use the Docker cache. + +Every Actor needs a build under its default build tag, built from a Git repository version that points to this +repository. Build it once manually on the platform before the first run. ### Repository check -`build` points each Actor's version at the `origin` remote. Because a build overwrites the version's Git URL, -building from a fork or a mirror would repoint the Actor. So, before building, the remote is compared with the Git -URL of the Actor's default version (the one its default build tag points to), and the command fails if they differ -or if the default version isn't built from a Git repository. The URL form doesn't matter -(`https://github.com/org/repo` equals `git@github.com:org/repo.git`). +A build overwrites the version's Git URL with the `origin` remote, so building from a fork or a mirror would repoint +the Actor. Before building, `build` compares the remote with the Git URL of the Actor's default version (the one its +default build tag points to). It fails if they differ or if the default version isn't built from a Git repository. The +URL form doesn't matter: `https://github.com/org/repo` equals `git@github.com:org/repo.git`. -To build from a different repository on purpose, e.g. when moving an Actor, pass `--repo-url`. That skips the check. +To build from a different repository on purpose, for example when moving an Actor, pass `--repo-url`. That skips the +check. ### Env var check -Tests should run the Actor with the same env vars users run it with. Pass `--require-env-vars-in-sync` to `build` or -`build-from-local` to compare the env vars of the version they build (e.g. `0.99`, or `0.98` for `build-from-local`) -with those of the default version, and fail if a name is missing or extra. Only names are compared, since the API -doesn't return secret values. A version that doesn't exist yet counts as having no env vars, so if the default -version has any, create the test version on the platform with the same env vars first. A dry run checks the env vars -too. +Tests should run the Actor with the same env vars users run it with. With `--require-env-vars-in-sync`, `build` and +`build-from-local` compare the env vars of the version they build (for example, `0.99`, or `0.98` for +`build-from-local`) with those of the default version, and fail if a name is missing or extra. Only names are +compared, since the API doesn't return secret values. A version that doesn't exist yet has no env vars, so if the +default version has some, first create the test version on the platform with the same env vars. -The CLI leaves it off by default, so a one-off build, e.g. of a debug branch, isn't held up by it. +The CLI leaves the check off by default, so a one-off build (for example, of a debug branch) isn't held up by it. [`public_pr-build-test.yaml`](workflows.md#public_pr-build-testyaml) turns it on by default; set its `require-env-vars-in-sync` input to `false` to turn it off. ## Build from local source (`build-from-local`) -Builds Actors directly from your local files, with no push needed: the sources are zipped into the Actor's -`actor--source` key-value store and built as `TARBALL`, like `apify push`. It prints the same build array as -`build`. +Builds Actors from your local files, with no push needed, into version `0.98`. Like `apify push`, it zips the sources +into the Actor's `actor--source` key-value store and builds them as `TARBALL`, without the Docker cache. The zip +holds the files git doesn't ignore, minus those the `.dockerignore` excludes. The Actor's `.actor/` folder is always +included, and secret files (`.env*`, `*.pem`, `*.key`, `*.pfx`, and `*.p12`) never are. It prints the same build array +as `build`. ```bash APIFY_TOKEN_JOHN_DOE= npx apify-test-tools build-from-local --actors john.doe/my-actor @@ -279,15 +283,15 @@ APIFY_TOKEN_JOHN_DOE= npx apify-test-tools build-from-local --actors john | Flag | Default | Meaning | | ---------------------------- | ------- | -------------------------------------------------------------------------------------------------------- | -| `--actors` | all | Only build these Actors. Point vitest at their tests only, for quicker feedback | +| `--actors` | all | Only build these Actors | | `--ignore` | none | Never build these Actors | | `--require-env-vars-in-sync` | `false` | Fail unless the env var names of `0.98` match the default version's, see [Env var check](#env-var-check) | -| `--dry-run` | `false` | Check the token, the Actor and the zipped sources without uploading or building | +| `--dry-run` | `false` | Check the token, the Actor, and the zipped sources without uploading or building | ## Releasing Actors -A release is three commands: find what changed since the last released commit, build those Actors into their -default version (the one users run), and announce it. +A release is three commands: find what changed since the last released commit, build those Actors into their default +version (the one users run), and announce it. ```bash npx apify-test-tools get-affected-actors --since > affected.json @@ -298,15 +302,15 @@ jq '{ actors: (.functionallyChangedActors + .cosmeticallyChangedActors) }' affec npx apify-test-tools notify --slack-channel "#notif-my-repo" --dry-run < affected.json ``` -[`notify`](#notifying-notify) says what it posts for a release. +[`notify`](#notifying-notify) describes what it posts for a release. ### The last released commit (`--since`) -The last commit that is **already released**. Everything after it, up to `HEAD`, is released. Git alone can't tell -which commits a push brought, and guessing wrong silently leaves Actors on old code, so it has to be passed. +`--since` is the last commit that is **already released**. Everything after it, up to `HEAD`, is released. Git alone +can't tell which commits a push brought, and a wrong guess silently leaves Actors on old code, so you have to pass it. -The changed files come from diffing `--since` and `HEAD` directly, so this works for every merge strategy as long as -`--since` is the branch tip from **before** the push: +The changed files come from diffing `--since` and `HEAD` directly, so every merge strategy works as long as `--since` +is the branch tip from **before** the push: | Merge strategy | What lands on the branch | What to pass | | ------------------------------ | --------------------------------- | ---------------------------------------------------------------------- | @@ -314,29 +318,29 @@ The changed files come from diffing `--since` and `HEAD` directly, so this works | Merge commit | the PR's commits + 1 merge commit | the push's "before" commit (`HEAD^1`, the first parent, also works) | | Rebase and merge / direct push | N new commits | the push's "before" commit (`HEAD~1` would miss the first N-1 commits) | -On GitHub, the push's "before" commit is `${{ github.event.before }}`, which the reusable workflow passes for you. -On other CIs use the equivalent, e.g. `$CI_COMMIT_BEFORE_SHA` on GitLab. The checkout needs the full history +On GitHub, the push's "before" commit is `${{ github.event.before }}`, which the reusable workflow passes for you. On +other CIs, use the equivalent, such as `$CI_COMMIT_BEFORE_SHA` on GitLab. The checkout needs the full history (`fetch-depth: 0` in `actions/checkout`) so the commit is available locally. `get-affected-actors --since` without `--base` fails instead of guessing when: - the commit is all zeros (GitHub sends this for a push that created the branch) -- the commit isn't in the local history (shallow checkout) or isn't an ancestor of `HEAD` (the branch was - force-pushed) +- the commit isn't in the local history (a shallow checkout or an invalid commit) +- the commit isn't an ancestor of `HEAD` (the branch was force-pushed) -In those cases, rerun it with a `--since` you pick yourself: an ancestor of `HEAD` from before the changes you want -to release (for a shallow checkout, fetch the full history instead). `--actors` only narrows which of the changed -Actors are reported; it never forces a build, so on its own it doesn't get past these errors. If `HEAD` is -`--since`, nothing is reported, so nothing is built or announced. +Then rerun it with a `--since` you pick yourself: an ancestor of `HEAD` from before the changes you want to release. +For a shallow checkout, fetch the full history instead. `--actors` only narrows which changed Actors are reported. It +never forces a build, so it doesn't get past these errors. If `HEAD` is `--since`, nothing is reported, built, or +announced. -A failed release isn't retried by the next push: that push's base commit is the failed one's head, so its changes -are skipped. Re-run the failed workflow run, or release the Actors manually. +The next push doesn't retry a failed release: its "before" commit is the failed push's head, so the failed changes are +skipped. Re-run the failed workflow run, or release the Actors manually. ## Running tests (`test`) -`test` runs the repository's own vitest (the version in its `node_modules`, so the tests keep the lib version -the repository locked) on the Actors it is given on stdin, and prints a report of the run for -[`notify`](#notifying-notify). Only the tests of those Actors run. +`test` runs the repository's own Vitest (the one in its `node_modules`, so the tests keep the versions the repository +locked) on the Actors given on stdin. Only the tests of those Actors run. It prints a report of the run for +[`notify`](#notifying-notify). ```bash # A PR: test what was just built @@ -350,49 +354,50 @@ npx apify-test-tools get-actor-configs \ npx apify-test-tools get-actor-configs --actors john.doe/my-actor | npx apify-test-tools test > test-report.json ``` -The input is a JSON array of Actors, each given by its full name: `[{ "actorFullName": "" }]`, the ID the -tests name their Actor by. An Actor's tests run against the build given with it (`buildId` and `buildNumber`, as -`build` and `build-from-local` print them), or against its default build without one. Other fields are ignored, so the -output of [`get-actor-configs`](#listing-actors-get-actor-configs) works as it is. - -Each Actor's tests run with its test token: the environment variable its `testTokenEnvVar` in the config names. `test` -reads the config for it, so the Actors must be listed there. An Actor that isn't in the config or whose token isn't set -gets a warning, and only its own tests fail. A dry-run plan, empty or invalid input is an error, as with `build`, and so -is a missing config. - -`test` passes the Actors to vitest as `ACTOR_BUILDS`, each with its `testTokenEnvVar`, in place of any `ACTOR_BUILDS` -in its own environment. It needs apify-test-tools 1.0.0 or newer in the repository, and fails on an older one, which -could skip every test. It also excludes `**/dist/**`, which vitest doesn't exclude by default, so a compiled copy of the -tests doesn't run next to them. The repository's own `exclude` still applies. - -When `test` is given Actors but no test runs, the report fails with an error, since a run that tested nothing must -not pass. For any set of given Actors, at least 1 test must be performed, not 1 for each Actor. When none runs, the -tests usually name the Actors differently, or `--test-files-glob` selects none of their tests. A given Actor none of -whose tests ran only gets a warning, since an Actor may have no tests in the selected files. - -It runs vitest with `--maxConcurrency=20 --fileParallelism --maxWorkers=100`, since platform tests mostly wait on -Actor runs rather than the CPU, and with the default reporter plus the JSON one the report is read from. These -replace any `reporters` in the repository's vitest config; add more with `--reporter`, e.g. `github-actions` to -annotate the failing tests in a GitHub Actions run. It takes no other vitest options; for those, e.g. `-t` to run one -test by name, run vitest directly with the builds in `ACTOR_BUILDS` (see -[Running tests locally](lib.md#running-tests-locally)). - -| Flag | Default | Meaning | -| ---------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------- | -| `--test-files-glob` | `test/platform/**` | Glob from the repo root of the test files to run, see below | -| `--vitest-output-file` | | Also keep vitest's own JSON report there, e.g. to upload it | -| `--reporter` | | [Vitest reporter](https://vitest.dev/guide/reporters) to add to `default` and `json`, e.g. `github-actions`. Repeat it for more | - -`test` takes no test paths as arguments, only `--test-files-glob`. The glob is read the same way as -`platformTestsGlob` in the config file. Vitest filters are parts of a file path, not globs, so `test` finds the files -the glob matches and passes vitest as few paths as it can: each folder whose files all match, with a trailing `/`, and -the other matched files one by one. `test/platform/{daily,hourly}/**` becomes two folders however many tests they -hold, so the command line stays short. Vitest still applies its own `include` and `exclude`, so helper files in the -glob run nothing. A glob that matches no file is an error, because vitest without filters would run every test of the -repo. Quote the glob, so the shell doesn't expand it. - -Vitest's own output goes to stderr, followed by a summary that lists every test with the link to its run. Stdout -gets only the report: +The input is a JSON array of Actors, each named by its full name: `[{ "actorFullName": "" }]`, the name the +tests use for it. An Actor's tests run on the build given with it (`buildId` and `buildNumber`, as `build` and +`build-from-local` print them), or on its default build without one. Other fields are ignored, so the output of +[`get-actor-configs`](#listing-actors-get-actor-configs) works as it is. A dry-run plan, empty input, or invalid input +is an error, as with `build`. + +Each Actor's tests run with its test token, the environment variable named by its `testTokenEnvVar`. `test` reads the +config for it, so the config file must exist. An Actor that isn't in the config, or whose token isn't set, gets a +warning, and only its own tests fail. + +`test` passes the Actors to Vitest as `ACTOR_BUILDS`, each with its `testTokenEnvVar`, replacing any `ACTOR_BUILDS` in +its own environment. It needs `vitest` installed in the repository, and fails if the repository has apify-test-tools +older than 1.0.0, which could otherwise skip every test. It also excludes `**/dist/**`, which Vitest doesn't +exclude by default, so a compiled copy of the tests doesn't run next to them. The repository's own `exclude` still +applies. + +If `test` is given Actors but no test runs, the report fails, since a run that tested nothing must not pass. At least 1 +test must run for the whole set of given Actors, not 1 for each Actor. When none runs, the tests usually name the +Actors differently, or `--test-files-glob` selects none of their tests. A given Actor none of whose tests ran only gets +a warning, since an Actor may have no tests in the selected files. + +`test` runs Vitest with `--maxConcurrency=20 --fileParallelism --maxWorkers=100`, since platform tests mostly wait on +Actor runs rather than the CPU. It uses the `default` reporter plus the `json` one the report is read from. These +replace any `reporters` in the repository's Vitest config; add more with `--reporter`, such as `github-actions` to +annotate failing tests in a GitHub Actions run. It takes no other Vitest options. For those (for example, `-t` to run +one test by name), run Vitest directly with the builds in `ACTOR_BUILDS`, see +[Running tests locally](lib.md#running-tests-locally). + +| Flag | Default | Meaning | +| ---------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | +| `--test-files-glob` | `test/platform/**` | Glob from the repo root of the test files to run, see below | +| `--vitest-output-file` | | Also keep Vitest's own JSON report there, for example to upload it | +| `--reporter` | | [Vitest reporter](https://vitest.dev/guide/reporters) to add to `default` and `json`, such as `github-actions`. Repeat it for more | + +`test` takes no test paths as arguments, only `--test-files-glob`, which is read the same way as `platformTestsGlob` in +the config file. Vitest filters are parts of a file path, not globs, so `test` finds the files the glob matches and +passes Vitest as few paths as it can: each folder whose files all match, with a trailing `/`, and the other matched +files one by one. For example, `test/platform/{daily,hourly}/**` becomes two folders however many tests they hold. +Vitest still applies its own `include` and `exclude`, so helper files in the glob run nothing. A glob that matches no +file is an error, because Vitest without filters would run every test in the repository. Quote the glob, so the shell +doesn't expand it. + +Vitest's own output goes to stderr, followed by a summary that lists the passed and failed tests with links to their +runs. Stdout gets only the report: ```json { @@ -418,21 +423,21 @@ gets only the report: } ``` -`failureMessages` keeps the first line of each failure; diffs and stack traces are in the vitest output. `run` is -`null` for a test that started no run. `errors` lists what failed outside of any test: a test file that failed to -load, or vitest exiting without a report. `test` exits with 1 whenever `success` is false, and prints the report -anyway, so `notify` still hears about the failure. +`failureMessages` keeps the first line of each failure; diffs and stack traces are in the Vitest output. `run` is +`null` for a test that started no run. `errors` lists failures outside any test, such as a test file that failed to +load, or Vitest exiting without a report. `test` exits with 1 whenever `success` is false, and prints the report anyway, +so `notify` still hears about the failure. ## Notifying (`notify`) -`notify` tells one target about what it reads on stdin: a test run, as [`test`](#running-tests-test) reports it, -or a release, as [`get-affected-actors`](#finding-affected-actors-get-affected-actors) reports it. It tells the two -apart by the report's `kind` and the release's `commits`, so either can be piped in as it is. Slack is the only target for now. To post to more -places, call it once for each. +`notify` reads a test run (the output of [`test`](#running-tests-test)) or a release (the output of +[`get-affected-actors`](#finding-affected-actors-get-affected-actors)) on stdin and posts about it. It tells the two +apart by the report's `kind` and the release's `commits`, so either can be piped in as it is. Slack is the only target +for now, and each call posts to one channel; to post to more channels, call it once for each. ```bash -# A test run: posts only when the tests failed, the failure counts and the first failure, linked to its run, -# with the other failures in the message's thread +# A test run: posts only when the tests failed. The message has the failure counts and the first failure, linked to +# its run, with the other failures in the message's thread npx apify-test-tools notify --slack-channel '#notif-my-repo' < test-report.json npx apify-test-tools notify --slack-channel '#my-team' < test-report.json @@ -445,24 +450,26 @@ npx apify-test-tools get-affected-actors --since | npx apify-test-tools no | Flag | Input | Default | Meaning | | ----------------- | ------- | ------------------- | ----------------------------------------------------------------- | -| `--slack-channel` | both | | Slack channel to post to | +| `--slack-channel` | both | | Slack channel to post to (one per call) | | `--on` | tests | `failure` | `failure` posts only when the tests failed, `always` on every run | -| `--title` | tests | `-` | What the message calls the run, e.g. the CI workflow name | +| `--title` | tests | `-` | What the message calls the run, such as the CI workflow name | | `--job-url` | tests | | Link to the CI job, included in the message | | `--repo-url` | release | the `origin` remote | The repository the release is named after and its commits link to | +| `--dry-run` | both | `false` | See [Dry runs](#dry-runs---dry-run) | -A flag the input has no use for, e.g. `--repo-url` with a test report, is an error rather than ignored. Both kinds -of notification post with `SLACK_BOT_TOKEN`. +A flag the input has no use for (for example, `--repo-url` with a test report) is an error. Both kinds of notification +post with the Slack token in `SLACK_BOT_TOKEN`. -Without a target, `notify` posts nothing and needs no token. With one, it checks the token on every run, also when -there is nothing to post, so a broken token shows up on a green run rather than on the day tests fail. A release -with no new commits is the exception: there is nothing to announce, so it needs no token either. +Without `--slack-channel`, `notify` posts nothing and needs no token. With it, the token must be set on every run, even +when there is nothing to post, so a missing token shows up on a green run rather than on the day tests fail. A dry run +also verifies the token with Slack. A release with no new commits is the exception: there is nothing to announce, so it +needs no token. -For a release, `notify` posts the changelog additions, then the commits, oldest first. Each commit is its title (cut -at 200 characters) linked to its page on GitHub, and its author. A merge commit or a squash merge is one commit; a -rebase merge lists every commit it brought. A repository hosted elsewhere gets the titles without links. The release -is named after the `origin` remote (or `--repo-url`) and the author of the newest commit. Nothing is posted when there -are no new commits: +For a release, `notify` posts the changelog additions, then the commits, oldest first. Each commit is its title (cut at +200 characters) linked to its page on GitHub, followed by its author. A merge commit or a squash merge is one commit; a +rebase merge lists every commit it brought. A repository hosted elsewhere gets the titles without links. The release is +named after the `origin` remote (or `--repo-url`) and the author of the newest commit. Without a changelog addition, +`notify` logs a warning and posts the commits only. ```text *my-repo* – New release (by Jane Doe): @@ -475,8 +482,8 @@ are no new commits: ## Deleting old builds (`delete-old-builds`) -Deletes builds older than 30 days of every selected Actor. It never deletes the default build, or a build tagged -`latest`, `version…`, `v-…` or `v0`–`v9…`. +Deletes every build older than 30 days of each selected Actor, except the default build and builds whose tag starts +with `latest`, `version`, `v-`, or `v0`–`v9`. It needs each Actor's build token. | Flag | Default | Meaning | | ----------- | ------- | ----------------------------------------------------------- | @@ -487,14 +494,13 @@ Deletes builds older than 30 days of every selected Actor. It never deletes the ## Listing Actors (`get-actor-configs`) Prints the [config](../README.md#config-file) as the tool resolves it: one entry per Actor, with the group's values -applied and `actor.json` read. Takes `--actors` and `--ignore`. -Useful to check a config change. +applied and `actor.json` read. It takes `--actors` and `--ignore`. Use it to check a config change, or to pipe every +Actor into [`test`](#running-tests-test). ## Running locally -Running the tests locally is useful when you only want to update the testing code in `test/`, because you can -iterate on it without pushing new code to the remote. If you only change tests, skip the builds entirely and run -them against the default builds, see [Running tests locally](lib.md#running-tests-locally). +To update only the tests in `test/`, you don't need new builds: run the tests against the default builds, see +[Running tests locally](lib.md#running-tests-locally). To test changed Actor source, you need builds of it. The quickest way is [`build-from-local`](#build-from-local-source-build-from-local), which needs no push: @@ -506,11 +512,11 @@ APIFY_TOKEN_JOHN_DOE=apify_api_xxx \ To build from git, like CI does: -1. Switch to a dummy branch that you will push and can later delete -2. `npm i apify-test-tools@latest -D` -3. Push your code (changes you want to test) -4. Build the Actors on Apify (with your new code) -5. Run tests against those builds. You can change tests and run on the same builds. +1. Switch to a dummy branch that you will push and can delete later. +2. Run `npm i apify-test-tools@latest -D`. +3. Push the code you want to test. +4. Build the Actors on Apify. +5. Run the tests against those builds. You can change the tests and rerun them on the same builds. ```bash npx apify-test-tools get-affected-actors --base origin/master \ @@ -518,16 +524,15 @@ npx apify-test-tools get-affected-actors --base origin/master \ | APIFY_TOKEN_JOHN_DOE=apify_api_xxx npx apify-test-tools build --version-number 0.99 > builds.json ``` -Run it with your dummy branch checked out: it builds the Actors that branch changed functionally, from the branch as -it is on the remote, into the test version `0.99`. Add `--dry-run` to `build` to print the plan (the version and Git -URL each Actor would be built from) first, and update `--base` to the branch you compare against. Tests only run for -Actors in `ACTOR_BUILDS`, so the `jq` filter also passes the Actors whose platform tests changed. Those whose code the -branch didn't change run on their default build, the others are built. +Run it with your dummy branch checked out, and set `--base` to the branch you compare against. It builds the Actors the +branch changed functionally into the test version `0.99`, from the branch as it is on the remote. Add `--dry-run` to +`build` to print the plan (the version and Git URL of each build) first. Tests only run for the Actors in +`ACTOR_BUILDS`, so the `jq` filter also passes the Actors whose platform tests changed: those whose code the branch +didn't change run on their default build, the others are built. -If you want to test against existing builds instead, skip the build and write the build array by hand, only for the -Actors you need to test. +To test existing builds instead, skip the build and write the build array by hand, only for the Actors you need. -Then run the tests against the builds with [`test`](#running-tests-test), as often as you like: +Then run the tests on the builds with [`test`](#running-tests-test), as often as you like: ```bash APIFY_TOKEN_JOHN_DOE=apify_api_xxx npx apify-test-tools test < builds.json diff --git a/docs/lib.md b/docs/lib.md index 094f086..e477019 100644 --- a/docs/lib.md +++ b/docs/lib.md @@ -8,14 +8,9 @@ Requires `vitest` 5 or later as a peer dependency. ## Environment variables -The library reads these when the test file is loaded: - -| Variable | Description | -| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `ACTOR_BUILDS` | JSON array of Actors to test, e.g. the builds the CLI's [`build`](cli.md#building-actors-build) and [`build-from-local`](cli.md#build-from-local-source-build-from-local) print. Only tests of Actors listed here run, against the listed build, or the default build for an Actor listed without one. Each entry names the env var holding the token its tests run with, see below. Without any Actors, every `describe` block is skipped, so a plain `npm test` stays unaffected. | - -`ACTOR_BUILDS` entries look like this, and are matched to tests by `actorFullName`. Without `buildNumber`, the Actor's -tests run on its default build: +The library reads `ACTOR_BUILDS` when a test file loads: a JSON array of the Actors to test. A test runs only when its +Actor is listed there. [`test`](cli.md#running-tests-test) sets it from its input. Without any Actors, every +`describe` block is skipped, so a plain `npm test` is unaffected. A value that isn't a JSON array fails the test file. ```json [ @@ -28,41 +23,49 @@ tests run on its default build: ] ``` -The tests of an Actor start runs and read their data with the token in the environment variable `testTokenEnvVar` -names. [`test`](cli.md#running-tests-test) fills it in from the Actor's `testTokenEnvVar` in -`apify-test-tools.config.json`. An Actor listed without one, or whose variable isn't set, fails its own tests, and the -other Actors' tests still run. +| Field | Description | +| ----------------- | ------------------------------------------------------------------------------------------------- | +| `actorFullName` | The Actor's full name, `owner/name`. Tests are matched to entries by it | +| `buildNumber` | The build to test. Without it, the Actor's tests run on its default build | +| `buildId` | The build whose input schema [`prefilledInput`](#runoptions) reads. Without it, the default build | +| `testTokenEnvVar` | Name of the environment variable holding the token the Actor's tests run with | + +`test` fills in `testTokenEnvVar` from the Actor's `testTokenEnvVar` in `apify-test-tools.config.json`. If an entry has +no `testTokenEnvVar`, or the variable isn't set, that Actor's tests fail. The other Actors' tests still run. ## `describe(name, fn, options?)` -Same as vitest's `describe`, but skipped unless `ACTOR_BUILDS` lists any Actors. Its tests -run concurrently by default. Use it instead of vitest's `describe` for platform tests. +Vitest's `describe`, skipped unless `ACTOR_BUILDS` lists at least one Actor. Its tests run concurrently by default. Use +it instead of Vitest's `describe` for platform tests. ## `testActor(actorFullName, testName, fn, options?)` -Registers a test for an Actor. `actorFullName` is the Actor's full name, `owner/name`. Anything else, like a raw -Actor ID, throws, so the test file fails to load instead of the test being skipped. The test only runs when the Actor -is in `ACTOR_BUILDS`. Its name is `: `. +Registers a test named `: `. It runs only when `ACTOR_BUILDS` lists the Actor. +`actorFullName` must be the Actor's full name, `owner/name`. Anything else, such as an Actor ID, throws, so the test +file fails to load instead of the test being skipped without a word. -`fn` gets the vitest test context, with `expect` extended by the [custom matchers](#custom-matchers), a `run` -function, and `apifyClient`: an `ApifyClient` with the token the Actor's tests run with, e.g. to read storages the run -left elsewhere. Use it rather than a client of your own, whose token may not see the runs. +`fn` gets the Vitest test context with: -`expect` is soft: a failed assertion marks the test as failed but the test keeps going, so one run reports every -failed check at once. Use `expect.hard(...)` for an assertion that must stop the test, e.g. before indexing into a -list that may be empty. +- `expect`, extended with the [custom matchers](#custom-matchers). +- `run`, which runs the Actor, see [`run(options)`](#runoptions). +- `apifyClient`, an `ApifyClient` with the Actor's test token, e.g. to read storages the run left elsewhere. Use it + rather than a client of your own, whose token may not see the runs. + +`expect` is soft: a failed assertion marks the test as failed, but the test continues, so one run reports every failed +check. Use `expect.hard(...)` for an assertion that must stop the test, e.g. before indexing into a list that may be +empty. ```ts import { describe, testActor } from 'apify-test-tools'; -describe('test', () => { - testActor('john.doe/my-actor', 'actor test 1', async ({ expect, run }) => { +describe('my-actor', () => { + testActor('john.doe/my-actor', 'first test', async ({ expect, run }) => { const runResult = await run({ input }); // your checks }); - testActor('john.doe/my-actor', 'actor test 2', async ({ expect, run }) => { + testActor('john.doe/my-actor', 'second test', async ({ expect, run }) => { const runResult = await run({ input }); // your checks @@ -72,7 +75,7 @@ describe('test', () => { ### Test options -The fourth argument takes vitest's test options: +The fourth argument takes Vitest's test options. These defaults differ from Vitest's: | Option | Default | | ------------ | ------- | @@ -83,7 +86,7 @@ The fourth argument takes vitest's test options: ```ts testActor( 'john.doe/my-actor', - 'slow actor test', + 'slow test', async ({ expect, run }) => { const runResult = await run({ input }); await expect(runResult).toFinishWith({ datasetItemCount: 100 }); @@ -97,17 +100,17 @@ testActor( ### `run(options)` -Starts the Actor, waits for the run to finish, and returns a [`RunTestResult`](#runtestresult). It runs the build -from `ACTOR_BUILDS`, or the Actor's default build when it isn't listed there. Before returning, it waits 20 seconds -for the run's dataset and statistics to sync, since the platform is only eventually consistent. The run's Console -link is added to the test as a vitest annotation. +Starts the Actor, waits for the run to finish, and returns a [`RunTestResult`](#runtestresult). It runs the +`buildNumber` that `ACTOR_BUILDS` lists for the Actor, or its default build without one. It then waits 20 seconds for +the run's dataset and statistics to sync, since the platform is eventually consistent. The run's Console link is added +to the test as a Vitest annotation. -| Option | Description | -| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `input` | Actor input | -| `prefilledInput` | When `true`, `input` is merged on top of the Actor's prefilled input | -| `options` | [Actor call options](https://docs.apify.com/api/client/js/reference/interface/ActorCallOptions) like `memory`. `timeout` is in seconds and defaults to the Actor's default run timeout, at most 59 minutes, so the run finishes before the test times out | -| `runId` | Don't start a run; return this existing run instead. Every other option is ignored | +| Option | Description | +| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `input` | Actor input | +| `prefilledInput` | When `true`, `input` is merged on top of the prefilled values from the input schema of the build under test | +| `options` | [Actor call options](https://docs.apify.com/api/client/js/reference/interface/ActorCallOptions), such as `memory`. `timeout` is in seconds and defaults to the Actor's default run timeout, capped at 59 minutes, so the run finishes before the test times out | +| `runId` | Don't start a run. Return this existing run instead, without the 20-second wait. Every other option is ignored | #### Using prefilled input @@ -123,7 +126,7 @@ testActor('john.doe/my-actor', 'with prefilled input', async ({ expect, run }) = #### Testing an existing run -Useful for iterating on the checks of a test without waiting for a new run: +Useful for iterating on a test's checks without waiting for a new run: ```ts testActor('john.doe/my-actor', 'validate existing run', async ({ expect, run }) => { @@ -134,22 +137,28 @@ testActor('john.doe/my-actor', 'validate existing run', async ({ expect, run }) ## `testServerInterfaceActor(actorFullName, testName, fn, options?)` -Same as `testActor`, for an Actor's server interface (formerly standby mode). Instead of `run`, `fn` gets -`fetchServer(path, init?)`: [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch) for the Actor's -server interface. `path` is resolved against the server interface's URL, with any query string, e.g. -`/search?q=shoes`, and `init` takes what `fetch` takes: `method`, `headers`, `body`, `signal` and the rest. It returns -the `Response` as `fetch` does, and doesn't throw on an error status. `fn` gets `apifyClient` too. +Like `testActor`, for an Actor's server interface (formerly standby mode). Instead of `run`, `fn` gets +`fetchServer(path, init?)`. It gets `expect` and `apifyClient` as in `testActor`. The test fails if the Actor has no +server interface. + +`fetchServer` is [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch) for the Actor's server +interface: + +- `path` is appended to the server interface's URL and can include a query string, e.g. `/search?q=shoes`. It defaults + to `/`. +- `init` takes the same options as `fetch`: `method`, `headers`, `body`, `signal`, and the rest. +- It returns the `Response`, and doesn't throw on an error status. -`fetchServer` adds two headers, unless `init` sets them itself: +It adds two headers, unless `init` sets them: - `Authorization` with the Actor's test token. -- `X-Actor-Build` with the build `ACTOR_BUILDS` lists for the Actor, as on a PR. Without one, as in the scheduled - platform tests, it sends none and the platform serves the Actor's configured server interface build. A test that - sets its own `X-Actor-Build` runs against that build instead of the one under test. +- `X-Actor-Build` with the `buildNumber` that `ACTOR_BUILDS` lists for the Actor, e.g. the build of a PR. Without one, + as in scheduled tests on the default build, it sends no `X-Actor-Build`, and the platform serves the Actor's + configured server interface build. A test that sets its own `X-Actor-Build` runs against that build instead. **Server interface tests need a full-permission test token.** Only the Actor's owner, or an account with write access -to it, can select a build with `X-Actor-Build`, and a scoped token can't get write access to an Actor on its own. So -point the Actor's `testTokenEnvVar` at a full-permission token of such an account, e.g. the same token as its +to it, can select a build with `X-Actor-Build`, and a scoped token can't get write access to an Actor on its own. Point +the Actor's `testTokenEnvVar` at a full-permission token of such an account, e.g. the same token as its `buildTokenEnvVar`, or its tests fail on a PR. See [Token permissions](../README.md#token-permissions). ```ts @@ -163,7 +172,7 @@ describe('server interface tests', () => { body: JSON.stringify({ query: 'test' }), }); - // The response text as the message shows what came back when the status is wrong + // With the response text as the message, a wrong status shows what came back expect(response.status, await response.clone().text()).toBe(200); const data = await response.json(); expect(data.results).toBeNonEmptyArray(); @@ -176,23 +185,21 @@ describe('server interface tests', () => { }); ``` -It fails if the Actor doesn't have a server interface. - ## `RunTestResult` -What `run` returns. Every getter fetches its data on the first call and returns the same result afterwards, so you -can call them freely. +What `run` returns. Each method fetches its data on the first call and reuses it afterwards, so you can call them +freely. -| Member | Returns | -| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `id` | The run ID | -| `status` | The run status when it finished | -| `getDataset()` | `{ items: T[] }`, every item of the default dataset | -| `getLog()` | The run log as a string | -| `getStatistics(keys?)` | The crawler statistics, summed over every crawler's record as `toFinishWith` reads them, or `undefined` without any. `keys` reads only those records, see [Crawler statistics](#crawler-statistics) | -| `getInput()` | The `INPUT` record of the default key-value store | -| `getKeyValueStoreClient()` | An `apify-client` client for the default key-value store | -| `getRunInfo()` | The run object, fetched again so it reflects changes after the run finished | +| Member | Returns | +| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| `id` | The run ID | +| `status` | The run status when it finished | +| `getDataset()` | `{ items: T[] }`, every item of the default dataset | +| `getLog()` | The run log as a string | +| `getStatistics(keys?)` | The crawler statistics, summed over every crawler, or `undefined` without any. See [Crawler statistics](#crawler-statistics) | +| `getInput()` | The `INPUT` record of the default key-value store | +| `getKeyValueStoreClient()` | An `apify-client` client for the default key-value store | +| `getRunInfo()` | The run object, fetched again, so it reflects changes made after the run finished | ```ts testActor('john.doe/my-actor', 'check dataset items', async ({ expect, run }) => { @@ -216,39 +223,45 @@ testActor('john.doe/my-actor', 'check dataset items', async ({ expect, run }) => ## `toFinishWith(options)` -Validates the common run properties in a single call and reports every failed check at once. Only -`datasetItemCount` is required. Numeric checks take an exact number or a range: `{ min }`, `{ max }` or -`{ min, max }`. Set a check with a default to `null` to skip it. - -| Option | Default | Checks | -| -------------------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `datasetItemCount` | required | Number of items in the default dataset | -| `status` | `'SUCCEEDED'` | Run status | -| `failedRequests` | `0` | Failed requests in the crawler statistics. **Set it to `null` for an Actor without crawler statistics**, or the check fails | -| `forbiddenLogs` | `[/\bReferenceError: /, /\bTypeError: /]` | Strings that no log line may contain, or regular expressions that no log line may match. A failure quotes the offending lines | -| `duration` | not checked | Run duration in milliseconds | -| `requestsRetries` | not checked | Request retries in the crawler statistics, over all requests | -| `maxRetriesPerRequest` | not checked | The most retries any single request needed | -| `chargedEventCounts` | not checked | Pay-per-event counts, per event name. Only the events listed are checked, and an event that was never charged counts as 0 | -| `strictChargedEventCounts` | `false` | Also fail on any charged event that `chargedEventCounts` doesn't list | -| `statisticsKeys` | every crawler's | The key-value store record, or records, with the crawler statistics. By default every record starting with `SDK_CRAWLER_STATISTICS_` or `CRAWLEE_CRAWLER_STATISTICS_` | - -The default `forbiddenLogs` match a `ReferenceError` or `TypeError` the way JavaScript prints one, `TypeError: `, -not the word in prose or in a longer name. Your own `forbiddenLogs` replace them. +Checks the common run properties in one call and reports every failed check at once. Only `datasetItemCount` is +required. `datasetItemCount`, `duration`, `failedRequests`, `requestsRetries`, and each `chargedEventCounts` value take +an exact number or a range: `{ min }`, `{ max }`, or `{ min, max }`. + +| Option | Default | Checks | +| -------------------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `datasetItemCount` | required | Number of items in the default dataset | +| `status` | `'SUCCEEDED'` | Run status | +| `failedRequests` | `0` | Failed requests in the crawler statistics. **Set it to `null` for an Actor without crawler statistics**, or the check fails | +| `forbiddenLogs` | `[/\bReferenceError: /, /\bTypeError: /]` | Strings no log line may contain, or regular expressions no log line may match. A failure quotes up to three offending lines. `[]` turns the check off | +| `duration` | not checked | Run duration in milliseconds | +| `requestsRetries` | not checked | Request retries over all requests, from the crawler statistics | +| `maxRetriesPerRequest` | not checked | A number: the most retries any single request may have needed, from the crawler statistics | +| `chargedEventCounts` | not checked | Pay-per-event counts by event name. Only the listed events are checked, and an event that was never charged counts as `0` | +| `strictChargedEventCounts` | `false` | With `chargedEventCounts`, also fail on any charged event it doesn't list | +| `statisticsKeys` | every crawler's | The key-value store record, or records, with the crawler statistics. By default, every record starting with `SDK_CRAWLER_STATISTICS_` or `CRAWLEE_CRAWLER_STATISTICS_` | + +`duration`, `failedRequests`, `requestsRetries`, and `maxRetriesPerRequest` take `null` to skip the check. + +The default `forbiddenLogs` match a `ReferenceError` or `TypeError` as JavaScript prints one (`TypeError: `), +not the word in prose or in a longer name. Your own `forbiddenLogs` replace the defaults. ### Crawler statistics -`failedRequests`, `requestsRetries` and `maxRetriesPerRequest` read the crawler statistics, which a Crawlee crawler -persists in the record `SDK_CRAWLER_STATISTICS_` or `CRAWLEE_CRAWLER_STATISTICS_`: `0` for the first crawler of -a run, or the id its statistics were given. By default the checks read every such record of the run and sum them, so a -run with several crawlers, e.g. an adaptive crawler, needs no setting. The records are found by listing the first 1,000 -keys under each prefix. Set `statisticsKeys` to read only some records, e.g. one crawler's out of several. A record it -names that doesn't exist fails those checks. `runResult.getStatistics(keys?)` reads them the same way, and returns the -counters that add up across crawlers: `requestsFinished`, `requestsFailed`, `requestsRetries`, `requestRetryHistogram`, -`maxRetriesPerRequest` and the total request durations. A record's other fields, like its timestamps, are in the -key-value store, see `getKeyValueStoreClient()`. - -**An Actor without crawler statistics, e.g. one that doesn't use a Crawlee crawler, must set `failedRequests: null`.** +`failedRequests`, `requestsRetries`, and `maxRetriesPerRequest` read the crawler statistics. A Crawlee crawler persists +them in the record `SDK_CRAWLER_STATISTICS_` or `CRAWLEE_CRAWLER_STATISTICS_`, where `` is `0` for a run's +first crawler, or the ID its statistics were given. By default, the checks sum every such record of the run, found by +listing the first 1,000 keys under each prefix. A run with several crawlers, e.g. an adaptive crawler, needs no +setting. Set `statisticsKeys` to read only some records, e.g. one crawler's out of several. If a record it names +doesn't exist, those checks fail. + +`runResult.getStatistics(keys?)` reads the same records: every crawler's by default, or only the `keys` given (a string +or an array). It returns the counters summed across them: `requestsFinished`, `requestsFailed`, `requestsRetries`, +`requestRetryHistogram`, `maxRetriesPerRequest`, `requestTotalFinishedDurationMillis`, and +`requestTotalFailedDurationMillis`, plus `keys`, the records it summed. It returns `undefined` when the run has no +statistics record, and throws a `MissingStatisticsError` when a key you gave doesn't exist. To read a record's other +fields, like its timestamps, use `getKeyValueStoreClient()`. + +**An Actor without crawler statistics, such as one without a Crawlee crawler, must set `failedRequests: null`.** `failedRequests` is checked by default, and a run without any statistics record fails it with `got no statistics record SDK_CRAWLER_STATISTICS_* or CRAWLEE_CRAWLER_STATISTICS_*`. With `null`, and no other check that needs them, the statistics aren't read at all: @@ -275,11 +288,11 @@ await expect(runResult).toFinishWith({ `expect` in `testActor` and `testServerInterfaceActor` is extended with: -- `toBeArray()` / `toBeEmptyArray()` / `toBeNonEmptyArray()` -- `toBeString()` / `toBeNonEmptyString()` / `toStartWith(prefix)` -- `toBeNumber()` / `toBeWholeNumber()` / `toBeWithinRange(min, max)` -- `toBeBoolean()` / `toBeTrue()` / `toBeFalse()` -- `toBeObject()` / `toBeNonEmptyObject()` +- `toBeArray()`, `toBeEmptyArray()`, `toBeNonEmptyArray()` +- `toBeString()`, `toBeNonEmptyString()`, `toStartWith(prefix)` +- `toBeNumber()`, `toBeWholeNumber()`, `toBeWithinRange(min, max)` (inclusive) +- `toBeBoolean()`, `toBeTrue()`, `toBeFalse()` +- `toBeObject()`, `toBeNonEmptyObject()` - [`toFinishWith(options)`](#tofinishwithoptions) Pass a message as the second argument of `expect` to say what failed: @@ -290,8 +303,8 @@ expect(place.title, `London Eye's title`).toEqual('lastminute.com London Eye'); ### Custom validation functions -Wrap shared checks in your own functions, e.g. in `test/platform/utils.ts`, and pass them `expect`. Use the -`ExpectStatic` type so the custom matchers type-check: +Put shared checks in your own functions, e.g. in `test/platform/utils.ts`, and pass them `expect`. Type it as +`ExpectStatic` so the custom matchers type-check: ```ts import { ExpectStatic } from 'apify-test-tools'; @@ -313,12 +326,13 @@ Run every command from the root of the Actor repository. npx apify-test-tools get-actor-configs --actors john.doe/my-actor | APIFY_TOKEN_JOHN_DOE= npx apify-test-tools test ``` -This also runs a test that reuses an existing run with [`runId`](#testing-an-existing-run), as long as its Actor is +This also runs tests that reuse an existing run with [`runId`](#testing-an-existing-run), as long as their Actor is listed. -**Against builds of your changes.** Build the Actors with the CLI, either from local files with -[`build-from-local`](cli.md#build-from-local-source-build-from-local) or from a pushed branch with -[`build`](cli.md#building-actors-build), and pass the output to [`test`](cli.md#running-tests-test): +**Against builds of your changes.** Build the Actors from local files with +[`build-from-local`](cli.md#build-from-local-source-build-from-local), or from a pushed branch with +[`build`](cli.md#building-actors-build), and pass the output to `test`. You can change the tests and re-run them +against the same builds. ```bash APIFY_TOKEN_JOHN_DOE= npx apify-test-tools build-from-local --actors john.doe/my-actor > builds.json @@ -326,11 +340,13 @@ APIFY_TOKEN_JOHN_DOE= npx apify-test-tools build-from-local --actors john APIFY_TOKEN_JOHN_DOE= npx apify-test-tools test < builds.json ``` -`test` passes the builds to vitest as `ACTOR_BUILDS`, with each Actor's `testTokenEnvVar`. To run plain vitest, add -`testTokenEnvVar` to each build yourself: -`ACTOR_BUILDS='[{"actorFullName":"john.doe/my-actor","testTokenEnvVar":"APIFY_TOKEN_JOHN_DOE"}]' APIFY_TOKEN_JOHN_DOE= npx vitest run test/platform`. +To run only some test files, pass `--test-files-glob` to `test`. `test` rejects any other flag, so to filter tests by +name with Vitest's `-t`, run Vitest directly. Set `ACTOR_BUILDS` yourself then, with each Actor's `testTokenEnvVar`, +which `test` would otherwise add: -You can change the tests and re-run them against the same builds. +```bash +ACTOR_BUILDS='[{"actorFullName":"john.doe/my-actor","testTokenEnvVar":"APIFY_TOKEN_JOHN_DOE"}]' \ + APIFY_TOKEN_JOHN_DOE= npx vitest run test/platform -t 'first test' +``` -To run only some tests, pass a specific file instead of `test/platform`, or filter by name with vitest's `-t ` -when running vitest directly. See [Running locally](cli.md#running-locally) for the full flow. +See [Running locally](cli.md#running-locally) for the full flow. diff --git a/docs/migrating-to-v1.md b/docs/migrating-to-v1.md index d8c5e8d..7fa88b4 100644 --- a/docs/migrating-to-v1.md +++ b/docs/migrating-to-v1.md @@ -1,18 +1,18 @@ # Migrating to v1 -Version 1 of the library and `@workflows-v1` of the workflows go together: the v1 workflows refuse a library older +Version 1.0 of the library and `@workflows-v1` of the workflows go together: the v1 workflows refuse a library older than 1.0.0, and the 1.0 library expects what the v1 workflows pass it. Migrate a repository in one PR: -1. [Update the packages](#update-the-packages): `apify-test-tools` 1.0, vitest 5 and Node.js -2. [Convert the config](#convert-the-config) to `"mode": "grouped"`, with `tokenEnvVar` renamed to `buildTokenEnvVar` - and a `testTokenEnvVar` on every group -3. [Choose the test token](#choose-the-test-token) of every group, `testTokenEnvVar`: the Actor's owner, or - `TESTER_APIFY_TOKEN` as before -4. [Switch the workflows](#switch-the-workflows) to `@workflows-v1`, with every Apify token in `CONFIG_SECRETS` -5. [Update the tests](#update-the-tests): Actors by full name, the imports, server interface tests and `toFinishWith` +1. [Update the packages](#update-the-packages): `apify-test-tools` 1.0, `vitest` 5, and Node.js. +2. [Convert the config](#convert-the-config): add `"mode": "grouped"`, rename `tokenEnvVar` to `buildTokenEnvVar`, and + add a `testTokenEnvVar` to every group. +3. [Choose the test token](#choose-the-test-token) of every group: the Actor owner's token, or `TESTER_APIFY_TOKEN` as + before. +4. [Switch the workflows](#switch-the-workflows) to `@workflows-v1` and pass every Apify token in `CONFIG_SECRETS`. +5. [Update the tests](#update-the-tests): full Actor names, imports, server interface tests, and `toFinishWith`. -`@workflows-v0` keeps working with the libraries before 1.0, so a repository can stay on it until its PR is merged. -The [Troubleshooting](#troubleshooting) section maps the errors you may hit to the step that fixes them. +`@workflows-v0` keeps working with libraries before 1.0, so a repository can stay on it until its PR is merged. +[Troubleshooting](#troubleshooting) maps each error you may hit to the step that fixes it. ## Update the packages @@ -20,26 +20,26 @@ The [Troubleshooting](#troubleshooting) section maps the errors you may hit to t npm install --save-dev apify-test-tools@^1.0.0 vitest@^5 ``` -- **vitest 5 or later** is a peer dependency. If your repository has its own vitest config or uses vitest APIs - directly, go through [vitest's migration guide](https://vitest.dev/guide/migration). -- **Node.js 22.12 or later, 24, or 26 and later**, the versions vitest 5 runs on. The workflows run Node.js 24. -- **vitest no longer excludes `dist` by default.** The workflows' test step excludes `**/dist/**` itself. If you - compile your tests and run `npx vitest` locally, add `dist/**` to `exclude` in your vitest config, or a compiled copy - of each test runs next to it. +- **Vitest 5 or later** is a peer dependency. If your repository has its own Vitest config or uses Vitest APIs + directly, follow [Vitest's migration guide](https://vitest.dev/guide/migration). +- **Node.js `^22.12.0`, `^24.0.0`, or `>=26.0.0`** is required, as for Vitest 5. The workflows use Node.js 24. +- **Vitest no longer excludes `dist` by default.** `apify-test-tools test` excludes `**/dist/**` itself, so the + workflows need nothing. If you compile your tests and run `npx vitest` locally, add `dist/**` to `exclude` in your + Vitest config, or a compiled copy of each test runs too. ## Convert the config -`apify-test-tools.config.json` needs `"mode": "grouped"`, and its Actors go into groups. A config with a top-level -`actors` array and no `mode` fails with `Invalid input: expected "grouped" → at mode`. +In `apify-test-tools.config.json`: -`tokenEnvVar` is renamed to `buildTokenEnvVar`, on the groups and on the Actors, so it reads apart from -`testTokenEnvVar`. A config that still has `tokenEnvVar` anywhere fails with -`tokenEnvVar is renamed to buildTokenEnvVar`. +1. **Add `"mode": "grouped"` and move the Actors into `groups`.** A config with a top-level `actors` array and no + `mode` fails with `Invalid input: expected "grouped" → at mode`. +2. **Rename `tokenEnvVar` to `buildTokenEnvVar`**, on groups and on Actors. A config that still has `tokenEnvVar` + anywhere fails with `tokenEnvVar is renamed to buildTokenEnvVar`. +3. **Add a `testTokenEnvVar` to every group**: the env var with the token the group's platform tests run with. It has + no default, so a group without one fails with `testTokenEnvVar is required`. -Every group also needs a `testTokenEnvVar`, the token its Actors' platform tests run with. It has no default, and a -group without one fails with `testTokenEnvVar is required`. The example below tests with the same token that builds; -[Choose the test token](#choose-the-test-token) covers the other choice. A config that is already grouped only needs -the rename and the test tokens. +A config that is already grouped only needs steps 2 and 3. The example below tests with the build token. +[Choose the test token](#choose-the-test-token) covers the alternative. Before: @@ -80,44 +80,39 @@ After: } ``` -Group the Actors by the token that builds them. The group key is only a label. An Actor can still set its own -`buildTokenEnvVar`, `testTokenEnvVar` or `overrideActorContext`, which replaces the group's. `platformTestsGlob` stays -at the top level. - -See [Config file](../README.md#config-file) for every field. +Group the Actors by the token that builds them. The group key is only a label. An Actor can set its own +`buildTokenEnvVar`, `testTokenEnvVar`, or `overrideActorContext` to replace the group's. `platformTestsGlob` stays at +the top level. See [Config file](../README.md#config-file) for every field. ## Choose the test token -Before v1, every platform test ran its Actor with `TESTER_APIFY_TOKEN`. In v1, the tests of each Actor run with the -`testTokenEnvVar` of its group, or its own. The test token decides: - -- which account the test runs start in, and whose usage they count against; -- whose runs they show up among; -- which token the Claude investigation workflow needs to read a failed run, see - [The Claude investigation workflow](#the-claude-investigation-workflow); -- whether server interface tests can run an Actor's PR build. +Before v1, every platform test ran its Actor with `TESTER_APIFY_TOKEN`. In v1, an Actor's tests run with its group's +`testTokenEnvVar`, or its own. The test token decides: -**Only the owner, or an account with write access to the Actor, can call an Actor's -[server interface](lib.md#testserverinterfaceactoractorfullname-testname-fn-options) on a build other than its default -one, which is what the tests do on a PR.** +- Which account the test runs start in, and whose usage they count against. +- Which token the Claude investigation workflow needs to read a failed run. See + [The Claude investigation workflow](#the-claude-investigation-workflow). +- Whether server interface tests can run an Actor's PR build. ### Token permissions -- **`buildTokenEnvVar`** needs a token with full permissions, for now. A token that needs less is planned. +- **`buildTokenEnvVar`** needs a full-permission token, for now. A token that needs less is planned. - **`testTokenEnvVar`** depends on the tests: - - **Server interface tests need a full-permission token**, of the Actor's owner or of an account with write access - to the Actor. A scoped token can't get write access to an Actor on its own, so a scoped token makes these tests - fail on a PR. - - **Other tests only need to run the repo's Actors**, so a scoped token with run access to them is enough. + - **Server interface tests need a full-permission token of the Actor's owner, or of an account with write access + to the Actor.** Only those can call an Actor's + [server interface](lib.md#testserverinterfaceactoractorfullname-testname-fn-options) on a build other than its + default one, which is what the tests do on a PR. A scoped token can't get write access to an Actor on its own, so + it makes these tests fail on a PR. + - **Other tests only need to run the repository's Actors**, so a scoped token with run access to them is enough. ### The owner's token or `TESTER_APIFY_TOKEN` -Testing with the owner's token, the same env var as `buildTokenEnvVar` as in [Convert the config](#convert-the-config), -works for every test, server interface tests included, and the runs start in the owner's account. +**The owner's token** works for every test, server interface tests included, and the runs start in the owner's +account. Use the same env var as `buildTokenEnvVar`, as in [Convert the config](#convert-the-config). -To keep the tests running with `TESTER_APIFY_TOKEN`, as before, set it as the `testTokenEnvVar` of every group. That -works for server interface tests only if it is a full-permission token of an account with write access to the Actor. -It can't be set for the whole config at once: +**`TESTER_APIFY_TOKEN`** keeps the tests running as before. Set it as the `testTokenEnvVar` of every group, since there +is no config-wide setting. Server interface tests then pass only if it's a full-permission token of an account with +write access to the Actor. ```json { @@ -140,27 +135,23 @@ It can't be set for the whole config at once: } ``` -An Actor can set its own `testTokenEnvVar` too, to run only its tests with another token, e.g. the owner's token for an -Actor with server interface tests in a group tested with `TESTER_APIFY_TOKEN`. Pass `TESTER_APIFY_TOKEN` inside -`CONFIG_SECRETS` then, see [Switch the workflows](#switch-the-workflows). - -## Switch the workflows +To test a single Actor with another token, set `testTokenEnvVar` on that Actor. For example, use the owner's token for +an Actor with server interface tests in a group tested with `TESTER_APIFY_TOKEN`. -In every workflow that calls this repository's workflows, change `@workflows-v0` to `@workflows-v1`. The workflow -inputs are unchanged. +Whichever tokens you choose, pass each of them in `CONFIG_SECRETS`, `TESTER_APIFY_TOKEN` included. See +[Switch the workflows](#switch-the-workflows). -The workflows read the Apify tokens only from the `CONFIG_SECRETS` secret, one JSON object with an entry per name the -config uses as a `buildTokenEnvVar` or `testTokenEnvVar`. Before v1, internal repositories could pass all their -secrets with `secrets: inherit` instead. In v1 that no longer passes the tokens, and GitHub doesn't let a job inherit -its secrets and list `CONFIG_SECRETS` too, so every job lists its secrets by name. - -The PR and scheduled test workflows no longer take `TESTER_APIFY_TOKEN`: the tests run each Actor with its own test -token, its `testTokenEnvVar`. +## Switch the workflows -Remove `TESTER_APIFY_TOKEN` from the `secrets:` you pass to `public_pr-build-test.yaml` and -`public_platform-tests.yaml`. A reusable workflow refuses a secret it doesn't declare, so leaving it in fails the -workflow. Pass the test tokens in `CONFIG_SECRETS`, like the build tokens. A job with `secrets: inherit` gets the same -`secrets:` block as the one after. +1. **Change `@workflows-v0` to `@workflows-v1`** in every workflow that calls this repository's workflows. The inputs + are unchanged. +2. **Remove `TESTER_APIFY_TOKEN` from the `secrets:`** you pass to `public_pr-build-test.yaml` and + `public_platform-tests.yaml`. They no longer declare it, and GitHub rejects a secret that a reusable workflow doesn't + declare. +3. **Pass every Apify token in `CONFIG_SECRETS`**: one JSON object with an entry for each name the config uses as a + `buildTokenEnvVar` or `testTokenEnvVar`. The workflows read Apify tokens only from there. +4. **Replace `secrets: inherit` with secrets listed by name.** It no longer passes the tokens, and GitHub doesn't let a + job inherit its secrets and list `CONFIG_SECRETS` too. Before: @@ -195,18 +186,18 @@ jobs: } ``` -`public_pr-build-test.yaml` already takes `CONFIG_SECRETS` for the builds. Drop `TESTER_APIFY_TOKEN` there, and make -sure `CONFIG_SECRETS` also holds any `testTokenEnvVar` that differs from the build tokens. If the tests keep running -with `TESTER_APIFY_TOKEN`, that means adding `"TESTER_APIFY_TOKEN": "${{ secrets.TESTER_APIFY_TOKEN }}"`. +`public_pr-build-test.yaml` already takes `CONFIG_SECRETS` for the builds. Add every `testTokenEnvVar` that isn't a +build token, for example `"TESTER_APIFY_TOKEN": "${{ secrets.TESTER_APIFY_TOKEN }}"` if the tests keep running with it. -A token the config names that `CONFIG_SECRETS` leaves out is a warning in the build or test step, and the tests of its -Actors fail with an error naming it. +A token the config names but `CONFIG_SECRETS` leaves out is a warning in the build or test step, and the tests of its +Actors fail with an error naming it. To pass all of the repository's secrets in `CONFIG_SECRETS` instead of listing +them, see [Secrets](workflows.md#secrets). ### The Claude investigation workflow -`public_platform-tests-claude-investigate-and-fix.yaml` still takes `TESTER_APIFY_TOKEN`: there it is the token Claude -reads and re-runs the failed run with. Runs are private to the account that started them, so pass it the token your -tests ran the Actors with, by name: +`public_platform-tests-claude-investigate-and-fix.yaml` still takes `TESTER_APIFY_TOKEN`: Claude reads and re-runs the +failed run with it. Runs are private to the account that started them, so pass the token your tests ran the Actors +with: ```yaml handle-failure: @@ -223,8 +214,8 @@ handle-failure: ### Name every Actor by its full name -`testActor` and `testServerInterfaceActor` take the Actor's full name, `owner/name`. A test that names its Actor by its raw ID -now fails its whole test file to load, instead of being skipped: +`testActor` and `testServerInterfaceActor` take the Actor's full name, `owner/name`. A test that names its Actor by +its raw ID now makes its whole test file fail to load, instead of being skipped: ```ts // Before @@ -236,20 +227,23 @@ testActor('myteam/web-scraper', 'scrapes the start URL', async ({ expect, run }) ### Import from the package root -The package exports only its root, `apify-test-tools`. Deep imports such as `apify-test-tools/dist/lib/lib.js` fail -with `ERR_PACKAGE_PATH_NOT_EXPORTED`. Import everything from the root: +The package exports only its root. Deep imports such as `apify-test-tools/dist/lib/lib.js` fail with +`ERR_PACKAGE_PATH_NOT_EXPORTED`. Import everything from `apify-test-tools`: ```ts import { describe, testActor, testServerInterfaceActor, RunTestResult } from 'apify-test-tools'; ``` -The `it` alias of `testActor` is gone: use `testActor`. +The `it` alias of `testActor` is gone. Use `testActor`. ### Server interface tests -The platform renamed standby mode to server interface, and so did the library. `callStandby` is now `fetchServer`, a -`fetch` for the Actor's server interface: it takes a path and `fetch`'s own options, and returns the `Response`. It -no longer turns an `input` into the JSON body of a `POST`, so send the body, method and content type yourself: +The platform renamed standby mode to server interface, and so did the library: `testStandbyActor` is now +`testServerInterfaceActor`, and `callStandby` is now `fetchServer`. + +`fetchServer(path, init?)` is `fetch` for the Actor's server interface: it resolves `path` against the server interface +URL, takes `fetch`'s own options as `init`, and returns the `Response`. It no longer turns an `input` into the JSON body +of a `POST`, so set the method, body, and content type yourself: ```ts // Before @@ -271,72 +265,75 @@ testServerInterfaceActor('myteam/search', 'answers a query', async ({ expect, fe }); ``` -`fetchServer` returns the `Response` itself: read it with `response.json()` or `response.text()`, as with `fetch`. -Pass the text as the message of the status assertion to see what came back when it fails. +Read the response with `response.json()` or `response.text()`, as with `fetch`. Passing its text as the message of the +status assertion shows what came back when the assertion fails. -`testServerInterfaceActor` sends its requests straight to the Actor's server interface URL and selects the PR build -with the `X-Actor-Build` header, instead of creating a temporary task on that build. So the report and the test -annotations no longer link the server interface runs. +`fetchServer` sends requests straight to the Actor's server interface URL, authenticated with the Actor's test token. +It selects the build under test, such as the PR build, with the `X-Actor-Build` header, instead of creating a temporary +task on that build. `init` can set either header itself. The test doesn't start a run, so the report and the test +annotations no longer link server interface runs. ### `toFinishWith` -| Option | Before | Now | -| -------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -| `duration` | `{ min: 600, max: 600_000 }` by default | not checked unless set | -| `requestsRetries` | `{ max: 3 }` by default | not checked unless set | -| `forbiddenLogs` | the strings `ReferenceError`, `TypeError` anywhere in the log | strings or regular expressions, per log line. The defaults match a printed error, `TypeError: ` | -| `chargedEventCounts` | an event you don't list must be 0 | only the events you list are checked | -| `strictChargedEventCounts` | – | `true` brings back: an event you don't list must be 0 | -| `statisticsKeys` | always `SDK_CRAWLER_STATISTICS_0` | every `SDK_CRAWLER_STATISTICS_*` and `CRAWLEE_CRAWLER_STATISTICS_*` record, summed, or the keys you list | +| Option | Before | Now | +| -------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `duration` | `{ min: 600, max: 600_000 }` by default | not checked unless set | +| `requestsRetries` | `{ max: 3 }` by default | not checked unless set | +| `forbiddenLogs` | the strings `ReferenceError` and `TypeError` anywhere in the log | strings or regular expressions, matched per log line. The defaults match a printed error, `TypeError: ` | +| `chargedEventCounts` | an event you don't list must be 0 | only the events you list are checked | +| `strictChargedEventCounts` | didn't exist | `true` restores the old check: an event you don't list must be 0 | +| `statisticsKeys` | always `SDK_CRAWLER_STATISTICS_0` | every `SDK_CRAWLER_STATISTICS_*` and `CRAWLEE_CRAWLER_STATISTICS_*` record, summed, or the keys you list | What to change: -- **A test that relied on a duration or retries limit** sets it itself, e.g. `duration: { max: 10 * 60 * 1000 }`. +- **A test that relied on the duration or retries limit** sets it itself, for example + `duration: { max: 10 * 60 * 1000 }`. - **A test that relied on every unlisted event being 0** adds `strictChargedEventCounts: true`. -- **An event listed as never charged** passes now: `'premium': 0` asserts it wasn't charged. Before, an event listed - but never charged failed. -- **An Actor without crawler statistics, e.g. without a Crawlee crawler, must set `failedRequests: null`**, as before: - `failedRequests` is checked by default and fails without statistics. It can drop `requestsRetries: null` and - `duration: null`. -- **An adaptive crawler, a crawler with its own statistics id, or a run with several crawlers** needs no setting: - the checks read every statistics record of the run and sum them. To read only some, set `statisticsKeys`, e.g. +- **An event listed but never charged** now counts as 0, so `'premium': 0` asserts it wasn't charged. Before, it failed. +- **An Actor without crawler statistics**, for example one without a Crawlee crawler, still sets + `failedRequests: null`. `failedRequests` is checked by default and fails without statistics. The Actor can drop + `requestsRetries: null` and `duration: null`. +- **An adaptive crawler, a crawler with its own statistics ID, or a run with several crawlers** needs no setting: the + checks sum every statistics record of the run. To read only some, set `statisticsKeys`, for example `'SDK_CRAWLER_STATISTICS_0'`. -- **Your own `forbiddenLogs`** replace the defaults, as before. A string still matches anywhere in a line, but no - longer across lines. +- **Your own `forbiddenLogs`** replace the defaults, as before. A string still matches anywhere in a line, but no longer + across lines. -`runResult.getStatistics()` reads the statistics the way `toFinishWith` does: summed over every crawler's record, or -only the records you pass, e.g. `getStatistics('SDK_CRAWLER_STATISTICS_1')`. It returns the counters that add up, -`requestsFinished`, `requestsFailed`, `requestsRetries`, `requestRetryHistogram`, `maxRetriesPerRequest` and the total -durations, not the whole record. Read a record's other fields, like its timestamps, from the key-value store with -`runResult.getKeyValueStoreClient()`. +`runResult.getStatistics(keys?)` reads the statistics the way `toFinishWith` does: summed over every crawler's record, +or only the records you pass, for example `getStatistics('SDK_CRAWLER_STATISTICS_1')`. It returns the summed counters +(`requestsFinished`, `requestsFailed`, `requestsRetries`, `requestRetryHistogram`, `maxRetriesPerRequest`, and the +total durations) and the `keys` it read, not the whole record. Without any record, it returns `undefined`. Read a +record's other fields, like its timestamps, from the key-value store with `runResult.getKeyValueStoreClient()`. ## Running the CLI yourself Skip this if you only use the workflows. -- `test` needs `apify-test-tools` 1.0.0 or newer installed in the repository, and fails on an older one. -- `test` takes its Actors by full name: each entry on stdin needs `actorFullName`. An entry with only `actorRawId` - is rejected. -- `test` reads the config for each Actor's test token, so it needs `apify-test-tools.config.json`, and it doesn't use - `TESTER_APIFY_TOKEN`. Set each Actor's test token env var instead. +- `test` needs `apify-test-tools` 1.0.0 or later installed in the repository, and fails with an older one. +- `test` takes Actors by full name: each entry on stdin needs `actorFullName`. An entry with only `actorRawId` is + rejected. +- `test` reads each Actor's test token env var from `apify-test-tools.config.json`, so it needs the config. It doesn't + use `TESTER_APIFY_TOKEN`, so set each test token env var instead. +- The report `test` prints is `"version": 2`, and each test's `run` names its Actor by `actorFullName`. +- The CLI rejects unknown flags instead of ignoring them. - The CLI's help calls it `apify-test-tools`. ## Troubleshooting -| Error or warning | Fix | -| ------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | -| `The repository uses apify-test-tools 0.x, older than 1.0.0, the oldest version this CLI supports` | [Update the packages](#update-the-packages) | -| `Invalid input: expected "grouped" → at mode` | [Convert the config](#convert-the-config) | -| `tokenEnvVar is renamed to buildTokenEnvVar` | [Convert the config](#convert-the-config) | -| `testTokenEnvVar is required` | [Choose the test token](#choose-the-test-token) and add it to every group | -| `Test "…" names its Actor "…", which is not a full name` | [Name every Actor by its full name](#name-every-actor-by-its-full-name) | -| `APIFY_TOKEN_… is not set, so the tests of … will fail.` and `APIFY_TOKEN_… is not set. The tests of Actor "…" need it.` | Pass it in `CONFIG_SECRETS`, see [Switch the workflows](#switch-the-workflows) | -| `Actor … is not in apify-test-tools.config.json, so its tests will fail.` | Add the Actor to the config | -| `Failed failedRequests check, expected 0, got no statistics record SDK_CRAWLER_STATISTICS_* or CRAWLEE_CRAWLER_STATISTICS_*.` | `failedRequests: null` for an Actor without a Crawlee crawler | -| A `chargedEventCounts` check that passes although an unlisted event was charged | Add `strictChargedEventCounts: true` | -| The workflow fails to start over `TESTER_APIFY_TOKEN` | Remove it from the `secrets:` of the PR and scheduled test workflows | -| ``Warning: … declares … as `buildTokenEnvVar`, but the CONFIG_SECRETS secret has no such entry``, e.g. with `secrets: inherit` | List the secrets by name, with every Apify token in `CONFIG_SECRETS`, see [Switch the workflows](#switch-the-workflows) | -| Claude's investigation can't find the failed run | Pass it the token the tests ran with, see [The Claude investigation workflow](#the-claude-investigation-workflow) | -| `ERR_PACKAGE_PATH_NOT_EXPORTED` | [Import from the package root](#import-from-the-package-root) | -| `Module '"apify-test-tools"' has no exported member 'testStandbyActor'` or `testStandbyActor is not a function` | [Rename it to `testServerInterfaceActor`](#server-interface-tests) | -| `Property 'callStandby' does not exist`, or `callStandby is not a function` | [Use `fetchServer`](#server-interface-tests) | +| Error or warning | Fix | +| ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| `The repository uses apify-test-tools …, older than 1.0.0, the oldest version this CLI supports` | [Update the packages](#update-the-packages) | +| `Invalid input: expected "grouped" → at mode` | [Convert the config](#convert-the-config) | +| `tokenEnvVar is renamed to buildTokenEnvVar` | [Convert the config](#convert-the-config) | +| `testTokenEnvVar is required` | [Choose the test token](#choose-the-test-token) and add it to every group | +| `Test "…" names its Actor "…", which is not a full name` | [Name every Actor by its full name](#name-every-actor-by-its-full-name) | +| `… is not set, so the tests of … will fail.` or `… is not set. The tests of Actor "…" need it.` | Pass the token in `CONFIG_SECRETS`. See [Switch the workflows](#switch-the-workflows) | +| `Actor … is not in apify-test-tools.config.json, so its tests will fail.` | Add the Actor to the config | +| `Failed failedRequests check, expected 0, got no statistics record SDK_CRAWLER_STATISTICS_* or CRAWLEE_CRAWLER_STATISTICS_*.` | Set `failedRequests: null` for an Actor without a Crawlee crawler | +| A `chargedEventCounts` check passes although an unlisted event was charged | Add `strictChargedEventCounts: true` | +| `Invalid secret, TESTER_APIFY_TOKEN is not defined in the referenced workflow` | Remove it from the `secrets:` of the PR and scheduled test workflows | +| ``Warning: … declares … as `…`, but the CONFIG_SECRETS secret has no such entry``, for example with `secrets: inherit` | List the secrets by name, with every Apify token in `CONFIG_SECRETS`. See [Switch the workflows](#switch-the-workflows) | +| Claude's investigation can't find the failed run | Pass it the token the tests ran with. See [The Claude investigation workflow](#the-claude-investigation-workflow) | +| `ERR_PACKAGE_PATH_NOT_EXPORTED` | [Import from the package root](#import-from-the-package-root) | +| `Module '"apify-test-tools"' has no exported member 'testStandbyActor'` or `testStandbyActor is not a function` | [Rename it to `testServerInterfaceActor`](#server-interface-tests) | +| `Property 'callStandby' does not exist` or `callStandby is not a function` | [Use `fetchServer`](#server-interface-tests) | diff --git a/docs/workflows.md b/docs/workflows.md index f012449..d421a85 100644 --- a/docs/workflows.md +++ b/docs/workflows.md @@ -1,8 +1,8 @@ # Workflow API -Ready-made GitHub Actions workflows built on the [CLI](cli.md) and the [vitest library](lib.md). They are the -`public_`-prefixed files in this repo's `.github/workflows`. Call them from a job with `uses:` and pass the secrets -the workflow lists, see [Secrets](#secrets): +Ready-made GitHub Actions workflows built on the [CLI](cli.md) and the [Vitest library](lib.md). They are the +`public_`-prefixed files in this repo's `.github/workflows`. Call them from a job with `uses:` and pass the secrets the +workflow lists (see [Secrets](#secrets)): ```yaml jobs: @@ -14,67 +14,65 @@ jobs: # the secrets the workflow lists ``` -Always reference them at the `@workflows-v1` major tag, never at `@master` — see [Versioning](#versioning). +Always reference them at the `@workflows-v1` major tag, never at `@master`. See [Versioning](#versioning). -They only run on GitHub Actions. On another CI platform, build the same steps with the [CLI](cli.md); each workflow -The build, release and test workflows below list the CLI commands they run. +They only run on GitHub Actions. On another CI platform, build the same steps with the [CLI](cli.md): the build, +release, and test workflows below list the CLI commands they run. -| Workflow | Typical trigger | What it does | -| ---------------------------------------------------------------------------------------------------------------- | ----------------------------------- | -------------------------------------------------------------------------------- | -| [`public_pr-build-test.yaml`](#public_pr-build-testyaml) | `pull_request` | Builds the Actors a PR changes into `0.99` and tests them, plus static checks | -| [`public_push-build-latest.yaml`](#public_push-build-latestyaml) | `push` to `master` | Builds the changed Actors into their default version and announces the release | -| [`public_platform-tests.yaml`](#public_platform-testsyaml) | `schedule` | Runs platform tests against the released builds and reports results to Slack | -| [`public_review.yaml`](#public_reviewyaml) | `pull_request` (labeled) | Claude reviews the PR against the shared guidelines | -| [`public_claude.yaml`](#public_claudeyaml) | issue and PR comments, issue labels | Claude acts on `@claude` mentions | -| [`public_stale-issues.yaml`](#public_stale-issuesyaml) | `schedule` | Warns owners of inactive issues, then closes them a month later | -| [`public_platform-tests-claude-investigate-and-fix.yaml`](#public_platform-tests-claude-investigate-and-fixyaml) | after a failed platform test job | Claude investigates a failing platform test, opens an issue, and tries to fix it | +| Workflow | Typical trigger | What it does | +| ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -------------------------------------------------------------------------------- | +| [`public_pr-build-test.yaml`](#public_pr-build-testyaml) | `pull_request` | Builds the Actors a PR changes into `0.99` and tests them, plus static checks | +| [`public_push-build-latest.yaml`](#public_push-build-latestyaml) | `push` to `master` | Builds the changed Actors into their default version and announces the release | +| [`public_platform-tests.yaml`](#public_platform-testsyaml) | `schedule` | Runs platform tests against the released builds and reports failures to Slack | +| [`public_review.yaml`](#public_reviewyaml) | `pull_request` (`labeled`, `synchronize`) | Claude reviews the PR against the shared guidelines | +| [`public_claude.yaml`](#public_claudeyaml) | issue and PR comments, issue labels | Claude acts on `@claude` mentions | +| [`public_stale-issues.yaml`](#public_stale-issuesyaml) | `schedule` | Warns owners of inactive issues, then closes them a month later | +| [`public_platform-tests-claude-investigate-and-fix.yaml`](#public_platform-tests-claude-investigate-and-fixyaml) | after a failed platform test job | Claude investigates a failing platform test, opens an issue, and tries to fix it | -All of them run on `ubuntu-latest` with Node.js 24. The ones that need the repo's dependencies install them with -`npm ci`, or with pnpm when the repo has a `pnpm-lock.yaml` and no `package-lock.json`. +All of them run on `ubuntu-latest`. The jobs that need the repo's dependencies set up Node.js 24 and install them with +`npm ci`, or with `pnpm install` when the repo has a `pnpm-lock.yaml` and no `package-lock.json`. ## `public_pr-build-test.yaml` -Validates a pull request. It runs two jobs in parallel. +Validates a pull request with two parallel jobs. A new push to the same PR cancels the run in progress. **`platformTest`** builds and tests the Actors the PR changes: -1. Finds the affected Actors with [`get-affected-actors`](cli.md#finding-affected-actors-get-affected-actors), - comparing the PR branch with its base branch. Changed files that match `platformTestsGlob` in the config file - (default `test/platform/**`) are test changes, also when `.dockerignore` lists them. -2. Builds the Actors with functional changes into the test version `0.99` with - [`build`](cli.md#building-actors-build). Actors with only test changes are not built: they are tested on their - default build when the branch didn't change their code, or on the build an earlier run of the PR made, while that - build still exists. Cosmetic-only changes (README, CHANGELOG, schema formatting) need no tests, so they're not built. -3. Runs [`test`](cli.md#running-tests-test) on the files that match `test-files-glob`, with the new and reused builds, - so only the tests of those Actors run, each Actor with its test token. Failing tests are annotated on the PR. -4. On success, caches the tested commit as the "last validated commit", together with the builds the PR tested. The - next push to the PR then only builds and tests the Actors that changed since it (see `--since` in - [`get-affected-actors`](cli.md#finding-affected-actors-get-affected-actors)). If GitHub evicts the cache, the - next push checks and builds the whole branch again. - -**`unitTest`** runs static checks against the repo, using the repo's own scripts where they exist: - -| Check | Runs | -| -------------- | ------------------------------------------------------------------------------------------- | -| TypeScript | `npm run build-check` if the script exists, else `npx tsc --noEmit` | -| Lint | `npm run lint` | -| Test | `npm test` | -| Formatter | `npm run format:check` if it exists, else `npx prettier --check .` if prettier is installed | -| Unused exports | `npm run check-unused` if it exists | - -In a repo whose Actors aren't written in JavaScript or TypeScript, define the `build-check`, `lint` and `test` -scripts, e.g. to run your language's own checks: without them, the TypeScript, Lint and Test checks fail. +1. Finds the affected Actors with [`get-affected-actors`](cli.md#finding-affected-actors-get-affected-actors), comparing + the PR branch with its base branch. Changed files that match `platformTestsGlob` in the config file (default + `test/platform/**`) are test changes, even when `.dockerignore` lists them. +2. Builds the Actors with functional changes into the test version `0.99` with [`build`](cli.md#building-actors-build). + An Actor with only test changes is tested on its default build if the branch didn't change its code, or on the build + an earlier run of the PR made, while that build exists. Otherwise it is built too. Cosmetic-only changes (README, + CHANGELOG, schema formatting) need no tests, so they're not built. +3. Runs [`test`](cli.md#running-tests-test) on the files that match `test-files-glob`, against the new and reused + builds, so only the tests of those Actors run, each Actor with its test token. Failing tests are annotated on the PR. +4. If the tests pass, caches the tested commit as the "last validated commit", with the builds the PR tested. The next + push to the PR then only builds and tests the Actors that changed since that commit (see `--since` in + [`get-affected-actors`](cli.md#finding-affected-actors-get-affected-actors)). If GitHub evicts the cache, the next + push checks and builds the whole branch again. + +**`unitTest`** runs static checks, using the repo's own scripts where they exist: + +| Check | Runs | +| -------------- | ---------------------------------------------------------------------------------------------------------------------------------- | +| TypeScript | `npm run build-check` if the script exists, else `npx tsc --noEmit` | +| Lint | `npm run lint` | +| Test | `npm test` | +| Formatter | `npm run format:check` if it exists, else `npx prettier --check .` if Prettier is installed | +| Unused exports | `npm run check-unused` if it exists, else `knip` or `ts-unused-exports` if installed (in that order). Skipped when none is present | + +If your Actors aren't written in JavaScript or TypeScript, define the `build-check`, `lint`, and `test` scripts (for +example, to run your language's own checks). Without them, the TypeScript, Lint, and Test checks fail. | Input | Type | Default | Description | | -------------------------- | ------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------- | | `skip-platform-tests` | boolean | `false` | Skip the `platformTest` job and run the static checks only | | `test-files-glob` | string | `test/platform/**` | Glob of the test files to run, from the repo root. Empty means the default. See [Splitting the tests](#splitting-the-tests) | -| `require-env-vars-in-sync` | boolean | `true` | Fail the build unless the env var names of `0.99` match the default version's, see [Env var check](cli.md#env-var-check) | +| `require-env-vars-in-sync` | boolean | `true` | Fail the build unless the env var names of `0.99` match the default version's. See [Env var check](cli.md#env-var-check) | -Secrets: the Actor and test tokens in `CONFIG_SECRETS`, and optionally `NPM_TOKEN`. With `skip-platform-tests`, only -`NPM_TOKEN`. The build gets each Actor's `buildTokenEnvVar`, the tests its `testTokenEnvVar`. - -A new push to the same PR cancels the run in progress. +Secrets: `CONFIG_SECRETS` with each Actor's `buildTokenEnvVar` and `testTokenEnvVar`, and optionally `NPM_TOKEN`. With +`skip-platform-tests`, only `NPM_TOKEN`. ```yaml name: PR Test @@ -84,7 +82,7 @@ on: branches: [master] jobs: - buildDevelAndTest: + buildAndTest: uses: apify/apify-test-tools/.github/workflows/public_pr-build-test.yaml@workflows-v1 with: # Leaves out the *-without-pr folders, see "Splitting the tests" @@ -105,21 +103,21 @@ Releases the Actors a push changed. Skipped when the head commit message contain 1. `get-affected-actors --since ${{ github.event.before }}` finds everything the push changed. See [Releasing Actors](cli.md#releasing-actors) for how the released range is determined. -2. `build --version-number default` builds both the functionally and the cosmetically changed Actors into their - default version, the one users run. A push that only changes platform tests builds nothing. -3. [`notify`](cli.md#notifying-notify) posts the release (its changelog additions and its commits, linked to - GitHub) to the report channel. It posts nothing when the push brought no new commits. -4. `delete-old-builds` deletes old builds of every Actor in the config (see - [`delete-old-builds`](cli.md#deleting-old-builds-delete-old-builds)). +2. `build --version-number default` builds the functionally and the cosmetically changed Actors into their default + version, the one users run. A push that only changes platform tests builds nothing. +3. [`notify`](cli.md#notifying-notify) posts the release (its changelog additions and its commits, linked to GitHub) to + `report-slack-channel`. It posts nothing when the channel is empty or the push brought no new commits. +4. [`delete-old-builds`](cli.md#deleting-old-builds-delete-old-builds) deletes old builds of every Actor in the config. -| Input | Type | Default | Description | -| ---------------------- | ------ | ------- | ----------------------------------------------- | -| `report-slack-channel` | string | `''` | Slack channel for the report. Empty skips Slack | +| Input | Type | Default | Description | +| ---------------------- | ------ | ------- | ------------------------------------------------ | +| `report-slack-channel` | string | `''` | Slack channel for the release. Empty skips Slack | -Secrets: `SLACK_BOT_TOKEN`, the Actor tokens in `CONFIG_SECRETS`, and optionally `NPM_TOKEN`. +Secrets: `CONFIG_SECRETS` with each Actor's `buildTokenEnvVar`, `SLACK_BOT_TOKEN` when `report-slack-channel` is set, +and optionally `NPM_TOKEN`. -A failed release isn't retried by the next push: that push's "before" commit is the failed one's head, so its changes -are skipped. Re-run the failed workflow run, or release the Actors manually. +The next push doesn't retry a failed release: its "before" commit is the failed push's head, so the failed push's +changes are skipped. Re-run the failed workflow run, or release the Actors manually. ```yaml name: Release latest @@ -146,20 +144,23 @@ jobs: ## `public_platform-tests.yaml` Runs the platform tests of every Actor in the config against its current default build, by piping -[`get-actor-configs`](cli.md#listing-actors-get-actor-configs) into [`test`](cli.md#running-tests-test). A separate step then posts failures to Slack with -[`notify`](cli.md#notifying-notify), named after the calling workflow and linking to the run, so the Slack token never -reaches the tests. Both the report of `test` and -vitest's own JSON report are uploaded as the `vitest-results` artifact. Runs only on `master` or `main`. +[`get-actor-configs`](cli.md#listing-actors-get-actor-configs) into [`test`](cli.md#running-tests-test). Runs only on +`master` or `main`. + +A separate [`notify`](cli.md#notifying-notify) step then posts failures to `report-slack-channel`, titled with the +calling workflow's name and linking to the run, so the Slack token never reaches the tests. It posts nothing when the +tests pass or the channel is empty. The report of `test` and Vitest's JSON report are uploaded as the `vitest-results` +artifact. | Input | Type | Default | Description | | ---------------------- | ------ | ------------------ | --------------------------------------------------------------------------------------------------------------------------- | | `test-files-glob` | string | `test/platform/**` | Glob of the test files to run, from the repo root. Empty means the default. See [Splitting the tests](#splitting-the-tests) | -| `report-slack-channel` | string | `''` | Slack channel for the results. Empty skips Slack | +| `report-slack-channel` | string | `''` | Slack channel for failed tests. Empty skips Slack | -Secrets: the test tokens in `CONFIG_SECRETS`, `SLACK_BOT_TOKEN`, and optionally `NPM_TOKEN`. The tests run each Actor -with its `testTokenEnvVar`. +Secrets: `CONFIG_SECRETS` with each Actor's `testTokenEnvVar`, `SLACK_BOT_TOKEN` when `report-slack-channel` is set, +and optionally `NPM_TOKEN`. -How often to run which tests is up to you, see [Splitting the tests](#splitting-the-tests). For example, the daily +How often to run which tests is up to you (see [Splitting the tests](#splitting-the-tests)). For example, the daily tests once a day: ```yaml @@ -216,8 +217,8 @@ jobs: `test-files-glob` is one glob from the repo root, for example `test/platform/**`. Both test workflows take it, and it only selects which tests run. Which changed files count as test changes is a separate setting, `platformTestsGlob` in -the config file (default `test/platform/**`). So on a PR, a change to a `*-without-pr` test or to a shared helper -still builds and tests the Actors, even though the PR doesn't run that test. +the config file (default `test/platform/**`). So on a PR, a change to a `*-without-pr` test or to a shared helper still +builds and tests the Actors, even though the PR doesn't run that test. Most repos split `test/platform` into folders by how often the tests run, and by whether a PR runs them: @@ -225,7 +226,7 @@ Most repos split `test/platform` into folders by how often the tests run, and by | --------------------------------- | --------------------------------------------------------------- | | `test/platform/hourly` | every hour and on every PR | | `test/platform/daily` | once a day and on every PR | -| `test/platform/hourly-without-pr` | every hour only, e.g. tests that are too slow or costly for PRs | +| `test/platform/hourly-without-pr` | every hour only (for example, tests too slow or costly for PRs) | | `test/platform/daily-without-pr` | once a day only | Each workflow then selects its folders with a brace pattern: @@ -237,13 +238,14 @@ Each workflow then selects its folders with a brace pattern: | Daily (`public_platform-tests.yaml`) | `test/platform/{daily,daily-without-pr}/**` | Write the glob to match files, not folders: `test/platform/hourly` matches no file, `test/platform/hourly/**` matches -every file in it. A glob that matches no file fails the test step, so a typo doesn't pass as a run with no tests. -`test` only runs the matched files that vitest sees as test files, so a helper in the glob runs nothing. +every file in it. A glob that matches no file fails the test step, so a typo can't pass as a run with no tests. `test` +only runs the matched files that Vitest sees as test files, so a helper in the glob runs nothing. ## `public_review.yaml` -Optional. Reviews a PR against the shared guidelines when you add the trigger label, and again on every push while -that label is on. The trigger label is removed once the review finishes, so re-applying it asks for another review. +Optional. Reviews a PR against the shared guidelines when you add the trigger label. The label is removed when the +review finishes, so adding it again asks for another review. A push while the label is still on restarts the review on +the new commit. | Input | Type | Default | Description | | ---------------- | ------ | ------------------- | --------------------------------------------------------------------------------------------- | @@ -268,20 +270,21 @@ jobs: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} ``` -The review instructions live in `.github/review-prompt.md` in this repo and are fetched at run time, because a -reusable workflow doesn't get its own repo checked out. When `prompt-ref` is empty they come from the same commit as -the workflow you're calling — point it at a branch only to test a prompt change. +The review instructions live in `.github/review-prompt.md` in this repo. A reusable workflow doesn't get its own repo +checked out, so they are fetched at run time. When `prompt-ref` is empty, they come from the same commit as the +workflow you're calling. ## `public_claude.yaml` -Optional. Runs Claude Code when someone mentions `@claude` in an issue, an issue or PR comment, or a PR review, or -labels an issue `claude` (unless it is also labeled `claude:done`). On a PR it pushes to the PR's branch; on an issue -it opens a PR. It also picks up a "changes requested" review on PRs Claude opened. +Optional. Runs Claude Code when someone mentions `@claude` in an issue's title or body, an issue or PR comment, or a PR +review, or labels an issue `claude` (unless it also has `claude:done`). On a PR, Claude pushes to the PR's branch. On +an issue, it opens a PR and, when the run came from the `claude` label, labels the issue `claude:done`. It also acts on +a "changes requested" review of a PR Claude opened. -| Input | Type | Default | Description | -| --------------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------ | -| `model` | string | `sonnet` | Claude Code model (`best`, `sonnet`, `opus`, `haiku`, `sonnet[1m]`, `opus[1m]`, `opusplan`) | -| `extra_allowed_tools` | string | `''` | Comma-separated tool patterns appended to `--allowedTools`, e.g. `Bash(npm run e2e),Bash(npm run typecheck)` | +| Input | Type | Default | Description | +| --------------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------- | +| `model` | string | `sonnet` | Claude Code model (`best`, `sonnet`, `opus`, `haiku`, `sonnet[1m]`, `opus[1m]`, `opusplan`) | +| `extra_allowed_tools` | string | `''` | Comma-separated tool patterns appended to `--allowedTools`, for example `Bash(npm run e2e),Bash(npm run typecheck)` | Secrets: `ANTHROPIC_API_KEY`. @@ -309,40 +312,40 @@ jobs: Optional. Call it after a failed platform test job. It runs in two phases: -1. **investigate** — Claude reviews the test logs, recent workflow runs and existing issues, and investigates the - failing run on the Apify platform (its log, dataset and key-value store). It opens a GitHub issue with its - findings and labels it `claude`, or does nothing if a matching issue already exists. -2. **fix** — runs only when the first phase opened an issue. Claude implements a fix, opens a PR, and labels the - issue `claude:done`. - -Scheduled runs use a `GITHUB_TOKEN` that cannot trigger other workflows, so the fix phase is a direct job -dependency rather than a label-triggered run of `public_claude.yaml`. - -| Input | Type | Default | Description | -| -------------------- | ------ | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `model` | string | `sonnet` | Claude model for both phases | -| `effort` | string | `''` | Claude effort level (`low`, `medium`, `high`, `xhigh`, `max`). Empty uses the Claude Code default | -| `max_flakiness_runs` | number | `200` | The most times Claude may re-run the failing Actor run to measure how often the failure happens | -| `investigate_prompt` | string | (built in) | Prompt for the investigation phase. Override to change how issues are investigated, titled and described | -| `priority_prompt` | string | (built in) | Prompt for setting a new issue's Priority field from its impact and flakiness. Override to change how priority is judged, e.g. to set revenue thresholds | -| `humanize_duty` | string | `''` | Where to record the developer who rewrites each new issue in plain language. `label` labels the issue `needs-humanize:`. Off when empty | - -With `humanize_duty: label`, each new issue gets a label like `needs-humanize:alice`. -The developers are the individual users on the `*` rule of the repo's CODEOWNERS (`.github/CODEOWNERS`, `CODEOWNERS` -or `docs/CODEOWNERS`), in the order listed; teams and emails are skipped. They take turns: the next issue goes to the -developer after the one most recently labeled `needs-humanize:`. The first issue, or one after that developer -left CODEOWNERS, goes to a developer picked from the repo name, so repos don't all start with the same person. Labels -stay on the issues; the rotation reads them back, so removing one makes that developer's turn come round again early. -Without CODEOWNERS or any individual user on its `*` rule, the job logs a warning and adds no label. It uses -`GITHUB_TOKEN` and needs no extra setup. - -`label` is the only supported value for now. Any other value fails the job that records the duty, and leaves the -investigate and fix phases alone. - -Secrets: `ANTHROPIC_API_KEY`, `TESTER_APIFY_TOKEN`, and optionally `NPM_TOKEN`, `REDASH_API_KEY` and `AGENT_SKILLS_INTERNAL_GITHUB_TOKEN`. - -Runs are private to the account that started them, so `TESTER_APIFY_TOKEN` here must be the token the tests ran the -failing Actor with: its `testTokenEnvVar`. +1. **Investigate:** Claude reviews the test logs, recent workflow runs, and existing issues, and investigates the + failing run on the Apify platform (its log, dataset, and key-value store). It opens a GitHub issue with its findings + and labels it `claude`, or does nothing if a matching issue already exists. +2. **Fix:** runs only when the first phase opened an issue. Claude implements a fix, opens a PR, and labels the issue + `claude:done`. + +Scheduled runs use a `GITHUB_TOKEN` that can't trigger other workflows, so the fix phase is a direct job dependency +rather than a label-triggered run of `public_claude.yaml`. + +| Input | Type | Default | Description | +| -------------------- | ------ | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `model` | string | `sonnet` | Claude model for both phases | +| `effort` | string | `''` | Claude effort level (`low`, `medium`, `high`, `xhigh`, `max`). Empty uses the Claude Code default | +| `max_flakiness_runs` | number | `200` | The most times Claude may re-run the failing Actor run to measure how often the failure happens | +| `investigate_prompt` | string | (built in) | Prompt for the investigation phase. Override to change how issues are investigated, titled, and described | +| `priority_prompt` | string | (built in) | Prompt for setting a new issue's Priority field from its impact and flakiness. Override to change how priority is judged, for example, to set revenue thresholds | +| `humanize_duty` | string | `''` | Where to record the developer who rewrites each new issue in plain language. `label` labels the issue `needs-humanize:`. Off when empty | + +`label` is the only supported `humanize_duty` value. It labels each new issue like `needs-humanize:alice`, in a separate +job that never holds up the investigate or fix phase. Any other value fails that job only. + +The developers are the individual users on the `*` rule of the repo's CODEOWNERS (`.github/CODEOWNERS`, `CODEOWNERS`, or +`docs/CODEOWNERS`; the last `*` rule if there are several), in the order listed. Teams and emails are skipped. They take +turns: the next issue goes to the developer after the one most recently labeled `needs-humanize:`. The first +issue, or one after that developer left CODEOWNERS, goes to a developer picked from the repo name, so repos don't all +start with the same person. The rotation reads the labels back from the issues, so removing one gives that developer +their turn again early. Without CODEOWNERS or any individual user on its `*` rule, the job logs a warning and adds no +label. It uses `GITHUB_TOKEN` and needs no extra setup. + +Secrets: `ANTHROPIC_API_KEY`, `TESTER_APIFY_TOKEN`, and optionally `NPM_TOKEN`, `REDASH_API_KEY`, and +`AGENT_SKILLS_INTERNAL_GITHUB_TOKEN`. + +Runs are private to the account that started them, so `TESTER_APIFY_TOKEN` must be the token the tests ran the failing +Actor with: its `testTokenEnvVar`. ```yaml jobs: @@ -372,12 +375,12 @@ jobs: ## `public_stale-issues.yaml` Optional. Wraps [`actions/stale`](https://github.com/actions/stale) to warn on inactive GitHub issues, then close them -as **not planned** 30 days later if still inactive. Locked issues are skipped. Pull requests use the same stale and -close thresholds, with the `Stale` label and no warning or closing comments. +as **not planned** 30 days later if still inactive. Locked issues are skipped. Pull requests use the same thresholds, +with the `Stale` label and no warning or closing comments. -| Input | Type | Default | Description | -| -------------- | ------ | ------- | -------------------------------------------------------------------- | -| `stale-months` | number | `6` | Optional whole number of inactive months (1–12); one month = 30 days | +| Input | Type | Default | Description | +| -------------- | ------ | ------- | ----------------------------------------------------------- | +| `stale-months` | number | `6` | Whole number of inactive months (1–12). One month = 30 days | ```yaml name: Close stale issues @@ -397,77 +400,81 @@ jobs: ``` With `stale-months: 6`, an issue is labeled `stale` and warned after 180 days without activity, then closed after -another 30 inactive days. Existing older issues also get the full 30-day warning when adopting the workflow. -Actions happen on a scheduled run after the threshold; large backlogs are processed over successive runs. +another 30 inactive days. When you adopt the workflow, older issues also get the full 30-day warning. Each scheduled run +acts on the issues past the threshold, and a large backlog is processed over several runs. -The warning comment uses [GitHub's normal issue notifications](https://docs.github.com/en/subscriptions-and-notifications/reference/inbox-filters), -including notifications for assigned issues, subject to each user's notification settings. It does not add explicit -@mentions. Subsequent activity causes `actions/stale` to remove the stale label and restart the inactivity period. +The warning comment reaches people through +[GitHub's normal issue notifications](https://docs.github.com/en/subscriptions-and-notifications/reference/inbox-filters) +(including for assigned issues), subject to each user's settings. It adds no @mentions. Any later activity removes the +`stale` label and restarts the inactivity period. -The caller must grant `issues: write` as shown above. The workflow uses the automatic `GITHUB_TOKEN`; no additional -secrets, checkout, project dependencies, or Apify configuration are needed. +The caller must grant `issues: write`, as shown above. The workflow uses the automatic `GITHUB_TOKEN` and needs no +secrets, checkout, project dependencies, or Apify configuration. ## Secrets The workflows take two kinds of secrets: -- **Secrets a workflow always reads**, like `SLACK_BOT_TOKEN` for notifications or `NPM_TOKEN` for installing private - packages. Each workflow declares these, and you pass them by name. +- **Secrets a workflow declares by name**, like `SLACK_BOT_TOKEN` for Slack reports or `NPM_TOKEN` for installing + private packages. Pass them by name. - **Secrets your `apify-test-tools.config.json` names**: each Actor's `buildTokenEnvVar` and `testTokenEnvVar`. Their - names differ per repo, and a reusable workflow only accepts secrets it declares by name, so they go packed in one - JSON object, `CONFIG_SECRETS`, with one entry per name the config uses. A name the config declares but the object - leaves out is reported as a warning in the build or test step. + names differ per repo, and a reusable workflow only accepts secrets it declares, so they go packed in one JSON object, + `CONFIG_SECRETS`, with one entry per name the config uses. The workflows read the Apify tokens only from + `CONFIG_SECRETS`. -The examples above show both. If you'd rather not keep `CONFIG_SECRETS` in sync with the config, you can pass all of -the repo's secrets in it: +The examples above show both. If you'd rather not keep `CONFIG_SECRETS` in sync with the config, pass all of the repo's +secrets in it: ```yaml secrets: CONFIG_SECRETS: ${{ toJSON(secrets) }} ``` -Only the names the config declares are used. The cost is that every secret the repo can read, deploy keys and publish -tokens included, goes to code at a tag this repo moves, and you are trusting it to use only those. +Only the names the config declares are used. The cost: every secret the repo can read, deploy keys and publish tokens +included, goes to code at a tag this repo moves, and you trust it to use only those. `secrets: inherit` doesn't pass the Apify tokens: the workflows read them only from `CONFIG_SECRETS`, and GitHub doesn't let a job inherit its secrets and list `CONFIG_SECRETS` too. Pass the secrets by name. -`required` on a reusable workflow's secret only checks that the caller lists it, not that it has a value: the repo -may not have the secret, and PRs from forks never get secrets. A test token that doesn't arrive is a warning in the -test step, and the tests of its Actors fail with a message naming the token. +The build and test workflows declare every secret optional, and PRs from forks never get secrets. A missing token shows +up where it's needed: + +- A name the config declares but `CONFIG_SECRETS` leaves out is a warning in the build or test step. +- A build fails with an error naming the Actor only once it needs the missing build token. A repo can carry an Actor + whose token isn't set and still build, as long as that Actor never changes. +- The tests of an Actor whose test token is missing fail with a message naming the token. -Values that arrive inside `CONFIG_SECRETS` are registered as masks one by one before anything uses them. The runner -masks a secret by its exact value, so it would otherwise only recognise the whole JSON blob, not a single token taken -out of it. +The values inside `CONFIG_SECRETS` are registered as masks one by one before anything uses them. The runner masks a +secret by its exact value, so otherwise it would only recognize the whole JSON object, not a single token taken out of +it. -The workflows do not turn the secrets they receive into job-wide environment variables, so a secret is only visible -to the step that needs it: +The workflows don't turn secrets into job-wide environment variables, so a secret is only visible to the steps that +need it: -| Secret | Reaches | -| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `NPM_TOKEN` | dependency install steps only, as both `NPM_TOKEN` and `NODE_AUTH_TOKEN`. Use a read-only token: npm granular tokens can be read-only, classic automation tokens can publish. | -| the Actor tokens named by `buildTokenEnvVar` in `apify-test-tools.config.json` | the build and `delete-old-builds` steps only | -| the test tokens named by `testTokenEnvVar`, which can be the Actor tokens | the test step only. A token that is also an Actor token reaches the build steps too | -| `TESTER_APIFY_TOKEN` | the Claude investigation step: the Apify MCP server's bearer token for reading the failing run, its log and its storages, and Claude's token for re-running it to measure how often the failure happens | -| `SLACK_BOT_TOKEN` | the `notify` steps only | -| `ANTHROPIC_API_KEY` | the Claude steps of the Claude workflows only | -| `REDASH_API_KEY` | the Claude investigation step: the Redash MCP server's key for measuring the failure's impact from Snowflake. Optional | -| `AGENT_SKILLS_INTERNAL_GITHUB_TOKEN` | the investigation job's checkout of `apify/agent-skills-internal` only, for the `redash-analyst` plugin. Optional | +| Secret | Reaches | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `NPM_TOKEN` | the dependency install steps only, as both `NPM_TOKEN` and `NODE_AUTH_TOKEN`. Use a read-only token: npm granular tokens can be read-only, classic automation tokens can publish | +| build tokens (`buildTokenEnvVar`) | the build and `delete-old-builds` steps only | +| test tokens (`testTokenEnvVar`) | the test step only. A token that is also a build token reaches the build steps too | +| `TESTER_APIFY_TOKEN` | the Claude investigation step: the Apify MCP server's token for reading the failing run, its log, and its storages, and Claude's token for re-running it to measure how often the failure happens | +| `SLACK_BOT_TOKEN` | the `notify` steps only | +| `ANTHROPIC_API_KEY` | the Claude steps only | +| `REDASH_API_KEY` | the Claude investigation step: the Redash MCP server's key for measuring the failure's impact from Snowflake. Optional | +| `AGENT_SKILLS_INTERNAL_GITHUB_TOKEN` | the investigation job's checkout of `apify/agent-skills-internal` only, for the `redash-analyst` plugin. Optional | -The Actor tokens reach the build only for the Actors your config declares: a secret that merely looks like an Actor -token is not passed on. A token the config declares but the repo hasn't set is a warning, not a failure: a repo can -carry an Actor whose token isn't configured and still build fine as long as that Actor never changes. The build fails -with an error naming the Actor once it actually needs the token. +The build and test steps get only the tokens the config declares for that step: a secret that merely looks like an +Apify token is not passed on, and `CONFIG_SECRETS` itself never reaches the CLI. -The wrapper validates the config with the CLI's parser. Each Actor must declare a nonempty `buildTokenEnvVar` and -`testTokenEnvVar` or take them from its group. An empty or missing name fails during config validation. +To find the token names, the steps read the config with the CLI's own parser, so an invalid config fails them. With +`mode: "grouped"`, each group must declare a nonempty `buildTokenEnvVar` and `testTokenEnvVar` (there is no default), +and an Actor entry can override either. The pre-v1 `tokenEnvVar` field is rejected. -The `unitTest` job runs static checks and needs `NPM_TOKEN` only. No job runs `npm ci` or `pnpm install` with Apify -or Slack credentials in scope, so a postinstall script in the dependency tree cannot read them. +No job runs `npm ci` or `pnpm install` with Apify or Slack credentials in scope, so a postinstall script in the +dependency tree can't read them. The `unitTest` job needs `NPM_TOKEN` only. ## Versioning -The workflows and the vitest library ship separately: +The workflows and the Vitest library ship separately: | What | You get it through | Updates when | | ------------------------------------------------ | ----------------------------------------- | -------------------------------- | @@ -477,11 +484,11 @@ The workflows and the vitest library ship separately: The workflows bring their own copy of the CLI, so they don't use or change the `apify-test-tools` version in your `node_modules`, and your tests keep the library version you locked. -Whatever ref you call a workflow at, it runs the setup action and the CLI from that same commit. Pinning a commit SHA -or pointing at a branch of this repo therefore gets you that commit's workflows as a whole. +Whatever ref you call a workflow at, it runs the setup action and the CLI from that same commit. Pinning a commit SHA or +a branch of this repo gets you that commit's workflows as a whole. -`@workflows-v1` always points at the latest workflows, so fixes and new features reach you without any change on your -side. Changes that would break callers go to a new tag (`@workflows-v2`), and `@workflows-v1` keeps working, so you -can migrate when it suits you. +`@workflows-v1` always points at the latest workflows, so fixes and new features reach you with no change on your side. +Changes that would break callers go to a new tag (`@workflows-v2`), and `@workflows-v1` keeps working, so you can +migrate when it suits you. -`@workflows-v1` needs `apify-test-tools` 1.0.0 or newer in your `package.json`: the test step fails on an older one. +`@workflows-v1` needs `apify-test-tools` 1.0.0 or newer in your `package.json`. The test step fails on an older one.