diff --git a/.github/scripts/js_examples/README.md b/.github/scripts/js_examples/README.md index b18db96eb..12dfe618c 100644 --- a/.github/scripts/js_examples/README.md +++ b/.github/scripts/js_examples/README.md @@ -66,7 +66,7 @@ Each command below follows `hatch run dev-testing:js-examples`. | Skip the JS build for that checkout | `--js-dir ~/github/aws-durable-execution-sdk-js --no-build` | | Force a JS rebuild | `--rebuild` | | See runner debug logs | `--log-level DEBUG hello-world` | -| Pass options to jest | `invoke --jest-args='--verbose'` | +| Pass options to vitest | `invoke --jest-args='--reporter=verbose'` | | All options | `--help` | `--js-ref` works only with the cloned JS SDK, so it cannot be combined with @@ -92,13 +92,13 @@ an earlier run. It also refuses a directory that another run is still using. | `report.json` | Passed, failed, flaky and skipped test files | | `runner.log` | The Python local runner, which is the code under test | | `shim.log` | One line per handler invocation: request ID, function, duration, outcome | -| `jest.json`, `retry1.json` | Raw jest results, for the first run and the retry | +| `vitest.json`, `retry1.json` | Raw test results, for the first run and the retry. A run on an older JS ref writes `jest.json` instead. | | `maps/` | The function maps generated from the examples' `template.yml` | To investigate one example, run it alone with debug logs: ```sh -hatch run dev-testing:js-examples --log-level DEBUG --retries 0 --jest-args='--verbose' step/interrupted-no-retry +hatch run dev-testing:js-examples --log-level DEBUG --retries 0 --jest-args='--reporter=verbose' step/interrupted-no-retry ``` Add `--dump-dir /tmp/dump` to also save every history, state and checkpoint @@ -116,15 +116,15 @@ The Python local runner is the backend, in place of the Lambda service. Three helpers run around it, on the loopback, on free ports chosen for each run: ```text -jest ----> invoke_proxy.py ----> local runner ----> lambda-shim.cjs +vitest --> invoke_proxy.py ----> local runner ----> lambda-shim.cjs (test (starts executions) (the code under (runs the JS handlers, driver) test) like the Lambda runtime) ``` -1. **jest** runs the JS example tests unchanged, in the mode the JS repository - uses against real Lambda (`NODE_ENV=integration`). Each test is a client: - it starts an execution, then reads history and state, and some tests send - callbacks. `LAMBDA_ENDPOINT` points the tests' Lambda client at the proxy. +1. **vitest** runs the JS example tests unchanged, in the mode the JS + repository uses against real Lambda (`NODE_ENV=integration`). Each test is + a client: it starts an execution, then reads history and state, and some + tests send callbacks. `LAMBDA_ENDPOINT` points the tests' Lambda client at the proxy. 2. **invoke_proxy.py** exists because the tests start an execution with Lambda `Invoke`, and the local runner has no `Invoke` route. The proxy turns that call into the runner's `POST /start-durable-execution`, and returns the @@ -145,9 +145,9 @@ jest ----> invoke_proxy.py ----> local runner ----> lambda-shim.cjs `run.py` starts the runner with `WebRunner` from the testing package, in a child process, so each server session gets a runner with no state left from an earlier one. A run has one session, plus one per retry. The proxy runs on a -thread in `run.py`, and the shim and jest run as separate Node processes. +thread in `run.py`, and the shim and vitest run as separate Node processes. Before the run, `run.py` reads the examples' `template.yml` and writes three maps: test file to -function name (for jest), function name to bundle, timeout and environment +function name (for the tests), function name to bundle, timeout and environment (for the shim), and function name to `DurableConfig` (for the runner). The runner emulates region `us-west-2` and account `123456789012`. The proxy @@ -164,7 +164,7 @@ three groups: - Examples marked `localOnly` in the JS catalog. `template.yml` omits them, and the JS repository's integration run skips them too. The output reports how many were skipped. -- Tests without "cloud" in their name. The integration jest config runs only +- Tests without "cloud" in their name. The integration test config runs only those. A file with no such test is reported as "no cloud tests". ## Known failures @@ -187,6 +187,12 @@ hatch run dev-testing:js-examples --js-ref If it passes there, the new JS commit exposed something the runner does not handle yet. +The JS SDK replaced jest with vitest in aws/aws-durable-execution-sdk-js#1167. +So the harness picks the test runner from the JS checkout. When the examples +package has `jest.config.integration.js`, the harness runs jest. Otherwise it +runs vitest. So `--js-ref` works with a commit from before and after that +change. `--jest-args` go to the runner that the harness picks. + ## Harness tests `.github/scripts/tests/test_js_examples.py` tests the template parsing, test diff --git a/.github/scripts/js_examples/invoke_proxy.py b/.github/scripts/js_examples/invoke_proxy.py index be8d3033f..6e671ef26 100644 --- a/.github/scripts/js_examples/invoke_proxy.py +++ b/.github/scripts/js_examples/invoke_proxy.py @@ -4,7 +4,7 @@ Lambda Invoke on the function. It reads the execution ARN from the X-Amz-Durable-Execution-Arn response header. The local runner has no Invoke route. It starts executions with POST /start-durable-execution. So this -proxy sits between jest and the runner: +proxy sits between the JS tests and the runner: * POST /2015-03-31/functions/{name}/invocations: the proxy calls POST /start-durable-execution on the runner, then answers with the new diff --git a/.github/scripts/js_examples/run.py b/.github/scripts/js_examples/run.py index 421312e6f..6bd4837f6 100755 --- a/.github/scripts/js_examples/run.py +++ b/.github/scripts/js_examples/run.py @@ -6,7 +6,7 @@ they run against real Lambda. This script runs them against the Python testing package's web runner instead, with every process on the loopback: - jest (CloudDurableTestRunner) + vitest (CloudDurableTestRunner) -> invoke_proxy.py Lambda Invoke becomes POST /start-durable-execution; every other request is forwarded unchanged -> web runner the code under test, from this checkout @@ -284,7 +284,7 @@ def check_node() -> None: @dataclass(frozen=True) class FunctionMaps: - # Handler file basename -> FunctionName. jest reads it from FUNCTION_NAME_MAP. + # Handler file basename -> FunctionName. The tests read it from FUNCTION_NAME_MAP. name_map: dict[str, str] # FunctionName -> bundle, export, timeout, environment. The shim reads it. shim_map: dict[str, dict[str, Any]] @@ -349,8 +349,8 @@ def select_tests( """Return (tests to run, tests skipped as not deployed). Paths are relative to the examples package. A pattern is a regular - expression matched against the path, as jest matches its positional - patterns. With no patterns, every test outside EXCLUDED_DIRS is selected. + expression matched against the path. With no patterns, every test + outside EXCLUDED_DIRS is selected. template.yml omits examples marked localOnly in the JS catalog. The JS test helper skips the cloud tests of such an example, and the JS repo's @@ -632,7 +632,7 @@ def stop_group(proc: subprocess.Popen[bytes]) -> None: Sends SIGTERM to the process group, waits up to 5 seconds, then sends SIGKILL. The group is signalled even after the leader exits, because a - child such as a jest worker can outlive it. + child such as a test worker process can outlive it. """ with contextlib.suppress(ProcessLookupError): os.killpg(proc.pid, signal.SIGTERM) @@ -668,11 +668,77 @@ def harness_env() -> dict[str, str]: # --------------------------------------------------------------------------- -# jest +# Test runner: vitest, or jest for older JS refs # --------------------------------------------------------------------------- +# aws/aws-durable-execution-sdk-js#1167 replaced jest with vitest in the +# examples package. A JS ref from before that change has this jest config, +# and its examples run with jest. A ref from after it has no jest config, and +# its examples run with vitest. The harness builds any JS ref, so it supports +# both runners. +JEST_CONFIG = "jest.config.integration.js" -def run_jest( + +def detect_test_runner(examples: Path) -> str: + """Return "jest" when the examples package has the jest config, else "vitest".""" + return "jest" if (examples / JEST_CONFIG).is_file() else "vitest" + + +def runner_command( + runner: str, + tests: list[str], + results_file: Path, + workers: int, + extra: list[str], +) -> list[str]: + """Build the command that runs tests and writes jest-style JSON results. + + Both runners read NODE_ENV=integration from the environment. With it, + the examples' config selects only tests named "cloud", sets a 120 s test + timeout, and stops at the first failure. The command turns that last + setting off, because the harness wants every result. + """ + if runner == "jest": + return [ + "npx", + "--no-install", + "jest", + "--config", + JEST_CONFIG, + "--bail=0", + f"--maxWorkers={workers}", + "--json", + f"--outputFile={results_file}", + *extra, + "--runTestsByPath", + *tests, + ] + # vitest finds vitest.config.ts by itself. Its json reporter writes the + # same fields as jest --json, so outcomes() reads both. The default + # reporter keeps the progress output that jest printed. + # + # vitest has no --runTestsByPath. It treats each positional argument as a + # substring of the test file path. Every selected path starts with + # src/examples/, so a selected path matches only itself, unless another + # file's path contains it. summarize() reports every file in the results, + # so such a match would be visible in the report. + return [ + "npx", + "--no-install", + "vitest", + "run", + "--bail=0", + f"--maxWorkers={workers}", + "--reporter=default", + "--reporter=json", + f"--outputFile.json={results_file}", + *extra, + *tests, + ] + + +def run_test_runner( + runner: str, examples: Path, tests: list[str], servers: Servers, @@ -687,28 +753,17 @@ def run_jest( LAMBDA_ENDPOINT=servers.proxy_url, FUNCTION_NAME_MAP=(maps_dir / "function-name-map.json").read_text(), ) - # The AWS SDK client in CloudDurableTestRunner loads modules with a - # dynamic import(). jest's CommonJS runtime needs this flag for that. - node_options = env.get("NODE_OPTIONS", "") - if "--experimental-vm-modules" not in node_options: - env["NODE_OPTIONS"] = f"{node_options} --experimental-vm-modules".strip() - cmd = [ - "npx", - "--no-install", - "jest", - "--config", - "jest.config.integration.js", - # The config sets bail: true. The harness wants every result. - "--bail=0", - f"--maxWorkers={workers}", - "--json", - f"--outputFile={results_file}", - *extra, - "--runTestsByPath", - *tests, - ] - # jest runs in its own process group, like the servers. A Ctrl-C reaches - # this script, and the finally block stops jest and all its workers. + if runner == "jest": + # The AWS SDK client in CloudDurableTestRunner loads modules with a + # dynamic import(). jest's CommonJS runtime needs this flag for that. + # vitest supports dynamic import() without it. + node_options = env.get("NODE_OPTIONS", "") + if "--experimental-vm-modules" not in node_options: + env["NODE_OPTIONS"] = f"{node_options} --experimental-vm-modules".strip() + cmd = runner_command(runner, tests, results_file, workers, extra) + # The test runner runs in its own process group, like the servers. A + # Ctrl-C reaches this script, and the finally block stops the runner and + # all its workers. proc = subprocess.Popen(cmd, cwd=examples, env=env, start_new_session=True) try: status = proc.wait() @@ -716,11 +771,12 @@ def run_jest( stop_group(proc) if not results_file.exists(): raise HarnessError( - f"jest wrote no results to {results_file}; see its output above" + f"{runner} wrote no results to {results_file}; see its output above" ) results: dict[str, Any] = json.loads(results_file.read_text()) - # summarize() reads the verdict from the JSON, but jest can also exit - # non-zero for an error no suite reports, for example in global teardown. + # summarize() reads the verdict from the JSON, but the test runner can + # also exit non-zero for an error no suite reports, for example in global + # teardown. results[EXIT_STATUS_KEY] = status return results @@ -734,7 +790,7 @@ def run_jest( def unexplained_exits(results: list[dict[str, Any]]) -> list[int]: - """Non-zero jest exit statuses that no failed suite in that run explains.""" + """Non-zero test runner exit statuses that no failed suite in that run explains.""" statuses = [] for result in results: status = result.get(EXIT_STATUS_KEY, 0) @@ -776,7 +832,7 @@ def outcomes(results: list[dict[str, Any]], examples: Path) -> dict[str, str]: if suite["status"] == "failed" or "failed" in statuses: outcome[rel] = "failed" elif "passed" not in statuses: - # The file has no cloud tests: the integration jest config + # The file has no cloud tests: the integration test config # runs only tests whose name contains "cloud". The JS repo's # integration run skips these files the same way. outcome.setdefault(rel, "skipped") @@ -806,9 +862,10 @@ def summarize( The run fails when: 1. a test file fails, after retries, and is not in known-failures.txt, 2. a listed file passes, so the list is out of date, - 3. jest reported fewer files than were selected, + 3. the test runner reported fewer files than were selected, 4. no test passed or failed at all, or - 5. jest exited non-zero although every suite in its results passed. + 5. the test runner exited non-zero although every suite in its + results passed. Checks 3 and 4 catch a run that silently executed nothing. A file that failed and then passed on retry does not fail the run. It is reported as flaky. @@ -822,7 +879,7 @@ def summarize( unexpected = [t for t in failed if t not in known] stale = [t for t in passed if t in known] missing = sorted(set(selected) - set(outcome)) - jest_errors = unexplained_exits(results) + runner_errors = unexplained_exits(results) (out / "report.json").write_text( json.dumps( @@ -834,7 +891,9 @@ def summarize( "unexpected_failures": unexpected, "known_failures_now_passing": stale, "not_run": missing, - "jest_exit_errors": jest_errors, + # The key keeps its jest-era name, so readers of + # report.json need no change. + "jest_exit_errors": runner_errors, }, indent=2, ) @@ -856,9 +915,10 @@ def summarize( log(f"PASS {t} is listed in known-failures.txt; remove it from the list") for t in missing: log(f"NOT RUN {t}") - for status in jest_errors: + for status in runner_errors: log( - f"jest exited with status {status} although every suite passed; see its output above" + f"the test runner exited with status {status} although every suite passed;" + " see its output above" ) log(f"logs and report.json: {out}") # A run in which no test passed or failed ran nothing, which must not @@ -866,7 +926,7 @@ def summarize( if not passed and not failed: log("no test ran; treating the run as failed") return 1 - return 1 if (unexpected or stale or missing or jest_errors) else 0 + return 1 if (unexpected or stale or missing or runner_errors) else 0 # --------------------------------------------------------------------------- @@ -915,7 +975,7 @@ def parse_args(argv: list[str]) -> argparse.Namespace: "--shard", type=parse_shard, metavar="I/N", help="run only shard I of N" ) parser.add_argument( - "--workers", type=int, default=4, help="jest --maxWorkers (default 4)" + "--workers", type=int, default=4, help="test runner --maxWorkers (default 4)" ) parser.add_argument( "--retries", @@ -947,7 +1007,8 @@ def parse_args(argv: list[str]) -> argparse.Namespace: type=shlex.split, default=[], metavar="ARGS", - help="extra jest arguments, as one quoted string, e.g. --jest-args='--verbose'", + help="extra test runner arguments, as one quoted string: vitest, or" + " jest for an older JS ref, e.g. --jest-args='--reporter=verbose'", ) args = parser.parse_args(argv) if args.js_dir and args.js_ref: @@ -1163,12 +1224,13 @@ def run_tests(args: argparse.Namespace, examples: Path, out: Path) -> int: if not tests: raise HarnessError("no test files match the selection") check_bundles_exist(tests, maps, examples / "dist") + runner = detect_test_runner(examples) log( - f"{len(tests)} test files, {args.workers} jest workers" + f"{len(tests)} test files, {args.workers} {runner} workers" + (", --skip-time" if args.skip_time else "") ) - results = [run_session(args, examples, maps_dir, out, tests, "jest")] + results = [run_session(args, runner, examples, maps_dir, out, tests, runner)] failed = failed_tests(results, examples) retried: list[str] = [] if failed and args.retries > 0: @@ -1180,7 +1242,9 @@ def run_tests(args: argparse.Namespace, examples: Path, out: Path) -> int: log(f"retrying {len(failed)} failed test file(s), attempt {attempt}") retried = sorted(set(retried) | set(failed)) results.append( - run_session(args, examples, maps_dir, out, failed, f"retry{attempt}") + run_session( + args, runner, examples, maps_dir, out, failed, f"retry{attempt}" + ) ) failed = failed_tests(results, examples) if not failed: @@ -1190,19 +1254,21 @@ def run_tests(args: argparse.Namespace, examples: Path, out: Path) -> int: def run_session( args: argparse.Namespace, + runner: str, examples: Path, maps_dir: Path, out: Path, tests: list[str], label: str, ) -> dict[str, Any]: - """Start fresh servers, run tests with jest, and stop the servers.""" + """Start fresh servers, run tests with the test runner, and stop the servers.""" servers = Servers( out, maps_dir, examples, args.skip_time, args.log_level, args.dump_dir ) try: servers.start() - return run_jest( + return run_test_runner( + runner, examples, tests, servers, @@ -1217,7 +1283,7 @@ def run_session( if __name__ == "__main__": # SIGTERM (for example a cancelled CI job) raises SystemExit, so the - # finally blocks stop the servers and jest. + # finally blocks stop the servers and the test runner. signal.signal(signal.SIGTERM, lambda *_: sys.exit(143)) # A shell starts background jobs with SIGINT ignored. Restore the default # so Ctrl-C and kill -INT always stop the run. diff --git a/.github/scripts/tests/test_js_examples.py b/.github/scripts/tests/test_js_examples.py index 1d29d8aa6..3ff04db39 100644 --- a/.github/scripts/tests/test_js_examples.py +++ b/.github/scripts/tests/test_js_examples.py @@ -352,6 +352,138 @@ def test_jest_args_are_split(monkeypatch: pytest.MonkeyPatch) -> None: assert args.jest_args == ["--verbose", "--testTimeout=5000"] +@pytest.mark.parametrize(("runner", "has_flag"), [("jest", True), ("vitest", False)]) +def test_only_jest_gets_the_vm_modules_flag( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, runner: str, has_flag: bool +) -> None: + monkeypatch.setenv("NODE_OPTIONS", "--max-old-space-size=4096") + (tmp_path / "function-name-map.json").write_text("{}") + results_file = tmp_path / "results.json" + seen: dict[str, Any] = {} + + class FakeProc: + pid = 0 + + def wait(self) -> int: + return 0 + + def fake_popen(cmd: list[str], **kwargs: Any) -> FakeProc: + seen["env"] = kwargs["env"] + results_file.write_text("{}") + return FakeProc() + + monkeypatch.setattr(run.subprocess, "Popen", fake_popen) + monkeypatch.setattr(run, "stop_group", lambda proc: None) + servers = type("FakeServers", (), {"proxy_url": "http://127.0.0.1:1"})() + + run.run_test_runner(runner, tmp_path, [], servers, tmp_path, results_file, 1, []) + + node_options = seen["env"]["NODE_OPTIONS"] + assert node_options.startswith("--max-old-space-size=4096") + assert ("--experimental-vm-modules" in node_options) is has_flag + + +def test_runner_is_jest_only_with_the_jest_config(examples: Path) -> None: + assert run.detect_test_runner(examples) == "vitest" + (examples / "jest.config.integration.js").write_text("") + assert run.detect_test_runner(examples) == "jest" + + +def test_vitest_command(tmp_path: Path) -> None: + results = tmp_path / "vitest.json" + + cmd = run.runner_command("vitest", [A, B], results, 6, ["--reporter=verbose"]) + + assert cmd == [ + "npx", + "--no-install", + "vitest", + "run", + # The integration config stops at the first failure. + "--bail=0", + "--maxWorkers=6", + "--reporter=default", + "--reporter=json", + f"--outputFile.json={results}", + "--reporter=verbose", + A, + B, + ] + + +def test_jest_command(tmp_path: Path) -> None: + results = tmp_path / "jest.json" + + cmd = run.runner_command("jest", [A], results, 4, ["--verbose"]) + + assert cmd == [ + "npx", + "--no-install", + "jest", + "--config", + "jest.config.integration.js", + "--bail=0", + "--maxWorkers=4", + "--json", + f"--outputFile={results}", + "--verbose", + "--runTestsByPath", + A, + ] + + +def vitest_result(examples: Path) -> dict[str, object]: + """A vitest json reporter result, with the fields vitest 5 writes.""" + return { + "numTotalTestSuites": 4, + "success": False, + "testResults": [ + { + "assertionResults": [ + {"fullName": "a cloud", "status": "passed", "title": "cloud"}, + {"fullName": "a local", "status": "skipped", "title": "local"}, + ], + "status": "passed", + "message": "", + "name": str(examples / A), + }, + { + "assertionResults": [ + {"fullName": "b cloud", "status": "failed", "title": "cloud"} + ], + "status": "failed", + "message": "", + "name": str(examples / B), + }, + { + # A file with no cloud test: testNamePattern skips every test. + "assertionResults": [ + {"fullName": "c local", "status": "skipped", "title": "local"} + ], + "status": "passed", + "message": "", + "name": str(examples / C), + }, + { + # A file that fails to load reports no tests. + "assertionResults": [], + "status": "failed", + "message": "Cannot find module", + "name": str(examples / "src/examples/d.test.ts"), + }, + ], + } + + +def test_outcomes_read_vitest_results(examples: Path) -> None: + assert run.outcomes([vitest_result(examples)], examples) == { + A: "passed", + B: "failed", + C: "skipped", + "src/examples/d.test.ts": "failed", + } + + class FakeRunner(BaseHTTPRequestHandler): """Answers like the local runner: 201 on start, 200 elsewhere."""