Files
mesh-catalog/modules/mesh-build-node/cmd/mesh-build-node/check_test.go
T
jschoubben 5326fb6142 Node build module: a test level's bounds follow the steps in hand (H-A-488)
The Node build module judged its levels by the same fixed bounds, and its
integration setup took 40 s against 30 s while three nodes' checks ran.
The rule is the kind's, not the Go module's: its bounds, and the
MESH_TEST_LEVEL_BOUND its scripts get, are now their defaults times the
steps the seat has in hand at the step's start (at least 1), and the
result names them (bound, setup_bound).

Builds: design 47 H2 H-A-488, H-A-488 addendum
2026-11-22 19:43:42 +01:00

301 lines
15 KiB
Go

package main
import (
"context"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
"git.novox.be/novox/mesh-sdk/go/forgekey"
)
// tscTypeError is what tsc 5.9.3 printed for `export const n: number = "text";` in tools/bad.ts, run on this machine
// on 2026-10-20 with the flags of the type-check below (status 2).
const tscTypeError = "tools/bad.ts(1,14): error TS2322: Type 'string' is not assignable to type 'number'.\n"
func testArgs(level string) map[string]any {
return map[string]any{"workspace": "w1", "module": ".", "level": level}
}
// 1491/AC1: a package with a type error fails the unit level, naming the file.
func TestATypeErrorFailsTheUnitLevelNamingTheFile(t *testing.T) {
m, f, work := newMachine(t)
workspaceWith(t, work, map[string]string{"tools/bad.ts": `export const n: number = "text";`, "package.json": `{"name":"x"}`})
f.answer["tsc"] = forgekey.Ran{Status: 2, Stdout: tscTypeError}
out, err := m.test(context.Background(), testArgs("unit"))
if err != nil {
t.Fatalf("a type error ended the step %v, want it finished with the verdict in its result", err)
}
r := out.(*TestResult)
if r.Passed || len(r.Failed) != 1 || !strings.Contains(r.Why, "tools/bad.ts") || !strings.Contains(r.Failed[0].Output, "TS2322") {
t.Fatalf("result = %+v, want passed false, naming tools/bad.ts", r)
}
if c := f.calls[0]; !strings.Contains(joined(c), "--noEmit") || !strings.Contains(joined(c), "typescript/bin/tsc") ||
!strings.Contains(joined(c), "--moduleResolution NodeNext --target ES2022") || !strings.HasSuffix(joined(c), "tools/bad.ts") {
t.Errorf("the type-check ran %s", joined(c))
}
}
// 1491/AC2: a package with a passing test script passes the unit level, which reports its time; over its bound it
// says so and still passes.
func TestAPassingTestScriptPassesTheUnitLevelAndReportsItsTime(t *testing.T) {
m, f, work := newMachine(t)
workspaceWith(t, work, map[string]string{"index.ts": `export const a = 1;`, "package.json": `{"scripts":{"test":"node --test"}}`})
f.cost["tsc"], f.cost["npm"] = 400*time.Millisecond, 600*time.Millisecond
out, err := m.test(context.Background(), testArgs("unit"))
if err != nil {
t.Fatal(err)
}
r := out.(*TestResult)
if !r.Passed || r.NoTests || r.Elapsed != 1 || r.OverBound || r.Bound != 5 || strings.Join(r.Ran, ",") != "type-check,test" {
t.Errorf("result = %+v, want the type-check and the test script in 1 s within the bound", r)
}
last := f.calls[len(f.calls)-1]
if last.name != "npm" || strings.Join(last.args, " ") != "test" {
t.Errorf("ran %s, want npm test", joined(last))
}
f.cost["npm"] = 6 * time.Second
out, err = m.test(context.Background(), testArgs("unit"))
if r := out.(*TestResult); err != nil || !r.OverBound {
t.Errorf("a slow unit level = %+v, %v, want passed and over_bound", r, err)
}
}
// 1491/AC3: a package with neither script nor .ts files has no tests, and nothing runs.
func TestAPackageWithNeitherScriptNorTypeScriptHasNoTests(t *testing.T) {
m, f, work := newMachine(t)
workspaceWith(t, work, map[string]string{"package.json": `{"name":"x"}`, "node_modules/p/x.ts": "ignored", "types.d.ts": "declare const a: 1;"})
for _, level := range []string{"unit", "integration"} {
out, err := m.test(context.Background(), testArgs(level))
r := out.(*TestResult)
if err != nil || !r.Passed || !r.NoTests || !strings.Contains(r.Why, "no tests") {
t.Errorf("%s = %+v, %v, want the result to say no tests", level, r, err)
}
}
if len(f.calls) != 0 {
t.Errorf("%d commands ran for a package with no tests", len(f.calls))
}
// CAT-BN2: a contracts module (a package artifact naming generated-from) with no tests of its own still fails its
// unit level on a generated TypeScript file out of step with the seat generator, each named; its Go files are
// mesh-build-go's to compare.
m, _, work = newMachine(t)
workspaceWith(t, work, map[string]string{
"module.json": `{"module":"c","build":{"artifacts":[{"name":"ts","kind":"package","language":"typescript","paths":["ts"],"generated-from":"."}]}}`,
"seats/one-store/seat.json": `{"format":1,"seat":"one-store","scope":"mesh","grain":"seat-list","domain":"Module","decision":"ADR 1","verbs":[{"name":"query","input":{"type":"object"}}]}`,
"go/go.mod": "module example.org/c/go\n", "go/stray.go": "package stray\n",
"ts/package.json": `{"name":"@example/c"}`, "ts/stray.ts.txt": "not written by the generator\n",
})
out, err := m.test(context.Background(), testArgs("unit"))
r := out.(*TestResult)
stray := false
for _, p := range r.OutOfStep {
stray = stray || p == "ts/stray.ts.txt"
if !strings.HasPrefix(p, "ts/") {
t.Errorf("%s is not under the TypeScript root", p)
}
}
if err != nil || r.Passed || r.NoTests || !stray || !strings.Contains(r.Why, "ts/stray.ts.txt") {
t.Errorf("a contracts module out of step = %+v, %v", r, err)
}
}
// 1491/AC4: with test:integration present the integration level runs it, and reports the setup (the type-check) and
// the running time apart.
func TestTheIntegrationLevelRunsItsScriptAndReportsSetupAndRunningApart(t *testing.T) {
m, f, work := newMachine(t)
workspaceWith(t, work, map[string]string{"index.ts": `export const a = 1;`, "tsconfig.json": `{}`,
"package.json": `{"scripts":{"test":"x","test:integration":"node --test int"}}`})
f.cost["tsc"], f.cost["npm"] = 2*time.Second, 40*time.Second
f.answer["npm"] = forgekey.Ran{Stdout: "ok 1 - joins\n", Stderr: "(node) warning\n"}
out, err := m.test(context.Background(), testArgs("integration"))
if err != nil {
t.Fatal(err)
}
r := out.(*TestResult)
if r.Setup != 2 || r.Elapsed != 40 || r.SetupBound != 30 || r.Bound != 60 || !r.Passed || r.OverBound || r.Level != "integration" {
t.Errorf("result = %+v, want setup 2 s and running 40 s apart", r)
}
last := f.calls[len(f.calls)-1]
if strings.Join(last.args, " ") != "run test:integration" {
t.Errorf("ran %s, want npm run test:integration", joined(last))
}
// Design 47 H2 §800: the level's tests get its bound in the environment, the setup bound being half of it.
if !slices.Contains(last.env, "MESH_TEST_LEVEL_BOUND=1m0s") {
t.Errorf("the integration script ran with %v, not the level's bound MESH_TEST_LEVEL_BOUND=1m0s", last.env)
}
// Design 47 H2 §791, H-A-412 (a): the level's answer carries its text in output, what its commands wrote.
if !strings.HasSuffix(r.Output, "ok 1 - joins\n(node) warning\n") {
t.Errorf("the level's output is %q, want the script's stdout then its stderr", r.Output)
}
if tsc := f.calls[0]; strings.Join(tsc.args[1:], " ") != "--noEmit -p ." {
t.Errorf("a package with a tsconfig was checked with %s", joined(tsc))
}
f.cost["npm"] = 61 * time.Second
out, _ = m.test(context.Background(), testArgs("integration"))
if !out.(*TestResult).OverBound {
t.Errorf("61 s of running is within the bound")
}
// Design 47 H2 H-A-488: with four steps in hand at the step's start, the bounds are four times their defaults: the
// script gets 240 s as its level's bound, 40 s of setup is within its 120 s, and the result names both.
f.cost["tsc"], f.cost["npm"] = 40*time.Second, 61*time.Second
m.inHand = func() int { return 4 }
out, _ = m.test(context.Background(), testArgs("integration"))
if r := out.(*TestResult); r.OverBound || r.Bound != 240 || r.SetupBound != 120 {
t.Errorf("40 s of setup and 61 s of running with four steps in hand: %+v", r)
}
if last := f.calls[len(f.calls)-1]; !slices.Contains(last.env, "MESH_TEST_LEVEL_BOUND=4m0s") {
t.Errorf("with four steps in hand the integration script ran with %v, not MESH_TEST_LEVEL_BOUND=4m0s", last.env)
}
}
// The commands of a step get an environment built from scratch: no word of this process's, the level's bound alone (§800).
func TestTheStepsCommandsGetAnEnvironmentOfTheirOwn(t *testing.T) {
t.Setenv("MESH_SECRET_TOKEN", "hunter2")
m, f, work := newMachine(t)
workspaceWith(t, work, map[string]string{"index.ts": `export const a = 1;`, "package.json": `{"scripts":{"test":"x"}}`})
if _, err := m.test(context.Background(), testArgs("unit")); err != nil {
t.Fatal(err)
}
for _, c := range f.calls {
for _, e := range c.env {
if strings.Contains(e, "hunter2") || (strings.HasPrefix(e, "MESH_") && !strings.HasPrefix(e, LevelBoundEnv+"=")) {
t.Errorf("%s was given %s", joined(c), e)
}
}
// 1309: the HOME of a run step is its own, inside its /tmp, never the account's.
if len(c.env) < 3 || !strings.HasPrefix(c.env[0], "PATH=") || !slices.Contains(c.env, "HOME=/tmp/home") || !slices.Contains(c.env, "LC_ALL=C") {
t.Errorf("%s env = %v, want PATH, the step's own HOME and the locale", c.name, c.env)
}
}
}
// 1491: the step finishes with the verdict when the tests fail, and fails only when they could not be run: a failing
// test script is a verdict, a program that cannot start is not.
func TestAFailingScriptIsAVerdictAndACommandThatCannotStartIsAFailedStep(t *testing.T) {
m, f, work := newMachine(t)
workspaceWith(t, work, map[string]string{"package.json": `{"scripts":{"test":"x"}}`})
f.answer["npm"] = forgekey.Ran{Status: 1, Stdout: "not ok 1 - adds\n"}
out, err := m.test(context.Background(), testArgs("unit"))
r, _ := out.(*TestResult)
if err != nil || r == nil || r.Passed || len(r.Failed) != 1 || r.Failed[0].Test != "test" || !strings.Contains(r.Failed[0].Output, "not ok 1") {
t.Errorf("a failing script = %+v, %v, want passed false and its output", r, err)
}
f.answer["npm"] = forgekey.Ran{Status: 127, Err: "ENOENT"}
if out, err := m.test(context.Background(), testArgs("unit")); err == nil {
t.Errorf("npm not installed = %v, want the step to fail", out)
}
if _, err := m.test(context.Background(), map[string]any{"workspace": "nope", "level": "unit"}); err == nil {
t.Errorf("a workspace never fetched did not fail the step")
}
}
func TestAWorkspaceOutsideTheWorkDirectoryIsRefused(t *testing.T) {
m, _, _ := newMachine(t)
for _, a := range []map[string]any{
{"workspace": "../etc", "level": "unit"},
{"workspace": "w1", "module": "../x", "level": "unit"},
{"workspace": "w1", "module": "/etc", "level": "unit"},
{"workspace": "w1", "level": "smoke"},
} {
if _, err := m.test(context.Background(), a); err == nil {
t.Errorf("%v was accepted", a)
}
}
}
// 1491 (review 6): --no-bin-links leaves the toolchain no bin directory, so `npm run build` found no tsc or esbuild
// and exited 127, which read as a failed test. The workspace now has a bin directory of small shell scripts (files,
// not links) that call the toolchain's tsc and esbuild, first on the PATH of the test script.
func TestTheTestScriptFindsTscAndEsbuildOnItsPath(t *testing.T) {
m, f, work := newMachine(t)
workspaceWith(t, work, map[string]string{"package.json": `{"scripts":{"test":"tsc && esbuild"}}`})
if _, err := m.test(context.Background(), testArgs("unit")); err != nil {
t.Fatal(err)
}
bin := filepath.Join(work, "w1", "bin")
nm := filepath.Join(m.toolchainDir(), "node_modules")
for name, want := range map[string]string{
"tsc": "exec node '" + nm + "/typescript/bin/tsc' \"$@\"",
"esbuild": "exec '" + nm + "/esbuild/bin/esbuild' \"$@\"",
} {
info, err := os.Lstat(filepath.Join(bin, name))
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 {
t.Fatalf("bin/%s: %v %v, want an executable file", name, info, err)
}
raw, _ := os.ReadFile(filepath.Join(bin, name))
if !strings.HasPrefix(string(raw), "#!/bin/sh\n") || !strings.Contains(string(raw), want) {
t.Errorf("bin/%s = %q, want a script calling the toolchain's program", name, raw)
}
}
npm := f.calls[len(f.calls)-1]
path := ""
for _, e := range npm.env {
if strings.HasPrefix(e, "PATH=") {
path = strings.TrimPrefix(e, "PATH=") // the last PATH wins
}
}
if npm.name != "npm" || !strings.HasPrefix(path, bin+":") {
t.Errorf("npm ran with PATH %q, want %s first", path, bin)
}
// 1901/AC7: the test script runs under node's TAP reporter, written to a file of the workspace the step reads
if !slices.Contains(npm.env, "NODE_OPTIONS="+steprun.NodeTestOptions(filepath.Join(work, "w1", ".mesh-node-test-unit.tap"))) {
t.Errorf("npm ran with %v, want NODE_OPTIONS naming the TAP reporter and its file", npm.env)
}
}
// Design 47 G §328 (*Lint per language*: TypeScript's lint is the type-check) and §24: the pipeline step lint of a TypeScript
// artifact runs tsc without emitting over the module's directory; a type error fails it naming the file, a clean package passes,
// a tree with no .ts file has nothing to lint, and a tsc that cannot start is an error, not a verdict.
func TestTheLintStepIsTheTypeCheck(t *testing.T) {
for _, c := range []struct {
name string
files map[string]string
ran forgekey.Ran
failed int
nothing bool
err bool
}{
{"a type error", map[string]string{"tools/bad.ts": `export const n: number = "text";`}, forgekey.Ran{Status: 2, Stdout: tscTypeError}, 1, false, false},
{"a clean package", map[string]string{"index.ts": `export const a = 1;`}, forgekey.Ran{}, 0, false, false},
{"no TypeScript", map[string]string{"package.json": `{"name":"x"}`}, forgekey.Ran{}, 0, true, false},
{"tsc cannot start", map[string]string{"index.ts": `export const a = 1;`}, forgekey.Ran{Status: 127, Err: "no such file"}, 0, false, true},
} {
t.Run(c.name, func(t *testing.T) {
m, f, work := newMachine(t)
workspaceWith(t, work, c.files)
f.answer["tsc"] = c.ran
out, err := m.lintStep(context.Background(), map[string]any{"workspace": "w1", "dir": "."})
if (err != nil) != c.err {
t.Fatalf("error = %v, want error %v", err, c.err)
}
if err != nil {
return
}
la := out.(steprun.LintAnswer)
if len(la.Failed) != c.failed || la.Nothing != c.nothing {
t.Fatalf("answer = %+v, want %d failed, nothing %v", la, c.failed, c.nothing)
}
if c.failed > 0 && !strings.Contains(la.Failed[0].Cause+la.Failed[0].Output, "tools/bad.ts") {
t.Errorf("the failure %+v does not name tools/bad.ts", la.Failed[0])
}
if !c.nothing && !strings.Contains(joined(f.calls[0]), "--noEmit") {
t.Errorf("the lint ran %s, want tsc --noEmit", joined(f.calls[0]))
}
})
}
}
// Design 47 G §24: the Node build module's steps carry what a step ask needs (its node, the lint body, the end's publisher and
// its own need), so the ask the first live pipeline sent is no longer refused as "says no step's end".
func TestTheNodeStepsCarryWhatAStepAskNeeds(t *testing.T) {
s := (&Module{Node: "shanks"}).askSteps(nil)
if s.Lint == nil || s.Node != "shanks" || s.SayStep == nil || s.Has == nil || !s.Has(sdkstep.NeedNodeBuildNode) || s.Has("other") {
t.Errorf("steps = %+v, want Lint, Node, SayStep and Has set", s)
}
}