Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
- `npm run docs`: regenerates README frontmatter, the badge line, `examples.json` and the tables in the root `README.md` from the manifests.
- `npm test`: runs the tests of the repository's scripts.
- `node scripts/check-examples.mjs <dir>`: the static checks for one example.
- `node scripts/test-example.mjs <dir>`: deploys the example to the AWS account of the credentials in your environment, runs the checks its `example.json` declares, and removes it. It creates real resources and costs money. `--stage <stage>` uses that stage (`ex` plus 1 to 13 lowercase letters or digits) instead of a new one; `--remove-only --stage <stage>` deploys nothing and only removes what that stage left.
- `node scripts/test-example.mjs <dir>`: deploys the example to the AWS account of the credentials in your environment, runs the checks its `example.json` declares, and removes it. It creates real resources and costs money. `--stage <stage>` uses that stage (`ex` plus 1 to 13 lowercase letters or digits) instead of a new one; `--remove-only --stage <stage>` deploys nothing and only removes what that stage left. An example that needs something CloudFormation can't create before its deploy (a container image pushed to a repository) names Node.js scripts in `test.prepare`, which runs before deploy, and `test.cleanup`, which runs after remove, also with `--remove-only`, and must pass when there is nothing to remove; both get `EXAMPLE_STAGE`, `EXAMPLE_REGION` and `EXAMPLE_DIR`.
- `node scripts/select-examples.mjs --changed <base-sha>` or `--all --tier fast|slow`: prints the examples a live test run covers, as JSON.
- `node scripts/publish-verified.mjs --results-dir <dir> --out <dir> --run-url <url>`: adds `latest` result files to `results.json` in `--out` and writes `badges/<example dir>.svg`. The `publish-verified` workflow runs it for the `verified` branch.
- `node scripts/cleanup-report.mjs --regions <list>`: lists CloudFormation stacks whose names end in a test stage and that are older than 24 hours. It deletes nothing.
Expand Down
22 changes: 20 additions & 2 deletions scripts/lib/manifest.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@
// region? string
// priority? number
// onboarding? boolean
// test? { tier: "fast"|"slow", checks: Check[], timeoutMinutes?, quarantine?: { reason, since } }
// test? { tier: "fast"|"slow", checks: Check[], timeoutMinutes?, quarantine?: { reason, since },
// prepare?: { path }, cleanup?: { path } }
//
// prepare and cleanup name Node.js scripts the live test runs before deploy and
// after remove; cleanup needs prepare.
//
// A Check has exactly one key:
// http: { output, path?, status?, contains? } status or contains is required
Expand All @@ -31,7 +35,8 @@ const CHECK_KINDS = ['http', 'invoke', 'script'];
const KEYS = {
root: ['dir', 'title', 'description', 'language', 'platform', 'framework', 'author', 'services', 'region', 'priority', 'onboarding', 'test'],
author: ['name', 'link', 'avatar'],
test: ['tier', 'checks', 'timeoutMinutes', 'quarantine'],
test: ['tier', 'checks', 'timeoutMinutes', 'quarantine', 'prepare', 'cleanup'],
hook: ['path'],
quarantine: ['reason', 'since'],
http: ['output', 'path', 'status', 'contains'],
invoke: ['function', 'event', 'args', 'contains'],
Expand Down Expand Up @@ -124,6 +129,19 @@ function validateTest(errors, t) {
errors.push('test.timeoutMinutes: must be a positive number');
}

for (const hook of ['prepare', 'cleanup']) {
if (t[hook] === undefined) continue;
if (!isObject(t[hook])) {
errors.push(`test.${hook}: must be an object with path`);
continue;
}
rejectUnknownKeys(errors, t[hook], KEYS.hook, `test.${hook}.`);
requireString(errors, t[hook], 'path', `test.${hook}.path`);
}
if (t.cleanup !== undefined && t.prepare === undefined) {
errors.push('test.cleanup: needs test.prepare; cleanup runs only after a prepare script ran');
}

if (t.quarantine !== undefined) {
if (!isObject(t.quarantine)) {
errors.push('test.quarantine: must be an object with reason and since');
Expand Down
8 changes: 7 additions & 1 deletion scripts/lib/static-checks.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
// blocks) in files tracked by git
// generated-readme README.md frontmatter and badge match the manifest
// generated-catalogue the examples.json entry matches the manifest
// check-paths script check paths and invoke event files exist
// check-paths script check paths, invoke event files and prepare and cleanup scripts exist
//
// An example whose manifest sets `"onboarding": true` is exempt from the
// lockfile and exact-version rules only.
Expand Down Expand Up @@ -329,6 +329,12 @@ function checkPaths(exampleDir, manifest) {
errors.push(`check-paths: test.checks[${i}]: ${what} ${target} does not exist`);
}
});
for (const hook of ['prepare', 'cleanup']) {
const target = manifest.test?.[hook]?.path;
if (typeof target === 'string' && !fs.existsSync(path.join(exampleDir, target))) {
errors.push(`check-paths: test.${hook}: script ${target} does not exist`);
}
}
return errors;
}

Expand Down
56 changes: 53 additions & 3 deletions scripts/test-example.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@
// `SKIP <dir> quarantined: <reason>` for a quarantined example.
// Exit code: 0 pass or skip, 1 a failed step (remove included), 2 usage or manifest error.
//
// A manifest's test.prepare script runs after install and before deploy, and
// its test.cleanup script after remove, whenever prepare started (also when a
// step failed or the run was interrupted) and in --remove-only runs. Both run
// with `node` in the copy, with EXAMPLE_STAGE, EXAMPLE_REGION and EXAMPLE_DIR
// set; cleanup must pass when there is nothing to remove.
//
// On SIGINT or SIGTERM the current step stops, remove runs, the result records
// the stopped step as `interrupted`, and the exit code is 1. A second signal
// kills every running command's process group, exits at once and names the
Expand Down Expand Up @@ -67,6 +73,7 @@ const MINUTE = 60_000;
const DEFAULT_TIMEOUT_MINUTES = 15;
const DEFAULT_REGION = 'us-east-1';
const REMOVE_TIMEOUT_MS = 15 * MINUTE;
const CLEANUP_TIMEOUT_MS = 10 * MINUTE;
const VERSION_TIMEOUT_MS = 2 * MINUTE;
// After a remove that exits non-zero: how often and how long to watch the stage's stacks.
const REMOVE_POLL_MS = 10_000;
Expand Down Expand Up @@ -126,7 +133,7 @@ export class UsageError extends Error {
* @property {string} region the region every command used
* @property {string} startedAt ISO 8601
* @property {number} durationSeconds
* @property {'install'|'deploy'|'check'|'remove'} [failedStep] the first step that did not complete
* @property {'install'|'prepare'|'deploy'|'check'|'remove'|'cleanup'} [failedStep] the first step that did not complete
* @property {string} [detail] what went wrong, or why the example was skipped
* @property {string} [leftBehind] stacks a failed remove may have left, comma-separated
* In `detail` and `leftBehind` every 12-digit number reads 123456789012.
Expand All @@ -142,8 +149,9 @@ export function newStage(now = Date.now()) {

/**
* Copies the example at `<root>/<dir>` to a temporary directory, installs its
* dependencies, deploys it with a new stage, reads the stack outputs, runs the
* manifest's checks and removes the deployment. Every external command goes
* dependencies, runs the manifest's prepare script, deploys it with a new stage,
* reads the stack outputs, runs the manifest's checks, removes the deployment
* and runs the manifest's cleanup script. Every external command goes
* through `exec` (signature of runCommand), HTTP through `fetchImpl`. The
* region is `region`, else the manifest's, else AWS_REGION or
* AWS_DEFAULT_REGION from `env`, else us-east-1. When `signal` aborts, the
Expand Down Expand Up @@ -230,6 +238,7 @@ export async function runExample({

const { copy, cleanup } = copyExample(root, dir, 'example-run-');
let deployStarted = false;
let prepareStarted = false;
let resolvedVersion = 'unknown';
let leftBehind;
try {
Expand All @@ -243,6 +252,12 @@ export async function runExample({
}
});

await attempt('prepare', () => {
if (!manifest.test.prepare) return undefined;
prepareStarted = true;
return runHook({ exec, env, hook: 'prepare', script: manifest.test.prepare.path, cwd: copy, stage, region, timeoutMs: left(), signal });
});

await attempt('deploy', () => {
deployStarted = true;
onDeployStart(stacks);
Expand Down Expand Up @@ -287,6 +302,15 @@ export async function runExample({
}
}
}
if (prepareStarted) {
const error = await runCleanupHook({ exec, env, manifest, cwd: copy, stage, region, log });
if (error && failure.step) {
failure.detail += `; cleanup: ${error}`;
} else if (error) {
failure.step = 'cleanup';
failure.detail = error;
}
}
}
} finally {
cleanup();
Expand All @@ -311,6 +335,7 @@ export async function runExample({
* in `-<stage>`, installs dependencies where a serverless.yml loads plugins and
* runs `serverless remove`. Nothing deployed is a pass with the detail
* `nothing deployed`. When the stacks cannot be listed, remove runs anyway.
* The manifest's cleanup script runs last, whatever remove found.
* The region is chosen as in runExample. Resolves to a Result.
*/
export async function removeOnly({
Expand Down Expand Up @@ -379,6 +404,12 @@ export async function removeOnly({
});
}
}
const error = await runCleanupHook({ exec, env, manifest, cwd: copy, stage, region, log });
if (error && result.result === 'fail') {
result.detail += `; cleanup: ${error}`;
} else if (error) {
Object.assign(result, { result: 'fail', failedStep: 'cleanup', detail: error });
}
} finally {
cleanup();
}
Expand All @@ -391,6 +422,25 @@ export async function removeOnly({
return result;
}

// Runs a test.prepare or test.cleanup script with node in `cwd`.
function runHook({ exec, env, hook, script, cwd, stage, region, timeoutMs, signal }) {
const hookEnv = { ...env, EXAMPLE_STAGE: stage, EXAMPLE_REGION: region, EXAMPLE_DIR: cwd };
return runOrThrow(exec, 'node', [script], { cwd, env: hookEnv, step: hook, timeoutMs, signal });
}

// Runs the manifest's cleanup script, when it has one, with its own deadline and
// no signal, like remove. Resolves to undefined, or to why it did not complete.
async function runCleanupHook({ exec, env, manifest, cwd, stage, region, log }) {
if (!manifest.test.cleanup) return undefined;
try {
await runHook({ exec, env, hook: 'cleanup', script: manifest.test.cleanup.path, cwd, stage, region, timeoutMs: CLEANUP_TIMEOUT_MS });
return undefined;
} catch (err) {
log(`[cleanup] ${err.message}`);
return err.message;
}
}

// Result files are uploaded as artifacts of a public repository, and AWS error
// messages quoted in `detail` can name the account: every 12-digit number in
// `detail` and `leftBehind` becomes the placeholder account id. Changes `result`.
Expand Down
24 changes: 24 additions & 0 deletions tests/manifest.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ test('optional fields with the right types are valid', () => {
{ script: { path: 'test/smoke.mjs' } },
);
m.test.quarantine = { reason: 'Upstream API rate limits', since: '2026-11-01' };
m.test.prepare = { path: 'test/prepare.mjs' };
m.test.cleanup = { path: 'test/cleanup.mjs' };
assert.deepEqual(validateManifest(m), []);
});

Expand Down Expand Up @@ -122,6 +124,7 @@ test('unknown keys are errors naming the key and its path, at every level', () =
[(m) => { m.test.checks[0].http.statusCode = 200; }, 'test.checks[0].http.statusCode'],
[(m) => { m.test.checks = [{ invoke: { function: 'f', contains: 'ok', payload: '{}' } }]; }, 'test.checks[0].invoke.payload'],
[(m) => { m.test.checks = [{ script: { path: 'test/smoke.mjs', args: [] } }]; }, 'test.checks[0].script.args'],
[(m) => { m.test.prepare = { path: 'test/prepare.mjs', args: [] }; }, 'test.prepare.args'],
];
for (const [mutate, keyPath] of cases) {
const m = validManifest();
Expand Down Expand Up @@ -339,3 +342,24 @@ test('loadManifest names the file when the JSON is invalid', () => {
fs.rmSync(root, { recursive: true, force: true });
}
});

test('prepare and cleanup need a path', () => {
for (const hook of ['prepare', 'cleanup']) {
for (const value of [{}, { path: '' }, 'test/prepare.mjs']) {
const m = validManifest();
m.test.prepare = { path: 'test/prepare.mjs' };
m.test[hook] = value;
const errors = validateManifest(m);
assert.equal(errors.length, 1, `${hook}=${JSON.stringify(value)}: ${errors.join('\n')}`);
assert.match(errors[0], new RegExp(`test\\.${hook}`));
}
}
});

test('cleanup without prepare is an error', () => {
const m = validManifest();
m.test.cleanup = { path: 'test/cleanup.mjs' };
const errors = validateManifest(m);
assert.equal(errors.length, 1, errors.join('\n'));
assert.match(errors[0], /test\.cleanup: needs test\.prepare/);
});
124 changes: 124 additions & 0 deletions tests/runner.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1312,3 +1312,127 @@ test('a successful listing resets the count of failed ones', async () => {
assert.equal(fx.calls.filter((c) => c.args[1] === 'list-stacks').length, 6);
assert.equal(result.result, 'pass');
});

// --- prepare and cleanup

function hookManifest(hooks = { prepare: { path: 'test/prepare.mjs' }, cleanup: { path: 'test/cleanup.mjs' } }) {
const m = manifest();
Object.assign(m.test, hooks);
return m;
}

const nodeStep = (script) => (c) => c.step === `node ${script}`;

function hookFixture(hooks) {
return fixture({ example: hookManifest(hooks), files: { 'test/prepare.mjs': '', 'test/cleanup.mjs': '' } });
}

test('prepare runs after install and before deploy, cleanup after remove, both in the copy with the stage, region and dir', async () => {
const root = hookFixture();
const { result, fx } = await run(root, { args: { region: 'eu-west-1' } });
assert.equal(result.result, 'pass');
assert.deepEqual(fx.steps(), [
'serverless --version',
'npm ci',
'node test/prepare.mjs',
'serverless deploy',
'aws cloudformation',
'serverless remove',
'node test/cleanup.mjs',
]);
const deployCwd = fx.calls.find((c) => c.step === 'serverless deploy').cwd;
for (const script of ['test/prepare.mjs', 'test/cleanup.mjs']) {
const call = fx.calls.find(nodeStep(script));
assert.equal(call.cwd, deployCwd);
assert.equal(call.env.EXAMPLE_STAGE, result.stage);
assert.equal(call.env.EXAMPLE_REGION, 'eu-west-1');
assert.equal(call.env.EXAMPLE_DIR, deployCwd);
}
assert.equal(fx.calls.find(nodeStep('test/cleanup.mjs')).timeoutMs, 10 * MINUTE);
});

test('a failed prepare deploys nothing, removes nothing and still runs cleanup', async () => {
const root = hookFixture();
const { result, fx } = await run(root, { fx: fakeExec({ 'node test/prepare.mjs': { status: 1 } }) });
assert.equal(result.failedStep, 'prepare');
assert.equal(result.detail, 'node test/prepare.mjs exited with code 1');
assert.deepEqual(fx.steps(), ['serverless --version', 'npm ci', 'node test/prepare.mjs', 'node test/cleanup.mjs']);
});

test('a failed install runs neither prepare nor cleanup', async () => {
const root = hookFixture();
const { result, fx } = await run(root, { fx: fakeExec({ 'npm ci': { status: 1 } }) });
assert.equal(result.failedStep, 'install');
assert.deepEqual(fx.steps(), ['serverless --version', 'npm ci']);
});

test('cleanup runs after a failed check and its error is added to the detail', async () => {
const root = hookFixture();
const { result, fx } = await run(root, {
fx: fakeExec({ 'node test/cleanup.mjs': { status: 2 } }),
ff: fakeFetch(response(500, 'Internal Server Error')),
});
assert.equal(result.failedStep, 'check');
assert.match(result.detail, /; cleanup: node test\/cleanup\.mjs exited with code 2$/);
assert.deepEqual(fx.steps().slice(-2), ['serverless remove', 'node test/cleanup.mjs']);
});

test('a failed cleanup after a pass fails the run at the cleanup step', async () => {
const root = hookFixture();
const { result } = await run(root, { fx: fakeExec({ 'node test/cleanup.mjs': { status: 1 } }) });
assert.equal(result.result, 'fail');
assert.equal(result.failedStep, 'cleanup');
assert.equal(result.detail, 'node test/cleanup.mjs exited with code 1');
});

test('prepare without cleanup runs only prepare', async () => {
const root = hookFixture({ prepare: { path: 'test/prepare.mjs' } });
const { result, fx } = await run(root);
assert.equal(result.result, 'pass');
assert.equal(fx.steps().filter((s) => s.startsWith('node ')).join(','), 'node test/prepare.mjs');
});

test('an interruption during prepare deploys nothing and still runs cleanup without the signal', async () => {
const root = hookFixture();
const controller = new AbortController();
const fx = fakeExec({
'node test/prepare.mjs': () => {
controller.abort();
return { status: 0 };
},
});
const { result } = await run(root, { fx, args: { signal: controller.signal } });
assert.equal(result.failedStep, 'prepare');
assert.ok(!fx.steps().includes('serverless deploy'));
const cleanupCall = fx.calls.find(nodeStep('test/cleanup.mjs'));
assert.ok(cleanupCall, fx.steps().join(','));
assert.equal(cleanupCall.signal, undefined);
});

test('CLI: --remove-only runs cleanup after remove, and also when nothing was deployed', async () => {
for (const [listing, steps] of [
[stackList([`hello-svc-${STAGE}`]), ['aws cloudformation', 'serverless remove', 'node test/cleanup.mjs']],
[stackList(), ['aws cloudformation', 'node test/cleanup.mjs']],
]) {
const root = hookFixture();
const fx = fakeExec({ 'aws cloudformation': listing });
const { code } = await cli([DIR, '--remove-only', '--stage', STAGE], root, { exec: fx.exec, env: { AWS_REGION: 'eu-west-1' } });
assert.equal(code, 0);
assert.deepEqual(fx.steps(), steps);
const call = fx.calls.at(-1);
assert.equal(call.env.EXAMPLE_STAGE, STAGE);
assert.equal(call.env.EXAMPLE_REGION, 'eu-west-1');
}
});

test('CLI: --remove-only exits 1 when cleanup does not complete', async () => {
const root = hookFixture();
const resultFile = path.join(root, 'r.json');
const fx = fakeExec({ 'aws cloudformation': stackList(), 'node test/cleanup.mjs': { status: 1 } });
const { code, out } = await cli([DIR, '--remove-only', '--stage', STAGE, '--result-file', resultFile], root, { exec: fx.exec });
assert.equal(code, 1);
assert.match(out[0], /^FAIL hello /);
const result = JSON.parse(fs.readFileSync(resultFile, 'utf8'));
assert.equal(result.failedStep, 'cleanup');
assert.equal(result.detail, 'node test/cleanup.mjs exited with code 1');
});
13 changes: 13 additions & 0 deletions tests/static-checks.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,19 @@ test('check-paths: reports a missing invoke event file', () => {
assertOneError(root, 'check-paths', /events\/hello\.json/);
});

test('check-paths: reports missing prepare and cleanup scripts', () => {
const root = fixture(({ file }) =>
editJson(file('example.json'), (m) => {
m.test.prepare = { path: 'test/prepare.mjs' };
m.test.cleanup = { path: 'test/cleanup.mjs' };
}),
);
const errors = checkExample(root, DIR).filter((e) => e.startsWith('check-paths'));
assert.equal(errors.length, 2, errors.join('\n'));
assert.match(errors[0], /test\.prepare: script test\/prepare\.mjs does not exist/);
assert.match(errors[1], /test\.cleanup: script test\/cleanup\.mjs does not exist/);
});

// --package

// Records each exec call; `statuses` maps a step ("npm ci", "serverless package") to its exit status.
Expand Down