From 6b3139218d9e0998f105dd0361fd1f5fa6ed6383 Mon Sep 17 00:00:00 2001 From: jochen Date: Sat, 21 Nov 2026 23:07:16 +0100 Subject: [PATCH 01/23] E6: mark each derived accept rule's scope in its one comment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The holder of node-packet-filter reads a port's scope from rules, not from the rule's shape; the older firewall's mesh-host mark stays. Builds: design 47 H2 §813 (4); H-A-357 --- internal/compose/resolution/filtering.go | 53 ++++++++++++------- .../compose/resolution/localnetwork_test.go | 10 +++- 2 files changed, 44 insertions(+), 19 deletions(-) diff --git a/internal/compose/resolution/filtering.go b/internal/compose/resolution/filtering.go index 7d244245..e3bdab86 100644 --- a/internal/compose/resolution/filtering.go +++ b/internal/compose/resolution/filtering.go @@ -145,6 +145,23 @@ func Exposure(m mcat.Manifest, layers []mcat.Layer) (map[int]string, error) { return out, nil } +// scopeWords are the words a derived accept rule's comment names its source by (design 47 H2 §813 (4), H-A-357): the +// holder of node-packet-filter reads a port's scope from them, never from the rule's shape. A machine-only rule renders +// no rule, so it has none. +var scopeWords = map[string]string{ + mcat.FromEverywhere: "any", + mcat.FromMesh: "private-network", + mcat.FromLocalNetwork: "local-network", +} + +// derivedComment is the one comment of a derived accept rule, `derived / scope +// `, with the space before it (design 47 H2 §813 (4), H-A-357). It carries no mark: +// the table is loaded whole, never reconciled rule by rule. +func derivedComment(rule mcat.Rule) string { + return fmt.Sprintf(" comment %q", fmt.Sprintf("derived %s %s/%d scope %s", + strings.Join(rule.Because, ","), rule.Protocol, rule.Port, scopeWords[rule.From])) +} + // widest drops a rule that another already covers. // // A port open to anywhere is not additionally restricted by a second rule opening it to the mesh: @@ -374,12 +391,12 @@ func AsNftablesAllowing(rules []mcat.Rule, mesh []string, outward bool, foundati } four, six := byFamily(mesh) if len(four) > 0 { - b.WriteString(fmt.Sprintf("\t\tip saddr { %s } %s dport %d accept\n", - strings.Join(four, ", "), rule.Protocol, rule.Port)) + b.WriteString(fmt.Sprintf("\t\tip saddr { %s } %s dport %d accept%s\n", + strings.Join(four, ", "), rule.Protocol, rule.Port, derivedComment(rule))) } if len(six) > 0 { - b.WriteString(fmt.Sprintf("\t\tip6 saddr { %s } %s dport %d accept\n", - strings.Join(six, ", "), rule.Protocol, rule.Port)) + b.WriteString(fmt.Sprintf("\t\tip6 saddr { %s } %s dport %d accept%s\n", + strings.Join(six, ", "), rule.Protocol, rule.Port, derivedComment(rule))) } case mcat.FromLocalNetwork: // The private network and the machine's own local networks, on this port alone (novox/hq @@ -399,15 +416,15 @@ func AsNftablesAllowing(rules []mcat.Rule, mesh []string, outward bool, foundati break } if len(four) > 0 { - b.WriteString(fmt.Sprintf("\t\tip saddr { %s } %s dport %d accept\n", - strings.Join(four, ", "), rule.Protocol, rule.Port)) + b.WriteString(fmt.Sprintf("\t\tip saddr { %s } %s dport %d accept%s\n", + strings.Join(four, ", "), rule.Protocol, rule.Port, derivedComment(rule))) } if len(six) > 0 { - b.WriteString(fmt.Sprintf("\t\tip6 saddr { %s } %s dport %d accept\n", - strings.Join(six, ", "), rule.Protocol, rule.Port)) + b.WriteString(fmt.Sprintf("\t\tip6 saddr { %s } %s dport %d accept%s\n", + strings.Join(six, ", "), rule.Protocol, rule.Port, derivedComment(rule))) } case mcat.FromEverywhere: - b.WriteString(fmt.Sprintf("\t\t%s dport %d accept\n", rule.Protocol, rule.Port)) + b.WriteString(fmt.Sprintf("\t\t%s dport %d accept%s\n", rule.Protocol, rule.Port, derivedComment(rule))) } } @@ -521,27 +538,27 @@ func AsNftablesAllowing(rules []mcat.Rule, mesh []string, outward bool, foundati case mcat.FromMesh: four, six := byFamily(mesh) if len(four) > 0 { - b.WriteString(fmt.Sprintf("\t\tip saddr { %s } ct original proto-dst %d accept\n", - strings.Join(four, ", "), rule.Port)) + b.WriteString(fmt.Sprintf("\t\tip saddr { %s } ct original proto-dst %d accept%s\n", + strings.Join(four, ", "), rule.Port, derivedComment(rule))) } if len(six) > 0 { - b.WriteString(fmt.Sprintf("\t\tip6 saddr { %s } ct original proto-dst %d accept\n", - strings.Join(six, ", "), rule.Port)) + b.WriteString(fmt.Sprintf("\t\tip6 saddr { %s } ct original proto-dst %d accept%s\n", + strings.Join(six, ", "), rule.Port, derivedComment(rule))) } case mcat.FromLocalNetwork: four, six := byFamily(mesh) lfour, lsix := byFamily(local) four, six = append(four, lfour...), append(six, lsix...) if len(four) > 0 { - b.WriteString(fmt.Sprintf("\t\tip saddr { %s } ct original proto-dst %d accept\n", - strings.Join(four, ", "), rule.Port)) + b.WriteString(fmt.Sprintf("\t\tip saddr { %s } ct original proto-dst %d accept%s\n", + strings.Join(four, ", "), rule.Port, derivedComment(rule))) } if len(six) > 0 { - b.WriteString(fmt.Sprintf("\t\tip6 saddr { %s } ct original proto-dst %d accept\n", - strings.Join(six, ", "), rule.Port)) + b.WriteString(fmt.Sprintf("\t\tip6 saddr { %s } ct original proto-dst %d accept%s\n", + strings.Join(six, ", "), rule.Port, derivedComment(rule))) } case mcat.FromEverywhere: - b.WriteString(fmt.Sprintf("\t\tct original proto-dst %d accept\n", rule.Port)) + b.WriteString(fmt.Sprintf("\t\tct original proto-dst %d accept%s\n", rule.Port, derivedComment(rule))) } } diff --git a/internal/compose/resolution/localnetwork_test.go b/internal/compose/resolution/localnetwork_test.go index fb604172..caaa61db 100644 --- a/internal/compose/resolution/localnetwork_test.go +++ b/internal/compose/resolution/localnetwork_test.go @@ -69,6 +69,7 @@ func TestALocalNetworkPortIsAdmittedFromItsNetworksAndTheMesh(t *testing.T) { rules := []mcat.Rule{ {Port: 1883, Protocol: "tcp", From: mcat.FromLocalNetwork, Because: []string{"mosquitto"}}, {Port: 5432, Protocol: "tcp", From: mcat.FromMesh, Because: []string{"postgres"}}, + {Port: 443, Protocol: "tcp", From: mcat.FromEverywhere, Because: []string{"caddy", "forge"}}, } local := CountedLocalNetworks(judged(t)) out := AsNftablesWithLocal(rules, []string{"10.10.0.1", "10.10.0.4"}, false, nil, @@ -80,6 +81,13 @@ func TestALocalNetworkPortIsAdmittedFromItsNetworksAndTheMesh(t *testing.T) { "ip saddr { 10.10.0.1, 10.10.0.4, 192.168.1.0/24 } ct original proto-dst 1883 accept", // The mesh-only port is not widened by the machine having a local network. "ip saddr { 10.10.0.1, 10.10.0.4 } tcp dport 5432 accept", + // Each derived accept rule names its modules, its listen and its scope in one comment (design 47 H2 §813 (4), + // H-A-357), in both chains. + `tcp dport 1883 accept comment "derived mosquitto tcp/1883 scope local-network"`, + `ct original proto-dst 1883 accept comment "derived mosquitto tcp/1883 scope local-network"`, + `tcp dport 5432 accept comment "derived postgres tcp/5432 scope private-network"`, + "\t\ttcp dport 443 accept comment \"derived caddy,forge tcp/443 scope any\"\n", + "\t\tct original proto-dst 443 accept comment \"derived caddy,forge tcp/443 scope any\"\n", } { if !strings.Contains(out, want) { t.Errorf("the rule set lacks %q:\n%s", want, out) @@ -92,7 +100,7 @@ func TestALocalNetworkPortIsAdmittedFromItsNetworksAndTheMesh(t *testing.T) { t.Errorf("1883 is open to anywhere:\n%s", out) } for _, line := range strings.Split(out, "\n") { - if strings.TrimSpace(line) == "tcp dport 1883 accept" { + if strings.HasPrefix(strings.TrimSpace(line), "tcp dport 1883 accept") { t.Fatalf("1883 is open to anywhere:\n%s", out) } } -- 2.54.0 From 019ced4449804571fd3af025dd76e67595bad992 Mon Sep 17 00:00:00 2001 From: jochen Date: Sat, 21 Nov 2026 23:10:59 +0100 Subject: [PATCH 02/23] E5: answer the node-engine seat's composition-diff MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The node-engine serves seat verbs and no tools bundle, so composed values read by resource are a read verb beside composition: per resource, the entries that differ between what runs and a revision or digest of its composition key, environment entries by name, a secret's value masked. Builds: design 47 H2 §813 (3); H-A-349 DQ-12b --- cmd/mesh-host/engineseat.go | 14 +++ cmd/mesh-host/main.go | 1 + internal/agent/agent_test.go | 23 +++++ internal/agent/composition.go | 162 ++++++++++++++++++++++++++++++++++ internal/link/handacts.go | 20 +++++ 5 files changed, 220 insertions(+) diff --git a/cmd/mesh-host/engineseat.go b/cmd/mesh-host/engineseat.go index 81914329..b806028b 100644 --- a/cmd/mesh-host/engineseat.go +++ b/cmd/mesh-host/engineseat.go @@ -319,6 +319,20 @@ func compositionFrom(current *agentNow, withheld func(ctx context.Context, modul } } +// compositionDiffFrom answers the verb composition-diff from the node agent that runs now (design 47 H2 §813 (3)); refused in +// words while none does. +func compositionDiffFrom(current *agentNow) func(module string, revision int64, digest string) (any, error) { + return func(module string, revision int64, digest string) (any, error) { + ag := current.get() + if ag == nil { + return nil, errors.New("this engine's node agent has not started, so it holds no composition yet") + } + ctx, cancel := context.WithTimeout(context.Background(), compositionReadFor) + defer cancel() + return ag.CompositionDiff(ctx, module, revision, digest) + } +} + // withheldPartsOf is, of the composer that runs now, each part its last pass kept for module because its read did not answer. func withheldPartsOf(composer *atomic.Pointer[selfcompose.Composer]) func(module string) map[string]string { return func(module string) map[string]string { diff --git a/cmd/mesh-host/main.go b/cmd/mesh-host/main.go index 0651e1e5..2ce4db11 100644 --- a/cmd/mesh-host/main.go +++ b/cmd/mesh-host/main.go @@ -1028,6 +1028,7 @@ func runLink(ctx context.Context, opts options) error { go reconcileActs(ctx, queue.Acts) current := &agentNow{} queue.Acts.Composition = compositionFrom(current, queue.WithheldOf, withheldPartsOf(&composerNow)) + queue.Acts.CompositionDiff = compositionDiffFrom(current) queue.Acts.Compose = composeFrom(current, &composerNow) queue.Acts.ApplyOrder = applyOrderFrom(current) queue.Acts.Packages = packagesFrom(mine.Node, queue, &composerNow) diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index 3f12b797..77990ac5 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -1949,6 +1949,29 @@ func TestTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes( if _, err := b.ag.Composition(context.Background(), "db", "sha256:"+strings.Repeat("0", 64), false); err == nil { t.Error("a digest no revision has was answered") } + // Design 47 H2 §813 (3): composition-diff answers, by resource, the entries that differ between what runs and the + // revision asked, by its digest or its revision; a secret's value is masked, an environment entry named by its name. + if d, err := b.ag.CompositionDiff(context.Background(), "db", 0, ddigMoved); err != nil || d.Running != ddig || d.Other == nil || + d.Other.Digest != ddigMoved || len(d.Resources) != 1 || d.Resources[0].Resource != "db.server" || len(d.Resources[0].Entries) != 1 || + d.Resources[0].Entries[0] != (nodeengine.CompositionDiffEntry{Name: "image", Running: "db@sha256:" + strings.Repeat("1", 64), + Other: "db@sha256:" + strings.Repeat("7", 64)}) { + t.Errorf("composition-diff of db's waiting revision reads %+v (%v)", d, err) + } + if d, err := b.ag.CompositionDiff(context.Background(), "db", int64(view.Revisions[0].Revision), ""); err != nil || + d.Other == nil || d.Other.Digest != ddig || len(d.Resources) != 0 { + t.Errorf("composition-diff of db's running revision, by its revision, reads %+v (%v)", d, err) + } + if _, err := b.ag.CompositionDiff(context.Background(), "db", 0, ""); err == nil { + t.Error("composition-diff with neither a revision nor a digest was answered") + } + if got := DiffResources([]json.RawMessage{json.RawMessage(`{"id":"web.key","type":"file","sealed":"a","content":"x"}`), + json.RawMessage(`{"id":"web.run","type":"process","env":{"MODE":"a","GONE":"1"}}`)}, + []json.RawMessage{json.RawMessage(`{"id":"web.key","type":"file","sealed":"b","content":"y"}`), + json.RawMessage(`{"id":"web.run","type":"process","env":{"MODE":"b"}}`)}); len(got) != 2 || + !slices.Equal(got[0].Entries, []nodeengine.CompositionDiffEntry{{Name: "content", Masked: true}, {Name: "sealed", Masked: true}}) || + !slices.Equal(got[1].Entries, []nodeengine.CompositionDiffEntry{{Name: "env.GONE", Running: "1"}, {Name: "env.MODE", Running: "a", Other: "b"}}) { + t.Errorf("the entries that differ, a secret masked, read %+v", got) + } // Issue 774 (ace, 2026-11-04 01:29): the node's own revision shows its own fields, the provisioner client's account // and the adoption among them, and what the composer's last pass held. ownKey, ownRaw, ownDig := encodedAs(t, compositions.Composed{Node: node, Own: compositions.NodeOwn{Provisioner: "mesh-provisioner-client", diff --git a/internal/agent/composition.go b/internal/agent/composition.go index b80a2891..e9017838 100644 --- a/internal/agent/composition.go +++ b/internal/agent/composition.go @@ -2,9 +2,14 @@ package agent import ( "context" + "encoding/json" "errors" "fmt" + "maps" + "slices" + "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" + "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" engcomp "github.com/novox/mesh-host/internal/compositions" "git.novox.be/novox/mesh-sdk/go/catalogue" @@ -335,3 +340,160 @@ func (a *Agent) revisionsOf(ctx context.Context, key string) ([]compNow, error) } return out, nil } + +// CompositionDiff answers the node-engine seat's read verb composition-diff (design 47 H2 §813 (3), H-A-349 DQ-12b): one +// module's composition that runs beside another revision of its composition key, given by its revision or its digest, +// as the entries that differ per resource; environment entries by name, a secret's value masked. It changes nothing. +func (a *Agent) CompositionDiff(ctx context.Context, module string, revision int64, digest string) (nodeengine.CompositionDiffAnswer, error) { + answer := nodeengine.CompositionDiffAnswer{Node: a.env.Node, Module: module, Resources: []nodeengine.CompositionDiffResource{}} + switch { + case module == "": + return answer, errors.New("name the module, or node for the node's own composition") + case (revision == 0) == (digest == ""): + return answer, errors.New("give the revision or the digest of the composition to compare with, one of the two") + } + a.mu.Lock() + fp := "" + if w := a.wants[module]; w.Present { + fp = w.Want.Fp + } + running, known := a.runningComposition(module) + a.mu.Unlock() + if fp == "" && known { + fp = running.FP + } + if module != NodeModule && fp == "" { + return answer, fmt.Errorf("%s has no want and nothing runs of it on %s, so no composition of it is kept here", module, a.env.Node) + } + key, err := a.compositionKey(module, fp) + if err != nil { + return answer, err + } + revs, err := a.revisionsOf(ctx, key) + if err != nil { + return answer, fmt.Errorf("the revisions of %s cannot be read: %w", key, err) + } + var other *compNow + for i := range revs { + if (revision != 0 && revs[i].Rev == uint64(revision)) || (digest != "" && revs[i].Err == nil && revs[i].Dig == digest) { + other = &revs[i] + } + } + if other == nil { + return answer, fmt.Errorf("no revision of %s the bucket keeps is the one asked; composition lists those it keeps", key) + } + answer.Other = &nodeengine.Revision{Key: key, Revision: int64(other.Rev), Digest: other.Dig, Resources: int64(len(other.C.Resources)), + Latest: other.Rev == revs[len(revs)-1].Rev} + if other.Err != nil { + answer.Other.Refused = other.Err.Error() + return answer, nil + } + var from []json.RawMessage + if known { + from = running.Resources + if answer.Running, err = engcomp.DigestOf(running); err != nil { + return answer, fmt.Errorf("the composition that runs of %s has no digest: %w", module, err) + } + } + answer.Resources = DiffResources(from, other.C.Resources) + return answer, nil +} + +// DiffResources is, per resource by its id, the entries that differ from running to other (design 47 H2 §813 (3)): each +// top-level field by its name, the environment's entries each by `env.`, and a value the declaration keeps secret +// (a file's sealed, vault-sealed or secrets, and the content of a file that has any of them) masked. Resources in id +// order, entries in name order; none that is the same in both. +func DiffResources(running, other []json.RawMessage) []nodeengine.CompositionDiffResource { + was, now := entriesByID(running), entriesByID(other) + ids := map[string]bool{} + for id := range was { + ids[id] = true + } + for id := range now { + ids[id] = true + } + out := []nodeengine.CompositionDiffResource{} + for _, id := range slices.Sorted(maps.Keys(ids)) { + w, n := was[id], now[id] + names := map[string]bool{} + for k := range w.values { + names[k] = true + } + for k := range n.values { + names[k] = true + } + var entries []nodeengine.CompositionDiffEntry + for _, name := range slices.Sorted(maps.Keys(names)) { + rv, rok := w.values[name] + ov, ook := n.values[name] + if rok == ook && rv == ov { + continue + } + e := nodeengine.CompositionDiffEntry{Name: name} + if w.secret[name] || n.secret[name] { + e.Masked = true + } else { + e.Running, e.Other = rv, ov + } + entries = append(entries, e) + } + if len(entries) > 0 { + out = append(out, nodeengine.CompositionDiffResource{Resource: id, Entries: entries}) + } + } + return out +} + +// resourceEntries are one resource's entries by name, as text, and which of them hold a secret. +type resourceEntries struct { + values map[string]string + secret map[string]bool +} + +// secretFields are the fields of a resource the declaration keeps secret (declaration.File.Secret, its Secrets). +var secretFields = []string{"sealed", "vault-sealed", "secrets"} + +func entriesByID(resources []json.RawMessage) map[string]resourceEntries { + out := map[string]resourceEntries{} + for _, raw := range resources { + var fields map[string]json.RawMessage + if json.Unmarshal(raw, &fields) != nil { + continue + } + var id string + _ = json.Unmarshal(fields["id"], &id) + r := resourceEntries{values: map[string]string{}, secret: map[string]bool{}} + hasSecret := false + for _, f := range secretFields { + if _, ok := fields[f]; ok { + hasSecret = true + } + } + for name, value := range fields { + if name == "env" { + var env map[string]string + if json.Unmarshal(value, &env) == nil { + for k, v := range env { + r.values["env."+k] = v + } + continue + } + } + r.values[name] = entryText(value) + if slices.Contains(secretFields, name) || (hasSecret && name == "content") { + r.secret[name] = true + } + } + out[id] = r + } + return out +} + +// entryText is a field's value as the answer says it: a string as itself, anything else as its JSON. +func entryText(value json.RawMessage) string { + var s string + if json.Unmarshal(value, &s) == nil { + return s + } + return string(value) +} diff --git a/internal/link/handacts.go b/internal/link/handacts.go index d902eb3f..cbea5eb1 100644 --- a/internal/link/handacts.go +++ b/internal/link/handacts.go @@ -44,6 +44,9 @@ const ( ActSetuidSearch = nodeengine.VerbSetuidSearch // ActComposition reads a module's composition beside what runs of it; read-only, no warrant (issue 774). ActComposition = nodeengine.VerbComposition + // ActCompositionDiff reads a module's running composition beside another revision of it, by resource; read-only (design + // 47 H2 §813 (3)). + ActCompositionDiff = nodeengine.VerbCompositionDiff // ActCompose composes the node now, the recovery of a failed composition (issue 774). ActCompose = nodeengine.VerbCompose // ActPackages reads the packages this node's compositions declare, and with write writes its key again (novox/hq @@ -163,6 +166,9 @@ type HandActs struct { // Composition reads one module's composition beside what runs of it, read-only (the verb composition, issue 774): // the latest of its want's build or the one whose digest is given, and with diff the resources that differ. Composition func(module, digest string, diff bool) (any, error) + // CompositionDiff answers the verb composition-diff: the entries that differ per resource between the module's running + // composition and the revision or digest given (design 47 H2 §813 (3)). + CompositionDiff func(module string, revision int64, digest string) (any, error) // Compose makes a pass of the node's composition now and says how it went; with module, its apply is also tried // again (the verb compose, issue 774). Compose func(module string) (any, error) @@ -248,6 +254,20 @@ func (h *HandActs) Call(c EngineCall) (any, error) { diff = b } return h.Composition(arg("module"), arg("digest"), diff) + case ActCompositionDiff: + if h.CompositionDiff == nil { + return nil, errors.New("this engine reads no composition yet: its node agent has not started") + } + var revision int64 + switch r := c.Args["revision"].(type) { + case float64: + revision = int64(r) + case int64: + revision = r + case int: + revision = int64(r) + } + return h.CompositionDiff(arg("module"), revision, arg("digest")) case ActCompose: if h.Compose == nil { return nil, errors.New("this engine composes nothing on a call yet: its node agent has not started") -- 2.54.0 From 7adf9996c57d03211810c1ebf366c22c65af5ea6 Mon Sep 17 00:00:00 2001 From: jochen Date: Sat, 21 Nov 2026 23:13:34 +0100 Subject: [PATCH 03/23] E7: stop the tool runner alone and wait its drain bound MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The service manager's stop signalled the tool runner's whole group, so its bundles died with their calls. The composer carries the runner's drain-bound setting on its process; the unit stops the runner alone and waits the bound and 15 s before it kills what is left, so the new runner starts only after the old one exits or that bound passes. Builds: design 47 H2 §813 (12); H-A-353; H-A-358 --- internal/apply/process.go | 14 +++++- internal/apply/process_test.go | 10 +++++ internal/compose/resolution/runtime.go | 50 +++++++++++++++++++-- internal/compose/resolution/runtime_test.go | 26 +++++++++++ 4 files changed, 96 insertions(+), 4 deletions(-) diff --git a/internal/apply/process.go b/internal/apply/process.go index 4d434ab0..94d1a48e 100644 --- a/internal/apply/process.go +++ b/internal/apply/process.go @@ -293,6 +293,10 @@ func withNode(r *declaration.Process, node string) *declaration.Process { return &p } +// drainStopMargin is the seconds a draining process's stop timeout lies above its drain bound: the time it takes to stop +// its children after its drain (H-A-358). +const drainStopMargin = 15 + // unitFor is the unit the mesh writes for a daemon. // // **Generated whole and never edited in place**, the same rule as every other managed file: an @@ -333,7 +337,15 @@ func unitFor(r *declaration.Process) string { } // Restarted when it exits, because something that stops is not something that stays up. // Delayed, so a process that fails at once does not spin the machine. - b.WriteString("Restart=always\nRestartSec=5\n\n") + b.WriteString("Restart=always\nRestartSec=5\n") + // **A process that drains is stopped alone** (design 47 H2 §813 (12), H-A-353, H-A-358): the stop signal reaches it + // and not its children, so the calls in flight finish within its drain bound and it stops its children itself; the + // service manager waits the bound and the time they take before it kills what is left, so the new process starts only + // after the old one exits or that bound passes. + if r.DrainBound > 0 { + fmt.Fprintf(&b, "KillMode=mixed\nTimeoutStopSec=%ds\n", r.DrainBound+drainStopMargin) + } + b.WriteString("\n") b.WriteString("[Install]\nWantedBy=multi-user.target\n") return b.String() diff --git a/internal/apply/process_test.go b/internal/apply/process_test.go index 1cab4259..91ab037d 100644 --- a/internal/apply/process_test.go +++ b/internal/apply/process_test.go @@ -43,6 +43,16 @@ func TestTheUnitRunsWhatTheDaemonSaid(t *testing.T) { if strings.Contains(unit, "Type=oneshot") { t.Fatalf("a process that should stay up is declared a step:\n%s", unit) } + // Design 47 H2 §813 (12), H-A-353, H-A-358: a process that drains is stopped alone, its stop waiting its drain bound and + // 15 s for its children; one that does not keeps the service manager's defaults. + if strings.Contains(unit, "KillMode=") || strings.Contains(unit, "TimeoutStopSec=") { + t.Fatalf("a process with no drain bound has its stop written:\n%s", unit) + } + draining := aProcess() + draining.DrainBound = 30 + if got := unitFor(draining); !strings.Contains(got, "Restart=always\nRestartSec=5\nKillMode=mixed\nTimeoutStopSec=45s\n\n[Install]") { + t.Fatalf("a process with a drain bound of 30 s is not stopped alone within 45 s:\n%s", got) + } } // **Deterministic, because the unit is half the daemon's identity.** Environment held in a map diff --git a/internal/compose/resolution/runtime.go b/internal/compose/resolution/runtime.go index 675010e6..10f6722c 100644 --- a/internal/compose/resolution/runtime.go +++ b/internal/compose/resolution/runtime.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "sort" + "strconv" "strings" mcat "git.novox.be/novox/mesh-sdk/go/catalogue" @@ -171,12 +172,17 @@ func resolutionRuntimeProcess(r mcat.Resolution, with mcat.Rendering, h Holding) } env[mcat.RuntimeToolEnv] = string(body) } + drain, err := drainBoundOf(*runtime, with.Settings[runtime.Module]) + if err != nil { + return nil, err + } process := map[string]any{ "id": runtime.Module + "." + RuntimeProcessID(), "type": "process", "name": runtime.Module, "source": bundle.Source, "digest": bundle.Digest, - "run": run, - "env": env, - "restart-on": toAny(restartOn), + "run": run, + "env": env, + "restart-on": toAny(restartOn), + "drain-bound": drain, } if r.Account != "" { env[mcat.RuntimeOperatorAccount] = r.Account @@ -195,6 +201,44 @@ func resolutionRuntimeProcess(r mcat.Resolution, with mcat.Rendering, h Holding) return process, nil } +// DrainBoundSetting is the tool runner module's setting of how long, in seconds, it finishes its calls in flight once +// stopped (design 47 H2 §813 (12)); DefaultDrainBound is its default where no layer sets it (H-A-358). +const ( + DrainBoundSetting = "drain-bound" + DefaultDrainBound = 30 +) + +// drainBoundOf is the tool runner's drain bound in seconds, from its setting drain-bound, else DefaultDrainBound (design +// 47 H2 §813 (12), H-A-358): the node-engine writes its unit's stop from it. A value that is no whole number of seconds +// above zero is refused by name. +func drainBoundOf(m mcat.Manifest, layers []mcat.Layer) (int, error) { + v, set := settingValue(WithDefaults(m, layers), DrainBoundSetting) + if !set { + return DefaultDrainBound, nil + } + var n float64 + switch x := v.(type) { + case float64: + n = x + case int: + n = float64(x) + case int64: + n = float64(x) + case string: + parsed, err := strconv.Atoi(strings.TrimSpace(x)) + if err != nil { + return 0, fmt.Errorf("%s's setting %s is %q, and it is a whole number of seconds", m.Module, DrainBoundSetting, x) + } + n = float64(parsed) + default: + return 0, fmt.Errorf("%s's setting %s is %v, and it is a whole number of seconds", m.Module, DrainBoundSetting, v) + } + if n < 1 || n != float64(int(n)) { + return 0, fmt.Errorf("%s's setting %s is %v, and it is a whole number of seconds above zero", m.Module, DrainBoundSetting, v) + } + return int(n), nil +} + // NoRuntimeToRunError is a module of its own account with no runtime program on its node to run it from. Held says the // runtime is there and held (its stand-in, Stubbed): the module cannot compose because the runtime does not, so a // composition that holds the runtime holds it too, never the node (issue 774). diff --git a/internal/compose/resolution/runtime_test.go b/internal/compose/resolution/runtime_test.go index 3fdd4216..f7ed2da6 100644 --- a/internal/compose/resolution/runtime_test.go +++ b/internal/compose/resolution/runtime_test.go @@ -168,6 +168,32 @@ func TestTheMachineRunsOneRuntimeLoadingEveryDeliveredBundle(t *testing.T) { if names[len(names)-1] != "node-tools"+"."+RuntimeProcessID() { t.Errorf("the runtime's process is not last: %v", names) } + // Design 47 H2 §813 (12), H-A-358: the runtime's process carries the module's drain bound, 30 s where no layer sets it, + // the value a layer sets, and a value that is no number of seconds is refused by name. + if process["drain-bound"] != DefaultDrainBound { + t.Errorf("the runtime's process drains for %v, not the default 30 s", process["drain-bound"]) + } + for _, row := range []struct { + value any + want int + words string + }{{float64(45), 45, ""}, {"60", 60, ""}, {"soon", 0, "whole number of seconds"}, {float64(0), 0, "above zero"}} { + set := with + set.Settings = mcat.SettingsBy{"node-tools": {{From: "mesh", Values: map[string]any{DrainBoundSetting: row.value}}}} + out, err := Declaration(r, set) + if row.words != "" { + if err == nil || !strings.Contains(err.Error(), row.words) { + t.Errorf("drain-bound %v was composed: %v", row.value, err) + } + continue + } + if err != nil { + t.Fatal(err) + } + if got := fileNamed(out, "node-tools."+RuntimeProcessID())["drain-bound"]; got != row.want { + t.Errorf("drain-bound %v composed the runtime's process with %v", row.value, got) + } + } t.Run("a machine with no account runs it as root without the operator words", func(t *testing.T) { out, err := Declaration(mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{nftables, theRuntime(t)}}, with) -- 2.54.0 From 38447a66b8934813b0a05aaf0a7267db38e3da66 Mon Sep 17 00:00:00 2001 From: jochen Date: Sat, 21 Nov 2026 23:16:38 +0100 Subject: [PATCH 04/23] E8: merge seven unit tests into the tests they extend MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The node-engine holds 1,715 unit tests against a budget of 500; each of these asserted one more case of a rendering another test already holds. Builds: design 47 H2 §819 --- internal/apply/process_test.go | 22 ++--- internal/compose/resolution/filtering_test.go | 9 +-- .../compose/resolution/localnetwork_test.go | 81 +++++++++---------- 3 files changed, 46 insertions(+), 66 deletions(-) diff --git a/internal/apply/process_test.go b/internal/apply/process_test.go index 91ab037d..6168e2e4 100644 --- a/internal/apply/process_test.go +++ b/internal/apply/process_test.go @@ -53,12 +53,9 @@ func TestTheUnitRunsWhatTheDaemonSaid(t *testing.T) { if got := unitFor(draining); !strings.Contains(got, "Restart=always\nRestartSec=5\nKillMode=mixed\nTimeoutStopSec=45s\n\n[Install]") { t.Fatalf("a process with a drain bound of 30 s is not stopped alone within 45 s:\n%s", got) } -} -// **Deterministic, because the unit is half the daemon's identity.** Environment held in a map -// would be written in Go's iteration order, so every apply would see a different unit and call an -// unchanged daemon changed — restarting it on every declaration for ever. -func TestTheUnitIsTheSameEveryTime(t *testing.T) { + // **Deterministic, because the unit is half the daemon's identity.** Environment held in a map would be written in + // Go's iteration order, so every apply would see a different unit and call an unchanged daemon changed. first := unitFor(aProcess()) for i := 0; i < 20; i++ { if again := unitFor(aProcess()); again != first { @@ -69,15 +66,11 @@ func TestTheUnitIsTheSameEveryTime(t *testing.T) { if strings.Index(first, "A_FIRST") > strings.Index(first, "MESH_NODE") { t.Fatalf("environment is not in a stable order:\n%s", first) } -} - -// **Two daemons from one bundle differing only in their command are different daemons.** Tracking -// the digest alone would call the second one unchanged and leave the first one running. -func TestAProcesssIdentityIncludesHowItIsRun(t *testing.T) { - one := aProcess() + // **Two daemons from one bundle differing only in their command are different daemons.** Tracking the digest alone + // would call the second one unchanged and leave the first one running. two := aProcess() two.Run = []string{"node", "other.js"} - if unitFor(one) == unitFor(two) { + if first == unitFor(two) { t.Fatal("two daemons with different commands render one unit, so a change would be missed") } } @@ -173,10 +166,7 @@ func TestAScheduledProcessRunsOnItsCadenceRatherThanContinuously(t *testing.T) { if !strings.Contains(timer, "Persistent=true") { t.Fatalf("a missed fire is skipped silently:\n%s", timer) } -} - -// Five-field cron becomes what a timer reads, rather than the host waking to decide. -func TestACronBecomesATimersCalendar(t *testing.T) { + // Five-field cron becomes what a timer reads, rather than the host waking to decide. for cron, want := range map[string]string{ "0 3 * * *": "*-*-* 3:0:00", "30 4 1 * *": "*-*-1 4:30:00", diff --git a/internal/compose/resolution/filtering_test.go b/internal/compose/resolution/filtering_test.go index 8450a0b4..46eb3b63 100644 --- a/internal/compose/resolution/filtering_test.go +++ b/internal/compose/resolution/filtering_test.go @@ -27,13 +27,8 @@ func TestAMachineThatNamedNoOutwardLinkIsSentNoFilter(t *testing.T) { t.Fatalf("the refusal does not say %q: %v", want, err) } } -} - -// And a machine that names none but loads no filter is not refused: there is nothing to write. -func TestAMachineWithNoFilterModuleIsNotRefused(t *testing.T) { - r := mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{ - {Module: "web", Listens: []mcat.Listening{{Port: 443, From: mcat.FromEverywhere}}}, - }} + // And a machine that names none but loads no filter is not refused: there is nothing to write. + r.Modules = r.Modules[1:] if _, err := Declaration(r, mcat.Rendering{Mesh: []string{"198.51.100.2"}}); err != nil { t.Fatalf("a machine that loads no filter was refused one: %v", err) } diff --git a/internal/compose/resolution/localnetwork_test.go b/internal/compose/resolution/localnetwork_test.go index caaa61db..a289eede 100644 --- a/internal/compose/resolution/localnetwork_test.go +++ b/internal/compose/resolution/localnetwork_test.go @@ -50,17 +50,31 @@ func TestOnlyAPrivateNetworkOnALinkFacingOutsideCounts(t *testing.T) { } } } -} - -// A network overlapping a private range without lying wholly inside it does not count either, so a -// wide prefix around a private range cannot carry the internet with it. -func TestANetworkNotWhollyInAPrivateRangeDoesNotCount(t *testing.T) { + // A network overlapping a private range without lying wholly inside it does not count either, so a + // wide prefix around a private range cannot carry the internet with it. for _, n := range []string{"10.0.0.0/7", "172.0.0.0/8", "100.64.0.0/10", "0.0.0.0/0", "::/0"} { got := JudgeLocalNetworks([]mcat.AttachedNetwork{{Link: "eth0", Network: n}}, []string{"eth0"}, "") if len(got) != 1 || got[0].Counts { t.Errorf("%s counts as a local network: %+v", n, got) } } + // A global unicast IPv6 subnet on a link facing outside is public, and never counts: the IPv6 side of the + // rule that `local-network` cannot open a port to the internet (ADR 0340 §2). + { + got := JudgeLocalNetworks([]mcat.AttachedNetwork{{Link: "eth0", Network: "2001:db8:1234::7/48"}}, []string{"eth0"}, "wg-mesh") + if len(got) != 1 { + t.Fatalf("judged %+v", got) + } + if got[0].Counts { + t.Fatalf("the global IPv6 subnet %s counts as a local network", got[0].Network) + } + if got[0].Network != "2001:db8:1234::/48" || !strings.Contains(got[0].Why, "public, never counted") { + t.Fatalf("judged %s with why %q, want it named public and never counted", got[0].Network, got[0].Why) + } + if n := CountedLocalNetworks(got); len(n) != 0 { + t.Fatalf("counted %v", n) + } + } } // **The filter admits the local network on that port's rule alone** (§5), beside the private network, @@ -104,27 +118,26 @@ func TestALocalNetworkPortIsAdmittedFromItsNetworksAndTheMesh(t *testing.T) { t.Fatalf("1883 is open to anywhere:\n%s", out) } } -} - -// **Nothing resolved is closed and said** (§6): a machine that reported no private network admits the -// port from the private network only, and the rule set says it found none — never widened to anywhere. -func TestNoLocalNetworkIsSaidAndNotWidened(t *testing.T) { - rules := []mcat.Rule{{Port: 1883, Protocol: "tcp", From: mcat.FromLocalNetwork, Because: []string{"mosquitto"}}} - out := AsNftablesWithLocal(rules, []string{"10.10.0.1"}, false, nil, []string{"eth0"}, "wg-mesh", nil) - if !strings.Contains(out, "1883 wanted the local network, and this machine reported no private network") { - t.Errorf("the rule set does not say the local network resolved to nothing:\n%s", out) - } - if !strings.Contains(out, "ip saddr { 10.10.0.1 } tcp dport 1883 accept") { - t.Errorf("the port is not admitted from the private network:\n%s", out) - } - for _, line := range strings.Split(out, "\n") { - if strings.TrimSpace(line) == "tcp dport 1883 accept" { - t.Fatalf("an unresolved local network was widened to anywhere:\n%s", out) + // **Nothing resolved is closed and said** (§6): a machine that reported no private network admits the + // port from the private network only, and the rule set says it found none — never widened to anywhere. + { + rules := []mcat.Rule{{Port: 1883, Protocol: "tcp", From: mcat.FromLocalNetwork, Because: []string{"mosquitto"}}} + out := AsNftablesWithLocal(rules, []string{"10.10.0.1"}, false, nil, []string{"eth0"}, "wg-mesh", nil) + if !strings.Contains(out, "1883 wanted the local network, and this machine reported no private network") { + t.Errorf("the rule set does not say the local network resolved to nothing:\n%s", out) + } + if !strings.Contains(out, "ip saddr { 10.10.0.1 } tcp dport 1883 accept") { + t.Errorf("the port is not admitted from the private network:\n%s", out) + } + for _, line := range strings.Split(out, "\n") { + if strings.HasPrefix(strings.TrimSpace(line), "tcp dport 1883 accept") { + t.Fatalf("an unresolved local network was widened to anywhere:\n%s", out) + } + } + said := LocalNetworkPorts(rules, nil)[0].Said() + if !strings.Contains(said, "none") { + t.Errorf("plan says %q, want it to say no local network was found", said) } - } - said := LocalNetworkPorts(rules, nil)[0].Said() - if !strings.Contains(said, "none") { - t.Errorf("plan says %q, want it to say no local network was found", said) } } @@ -171,21 +184,3 @@ func TestAnAdoptedNodeOpensTheLocalNetworkPortToTheMeshOnly(t *testing.T) { t.Fatalf("openings %v", out) } } - -// A global unicast IPv6 subnet on a link facing outside is public, and never counts: the IPv6 side of the -// rule that `local-network` cannot open a port to the internet (ADR 0340 §2). -func TestAGlobalIPv6SubnetIsPublicAndNeverCounts(t *testing.T) { - got := JudgeLocalNetworks([]mcat.AttachedNetwork{{Link: "eth0", Network: "2001:db8:1234::7/48"}}, []string{"eth0"}, "wg-mesh") - if len(got) != 1 { - t.Fatalf("judged %+v", got) - } - if got[0].Counts { - t.Fatalf("the global IPv6 subnet %s counts as a local network", got[0].Network) - } - if got[0].Network != "2001:db8:1234::/48" || !strings.Contains(got[0].Why, "public, never counted") { - t.Fatalf("judged %s with why %q, want it named public and never counted", got[0].Network, got[0].Why) - } - if n := CountedLocalNetworks(got); len(n) != 0 { - t.Fatalf("counted %v", n) - } -} -- 2.54.0 From 53d5c8b20fca66a0a12ae91a3e82b5146f082030 Mon Sep 17 00:00:00 2001 From: jochen Date: Sat, 21 Nov 2026 23:18:48 +0100 Subject: [PATCH 05/23] E1: read another part's values tolerantly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The generated decoders keep unknown fields and return the form read, so a want the assigner writes with run, or any field added later, is applied rather than refused: the node-engine that reads run runs before the assigner writes it. Builds: design 47 H2 §780; §813 (1) (the edge) --- internal/agent/agent.go | 4 ++-- internal/agent/agent_test.go | 8 ++++++++ internal/selfcompose/candidate.go | 2 +- internal/selfcompose/selfcompose.go | 2 +- internal/selfcompose/shadow.go | 2 +- 5 files changed, 13 insertions(+), 5 deletions(-) diff --git a/internal/agent/agent.go b/internal/agent/agent.go index c78eedf2..50e8283e 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -828,7 +828,7 @@ func (a *Agent) takeWant(u Update) string { if _, ok := meshwants.ParseWantsByWantNodeNodeKey(u.Key); ok { w := wantNow{Node: true, Rev: u.Revision} if !u.Deleted { - nw, err := meshwants.DecodeWantsByWantNodeNodeValue(u.Value) + nw, _, err := meshwants.DecodeWantsByWantNodeNodeValue(u.Value) if err != nil { a.sayOnce("want:node", fmt.Sprintf("the node's own want is not one: %v", err)) return "" @@ -844,7 +844,7 @@ func (a *Agent) takeWant(u Update) string { } w := wantNow{Rev: u.Revision} if !u.Deleted { - want, err := meshwants.DecodeWantsByWantNodeModuleValue(u.Value) + want, _, err := meshwants.DecodeWantsByWantNodeModuleValue(u.Value) if err != nil { a.sayOnce("want:"+module, fmt.Sprintf("the want of %s is not one: %v", module, err)) return "" diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index 77990ac5..92080f0b 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -331,6 +331,14 @@ func TestAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) { ckn, crawn, dign := composition(t, "web", fpn, false, archive("a", d1), archive("b", d2)) b.comps.put(ckn, crawn) wkn, wrawn := wantFor(t, "web", fpn, dign, "") + // Design 47 H2 §780, §813 (1): the want is read tolerantly, a field this engine does not know and a later form kept + // rather than refused, so the engine that reads run runs before the assigner writes it. + var later map[string]any + if err := json.Unmarshal(wrawn, &later); err != nil { + t.Fatal(err) + } + later["form"], later["a-later-field"] = 3, "x" + wrawn, _ = json.Marshal(later) b.wants.put(wkn, wrawn) b.idle() if got := len(b.appliedList()) - before; got != 1 { diff --git a/internal/selfcompose/candidate.go b/internal/selfcompose/candidate.go index c03ba799..15cbdac5 100644 --- a/internal/selfcompose/candidate.go +++ b/internal/selfcompose/candidate.go @@ -187,7 +187,7 @@ func (s *Shadow) composeCandidate(ctx context.Context, c *Composer, ask nodeengi if raw == nil { return refuse("the indexer holds no candidate " + ask.Candidate) } - cand, err = meshcatalog.DecodeCandidatesByGroupValue(raw) + cand, _, err = meshcatalog.DecodeCandidatesByGroupValue(raw) if err != nil { return refuse(fmt.Sprintf("the indexer's candidate %s cannot be read: %v", ask.Candidate, err)) } diff --git a/internal/selfcompose/selfcompose.go b/internal/selfcompose/selfcompose.go index f177fd83..7b12cccb 100644 --- a/internal/selfcompose/selfcompose.go +++ b/internal/selfcompose/selfcompose.go @@ -898,7 +898,7 @@ func (c *Composer) takeWantLocked(u agent.Update) string { delete(c.notTaken, module) delete(c.keptWants, module) c.dropForgottenLocked(module) // its next want asks again what a failed fetch made it forget (H-A-146) - w, err := meshwants.DecodeWantsByWantNodeModuleValue(u.Value) + w, _, err := meshwants.DecodeWantsByWantNodeModuleValue(u.Value) if u.Deleted || err != nil || w.Removed || w.Fp == "" { delete(c.wants, module) switch { diff --git a/internal/selfcompose/shadow.go b/internal/selfcompose/shadow.go index c4ebd49d..506efd1b 100644 --- a/internal/selfcompose/shadow.go +++ b/internal/selfcompose/shadow.go @@ -332,7 +332,7 @@ func (s *Shadow) takeCandidate(u agent.Update) bool { } return true } - c, err := meshmoduleassigner.DecodeCandidatesByProposalNodeValue(u.Value) + c, _, err := meshmoduleassigner.DecodeCandidatesByProposalNodeValue(u.Value) if err != nil || c.Proposal != proposal || (c.Assignments != nil && c.Assignments.Node != node) { // Not one: read as gone. if _, ok := s.candidates[proposal][node]; ok { -- 2.54.0 From 84fc34398ad826921eb313081974de2c17447c53 Mon Sep 17 00:00:00 2001 From: jochen Date: Sat, 21 Nov 2026 23:22:30 +0100 Subject: [PATCH 06/23] E4: apply a want again only from a newer run MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One writer per composition key: the holder of mesh-wants writes run, the composition run's pipeline sequence, on the want; the node-engine keeps the run each module was applied from, applies again only a want whose run is newer, and names the run in its journal. Builds: design 47 H2 §813 (1); H-A-355 --- internal/agent/agent.go | 35 ++++++++++++++++++++++++++++++++++- internal/agent/agent_test.go | 31 ++++++++++++++++++++++++++++++- 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 50e8283e..754478f7 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -23,6 +23,7 @@ import ( "github.com/novox/mesh-host/internal/compositions" "slices" "sort" + "strconv" "strings" "sync" "sync/atomic" @@ -249,6 +250,9 @@ type Agent struct { // applied is the composition each module was last applied from: a revision a want named from the key's history is // not the key's latest value, and what it holds is still held out of the others' applies. applied map[string]compNow + // appliedRun is, of each module applied from a want that carried run, that run: the composition run's pipeline sequence + // in decimal (design 47 H2 §813 (1), H-A-355). A want whose run is not newer is not applied again. + appliedRun map[string]string // had is, for each module whose have names a composition the bucket keeps (its latest value or a revision), that // composition, read once at the start (loadHad): what runs of a module the agent has not taken yet, ahead of the kept // declaration (issue 924). @@ -341,7 +345,7 @@ func New(env Env) *Agent { if env.Say == nil { env.Say = func(string) {} } - return &Agent{env: env, wants: map[string]wantNow{}, comps: map[string]compNow{}, running: map[string]nodeengine.HaveByNodeModuleValue{}, applied: map[string]compNow{}, had: map[string]compNow{}, keptData: map[string]bool{}, + return &Agent{env: env, wants: map[string]wantNow{}, comps: map[string]compNow{}, running: map[string]nodeengine.HaveByNodeModuleValue{}, applied: map[string]compNow{}, appliedRun: map[string]string{}, had: map[string]compNow{}, keptData: map[string]bool{}, attempt: map[string]attempt{}, checked: map[string]bool{}, prior: map[string]bool{}, said: map[string]string{}, waited: map[string]string{}, notComposed: map[string]notComposedMark{}, pulls: map[string]*pullWait{}, settledAt: map[string]time.Time{}, settledSeq: map[string]int{}, retry: make(chan []string, 8), reconcile: make(chan []string, 64), failedAgain: make(chan string, 8), tries: map[string]int{}, again: make(chan againAsk, 64), @@ -1544,6 +1548,13 @@ func (a *Agent) settleOne(ctx context.Context, module string) { a.mu.Unlock() return // failed already for exactly these keys: retried by the next change of either } + if was := a.appliedRun[module]; !runIsNewer(w.Want.Run, was) { + // Design 47 H2 §813 (1), H-A-355: one writer per composition key, and the engine applies again only a newer write. + a.sayOnce("run:"+module+":"+w.Want.Run, fmt.Sprintf("the want of %s carries run %s, and the engine applied it from run %s, "+ + "which is not older: nothing is applied", module, w.Want.Run, was)) + a.mu.Unlock() + return + } if module == NodeModule { // Not while a module's composition cannot be read or is refused: what it carries may be what left the node's own, // and the node's own apply would remove it, held out by nothing (issue 1945, the review's gap 2). @@ -1829,7 +1840,14 @@ func (a *Agent) apply(ctx context.Context, module string, w wantNow, comp compNo delete(a.notComposed, module) // the apply says what it runs now a.running[module] = nodeengine.HaveByNodeModuleValue{Fp: fp, Composed: dig, Phase: nodeengineclient.PhaseRunning} a.applied[module] = comp + run := w.Want.Run + if run != "" { + a.appliedRun[module] = run + } a.mu.Unlock() + if run != "" { + a.env.Say(fmt.Sprintf("applied %s from run %s", what, run)) + } a.keepApplied(module, comp) if a.env.Settled != nil { a.env.Settled(module) @@ -1838,6 +1856,21 @@ func (a *Agent) apply(ctx context.Context, module string, w wantNow, comp compNo a.catchUp(ctx, module, catchUps) } +// runIsNewer says whether a want's run orders after the run a module was applied from (design 47 H2 §813 (1)): each is +// the composition run's pipeline sequence in decimal. A want or an apply without one is not ordered by run, nor is a run +// that is no decimal number. +func runIsNewer(want, applied string) bool { + if want == "" || applied == "" { + return true + } + w, err1 := strconv.ParseUint(want, 10, 64) + p, err2 := strconv.ParseUint(applied, 10, 64) + if err1 != nil || err2 != nil { + return true + } + return w > p +} + // ranFailed marks what runs of a module as failed once an apply of it failed (novox/hq issue 1966, 2026-11-08): a failed // apply may have replaced some of its resources (distribution's store container) before it stopped, so what ran is no // longer whole, and a want of it again (a put back) is applied rather than taken as running. Called with a.mu held. diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index 92080f0b..0e7c6ff5 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -337,7 +337,7 @@ func TestAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) { if err := json.Unmarshal(wrawn, &later); err != nil { t.Fatal(err) } - later["form"], later["a-later-field"] = 3, "x" + later["form"], later["a-later-field"], later["run"] = 3, "x", "7" wrawn, _ = json.Marshal(later) b.wants.put(wkn, wrawn) b.idle() @@ -347,6 +347,35 @@ func TestAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) { if h := b.haves.last("web"); h.Phase != string(nodeengineclient.PhaseRunning) || h.Wait != nil || h.FP != fpn { t.Fatalf("the have is %s %q wait %+v, want running at %s with no wait (§750)", h.Phase, h.Detail, h.Wait, fpn) } + // Design 47 H2 §813 (1), H-A-355: the engine applies a composition again only when its run is newer than the one it + // applied, naming the run in its journal; a want of an older run is said and not applied. + for _, row := range []struct { + fp, run string + applied int + }{{"6", "5", 0}, {"6", "7", 0}, {"6", "8", 1}} { + before := len(b.appliedList()) + fpr := fpOf(row.fp) + ckr, crawr, digr := composition(t, "web", fpr, false, archive("a", d2)) + b.comps.put(ckr, crawr) + wkr, _ := wantFor(t, "web", fpr, digr, "") + rawr, err := bucketstest.Want(meshwants.WantsByWantNodeModuleValue{Fp: fpr, Run: row.run}) + if err != nil { + t.Fatal(err) + } + b.wants.put(wkr, rawr) + b.idle() + if got := len(b.appliedList()) - before; got != row.applied { + t.Errorf("a want of run %s after run 7: applied %d times, want %d", row.run, got, row.applied) + } + } + b.mu.Lock() + said := strings.Join(b.said, "\n") + b.mu.Unlock() + for _, want := range []string{"from run 7", "from run 8", "carries run 5, and the engine applied it from run 7"} { + if !strings.Contains(said, want) { + t.Errorf("the journal does not say %q:\n%s", want, said) + } + } } // R6-A AC2: given a kept declaration and wants and compositions equal to it, when the agent starts, nothing is applied -- 2.54.0 From b33061088a108773a249caa926c1de8f0da9aa7d Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 00:09:04 +0100 Subject: [PATCH 07/23] E3: compose every setting as the word the one settings reader takes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A module's settings reached its own process only as files its manifest named, and its tools bundles not at all. The node-engine now composes each setting the module declares as MESH_CONFIG_, its value as text, into each of its processes' environments and its slice of the tool runner's MESH_TOOL_ENV alike, and the tool runner's own into its process; the runner's drain-bound is a Go duration like every time setting. Builds: design 47 H2 §781; H-A-350 DMC-13, H-A-370, H-A-377 --- internal/compose/resolution/declaration.go | 5 ++ internal/compose/resolution/runtime.go | 63 +++++++------- internal/compose/resolution/runtime_test.go | 18 ++-- .../resolution/setting_defaults_test.go | 17 +++- internal/compose/resolution/setting_words.go | 84 +++++++++++++++++++ 5 files changed, 152 insertions(+), 35 deletions(-) create mode 100644 internal/compose/resolution/setting_words.go diff --git a/internal/compose/resolution/declaration.go b/internal/compose/resolution/declaration.go index cc071c50..8ac7537b 100644 --- a/internal/compose/resolution/declaration.go +++ b/internal/compose/resolution/declaration.go @@ -1025,6 +1025,11 @@ func resolutionCompose(r mcat.Resolution, with mcat.Rendering, h Holding, filter if err := contributionsInto(copied, m, contributing, thisMachine, with, r.Capabilities, unplaced); err != nil { return nil, err } + // And its settings, each as the word the one settings reader takes it from (design 47 H2 §781, H-A-370), after + // every placeholder pass: a value is the operator's text, never a placeholder to fill. + if err := settingWordsInto(copied, m, with.Settings[m.Module]); err != nil { + return nil, err + } copied["id"] = m.Module + "." + fmt.Sprint(resource["id"]) // A service saying what it reflects names resources within its own module, so those // are prefixed too or they would point at nothing. diff --git a/internal/compose/resolution/runtime.go b/internal/compose/resolution/runtime.go index 10f6722c..f7805a16 100644 --- a/internal/compose/resolution/runtime.go +++ b/internal/compose/resolution/runtime.go @@ -3,9 +3,10 @@ package resolution import ( "encoding/json" "fmt" + "slices" "sort" - "strconv" "strings" + "time" mcat "git.novox.be/novox/mesh-sdk/go/catalogue" ) @@ -164,6 +165,14 @@ func resolutionRuntimeProcess(r mcat.Resolution, with mcat.Rendering, h Holding) sort.Strings(restartOn) env := map[string]string{mcat.RuntimeToolModules: strings.Join(served, ","), mcat.RuntimeBrokerFile: credential.Path} + // The tool runner's own settings, as every module's process is given its own (design 47 H2 §781, H-A-370). + own, err := settingWords(*runtime, with.Settings[runtime.Module]) + if err != nil { + return nil, err + } + for word, value := range own { + env[word] = value + } if len(given) > 0 { // Marshalled from maps, whose keys encoding/json sorts: the same words, the same unit. body, err := json.Marshal(given) @@ -201,42 +210,29 @@ func resolutionRuntimeProcess(r mcat.Resolution, with mcat.Rendering, h Holding) return process, nil } -// DrainBoundSetting is the tool runner module's setting of how long, in seconds, it finishes its calls in flight once -// stopped (design 47 H2 §813 (12)); DefaultDrainBound is its default where no layer sets it (H-A-358). +// DrainBoundSetting is the tool runner module's setting of how long it finishes its calls in flight once stopped, a Go +// duration such as "30s" (design 47 H2 §813 (12), H-A-377); DefaultDrainBound is its default where no layer sets it +// (H-A-358). const ( DrainBoundSetting = "drain-bound" - DefaultDrainBound = 30 + DefaultDrainBound = 30 * time.Second ) -// drainBoundOf is the tool runner's drain bound in seconds, from its setting drain-bound, else DefaultDrainBound (design -// 47 H2 §813 (12), H-A-358): the node-engine writes its unit's stop from it. A value that is no whole number of seconds -// above zero is refused by name. +// drainBoundOf is the tool runner's drain bound in whole seconds, the declaration's process field, from its setting +// drain-bound, else DefaultDrainBound (design 47 H2 §813 (12), H-A-358, H-A-377): the node-engine writes its unit's stop +// from it. The setting is a Go duration, as every time setting is (H-A-370); part of a second counts as a whole one, so +// the bound is never shorter than the setting. A value that is no duration above zero is refused by name. func drainBoundOf(m mcat.Manifest, layers []mcat.Layer) (int, error) { v, set := settingValue(WithDefaults(m, layers), DrainBoundSetting) if !set { - return DefaultDrainBound, nil + return int(DefaultDrainBound / time.Second), nil } - var n float64 - switch x := v.(type) { - case float64: - n = x - case int: - n = float64(x) - case int64: - n = float64(x) - case string: - parsed, err := strconv.Atoi(strings.TrimSpace(x)) - if err != nil { - return 0, fmt.Errorf("%s's setting %s is %q, and it is a whole number of seconds", m.Module, DrainBoundSetting, x) - } - n = float64(parsed) - default: - return 0, fmt.Errorf("%s's setting %s is %v, and it is a whole number of seconds", m.Module, DrainBoundSetting, v) + text, ok := v.(string) + d, err := time.ParseDuration(strings.TrimSpace(text)) + if !ok || err != nil || d <= 0 { + return 0, fmt.Errorf("%s's setting %s is %v, and it is a Go duration above zero, such as \"30s\" (H-A-377)", m.Module, DrainBoundSetting, v) } - if n < 1 || n != float64(int(n)) { - return 0, fmt.Errorf("%s's setting %s is %v, and it is a whole number of seconds above zero", m.Module, DrainBoundSetting, v) - } - return int(n), nil + return int((d + time.Second - 1) / time.Second), nil } // NoRuntimeToRunError is a module of its own account with no runtime program on its node to run it from. Held says the @@ -400,7 +396,16 @@ func bundleWords(m mcat.Manifest, with mcat.Rendering) (map[string]string, error out[word] = value } } - return out, nil + // And the module's settings, as its processes are given them (design 47 H2 §781, H-A-370), for a module the runtime + // loads a bundle of. + if !slices.ContainsFunc(m.Bundles, func(b mcat.Bundle) bool { return len(b.Loads) > 0 }) { + return out, nil + } + settings, err := settingWords(m, with.Settings[m.Module]) + if err != nil { + return nil, err + } + return withSettingWords(out, settings, m.Module, "bundles' words") } // givenTo makes what a bundle's words name readable by the account the runtime runs as (novox/hq diff --git a/internal/compose/resolution/runtime_test.go b/internal/compose/resolution/runtime_test.go index f7ed2da6..8d44248a 100644 --- a/internal/compose/resolution/runtime_test.go +++ b/internal/compose/resolution/runtime_test.go @@ -125,7 +125,11 @@ func TestTheMachineRunsOneRuntimeLoadingEveryDeliveredBundle(t *testing.T) { t.Fatal(err) } - r := mcat.Resolution{Node: "anchor", Account: "ops", Modules: []mcat.Manifest{nftables, showcase, theRuntime(t)}} + // Design 47 H2 §781, H-A-370: a module's settings reach its slice of the runtime's words, and the runtime's own its process. + showcase.Settings = map[string]mcat.SettingDeclaration{"greeting": {Kind: mcat.KindPreference, Default: "hello", Why: "polite"}} + runner := theRuntime(t) + runner.Settings = map[string]mcat.SettingDeclaration{DrainBoundSetting: {Kind: mcat.KindPreference, Default: "30s", Why: "a call's length"}} + r := mcat.Resolution{Node: "anchor", Account: "ops", Modules: []mcat.Manifest{nftables, showcase, runner}} out, err := Declaration(r, with) if err != nil { t.Fatal(err) @@ -146,6 +150,9 @@ func TestTheMachineRunsOneRuntimeLoadingEveryDeliveredBundle(t *testing.T) { "showcase="+mcat.BundleRoot+"/showcase/code/tools/index.js" { t.Errorf("the runtime is told to serve %q: every loaded file, by module, and nothing a bundle runs", env[mcat.RuntimeToolModules]) } + if env["MESH_CONFIG_DRAIN_BOUND"] != "30s" || env[mcat.RuntimeToolEnv] != `{"showcase":{"MESH_CONFIG_GREETING":"hello"}}` { + t.Errorf("the settings reach the runtime as %q and its served modules as %s", env["MESH_CONFIG_DRAIN_BOUND"], env[mcat.RuntimeToolEnv]) + } if env[mcat.RuntimeBrokerFile] != "/var/lib/mesh/"+"node-tools"+"/broker" { t.Errorf("the runtime reads its credential at %q, not where the module's own secret is placed", env[mcat.RuntimeBrokerFile]) } @@ -168,16 +175,17 @@ func TestTheMachineRunsOneRuntimeLoadingEveryDeliveredBundle(t *testing.T) { if names[len(names)-1] != "node-tools"+"."+RuntimeProcessID() { t.Errorf("the runtime's process is not last: %v", names) } - // Design 47 H2 §813 (12), H-A-358: the runtime's process carries the module's drain bound, 30 s where no layer sets it, - // the value a layer sets, and a value that is no number of seconds is refused by name. - if process["drain-bound"] != DefaultDrainBound { + // Design 47 H2 §813 (12), H-A-358, H-A-377: the runtime's process carries the module's drain bound in whole seconds, 30 + // where no layer sets it, the Go duration a layer sets (part of a second a whole one), and a value that is no duration + // above zero is refused by name. + if process["drain-bound"] != 30 { t.Errorf("the runtime's process drains for %v, not the default 30 s", process["drain-bound"]) } for _, row := range []struct { value any want int words string - }{{float64(45), 45, ""}, {"60", 60, ""}, {"soon", 0, "whole number of seconds"}, {float64(0), 0, "above zero"}} { + }{{"45s", 45, ""}, {"1500ms", 2, ""}, {"60", 0, "Go duration"}, {float64(45), 0, "Go duration"}, {"0s", 0, "above zero"}} { set := with set.Settings = mcat.SettingsBy{"node-tools": {{From: "mesh", Values: map[string]any{DrainBoundSetting: row.value}}}} out, err := Declaration(r, set) diff --git a/internal/compose/resolution/setting_defaults_test.go b/internal/compose/resolution/setting_defaults_test.go index 9ec70f16..efe655c3 100644 --- a/internal/compose/resolution/setting_defaults_test.go +++ b/internal/compose/resolution/setting_defaults_test.go @@ -1,6 +1,7 @@ package resolution import ( + "fmt" "strings" "testing" @@ -64,7 +65,10 @@ func theNodeOverTheMeshOverTheDefault(t *testing.T) { // layer overrides it. func TestAComposedMachineGetsTheDefaultAndTheNodesValue(t *testing.T) { r := anAdoptedAnchor() - r.Modules = append(r.Modules, notifier()) + n := notifier() + n.Resources = append(n.Resources, map[string]any{"id": "daemon", "type": "process", "name": "notifier", + "run": []any{"/usr/bin/notifier"}, "env": map[string]any{"LANG": "C"}}) + r.Modules = append(r.Modules, n) with := anchorRendering(false) composed, err := Compose(r, with) if err != nil { @@ -83,6 +87,17 @@ func TestAComposedMachineGetsTheDefaultAndTheNodesValue(t *testing.T) { if c := byID(composed.Resources)["notifier.configuration"]["content"]; c != "font = Inter 13\nwidth = 250\n" { t.Fatalf("composed with the node's font size as %q", c) } + // Design 47 H2 §781, H-A-370: and each setting it declares reaches its process as the word the one settings reader + // takes it from, the value as text, beside the process's own words; one its own words give otherwise is refused. + env := fmt.Sprint(byID(composed.Resources)["notifier.daemon"]["env"]) + if env != "map[LANG:C MESH_CONFIG_FONT_SIZE:13 MESH_CONFIG_WIDTH:250]" { + t.Errorf("the notifier's process is given %s", env) + } + n.Resources[1]["env"] = map[string]any{"MESH_CONFIG_WIDTH": "9"} + r.Modules[len(r.Modules)-1] = n + if _, err = Compose(r, with); err == nil || !strings.Contains(err.Error(), "MESH_CONFIG_WIDTH") { + t.Errorf("a process whose own word is its setting's composed: %v", err) + } } // A default fills ${setting:…} only: it never becomes a key of a mergeable file (issue 168). diff --git a/internal/compose/resolution/setting_words.go b/internal/compose/resolution/setting_words.go new file mode 100644 index 00000000..24db159d --- /dev/null +++ b/internal/compose/resolution/setting_words.go @@ -0,0 +1,84 @@ +package resolution + +import ( + "encoding/json" + "fmt" + "sort" + + stdio "git.novox.be/novox/mesh-sdk/go" + mcat "git.novox.be/novox/mesh-sdk/go/catalogue" +) + +// settingWords is every setting m declares that a layer over it sets, its default among them, as the word the one +// settings reader takes it from (design 47 H2 §781, H-A-370): stdio.SettingWord(), MESH_CONFIG_, holding the +// value as text (a duration as "10m", a number as a program reads it, a list or an object as JSON). Composed alike into +// each of m's processes' environments and into m's slice of the tool runner's MESH_TOOL_ENV. Nil when it sets none. +func settingWords(m mcat.Manifest, layers []mcat.Layer) (map[string]string, error) { + keys := declaredConfig(m) + sort.Strings(keys) + var out map[string]string + for _, key := range keys { + value, set := settingValue(WithDefaults(m, layers), key) + if !set { + continue + } + text := plainly(value) + switch value.(type) { + case map[string]any, []any: + raw, err := json.Marshal(value) + if err != nil { + return nil, fmt.Errorf("%s's setting %s cannot be written as text: %w", m.Module, key, err) + } + text = string(raw) + } + if out == nil { + out = map[string]string{} + } + out[stdio.SettingWord(key)] = text + } + return out, nil +} + +// withSettingWords is words with each of the setting words laid in, refusing a word the module's own words give +// another value: a module's settings reach its code under one word each (H-A-370). +func withSettingWords(words, settings map[string]string, module, where string) (map[string]string, error) { + for word, value := range settings { + if was, had := words[word]; had && was != value { + return nil, fmt.Errorf("%s's %s gives %s the value %q, and the word is its setting's, composed as %q (design 47 H2 §781)", + module, where, word, was, value) + } + if words == nil { + words = map[string]string{} + } + words[word] = value + } + return words, nil +} + +// settingWordsInto lays m's setting words into a process resource's environment (H-A-370); any other resource is left. +func settingWordsInto(resource map[string]any, m mcat.Manifest, layers []mcat.Layer) error { + if fmt.Sprint(resource["type"]) != "process" { + return nil + } + settings, err := settingWords(m, layers) + if err != nil || len(settings) == 0 { + return err + } + env, _ := resource["env"].(map[string]any) + words := map[string]string{} + for k, v := range env { + words[k] = fmt.Sprint(v) + } + if _, err := withSettingWords(words, settings, m.Module, fmt.Sprintf("process %v", resource["id"])); err != nil { + return err + } + filled := map[string]any{} + for k, v := range env { + filled[k] = v + } + for word, value := range settings { + filled[word] = value + } + resource["env"] = filled + return nil +} -- 2.54.0 From f5dcea2f10bf9403a6ebabba2c07338433accf00 Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 00:10:01 +0100 Subject: [PATCH 08/23] E2: take a compose-candidate ask once by its id MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The holder of mesh-wants asks each node-engine compose-candidate as a kept call, so the same ask may come again on a transport fault. The engine reads the ask id from the request header, keeps it in its own state taken for compose-ask-bound (process.StateOver over the link it serves its seat on), and a repeat while the ask's run goes joins that run and gets the answer composed once; a repeat after the run ended is composed again, since the verb is a read and no answer is kept. The manifest declares taken with its 8 MiB cap. Builds: design 47 H2 §775, §820; H-A-351, H-A-364, H-A-383 --- cmd/mesh-host/engineseat.go | 7 +- cmd/mesh-host/nodeagent.go | 2 + cmd/mesh-host/nodeagent_integration_test.go | 4 +- cmd/mesh-host/recovery_integration_test.go | 17 +++- internal/link/engineseat.go | 16 ++-- internal/link/handacts.go | 5 +- internal/link/handover_test.go | 16 +++- internal/link/taken.go | 65 +++++++++++++++ internal/selfcompose/candidate.go | 87 +++++++++++++++++++-- internal/selfcompose/candidate_test.go | 83 +++++++++++++++++--- internal/selfcompose/selfcompose.go | 3 + internal/selfcompose/shadow.go | 2 + module.json | 6 ++ packaging/bounds_state_test.go | 30 ------- packaging/operator_keys_test.go | 8 +- 15 files changed, 282 insertions(+), 69 deletions(-) create mode 100644 internal/link/taken.go delete mode 100644 packaging/bounds_state_test.go diff --git a/cmd/mesh-host/engineseat.go b/cmd/mesh-host/engineseat.go index b806028b..02d5ef00 100644 --- a/cmd/mesh-host/engineseat.go +++ b/cmd/mesh-host/engineseat.go @@ -428,8 +428,9 @@ func packagesFrom(node string, session *link.Session, composer *atomic.Pointer[s // nec.AnswerBound, selfcompose candidateWithin). The answer is // the seat's shape (nodeengine.ComposeCandidateAnswer), checked as it is encoded; a node whose shadow does not run yet // answers unready, which the checker takes as no answer. -func composeCandidateFrom(node string, shadow *atomic.Pointer[selfcompose.Shadow]) func(candidate string, input bool, call string, line buscalls.ChunkLine) (any, error) { - return func(candidate string, input bool, call string, line buscalls.ChunkLine) (any, error) { +// An ask carrying an id is taken once by it (design 47 H2 §775, H-A-364). +func composeCandidateFrom(node string, shadow *atomic.Pointer[selfcompose.Shadow]) func(candidate string, input bool, call, askID string, line buscalls.ChunkLine) (any, error) { + return func(candidate string, input bool, call, askID string, line buscalls.ChunkLine) (any, error) { ask := nodeengine.ComposeCandidateInput{Candidate: candidate, Input: input, Call: call} if _, err := nec.EncodeAsk(ask); err != nil { return nil, err @@ -442,7 +443,7 @@ func composeCandidateFrom(node string, shadow *atomic.Pointer[selfcompose.Shadow } else { ctx, cancel := context.WithTimeout(context.Background(), nec.AnswerBound) defer cancel() - a = s.ComposeCandidate(ctx, ask) + a = s.ComposeCandidate(ctx, ask, askID) } return answerComposeCandidate(a, candidate, input, call, line) } diff --git a/cmd/mesh-host/nodeagent.go b/cmd/mesh-host/nodeagent.go index 92c0b224..7c77f6b2 100644 --- a/cmd/mesh-host/nodeagent.go +++ b/cmd/mesh-host/nodeagent.go @@ -1241,6 +1241,8 @@ func composerEnv(session *link.Session, node string, say func(string), hooks com return session.AskSeat(ctx, nodepacketfilter.Seat, nodepacketfilter.VerbAllowed, nodepacketfilter.AllowedInput{}, within) } env.ComposeAskBound = composeAskBound() + // And the state taken, where an ask of the seat's verbs is taken once by its id (design 47 H2 §775, H-A-364). + env.Taken = session.TakeOnce return env } diff --git a/cmd/mesh-host/nodeagent_integration_test.go b/cmd/mesh-host/nodeagent_integration_test.go index 067c13c6..9ec999b9 100644 --- a/cmd/mesh-host/nodeagent_integration_test.go +++ b/cmd/mesh-host/nodeagent_integration_test.go @@ -866,7 +866,7 @@ func h8candidate(t *testing.T, b *itBed, fp, running string) { before, _ := b.composed.Status() // A-237c: asked with input and no call token (the checker's, until G removes it, G-6 §321) an input past what one answer carries // is refused; asked with a token it is sent in chunks through the engine's call, whatever its size (A-237b). - if over, err := composeCandidateFrom(itNode, &shadowNow)(key, true, "", nil); err != nil { + if over, err := composeCandidateFrom(itNode, &shadowNow)(key, true, "", "", nil); err != nil { t.Fatal(err) } else if a, err := nec.DecodeAnswer(over.(json.RawMessage)); err != nil || a.Verdict != nec.Refused || !strings.Contains(a.Refused, "an answer on the bus carries") || a.Input != nil { t.Errorf("an input over the inline bound asked with no token answered %+v (%v)", a, err) @@ -900,7 +900,7 @@ func h8candidate(t *testing.T, b *itBed, fp, running string) { if len(file) <= 900<<10 || !json.Valid(file) { t.Errorf("the chunks held %d bytes, want a JSON input over 900 KiB", len(file)) } - got, err := composeCandidateFrom(itNode, &shadowNow)(key, false, "", nil) + got, err := composeCandidateFrom(itNode, &shadowNow)(key, false, "", "", nil) if err != nil { t.Fatal(err) } diff --git a/cmd/mesh-host/recovery_integration_test.go b/cmd/mesh-host/recovery_integration_test.go index c9def26a..70956784 100644 --- a/cmd/mesh-host/recovery_integration_test.go +++ b/cmd/mesh-host/recovery_integration_test.go @@ -36,9 +36,9 @@ import ( // says the events; the grants part composes the node's subjects from the manifest, so the test adds them to the node's grant. func TestNatsTheRecoveryStepAsksHearsBoundsAndCatchesUpOverTheBus(t *testing.T) { perms := nodegrant.For(itNode) - perms.Publish = append(perms.Publish, "$JS.API.>", "$KV.mesh-host_bounds.>", "mesh.seat.mesh-recovery.call.*.node~"+itNode, + perms.Publish = append(perms.Publish, "$JS.API.>", "$KV.mesh-host_bounds.>", "$KV."+link.TakenBucket+".>", "mesh.seat.mesh-recovery.call.*.node~"+itNode, "mesh.mod.db.tool.rebuild."+itNode) - perms.Subscribe = append(perms.Subscribe, "mesh.seat.mesh-recovery.event.>", "$KV.mesh-host_bounds.>", "_INBOX.>", "$JS.ACK.>", "$JS.FC.>") + perms.Subscribe = append(perms.Subscribe, "mesh.seat.mesh-recovery.event.>", "$KV.mesh-host_bounds.>", "$KV."+link.TakenBucket+".>", "_INBOX.>", "$JS.ACK.>", "$JS.FC.>") b := newItBedAs(t, perms) ctx := context.Background() @@ -52,8 +52,10 @@ func TestNatsTheRecoveryStepAsksHearsBoundsAndCatchesUpOverTheBus(t *testing.T) if err != nil { t.Fatal(err) } - if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: link.BoundsBucket, History: 1, LimitMarkerTTL: time.Second}); err != nil { - t.Fatal(err) + for _, bucket := range []string{link.BoundsBucket, link.TakenBucket} { + if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: bucket, History: 1, LimitMarkerTTL: time.Second}); err != nil { + t.Fatal(err) + } } say := func(act, outcome string) { raw, _ := json.Marshal(meshrecovery.RestoredEvent{Act: act, Module: "db", Kept: "cache", Outcome: outcome, At: time.Now().UTC()}) @@ -133,6 +135,13 @@ func TestNatsTheRecoveryStepAsksHearsBoundsAndCatchesUpOverTheBus(t *testing.T) say("old", meshrecovery.RestoredEventOutcomeFailed) // said before anyone listens: the last message of the subject session := b.startSession() r := recoveryEnv(session, nil) + // Design 47 H2 §775, H-A-364: over the same session, an ask of the seat is taken once in the state taken: the first time, + // and never again within its bound. + for i, want := range []bool{true, false} { + if took, err := session.TakeOnce(nodeengine.Seat, "ask-1", time.Minute); err != nil || took != want { + t.Fatalf("take %d of ask-1: %v, %v; want %v", i+1, took, err, want) + } + } events, stop, err := r.Hear(ctx, "restored", "db", "cache") if err != nil { diff --git a/internal/link/engineseat.go b/internal/link/engineseat.go index 5551322f..2f110b91 100644 --- a/internal/link/engineseat.go +++ b/internal/link/engineseat.go @@ -57,6 +57,9 @@ type EngineCall struct { // Line is the link's bus connection, which a verb marked chunks sends its answer's file on (buscalls.SeatChunks.Send); nil // where the call did not come over a live link. Line buscalls.ChunkLine + // Ask is the id of the ask the call carried in the header stdio.AskHeader, by which the verb takes it once (design 47 H2 + // §775, H-A-351, H-A-364); empty when it carried none. + Ask string } // EngineFunc answers one call: its result, or why it is refused. @@ -75,8 +78,9 @@ func CallerOfSubject(subject, verb, node string) string { // MaxEngineCall bounds a call's arguments: a path, an access and a few words. const MaxEngineCall = 16 << 10 -// AnswerEngineCall is the envelope one call is answered with: the verb's result, or its refusal in words. -func AnswerEngineCall(handle EngineFunc, verb, node, subject string, body []byte) []byte { +// AnswerEngineCall is the envelope one call is answered with: the verb's result, or its refusal in words. ask is the id +// the call carried in the header stdio.AskHeader. +func AnswerEngineCall(handle EngineFunc, verb, node, subject, ask string, body []byte) []byte { envelope := map[string]any{"node": node} say := func() []byte { raw, err := json.Marshal(envelope) @@ -99,7 +103,7 @@ func AnswerEngineCall(handle EngineFunc, verb, node, subject string, body []byte return say() } } - result, err := handle(EngineCall{Verb: verb, Caller: CallerOfSubject(subject, verb, node), Args: args}) + result, err := handle(EngineCall{Verb: verb, Caller: CallerOfSubject(subject, verb, node), Args: args, Ask: ask}) if err != nil { envelope["error"] = err.Error() } else { @@ -200,7 +204,7 @@ const apartAtOnce = 4 func EngineAnswer(handle EngineFunc, verb, node string, apart chan struct{}) micro.HandlerFunc { return func(r micro.Request) { if !answeredApart[verb] { - _ = r.Respond(AnswerEngineCall(handle, verb, node, r.Subject(), r.Data())) + _ = r.Respond(AnswerEngineCall(handle, verb, node, r.Subject(), r.Headers().Get(stdio.AskHeader), r.Data())) return } select { @@ -211,10 +215,10 @@ func EngineAnswer(handle EngineFunc, verb, node string, apart chan struct{}) mic _ = r.Respond(raw) return } - subject, data := r.Subject(), r.Data() + subject, ask, data := r.Subject(), r.Headers().Get(stdio.AskHeader), r.Data() go func() { defer func() { <-apart }() - _ = r.Respond(AnswerEngineCall(handle, verb, node, subject, data)) + _ = r.Respond(AnswerEngineCall(handle, verb, node, subject, ask, data)) }() } } diff --git a/internal/link/handacts.go b/internal/link/handacts.go index cbea5eb1..18a44c91 100644 --- a/internal/link/handacts.go +++ b/internal/link/handacts.go @@ -192,7 +192,8 @@ type HandActs struct { // module, applying and writing nothing; with input, also the composition input it composed from (the verb // compose-candidate, ADR 0593 §7). // call is the caller's token for the chunks the input is sent in (A-237b) and line the connection they go on; with no token the input is inline. - ComposeCandidate func(candidate string, input bool, call string, line buscalls.ChunkLine) (any, error) + // ask is the id of the ask, taken once (design 47 H2 §775, H-A-364). + ComposeCandidate func(candidate string, input bool, call, ask string, line buscalls.ChunkLine) (any, error) // ManifestReads is what this engine states it reads of a manifest and when its record last carried them (the verb // manifest-reads, novox/hq ADR 0618 §3). ManifestReads func() ([]string, time.Time) @@ -330,7 +331,7 @@ func (h *HandActs) Call(c EngineCall) (any, error) { if b, ok := c.Args["input"].(bool); ok { input = b } - return h.ComposeCandidate(arg("candidate"), input, arg("call"), c.Line) + return h.ComposeCandidate(arg("candidate"), input, arg("call"), c.Ask, c.Line) case ActManifestReads: if h.ManifestReads == nil { return nil, errors.New("this engine states no manifest reads yet: its node agent has not started") diff --git a/internal/link/handover_test.go b/internal/link/handover_test.go index 3b502ed8..1ca0b771 100644 --- a/internal/link/handover_test.go +++ b/internal/link/handover_test.go @@ -343,7 +343,7 @@ func TestALinkThatHearsHandOversIsGivenTheQueues(t *testing.T) { if !ok { body = `{}` } - if got := string(AnswerEngineCall(h.Call, row.verb, "n1", subject, []byte(body))); !strings.Contains(got, row.want) || + if got := string(AnswerEngineCall(h.Call, row.verb, "n1", subject, "", []byte(body))); !strings.Contains(got, row.want) || !strings.Contains(got, `"node":"n1"`) { t.Errorf("%s on %s: %s", row.verb, row.subject, got) } @@ -360,8 +360,10 @@ func TestALinkThatHearsHandOversIsGivenTheQueues(t *testing.T) { t.Run("two asks of compose-candidate at once are answered side by side", func(t *testing.T) { var mu sync.Mutex arrived, both := 0, make(chan struct{}) + var asks []string handle := func(c EngineCall) (any, error) { mu.Lock() + asks = append(asks, c.Ask) if arrived++; arrived == 2 { close(both) } @@ -376,13 +378,18 @@ func TestALinkThatHearsHandOversIsGivenTheQueues(t *testing.T) { answered := make(chan string, 2) answer := EngineAnswer(handle, ActComposeCandidate, "n1", make(chan struct{}, 4)) for range 2 { - answer(fakeRequest{subject: EngineToolSubject(ActComposeCandidate, "n1"), answered: answered}) + answer(fakeRequest{subject: EngineToolSubject(ActComposeCandidate, "n1"), answered: answered, ask: "ask-1"}) } for range 2 { if got := <-answered; !strings.Contains(got, `"result":"together"`) { t.Errorf("an ask answered %s; want both answered side by side", got) } } + // Design 47 H2 §775, H-A-364: the ask id the call carried in its header reaches the verb, to take it once by. + if mu.Lock(); strings.Join(asks, ",") != "ask-1,ask-1" { + t.Errorf("the verb was handed the asks %v; want the header's ask-1 each time", asks) + } + mu.Unlock() full := make(chan struct{}, 1) full <- struct{}{} EngineAnswer(handle, ActComposeCandidate, "n1", full)(fakeRequest{subject: "s", answered: answered}) @@ -396,6 +403,7 @@ func TestALinkThatHearsHandOversIsGivenTheQueues(t *testing.T) { type fakeRequest struct { subject string answered chan string + ask string // the header stdio.AskHeader } func (r fakeRequest) Respond(b []byte, _ ...micro.RespondOpt) error { @@ -407,7 +415,9 @@ func (r fakeRequest) Error(string, string, []byte, ...micro.RespondOpt) error { return nil } func (r fakeRequest) Data() []byte { return []byte(`{}`) } -func (r fakeRequest) Headers() micro.Headers { return nil } +func (r fakeRequest) Headers() micro.Headers { + return micro.Headers{stdio.AskHeader: []string{r.ask}} +} func (r fakeRequest) Subject() string { return r.subject } func (r fakeRequest) Reply() string { return "_INBOX.x" } diff --git a/internal/link/taken.go b/internal/link/taken.go new file mode 100644 index 00000000..ec2e8975 --- /dev/null +++ b/internal/link/taken.go @@ -0,0 +1,65 @@ +package link + +import ( + "context" + "fmt" + "time" + + "git.novox.be/novox/mesh-sdk/go/process" + "github.com/nats-io/nats.go" + "github.com/nats-io/nats.go/jetstream" +) + +// The node-engine takes an ask once by its id (design 47 H2 §775, §820; H-A-364 (a)): the ids it took are kept in its own +// state taken, under `.`, each for the ask's bound, bound over the link it serves its seat on. + +// TakenBucket is the node-engine's state `taken`, named by its holder as every state is. +const TakenBucket = "mesh-host_" + process.TakenState + +// TakenBus is a link that binds the node-engine's state taken. +type TakenBus interface { + TakenKV(ctx context.Context) (jetstream.KeyValue, error) +} + +func takenKV(ctx context.Context, conn *nats.Conn) (jetstream.KeyValue, error) { + js, err := jetstream.New(conn) + if err != nil { + return nil, err + } + kv, err := js.KeyValue(ctx, TakenBucket) + if err != nil { + return nil, fmt.Errorf("the state %s cannot be bound: %w", TakenBucket, err) + } + return kv, nil +} + +func (l *natsLink) TakenKV(ctx context.Context) (jetstream.KeyValue, error) { return takenKV(ctx, l.conn) } +func (b OverNATS) TakenKV(ctx context.Context) (jetstream.KeyValue, error) { return takenKV(ctx, b.Conn) } + +var ( + _ TakenBus = (*natsLink)(nil) + _ TakenBus = OverNATS{} +) + +// takenWithin bounds binding the state taken. +const takenWithin = 5 * time.Second + +// TakeOnce takes the ask ask of seat once, in the state taken for bound (process.State.TakeOnce): true the first time it +// is given, false when it was taken within its bound. ErrNoLink when no link is held. +func (q *Session) TakeOnce(seat, ask string, bound time.Duration) (bool, error) { + q.init() + q.mu.Lock() + bus := q.bus + q.mu.Unlock() + t, ok := bus.(TakenBus) + if bus == nil || !ok { + return false, ErrNoLink + } + ctx, cancel := context.WithTimeout(context.Background(), takenWithin) + defer cancel() + kv, err := t.TakenKV(ctx) + if err != nil { + return false, err + } + return process.StateOver("mesh-host", process.TakenState, kv).TakeOnce(seat, ask, bound) +} diff --git a/internal/selfcompose/candidate.go b/internal/selfcompose/candidate.go index 15cbdac5..0badb931 100644 --- a/internal/selfcompose/candidate.go +++ b/internal/selfcompose/candidate.go @@ -98,10 +98,87 @@ func (r *candidateRun) said(now time.Time) (waits string, on string) { return waits, on } -// ComposeCandidate is the node's answer to ask, within candidateWithin (or ctx's deadline, if sooner). Each answer is -// said in one line, with what it waited on and for how long (issue 1126: ace, g14 and shanks answered nothing for a -// minute while nothing said why). An answer not composed within the bound is unready, naming what the node waits on. -func (s *Shadow) ComposeCandidate(ctx context.Context, ask nodeengine.ComposeCandidateInput) nodeengine.ComposeCandidateAnswer { +// askRuns are the compose-candidate runs going now, by their ask's id (design 47 H2 §775, H-A-364 (b)): compose-candidate +// is a read, so a repeat of an ask while its run goes joins that run and gets the answer it composes once, and a repeat +// after the run ended is composed again. No answer is kept. +type askRuns struct { + mu sync.Mutex + runs map[string]*askRun +} + +// askRun is one ask's run: done is closed once a holds its answer; joined counts the repeats that joined it, under the +// runs' lock. +type askRun struct { + done chan struct{} + a nodeengine.ComposeCandidateAnswer + joined int +} + +// once answers the ask id by compose, run once for every repeat of id that comes while it runs; joined says this call +// joined a run another started. A joiner whose ctx ends first answers ended's answer. +func (r *askRuns) once(ctx context.Context, id string, compose func() nodeengine.ComposeCandidateAnswer, ended func() nodeengine.ComposeCandidateAnswer) (a nodeengine.ComposeCandidateAnswer, joined bool) { + r.mu.Lock() + if run, ok := r.runs[id]; ok { + run.joined++ + r.mu.Unlock() + select { + case <-run.done: + return run.a, true + case <-ctx.Done(): + return ended(), true + } + } + if r.runs == nil { + r.runs = map[string]*askRun{} + } + run := &askRun{done: make(chan struct{})} + r.runs[id] = run + r.mu.Unlock() + defer func() { + r.mu.Lock() + delete(r.runs, id) + r.mu.Unlock() + close(run.done) + }() + run.a = compose() + return run.a, false +} + +// ComposeCandidate is the node's answer to ask, carried with the ask id id, within candidateWithin (or ctx's deadline, if +// sooner). An ask with an id is taken once (design 47 H2 §775, H-A-364): kept in the state taken for compose-ask-bound, and +// a repeat while its run goes joins that run (askRuns); an ask with none is composed as it comes. Each answer is said in one +// line, with what it waited on and for how long (issue 1126: ace, g14 and shanks answered nothing for a minute while +// nothing said why). An answer not composed within the bound is unready, naming what the node waits on. +func (s *Shadow) ComposeCandidate(ctx context.Context, ask nodeengine.ComposeCandidateInput, id string) nodeengine.ComposeCandidateAnswer { + if id == "" { + return s.composeCandidateNow(ctx, ask, "") + } + s.mu.Lock() + c := s.c + s.mu.Unlock() + a, joined := s.asked.once(ctx, id, func() nodeengine.ComposeCandidateAnswer { + took := "" + if c.env.Taken != nil { + switch first, err := c.env.Taken(nodeengine.Seat, id, c.composeAskBound()); { + case err != nil: + took = fmt.Sprintf(", not kept in taken: %v", err) + case !first: + took = ", taken before and its run ended, so composed again" + } + } + return s.composeCandidateNow(ctx, ask, " (ask "+id+took+")") + }, func() nodeengine.ComposeCandidateAnswer { + return nodeengine.ComposeCandidateAnswer{Node: c.env.Node, Candidate: ask.Candidate, Verdict: nec.Unready, + Refused: "the run of ask " + id + " this repeat joined did not end within the ask's bound"} + }) + if joined { + c.env.Say(fmt.Sprintf("compose-candidate %s (ask %s again) joined its run and answered %s", ask.Candidate, id, a.Verdict)) + } + return a +} + +// composeCandidateNow composes ask, its journal line naming its ask in about. +func (s *Shadow) composeCandidateNow(ctx context.Context, ask nodeengine.ComposeCandidateInput, about string) nodeengine.ComposeCandidateAnswer { s.mu.Lock() c := s.c s.mu.Unlock() @@ -125,7 +202,7 @@ func (s *Shadow) ComposeCandidate(ctx context.Context, ask nodeengine.ComposeCan if a.Refused != "" { words = ": " + a.Refused } - c.env.Say(fmt.Sprintf("compose-candidate %s answered %s in %s (%s)%s", ask.Candidate, a.Verdict, + c.env.Say(fmt.Sprintf("compose-candidate %s%s answered %s in %s (%s)%s", ask.Candidate, about, a.Verdict, (time.Duration(a.Took) * time.Millisecond).String(), waits, words)) return a } diff --git a/internal/selfcompose/candidate_test.go b/internal/selfcompose/candidate_test.go index 0216f65b..ba0d54eb 100644 --- a/internal/selfcompose/candidate_test.go +++ b/internal/selfcompose/candidate_test.go @@ -3,6 +3,7 @@ package selfcompose import ( "context" "encoding/json" + "runtime" "strings" "sync/atomic" "testing" @@ -84,12 +85,21 @@ func TestTheNodeComposesACandidateOnAsk(t *testing.T) { } return json.Marshal(meshcatalog.EntryAnswer{Entry: entry}) }) + // Design 47 H2 §775, H-A-364: an ask with an id is taken once in the state taken, for compose-ask-bound. + var takes []string + taken := map[string]bool{} + env.Taken = func(seat, ask string, bound time.Duration) (bool, error) { + takes = append(takes, seat+"."+ask+" "+bound.String()) + first := !taken[ask] + taken[ask] = true + return first, nil + } var handed atomic.Int64 s := NewShadow(env, func(context.Context, map[string]nodeengine.CandidateAnswer) { handed.Add(1) }) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go func() { _ = s.Run(ctx) }() - if a := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted}); a.Verdict != nec.Unready || a.Refused == "" { + if a := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted}, ""); a.Verdict != nec.Unready || a.Refused == "" { t.Errorf("a shadow not ready answered %+v", a) } place := assignedValues(t, meshmoduleassigner.Assignments{Node: "n1", Decided: meshmoduleassigner.NodeDecided{Hub: true, Address: "10.77.0.1"}, @@ -111,7 +121,7 @@ func TestTheNodeComposesACandidateOnAsk(t *testing.T) { time.Sleep(5 * time.Millisecond) } - a := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted}) + a := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted}, "") if _, err := nec.EncodeAnswer(a); err != nil { t.Fatalf("the answer does not fit the seat's shape: %v (%+v)", err, a) } @@ -120,9 +130,20 @@ func TestTheNodeComposesACandidateOnAsk(t *testing.T) { a.Own.Module != nec.NodeWord || a.Took > nec.AnswerBound.Milliseconds() { t.Errorf("an accepted candidate answered %+v", a) } + // Design 47 H2 §775, H-A-364 (b): an ask with an id is taken once; given again after its run ended it is composed again, + // to the same answer, and nothing of the answer is kept. + for range 2 { + if a := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted}, "ask-1"); a.Verdict != nec.Composed || + len(a.Modules) != 1 || a.Modules[0].Fp != fpNew { + t.Errorf("an ask with an id answered %+v", a) + } + } + if strings.Join(takes, ",") != "node-engine.ask-1 10s,node-engine.ask-1 10s" { + t.Errorf("the asks with an id were taken as %v; want node-engine.ask-1 for compose-ask-bound, each time", takes) + } // Issue 774: the input it sends the sandbox says how it composed the node (the builds), so the sandbox composes it // through the same path. - sent := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted, Input: true}) + sent := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted, Input: true}, "") var in compose.Input raw, _ := json.Marshal(sent.Input) if err := json.Unmarshal(raw, &in); err != nil || in.ComposedHow == nil || in.ComposedHow.Node != "n1" || @@ -132,43 +153,83 @@ func TestTheNodeComposesACandidateOnAsk(t *testing.T) { // A-226b: a branch pipeline's revision composes as the candidate, each module at the revision's build; one the catalog does // not hold, and a run on request's key, are refused in words. revKey, _ := nec.RevisionKey("main", 362) - rv := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: revKey}) + rv := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: revKey}, "") if rv.Verdict != nec.Composed || len(rv.Modules) != 1 || rv.Modules[0].Fp != fpNew || !rv.Modules[0].Changed { t.Errorf("a catalog revision answered %+v", rv) } noRev, _ := nec.RevisionKey("main", 999) - if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: noRev}); m.Verdict != nec.Refused || !strings.Contains(m.Refused, "holds no revision 999") { + if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: noRev}, ""); m.Verdict != nec.Refused || !strings.Contains(m.Refused, "holds no revision 999") { t.Errorf("a revision the catalog does not hold answered %+v", m) } // A-226c: a run's key reads the indexer's candidates.run- by its group, with no heads compared; one it holds none of is refused. candidateOf("run-r1", digest2) runKey, _ := nec.RunKey("r1") - if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: runKey}); m.Verdict != nec.Composed || len(m.Modules) != 1 || m.Modules[0].Fp != fpNew || !m.Modules[0].Changed { + if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: runKey}, ""); m.Verdict != nec.Composed || len(m.Modules) != 1 || m.Modules[0].Fp != fpNew || !m.Modules[0].Changed { t.Errorf("a run's key answered %+v", m) } noRun, _ := nec.RunKey("r2") - if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: noRun}); m.Verdict != nec.Refused || !strings.Contains(m.Refused, "holds no candidate") { + if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: noRun}, ""); m.Verdict != nec.Refused || !strings.Contains(m.Refused, "holds no candidate") { t.Errorf("a run the indexer holds none of answered %+v", m) } missing, _ := nec.CompositionKey("novox/x#8", "0123456789ab") - if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: missing}); !strings.Contains(m.Refused, "holds no candidate") { + if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: missing}, ""); !strings.Contains(m.Refused, "holds no candidate") { t.Errorf("a candidate the indexer does not hold answered %+v", m) } // The group's candidate moved to other heads since the ask: the node composes not the one asked, and answers // unready (no answer), naming the heads it holds. moved, _ := nec.CompositionKey("fix/940-no-retire-on-partial-read", "0123456789ab") - if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: moved}); m.Verdict != nec.Unready || + if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: moved}, ""); m.Verdict != nec.Unready || !strings.Contains(m.Refused, "heads") { t.Errorf("a candidate at other heads answered %+v", m) } ended, end := context.WithCancel(ctx) end() - if e := s.ComposeCandidate(ended, nodeengine.ComposeCandidateInput{Candidate: accepted}); e.Verdict != nec.Unready { + if e := s.ComposeCandidate(ended, nodeengine.ComposeCandidateInput{Candidate: accepted}, ""); e.Verdict != nec.Unready { t.Errorf("an ended bound answered %+v", e) } if len(state.written()) != 0 || applied.Load() != 0 || handed.Load() != 0 { t.Errorf("composing candidates wrote %v, marked %d have(s), handed %d answer(s); want nothing", state.written(), applied.Load(), handed.Load()) } + // H-A-364 (b): a repeat of an ask while its run goes joins that run and gets the answer it composes once; one whose + // bound ends first answers unready; a repeat after the run ended composes again. + t.Run("a repeat of an ask joins the run it started", func(t *testing.T) { + var runs askRuns + var composed atomic.Int64 + release, started := make(chan struct{}), make(chan struct{}) + compose := func() nodeengine.ComposeCandidateAnswer { + if composed.Add(1) == 1 { + close(started) + <-release + } + return nodeengine.ComposeCandidateAnswer{Verdict: nec.Composed} + } + ended := func() nodeengine.ComposeCandidateAnswer { return nodeengine.ComposeCandidateAnswer{Verdict: nec.Unready} } + first := make(chan bool, 1) + go func() { _, joined := runs.once(ctx, "a", compose, ended); first <- joined }() + <-started + gone, cut := context.WithCancel(ctx) + cut() + if a, joined := runs.once(gone, "a", compose, ended); !joined || a.Verdict != nec.Unready { + t.Errorf("a repeat whose bound ended answered %+v (joined %v)", a, joined) + } + again := make(chan nodeengine.ComposeCandidateAnswer, 1) + go func() { a, _ := runs.once(ctx, "a", compose, ended); again <- a }() + for joined := 0; joined < 2; runtime.Gosched() { // the cut repeat, then this one + runs.mu.Lock() + joined = runs.runs["a"].joined + runs.mu.Unlock() + } + close(release) + if joined := <-first; joined { + t.Error("the first ask joined a run") + } + if a := <-again; a.Verdict != nec.Composed || composed.Load() != 1 { + t.Errorf("a repeat while the run went answered %+v after %d composition(s); want the one", a, composed.Load()) + } + if _, joined := runs.once(ctx, "a", compose, ended); joined || composed.Load() != 2 { + t.Errorf("a repeat after the run ended joined %v, %d composition(s); want composed again", joined, composed.Load()) + } + }) // Issue 1126, 2026-11-03: off the control-node an ask of compose-candidate was not answered within a minute, and said // nothing of why. Each of its two compositions read every manifest in the mesh one by one, on copies of the shadow // that kept nothing, so every ask read them all twice again. Each manifest is now read once, before either @@ -269,7 +330,7 @@ func TestTheNodeComposesACandidateOnAsk(t *testing.T) { } var a nodeengine.ComposeCandidateAnswer for range tc.asks { - a = s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: key}) + a = s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: key}, "") } if a.Verdict != tc.verdict || !strings.Contains(a.Refused, tc.words) { t.Errorf("answered %s %q; want %s with %q", a.Verdict, a.Refused, tc.verdict, tc.words) diff --git a/internal/selfcompose/selfcompose.go b/internal/selfcompose/selfcompose.go index 7b12cccb..0850f3a3 100644 --- a/internal/selfcompose/selfcompose.go +++ b/internal/selfcompose/selfcompose.go @@ -153,6 +153,9 @@ type Env struct { // ComposeAskBound is the setting `compose-ask-bound`: how long a compose waits for allowed; DefaultComposeAskBound when 0 // (design 08 control-verbs §1, H-A-314 (5)). ComposeAskBound time.Duration + // Taken takes an ask of the seat seat once by its id (design 47 H2 §775, H-A-364 (a)): kept in the node-engine's state + // `taken` under `.` for bound; false when it was taken before. Nil keeps nothing. + Taken func(seat, ask string, bound time.Duration) (bool, error) // Registry asks the registry seats' verb versions (oci-artifact-registry, container-image-registry) in the engine's own // name: a want naming its version is resolved to its artifacts' digests through it (design 47 G A-430a). Registry meshcatalogclient.Call diff --git a/internal/selfcompose/shadow.go b/internal/selfcompose/shadow.go index 506efd1b..2eae3305 100644 --- a/internal/selfcompose/shadow.go +++ b/internal/selfcompose/shadow.go @@ -68,6 +68,8 @@ type Shadow struct { entryMoved chan struct{} // ready says this run read every input once: the verb compose-candidate composes only then (ComposeCandidate). ready atomic.Bool + // asked are the compose-candidate runs going now, by their ask's id (H-A-364 (b)). + asked askRuns } // answeredAt is what one proposal's answer was composed at: its keys' revisions, by node, and the changes of each input. diff --git a/module.json b/module.json index 8f6929b1..52b30be5 100644 --- a/module.json +++ b/module.json @@ -93,6 +93,12 @@ "name": "bounds", "history": 1, "key-ttl": true + }, + { + "name": "taken", + "history": 1, + "key-ttl": true, + "max-mib": 8 } ], "config": { diff --git a/packaging/bounds_state_test.go b/packaging/bounds_state_test.go deleted file mode 100644 index d92beab9..00000000 --- a/packaging/bounds_state_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package packaging_test - -import ( - "os" - "testing" - - "git.novox.be/novox/mesh-sdk/go/catalogue" -) - -// The node-engine's waits run against bound keys with their own time to live, in its old section as its other states are -// (design 47 G A-92, §560, §627): the manifest declares the state bounds with a lifetime per key. -func TestTheManifestDeclaresTheBoundsStateWithAKeyLifetime(t *testing.T) { - raw, err := os.ReadFile("../module.json") - if err != nil { - t.Fatal(err) - } - m, err := catalogue.Decode(raw) - if err != nil { - t.Fatalf("the manifest no longer parses: %v", err) - } - for _, s := range m.State { - if s.Name == "bounds" { - if !s.KeyTTL || s.History != 1 { - t.Fatalf("the state bounds is %+v: one value a key, each key with its own lifetime", s) - } - return - } - } - t.Fatal("the manifest declares no state bounds") -} diff --git a/packaging/operator_keys_test.go b/packaging/operator_keys_test.go index b29841a8..f13e9455 100644 --- a/packaging/operator_keys_test.go +++ b/packaging/operator_keys_test.go @@ -128,11 +128,13 @@ func TestTheManifestConsumesTheBackupEvent(t *testing.T) { // ADR 0565 clause 6: and the state packages, one key per node, its compositions' declared packages, read by pacman. // ADR 0564 §2, ADR 0636 §1: and the state findings, the node's finding that it waits for the seat list (no TTL: the // finding stays until the first full read deletes its key). - // Design 47 G A-92: and the state bounds, each key a wait's bound with its own lifetime (packaging/bounds_state_test.go). - if len(parsed.State) != 5 || parsed.State[0].Name != "health" || parsed.State[0].TTLSeconds != 0 || + // Design 47 G A-92: and the state bounds, each key a wait's bound with its own lifetime, one value a key. + // Design 47 H2 §775, §820, H-A-364: and the state taken, the asks taken once, each key for its ask's bound, 8 MiB. + if len(parsed.State) != 6 || parsed.State[0].Name != "health" || parsed.State[0].TTLSeconds != 0 || parsed.State[1].Name != "findings" || parsed.State[1].TTLSeconds != 0 || parsed.State[2].Name != "data" || parsed.State[2].TTLSeconds != 0 || parsed.State[3].Name != "packages" || - parsed.State[3].TTLSeconds != 0 || parsed.State[4].Name != "bounds" { + parsed.State[3].TTLSeconds != 0 || parsed.State[4].Name != "bounds" || !parsed.State[4].KeyTTL || parsed.State[4].History != 1 || + parsed.State[5].Name != "taken" || !parsed.State[5].KeyTTL || parsed.State[5].History != 1 || parsed.State[5].MaxMiB != 8 { t.Fatalf("the manifest declares the state %+v", parsed.State) } } -- 2.54.0 From fea6836f9eb96e696c7f1d8ced080b8ce8bf1edd Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 00:11:18 +0100 Subject: [PATCH 09/23] E6b: cut a derived rule's comment to nftables' 128 bytes with a count MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit nftables refuses a rule comment past 128 bytes, and with it the whole table, so a port shared by enough modules took every opening down. The comment is a label: past the bound its module list is cut with a count of the rest; the whole list stands in the table's lines above the rule. Builds: design 47 H2 §813 (4); H-A-357, H-A-384 (1) --- internal/compose/resolution/filtering.go | 17 ++++++++++++++--- .../compose/resolution/localnetwork_test.go | 10 ++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/internal/compose/resolution/filtering.go b/internal/compose/resolution/filtering.go index e3bdab86..864f4071 100644 --- a/internal/compose/resolution/filtering.go +++ b/internal/compose/resolution/filtering.go @@ -154,12 +154,23 @@ var scopeWords = map[string]string{ mcat.FromLocalNetwork: "local-network", } +// commentMost is the most bytes nftables takes in a rule's comment; a longer one refuses the whole table. +const commentMost = 128 + // derivedComment is the one comment of a derived accept rule, `derived / scope // `, with the space before it (design 47 H2 §813 (4), H-A-357). It carries no mark: -// the table is loaded whole, never reconciled rule by rule. +// the table is loaded whole, never reconciled rule by rule. The comment is a label: past commentMost the module list is +// cut with a count of the rest, `derived a,b,+4 tcp/443 scope any`, and the whole list stands in the table's lines +// above the rule (H-A-384 (1)). func derivedComment(rule mcat.Rule) string { - return fmt.Sprintf(" comment %q", fmt.Sprintf("derived %s %s/%d scope %s", - strings.Join(rule.Because, ","), rule.Protocol, rule.Port, scopeWords[rule.From])) + label := func(names []string) string { + return fmt.Sprintf("derived %s %s/%d scope %s", strings.Join(names, ","), rule.Protocol, rule.Port, scopeWords[rule.From]) + } + text := label(rule.Because) + for kept := len(rule.Because) - 1; len(text) > commentMost && kept >= 0; kept-- { + text = label(append(slices.Clone(rule.Because[:kept]), fmt.Sprintf("+%d", len(rule.Because)-kept))) + } + return fmt.Sprintf(" comment %q", text) } // widest drops a rule that another already covers. diff --git a/internal/compose/resolution/localnetwork_test.go b/internal/compose/resolution/localnetwork_test.go index a289eede..8fe35db7 100644 --- a/internal/compose/resolution/localnetwork_test.go +++ b/internal/compose/resolution/localnetwork_test.go @@ -84,6 +84,9 @@ func TestALocalNetworkPortIsAdmittedFromItsNetworksAndTheMesh(t *testing.T) { {Port: 1883, Protocol: "tcp", From: mcat.FromLocalNetwork, Because: []string{"mosquitto"}}, {Port: 5432, Protocol: "tcp", From: mcat.FromMesh, Because: []string{"postgres"}}, {Port: 443, Protocol: "tcp", From: mcat.FromEverywhere, Because: []string{"caddy", "forge"}}, + // A shared port whose module list would pass nftables' 128 bytes: the label is cut with a count (H-A-384 (1)). + {Port: 8443, Protocol: "tcp", From: mcat.FromEverywhere, Because: []string{"mesh-delivery-pipeline", "mesh-delivery-builder", + "mesh-delivery-assigner", "mesh-delivery-indexer", "mesh-delivery-gate", "mesh-delivery-teller"}}, } local := CountedLocalNetworks(judged(t)) out := AsNftablesWithLocal(rules, []string{"10.10.0.1", "10.10.0.4"}, false, nil, @@ -102,11 +105,18 @@ func TestALocalNetworkPortIsAdmittedFromItsNetworksAndTheMesh(t *testing.T) { `tcp dport 5432 accept comment "derived postgres tcp/5432 scope private-network"`, "\t\ttcp dport 443 accept comment \"derived caddy,forge tcp/443 scope any\"\n", "\t\tct original proto-dst 443 accept comment \"derived caddy,forge tcp/443 scope any\"\n", + `tcp dport 8443 accept comment "derived mesh-delivery-pipeline,mesh-delivery-builder,mesh-delivery-assigner,mesh-delivery-indexer,+2 tcp/8443 scope any"`, + "\t\t# mesh-delivery-teller\n", } { if !strings.Contains(out, want) { t.Errorf("the rule set lacks %q:\n%s", want, out) } } + for _, line := range strings.Split(out, "\n") { + if _, comment, ok := strings.Cut(line, ` comment "`); ok && len(strings.TrimSuffix(comment, `"`)) > commentMost { + t.Errorf("a comment passes nftables' %d bytes: %s", commentMost, line) + } + } if strings.Contains(out, "203.0.113") { t.Errorf("the public subnet reached the rule set:\n%s", out) } -- 2.54.0 From f4f5615bfbb6d05423bc8cdc33bc4ded6550e944 Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 00:19:47 +0100 Subject: [PATCH 10/23] E4b: keep the run a module was applied from in its have MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The engine kept the applied run in its memory only, so a restarted engine applied an older run's want again. The have, the record of what the engine applied, carries the run (the node-engine seat's form 2): the engine reads it from the have before it applies a want that carries one, a write that names none keeps the last have's, and every have is written at the seat's form. Builds: design 47 H2 §813 (1); H-A-355, H-A-384 (2), H-A-388 (1) --- cmd/mesh-host/nodeagent.go | 4 +-- internal/agent/agent.go | 48 +++++++++++++++++++++++++----------- internal/agent/agent_test.go | 22 ++++++++++++++++- internal/link/have.go | 2 ++ internal/link/have_test.go | 11 +++++---- internal/link/messages.go | 2 ++ 6 files changed, 67 insertions(+), 22 deletions(-) diff --git a/cmd/mesh-host/nodeagent.go b/cmd/mesh-host/nodeagent.go index 7c77f6b2..f5a4c0a1 100644 --- a/cmd/mesh-host/nodeagent.go +++ b/cmd/mesh-host/nodeagent.go @@ -109,7 +109,7 @@ func (h sessionHaves) ReadErr(ctx context.Context, module string) (agent.Have, b return agent.Have{}, false, err } return agent.Have{Module: module, FP: got.Fp, Composed: got.Composed, Phase: string(got.Phase), Detail: got.Detail, - Sealed: got.SealedAt, Wait: got.Wait}, true, nil + Sealed: got.SealedAt, Wait: got.Wait, Run: got.Run}, true, nil } func (h sessionHaves) Write(ctx context.Context, x agent.Have) { @@ -126,7 +126,7 @@ func (h sessionHaves) Write(ctx context.Context, x agent.Have) { } h.session.NoteModule(ctx, link.ModuleFact{Module: x.Module, FP: x.FP, Composed: x.Composed, Phase: phase, Failed: phase == string(nodeengineclient.PhaseFailed), Detail: shorten(x.Detail), Judgement: x.Judgement, Waits: x.Waits, - BuildAlone: x.BuildAlone, Kept: x.Kept, Sealed: x.Sealed, PullWait: x.PullWait, Wait: x.Wait}) + BuildAlone: x.BuildAlone, Kept: x.Kept, Sealed: x.Sealed, PullWait: x.PullWait, Wait: x.Wait, Run: x.Run}) } func (h sessionHaves) Removed(ctx context.Context, module string) { diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 754478f7..e4beb02a 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -78,6 +78,10 @@ type Have struct { PullWait *nodeengine.PullWait // Wait is the hold or wait the have says, in the recovery wait with its ask-at and act (design 47 G §560). Wait *nodeengine.Wait + // Run is the composition run the module was applied from, its pipeline sequence in decimal (design 47 H2 §813 (1), + // H-A-384 (2), H-A-388; nodeengine.HaveByNodeModuleValue.Run): kept in the have, so a restarted engine applies no + // older run again. A write that names none keeps the one the module's last have said (writeHave). + Run string } // Haves is the node's have bucket as the agent uses it. @@ -250,9 +254,6 @@ type Agent struct { // applied is the composition each module was last applied from: a revision a want named from the key's history is // not the key's latest value, and what it holds is still held out of the others' applies. applied map[string]compNow - // appliedRun is, of each module applied from a want that carried run, that run: the composition run's pipeline sequence - // in decimal (design 47 H2 §813 (1), H-A-355). A want whose run is not newer is not applied again. - appliedRun map[string]string // had is, for each module whose have names a composition the bucket keeps (its latest value or a revision), that // composition, read once at the start (loadHad): what runs of a module the agent has not taken yet, ahead of the kept // declaration (issue 924). @@ -345,7 +346,7 @@ func New(env Env) *Agent { if env.Say == nil { env.Say = func(string) {} } - return &Agent{env: env, wants: map[string]wantNow{}, comps: map[string]compNow{}, running: map[string]nodeengine.HaveByNodeModuleValue{}, applied: map[string]compNow{}, appliedRun: map[string]string{}, had: map[string]compNow{}, keptData: map[string]bool{}, + return &Agent{env: env, wants: map[string]wantNow{}, comps: map[string]compNow{}, running: map[string]nodeengine.HaveByNodeModuleValue{}, applied: map[string]compNow{}, had: map[string]compNow{}, keptData: map[string]bool{}, attempt: map[string]attempt{}, checked: map[string]bool{}, prior: map[string]bool{}, said: map[string]string{}, waited: map[string]string{}, notComposed: map[string]notComposedMark{}, pulls: map[string]*pullWait{}, settledAt: map[string]time.Time{}, settledSeq: map[string]int{}, retry: make(chan []string, 8), reconcile: make(chan []string, 64), failedAgain: make(chan string, 8), tries: map[string]int{}, again: make(chan againAsk, 64), @@ -737,11 +738,17 @@ func (a *Agent) writeHave(ctx context.Context, h Have) { h.Kept = a.kept[h.Module] a.mu.Unlock() } - if h.Composed == "" && h.Module != NodeModule { - if last, ok := a.env.Haves.Read(ctx, h.Module); ok && last.Composed != "" { - h.FP, h.Composed = last.FP, last.Composed - if h.Sealed == nil { - h.Sealed = last.Sealed + if (h.Composed == "" || h.Run == "") && h.Module != NodeModule { + if last, ok := a.env.Haves.Read(ctx, h.Module); ok { + if h.Composed == "" && last.Composed != "" { + h.FP, h.Composed = last.FP, last.Composed + if h.Sealed == nil { + h.Sealed = last.Sealed + } + } + // The run the module was applied from stays in its have until an apply from another run (H-A-384 (2)). + if h.Run == "" { + h.Run = last.Run } } } @@ -1515,6 +1522,22 @@ func (a *Agent) settleOne(ctx context.Context, module string) { } else { a.mu.Unlock() } + // Design 47 H2 §813 (1), H-A-384 (2): the run the module was applied from is its have's, never this engine's memory, so + // a restarted engine applies no older run again. Read only for a want that carries one. + appliedRun := "" + if w.Want.Run != "" { + h, found, unread := a.readHave(ctx, module) + if unread { + a.mu.Lock() + a.sayOnce("run-unread:"+module+":"+w.Want.Run, fmt.Sprintf("the want of %s carries run %s, and its have, which says "+ + "the run it was applied from, cannot be read: nothing is applied until it reads", module, w.Want.Run)) + a.mu.Unlock() + return + } + if found { + appliedRun = h.Run + } + } a.mu.Lock() r, runs := a.running[module] // A module whose last apply failed runs no composition whole, whatever it ran before (ranFailed). @@ -1548,7 +1571,7 @@ func (a *Agent) settleOne(ctx context.Context, module string) { a.mu.Unlock() return // failed already for exactly these keys: retried by the next change of either } - if was := a.appliedRun[module]; !runIsNewer(w.Want.Run, was) { + if was := appliedRun; !runIsNewer(w.Want.Run, was) { // Design 47 H2 §813 (1), H-A-355: one writer per composition key, and the engine applies again only a newer write. a.sayOnce("run:"+module+":"+w.Want.Run, fmt.Sprintf("the want of %s carries run %s, and the engine applied it from run %s, "+ "which is not older: nothing is applied", module, w.Want.Run, was)) @@ -1841,9 +1864,6 @@ func (a *Agent) apply(ctx context.Context, module string, w wantNow, comp compNo a.running[module] = nodeengine.HaveByNodeModuleValue{Fp: fp, Composed: dig, Phase: nodeengineclient.PhaseRunning} a.applied[module] = comp run := w.Want.Run - if run != "" { - a.appliedRun[module] = run - } a.mu.Unlock() if run != "" { a.env.Say(fmt.Sprintf("applied %s from run %s", what, run)) @@ -1852,7 +1872,7 @@ func (a *Agent) apply(ctx context.Context, module string, w wantNow, comp compNo if a.env.Settled != nil { a.env.Settled(module) } - a.writeHave(ctx, Have{Module: module, FP: fp, Composed: dig, Phase: string(nodeengineclient.PhaseRunning), Detail: res.Detail}) + a.writeHave(ctx, Have{Module: module, FP: fp, Composed: dig, Phase: string(nodeengineclient.PhaseRunning), Detail: res.Detail, Run: run}) a.catchUp(ctx, module, catchUps) } diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index 0e7c6ff5..8c06ef1b 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -368,10 +368,30 @@ func TestAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) { t.Errorf("a want of run %s after run 7: applied %d times, want %d", row.run, got, row.applied) } } + // H-A-384 (2), H-A-388: the run is kept in the have, never in memory: the have names run 8, and a have an earlier life of + // the engine wrote at run 20 holds a want of run 10 back, though this one applied run 8 last. + if h := b.haves.last("web"); h.Run != "8" { + t.Errorf("the have names run %q after run 8 was applied", h.Run) + } + h := b.haves.last("web") + h.Run = "20" + b.haves.Write(context.Background(), h) + before = len(b.appliedList()) + fpr := fpOf("9") + ckr, crawr, digr := composition(t, "web", fpr, false, archive("a", d1)) + b.comps.put(ckr, crawr) + wkr, _ := wantFor(t, "web", fpr, digr, "") + rawr, _ := bucketstest.Want(meshwants.WantsByWantNodeModuleValue{Fp: fpr, Run: "10"}) + b.wants.put(wkr, rawr) + b.idle() + if got := len(b.appliedList()) - before; got != 0 { + t.Errorf("a want of run 10 after a have of run 20: applied %d times, want none", got) + } b.mu.Lock() said := strings.Join(b.said, "\n") b.mu.Unlock() - for _, want := range []string{"from run 7", "from run 8", "carries run 5, and the engine applied it from run 7"} { + for _, want := range []string{"from run 7", "from run 8", "carries run 5, and the engine applied it from run 7", + "carries run 10, and the engine applied it from run 20"} { if !strings.Contains(said, want) { t.Errorf("the journal does not say %q:\n%s", want, said) } diff --git a/internal/link/have.go b/internal/link/have.go index be776119..63d28d87 100644 --- a/internal/link/have.go +++ b/internal/link/have.go @@ -413,6 +413,8 @@ func (q *Session) writeHaves(ctx context.Context, bus Bus) { h.PullWait = f.PullWait } h.Wait = f.Wait + // The seat's form 2 carries the run the module was applied from (H-A-388). + h.Run, h.Form = f.Run, nodeengine.Form h.Health = s.healthOf(module, f) if h.Detail == "" { h.Detail = s.wordsOf(module, h.Health) diff --git a/internal/link/have_test.go b/internal/link/have_test.go index dc27c29a..94231488 100644 --- a/internal/link/have_test.go +++ b/internal/link/have_test.go @@ -256,11 +256,12 @@ func TestAnAppliedModuleIsWrittenRunningAndAFailedOneFailed(t *testing.T) { } } -// 1132/AC5: a have equal to the bucket's value is not written; a different one is written over the last revision. +// 1132/AC5: a have equal to the bucket's value is not written; a different one is written over the last revision. Each +// is written at the seat's form (H-A-388). func TestAHaveIsWrittenOnlyWhenItDiffers(t *testing.T) { l := newHaveLink() - l.put(t, "n1.a", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Build: "b-1", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) - l.put(t, "n1.b", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Build: "b-0", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) + l.put(t, "n1.a", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Form: nodeengine.Form, Build: "b-1", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) + l.put(t, "n1.b", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Form: nodeengine.Form, Build: "b-0", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) q, _ := aHaveQueue(l) q.SayFacts(context.Background(), appliedModules()) if l.kv["n1.a"].rev != 1 { @@ -711,8 +712,8 @@ func TestARefusedRemovalIsWrittenByTheNextPass(t *testing.T) { // before: one of them the new declaration lacks is written removed, one that is not in the bucket is not created. func TestARestartedNodeEngineWritesTheRemovalFromTheReportsBefore(t *testing.T) { l := newHaveLink() - l.put(t, "n1.a", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Build: "b-1", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) - l.put(t, "n1.b", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Build: "b-2", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) + l.put(t, "n1.a", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Form: nodeengine.Form, Build: "b-1", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) + l.put(t, "n1.b", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Form: nodeengine.Form, Build: "b-2", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) q, _ := aHaveQueue(l) // fresh: nothing written by this process r := onlyA() r.Before = []string{"a", "b", "c"} diff --git a/internal/link/messages.go b/internal/link/messages.go index e84f31e6..9c2490a9 100644 --- a/internal/link/messages.go +++ b/internal/link/messages.go @@ -649,4 +649,6 @@ type ModuleFact struct { PullWait *nodeengine.PullWait // Wait is the hold or wait the module has, with the ask-at and act of a recovery wait (nodeengine.HaveByNodeModuleValue.Wait, design 47 G §560). Wait *nodeengine.Wait + // Run is the composition run the module was applied from (nodeengine.HaveByNodeModuleValue.Run, design 47 H2 §813 (1), H-A-388). + Run string } -- 2.54.0 From 1c32872fccaf59e795783ed2a64b2c2f615e8087 Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 00:26:18 +0100 Subject: [PATCH 11/23] H-A-374: set a drifted directory the mesh made right at the engine's start MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ace's Node toolchain cache directory stood at 0700 against its entry's 0711 while the engine said its composition was unchanged: an unchanged composition is never applied, and the judgement reads the compositions, not the disk. Each module taken as running at the engine's start now has every directory entry its record says the mesh made given its declared owner and mode where they drifted on disk, one journal line each; one the mesh never made stays used as found and is said (issue 339). The verb composition's diff names a drifted directory the mesh made. The agent test that marks modules not composed now waits for every want it marks. Builds: design 47 H2 §813; H-A-374, H-A-392 --- cmd/mesh-host/nodeagent.go | 37 +++++++++ internal/agent/agent.go | 16 ++++ internal/agent/agent_test.go | 24 +++++- internal/agent/composition.go | 15 ++++ internal/apply/converge_dirs.go | 111 +++++++++++++++++++++++++ internal/apply/mesh_tree_found_test.go | 34 +++++++- 6 files changed, 232 insertions(+), 5 deletions(-) create mode 100644 internal/apply/converge_dirs.go diff --git a/cmd/mesh-host/nodeagent.go b/cmd/mesh-host/nodeagent.go index f5a4c0a1..7e6e8eb8 100644 --- a/cmd/mesh-host/nodeagent.go +++ b/cmd/mesh-host/nodeagent.go @@ -253,6 +253,21 @@ func awaitBackup(ctx context.Context, events <-chan []byte, node, module string, } } +// convergeDirectories gives each directory entry of runs that this node's record holds, drifted on disk, its declared +// owner and mode (apply.ConvergeDirectories, H-A-374, H-A-392): one line per directory, and one when the record or the +// composition does not read. +func convergeDirectories(statePath string, runs compositions.Composed) []string { + d, err := declarationOf(runs) + if err != nil { + return []string{fmt.Sprintf("the directories of %s are not judged at this start: its composition does not read: %v", runs.Module, err)} + } + known, err := store.Load(statePath) + if err != nil { + return []string{fmt.Sprintf("the directories of %s are not judged at this start: %v", runs.Module, err)} + } + return apply.ConvergeDirectories(d, known) +} + // declarationOf is the declaration the compositions make together: their resources, and the node's own parts when the // node's composition is among them. It is what the node judges and says its health by, and what one module's apply is // made of (with a single composition). @@ -536,6 +551,28 @@ func nodeAgent(ctx context.Context, opts options, signer ed25519.PublicKey, trus Backup: backupNode(session), // What the filling refused before this apply may be named now: the provisioner's client is told to fill // again (ace, 2026-10-25 21:17). + // A module taken as running at this start has each record-held directory entry of it given its owner and mode + // where they drifted on disk, one line each (H-A-374, H-A-392). + TakenAtStart: func(module string, runs compositions.Composed) { + for _, line := range convergeDirectories(opts.state, runs) { + say(line) + } + }, + DirectoryDrift: func(runs compositions.Composed) []agent.DriftView { + d, err := declarationOf(runs) + if err != nil { + return nil + } + known, err := store.Load(opts.state) + if err != nil { + return nil + } + var out []agent.DriftView + for _, x := range apply.DirectoryDrifts(d, known) { + out = append(out, agent.DriftView{ID: x.ID, Path: x.Path, Drift: x.Drift}) + } + return out + }, Settled: func(module string) { knockFilling(module+" settled", say) judgeWhatRunsNow(opts.state, signer) diff --git a/internal/agent/agent.go b/internal/agent/agent.go index e4beb02a..cf450d61 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -185,6 +185,13 @@ type Env struct { // them. The node-engine's filling tells the provisioner's client then to fill again what it refused (mesh-host // internal/filling Knock; ace, 2026-10-25 21:17). Nil tells nothing. Settled func(module string) + // TakenAtStart is told, outside the agent's lock, each module taken as running at this start from its have or the + // kept declaration, with no apply, and the composition it runs: the node-engine converges the owner and mode of each + // record-held directory entry of it (H-A-374, H-A-392). Nil tells nothing. + TakenAtStart func(module string, runs compositions.Composed) + // DirectoryDrift reads, for the verb composition's diff, each directory entry of runs the mesh made whose owner or + // mode on disk differ (apply.DirectoryDrifts, H-A-392). Nil reads none. + DirectoryDrift func(runs compositions.Composed) []DriftView // RunsChanged is told, outside the agent's lock, that what runs (Everything) changed other than by an apply or a // removal: once at the start, when the haves and the compositions they name are read, and each time a module is // taken as running from its have or the kept declaration. Like Settled, the filling then tells the provisioner's @@ -1700,6 +1707,7 @@ func (a *Agent) baseline(ctx context.Context, module string, w wantNow, comp com a.running[module] = nodeengine.HaveByNodeModuleValue{Fp: h.FP, Composed: h.Composed, Phase: nodeengineclient.PhaseRunning} a.mu.Unlock() a.runsChanged(module + " was taken from its have") + a.takenAtStart(module, comp.C) // Said again, so the session holds the module and its key carries the health this engine judges, // not the one an older engine left there (xorg's unknown on g14 and shanks, 2026-10-25). a.writeHave(ctx, Have{Module: module, FP: h.FP, Composed: h.Composed, @@ -1729,6 +1737,7 @@ func (a *Agent) baseline(ctx context.Context, module string, w wantNow, comp com a.running[module] = nodeengine.HaveByNodeModuleValue{Fp: w.Want.Fp, Composed: w.Composed, Phase: nodeengineclient.PhaseRunning} a.mu.Unlock() a.runsChanged(module + " was taken from the kept declaration") + a.takenAtStart(module, comp.C) a.writeHave(ctx, Have{Module: module, FP: w.Want.Fp, Composed: w.Composed, Phase: string(nodeengineclient.PhaseRunning)}) return true } @@ -1876,6 +1885,13 @@ func (a *Agent) apply(ctx context.Context, module string, w wantNow, comp compNo a.catchUp(ctx, module, catchUps) } +// takenAtStart tells TakenAtStart of a module taken as running at this start (H-A-392). +func (a *Agent) takenAtStart(module string, runs compositions.Composed) { + if a.env.TakenAtStart != nil { + a.env.TakenAtStart(module, runs) + } +} + // runIsNewer says whether a want's run orders after the run a module was applied from (design 47 H2 §813 (1)): each is // the composition run's pipeline sequence in decimal. A want or an apply without one is not ordered by run, nor is a run // that is no decimal number. diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index 8c06ef1b..71eaf3b6 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -133,6 +133,8 @@ type bed struct { said []string // settled is each module Settled was told, and settledRan whether what runs held it then. settled []string + // takenAtStart is each module TakenAtStart was told, with its composition's resource count. + takenAtStart []string settledRan []bool ag *Agent // the agent run() runs env Env @@ -179,6 +181,11 @@ func newBed(t *testing.T) *bed { } return Backup{Done: true} }, + TakenAtStart: func(m string, runs compositions.Composed) { + b.mu.Lock() + defer b.mu.Unlock() + b.takenAtStart = append(b.takenAtStart, fmt.Sprintf("%s:%d", m, len(runs.Resources))) + }, Settled: func(m string) { ran := false if b.ag != nil { @@ -420,6 +427,11 @@ func TestStartingOnWhatTheKeptDeclarationHoldsAppliesNothing(t *testing.T) { if got := b.appliedList(); len(got) != 0 { t.Fatalf("a module that already runs what the want names was applied: %v", got) } + // H-A-392: a module taken as running at the start is told with the composition it runs, for its directories' drift. + if b.mu.Lock(); !slices.Equal(b.takenAtStart, []string{"web:2"}) { + t.Errorf("taken at the start were %v; want web with its two resources", b.takenAtStart) + } + b.mu.Unlock() t.Run("starting on its own have applies nothing", testStartingOnItsOwnHaveAppliesNothing) } @@ -1907,10 +1919,11 @@ func TestTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes( b.haves.Write(context.Background(), Have{Module: "broken", FP: brokenFP, Composed: brokenDig, Phase: string(nodeengineclient.PhaseFailed), Detail: "apply: unit failed to start"}) want("broken", brokenFP, "") - eventually(t, "unread's want was not taken", func() bool { + // Every want taken before the mark, not unread's alone: fresh's taken after it was not marked (seen under -race). + eventually(t, "the wants were not taken", func() bool { b.ag.mu.Lock() defer b.ag.mu.Unlock() - return b.ag.wants["unread"].Present + return b.ag.wants["unread"].Present && b.ag.wants["fresh"].Present && b.ag.wants["broken"].Present }) b.ag.NotComposed(context.Background(), "a stand-in for web's password, again") if h := b.haves.last("unread"); h.Module != "" { @@ -1992,7 +2005,14 @@ func TestTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes( // container it recreates; the revision that runs, asked by its digest, is no move (issue 774). keep(dk, draw) keep(dk, drawMoved) + // H-A-392: and with diff, each directory the mesh made of what runs whose mode or owner on disk drifted. + b.ag.env.DirectoryDrift = func(runs compositions.Composed) []DriftView { + return []DriftView{{ID: runs.Module + ".data", Path: "/srv/db", Drift: "mode 0700, 0711 declared"}} + } view, err := b.ag.Composition(context.Background(), "db", "", true) + if len(view.Drift) != 1 || view.Drift[0].ID != "db.data" { + t.Errorf("the diff of db names the drift %+v", view.Drift) + } if err != nil || view.Have == nil || view.Have.Phase != string(nodeengineclient.PhaseWaitingYes) || view.Composition.Digest != ddigMoved || view.Runs == nil || view.Runs.Composed != ddig || view.Judged.Judgement != string(nodeengineclient.JudgedRecreates) || !view.Judged.WaitsForYes || len(view.Diff) != 1 || view.Diff[0].ID != "db.server" || view.Diff[0].Change != "changed" || diff --git a/internal/agent/composition.go b/internal/agent/composition.go index e9017838..c39bb8bd 100644 --- a/internal/agent/composition.go +++ b/internal/agent/composition.go @@ -49,6 +49,10 @@ type CompositionView struct { Judged JudgedView `json:"judged"` // Diff is every resource that differs from what runs, when asked. Diff []judge.ResourceChange `json:"diff,omitempty"` + // Drift is, when the diff is asked, each directory entry of what runs that the mesh made, as its record holds, whose + // owner or mode on disk differ from it (H-A-374, H-A-392): read-only; the engine sets it right at its next start or + // apply of the module. + Drift []DriftView `json:"drift,omitempty"` // Own is, of the node's own composition (module node), its own fields beside what runs names (issue 774: ace's // own composition dropped the provisioner client's account, and nothing read could show it). Own *OwnView `json:"own,omitempty"` @@ -302,6 +306,9 @@ func (a *Agent) Composition(ctx context.Context, module, digest string, diff boo } if diff { view.Diff = judge.ChangedResources(running, read.C) + if running != nil && a.env.DirectoryDrift != nil { + view.Drift = a.env.DirectoryDrift(*running) + } } return view, nil } @@ -341,6 +348,14 @@ func (a *Agent) revisionsOf(ctx context.Context, key string) ([]compNow, error) return out, nil } +// DriftView is one directory entry the mesh made whose owner or mode on disk differ from it, as the verb composition's +// diff names it (H-A-392): its id, its path and how, in words. +type DriftView struct { + ID string `json:"id"` + Path string `json:"path"` + Drift string `json:"drift"` +} + // CompositionDiff answers the node-engine seat's read verb composition-diff (design 47 H2 §813 (3), H-A-349 DQ-12b): one // module's composition that runs beside another revision of its composition key, given by its revision or its digest, // as the entries that differ per resource; environment entries by name, a secret's value masked. It changes nothing. diff --git a/internal/apply/converge_dirs.go b/internal/apply/converge_dirs.go new file mode 100644 index 00000000..c210a09f --- /dev/null +++ b/internal/apply/converge_dirs.go @@ -0,0 +1,111 @@ +package apply + +import ( + "errors" + "fmt" + "os" + + "git.novox.be/novox/mesh-sdk/go/declaration" + "github.com/novox/mesh-host/internal/store" +) + +// ConvergeDirectories gives each directory entry of d whose record known holds, found on disk with another owner or mode +// than declared, its declared owner and mode (design 47 H2's E lines, H-A-374, H-A-392): at the engine's start, so a +// drift lasts at most until then, and with no apply of an unchanged composition. One the mesh never made (its record used +// as found, issue 339) is left as found and said. Answered as one line per directory set right or left; a directory +// declared that is missing, that has no record, or that is as declared, says nothing. +func ConvergeDirectories(d *declaration.Declaration, known store.State) []string { + if d == nil { + return nil + } + var lines []string + for _, r := range d.Resources { + dir, ok := r.(*declaration.Directory) + if !ok { + continue + } + rec, held := known.Find(dir.ID) + if !held || rec.Type != string(declaration.TypeDirectory) { + continue + } + drift, err := directoryDrift(dir) + switch { + case errors.Is(err, os.ErrNotExist) || (err == nil && drift == ""): + continue + case err != nil: + lines = append(lines, fmt.Sprintf("%s (%s) cannot be judged at this start: %v", dir.Path, dir.ID, err)) + continue + } + out, err := applyDirectory(dir, rec, true) + switch { + case err != nil: + lines = append(lines, fmt.Sprintf("%s (%s) is %s and cannot be set right at this start: %v", dir.Path, dir.ID, drift, err)) + case out.asFound: + lines = append(lines, fmt.Sprintf("%s (%s) is %s, and is left as found at this start: %s", dir.Path, dir.ID, drift, out.Detail)) + default: + lines = append(lines, fmt.Sprintf("%s (%s) was %s, and is set right at this start", dir.Path, dir.ID, drift)) + } + } + return lines +} + +// DirectoryDrift is one directory entry the mesh made, as its record holds, whose owner or mode on disk differ from +// what is declared (H-A-392): its id, its path and how it differs, in words. +type DirectoryDrift struct { + ID string `json:"id"` + Path string `json:"path"` + Drift string `json:"drift"` +} + +// DirectoryDrifts is each directory entry of d the mesh made, by its record in known (not used as found), whose owner or +// mode on disk differ from its entry's (H-A-392): read-only, what the verb composition's diff names as drift. A directory +// that is missing, has no record, or cannot be read says nothing here. +func DirectoryDrifts(d *declaration.Declaration, known store.State) []DirectoryDrift { + if d == nil { + return nil + } + var out []DirectoryDrift + for _, r := range d.Resources { + dir, ok := r.(*declaration.Directory) + if !ok { + continue + } + if rec, held := known.Find(dir.ID); !held || rec.Type != string(declaration.TypeDirectory) || rec.AsFound { + continue + } + if drift, err := directoryDrift(dir); err == nil && drift != "" { + out = append(out, DirectoryDrift{ID: dir.ID, Path: dir.Path, Drift: drift}) + } + } + return out +} + +// directoryDrift says how a directory on disk differs from its entry's owner and mode, in words; empty when it does not. +func directoryDrift(dir *declaration.Directory) (string, error) { + mode, err := dirModeOf(dir.Mode, 0o755) + if err != nil { + return "", err + } + info, err := os.Lstat(dir.Path) + if err != nil { + return "", err + } + if !info.IsDir() { + return "", fmt.Errorf("%s is not a directory", dir.Path) + } + owned, err := ownedBy(dir.Path, dir.Owner) + if err != nil { + return "", err + } + var drift string + if dirBits(info.Mode()) != dirBits(mode) { + drift = fmt.Sprintf("mode %s, %s declared", modeText(dirBits(info.Mode())), modeText(mode)) + } + if !owned { + if drift != "" { + drift += ", and " + } + drift += fmt.Sprintf("owned by %s, %s declared", ownerText(info), dir.Owner) + } + return drift, nil +} diff --git a/internal/apply/mesh_tree_found_test.go b/internal/apply/mesh_tree_found_test.go index a3603a0a..134403a2 100644 --- a/internal/apply/mesh_tree_found_test.go +++ b/internal/apply/mesh_tree_found_test.go @@ -47,21 +47,49 @@ func TestADirectoryInTheMeshsOwnTreeMadeByTheEngineIsTheMeshs(t *testing.T) { if info, _ := os.Stat(made); info.Mode().Perm() != 0o750 { t.Errorf("it was not given its declared mode: %04o", info.Mode().Perm()) } + // H-A-374, H-A-392: a record-held directory whose mode drifted on disk is set right at the engine's start, with one + // line, though its composition is unchanged; as declared, it says nothing. + if err := os.Chmod(made, 0o700); err != nil { + t.Fatal(err) + } + postgres := declare(t, `{"id":"postgres.data","type":"directory","path":"`+made+`","mode":"0750"}`) + if drifts := DirectoryDrifts(postgres, state); len(drifts) != 1 || drifts[0].Drift != "mode 0700, 0750 declared" { + t.Errorf("the drift read is %+v", drifts) + } + if lines := ConvergeDirectories(postgres, state); len(lines) != 1 || !strings.Contains(lines[0], "was mode 0700, 0750 declared, and is set right") { + t.Errorf("a drifted directory the mesh made was converged as %q", lines) + } + if info, _ := os.Stat(made); info.Mode().Perm() != 0o750 { + t.Errorf("it was not set right at the start: %04o", info.Mode().Perm()) + } + if lines := ConvergeDirectories(postgres, state); len(lines) != 0 { + t.Errorf("a directory as declared was said at the start: %q", lines) + } - // Outside the mesh's tree the rule of issue 339 stands: found, used as found. + // Outside the mesh's tree the rule of issue 339 stands: found, used as found; and left so at a start, said. other := filepath.Join(root, "var-lib", "notes") if err := os.MkdirAll(other, 0o700); err != nil { t.Fatal(err) } said = nil decl = `{"id":"notes.data","type":"directory","path":"` + other + `","mode":"0750"}` - if _, _, err := Apply(context.Background(), archHost(t), declare(t, decl), store.State{}, store.OriginDeclared, - noServices, func(line string) { said = append(said, line) }, nil); err != nil { + _, found, err := Apply(context.Background(), archHost(t), declare(t, decl), store.State{}, store.OriginDeclared, + noServices, func(line string) { said = append(said, line) }, nil) + if err != nil { t.Fatal(err) } if !strings.Contains(strings.Join(said, "\n"), "WARNING notes.data") { t.Errorf("a directory found outside the mesh's tree was not used as found: %q", said) } + if lines := ConvergeDirectories(declare(t, decl), found); len(lines) != 1 || !strings.Contains(lines[0], "left as found") { + t.Errorf("a directory the mesh never made was converged as %q", lines) + } + if drifts := DirectoryDrifts(declare(t, decl), found); len(drifts) != 0 { + t.Errorf("a directory the mesh never made is named as drift: %+v", drifts) + } + if info, _ := os.Stat(other); info.Mode().Perm() != 0o700 { + t.Errorf("a directory the mesh never made was changed at the start: %04o", info.Mode().Perm()) + } } // Review of issue 1873's fix: the tree is judged by where the path leads, not by its text. A root-only link inside the -- 2.54.0 From ba78025469290c281ec59e0fb54e3ee0d524e694 Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 00:27:55 +0100 Subject: [PATCH 12/23] E7b: state the declaration Version the engine reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A process's drain-bound raises the declaration's Version to 2, and an engine before it decodes such a declaration strictly and refuses it, so the composer that writes Version 2 must come after every engine that reads it. The engine's manifest states the Version it reads, declaration-reads 2, the edge the delivery plan derives; an engine before it cannot state the word, so this build is held for a yes once at its delivery. Builds: design 47 H2 §813 (12); H-A-358, H-A-384 (3), H-A-388 (2) --- module.json | 1 + packaging/operator_keys_test.go | 12 ++++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/module.json b/module.json index 52b30be5..e0392d39 100644 --- a/module.json +++ b/module.json @@ -2,6 +2,7 @@ "module": "mesh-host", "version": "0.1", "slug": "host", + "declaration-reads": 2, "build": { "artifacts": [ { diff --git a/packaging/operator_keys_test.go b/packaging/operator_keys_test.go index f13e9455..1cf41516 100644 --- a/packaging/operator_keys_test.go +++ b/packaging/operator_keys_test.go @@ -9,6 +9,7 @@ import ( "testing" "git.novox.be/novox/mesh-sdk/go/catalogue" + "git.novox.be/novox/mesh-sdk/go/declaration" ) // The operator's public keys reach every node as a file beside the state file, fed by a setting of the node-engine @@ -115,12 +116,19 @@ func TestTheManifestConsumesTheBackupEvent(t *testing.T) { t.Fatal(err) } // ADR 0614 §4: the node-engine's own manifest uses only words every running engine reads (the baseline, what an engine - // stating none is read as), so its new build is never held for a word only it reads. + // stating none is read as), so its new build is never held for a word only it reads; but for the declaration Version it + // reads, which an engine before it cannot state, so its build is held for a yes once at that delivery (H-A-388 and + // its addendum). if needs, err := catalogue.ManifestNeeds(raw); err != nil || len(needs) == 0 { t.Fatalf("the manifest's needs: %v, %v", needs, err) - } else if missing := catalogue.MissingManifestReads(needs, nil); len(missing) != 0 { + } else if missing := catalogue.MissingManifestReads(needs, nil); !slices.Equal(missing, []string{"word:declaration-reads"}) { t.Errorf("the manifest needs %v, which an engine stating nothing does not read: its new build would be held", missing) } + // Design 47 H2 §813 (12), H-A-388: it states the declaration Version it reads, the one its contract parses, so the + // delivery plan orders the composer that writes that Version after it. + if parsed, err := catalogue.Decode(raw); err != nil || parsed.DeclarationReads != declaration.Version { + t.Errorf("the manifest states it reads declaration Version %d, and the engine reads %d (%v)", parsed.DeclarationReads, declaration.Version, err) + } // 774 (the alert table): the state health, one key per node, the node's own health report, kept until // written again (no TTL: a node that stops writing keeps its last word, which the watchman reads with its time). // ADR 0577 clause 1: and the state data, one key per module placed on the node that declares data items, kept until -- 2.54.0 From a882051de68d64d8fbe147df603af4d6939b4d0f Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 00:28:21 +0100 Subject: [PATCH 13/23] M: the node-engine's manifest declares its class, core MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The gate reads a mover's class from its manifest, and a module that claims a seat carries a contract of the mesh: the node-engine claims the seat node-engine, so it is core. An engine before it cannot state the word, so this build's one hold for a yes at its delivery covers it too. Builds: design 47 H2 §810, §814; H-A-394 (1) --- module.json | 1 + packaging/operator_keys_test.go | 12 ++++++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/module.json b/module.json index e0392d39..088d8463 100644 --- a/module.json +++ b/module.json @@ -2,6 +2,7 @@ "module": "mesh-host", "version": "0.1", "slug": "host", + "class": "core", "declaration-reads": 2, "build": { "artifacts": [ diff --git a/packaging/operator_keys_test.go b/packaging/operator_keys_test.go index 1cf41516..5987bbeb 100644 --- a/packaging/operator_keys_test.go +++ b/packaging/operator_keys_test.go @@ -116,16 +116,20 @@ func TestTheManifestConsumesTheBackupEvent(t *testing.T) { t.Fatal(err) } // ADR 0614 §4: the node-engine's own manifest uses only words every running engine reads (the baseline, what an engine - // stating none is read as), so its new build is never held for a word only it reads; but for the declaration Version it - // reads, which an engine before it cannot state, so its build is held for a yes once at that delivery (H-A-388 and - // its addendum). + // stating none is read as), so its new build is never held for a word only it reads; but for its class and the + // declaration Version it reads, which an engine before them cannot state, so its build is held for a yes once at that + // delivery (H-A-388 and its addendum, H-A-394). if needs, err := catalogue.ManifestNeeds(raw); err != nil || len(needs) == 0 { t.Fatalf("the manifest's needs: %v, %v", needs, err) - } else if missing := catalogue.MissingManifestReads(needs, nil); !slices.Equal(missing, []string{"word:declaration-reads"}) { + } else if missing := catalogue.MissingManifestReads(needs, nil); !slices.Equal(missing, []string{"word:class", "word:declaration-reads"}) { t.Errorf("the manifest needs %v, which an engine stating nothing does not read: its new build would be held", missing) } // Design 47 H2 §813 (12), H-A-388: it states the declaration Version it reads, the one its contract parses, so the // delivery plan orders the composer that writes that Version after it. + // H-A-394 (1): a module that claims a seat is core. + if parsed, err := catalogue.Decode(raw); err != nil || parsed.Class != catalogue.ClassCore { + t.Errorf("the manifest's class is %q, and the node-engine claims a seat (%v)", parsed.Class, err) + } if parsed, err := catalogue.Decode(raw); err != nil || parsed.DeclarationReads != declaration.Version { t.Errorf("the manifest states it reads declaration Version %d, and the engine reads %d (%v)", parsed.DeclarationReads, declaration.Version, err) } -- 2.54.0 From 0c01c81c3ff65487a1ee333b07fb3819b3525e6c Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 00:30:05 +0100 Subject: [PATCH 14/23] E8: run each file's unit tests as subtests of one test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The node-engine held 1,707 top-level unit tests against the budget of 500 a module. Each unit test file with two or more tests now runs them as subtests of one test named for the file, each named as its function was, in the same order: every check is kept, and the check counts 383. Files with a TestMain, a re-run of a test by its name, or the integration tag are left. Four files of this branch's earlier commits are formatted. Builds: design 47 H2 §819; H-A-349 DQ-14 --- cmd/mesh-bootstrap/main_test.go | 37 +++-- cmd/mesh-host/apply_context_test.go | 10 +- cmd/mesh-host/file_references_test.go | 10 +- cmd/mesh-host/found_test.go | 13 +- cmd/mesh-host/join_tunnel_test.go | 16 +- cmd/mesh-host/main_test.go | 49 ++++-- cmd/mesh-host/movesecret_test.go | 10 +- cmd/mesh-host/network_test.go | 13 +- cmd/mesh-host/nodekey_test.go | 10 +- cmd/mesh-host/ownname_test.go | 13 +- cmd/mesh-host/probe_test.go | 16 +- cmd/mesh-host/recorded_test.go | 16 +- cmd/mesh-host/replay233_test.go | 10 +- cmd/mesh-host/settled_manifest_test.go | 10 +- cmd/mesh-host/units_test.go | 16 +- cmd/mesh-host/vaultbox_nats_test.go | 10 +- cmd/mesh-host/version_from_path_test.go | 13 +- cmd/mesh-host/whatruns_test.go | 19 ++- cmd/mesh-host/witnessing_test.go | 13 +- examples/bundle_test.go | 16 +- internal/accounts/accounts_test.go | 25 ++- internal/accounts/root_test.go | 28 +++- internal/accounts/setuid_cache_test.go | 49 ++++-- internal/accounts/setuid_pace_test.go | 43 +++-- internal/accounts/setuid_progress_test.go | 22 ++- internal/accounts/setuid_reach_test.go | 13 +- internal/accounts/setuid_walk_test.go | 25 ++- internal/accounts/ways_test.go | 43 +++-- internal/agent/agent_test.go | 57 ++++--- internal/apply/access_test.go | 10 +- internal/apply/apply_test.go | 151 ++++++++++++------ internal/apply/archive_removal_test.go | 22 ++- internal/apply/archive_replace_test.go | 10 +- internal/apply/block_test.go | 67 +++++--- internal/apply/busy_test.go | 31 ++-- internal/apply/container_groups_test.go | 10 +- internal/apply/containers_kept_test.go | 13 +- internal/apply/declared_home_test.go | 19 ++- internal/apply/facts_test.go | 16 +- internal/apply/file_handover_test.go | 16 +- internal/apply/filled_apply_test.go | 19 ++- internal/apply/filled_runtime_roots_test.go | 16 +- internal/apply/filled_test.go | 19 ++- internal/apply/found_is_said_test.go | 22 ++- internal/apply/found_test.go | 34 ++-- internal/apply/giveback_test.go | 22 ++- internal/apply/groups_test.go | 25 ++- internal/apply/handover_test.go | 28 +++- internal/apply/home_links_test.go | 34 ++-- internal/apply/home_parents_test.go | 16 +- internal/apply/identities_test.go | 25 ++- internal/apply/inspect_scope_test.go | 10 +- internal/apply/into_handover_test.go | 10 +- internal/apply/into_test.go | 34 ++-- internal/apply/judge_directories_test.go | 10 +- internal/apply/library_test.go | 76 ++++++--- internal/apply/maintenance_window_test.go | 34 ++-- internal/apply/mesh_dirs_gate_test.go | 10 +- internal/apply/mesh_dirs_test.go | 13 +- internal/apply/mesh_tree_found_test.go | 10 +- internal/apply/module_results_test.go | 13 +- internal/apply/module_scope_test.go | 16 +- internal/apply/mount_waits_test.go | 10 +- internal/apply/move_out_test.go | 31 ++-- internal/apply/opening_test.go | 46 ++++-- internal/apply/ownership_test.go | 10 +- internal/apply/placement_guard_test.go | 22 ++- internal/apply/plan_test.go | 28 +++- internal/apply/process_test.go | 28 +++- internal/apply/process_witness_test.go | 13 +- internal/apply/reads_test.go | 25 ++- internal/apply/references_test.go | 22 ++- internal/apply/refused_directory_test.go | 19 ++- internal/apply/removal_order_test.go | 10 +- internal/apply/replace_image_test.go | 19 ++- internal/apply/restart_order_test.go | 10 +- internal/apply/runonce_test.go | 31 ++-- internal/apply/schedule_test.go | 28 +++- internal/apply/sealed_test.go | 25 ++- internal/apply/stateless_test.go | 19 ++- internal/apply/step_failed_test.go | 19 ++- internal/apply/store_away_test.go | 16 +- internal/apply/takeover_test.go | 58 ++++--- internal/apply/user_test.go | 31 ++-- internal/apply/userscope_test.go | 52 ++++-- internal/apply/vault_sealed_test.go | 13 +- internal/apply/vocabulary_test.go | 49 ++++-- internal/apply/whole_test.go | 25 ++- internal/bootstrap/adopted_test.go | 34 ++-- internal/bootstrap/apply_test.go | 25 ++- internal/bootstrap/build_test.go | 22 ++- internal/bootstrap/builder_test.go | 28 +++- internal/bootstrap/bus_adoption_test.go | 13 +- internal/bootstrap/choices_test.go | 16 +- internal/bootstrap/control_test.go | 34 ++-- internal/bootstrap/enrol_test.go | 34 ++-- internal/bootstrap/genesis_form_test.go | 19 ++- internal/bootstrap/genesis_registry_test.go | 10 +- internal/bootstrap/genesis_toolchains_test.go | 13 +- internal/bootstrap/inuse_test.go | 28 +++- internal/bootstrap/load_test.go | 28 +++- internal/bootstrap/phase2_test.go | 13 +- internal/bootstrap/phase3_test.go | 37 +++-- internal/bootstrap/ports_test.go | 40 +++-- internal/bootstrap/preflight_test.go | 22 ++- internal/bootstrap/publish_test.go | 22 ++- internal/bootstrap/push_places_users_test.go | 19 ++- internal/bootstrap/registry_test.go | 19 ++- internal/bootstrap/retire_test.go | 22 ++- internal/bootstrap/rewrite_test.go | 46 ++++-- internal/bootstrap/rootsecrets_test.go | 25 ++- internal/bootstrap/store_layout_test.go | 16 +- internal/bootstrap/trust_test.go | 25 ++- internal/bootstrap/verify_test.go | 22 ++- internal/buckets/buckets_test.go | 13 +- internal/bundle/bundle_test.go | 19 ++- internal/compose/credentials_test.go | 52 ++++-- internal/compose/network_test.go | 25 ++- internal/compose/node_test.go | 37 +++-- internal/compose/one_machine_alone_test.go | 19 ++- internal/compose/rendering_test.go | 37 +++-- internal/compose/resolution/accesses_test.go | 13 +- internal/compose/resolution/adoption_test.go | 40 +++-- .../compose/resolution/agent_account_test.go | 10 +- internal/compose/resolution/artifacts_test.go | 13 +- .../resolution/backup_placement_test.go | 10 +- .../resolution/bound_into_files_test.go | 25 ++- internal/compose/resolution/bound_test.go | 28 +++- .../compose/resolution/broker_seat_test.go | 10 +- internal/compose/resolution/brokered_test.go | 46 ++++-- .../compose/resolution/bucket_shares_test.go | 10 +- .../compose/resolution/co_located_test.go | 22 ++- .../resolution/collections_bar_test.go | 10 +- internal/compose/resolution/computed_test.go | 25 ++- internal/compose/resolution/config_test.go | 10 +- .../compose/resolution/contributes_test.go | 40 +++-- .../contribution_dependencies_test.go | 10 +- .../resolution/derived_for_consumer_test.go | 22 ++- internal/compose/resolution/dir_into_test.go | 34 ++-- internal/compose/resolution/domain_test.go | 22 ++- internal/compose/resolution/endpoint_test.go | 19 ++- .../resolution/endpoints_setting_test.go | 13 +- .../environment_into_integration_test.go | 2 +- .../resolution/environment_into_test.go | 25 ++- internal/compose/resolution/filtering_test.go | 46 ++++-- .../resolution/foundation_manifests_test.go | 19 ++- .../resolution/generated_collision_test.go | 13 +- .../resolution/grant_secret_owner_test.go | 10 +- .../resolution/graphical_session_test.go | 13 +- internal/compose/resolution/groups_test.go | 19 ++- .../compose/resolution/handed_bound_test.go | 13 +- .../resolution/handed_providers_test.go | 10 +- internal/compose/resolution/health_test.go | 10 +- internal/compose/resolution/holdings_test.go | 19 ++- .../compose/resolution/jails_into_test.go | 13 +- internal/compose/resolution/licence_test.go | 25 ++- .../compose/resolution/localnetwork_test.go | 19 ++- .../resolution/machine_into_files_test.go | 16 +- internal/compose/resolution/needs_test.go | 13 +- .../compose/resolution/node_resolver_test.go | 19 ++- .../resolution/optional_requirements_test.go | 22 ++- .../resolution/outside_not_given_test.go | 13 +- internal/compose/resolution/own_name_test.go | 16 +- .../resolution/own_secret_owner_test.go | 10 +- .../resolution/pin_names_module_test.go | 25 ++- internal/compose/resolution/port_into_test.go | 28 +++- .../compose/resolution/process_env_test.go | 10 +- internal/compose/resolution/proofs_test.go | 10 +- internal/compose/resolution/reach_test.go | 22 ++- internal/compose/resolution/reads_test.go | 10 +- internal/compose/resolution/resolve_test.go | 67 +++++--- .../compose/resolution/resolved_path_test.go | 10 +- .../resolver_file_is_the_uplinks_test.go | 10 +- .../resolution/resolver_manifests_test.go | 13 +- internal/compose/resolution/routing_test.go | 34 ++-- internal/compose/resolution/runtime_test.go | 25 ++- .../resolution/seat_contributions_test.go | 10 +- internal/compose/resolution/seat_data_test.go | 13 +- .../resolution/seat_dependencies_test.go | 16 +- internal/compose/resolution/seat_into_test.go | 28 +++- .../compose/resolution/seat_paths_test.go | 10 +- internal/compose/resolution/seats_test.go | 16 +- .../compose/resolution/secret_restart_test.go | 10 +- .../resolution/secrets_into_files_test.go | 28 +++- .../resolution/served_own_names_test.go | 16 +- .../resolution/setting_defaults_test.go | 25 ++- .../resolution/setting_in_owner_test.go | 16 +- .../resolution/setting_in_unit_test.go | 16 +- .../compose/resolution/setting_into_test.go | 10 +- internal/compose/resolution/settings_test.go | 19 ++- .../resolution/several_contributions_test.go | 16 +- .../resolution/several_secrets_test.go | 16 +- .../compose/resolution/shared_account_test.go | 13 +- .../resolution/terminal_settings_test.go | 13 +- .../resolution/toolchain_manifests_test.go | 10 +- .../compose/resolution/two_consumers_test.go | 13 +- .../compose/resolution/two_resolvers_test.go | 22 ++- .../resolution/unconsumed_placeholder_test.go | 13 +- internal/compose/resolution/zones_test.go | 10 +- internal/compose/resolve_test.go | 34 ++-- internal/compose/rest_test.go | 28 +++- internal/composer/composer_test.go | 13 +- internal/filling/filling_test.go | 58 ++++--- internal/firewall/filters_test.go | 16 +- internal/firewall/firewall_test.go | 91 +++++++---- internal/firewall/neighbour_ban_test.go | 10 +- internal/identity/identity_test.go | 58 ++++--- internal/identity/serving_test.go | 10 +- internal/image/image_test.go | 25 ++- internal/inventory/inventory_test.go | 22 ++- internal/link/access_act_test.go | 13 +- internal/link/handover_test.go | 25 ++- internal/link/have_test.go | 64 +++++--- internal/link/health_test.go | 13 +- internal/link/judge_directories_test.go | 10 +- internal/link/movesecret_test.go | 13 +- internal/link/pinned_test.go | 13 +- internal/link/rotate_test.go | 10 +- internal/link/roused_test.go | 10 +- internal/link/session_test.go | 13 +- internal/link/setuid_search_test.go | 10 +- internal/link/taken.go | 8 +- internal/liveness/liveness_test.go | 37 +++-- internal/liveness/readiness_test.go | 31 ++-- internal/liveness/replay_test.go | 10 +- internal/liveness/waiting_test.go | 37 +++-- internal/network/network_test.go | 46 ++++-- internal/outward/links_test.go | 25 ++- internal/outward/networks_test.go | 13 +- internal/profile/machine_test.go | 22 ++- internal/profile/power_test.go | 25 ++- internal/profile/profile_system_test.go | 13 +- internal/profile/profile_test.go | 34 ++-- internal/profile/seat_test.go | 22 ++- internal/profile/userns_test.go | 19 ++- internal/reachable/collect_test.go | 16 +- internal/selfcompose/candidate_test.go | 4 +- internal/selfcompose/entries_test.go | 10 +- internal/selfcompose/selfcompose_test.go | 25 ++- internal/store/declared_test.go | 25 ++- internal/store/store_test.go | 37 +++-- internal/system/arch_install_test.go | 19 ++- internal/system/identities_test.go | 13 +- internal/system/lookup_exit_test.go | 10 +- internal/system/system_test.go | 67 +++++--- internal/system/usermanager_test.go | 10 +- internal/tunnel/tunnel_test.go | 28 +++- internal/units/units_test.go | 40 +++-- internal/upgrade/fallback_test.go | 25 ++- internal/upgrade/upgrade_test.go | 34 ++-- internal/upgrade/versions_test.go | 28 +++- internal/upgrade/witnessed_test.go | 19 ++- internal/validate/sdk_test.go | 10 +- internal/witness/contract_test.go | 13 +- internal/witness/draining_test.go | 13 +- internal/witness/watch_test.go | 22 ++- packaging/operator_keys_test.go | 10 +- 257 files changed, 4189 insertions(+), 1589 deletions(-) diff --git a/cmd/mesh-bootstrap/main_test.go b/cmd/mesh-bootstrap/main_test.go index 8d19d6c9..65a128a2 100644 --- a/cmd/mesh-bootstrap/main_test.go +++ b/cmd/mesh-bootstrap/main_test.go @@ -15,7 +15,7 @@ import ( // command exits zero having ignored what it was asked. Here that would mean `--dry-run` ignored on // a program whose whole job is to change a machine. -func TestBootstrapIsWhatItDoesWithNoCommand(t *testing.T) { +func testBootstrapIsWhatItDoesWithNoCommand(t *testing.T) { // Running the installer with nothing but flags must install, not print usage: the command is // the reason the binary exists, and making somebody type its name twice buys nothing. command, opts, _, err := parseArgs([]string{"--dry-run"}) @@ -30,7 +30,7 @@ func TestBootstrapIsWhatItDoesWithNoCommand(t *testing.T) { } } -func TestFlagsAreReadWhereverTheySit(t *testing.T) { +func testFlagsAreReadWhereverTheySit(t *testing.T) { for _, args := range [][]string{ {"bootstrap", "--dry-run", "--bundle", "s.lock", "--json"}, {"bootstrap", "--json", "--bundle=s.lock", "--dry-run"}, @@ -48,7 +48,7 @@ func TestFlagsAreReadWhereverTheySit(t *testing.T) { } } -func TestAMistypedFlagIsRefusedNotIgnored(t *testing.T) { +func testAMistypedFlagIsRefusedNotIgnored(t *testing.T) { // Asymmetric cost: an error is a moment's annoyance, and a silently dropped --dry-run is a // machine changed by somebody who asked for it not to be. if _, _, _, err := parseArgs([]string{"bootstrap", "--dry-runn"}); err == nil { @@ -56,13 +56,13 @@ func TestAMistypedFlagIsRefusedNotIgnored(t *testing.T) { } } -func TestAnUnexpectedArgumentIsRefused(t *testing.T) { +func testAnUnexpectedArgumentIsRefused(t *testing.T) { if _, _, _, err := parseArgs([]string{"bootstrap", "foundation.lock"}); err == nil { t.Fatal("a stray argument was ignored rather than refused — the bundle is --bundle") } } -func TestTheDefaultsAreTheDocumentedOnes(t *testing.T) { +func testTheDefaultsAreTheDocumentedOnes(t *testing.T) { // The usage text is a promise. A default that drifts from what is printed is a small lie that // costs somebody an afternoon in front of a machine that will not come up. _, opts, jsonOut, err := parseArgs(nil) @@ -92,7 +92,7 @@ func TestTheDefaultsAreTheDocumentedOnes(t *testing.T) { // Every flag the usage text promises must exist, and every flag that exists must be in the usage // text. The two drifting apart is how a program acquires a feature nobody can find and a // documented option that does nothing. -func TestTheUsageTextAndTheFlagsAgree(t *testing.T) { +func testTheUsageTextAndTheFlagsAgree(t *testing.T) { var opts bootstrap.Options var jsonOut bool set := newFlagSet(&opts, &jsonOut) @@ -119,7 +119,7 @@ func TestTheUsageTextAndTheFlagsAgree(t *testing.T) { // The pivot's defaults are the documented ones too, and the one that has no default is the one // that decides whether the pivot happens at all. -func TestThePivotsDefaultsAreTheDocumentedOnes(t *testing.T) { +func testThePivotsDefaultsAreTheDocumentedOnes(t *testing.T) { _, opts, _, err := parseArgs(nil) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -152,7 +152,7 @@ func TestThePivotsDefaultsAreTheDocumentedOnes(t *testing.T) { // --node overrides the machine's own name rather than being ignored because a default was already // computed. The name is what the mesh's records, tokens, assignments and pushes all name. -func TestTheNodeNameCanBeSaid(t *testing.T) { +func testTheNodeNameCanBeSaid(t *testing.T) { _, opts, _, err := parseArgs([]string{"--node", "anchor", "--catalog", "/somewhere"}) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -167,7 +167,7 @@ func TestTheNodeNameCanBeSaid(t *testing.T) { // Defends novox/hq ADR 0100: the foundation's ports are inputs to genesis, and the registry's port // and the address nodes pull from say one port. -func TestTheFoundationsPortsAreGiven(t *testing.T) { +func testTheFoundationsPortsAreGiven(t *testing.T) { _, opts, _, err := parseArgs([]string{"--store-port", "5433", "--hub-port", "51821", "--overlay-range", "10.77.0.0/16"}) if err != nil { t.Fatal(err) @@ -177,7 +177,7 @@ func TestTheFoundationsPortsAreGiven(t *testing.T) { } } -func TestTheRegistrysPortAndAddressAgree(t *testing.T) { +func testTheRegistrysPortAndAddressAgree(t *testing.T) { _, opts, _, err := parseArgs([]string{"--registry-port", "5100"}) if err != nil || opts.Registry != "127.0.0.1:5100" { t.Errorf("--registry-port alone: %s %v", opts.Registry, err) @@ -191,7 +191,7 @@ func TestTheRegistrysPortAndAddressAgree(t *testing.T) { } } -func TestARegistryGivenAsAHostAloneTakesTheRegistrysPort(t *testing.T) { +func testARegistryGivenAsAHostAloneTakesTheRegistrysPort(t *testing.T) { _, opts, _, err := parseArgs([]string{"--registry", "192.0.2.10"}) if err != nil || opts.Registry != "192.0.2.10:5000" || opts.Ports.Registry != 5000 { t.Errorf("--registry host alone: %s %d %v", opts.Registry, opts.Ports.Registry, err) @@ -204,3 +204,18 @@ func TestARegistryGivenAsAHostAloneTakesTheRegistrysPort(t *testing.T) { t.Error("a registry with a port that is not a number was accepted") } } + +// TestMain runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestMain(t *testing.T) { + t.Run("BootstrapIsWhatItDoesWithNoCommand", testBootstrapIsWhatItDoesWithNoCommand) + t.Run("FlagsAreReadWhereverTheySit", testFlagsAreReadWhereverTheySit) + t.Run("AMistypedFlagIsRefusedNotIgnored", testAMistypedFlagIsRefusedNotIgnored) + t.Run("AnUnexpectedArgumentIsRefused", testAnUnexpectedArgumentIsRefused) + t.Run("TheDefaultsAreTheDocumentedOnes", testTheDefaultsAreTheDocumentedOnes) + t.Run("TheUsageTextAndTheFlagsAgree", testTheUsageTextAndTheFlagsAgree) + t.Run("ThePivotsDefaultsAreTheDocumentedOnes", testThePivotsDefaultsAreTheDocumentedOnes) + t.Run("TheNodeNameCanBeSaid", testTheNodeNameCanBeSaid) + t.Run("TheFoundationsPortsAreGiven", testTheFoundationsPortsAreGiven) + t.Run("TheRegistrysPortAndAddressAgree", testTheRegistrysPortAndAddressAgree) + t.Run("ARegistryGivenAsAHostAloneTakesTheRegistrysPort", testARegistryGivenAsAHostAloneTakesTheRegistrysPort) +} diff --git a/cmd/mesh-host/apply_context_test.go b/cmd/mesh-host/apply_context_test.go index a78a9930..065ef1ec 100644 --- a/cmd/mesh-host/apply_context_test.go +++ b/cmd/mesh-host/apply_context_test.go @@ -10,7 +10,7 @@ import ( // because of the apply itself (it replaces the bus's own container), which then must finish (issue 1945, live on // 2026-10-25 at 11:23: novox's node-engine removed the bus container, its link's context ended, and the docker run that // would have made the new one was never made). -func TestAnApplyOutlivesTheLinksContext(t *testing.T) { +func testAnApplyOutlivesTheLinksContext(t *testing.T) { type key struct{} link, cancel := context.WithCancel(context.WithValue(context.Background(), key{}, "v")) ctx, done := applyContext(link) @@ -26,7 +26,7 @@ func TestAnApplyOutlivesTheLinksContext(t *testing.T) { // An apply is bounded all the same: a step that hangs (a docker call that never returns) cannot hold the node agent for // ever (the review of issue 1945). -func TestAnApplyIsBounded(t *testing.T) { +func testAnApplyIsBounded(t *testing.T) { t.Run("the marks of the haves never hold the pass", marksOfTheHavesNeverHoldThePass) ctx, done := applyContext(context.Background()) defer done() @@ -38,3 +38,9 @@ func TestAnApplyIsBounded(t *testing.T) { t.Fatalf("the bound is %s away, want about %s", left, applyBound) } } + +// TestApplyContext runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestApplyContext(t *testing.T) { + t.Run("AnApplyOutlivesTheLinksContext", testAnApplyOutlivesTheLinksContext) + t.Run("AnApplyIsBounded", testAnApplyIsBounded) +} diff --git a/cmd/mesh-host/file_references_test.go b/cmd/mesh-host/file_references_test.go index 891dd4f0..6f9a0a95 100644 --- a/cmd/mesh-host/file_references_test.go +++ b/cmd/mesh-host/file_references_test.go @@ -39,7 +39,7 @@ func referenceDeclaration(path string, body []byte) []byte { // 1695/AC1 and AC2, through the whole apply: a reference is fetched, verified and written; a differing object // refuses the declaration whole and writes nothing. -func TestADeclarationWithAFileByDigestAppliesFromTheObject(t *testing.T) { +func testADeclarationWithAFileByDigestAppliesFromTheObject(t *testing.T) { unansweringPacman(t) body := []byte(strings.Repeat("a line of a big file\n", 4000)) name, _ := declaration.ObjectName(declaration.DigestOf(body)) @@ -159,7 +159,7 @@ func TestADeclarationWithAFileByDigestAppliesFromTheObject(t *testing.T) { // 1695/AC8: the hand-run `apply ` and `reconcile` have no bus: a reference whose file here verifies is applied // as it is, any other refuses and writes nothing — never an empty file. -func TestTheHandApplyNeverWritesAReferenceEmpty(t *testing.T) { +func testTheHandApplyNeverWritesAReferenceEmpty(t *testing.T) { unansweringPacman(t) body := []byte(strings.Repeat("a line of a big file\n", 4000)) dir := t.TempDir() @@ -187,3 +187,9 @@ func TestTheHandApplyNeverWritesAReferenceEmpty(t *testing.T) { t.Errorf("1695/AC8: the file holds %d bytes, want %d", len(got), len(body)) } } + +// TestFileReferences runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFileReferences(t *testing.T) { + t.Run("ADeclarationWithAFileByDigestAppliesFromTheObject", testADeclarationWithAFileByDigestAppliesFromTheObject) + t.Run("TheHandApplyNeverWritesAReferenceEmpty", testTheHandApplyNeverWritesAReferenceEmpty) +} diff --git a/cmd/mesh-host/found_test.go b/cmd/mesh-host/found_test.go index b6ef63aa..ab3b38e7 100644 --- a/cmd/mesh-host/found_test.go +++ b/cmd/mesh-host/found_test.go @@ -16,7 +16,7 @@ import ( // Every directory used as found is its module's resource of kind directory, unhealthy, naming its owner, on // every statement (novox/hq issue 339): the controller raises that as the module's condition. The way out it // names is the node seat's hand-over, with this node's name (novox/hq ADR 0563 §5). -func TestAFoundDirectoryIsStatedUnhealthy(t *testing.T) { +func testAFoundDirectoryIsStatedUnhealthy(t *testing.T) { dir := t.TempDir() known := store.State{Resources: []store.Applied{ {ID: "notes.data", Type: "directory", Target: dir, AsFound: true, Declared: "root, mode 755", AppliedAt: time.Now()}, @@ -61,7 +61,7 @@ func realDir(t *testing.T) string { // A hand-over records a directory used as found, and refuses one that is not — through the engine's own // subcommand and through the controller's ask alike, which are one judgement. -func TestHandOverRecordsOnlyAFoundDirectory(t *testing.T) { +func testHandOverRecordsOnlyAFoundDirectory(t *testing.T) { dir := realDir(t) statePath := filepath.Join(dir, "state.json") found := filepath.Join(dir, "found") @@ -111,7 +111,7 @@ func TestHandOverRecordsOnlyAFoundDirectory(t *testing.T) { // Every value of a hand-over is judged before anything is recorded, and each refusal records nothing: a relative // path, a path that is not the engine's statement of the directory (`..`, a doubled or trailing separator), one // not used as found, a link at the path, a link in the path, a file, a directory that is gone. -func TestAHandOverIsRefusedForEveryPathThatIsNotTheFoundDirectory(t *testing.T) { +func testAHandOverIsRefusedForEveryPathThatIsNotTheFoundDirectory(t *testing.T) { dir := realDir(t) statePath := filepath.Join(dir, "state.json") found := filepath.Join(dir, "found") @@ -176,3 +176,10 @@ func TestAHandOverIsRefusedForEveryPathThatIsNotTheFoundDirectory(t *testing.T) t.Fatalf("recorded: %+v", all) } } + +// TestFound runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFound(t *testing.T) { + t.Run("AFoundDirectoryIsStatedUnhealthy", testAFoundDirectoryIsStatedUnhealthy) + t.Run("HandOverRecordsOnlyAFoundDirectory", testHandOverRecordsOnlyAFoundDirectory) + t.Run("AHandOverIsRefusedForEveryPathThatIsNotTheFoundDirectory", testAHandOverIsRefusedForEveryPathThatIsNotTheFoundDirectory) +} diff --git a/cmd/mesh-host/join_tunnel_test.go b/cmd/mesh-host/join_tunnel_test.go index 6f6757bf..7ba527e4 100644 --- a/cmd/mesh-host/join_tunnel_test.go +++ b/cmd/mesh-host/join_tunnel_test.go @@ -14,7 +14,7 @@ import ( // `key` makes the tunnel key once and prints its public half; asked again it prints the same one, // because a token may already have been issued for it (novox/hq ADR 0169). -func TestKeyMakesTheTunnelKeyOnceAndKeepsIt(t *testing.T) { +func testKeyMakesTheTunnelKeyOnceAndKeepsIt(t *testing.T) { dir := t.TempDir() opts := options{state: filepath.Join(dir, "state.json")} first := captureStdout(t, func() { @@ -41,7 +41,7 @@ func TestKeyMakesTheTunnelKeyOnceAndKeepsIt(t *testing.T) { // A token through the tunnel takes the key it was issued for, and says so when this machine has none // or another. -func TestATokenThroughTheTunnelTakesItsOwnKey(t *testing.T) { +func testATokenThroughTheTunnelTakesItsOwnKey(t *testing.T) { dir := t.TempDir() state := filepath.Join(dir, "state.json") tt := &identity.TokenTunnel{Key: "x", Address: "10.42.0.9/32", Range: "10.42.0.0/16", HubKey: "h", HubEndpoint: "198.51.100.1:51820"} @@ -61,7 +61,7 @@ func TestATokenThroughTheTunnelTakesItsOwnKey(t *testing.T) { // The first tunnel is the mesh's interface and unit, with the hub as its one peer and no secret in // the file — the same shape the mesh's declaration replaces it with. -func TestTheFirstTunnelIsTheMeshsInterfaceWithTheHubAsItsPeer(t *testing.T) { +func testTheFirstTunnelIsTheMeshsInterfaceWithTheHubAsItsPeer(t *testing.T) { dir := t.TempDir() tunnelConfigPath = filepath.Join(dir, "wireguard", "mesh0.conf") lookPath = func(string) (string, error) { return "/usr/bin/wg-quick", nil } @@ -117,7 +117,7 @@ func captureStdout(t *testing.T, fn func()) string { // The bus is dialled only once the hub has answered the tunnel, and a hub that never does is said // as the tunnel's fault rather than the bus's. -func TestTheBusWaitsForTheHubToAnswer(t *testing.T) { +func testTheBusWaitsForTheHubToAnswer(t *testing.T) { asked := 0 answersOnThird := func(_ context.Context, name string, args ...string) (string, error) { asked++ @@ -137,3 +137,11 @@ func TestTheBusWaitsForTheHubToAnswer(t *testing.T) { t.Fatalf("a hub that never answered was not said: %v", err) } } + +// TestJoinTunnel runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestJoinTunnel(t *testing.T) { + t.Run("KeyMakesTheTunnelKeyOnceAndKeepsIt", testKeyMakesTheTunnelKeyOnceAndKeepsIt) + t.Run("ATokenThroughTheTunnelTakesItsOwnKey", testATokenThroughTheTunnelTakesItsOwnKey) + t.Run("TheFirstTunnelIsTheMeshsInterfaceWithTheHubAsItsPeer", testTheFirstTunnelIsTheMeshsInterfaceWithTheHubAsItsPeer) + t.Run("TheBusWaitsForTheHubToAnswer", testTheBusWaitsForTheHubToAnswer) +} diff --git a/cmd/mesh-host/main_test.go b/cmd/mesh-host/main_test.go index cd4df78c..772646d4 100644 --- a/cmd/mesh-host/main_test.go +++ b/cmd/mesh-host/main_test.go @@ -27,7 +27,7 @@ import ( // Silently doing something other than what was asked, and reporting success, is the fault this // project exists to name — so it gets defended here rather than remembered. -func TestAFlagAfterTheCommandIsRead(t *testing.T) { +func testAFlagAfterTheCommandIsRead(t *testing.T) { command, opts, err := parseArgs([]string{"inventory", "--json"}) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -40,7 +40,7 @@ func TestAFlagAfterTheCommandIsRead(t *testing.T) { } } -func TestFlagsAreReadInEitherPosition(t *testing.T) { +func testFlagsAreReadInEitherPosition(t *testing.T) { for _, args := range [][]string{ {"profile", "--json", "--timeout", "3s"}, {"profile", "--timeout=3s", "--json"}, @@ -55,7 +55,7 @@ func TestFlagsAreReadInEitherPosition(t *testing.T) { } } -func TestAMistypedFlagIsRefusedNotIgnored(t *testing.T) { +func testAMistypedFlagIsRefusedNotIgnored(t *testing.T) { // The cost of getting this wrong is asymmetric: an error is a moment's annoyance, and a // silently dropped flag is a report that answers a question nobody asked. if _, _, err := parseArgs([]string{"profile", "--jsom"}); err == nil { @@ -63,13 +63,13 @@ func TestAMistypedFlagIsRefusedNotIgnored(t *testing.T) { } } -func TestAnUnexpectedArgumentIsRefused(t *testing.T) { +func testAnUnexpectedArgumentIsRefused(t *testing.T) { if _, _, err := parseArgs([]string{"profile", "extra"}); err == nil { t.Fatal("a stray argument was ignored rather than refused") } } -func TestTheDefaultsAreTheDocumentedOnes(t *testing.T) { +func testTheDefaultsAreTheDocumentedOnes(t *testing.T) { // The usage text promises 10s. A default that drifts from what is printed is a small lie // that costs someone an afternoon. _, opts, err := parseArgs([]string{"profile"}) @@ -84,7 +84,7 @@ func TestTheDefaultsAreTheDocumentedOnes(t *testing.T) { } } -func TestNoCommandIsNotAnError(t *testing.T) { +func testNoCommandIsNotAnError(t *testing.T) { // Running the binary with no arguments prints usage and exits 0. A host that returns // failure for "tell me what you do" is noise in every script that probes it. command, _, err := parseArgs(nil) @@ -96,7 +96,7 @@ func TestNoCommandIsNotAnError(t *testing.T) { } } -func TestTheStateHasADocumentedDefault(t *testing.T) { +func testTheStateHasADocumentedDefault(t *testing.T) { // A host that wrote its state somewhere unexpected would forget what it owns on the next // run, and then leave everything it had applied behind forever. _, opts, err := parseArgs([]string{"owned"}) @@ -108,7 +108,7 @@ func TestTheStateHasADocumentedDefault(t *testing.T) { } } -func TestAFlagAfterAPositionalIsRead(t *testing.T) { +func testAFlagAfterAPositionalIsRead(t *testing.T) { // The same fault as TestAFlagAfterTheCommandIsRead, one level down. Taking the subcommand // off the front fixed the flag after the COMMAND and not the flag after its ARGUMENT: the // standard library stops at the first non-flag argument wherever that argument is. @@ -132,7 +132,7 @@ func TestAFlagAfterAPositionalIsRead(t *testing.T) { // Defends the node's own record: the link and the reconcile loop both apply, and each reads the // state, acts, and writes it back — so they must not run at the same time, or the last save loses // what the other recorded. -func TestOnlyOneApplyRunsAtATime(t *testing.T) { +func testOnlyOneApplyRunsAtATime(t *testing.T) { // Issue 1585: the engine's stop waits for the apply in flight to end and save, and then lets no save start; before, // the process ended under it and a save cut before its rename left its temporary file and the state before it. t.Run("the stop waits for the apply in flight and its save", func(t *testing.T) { @@ -242,7 +242,7 @@ func stateWithMode(t *testing.T, mode string) options { return opts } -func TestAConvergedDeclarationIsRefusedOnAnAdoptedNode(t *testing.T) { +func testAConvergedDeclarationIsRefusedOnAnAdoptedNode(t *testing.T) { opts := stateWithMode(t, store.ModeAdopted) path := filepath.Join(filepath.Dir(opts.state), "filter.conf") raw := []byte(`{"declaration":1,"resources":[{"id":"filter","type":"file","path":"` + path + @@ -266,7 +266,7 @@ func TestAConvergedDeclarationIsRefusedOnAnAdoptedNode(t *testing.T) { } } -func TestTheKeptDeclarationRepairsARecordThatDisagrees(t *testing.T) { +func testTheKeptDeclarationRepairsARecordThatDisagrees(t *testing.T) { // What a node kept is signed by the mesh and verified on load; the state's note of the mode is // the host's own. A genesis re-run after `converge`, or a state saved when the kept declaration // could not be, leaves them apart — and a loop that refused every five minutes would hold the @@ -286,7 +286,7 @@ func TestTheKeptDeclarationRepairsARecordThatDisagrees(t *testing.T) { } } -func TestTheMeshItselfMayChangeTheMode(t *testing.T) { +func testTheMeshItselfMayChangeTheMode(t *testing.T) { // The flip is a declaration: `converge` on the controller records the mode and sends the // first converged declaration. Delivered by the link, signed, it is not held to the record — // it becomes it. (With no system linked in, the apply is refused later for that; what this @@ -304,7 +304,7 @@ func TestTheMeshItselfMayChangeTheMode(t *testing.T) { // both — and `apply FILE` is refused altogether once the mesh has spoken, the last declaration // itself included: from a file it is applied as the bundle is, which would record the mesh's // resources as this machine's own and remove the foundation as undeclared. -func TestAnOlderDeclarationIsRefused(t *testing.T) { +func testAnOlderDeclarationIsRefused(t *testing.T) { opts := stateWithMode(t, "") genesis := []byte(`{"declaration":1,"resources":[{"id":"g","type":"file","path":"/tmp/g","content":"genesis\n"}]}`) since := []byte(`{"declaration":1,"resources":[{"id":"g","type":"file","path":"/tmp/g","content":"since\n"}]}`) @@ -364,7 +364,7 @@ func TestAnOlderDeclarationIsRefused(t *testing.T) { // Defends novox/hq issue 104: what an apply would change is said before anything is, and // `--dry-run` is that and nothing else — an action listed as the action it is. -func TestADryRunChangesNothingAndListsTheActions(t *testing.T) { +func testADryRunChangesNothingAndListsTheActions(t *testing.T) { opts := stateWithMode(t, "") opts.dryRun = true out := &bytes.Buffer{} @@ -420,7 +420,7 @@ func TestADryRunChangesNothingAndListsTheActions(t *testing.T) { // **It cannot catch the fault it was written for** — a call site passing nil directly — because that is // wiring, and wiring is only proved by running the thing. That proof is a deployed host whose journal // carries the apply's detail, which is how this fix was verified. -func TestTheApplysLogIsNeverNil(t *testing.T) { +func testTheApplysLogIsNeverNil(t *testing.T) { if announceOr(nil) == nil { t.Fatal("a host with nowhere to say things got a nil log, which the apply will call") } @@ -432,3 +432,22 @@ func TestTheApplysLogIsNeverNil(t *testing.T) { t.Fatalf("the apply's detail did not reach the caller's announce: %v", said) } } + +// TestMain runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestMain(t *testing.T) { + t.Run("AFlagAfterTheCommandIsRead", testAFlagAfterTheCommandIsRead) + t.Run("FlagsAreReadInEitherPosition", testFlagsAreReadInEitherPosition) + t.Run("AMistypedFlagIsRefusedNotIgnored", testAMistypedFlagIsRefusedNotIgnored) + t.Run("AnUnexpectedArgumentIsRefused", testAnUnexpectedArgumentIsRefused) + t.Run("TheDefaultsAreTheDocumentedOnes", testTheDefaultsAreTheDocumentedOnes) + t.Run("NoCommandIsNotAnError", testNoCommandIsNotAnError) + t.Run("TheStateHasADocumentedDefault", testTheStateHasADocumentedDefault) + t.Run("AFlagAfterAPositionalIsRead", testAFlagAfterAPositionalIsRead) + t.Run("OnlyOneApplyRunsAtATime", testOnlyOneApplyRunsAtATime) + t.Run("AConvergedDeclarationIsRefusedOnAnAdoptedNode", testAConvergedDeclarationIsRefusedOnAnAdoptedNode) + t.Run("TheKeptDeclarationRepairsARecordThatDisagrees", testTheKeptDeclarationRepairsARecordThatDisagrees) + t.Run("TheMeshItselfMayChangeTheMode", testTheMeshItselfMayChangeTheMode) + t.Run("AnOlderDeclarationIsRefused", testAnOlderDeclarationIsRefused) + t.Run("ADryRunChangesNothingAndListsTheActions", testADryRunChangesNothingAndListsTheActions) + t.Run("TheApplysLogIsNeverNil", testTheApplysLogIsNeverNil) +} diff --git a/cmd/mesh-host/movesecret_test.go b/cmd/mesh-host/movesecret_test.go index 2da4d478..643e1a3d 100644 --- a/cmd/mesh-host/movesecret_test.go +++ b/cmd/mesh-host/movesecret_test.go @@ -82,7 +82,7 @@ func aMoveOf(t *testing.T, key identity.SealingKey) link.MoveSecret { // The engine opens what was sealed to its machine, hands it to the vault sealed to the call's key — never in the // clear — and answers what the vault kept only once the read-back opens to the same value. -func TestTheEngineMovesAValueSealedToItAndChecksTheReadBack(t *testing.T) { +func testTheEngineMovesAValueSealedToItAndChecksTheReadBack(t *testing.T) { key, err := identity.GenerateSealingKey() if err != nil { t.Fatal(err) @@ -107,7 +107,7 @@ func TestTheEngineMovesAValueSealedToItAndChecksTheReadBack(t *testing.T) { // A read-back that is not the value handed in is a failed move, said; so is a value this machine cannot open, and // the vault's refusal. -func TestTheEngineSaysAMoveThatDidNotHold(t *testing.T) { +func testTheEngineSaysAMoveThatDidNotHold(t *testing.T) { key, _ := identity.GenerateSealingKey() vault := &standInVault{t: t, lie: "something-else"} if _, err := moveIntoTheVault(vault.ask, key, aMoveOf(t, key)); err == nil || @@ -159,3 +159,9 @@ func TestTheEngineSaysAMoveThatDidNotHold(t *testing.T) { t.Errorf("the pair's first step named %v", ends.opened) } } + +// TestMovesecret runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestMovesecret(t *testing.T) { + t.Run("TheEngineMovesAValueSealedToItAndChecksTheReadBack", testTheEngineMovesAValueSealedToItAndChecksTheReadBack) + t.Run("TheEngineSaysAMoveThatDidNotHold", testTheEngineSaysAMoveThatDidNotHold) +} diff --git a/cmd/mesh-host/network_test.go b/cmd/mesh-host/network_test.go index 8f9dcef2..485683db 100644 --- a/cmd/mesh-host/network_test.go +++ b/cmd/mesh-host/network_test.go @@ -12,7 +12,7 @@ import ( // The machine's networking in the engine's statement (novox/hq ADR 0241): the file judged is the one the // uplink holder declares whole, the mesh name asked is the bus's, and the statement carries the parts. -func TestTheResolverFileJudgedIsTheOneAModuleDeclaresWhole(t *testing.T) { +func testTheResolverFileJudgedIsTheOneAModuleDeclaresWhole(t *testing.T) { d := &declaration.Declaration{Resources: []declaration.Resource{ &declaration.File{ID: "hosts.file", Type: "file", Path: "/etc/hosts", Content: "x"}, &declaration.File{ID: "networkmanager.resolv", Type: "file", Path: network.ResolvConf, Content: "nameserver 10.10.0.1\n"}, @@ -30,7 +30,7 @@ func TestTheResolverFileJudgedIsTheOneAModuleDeclaresWhole(t *testing.T) { } } -func TestTheMeshNameAskedIsTheBuses(t *testing.T) { +func testTheMeshNameAskedIsTheBuses(t *testing.T) { for broker, want := range map[string]string{"anchor.internal:4222": "anchor.internal", "192.0.2.10:5671": "", "anchor.internal": "anchor.internal", "[2001:db8::1]:4222": ""} { if got := hostOf(broker); got != want { @@ -39,7 +39,7 @@ func TestTheMeshNameAskedIsTheBuses(t *testing.T) { } } -func TestTheStatementCarriesTheNetwork(t *testing.T) { +func testTheStatementCarriesTheNetwork(t *testing.T) { at := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) h := healthAsReported(liveness.Statement{At: at}, &network.Statement{State: network.Unhealthy, Since: at, Parts: []network.Part{{Part: network.PartResolvConf, State: network.Unhealthy, Writer: "FortiClient", @@ -52,3 +52,10 @@ func TestTheStatementCarriesTheNetwork(t *testing.T) { t.Fatal("an engine with no network judge said a network") } } + +// TestNetwork runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestNetwork(t *testing.T) { + t.Run("TheResolverFileJudgedIsTheOneAModuleDeclaresWhole", testTheResolverFileJudgedIsTheOneAModuleDeclaresWhole) + t.Run("TheMeshNameAskedIsTheBuses", testTheMeshNameAskedIsTheBuses) + t.Run("TheStatementCarriesTheNetwork", testTheStatementCarriesTheNetwork) +} diff --git a/cmd/mesh-host/nodekey_test.go b/cmd/mesh-host/nodekey_test.go index 6084cede..05abf9f4 100644 --- a/cmd/mesh-host/nodekey_test.go +++ b/cmd/mesh-host/nodekey_test.go @@ -64,7 +64,7 @@ func waitFor(t *testing.T, what string, ok func() bool) { t.Fatalf("timed out: %s", what) } -func TestTheEngineStatesItsSealingKeyToTheVaultAtStartRetriesAndRestatesAChange(t *testing.T) { +func testTheEngineStatesItsSealingKeyToTheVaultAtStartRetriesAndRestatesAChange(t *testing.T) { first, _ := identity.GenerateSealingKey() second, _ := identity.GenerateSealingKey() var mu sync.Mutex @@ -164,7 +164,7 @@ func asksAgainUntilItHearsTheVaultsKey(t *testing.T) { // The statement a host makes names this contract (issue 786), one above the vault's box. And the vault's key its // answer gives is kept; an answer without one (an older vault) or with no public key changes nothing (ADR 0547 clause // 9). -func TestTheNodeKeyContractIsThirteen(t *testing.T) { +func testTheNodeKeyContractIsThirteen(t *testing.T) { if link.NodeKeyContract != 13 { t.Errorf("NodeKeyContract %d", link.NodeKeyContract) } @@ -181,3 +181,9 @@ func TestTheNodeKeyContractIsThirteen(t *testing.T) { t.Fatalf("key %q, want the key", h.get()) } } + +// TestNodekey runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestNodekey(t *testing.T) { + t.Run("TheEngineStatesItsSealingKeyToTheVaultAtStartRetriesAndRestatesAChange", testTheEngineStatesItsSealingKeyToTheVaultAtStartRetriesAndRestatesAChange) + t.Run("TheNodeKeyContractIsThirteen", testTheNodeKeyContractIsThirteen) +} diff --git a/cmd/mesh-host/ownname_test.go b/cmd/mesh-host/ownname_test.go index 7f64d064..9307c367 100644 --- a/cmd/mesh-host/ownname_test.go +++ b/cmd/mesh-host/ownname_test.go @@ -20,7 +20,7 @@ import ( // Design 47 G §527, §634, A-149: the node-engine's own module is the module of its applied record at its own fingerprint, // and its finding writer is made, observing as that module, once the name is known: at once from the record, else when the // first composing names it. No name is fixed in code. -func TestTheEnginesOwnNameIsReadFromItsAppliedRecordOrItsFirstComposing(t *testing.T) { +func testTheEnginesOwnNameIsReadFromItsAppliedRecordOrItsFirstComposing(t *testing.T) { fp := "src2:" + strings.Repeat("a", 64) applied := appliedStoreFor(filepath.Join(t.TempDir(), "state", "state.json")) for module, f := range map[string]string{"node": "", "the-engine": fp, "other": "src2:" + strings.Repeat("b", 64)} { @@ -105,7 +105,7 @@ func TestTheEnginesOwnNameIsReadFromItsAppliedRecordOrItsFirstComposing(t *testi // Design 47 H, H-A-60: how often an entry whose ask failed is asked again is the file the manifest's `entry-asks` feeds, five when it // holds nothing usable. -func TestTheEntryAsksAreTheManifestsSetting(t *testing.T) { +func testTheEntryAsksAreTheManifestsSetting(t *testing.T) { was := entryAsksFile defer func() { entryAsksFile = was }() for content, want := range map[string]int{"2\n": 2, "": 5, "0": 5, "x": 5} { @@ -125,7 +125,7 @@ func TestTheEntryAsksAreTheManifestsSetting(t *testing.T) { // §633: the engine's bound for the first seat list is the file the manifest's `view-waits-minutes` feeds, five minutes // when it holds nothing usable. -func TestTheViewWaitsBoundIsTheManifestsSetting(t *testing.T) { +func testTheViewWaitsBoundIsTheManifestsSetting(t *testing.T) { was := viewWaitsFile defer func() { viewWaitsFile = was }() for content, want := range map[string]time.Duration{"2\n": 2 * time.Minute, "": 5 * time.Minute, "0": 5 * time.Minute, "x": 5 * time.Minute} { @@ -176,3 +176,10 @@ func TestTheViewWaitsBoundIsTheManifestsSetting(t *testing.T) { t.Errorf("no file gives %v", got) } } + +// TestOwnname runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestOwnname(t *testing.T) { + t.Run("TheEnginesOwnNameIsReadFromItsAppliedRecordOrItsFirstComposing", testTheEnginesOwnNameIsReadFromItsAppliedRecordOrItsFirstComposing) + t.Run("TheEntryAsksAreTheManifestsSetting", testTheEntryAsksAreTheManifestsSetting) + t.Run("TheViewWaitsBoundIsTheManifestsSetting", testTheViewWaitsBoundIsTheManifestsSetting) +} diff --git a/cmd/mesh-host/probe_test.go b/cmd/mesh-host/probe_test.go index be454719..367d8d3e 100644 --- a/cmd/mesh-host/probe_test.go +++ b/cmd/mesh-host/probe_test.go @@ -15,7 +15,7 @@ import ( // Defends novox/hq issue 233: a package manager that does not answer is said even when nothing declared // needs it — the apply is partial, never "applied" — and the report names it under one key, so the mesh // counts it as one failure that goes on. -func TestAPackageManagerThatDoesNotAnswerIsSaidWithNoPackageDeclared(t *testing.T) { +func testAPackageManagerThatDoesNotAnswerIsSaidWithNoPackageDeclared(t *testing.T) { unansweringPacman(t) dir := t.TempDir() opts := options{state: filepath.Join(dir, "state.json"), out: &strings.Builder{}} @@ -46,7 +46,7 @@ func TestAPackageManagerThatDoesNotAnswerIsSaidWithNoPackageDeclared(t *testing. // A system whose probe asks the system itself, not a tool a resource needs, still refuses whole: nothing // the mesh declares can remove it, and nothing else stands between that host and the wrong machine. -func TestASystemWithNoPackageManagerStillRefusesWhole(t *testing.T) { +func testASystemWithNoPackageManagerStillRefusesWhole(t *testing.T) { t.Setenv("PATH", t.TempDir()) sys, err := system.For("android") if err != nil { @@ -83,7 +83,7 @@ func pacmanAnsweringOnce(t *testing.T, conf string) { // installs its packages too**. The probe is asked again once the partial apply wrote something, and when it // answers the declaration is applied again over what the first pass left — the packages in this apply, not five // minutes later, and the report clean. -func TestThePackagesGoInWhenTheApplyThatRestoresThePackageManagerWroteIt(t *testing.T) { +func testThePackagesGoInWhenTheApplyThatRestoresThePackageManagerWroteIt(t *testing.T) { dir := t.TempDir() conf := filepath.Join(dir, "pacman.conf") pacmanAnsweringOnce(t, conf) @@ -108,7 +108,7 @@ func TestThePackagesGoInWhenTheApplyThatRestoresThePackageManagerWroteIt(t *test // Defends decision (1) of the review of novox/hq issue 233: **a package manager that is not there at all still // refuses whole**. That is the host installed on the wrong machine, which the probe exists to catch. -func TestAPackageManagerThatIsNotThereRefusesWhole(t *testing.T) { +func testAPackageManagerThatIsNotThereRefusesWhole(t *testing.T) { t.Setenv("PATH", t.TempDir()) was := builtFor builtFor = "arch" @@ -127,3 +127,11 @@ func TestAPackageManagerThatIsNotThereRefusesWhole(t *testing.T) { t.Error("the refused declaration touched the machine") } } + +// TestProbe runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestProbe(t *testing.T) { + t.Run("APackageManagerThatDoesNotAnswerIsSaidWithNoPackageDeclared", testAPackageManagerThatDoesNotAnswerIsSaidWithNoPackageDeclared) + t.Run("ASystemWithNoPackageManagerStillRefusesWhole", testASystemWithNoPackageManagerStillRefusesWhole) + t.Run("ThePackagesGoInWhenTheApplyThatRestoresThePackageManagerWroteIt", testThePackagesGoInWhenTheApplyThatRestoresThePackageManagerWroteIt) + t.Run("APackageManagerThatIsNotThereRefusesWhole", testAPackageManagerThatIsNotThereRefusesWhole) +} diff --git a/cmd/mesh-host/recorded_test.go b/cmd/mesh-host/recorded_test.go index 849e8e9b..b1cf3c37 100644 --- a/cmd/mesh-host/recorded_test.go +++ b/cmd/mesh-host/recorded_test.go @@ -13,7 +13,7 @@ import ( // The record check reads the engine's applied state: a composition one of whose resources has no record there is not // recorded (issue 1945). -func TestACompositionIsRecordedOnlyWhenEveryResourceIs(t *testing.T) { +func testACompositionIsRecordedOnlyWhenEveryResourceIs(t *testing.T) { path := filepath.Join(t.TempDir(), "state.json") var s store.State s.Record(store.Applied{ID: "ca-trust.trust", Type: "file", Target: "/etc/ca"}) @@ -34,7 +34,7 @@ func TestACompositionIsRecordedOnlyWhenEveryResourceIs(t *testing.T) { } // The modules applied again are those with a missing resource, each once; one down but there is not among them. -func TestTheModulesAppliedAgainAreThoseWithAMissingResource(t *testing.T) { +func testTheModulesAppliedAgainAreThoseWithAMissingResource(t *testing.T) { t.Run("1957: the machine shows a resource not active", testTheMachineShowsAResourceNotActive) st := liveness.Statement{Resources: []liveness.State{ {Resource: liveness.Resource{Module: "matrix", ID: "matrix.homeserver"}, State: liveness.Unhealthy, Missing: true}, @@ -50,7 +50,7 @@ func TestTheModulesAppliedAgainAreThoseWithAMissingResource(t *testing.T) { // A module is applied again only for a resource newly missing: one still missing at the next change of the statement is // not acted on again, so a resource that cannot be made is not applied (and backed up) at every unrelated change. One // that comes back and goes again is newly missing again (the review of issue 1945). -func TestOnlyANewlyMissingResourceAppliesItsModuleAgain(t *testing.T) { +func testOnlyANewlyMissingResourceAppliesItsModuleAgain(t *testing.T) { t.Run("1957: a resource newly down is an edge", testOnlyAResourceNewlyDownIsAnEdge) missing := func(ids ...string) liveness.Statement { var st liveness.Statement @@ -79,7 +79,7 @@ func TestOnlyANewlyMissingResourceAppliesItsModuleAgain(t *testing.T) { // A file the provisioner client fills is left to it by the apply and has no record until the client writes it: it does // not make its composition unrecorded (the review of issue 1945). -func TestAFilledFileDoesNotMakeItsCompositionUnrecorded(t *testing.T) { +func testAFilledFileDoesNotMakeItsCompositionUnrecorded(t *testing.T) { path := filepath.Join(t.TempDir(), "state.json") var s store.State s.Record(store.Applied{ID: "ca-trust.trust", Type: "file", Target: "/etc/ca"}) @@ -93,3 +93,11 @@ func TestAFilledFileDoesNotMakeItsCompositionUnrecorded(t *testing.T) { t.Fatal("a filled file the client has not written made its composition unrecorded") } } + +// TestRecorded runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRecorded(t *testing.T) { + t.Run("ACompositionIsRecordedOnlyWhenEveryResourceIs", testACompositionIsRecordedOnlyWhenEveryResourceIs) + t.Run("TheModulesAppliedAgainAreThoseWithAMissingResource", testTheModulesAppliedAgainAreThoseWithAMissingResource) + t.Run("OnlyANewlyMissingResourceAppliesItsModuleAgain", testOnlyANewlyMissingResourceAppliesItsModuleAgain) + t.Run("AFilledFileDoesNotMakeItsCompositionUnrecorded", testAFilledFileDoesNotMakeItsCompositionUnrecorded) +} diff --git a/cmd/mesh-host/replay233_test.go b/cmd/mesh-host/replay233_test.go index 9cc0277f..c9fd81a6 100644 --- a/cmd/mesh-host/replay233_test.go +++ b/cmd/mesh-host/replay233_test.go @@ -35,7 +35,7 @@ func unansweringPacman(t *testing.T) { // Held to: a declaration that restores the file is applied while pacman does not answer. Only what needs // pacman fails, with the probe's words; the file is written and recorded. Written only with what the // node-engine had before the fix, so it lays over the commit before it, where it fails. -func TestReplay233(t *testing.T) { +func testReplay233(t *testing.T) { unansweringPacman(t) dir := t.TempDir() opts := options{state: filepath.Join(dir, "state.json")} @@ -78,7 +78,7 @@ func failedWords(failed map[string]string) []string { // Defends novox/hq issue 233 at the machine: `mesh-host apply` applies what does not need the package // manager, and says the apply was partial with the probe's words — a non-zero exit, never "applied". -func TestApplyByHandAppliesWhatDoesNotNeedAPackageManagerThatDoesNotAnswer(t *testing.T) { +func testApplyByHandAppliesWhatDoesNotNeedAPackageManagerThatDoesNotAnswer(t *testing.T) { unansweringPacman(t) dir := t.TempDir() out := &bytes.Buffer{} @@ -107,3 +107,9 @@ func TestApplyByHandAppliesWhatDoesNotNeedAPackageManagerThatDoesNotAnswer(t *te t.Errorf("what was said before applying does not say the package manager does not answer:\n%s", out.String()) } } + +// TestReplay233File runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestReplay233File(t *testing.T) { + t.Run("Replay233", testReplay233) + t.Run("ApplyByHandAppliesWhatDoesNotNeedAPackageManagerThatDoesNotAnswer", testApplyByHandAppliesWhatDoesNotNeedAPackageManagerThatDoesNotAnswer) +} diff --git a/cmd/mesh-host/settled_manifest_test.go b/cmd/mesh-host/settled_manifest_test.go index 395819bf..cc896374 100644 --- a/cmd/mesh-host/settled_manifest_test.go +++ b/cmd/mesh-host/settled_manifest_test.go @@ -10,7 +10,7 @@ import ( // The subject the engine hears for a store settling is the event its manifest consumes: the grants part grants an account // what its manifest consumes and nothing named in code (novox/hq ADR 0625 §4). -func TestTheSettledEventIsTheManifestsConsume(t *testing.T) { +func testTheSettledEventIsTheManifestsConsume(t *testing.T) { raw, err := os.ReadFile("../../module.json") if err != nil { t.Fatal(err) @@ -29,7 +29,7 @@ func TestTheSettledEventIsTheManifestsConsume(t *testing.T) { // The manifest claims the seat node-engine, says its findings on its own stream and hears the keeper's ask and the // node-engine seat's running (design 47 G §364, §387, §199). -func TestTheManifestClaimsItsSeatAndSaysItsFindings(t *testing.T) { +func testTheManifestClaimsItsSeatAndSaysItsFindings(t *testing.T) { raw, err := os.ReadFile("../../module.json") if err != nil { t.Fatal(err) @@ -65,3 +65,9 @@ func TestTheManifestClaimsItsSeatAndSaysItsFindings(t *testing.T) { t.Errorf("version = %q, want MAJOR.MINOR 0.1 (§368, §411)", m.Version) } } + +// TestSettledManifest runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSettledManifest(t *testing.T) { + t.Run("TheSettledEventIsTheManifestsConsume", testTheSettledEventIsTheManifestsConsume) + t.Run("TheManifestClaimsItsSeatAndSaysItsFindings", testTheManifestClaimsItsSeatAndSaysItsFindings) +} diff --git a/cmd/mesh-host/units_test.go b/cmd/mesh-host/units_test.go index bbbcf32d..63f46b98 100644 --- a/cmd/mesh-host/units_test.go +++ b/cmd/mesh-host/units_test.go @@ -19,7 +19,7 @@ import ( // The machine's failed units in the engine's statement (novox/hq issue 315): a module's is among the // resources, unhealthy, as that module's unit, naming it; the machine's own beside them; and an engine // not reading them says nothing of them. -func TestTheStatementCarriesTheFailedUnits(t *testing.T) { +func testTheStatementCarriesTheFailedUnits(t *testing.T) { at := time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC) us := &units.Statement{At: at, State: units.Degraded, Failed: []units.Failed{ {Unit: "openrazer-daemon.service", Scope: units.ScopeUser, Load: "loaded", Result: "exit-code", @@ -55,7 +55,7 @@ func TestTheStatementCarriesTheFailedUnits(t *testing.T) { // Every resource that runs in an account's own service manager names the account, and so does the account // a module put in a group (novox/hq ADR 0254): the controller reads a unit that cannot run before a new login // by the two together. What the machine's own manager runs names none. -func TestTheStatementNamesTheAccountsManager(t *testing.T) { +func testTheStatementNamesTheAccountsManager(t *testing.T) { at := time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC) st := liveness.Statement{At: at, Resources: []liveness.State{ {Resource: liveness.Resource{Module: "openrazer", ID: "openrazer.daemon", Kind: "service", @@ -82,7 +82,7 @@ func TestTheStatementNamesTheAccountsManager(t *testing.T) { // An account declared never to become root (novox/hq ADR 0266) is said with root never, under the contract // that tells the controller this engine judges it; an account judged for its groups alone is not. -func TestTheStatementSaysAnAccountJudgedForRoot(t *testing.T) { +func testTheStatementSaysAnAccountJudgedForRoot(t *testing.T) { at := time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC) as := &accounts.Statement{At: at, Accounts: []accounts.Verdict{ {Account: accounts.Account{Module: "claude-code", ID: "claude-code.agent", Name: "agent", Root: true}, @@ -166,7 +166,7 @@ func TestTheStatementSaysAnAccountJudgedForRoot(t *testing.T) { // A verdict waiting for the setuid search says how far it got, in the reason the root-free verb repeats and as // fields (novox/hq issue 361); a mount point, never a path the walk visited or found. -func TestTheStatementSaysHowFarTheSetuidSearchGot(t *testing.T) { +func testTheStatementSaysHowFarTheSetuidSearchGot(t *testing.T) { at := time.Date(2026, 10, 10, 1, 40, 0, 0, time.UTC) sp := &accounts.SearchProgress{Started: at, Filesystems: 3, Done: 1, Walking: "/home", Visited: 42, Found: 2, Kept: at, Finished: []accounts.SearchedFilesystem{{Mount: "/", Took: 90 * time.Second}}} @@ -185,3 +185,11 @@ func TestTheStatementSaysHowFarTheSetuidSearchGot(t *testing.T) { t.Fatalf("the fields: %+v", s) } } + +// TestUnits runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestUnits(t *testing.T) { + t.Run("TheStatementCarriesTheFailedUnits", testTheStatementCarriesTheFailedUnits) + t.Run("TheStatementNamesTheAccountsManager", testTheStatementNamesTheAccountsManager) + t.Run("TheStatementSaysAnAccountJudgedForRoot", testTheStatementSaysAnAccountJudgedForRoot) + t.Run("TheStatementSaysHowFarTheSetuidSearchGot", testTheStatementSaysHowFarTheSetuidSearchGot) +} diff --git a/cmd/mesh-host/vaultbox_nats_test.go b/cmd/mesh-host/vaultbox_nats_test.go index 30e0fd52..b536fb22 100644 --- a/cmd/mesh-host/vaultbox_nats_test.go +++ b/cmd/mesh-host/vaultbox_nats_test.go @@ -28,7 +28,7 @@ import ( const coreCredential = "the-provisioner-clients-bus-password-2025" -func TestNatsTheEngineFillsACoreCredentialFromTheVaultsBoxWithNoValueInTheClear(t *testing.T) { +func testNatsTheEngineFillsACoreCredentialFromTheVaultsBoxWithNoValueInTheClear(t *testing.T) { url := os.Getenv("MESH_TEST_NATS") if url == "" { t.Skip("MESH_TEST_NATS unset") @@ -133,7 +133,7 @@ func TestNatsTheEngineFillsACoreCredentialFromTheVaultsBoxWithNoValueInTheClear( } // The engine opens a value the controller sealed (the NaCl box) as before, and the vault's box, with one key. -func TestTheEnginesOpenerOpensBothBoxes(t *testing.T) { +func testTheEnginesOpenerOpensBothBoxes(t *testing.T) { state := filepath.Join(t.TempDir(), "state.json") key, _ := identity.GenerateSealingKey() if err := os.WriteFile(identity.SealingKeyPath(state), []byte(key.Private), 0o600); err != nil { @@ -151,3 +151,9 @@ func TestTheEnginesOpenerOpensBothBoxes(t *testing.T) { t.Errorf("the vault's box opened to %q, %v", got, err) } } + +// TestVaultboxNats runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestVaultboxNats(t *testing.T) { + t.Run("NatsTheEngineFillsACoreCredentialFromTheVaultsBoxWithNoValueInTheClear", testNatsTheEngineFillsACoreCredentialFromTheVaultsBoxWithNoValueInTheClear) + t.Run("TheEnginesOpenerOpensBothBoxes", testTheEnginesOpenerOpensBothBoxes) +} diff --git a/cmd/mesh-host/version_from_path_test.go b/cmd/mesh-host/version_from_path_test.go index 4b00d953..af9d3411 100644 --- a/cmd/mesh-host/version_from_path_test.go +++ b/cmd/mesh-host/version_from_path_test.go @@ -10,7 +10,7 @@ import ( // toolchain stamps no version — a build does not know what it will be called — so a delivered host // read as "development build" and the mesh could not tell which host a machine ran (04-ISSUES/161). -func TestADeliveredHostReadsItsVersionFromItsPath(t *testing.T) { +func testADeliveredHostReadsItsVersionFromItsPath(t *testing.T) { // A delivered host lives at /versions//. dir := t.TempDir() versioned := filepath.Join(dir, "versions", "637f65559d16") @@ -26,7 +26,7 @@ func TestADeliveredHostReadsItsVersionFromItsPath(t *testing.T) { } } -func TestAHostPlacedByHandKeepsItsStamp(t *testing.T) { +func testAHostPlacedByHandKeepsItsStamp(t *testing.T) { // The honest answer for one the mesh did not deliver — and every machine is in that state until // a delivery reaches it. if got := versionAt("/usr/bin/nox-mesh-host", "04a27ca"); got != "04a27ca" { @@ -34,7 +34,7 @@ func TestAHostPlacedByHandKeepsItsStamp(t *testing.T) { } } -func TestADirectoryThatIsNotAVersionIsNotReadAsOne(t *testing.T) { +func testADirectoryThatIsNotAVersionIsNotReadAsOne(t *testing.T) { // A binary sitting anywhere else must not have its parent directory's name read as a version. for _, path := range []string{ "/opt/somewhere/nox-mesh-host", @@ -46,3 +46,10 @@ func TestADirectoryThatIsNotAVersionIsNotReadAsOne(t *testing.T) { } } } + +// TestVersionFromPath runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestVersionFromPath(t *testing.T) { + t.Run("ADeliveredHostReadsItsVersionFromItsPath", testADeliveredHostReadsItsVersionFromItsPath) + t.Run("AHostPlacedByHandKeepsItsStamp", testAHostPlacedByHandKeepsItsStamp) + t.Run("ADirectoryThatIsNotAVersionIsNotReadAsOne", testADirectoryThatIsNotAVersionIsNotReadAsOne) +} diff --git a/cmd/mesh-host/whatruns_test.go b/cmd/mesh-host/whatruns_test.go index efb5dc4a..676745ac 100644 --- a/cmd/mesh-host/whatruns_test.go +++ b/cmd/mesh-host/whatruns_test.go @@ -34,7 +34,7 @@ func aFileOf(module, id string) json.RawMessage { // What runs is the agent's compositions and the kept declaration's resources for each module the agent does not hold; // the node's own parts are the kept declaration's until the agent holds the node's composition (ADR 0539 §9). One module // under the agent must not make the rest invisible to the liveness, units, accounts, libraries, filling and the take act. -func TestWhatRunsIsTheAgentsCompositionsAndTheKeptRest(t *testing.T) { +func testWhatRunsIsTheAgentsCompositionsAndTheKeptRest(t *testing.T) { kept := &declaration.Declaration{Identities: []declaration.Identity{{Module: "db", Name: "mesh-db"}}, Libraries: []declaration.Library{{Library: "media"}}} everything := []engcomp.Composed{ @@ -62,7 +62,7 @@ func TestWhatRunsIsTheAgentsCompositionsAndTheKeptRest(t *testing.T) { } // What the take act, the judgement of directories and the filling read is what runs, not the frozen kept declaration. -func TestDeclaredNowReadsWhatRunsWhenTheAgentIsRunning(t *testing.T) { +func testDeclaredNowReadsWhatRunsWhenTheAgentIsRunning(t *testing.T) { t.Run("a fill while the agent restarts", aFillWhileTheAgentRestartsIsWrittenAfterwards) setRunsHere(func(string, ed25519.PublicKey) (*declaration.Declaration, error) { return &declaration.Declaration{Version: 1, Resources: nil, Provisioner: "from-agent"}, nil @@ -167,7 +167,7 @@ func TestDeclaredNowReadsWhatRunsWhenTheAgentIsRunning(t *testing.T) { // 1945/AC17 (unit): a resource the node's own composition shares with a running module's composition is declared once, // the module's: the declaration joined of both names each file once, so the filling writes it; the node's own resources // no module declares stay. (Live from 2026-10-25 12:43: "2 resources declare X" on every node.) -func TestTheNodesOwnCopyOfAModulesResourceIsLeftOut(t *testing.T) { +func testTheNodesOwnCopyOfAModulesResourceIsLeftOut(t *testing.T) { own := engcomp.Composed{Node: "n1", Resources: []json.RawMessage{aFileOf("zsh", "rc"), aFileOf("mesh-wireguard", "conf")}, Filled: []string{"/tmp/r6/zsh/rc"}} zsh := engcomp.Composed{Node: "n1", Module: "zsh", FP: "src2:aa", Resources: []json.RawMessage{aFileOf("zsh", "rc")}, @@ -203,7 +203,7 @@ func TestTheNodesOwnCopyOfAModulesResourceIsLeftOut(t *testing.T) { // 1945/AC18 (unit): the kept declaration's filled paths go to the module whose file is at each path, the node's own to // the node's; and what runs from it, joined with the node's composition, names them filled. -func TestTheKeptDeclarationsFilledPathsGoToTheirModules(t *testing.T) { +func testTheKeptDeclarationsFilledPathsGoToTheirModules(t *testing.T) { raw := []byte(`{"resources":[ {"id":"claude-code.settings","type":"file","module":"claude-code","path":"/etc/cc.json"}, {"id":"screen-lock.conf","type":"file","module":"screen-lock","path":"/etc/lock.conf"}, @@ -231,7 +231,7 @@ func TestTheKeptDeclarationsFilledPathsGoToTheirModules(t *testing.T) { // 1945/AC17 (unit, review): a resource of the node's own that shares only its target with a module's (another id: a // unit or a container of the same name) is not the module's, and is neither dropped nor left to be removed. -func TestASharedTargetWithAnotherIDIsNotDropped(t *testing.T) { +func testASharedTargetWithAnotherIDIsNotDropped(t *testing.T) { ownFile, _ := json.Marshal(map[string]any{"id": "host.zshrc", "type": "file", "path": "/tmp/r6/zsh/rc", "content": "x"}) own := engcomp.Composed{Node: "n1", Resources: []json.RawMessage{ownFile}} zsh := engcomp.Composed{Node: "n1", Module: "zsh", FP: "src2:aa", Resources: []json.RawMessage{aFileOf("zsh", "rc")}} @@ -303,3 +303,12 @@ func aFillWhileTheAgentRestartsIsWrittenAfterwards(t *testing.T) { t.Fatalf("the kept view stays after the new agent holds the node: %v, %v", err, current.lastView()) } } + +// TestWhatruns runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestWhatruns(t *testing.T) { + t.Run("WhatRunsIsTheAgentsCompositionsAndTheKeptRest", testWhatRunsIsTheAgentsCompositionsAndTheKeptRest) + t.Run("DeclaredNowReadsWhatRunsWhenTheAgentIsRunning", testDeclaredNowReadsWhatRunsWhenTheAgentIsRunning) + t.Run("TheNodesOwnCopyOfAModulesResourceIsLeftOut", testTheNodesOwnCopyOfAModulesResourceIsLeftOut) + t.Run("TheKeptDeclarationsFilledPathsGoToTheirModules", testTheKeptDeclarationsFilledPathsGoToTheirModules) + t.Run("ASharedTargetWithAnotherIDIsNotDropped", testASharedTargetWithAnotherIDIsNotDropped) +} diff --git a/cmd/mesh-host/witnessing_test.go b/cmd/mesh-host/witnessing_test.go index 3e304b65..4cffb6f0 100644 --- a/cmd/mesh-host/witnessing_test.go +++ b/cmd/mesh-host/witnessing_test.go @@ -15,7 +15,7 @@ import ( // The first have this build writes proves it to the launcher; nothing else does — not a report about a declaration, not // a facts event, not the haves of another build (novox/hq ADR 0539 §9, ADR 0227 §8). R6-A AC7. -func TestOnlyAHaveUnderThisBuildProvesIt(t *testing.T) { +func testOnlyAHaveUnderThisBuildProvesIt(t *testing.T) { state := filepath.Join(t.TempDir(), "state.json") t.Setenv("MESH_HOST_LIBEXEC", t.TempDir()) // Never the machine's own engine placed by hand: proving renews it (issue 356). @@ -65,7 +65,7 @@ func TestOnlyAHaveUnderThisBuildProvesIt(t *testing.T) { } // Every verdict that stands is said, and a reconcile that has one says it unasked. -func TestAStandingRollbackIsSaidOnEveryReport(t *testing.T) { +func testAStandingRollbackIsSaidOnEveryReport(t *testing.T) { state := filepath.Join(t.TempDir(), "state.json") line := "2.0\t1.0\t1759744800\trolled-back\tit did not report within 600s of starting\n" if err := os.WriteFile(upgrade.RolledBackPath(state), []byte(line), 0o644); err != nil { @@ -80,7 +80,7 @@ func TestAStandingRollbackIsSaidOnEveryReport(t *testing.T) { // The launcher running this host is known to have been replaced only when it certainly was: a shell // reading the launcher, from a file renamed over. Asked of a real process, not a model of one. -func TestAReplacedLauncherIsSeen(t *testing.T) { +func testAReplacedLauncherIsSeen(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "launch") if err := os.WriteFile(path, []byte("#!/bin/sh\nsleep 5\necho done\n"), 0o755); err != nil { @@ -110,3 +110,10 @@ func TestAReplacedLauncherIsSeen(t *testing.T) { t.Fatal("a process reading another script reads as this launcher") } } + +// TestWitnessing runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestWitnessing(t *testing.T) { + t.Run("OnlyAHaveUnderThisBuildProvesIt", testOnlyAHaveUnderThisBuildProvesIt) + t.Run("AStandingRollbackIsSaidOnEveryReport", testAStandingRollbackIsSaidOnEveryReport) + t.Run("AReplacedLauncherIsSeen", testAReplacedLauncherIsSeen) +} diff --git a/examples/bundle_test.go b/examples/bundle_test.go index 355fb481..c6297d74 100644 --- a/examples/bundle_test.go +++ b/examples/bundle_test.go @@ -33,7 +33,7 @@ func bundle(t *testing.T) *declaration.Declaration { // The object store was foundation for months on the strength of "it cannot grant itself a bucket", // which answers half the test. The control plane never needed one, and nothing noticed because // nothing counted what the bundle holds. -func TestTheBundleCarriesTheFoundationAndTheControlPlaneAndNothingElse(t *testing.T) { +func testTheBundleCarriesTheFoundationAndTheControlPlaneAndNothingElse(t *testing.T) { var images []string for _, r := range bundle(t).Resources { c, ok := r.(*declaration.Container) @@ -59,7 +59,7 @@ func TestTheBundleCarriesTheFoundationAndTheControlPlaneAndNothingElse(t *testin // The control plane is in the bundle, and the design overlooked it once by reasoning about // foundation services rather than counting containers (novox/hq 03-DESIGN/01-to-be/07). -func TestTheControlPlaneIsCarriedToo(t *testing.T) { +func testTheControlPlaneIsCarriedToo(t *testing.T) { for _, r := range bundle(t).Resources { if c, ok := r.(*declaration.Container); ok && strings.Contains(c.Image, "mesh-controller") { return @@ -71,7 +71,7 @@ func TestTheControlPlaneIsCarriedToo(t *testing.T) { // One genesis bundle, on the bus the mesh runs on (novox/hq ADR 0331 §2). Two bundles let every bed // and README name the one that could not raise a mesh, for weeks (issue 146). -func TestThereIsOneGenesisBundle(t *testing.T) { +func testThereIsOneGenesisBundle(t *testing.T) { bundles, err := filepath.Glob("*.lock") if err != nil { t.Fatal(err) @@ -83,7 +83,7 @@ func TestThereIsOneGenesisBundle(t *testing.T) { // The control plane the bundle raises is given the bus, with the account the installer fills and // the certificate it pins (ADR 0331 §4); without it, it crash-loops for ever (issue 146). -func TestTheControlPlaneIsGivenTheBus(t *testing.T) { +func testTheControlPlaneIsGivenTheBus(t *testing.T) { for _, r := range bundle(t).Resources { c, ok := r.(*declaration.Container) if !ok || !strings.Contains(c.Image, "mesh-controller") { @@ -97,3 +97,11 @@ func TestTheControlPlaneIsGivenTheBus(t *testing.T) { } t.Fatal("nothing in the bundle starts the control plane") } + +// TestBundle runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBundle(t *testing.T) { + t.Run("TheBundleCarriesTheFoundationAndTheControlPlaneAndNothingElse", testTheBundleCarriesTheFoundationAndTheControlPlaneAndNothingElse) + t.Run("TheControlPlaneIsCarriedToo", testTheControlPlaneIsCarriedToo) + t.Run("ThereIsOneGenesisBundle", testThereIsOneGenesisBundle) + t.Run("TheControlPlaneIsGivenTheBus", testTheControlPlaneIsGivenTheBus) +} diff --git a/internal/accounts/accounts_test.go b/internal/accounts/accounts_test.go index b1556bf8..fd322dcc 100644 --- a/internal/accounts/accounts_test.go +++ b/internal/accounts/accounts_test.go @@ -82,7 +82,7 @@ func look(t *testing.T, m *machine) Verdict { return st.Accounts[0] } -func TestAGroupTheRunningSessionLacksSaysReloginNeeded(t *testing.T) { +func testAGroupTheRunningSessionLacksSaysReloginNeeded(t *testing.T) { m := &machine{t: t, proc: t.TempDir(), inDB: "operator wheel openrazer", pid: "4242", held: "998"} v := look(t, m) if v.State != Unhealthy || !strings.HasPrefix(v.Reason, ReasonRelogin) || !strings.Contains(v.Reason, "openrazer") || @@ -101,21 +101,21 @@ func TestAGroupTheRunningSessionLacksSaysReloginNeeded(t *testing.T) { } } -func TestASessionThatHasTheGroupIsHealthy(t *testing.T) { +func testASessionThatHasTheGroupIsHealthy(t *testing.T) { m := &machine{t: t, proc: t.TempDir(), inDB: "operator wheel openrazer", pid: "4242", held: "998 964"} if v := look(t, m); v.State != Healthy || v.Reason != "" { t.Fatalf("a session with the group: %+v", v) } } -func TestNoSessionIsHealthyTheNextLoginTakesTheGroup(t *testing.T) { +func testNoSessionIsHealthyTheNextLoginTakesTheGroup(t *testing.T) { m := &machine{t: t, proc: t.TempDir(), inDB: "operator openrazer", pid: "0"} if v := look(t, m); v.State != Healthy { t.Fatalf("no session: %+v", v) } } -func TestAnAccountTheDatabaseDoesNotListIsUnhealthySayingSo(t *testing.T) { +func testAnAccountTheDatabaseDoesNotListIsUnhealthySayingSo(t *testing.T) { m := &machine{t: t, proc: t.TempDir(), inDB: "operator wheel", pid: "4242", held: "998"} v := look(t, m) if v.State != Unhealthy || !strings.HasPrefix(v.Reason, "not in the group openrazer") { @@ -123,14 +123,14 @@ func TestAnAccountTheDatabaseDoesNotListIsUnhealthySayingSo(t *testing.T) { } } -func TestADatabaseThatDoesNotAnswerIsUnknownNeverHealthy(t *testing.T) { +func testADatabaseThatDoesNotAnswerIsUnknownNeverHealthy(t *testing.T) { m := &machine{t: t, proc: t.TempDir(), failsID: true} if v := look(t, m); v.State != Unknown { t.Fatalf("an unread database: %+v", v) } } -func TestOnlyAModulesAccountWithGroupsIsJudged(t *testing.T) { +func testOnlyAModulesAccountWithGroupsIsJudged(t *testing.T) { d, err := declaration.ParseTrusted([]byte(`{"declaration":1,"resources":[ {"id":"zsh.login","type":"user","name":"operator","shell":"/bin/zsh"}, {"id":"openrazer.account","type":"user","name":"operator","groups":["openrazer"]}, @@ -146,7 +146,7 @@ func TestOnlyAModulesAccountWithGroupsIsJudged(t *testing.T) { } } -func TestAVerdictThatHoldsCountsItsStreakAndAChangeIsSaid(t *testing.T) { +func testAVerdictThatHoldsCountsItsStreakAndAChangeIsSaid(t *testing.T) { m := &machine{t: t, proc: t.TempDir(), inDB: "operator openrazer", pid: "4242", held: "998"} m.status() j := New(Exec{Run: m.run, Proc: m.proc}) @@ -163,3 +163,14 @@ func TestAVerdictThatHoldsCountsItsStreakAndAChangeIsSaid(t *testing.T) { t.Fatalf("after the new login: changed %v, %+v", changed, st.Accounts[0]) } } + +// TestAccounts runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestAccounts(t *testing.T) { + t.Run("AGroupTheRunningSessionLacksSaysReloginNeeded", testAGroupTheRunningSessionLacksSaysReloginNeeded) + t.Run("ASessionThatHasTheGroupIsHealthy", testASessionThatHasTheGroupIsHealthy) + t.Run("NoSessionIsHealthyTheNextLoginTakesTheGroup", testNoSessionIsHealthyTheNextLoginTakesTheGroup) + t.Run("AnAccountTheDatabaseDoesNotListIsUnhealthySayingSo", testAnAccountTheDatabaseDoesNotListIsUnhealthySayingSo) + t.Run("ADatabaseThatDoesNotAnswerIsUnknownNeverHealthy", testADatabaseThatDoesNotAnswerIsUnknownNeverHealthy) + t.Run("OnlyAModulesAccountWithGroupsIsJudged", testOnlyAModulesAccountWithGroupsIsJudged) + t.Run("AVerdictThatHoldsCountsItsStreakAndAChangeIsSaid", testAVerdictThatHoldsCountsItsStreakAndAChangeIsSaid) +} diff --git a/internal/accounts/root_test.go b/internal/accounts/root_test.go index bb128e00..bf9362fb 100644 --- a/internal/accounts/root_test.go +++ b/internal/accounts/root_test.go @@ -185,13 +185,13 @@ func lookAgent(t *testing.T, m *agentMachine) Verdict { return st.Accounts[0] } -func TestAnAgentAccountWithNoWayToRootIsHealthyWithNobodyLoggedIn(t *testing.T) { +func testAnAgentAccountWithNoWayToRootIsHealthyWithNobodyLoggedIn(t *testing.T) { if v := lookAgent(t, clean()); v.State != Healthy || v.Reason != "" || !v.Root { t.Fatalf("no way to root: %+v", v) } } -func TestEachWayToRootIsSaid(t *testing.T) { +func testEachWayToRootIsSaid(t *testing.T) { for _, c := range []struct { name string set func(*agentMachine) @@ -222,7 +222,7 @@ func TestEachWayToRootIsSaid(t *testing.T) { } } -func TestEveryWayIsSaidAtOnce(t *testing.T) { +func testEveryWayIsSaidAtOnce(t *testing.T) { m := clean() m.groups = "agent docker" m.sudo = "User agent may run the following commands on box:\n (ALL) ALL\n" @@ -232,7 +232,7 @@ func TestEveryWayIsSaidAtOnce(t *testing.T) { } } -func TestAnUnansweredQuestionIsUnknownNeverHealthy(t *testing.T) { +func testAnUnansweredQuestionIsUnknownNeverHealthy(t *testing.T) { m := clean() m.failsID = true if v := lookAgent(t, m); v.State != Unknown { @@ -245,7 +245,7 @@ func TestAnUnansweredQuestionIsUnknownNeverHealthy(t *testing.T) { } } -func TestASecretNotThereYetIsNoWay(t *testing.T) { +func testASecretNotThereYetIsNoWay(t *testing.T) { m := clean() delete(m.files, "/var/lib/mesh/node-tools/broker") if v := lookAgent(t, m); v.State != Healthy { @@ -253,7 +253,7 @@ func TestASecretNotThereYetIsNoWay(t *testing.T) { } } -func TestSudoRules(t *testing.T) { +func testSudoRules(t *testing.T) { none := []struct { out string err error @@ -276,14 +276,14 @@ func TestSudoRules(t *testing.T) { } } -func TestReadable(t *testing.T) { +func testReadable(t *testing.T) { m := FileMode{UID: 1500, GID: 1500, Perm: 0o600} if Readable(m, 1600, map[int]bool{1600: true}) || !Readable(m, 1500, nil) || !Readable(m, 0, nil) { t.Fatal("owner bits") } } -func TestOfJudgesARootNeverAccountWithNoGroupsAndItsSecrets(t *testing.T) { +func testOfJudgesARootNeverAccountWithNoGroupsAndItsSecrets(t *testing.T) { d, err := declaration.ParseTrusted([]byte(`{"declaration":1,"resources":[ {"id":"claude-code.agent","type":"user","name":"agent","root":"never"}, {"id":"zsh.login","type":"user","name":"operator","shell":"/bin/zsh"}, @@ -300,3 +300,15 @@ func TestOfJudgesARootNeverAccountWithNoGroupsAndItsSecrets(t *testing.T) { t.Fatalf("judged: %+v", got) } } + +// TestRoot runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRoot(t *testing.T) { + t.Run("AnAgentAccountWithNoWayToRootIsHealthyWithNobodyLoggedIn", testAnAgentAccountWithNoWayToRootIsHealthyWithNobodyLoggedIn) + t.Run("EachWayToRootIsSaid", testEachWayToRootIsSaid) + t.Run("EveryWayIsSaidAtOnce", testEveryWayIsSaidAtOnce) + t.Run("AnUnansweredQuestionIsUnknownNeverHealthy", testAnUnansweredQuestionIsUnknownNeverHealthy) + t.Run("ASecretNotThereYetIsNoWay", testASecretNotThereYetIsNoWay) + t.Run("SudoRules", testSudoRules) + t.Run("Readable", testReadable) + t.Run("OfJudgesARootNeverAccountWithNoGroupsAndItsSecrets", testOfJudgesARootNeverAccountWithNoGroupsAndItsSecrets) +} diff --git a/internal/accounts/setuid_cache_test.go b/internal/accounts/setuid_cache_test.go index 6cf980d1..e5b2372f 100644 --- a/internal/accounts/setuid_cache_test.go +++ b/internal/accounts/setuid_cache_test.go @@ -66,7 +66,7 @@ func notJudged(t *testing.T, err error, pending bool) *SetuidNotJudged { return nj } -func TestTheSearchRunsToCompletionWithNoBound(t *testing.T) { +func testTheSearchRunsToCompletionWithNoBound(t *testing.T) { c := &SetuidCache{} g := newGate() if _, _, err := c.Look(at, root, g.search); err == nil { @@ -90,7 +90,7 @@ func TestTheSearchRunsToCompletionWithNoBound(t *testing.T) { } } -func TestAFreshCompleteSearchJudgesUntilItIsDue(t *testing.T) { +func testAFreshCompleteSearchJudgesUntilItIsDue(t *testing.T) { c := &SetuidCache{} g := newGate() c.Look(at, root, g.search) @@ -111,7 +111,7 @@ func TestAFreshCompleteSearchJudgesUntilItIsDue(t *testing.T) { g.finish(c) } -func TestAStaleSearchIsNotJudgedNeverFree(t *testing.T) { +func testAStaleSearchIsNotJudgedNeverFree(t *testing.T) { c := &SetuidCache{} g := newGate() c.Look(at, root, g.search) @@ -128,7 +128,7 @@ func TestAStaleSearchIsNotJudgedNeverFree(t *testing.T) { } } -func TestAnIncompleteSearchIsNeverFree(t *testing.T) { +func testAnIncompleteSearchIsNeverFree(t *testing.T) { c := &SetuidCache{} g := newGate() g.err = errors.New("the search for setuid programs did not complete its walk") @@ -162,7 +162,7 @@ func TestAnIncompleteSearchIsNeverFree(t *testing.T) { g.finish(c) } -func TestAnApplyThatMovedRootSearchesAgain(t *testing.T) { +func testAnApplyThatMovedRootSearchesAgain(t *testing.T) { c := &SetuidCache{} g := newGate() c.Look(at, root, g.search) @@ -198,7 +198,7 @@ func TestAnApplyThatMovedRootSearchesAgain(t *testing.T) { } // A filesystem the last complete search did not walk is not judged by it: not judged yet, and a search starts. -func TestAFilesystemTheSearchDidNotWalkIsNotJudgedByIt(t *testing.T) { +func testAFilesystemTheSearchDidNotWalkIsNotJudgedByIt(t *testing.T) { c := &SetuidCache{} g := newGate() c.Look(at, root, g.search) @@ -216,7 +216,7 @@ func TestAFilesystemTheSearchDidNotWalkIsNotJudgedByIt(t *testing.T) { // An ask to search again forgets the walk under way, so an engine restarted before the next search does not // carry on a walk that started before root acted. -func TestAnAskToSearchAgainIsNotLostToARestart(t *testing.T) { +func testAnAskToSearchAgainIsNotLostToARestart(t *testing.T) { dir := t.TempDir() paths := func() *SetuidCache { return &SetuidCache{Path: filepath.Join(dir, SetuidSearchFile), ProgressPath: filepath.Join(dir, SetuidProgressFile)} @@ -240,7 +240,7 @@ func TestAnAskToSearchAgainIsNotLostToARestart(t *testing.T) { // A cursor whose name is not UTF-8 is kept as its bytes: JSON strings would change it, and the resumed walk // would skip what it stood before. -func TestACursorOfAnyBytesIsKeptExactly(t *testing.T) { +func testACursorOfAnyBytesIsKeptExactly(t *testing.T) { p := &SetuidProgress{Started: at, Mounts: Paths{"/"}, Cursor: Cursors{"/": "/home/agent/\x80/x"}, Found: Paths{"/opt/\xff"}} var back SetuidProgress @@ -250,7 +250,7 @@ func TestACursorOfAnyBytesIsKeptExactly(t *testing.T) { } } -func TestTheCompleteSearchIsKeptAndReadAfterARestart(t *testing.T) { +func testTheCompleteSearchIsKeptAndReadAfterARestart(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, SetuidSearchFile) c := &SetuidCache{Path: path} @@ -277,7 +277,7 @@ func TestTheCompleteSearchIsKeptAndReadAfterARestart(t *testing.T) { g2.finish(again) } -func TestAKeptSearchNotRootsAloneIsNotRead(t *testing.T) { +func testAKeptSearchNotRootsAloneIsNotRead(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, SetuidSearchFile) c := &SetuidCache{Path: path} @@ -318,7 +318,7 @@ func TestAKeptSearchNotRootsAloneIsNotRead(t *testing.T) { } } -func TestAKeptSearchFromTheFutureIsNotFresh(t *testing.T) { +func testAKeptSearchFromTheFutureIsNotFresh(t *testing.T) { c := &SetuidCache{} g := newGate() c.Look(at, root, g.search) @@ -329,7 +329,7 @@ func TestAKeptSearchFromTheFutureIsNotFresh(t *testing.T) { g.finish(c) } -func TestTheIdleRunnerLowersItsCommand(t *testing.T) { +func testTheIdleRunnerLowersItsCommand(t *testing.T) { if _, err := exec.LookPath("nice"); err != nil { t.Skip("no nice here") } @@ -373,7 +373,7 @@ func interrupted(seen chan<- *SetuidProgress) SetuidSearch { } } -func TestASearchInterruptedByARestartCarriesOnAndIsDatedByItsStart(t *testing.T) { +func testASearchInterruptedByARestartCarriesOnAndIsDatedByItsStart(t *testing.T) { dir := t.TempDir() paths := func() *SetuidCache { return &SetuidCache{Path: filepath.Join(dir, SetuidSearchFile), ProgressPath: filepath.Join(dir, SetuidProgressFile)} @@ -406,7 +406,7 @@ func TestASearchInterruptedByARestartCarriesOnAndIsDatedByItsStart(t *testing.T) } } -func TestAWalkTooOldOrAskedAgainStartsOver(t *testing.T) { +func testAWalkTooOldOrAskedAgainStartsOver(t *testing.T) { for name, c := range map[string]struct { after time.Duration again bool @@ -434,7 +434,7 @@ func TestAWalkTooOldOrAskedAgainStartsOver(t *testing.T) { } } -func TestASearchWhosePriorityCannotBeLoweredDoesNotWalk(t *testing.T) { +func testASearchWhosePriorityCannotBeLoweredDoesNotWalk(t *testing.T) { c := &SetuidCache{Lower: func() error { return errors.New("not permitted") }} walked := false c.Look(at, root, func(context.Context, *SetuidProgress, func()) ([]string, error) { walked = true; return nil, nil }) @@ -445,3 +445,22 @@ func TestASearchWhosePriorityCannotBeLoweredDoesNotWalk(t *testing.T) { t.Fatal("it walked at full priority") } } + +// TestSetuidCache runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSetuidCache(t *testing.T) { + t.Run("TheSearchRunsToCompletionWithNoBound", testTheSearchRunsToCompletionWithNoBound) + t.Run("AFreshCompleteSearchJudgesUntilItIsDue", testAFreshCompleteSearchJudgesUntilItIsDue) + t.Run("AStaleSearchIsNotJudgedNeverFree", testAStaleSearchIsNotJudgedNeverFree) + t.Run("AnIncompleteSearchIsNeverFree", testAnIncompleteSearchIsNeverFree) + t.Run("AnApplyThatMovedRootSearchesAgain", testAnApplyThatMovedRootSearchesAgain) + t.Run("AFilesystemTheSearchDidNotWalkIsNotJudgedByIt", testAFilesystemTheSearchDidNotWalkIsNotJudgedByIt) + t.Run("AnAskToSearchAgainIsNotLostToARestart", testAnAskToSearchAgainIsNotLostToARestart) + t.Run("ACursorOfAnyBytesIsKeptExactly", testACursorOfAnyBytesIsKeptExactly) + t.Run("TheCompleteSearchIsKeptAndReadAfterARestart", testTheCompleteSearchIsKeptAndReadAfterARestart) + t.Run("AKeptSearchNotRootsAloneIsNotRead", testAKeptSearchNotRootsAloneIsNotRead) + t.Run("AKeptSearchFromTheFutureIsNotFresh", testAKeptSearchFromTheFutureIsNotFresh) + t.Run("TheIdleRunnerLowersItsCommand", testTheIdleRunnerLowersItsCommand) + t.Run("ASearchInterruptedByARestartCarriesOnAndIsDatedByItsStart", testASearchInterruptedByARestartCarriesOnAndIsDatedByItsStart) + t.Run("AWalkTooOldOrAskedAgainStartsOver", testAWalkTooOldOrAskedAgainStartsOver) + t.Run("ASearchWhosePriorityCannotBeLoweredDoesNotWalk", testASearchWhosePriorityCannotBeLoweredDoesNotWalk) +} diff --git a/internal/accounts/setuid_pace_test.go b/internal/accounts/setuid_pace_test.go index 5d117ef0..3d65ae20 100644 --- a/internal/accounts/setuid_pace_test.go +++ b/internal/accounts/setuid_pace_test.go @@ -76,7 +76,7 @@ func (f *fakePace) paused() time.Duration { return total } -func TestTheWalkPausesWhileTheDiskIsUnderPressureAndGoesOnWhenItEases(t *testing.T) { +func testTheWalkPausesWhileTheDiskIsUnderPressureAndGoesOnWhenItEases(t *testing.T) { f := newFake(60, 40, 3) pc := f.pacer() if err := pc.yield(t.Context()); err != nil { // the first look sets where the counter counts from @@ -92,7 +92,7 @@ func TestTheWalkPausesWhileTheDiskIsUnderPressureAndGoesOnWhenItEases(t *testing } } -func TestTheFirstLookOnlySetsWhereTheNextCountsFrom(t *testing.T) { +func testTheFirstLookOnlySetsWhereTheNextCountsFrom(t *testing.T) { f := newFake(99) if err := f.pacer().yield(t.Context()); err != nil { t.Fatal(err) @@ -102,7 +102,7 @@ func TestTheFirstLookOnlySetsWhereTheNextCountsFrom(t *testing.T) { } } -func TestTheWalkDoesNotPauseOnAQuietDisk(t *testing.T) { +func testTheWalkDoesNotPauseOnAQuietDisk(t *testing.T) { f := newFake(0.4) pc := f.pacer() for range 10 { @@ -117,7 +117,7 @@ func TestTheWalkDoesNotPauseOnAQuietDisk(t *testing.T) { } // The control-node's own load sits near the bound with no walk running: the walk must still end (issue 361). -func TestTheWalkKeepsATenthOfTheTimeWhateverThePressure(t *testing.T) { +func testTheWalkKeepsATenthOfTheTimeWhateverThePressure(t *testing.T) { f := newFake(100) pc := f.pacer() var read time.Duration @@ -140,7 +140,7 @@ func TestTheWalkKeepsATenthOfTheTimeWhateverThePressure(t *testing.T) { // control-node on 2026-10-11, slowed to its worst, still completes well inside the time the controller stays quiet // while it waits for a search. A guard on the constants only: that the code keeps to the ratio is proven by // TestTheWalkKeepsATenthOfTheTimeWhateverThePressure. -func TestTheSlowestPacedWalkStillJudgesInTime(t *testing.T) { +func testTheSlowestPacedWalkStillJudgesInTime(t *testing.T) { const unpaced = 16*time.Minute + 31*time.Second worst := (1 + PaceRatio) * unpaced if worst >= rootsearch.Quiet { @@ -149,7 +149,7 @@ func TestTheSlowestPacedWalkStillJudgesInTime(t *testing.T) { } } -func TestARunOfPausesIsAtMostPaceAtMost(t *testing.T) { +func testARunOfPausesIsAtMostPaceAtMost(t *testing.T) { f := newFake(100) pc := f.pacer() if err := pc.yield(t.Context()); err != nil { @@ -164,7 +164,7 @@ func TestARunOfPausesIsAtMostPaceAtMost(t *testing.T) { } } -func TestTheWalkLooksAtThePressureAtMostEveryPaceLook(t *testing.T) { +func testTheWalkLooksAtThePressureAtMostEveryPaceLook(t *testing.T) { f := newFake(1) pc := f.pacer() for range 5 { @@ -186,7 +186,7 @@ func TestTheWalkLooksAtThePressureAtMostEveryPaceLook(t *testing.T) { } // Pressure that cannot be read pauses nothing, and is said once, with what it means, rather than at every look. -func TestAPressureThatCannotBeReadIsSaidOnce(t *testing.T) { +func testAPressureThatCannotBeReadIsSaidOnce(t *testing.T) { f := newFake(0) f.fail = errors.New("no such file") pc := f.pacer() @@ -205,7 +205,7 @@ func TestAPressureThatCannotBeReadIsSaidOnce(t *testing.T) { } // The engine's own walk is paced by the machine's pressure, and says through the search's own channel. -func TestTheEnginesWalkIsPacedByTheMachinesPressure(t *testing.T) { +func testTheEnginesWalkIsPacedByTheMachinesPressure(t *testing.T) { var said []string w := engineWalker(nil, func(s string) { said = append(said, s) }) if w.pace == nil || w.pace.path != ioPressureFile || w.pace.stalled == nil { @@ -227,7 +227,7 @@ func many(t *testing.T) string { } // A walk ended while it pauses is an incomplete walk, never one that found nothing. -func TestAWalkEndedWhileItPausesIsIncomplete(t *testing.T) { +func testAWalkEndedWhileItPausesIsIncomplete(t *testing.T) { top := many(t) f := newFake(80) f.tick = 100 * time.Millisecond @@ -252,7 +252,7 @@ func TestAWalkEndedWhileItPausesIsIncomplete(t *testing.T) { } // Paced, the walk finds what it finds unpaced: pausing changes when, never what. -func TestAPacedWalkFindsWhatAnUnpacedWalkFinds(t *testing.T) { +func testAPacedWalkFindsWhatAnUnpacedWalkFinds(t *testing.T) { top := many(t) plain := walkAll(t, mine(), top) @@ -269,7 +269,7 @@ func TestAPacedWalkFindsWhatAnUnpacedWalkFinds(t *testing.T) { } } -func TestTheIOPressureIsReadAsTheKernelWritesIt(t *testing.T) { +func testTheIOPressureIsReadAsTheKernelWritesIt(t *testing.T) { got, err := parseIOStalled([]byte("some avg10=26.24 avg60=20.07 avg300=27.47 total=123456789\n" + "full avg10=21.90 avg60=15.77 avg300=22.47 total=98765432\n")) if err != nil || got != 123456789*time.Microsecond { @@ -284,7 +284,7 @@ func TestTheIOPressureIsReadAsTheKernelWritesIt(t *testing.T) { // One directory of many files is paced as it is read, not only between directories: a file's own details may be // read from the disk too. -func TestADirectoryOfManyFilesIsPacedAsItIsRead(t *testing.T) { +func testADirectoryOfManyFilesIsPacedAsItIsRead(t *testing.T) { names := []string{"bin/"} for i := range 20 { names = append(names, "bin/f"+strings.Repeat("x", i+1)) @@ -300,3 +300,20 @@ func TestADirectoryOfManyFilesIsPacedAsItIsRead(t *testing.T) { t.Fatal("a directory of twenty files was read without a pause under pressure") } } + +// TestSetuidPace runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSetuidPace(t *testing.T) { + t.Run("TheWalkPausesWhileTheDiskIsUnderPressureAndGoesOnWhenItEases", testTheWalkPausesWhileTheDiskIsUnderPressureAndGoesOnWhenItEases) + t.Run("TheFirstLookOnlySetsWhereTheNextCountsFrom", testTheFirstLookOnlySetsWhereTheNextCountsFrom) + t.Run("TheWalkDoesNotPauseOnAQuietDisk", testTheWalkDoesNotPauseOnAQuietDisk) + t.Run("TheWalkKeepsATenthOfTheTimeWhateverThePressure", testTheWalkKeepsATenthOfTheTimeWhateverThePressure) + t.Run("TheSlowestPacedWalkStillJudgesInTime", testTheSlowestPacedWalkStillJudgesInTime) + t.Run("ARunOfPausesIsAtMostPaceAtMost", testARunOfPausesIsAtMostPaceAtMost) + t.Run("TheWalkLooksAtThePressureAtMostEveryPaceLook", testTheWalkLooksAtThePressureAtMostEveryPaceLook) + t.Run("APressureThatCannotBeReadIsSaidOnce", testAPressureThatCannotBeReadIsSaidOnce) + t.Run("TheEnginesWalkIsPacedByTheMachinesPressure", testTheEnginesWalkIsPacedByTheMachinesPressure) + t.Run("AWalkEndedWhileItPausesIsIncomplete", testAWalkEndedWhileItPausesIsIncomplete) + t.Run("APacedWalkFindsWhatAnUnpacedWalkFinds", testAPacedWalkFindsWhatAnUnpacedWalkFinds) + t.Run("TheIOPressureIsReadAsTheKernelWritesIt", testTheIOPressureIsReadAsTheKernelWritesIt) + t.Run("ADirectoryOfManyFilesIsPacedAsItIsRead", testADirectoryOfManyFilesIsPacedAsItIsRead) +} diff --git a/internal/accounts/setuid_progress_test.go b/internal/accounts/setuid_progress_test.go index 3bcfe11b..627b4795 100644 --- a/internal/accounts/setuid_progress_test.go +++ b/internal/accounts/setuid_progress_test.go @@ -15,7 +15,7 @@ import ( // A walk stopped midway and resumed counts every entry once, as the walk that was never stopped does, and says // how long each filesystem took. -func TestTheProgressCountsEachEntryOnceAcrossAResume(t *testing.T) { +func testTheProgressCountsEachEntryOnceAcrossAResume(t *testing.T) { top := tree(t, "a/1!", "a/2", "a-b/3!", "b/c/4!", "b/c/5", "b/d!", "c/6!", "d/7!") other := tree(t, "x/1", "y!") whole := &SetuidProgress{Mounts: []string{top, other}} @@ -57,7 +57,7 @@ func TestTheProgressCountsEachEntryOnceAcrossAResume(t *testing.T) { // A walk kept before the times were counted has them not known, never shifted onto the next filesystem, and // its entries visited are a lower bound; the filesystem it was part-way through took a time not known. -func TestAWalkKeptWithoutTimesSaysThemNotKnown(t *testing.T) { +func testAWalkKeptWithoutTimesSaysThemNotKnown(t *testing.T) { top, other := tree(t, "a"), tree(t, "b") p := &SetuidProgress{Mounts: []string{top, other}, Done: Paths{top}} if err := mine().walk(t.Context(), p, func() {}); err != nil { @@ -73,7 +73,7 @@ func TestAWalkKeptWithoutTimesSaysThemNotKnown(t *testing.T) { } // A look while the search runs says how far it got at its last checkpoint, with no path it visited or found. -func TestALookSaysHowFarTheRunningSearchGotAndNoPath(t *testing.T) { +func testALookSaysHowFarTheRunningSearchGotAndNoPath(t *testing.T) { dir := t.TempDir() c := &SetuidCache{ProgressPath: filepath.Join(dir, SetuidProgressFile)} secret := "/home/someone/private/rootshell" @@ -133,7 +133,7 @@ func (w *waiting) Escalation(context.Context, string, []string) ([]string, error return nil, &SetuidNotJudged{Pending: true, Since: at, Progress: w.progress} } -func TestTheProgressMovesWithoutChangingTheVerdict(t *testing.T) { +func testTheProgressMovesWithoutChangingTheVerdict(t *testing.T) { r := &waiting{progress: &SearchProgress{Filesystems: 2, Visited: 10}} j := New(r) j.Set([]Account{{Module: "claude-code", ID: "claude-code.agent", Name: "agent", Root: true}}) @@ -150,7 +150,7 @@ func TestTheProgressMovesWithoutChangingTheVerdict(t *testing.T) { // Asked at the terminal, a search starts afresh at the next look: the last complete one is thrown away, kept or // in memory, and a running one is ended and neither judges nor is carried on. -func TestSearchNowThrowsAwayTheLastSearchAndStartsAFullOne(t *testing.T) { +func testSearchNowThrowsAwayTheLastSearchAndStartsAFullOne(t *testing.T) { dir := t.TempDir() c := &SetuidCache{Path: filepath.Join(dir, SetuidSearchFile), ProgressPath: filepath.Join(dir, SetuidProgressFile)} g := newGate() @@ -206,7 +206,7 @@ func TestSearchNowThrowsAwayTheLastSearchAndStartsAFullOne(t *testing.T) { } } -func TestAFilesystemPartWalkedByAnEngineThatDidNotCountTookATimeNotKnown(t *testing.T) { +func testAFilesystemPartWalkedByAnEngineThatDidNotCountTookATimeNotKnown(t *testing.T) { top := tree(t, "a", "b") p := &SetuidProgress{Mounts: []string{top}, Cursor: Cursors{top: filepath.Join(top, "a")}} if err := mine().walk(t.Context(), p, func() {}); err != nil { @@ -216,3 +216,13 @@ func TestAFilesystemPartWalkedByAnEngineThatDidNotCountTookATimeNotKnown(t *test t.Fatalf("took %v", p.Took) } } + +// TestSetuidProgress runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSetuidProgress(t *testing.T) { + t.Run("TheProgressCountsEachEntryOnceAcrossAResume", testTheProgressCountsEachEntryOnceAcrossAResume) + t.Run("AWalkKeptWithoutTimesSaysThemNotKnown", testAWalkKeptWithoutTimesSaysThemNotKnown) + t.Run("ALookSaysHowFarTheRunningSearchGotAndNoPath", testALookSaysHowFarTheRunningSearchGotAndNoPath) + t.Run("TheProgressMovesWithoutChangingTheVerdict", testTheProgressMovesWithoutChangingTheVerdict) + t.Run("SearchNowThrowsAwayTheLastSearchAndStartsAFullOne", testSearchNowThrowsAwayTheLastSearchAndStartsAFullOne) + t.Run("AFilesystemPartWalkedByAnEngineThatDidNotCountTookATimeNotKnown", testAFilesystemPartWalkedByAnEngineThatDidNotCountTookATimeNotKnown) +} diff --git a/internal/accounts/setuid_reach_test.go b/internal/accounts/setuid_reach_test.go index 940f49a4..9cf39e1e 100644 --- a/internal/accounts/setuid_reach_test.go +++ b/internal/accounts/setuid_reach_test.go @@ -21,7 +21,7 @@ func homeMachine(home FileMode) *agentMachine { return m } -func TestReachabilityDecidesWhetherAFindCounts(t *testing.T) { +func testReachabilityDecidesWhetherAFindCounts(t *testing.T) { op := func(perm fs.FileMode) FileMode { return FileMode{UID: 1500, GID: 1500, Perm: fs.ModeDir | perm} } for _, c := range []struct { name string @@ -64,7 +64,7 @@ func TestReachabilityDecidesWhetherAFindCounts(t *testing.T) { } // The search keeps every find; whether one counts is read again at every look. -func TestAHomeOpenedAfterTheSearchCountsWithoutANewSearch(t *testing.T) { +func testAHomeOpenedAfterTheSearchCountsWithoutANewSearch(t *testing.T) { m := homeMachine(FileMode{UID: 1500, GID: 1500, Perm: fs.ModeDir | 0o700}) c := &SetuidCache{} j := New(Exec{Run: m.run, Walk: m.walk, Stat: m.stat, ReadFile: m.readFile, ReadDir: m.readDir, ACL: m.acl, @@ -88,7 +88,7 @@ func TestAHomeOpenedAfterTheSearchCountsWithoutANewSearch(t *testing.T) { // On the machine's own modes, as their owner (the directories above a test's are its own): a directory without // its owner's search bit hides what is in it. -func TestExecutableReadsTheMachinesModes(t *testing.T) { +func testExecutableReadsTheMachinesModes(t *testing.T) { if os.Getuid() == 0 { t.Skip("root searches every directory") } @@ -113,3 +113,10 @@ func TestExecutableReadsTheMachinesModes(t *testing.T) { t.Fatal("a file gone was executable") } } + +// TestSetuidReach runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSetuidReach(t *testing.T) { + t.Run("ReachabilityDecidesWhetherAFindCounts", testReachabilityDecidesWhetherAFindCounts) + t.Run("AHomeOpenedAfterTheSearchCountsWithoutANewSearch", testAHomeOpenedAfterTheSearchCountsWithoutANewSearch) + t.Run("ExecutableReadsTheMachinesModes", testExecutableReadsTheMachinesModes) +} diff --git a/internal/accounts/setuid_walk_test.go b/internal/accounts/setuid_walk_test.go index 4d6a6368..df7e948e 100644 --- a/internal/accounts/setuid_walk_test.go +++ b/internal/accounts/setuid_walk_test.go @@ -68,7 +68,7 @@ func rel(top string, paths []string) []string { return out } -func TestTheWalkFindsSetuidAndSetgidRootFilesAndFollowsNoLink(t *testing.T) { +func testTheWalkFindsSetuidAndSetgidRootFilesAndFollowsNoLink(t *testing.T) { top := tree(t, "bin/plain", "bin/rootshell!", "sbin/group%", "deep/a/b/c/x!") if err := os.Symlink(filepath.Join(top, "bin/rootshell"), filepath.Join(top, "link")); err != nil { t.Fatal(err) @@ -85,7 +85,7 @@ func TestTheWalkFindsSetuidAndSetgidRootFilesAndFollowsNoLink(t *testing.T) { } } -func TestAWalkThatCannotReadADirectoryIsIncomplete(t *testing.T) { +func testAWalkThatCannotReadADirectoryIsIncomplete(t *testing.T) { if os.Geteuid() == 0 { t.Skip("root reads every directory") } @@ -100,7 +100,7 @@ func TestAWalkThatCannotReadADirectoryIsIncomplete(t *testing.T) { } } -func TestWalkOrderIsNameByName(t *testing.T) { +func testWalkOrderIsNameByName(t *testing.T) { // "/a/b" is walked before "/a-c" although '-' sorts before '/': the walk goes name by name. if walkOrder(components("/a/b"), components("/a-c")) >= 0 { t.Fatal("/a/b is walked before /a-c") @@ -115,7 +115,7 @@ func TestWalkOrderIsNameByName(t *testing.T) { // A walk stopped midway carries on from its cursor: what was before the cursor is not walked again, what is after // it is, and every file of the first walk is found. -func TestAnInterruptedWalkCarriesOnFromItsCursor(t *testing.T) { +func testAnInterruptedWalkCarriesOnFromItsCursor(t *testing.T) { top := tree(t, "a/1!", "a/2", "a-b/3!", "b/c/4!", "b/c/5", "b/d!", "c/6!", "d/7!") w := mine() w.every = 0 // a checkpoint at every path @@ -169,7 +169,7 @@ func tree2(t *testing.T, top, n string) { } // A search's commands and walk run on a lowered thread while the rest of the engine keeps its priority. -func TestTheSearchRunsOnALoweredThreadOfItsOwn(t *testing.T) { +func testTheSearchRunsOnALoweredThreadOfItsOwn(t *testing.T) { var wg sync.WaitGroup wg.Add(1) var err error @@ -185,7 +185,7 @@ func TestTheSearchRunsOnALoweredThreadOfItsOwn(t *testing.T) { // Another filesystem's mount point is left without being read, and a file found that is gone, or no longer // setuid-root, when the walk ends is not asked about. -func TestTheWalkLeavesMountPointsAndDropsWhatWentMeanwhile(t *testing.T) { +func testTheWalkLeavesMountPointsAndDropsWhatWentMeanwhile(t *testing.T) { top := tree(t, "fuse/secret!", "bin/x!", "bin/y!") w := mine() w.mountPoints = map[string]bool{filepath.Join(top, "fuse"): true} @@ -205,9 +205,20 @@ func TestTheWalkLeavesMountPointsAndDropsWhatWentMeanwhile(t *testing.T) { } } -func TestAMountPointIsReadAsTheKernelEscapesIt(t *testing.T) { +func testAMountPointIsReadAsTheKernelEscapesIt(t *testing.T) { mp := MountPoints("/dev/a /mnt/a\\040b ext4 rw 0 0\n/dev/b /mnt/back\\134slash ext4 rw 0 0\n") if !mp["/mnt/a b"] || !mp[`/mnt/back\slash`] { t.Fatalf("read %v", mp) } } + +// TestSetuidWalk runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSetuidWalk(t *testing.T) { + t.Run("TheWalkFindsSetuidAndSetgidRootFilesAndFollowsNoLink", testTheWalkFindsSetuidAndSetgidRootFilesAndFollowsNoLink) + t.Run("AWalkThatCannotReadADirectoryIsIncomplete", testAWalkThatCannotReadADirectoryIsIncomplete) + t.Run("WalkOrderIsNameByName", testWalkOrderIsNameByName) + t.Run("AnInterruptedWalkCarriesOnFromItsCursor", testAnInterruptedWalkCarriesOnFromItsCursor) + t.Run("TheSearchRunsOnALoweredThreadOfItsOwn", testTheSearchRunsOnALoweredThreadOfItsOwn) + t.Run("TheWalkLeavesMountPointsAndDropsWhatWentMeanwhile", testTheWalkLeavesMountPointsAndDropsWhatWentMeanwhile) + t.Run("AMountPointIsReadAsTheKernelEscapesIt", testAMountPointIsReadAsTheKernelEscapesIt) +} diff --git a/internal/accounts/ways_test.go b/internal/accounts/ways_test.go index 51451a39..af445d16 100644 --- a/internal/accounts/ways_test.go +++ b/internal/accounts/ways_test.go @@ -15,7 +15,7 @@ import ( // runtime's socket, an ACL on a secret, a setuid program no package owns — each said; each unread question // unknown; and the judge's commands in the C locale. -func TestEachFurtherWayToRootIsSaid(t *testing.T) { +func testEachFurtherWayToRootIsSaid(t *testing.T) { const broker = "/var/lib/mesh/node-tools/broker" for _, c := range []struct { name string @@ -88,7 +88,7 @@ func TestEachFurtherWayToRootIsSaid(t *testing.T) { } } -func TestWhatGrantsSomebodyElseIsNoWay(t *testing.T) { +func testWhatGrantsSomebodyElseIsNoWay(t *testing.T) { m := clean() m.texts = map[string]string{"/etc/doas.conf": "permit operator\npermit :wheel\n# permit agent\n", "/usr/share/polkit-1/rules.d/50-default.rules": `polkit.addAdminRule(function(a, s) { return ["unix-group:wheel"]; });`} @@ -101,7 +101,7 @@ func TestWhatGrantsSomebodyElseIsNoWay(t *testing.T) { } } -func TestDoasWithoutSudoIsJudgedFromItsRules(t *testing.T) { +func testDoasWithoutSudoIsJudgedFromItsRules(t *testing.T) { m := clean() m.sudo, m.sudoErr = "", fmt.Errorf("sudo: %w", exec.ErrNotFound) m.texts = map[string]string{"/etc/doas.conf": "permit nopass agent\n"} @@ -111,7 +111,7 @@ func TestDoasWithoutSudoIsJudgedFromItsRules(t *testing.T) { } } -func TestAFurtherQuestionUnansweredIsUnknown(t *testing.T) { +func testAFurtherQuestionUnansweredIsUnknown(t *testing.T) { m := clean() m.findErr = errors.New("find: interrupted") if v := lookAgent(t, m); v.State != Unknown { @@ -131,7 +131,7 @@ func TestAFurtherQuestionUnansweredIsUnknown(t *testing.T) { } } -func TestANotJudgedSearchStillSaysAWayFound(t *testing.T) { +func testANotJudgedSearchStillSaysAWayFound(t *testing.T) { j := New(fakeReader{ways: []string{"in the group docker, which grants root"}, err: &SetuidNotJudged{Pending: true, Since: time.Now()}}) j.Set([]Account{{Module: "m", ID: "m.a", Name: "agent", Root: true}}) st, _ := j.Look(context.Background()) @@ -159,7 +159,7 @@ func (f fakeReader) Escalation(context.Context, string, []string) ([]string, err return f.ways, f.err } -func TestParseACL(t *testing.T) { +func testParseACL(t *testing.T) { entry := func(tag, perm uint16, id uint32) []byte { b := make([]byte, 8) binary.LittleEndian.PutUint16(b, tag) @@ -189,7 +189,7 @@ func TestParseACL(t *testing.T) { } } -func TestTheJudgesCommandsRunInTheCLocale(t *testing.T) { +func testTheJudgesCommandsRunInTheCLocale(t *testing.T) { t.Setenv("LC_ALL", "de_DE.UTF-8") t.Setenv("LANG", "de_DE.UTF-8") out, err := CLocale(t.Context(), "sh", "-c", `echo "$LC_ALL $LANG"`) @@ -202,13 +202,13 @@ func TestTheJudgesCommandsRunInTheCLocale(t *testing.T) { } } -func TestTheJudgedListIsWrittenDown(t *testing.T) { +func testTheJudgedListIsWrittenDown(t *testing.T) { if len(Judged) < 8 || len(NotJudged) == 0 { t.Fatal("what is judged and what is not are both written down") } } -func TestDistributionRulesForASeatOrForSomebodyAreNotEveryone(t *testing.T) { +func testDistributionRulesForASeatOrForSomebodyAreNotEveryone(t *testing.T) { for _, rule := range []string{ `polkit.addRule(function(a, s) { if (s.local && s.active) return polkit.Result.YES; });`, `polkit.addRule(function(a, s) { if (s.isInGroup("wheel")) return polkit.Result.YES; });`, @@ -223,7 +223,7 @@ func TestDistributionRulesForASeatOrForSomebodyAreNotEveryone(t *testing.T) { } } -func TestAMachineMissingWhatTheJudgeReadsIsUnknown(t *testing.T) { +func testAMachineMissingWhatTheJudgeReadsIsUnknown(t *testing.T) { for _, file := range []string{"/proc/sys/fs/protected_hardlinks", "/proc/net/tcp", "/proc/mounts"} { m := clean() delete(m.proc, file) @@ -233,7 +233,7 @@ func TestAMachineMissingWhatTheJudgeReadsIsUnknown(t *testing.T) { } } -func TestSuidMountsLeaveOutNosuidPseudoAndContainerLayers(t *testing.T) { +func testSuidMountsLeaveOutNosuidPseudoAndContainerLayers(t *testing.T) { got := SuidMounts("/dev/sdb1 /srv xfs rw 0 0\n/dev/sda2 / ext4 rw 0 0\noverlay /var/lib/docker/overlay2/x/merged overlay rw 0 0\n" + "/dev/sdc1 /data ext4 rw,nosuid 0 0\nproc /proc proc rw 0 0\nhost:/x /mnt/nfs nfs4 rw 0 0\n/dev/sdd1 /my\\040disk ext4 rw 0 0\n") if strings.Join(got, "|") != "/|/my disk|/srv" { @@ -242,7 +242,7 @@ func TestSuidMountsLeaveOutNosuidPseudoAndContainerLayers(t *testing.T) { } // Each polkit rule is judged on its own, comments taken out (the third review of 2026-10-08). -func TestAnUnconditionalPolkitYesIsNotMaskedByAnotherRuleOrAComment(t *testing.T) { +func testAnUnconditionalPolkitYesIsNotMaskedByAnotherRuleOrAComment(t *testing.T) { cases := []struct { name, text string every bool @@ -270,7 +270,7 @@ polkit.addRule(function(a, s) { /* isInGroup("wheel") */ return polkit.Result.YE } // The package manager is asked about every path found in one call, and answers each: owned, or owned by nothing. -func TestThePackageManagerIsAskedOnceForEveryPathFound(t *testing.T) { +func testThePackageManagerIsAskedOnceForEveryPathFound(t *testing.T) { m := clean() m.setuid = "/usr/bin/sudo\n/usr/bin/passwd\n/usr/local/bin/x\n/opt/y\n" m.packaged = map[string]bool{"/usr/bin/sudo": true, "/usr/bin/passwd": true} @@ -303,3 +303,20 @@ func TestThePackageManagerIsAskedOnceForEveryPathFound(t *testing.T) { t.Error("a walk that did not complete was read as an answer") } } + +// TestWays runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestWays(t *testing.T) { + t.Run("EachFurtherWayToRootIsSaid", testEachFurtherWayToRootIsSaid) + t.Run("WhatGrantsSomebodyElseIsNoWay", testWhatGrantsSomebodyElseIsNoWay) + t.Run("DoasWithoutSudoIsJudgedFromItsRules", testDoasWithoutSudoIsJudgedFromItsRules) + t.Run("AFurtherQuestionUnansweredIsUnknown", testAFurtherQuestionUnansweredIsUnknown) + t.Run("ANotJudgedSearchStillSaysAWayFound", testANotJudgedSearchStillSaysAWayFound) + t.Run("ParseACL", testParseACL) + t.Run("TheJudgesCommandsRunInTheCLocale", testTheJudgesCommandsRunInTheCLocale) + t.Run("TheJudgedListIsWrittenDown", testTheJudgedListIsWrittenDown) + t.Run("DistributionRulesForASeatOrForSomebodyAreNotEveryone", testDistributionRulesForASeatOrForSomebodyAreNotEveryone) + t.Run("AMachineMissingWhatTheJudgeReadsIsUnknown", testAMachineMissingWhatTheJudgeReadsIsUnknown) + t.Run("SuidMountsLeaveOutNosuidPseudoAndContainerLayers", testSuidMountsLeaveOutNosuidPseudoAndContainerLayers) + t.Run("AnUnconditionalPolkitYesIsNotMaskedByAnotherRuleOrAComment", testAnUnconditionalPolkitYesIsNotMaskedByAnotherRuleOrAComment) + t.Run("ThePackageManagerIsAskedOnceForEveryPathFound", testThePackageManagerIsAskedOnceForEveryPathFound) +} diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index 71eaf3b6..d41804f6 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -132,12 +132,12 @@ type bed struct { others [][]compositions.Composed said []string // settled is each module Settled was told, and settledRan whether what runs held it then. - settled []string + settled []string // takenAtStart is each module TakenAtStart was told, with its composition's resource count. takenAtStart []string - settledRan []bool - ag *Agent // the agent run() runs - env Env + settledRan []bool + ag *Agent // the agent run() runs + env Env // runs is, by module, a build the agent already runs when run() starts it. runs map[string]string } @@ -297,7 +297,7 @@ func (b *bed) appliedList() []string { // R6-A AC1 (the agent, with a bus that is a fake): given a want naming a digest and that composition, the module is // applied and its have names the fingerprint and the digest; a composition whose digest no want names is not applied. -func TestAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) { +func testAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) { b := newBed(t) stop := b.run() defer stop() @@ -407,7 +407,7 @@ func TestAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) { // R6-A AC2: given a kept declaration and wants and compositions equal to it, when the agent starts, nothing is applied // and every have names its fingerprint and digest. -func TestStartingOnWhatTheKeptDeclarationHoldsAppliesNothing(t *testing.T) { +func testStartingOnWhatTheKeptDeclarationHoldsAppliesNothing(t *testing.T) { b := newBed(t) fp := fpOf("a") rs := []json.RawMessage{file("web", "x", "1"), file("web", "y", "2")} @@ -526,7 +526,7 @@ func testStartingOnItsOwnHaveSaysTheHaveAgainSoItsHealthIsThisEngines(t *testing // A module whose kept resources differ from the composition is applied, and a failed apply is retried only by a change // of either key. -func TestAFailedApplyIsRetriedOnlyByAChangeOfEitherKey(t *testing.T) { +func testAFailedApplyIsRetriedOnlyByAChangeOfEitherKey(t *testing.T) { t.Run("1957: the judge's edge reconciles, and a failed re-apply is failed", testReconcileAppliesARunningModuleAgainAndLeavesTheHeldAndTheUnwantedAlone) // A real failure is not retried by the clock, however short the backoff: only by a change of either key. t.Run("a real failure", func(t *testing.T) { @@ -763,7 +763,7 @@ func TestAFailedApplyIsRetriedOnlyByAChangeOfEitherKey(t *testing.T) { // R6-A AC5: a data module that ran before asks its backup before any resource changes; a refusal holds it, nothing is // applied and the have says held; when the want then says skip, the module is applied. -func TestADataModuleIsBackedUpFirstAndHeldWhenItFails(t *testing.T) { +func testADataModuleIsBackedUpFirstAndHeldWhenItFails(t *testing.T) { b := newBed(t) fp1, fp2 := fpOf("a"), fpOf("b") ck1, craw1, dig1 := composition(t, "db", fp1, true, file("db", "x", "1")) @@ -1049,7 +1049,7 @@ func cutAsAHaveIs(s string) string { } // A data module with a good backup is applied after it; one that never ran has nothing to back up. -func TestABackupDoneIsFollowedByTheApplyAndANewModuleIsNotBackedUp(t *testing.T) { +func testABackupDoneIsFollowedByTheApplyAndANewModuleIsNotBackedUp(t *testing.T) { t.Run("a move across a kept data's form change is taken as a restore point and restored at a revert", testAMoveAcrossAFormChange) b := newBed(t) stop := b.run() @@ -1081,7 +1081,7 @@ func TestABackupDoneIsFollowedByTheApplyAndANewModuleIsNotBackedUp(t *testing.T) } // R6-A AC4 at the agent: a removed want removes that module only, and its have is written removed. -func TestARemovedWantRemovesThatModuleOnly(t *testing.T) { +func testARemovedWantRemovesThatModuleOnly(t *testing.T) { t.Run("its composition holds nothing back", testARemovedModulesCompositionHoldsNothingBack) b := newBed(t) stop := b.run() @@ -1110,7 +1110,7 @@ func TestARemovedWantRemovesThatModuleOnly(t *testing.T) { // module, the holder of the seat node-backup and the bus module (found by their claims), each pipeline's wants by rank (the // older source first), the rest by name, and its own module last; a want of a higher rank waits, on this machine, for the lower // ranks of its pipeline, held in its have as a wait of step placing, and the read apply-order answers the order with why. -func TestTheOrderTheChangedWantsAreAppliedIn(t *testing.T) { +func testTheOrderTheChangedWantsAreAppliedIn(t *testing.T) { type mod struct { name string pipeline string // the want's pipeline, with its rank @@ -1212,7 +1212,7 @@ func TestTheOrderTheChangedWantsAreAppliedIn(t *testing.T) { // What a module's apply must not take is every other module that runs, those the agent holds and those still running from // the kept declaration (ADR 0429 §4): the resources of the kept declaration reach Apply as the others. -func TestApplyingOneModuleHoldsOutTheModulesStillRunningFromTheKeptDeclaration(t *testing.T) { +func testApplyingOneModuleHoldsOutTheModulesStillRunningFromTheKeptDeclaration(t *testing.T) { b := newBed(t) b.kept = map[string][]json.RawMessage{"db": {file("db", "x", "1")}, NodeModule: {file("node", "n", "n")}} stop := b.run() @@ -1236,7 +1236,7 @@ func TestApplyingOneModuleHoldsOutTheModulesStillRunningFromTheKeptDeclaration(t } // Everything is what runs: the agent's compositions and the kept resources of each module it does not hold. -func TestEverythingIsWhatTheAgentRunsAndWhatIsKeptForTheRest(t *testing.T) { +func testEverythingIsWhatTheAgentRunsAndWhatIsKeptForTheRest(t *testing.T) { b := newBed(t) b.kept = map[string][]json.RawMessage{"db": {file("db", "x", "1")}, "web": {file("web", "x", "old")}} a := New(b.env) @@ -1434,7 +1434,7 @@ func testAFailedApplyIsAppliedAgainAfterARestartWhateverIsKept(t *testing.T) { } // A have written before the switch carries no composition: then the kept declaration says what runs. -func TestAHaveWithNoCompositionDefersToTheKeptDeclaration(t *testing.T) { +func testAHaveWithNoCompositionDefersToTheKeptDeclaration(t *testing.T) { b := newBed(t) fp := fpOf("a") ck, craw, dig := composition(t, "web", fp, false, file("web", "x", "1")) @@ -1557,7 +1557,7 @@ func testARemovedModulesCompositionHoldsNothingBack(t *testing.T) { // The node's own composition is not applied while a module's composition in the node's bucket cannot be read: what that one carries may be what left the node's own, and the node's own apply would remove // it (issue 1945, the review's gap 2). It is said, naming the composition, and applied once that one reads. -func TestTheNodesOwnWaitsWhileAModulesCompositionCannotBeRead(t *testing.T) { +func testTheNodesOwnWaitsWhileAModulesCompositionCannotBeRead(t *testing.T) { b := newBed(t) bad, err := compositions.Key(node, "broken", fpOf("c")) if err != nil { @@ -1593,7 +1593,7 @@ func TestTheNodesOwnWaitsWhileAModulesCompositionCannotBeRead(t *testing.T) { // A stale refused composition beside a newer readable one of the same module does not hold the node's own apply back: // only the composition the module's want names, else its newest, counts (the review of issue 1945: the bucket keeps // compositions written before the filled paths, which the SDK now refuses, and nobody applies them). -func TestAStaleRefusedCompositionDoesNotHoldTheNodesOwnBack(t *testing.T) { +func testAStaleRefusedCompositionDoesNotHoldTheNodesOwnBack(t *testing.T) { b := newBed(t) stale, err := compositions.Key(node, "power", fpOf("a")) if err != nil { @@ -1616,7 +1616,7 @@ func TestAStaleRefusedCompositionDoesNotHoldTheNodesOwnBack(t *testing.T) { // record of its resources: they were removed since (issue 1945, live on 2026-10-25: ace's and g14's node-engines removed // ca-trust's, power's and matrix's resources in a node's own apply, and the wants that named those modules' own // compositions were judged already running from the kept declaration, so nothing made them again). -func TestACompositionWhoseResourcesWereRemovedIsAppliedAgain(t *testing.T) { +func testACompositionWhoseResourcesWereRemovedIsAppliedAgain(t *testing.T) { for _, from := range []string{"kept", "have"} { t.Run(from, func(t *testing.T) { b := newBed(t) @@ -1647,7 +1647,7 @@ func TestACompositionWhoseResourcesWereRemovedIsAppliedAgain(t *testing.T) { // Only a have in a phase baseline takes as running names what runs; and what runs carries Data, from the composition // or, from the kept declaration, from the module's manifest, so a data module is not judged to move its data against // its first composition after a restart (mongodb and mssql on novox). -func TestWhatRunsBeforeTheAgentTakesAModuleNamesItsFilledPaths(t *testing.T) { +func testWhatRunsBeforeTheAgentTakesAModuleNamesItsFilledPaths(t *testing.T) { const old, added = "/tmp/r6/power/settings", "/tmp/r6/power/bound" filledFile := func(id string) json.RawMessage { return json.RawMessage(`{"id":"power.` + id + `","type":"file","module":"power","path":"/tmp/r6/power/` + id + @@ -1742,7 +1742,7 @@ func TestWhatRunsBeforeTheAgentTakesAModuleNamesItsFilledPaths(t *testing.T) { // composition composed for the want's build is applied, and only when it differs from what runs; for a module of // policy record a move that recreates a container waits in phase waiting-yes with its judgement until the want names // the yes for that composition, and is then applied. -func TestTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes(t *testing.T) { +func testTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes(t *testing.T) { b := newBed(t) b.env.SelfComposed = true b.env.Policy = func(_ context.Context, m string) string { @@ -2247,3 +2247,22 @@ func testReconcileAppliesARunningModuleAgainAndLeavesTheHeldAndTheUnwantedAlone( t.Fatalf("a failed apply was tried again with no edge: %v", got) } } + +// TestAgent runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestAgent(t *testing.T) { + t.Run("AWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth", testAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth) + t.Run("StartingOnWhatTheKeptDeclarationHoldsAppliesNothing", testStartingOnWhatTheKeptDeclarationHoldsAppliesNothing) + t.Run("AFailedApplyIsRetriedOnlyByAChangeOfEitherKey", testAFailedApplyIsRetriedOnlyByAChangeOfEitherKey) + t.Run("ADataModuleIsBackedUpFirstAndHeldWhenItFails", testADataModuleIsBackedUpFirstAndHeldWhenItFails) + t.Run("ABackupDoneIsFollowedByTheApplyAndANewModuleIsNotBackedUp", testABackupDoneIsFollowedByTheApplyAndANewModuleIsNotBackedUp) + t.Run("ARemovedWantRemovesThatModuleOnly", testARemovedWantRemovesThatModuleOnly) + t.Run("TheOrderTheChangedWantsAreAppliedIn", testTheOrderTheChangedWantsAreAppliedIn) + t.Run("ApplyingOneModuleHoldsOutTheModulesStillRunningFromTheKeptDeclaration", testApplyingOneModuleHoldsOutTheModulesStillRunningFromTheKeptDeclaration) + t.Run("EverythingIsWhatTheAgentRunsAndWhatIsKeptForTheRest", testEverythingIsWhatTheAgentRunsAndWhatIsKeptForTheRest) + t.Run("AHaveWithNoCompositionDefersToTheKeptDeclaration", testAHaveWithNoCompositionDefersToTheKeptDeclaration) + t.Run("TheNodesOwnWaitsWhileAModulesCompositionCannotBeRead", testTheNodesOwnWaitsWhileAModulesCompositionCannotBeRead) + t.Run("AStaleRefusedCompositionDoesNotHoldTheNodesOwnBack", testAStaleRefusedCompositionDoesNotHoldTheNodesOwnBack) + t.Run("ACompositionWhoseResourcesWereRemovedIsAppliedAgain", testACompositionWhoseResourcesWereRemovedIsAppliedAgain) + t.Run("WhatRunsBeforeTheAgentTakesAModuleNamesItsFilledPaths", testWhatRunsBeforeTheAgentTakesAModuleNamesItsFilledPaths) + t.Run("TheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes", testTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes) +} diff --git a/internal/apply/access_test.go b/internal/apply/access_test.go index f045bb59..fd947030 100644 --- a/internal/apply/access_test.go +++ b/internal/apply/access_test.go @@ -14,7 +14,7 @@ import ( // mode, because the media library and the download spool are the operator's and several modules // share them. This is the opposite of a directory on every axis, and the whole reason the two are // different shapes. -func TestAnAccessPresentIsConfirmedAndNothingIsChanged(t *testing.T) { +func testAnAccessPresentIsConfirmedAndNothingIsChanged(t *testing.T) { dir := t.TempDir() // the operator's directory, already there d := declare(t, `{"id":"lib","type":"access","path":"`+dir+`","mode":"read-write"}`) @@ -35,7 +35,7 @@ func TestAnAccessPresentIsConfirmedAndNothingIsChanged(t *testing.T) { // library must not delete the library — that is the data loss ADR 0030 exists to prevent, on a // directory the mesh never made. The record is dropped; the operator's data is left exactly as it // is. -func TestAnUndeclaredAccessLeavesTheOperatorsPathAlone(t *testing.T) { +func testAnUndeclaredAccessLeavesTheOperatorsPathAlone(t *testing.T) { lib := t.TempDir() // the operator's library keep := t.TempDir() if err := os.WriteFile(lib+"/a-real-file", []byte("the operator's data"), 0o644); err != nil { @@ -73,3 +73,9 @@ func TestAnUndeclaredAccessLeavesTheOperatorsPathAlone(t *testing.T) { t.Errorf("dropping an access was not reported as forgotten: %+v", report.Outcomes) } } + +// TestAccess runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestAccess(t *testing.T) { + t.Run("AnAccessPresentIsConfirmedAndNothingIsChanged", testAnAccessPresentIsConfirmedAndNothingIsChanged) + t.Run("AnUndeclaredAccessLeavesTheOperatorsPathAlone", testAnUndeclaredAccessLeavesTheOperatorsPathAlone) +} diff --git a/internal/apply/apply_test.go b/internal/apply/apply_test.go index 506a81a4..8ac6416b 100644 --- a/internal/apply/apply_test.go +++ b/internal/apply/apply_test.go @@ -31,7 +31,7 @@ func noServices(context.Context, string, ...string) (string, error) { return "", errors.New("this test declares no services and should not have run a command") } -func TestApplyingTwiceChangesNothingTheSecondTime(t *testing.T) { +func testApplyingTwiceChangesNothingTheSecondTime(t *testing.T) { // Idempotence is what makes an apply safe to run on a schedule. Without it, a host that // reconciles every few minutes rewrites files forever and every reader sees churn. dir := t.TempDir() @@ -61,7 +61,7 @@ func TestApplyingTwiceChangesNothingTheSecondTime(t *testing.T) { // // Not by overwriting silently — by noticing. An edit that vanishes without a word is how somebody // spends an afternoon re-fixing a bug they already fixed. -func TestADriftedMachineIsReturned(t *testing.T) { +func testADriftedMachineIsReturned(t *testing.T) { // The other half of idempotence, and the half that matters: converging is not "do nothing // if the state file says it was done". The machine is read, not the record. dir := t.TempDir() @@ -91,7 +91,7 @@ func TestADriftedMachineIsReturned(t *testing.T) { } } -func TestADroppedResourceIsRemoved(t *testing.T) { +func testADroppedResourceIsRemoved(t *testing.T) { // novox/hq ADR 0005: the host removes what it previously applied and is no longer // declared. Removing a line from a declaration is an act with an effect. dir := t.TempDir() @@ -129,7 +129,7 @@ func TestADroppedResourceIsRemoved(t *testing.T) { } } -func TestNothingTheHostDidNotCreateIsTouched(t *testing.T) { +func testNothingTheHostDidNotCreateIsTouched(t *testing.T) { // The boundary the whole removal rule turns on. A machine has things on it the mesh did // not put there, and a converger that treats "not declared" as "must not exist" deletes // them. Authoritative over its own footprint; inert everywhere else. @@ -152,7 +152,7 @@ func TestNothingTheHostDidNotCreateIsTouched(t *testing.T) { } } -func TestARenameToTheSamePathDoesNotDeleteTheNewFile(t *testing.T) { +func testARenameToTheSamePathDoesNotDeleteTheNewFile(t *testing.T) { // Why removal happens FIRST. A resource leaving a declaration while another arrives at the // same path is an ordinary rename; removing afterwards would delete the file just written. dir := t.TempDir() @@ -186,7 +186,7 @@ func TestARenameToTheSamePathDoesNotDeleteTheNewFile(t *testing.T) { // (novox/hq 04-ISSUES/011; design 42 zfs-owns-zfs §1, ADR 0679 §16 (a)): the resources of no module are all // attempted, so one broken resource holds no machine hostage and every failure is counted, not just the first; // a module's apply stops at its first failed resource, reports each one left, and no other module is touched. -func TestAFailedResourceFailsTheApplyAndWhatFollowsIsAttemptedByWhoseItIs(t *testing.T) { +func testAFailedResourceFailsTheApplyAndWhatFollowsIsAttemptedByWhoseItIs(t *testing.T) { dir := t.TempDir() for _, name := range []string{"blocker", "one", "two"} { if err := os.WriteFile(filepath.Join(dir, name), []byte("i am a file\n"), 0o644); err != nil { @@ -272,7 +272,7 @@ func TestAFailedResourceFailsTheApplyAndWhatFollowsIsAttemptedByWhoseItIs(t *tes } } -func TestNothingIsRecordedUntilItWorked(t *testing.T) { +func testNothingIsRecordedUntilItWorked(t *testing.T) { // novox/hq ADR 0018. A record written before the fact restates the request in a new place // and inherits none of the authority of having happened. dir := t.TempDir() @@ -293,7 +293,7 @@ func TestNothingIsRecordedUntilItWorked(t *testing.T) { } } -func TestAModeIsMaintainedNotJustSet(t *testing.T) { +func testAModeIsMaintainedNotJustSet(t *testing.T) { // A permission set at creation is not a permission maintained — this repository has // already paid for that once, with generated files left world-readable because the mode // applied only when the file was first written. @@ -324,7 +324,7 @@ func TestAModeIsMaintainedNotJustSet(t *testing.T) { } } -func TestAServiceIsReadBackNotAssumed(t *testing.T) { +func testAServiceIsReadBackNotAssumed(t *testing.T) { // `systemctl start` returning zero says the transaction was accepted, not that the unit is // running. A unit that starts and immediately dies satisfies the command. started := false @@ -352,7 +352,7 @@ func TestAServiceIsReadBackNotAssumed(t *testing.T) { } } -func TestAnUnknownServiceStateIsRefusedNotGuessed(t *testing.T) { +func testAnUnknownServiceStateIsRefusedNotGuessed(t *testing.T) { run := func(ctx context.Context, name string, args ...string) (string, error) { args = oldShape(name, args) return "LoadState=loaded\nActiveState=reticent\n", nil @@ -370,7 +370,7 @@ func TestAnUnknownServiceStateIsRefusedNotGuessed(t *testing.T) { // nothing of it runs, whatever its last run did (novox/hq issue 1126). The kernel module's // linux-modules-cleanup.service failed on ace with "was asked to be stopped and is running": an // inactive one-shot with ExecMainStatus=0 reads "running", and stopping it changes nothing. -func TestABootOneShotDeclaredStoppedIsSatisfiedAtRest(t *testing.T) { +func testABootOneShotDeclaredStoppedIsSatisfiedAtRest(t *testing.T) { for _, c := range []struct{ name, status string }{ {"exited 0: never ran, ran at boot, or unloaded", "0"}, } { @@ -402,7 +402,7 @@ func TestABootOneShotDeclaredStoppedIsSatisfiedAtRest(t *testing.T) { } } -func TestADroppedServiceIsGivenBackTheStateItWasFoundIn(t *testing.T) { +func testADroppedServiceIsGivenBackTheStateItWasFoundIn(t *testing.T) { // novox/hq ADR 0118: undeclaring removes what the mesh made, gives back what it changed, and // leaves what was the machine's. A service resource never installs a unit — so undeclaring it // undoes what the mesh did to the unit, and nothing more. Stopping every undeclared unit is @@ -462,7 +462,7 @@ func TestADroppedServiceIsGivenBackTheStateItWasFoundIn(t *testing.T) { } } -func TestAServiceRecordsTheStateItWasFoundInOnceAndCarriesIt(t *testing.T) { +func testAServiceRecordsTheStateItWasFoundInOnceAndCarriesIt(t *testing.T) { // Read the first time the host applies the unit — before it starts or enables anything — // and never again: by the next apply, the unit's state is the mesh's doing. active := "inactive" @@ -512,7 +512,7 @@ func TestAServiceRecordsTheStateItWasFoundInOnceAndCarriesIt(t *testing.T) { } } -func TestAUnitThatDoesNotExistIsNotStopped(t *testing.T) { +func testAUnitThatDoesNotExistIsNotStopped(t *testing.T) { // Found by applying inside a raised machine. `systemctl is-active` says "inactive" for a // unit that DOES NOT EXIST exactly as it does for one that is installed and stopped, so // declaring a unit stopped reported success for a unit the host cannot manage at all. @@ -539,7 +539,7 @@ func TestAUnitThatDoesNotExistIsNotStopped(t *testing.T) { } } -func TestAMaskedUnitIsRefused(t *testing.T) { +func testAMaskedUnitIsRefused(t *testing.T) { // Masked means someone deliberately made it unstartable. Applying over that would undo a // decision the host did not make and cannot see the reason for. masked := func(ctx context.Context, name string, args ...string) (string, error) { @@ -554,7 +554,7 @@ func TestAMaskedUnitIsRefused(t *testing.T) { } } -func TestForgettingAUnitThatIsGoneDoesNotStrandTheNode(t *testing.T) { +func testForgettingAUnitThatIsGoneDoesNotStrandTheNode(t *testing.T) { // Found on a real machine. Removing an orphaned service runs `systemctl stop`, which fails // when the unit no longer exists — and a failure there fails the whole apply. A host // holding a record of an uninstalled unit could then apply NOTHING, ever, with no way out @@ -610,7 +610,7 @@ func parseTrusted(t *testing.T, raw string) *declaration.Declaration { const pinned = "docker.io/library/postgres@sha256:" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -func TestABrokenPackageDatabaseIsNotReadAsNotInstalled(t *testing.T) { +func testABrokenPackageDatabaseIsNotReadAsNotInstalled(t *testing.T) { // The same trap serviceState documents. `pacman -Q x` exits non-zero both for a package // that is not installed and for a database that cannot be read — so believing the first // answer would silently reinstall on a machine whose package manager is broken, or report @@ -632,7 +632,7 @@ func TestABrokenPackageDatabaseIsNotReadAsNotInstalled(t *testing.T) { } } -func TestAnInstalledPackageIsNotReinstalled(t *testing.T) { +func testAnInstalledPackageIsNotReinstalled(t *testing.T) { var installed bool run := func(ctx context.Context, name string, args ...string) (string, error) { args = oldShape(name, args) @@ -657,7 +657,7 @@ func TestAnInstalledPackageIsNotReinstalled(t *testing.T) { } } -func TestAPackageIsNeverUninstalled(t *testing.T) { +func testAPackageIsNeverUninstalled(t *testing.T) { // Deliberate: the host cannot know what else needs the package. Uninstalling a container // runtime because a declaration changed would stop every container on the node, and the // machine may have had it before the mesh ever saw it. Undeclaring is not "remove it". @@ -692,7 +692,7 @@ func TestAPackageIsNeverUninstalled(t *testing.T) { } } -func TestAnActionThatIsAlreadyTrueDoesNotRun(t *testing.T) { +func testAnActionThatIsAlreadyTrueDoesNotRun(t *testing.T) { // Verify is the idempotency check as well as the read-back. The host does not know what a // database is, so "is it already there" is a question only the declaration can ask. var ran bool @@ -719,7 +719,7 @@ func TestAnActionThatIsAlreadyTrueDoesNotRun(t *testing.T) { } } -func TestAnActionThatSucceedsAndDoesNothingFails(t *testing.T) { +func testAnActionThatSucceedsAndDoesNothingFails(t *testing.T) { // The whole reason verify is mandatory: a command that exits zero and has no effect is // this repository's most expensive failure shape. Here the command "succeeds" every time // and verify never passes. @@ -746,7 +746,7 @@ func TestAnActionThatSucceedsAndDoesNothingFails(t *testing.T) { } } -func TestAnActionRunsInsideTheContainerItNames(t *testing.T) { +func testAnActionRunsInsideTheContainerItNames(t *testing.T) { // Steps 2 and 3 of the bootstrap act on something inside the store's container, before // there is any mesh to ask. var sawExec bool @@ -770,7 +770,7 @@ func TestAnActionRunsInsideTheContainerItNames(t *testing.T) { } } -func TestAContainerThatExitsImmediatelyFailsTheApply(t *testing.T) { +func testAContainerThatExitsImmediatelyFailsTheApply(t *testing.T) { // `docker run --detach` returning an id says the container was created, not that it is // still running. A container whose entrypoint dies satisfies the command exactly as one // that came up does — which is the read-back rule, in the place it matters most. @@ -802,7 +802,7 @@ func TestAContainerThatExitsImmediatelyFailsTheApply(t *testing.T) { } } -func TestAContainerWhoseDeclarationChangedIsReplaced(t *testing.T) { +func testAContainerWhoseDeclarationChangedIsReplaced(t *testing.T) { // A container's configuration is fixed when it is created, so any change is a replacement. // The spec label is what makes the difference visible without diffing everything the // runtime reports — which cannot be done reliably, because a runtime normalises what it is @@ -845,7 +845,7 @@ func TestAContainerWhoseDeclarationChangedIsReplaced(t *testing.T) { } } -func TestAContainerThatMatchesIsLeftAlone(t *testing.T) { +func testAContainerThatMatchesIsLeftAlone(t *testing.T) { d := parseTrusted(t, `{"declaration":1,"resources":[ {"id":"store","type":"container","name":"store","image":"`+pinned+`","env":{"PGDATA":"/data"}} ]}`) @@ -876,7 +876,7 @@ func TestAContainerThatMatchesIsLeftAlone(t *testing.T) { } } -func TestAContainerIsRecreatedWhenARestartOnResourceChanged(t *testing.T) { +func testAContainerIsRecreatedWhenARestartOnResourceChanged(t *testing.T) { // A container reads a mounted file once, at start. When the file changed this pass but the // container's spec did not, the plain "spec matches, leave it" rule would keep the process // holding the old value for ever, with every check passing (novox/hq 04-ISSUES/009). A @@ -933,7 +933,7 @@ func TestAContainerIsRecreatedWhenARestartOnResourceChanged(t *testing.T) { } } -func TestRestartOnFiresOnlyForResourcesThatChanged(t *testing.T) { +func testRestartOnFiresOnlyForResourcesThatChanged(t *testing.T) { // restart-on must not mean "always restart": it names resources, and only a resource that // changed this pass is a reason. This is the guard shared by containers and services // (novox/hq 04-ISSUES/009), so a container that reflects an unchanged file is left running. @@ -987,7 +987,7 @@ func systemctlStub(t *testing.T, load, active, enabled string, verbs *[]string) } } -func TestAServiceIsEnabledAtBootWhenAsked(t *testing.T) { +func testAServiceIsEnabledAtBootWhenAsked(t *testing.T) { // The gap this closes: the host could start a unit and never make it survive a reboot, so // the declaration reported success and stopped being true at the next power cut. var verbs []string @@ -1008,7 +1008,7 @@ func TestAServiceIsEnabledAtBootWhenAsked(t *testing.T) { } } -func TestBootIsEnabledBeforeTheUnitIsStarted(t *testing.T) { +func testBootIsEnabledBeforeTheUnitIsStarted(t *testing.T) { // Order matters when an apply fails part way. Enabled-and-stopped comes back at the next // boot; running-and-disabled does not. So the more durable half is made true first. var verbs []string @@ -1024,7 +1024,7 @@ func TestBootIsEnabledBeforeTheUnitIsStarted(t *testing.T) { } } -func TestAlreadyEnabledAndRunningIsUnchanged(t *testing.T) { +func testAlreadyEnabledAndRunningIsUnchanged(t *testing.T) { var verbs []string d := parseTrusted(t, `{"declaration":1,"resources":[ {"id":"rt","type":"service","unit":"docker.service","state":"running","boot":"enabled"} @@ -1043,7 +1043,7 @@ func TestAlreadyEnabledAndRunningIsUnchanged(t *testing.T) { } } -func TestOmittingBootLeavesItAlone(t *testing.T) { +func testOmittingBootLeavesItAlone(t *testing.T) { // Absent means the host asserts nothing. A machine whose operator enabled something must // not have it silently disabled because a declaration did not mention it. var verbs []string @@ -1061,7 +1061,7 @@ func TestOmittingBootLeavesItAlone(t *testing.T) { } } -func TestAStaticUnitCannotBeEnabled(t *testing.T) { +func testAStaticUnitCannotBeEnabled(t *testing.T) { // `static` is neither enabled nor disabled: the unit has no install section and CANNOT be // enabled. Reading it as "disabled" would have the host try, fail, and blame the wrong // thing — the same shape as reading a missing unit as "stopped". @@ -1080,7 +1080,7 @@ func TestAStaticUnitCannotBeEnabled(t *testing.T) { } } -func TestAnUnknownBootStateIsRefusedNotGuessed(t *testing.T) { +func testAnUnknownBootStateIsRefusedNotGuessed(t *testing.T) { var verbs []string d := parseTrusted(t, `{"declaration":1,"resources":[ {"id":"rt","type":"service","unit":"x.service","state":"running","boot":"enabled"} @@ -1094,7 +1094,7 @@ func TestAnUnknownBootStateIsRefusedNotGuessed(t *testing.T) { // --- more than one container runtime (novox/hq ADR 0005) --- -func TestTheRuntimeProbeIsPerRuntime(t *testing.T) { +func testTheRuntimeProbeIsPerRuntime(t *testing.T) { // Verified against a real podman 6.1.0 before this was written: // // docker info --format '{{.ServerVersion}}' -> 29.7.2 @@ -1137,7 +1137,7 @@ func TestTheRuntimeProbeIsPerRuntime(t *testing.T) { } } -func TestAContainerUsesTheRuntimeTheMachineHas(t *testing.T) { +func testAContainerUsesTheRuntimeTheMachineHas(t *testing.T) { // The applier must not call `docker` on a machine that has podman. Adoption keeps what the // machine already has (novox/hq research 012), so hardcoding one contradicts it. var calledWith []string @@ -1175,7 +1175,7 @@ func TestAContainerUsesTheRuntimeTheMachineHas(t *testing.T) { } } -func TestNoRuntimeIsSaidPlainly(t *testing.T) { +func testNoRuntimeIsSaidPlainly(t *testing.T) { // Naming what was tried, because "docker: command not found" on a machine that deliberately // runs podman sends the reader looking for the wrong thing. run := func(ctx context.Context, name string, args ...string) (string, error) { @@ -1208,7 +1208,7 @@ func archHost(t *testing.T) system.System { return s } -func TestAServiceIsRestartedWhenWhatItReflectsChanges(t *testing.T) { +func testAServiceIsRestartedWhenWhatItReflectsChanges(t *testing.T) { // A running service does not re-read its configuration. Replace the file, find the service // already running, do nothing — and the machine keeps behaving as it did while every check // passes, because the file is right and the service is up. @@ -1326,7 +1326,7 @@ func TestAServiceIsRestartedWhenWhatItReflectsChanges(t *testing.T) { } } -func TestAServiceIsNotRestartedByAChangeItDoesNotName(t *testing.T) { +func testAServiceIsNotRestartedByAChangeItDoesNotName(t *testing.T) { // The list is what it reflects, not everything in the declaration. A service restarted by any // change anywhere would make every apply a fleet-wide bounce. dir := t.TempDir() @@ -1382,7 +1382,7 @@ func recordingServices(commands *[]string) Runner { } } -func TestAFileChangedOnTheMachineIsCorrectedAndSaidSo(t *testing.T) { +func testAFileChangedOnTheMachineIsCorrectedAndSaidSo(t *testing.T) { // The question this answers: how would anybody know somebody edited a managed file? Before // this they would not. It was rewritten within five minutes and reported as "updated", // which is what the mesh changing its mind looks like — so the person's change vanished and @@ -1424,7 +1424,7 @@ func TestAFileChangedOnTheMachineIsCorrectedAndSaidSo(t *testing.T) { } } -func TestTheMeshChangingItsMindIsNotDrift(t *testing.T) { +func testTheMeshChangingItsMindIsNotDrift(t *testing.T) { // The other half. A new declaration is an ordinary update and must not read as somebody // having meddled, or every real change would look like an incident. dir := t.TempDir() @@ -1451,7 +1451,7 @@ func TestTheMeshChangingItsMindIsNotDrift(t *testing.T) { } } -func TestAnUntouchedFileIsStillUnchanged(t *testing.T) { +func testAnUntouchedFileIsStillUnchanged(t *testing.T) { // And nothing about this makes a steady machine look busy. dir := t.TempDir() path := filepath.Join(dir, "thing.conf") @@ -1474,7 +1474,7 @@ func TestAnUntouchedFileIsStillUnchanged(t *testing.T) { } } -func TestAFailedActionStopsWhatFollows(t *testing.T) { +func testAFailedActionStopsWhatFollows(t *testing.T) { // An action is the only shape whose purpose is to make something true BEFORE the next thing // needs it, which is why it is the only one with a verify. The bootstrap is a row of them: // the store answers, then its databases exist, then their schemas, then the broker. @@ -1515,7 +1515,7 @@ func TestAFailedActionStopsWhatFollows(t *testing.T) { // `resolv.conf` — so every internal name the mesh wrote for the machine is invisible to what the // machine is running. That was hit for real: a database client on one node could not resolve // another node, on a mesh where both names were correct and present on both machines. -func TestAContainerIsGivenTheMeshsNames(t *testing.T) { +func testAContainerIsGivenTheMeshsNames(t *testing.T) { var ran []string run := func(_ context.Context, name string, args ...string) (string, error) { args = oldShape(name, args) @@ -1551,7 +1551,7 @@ func TestAContainerIsGivenTheMeshsNames(t *testing.T) { } // And a container given no names is run exactly as before. -func TestAContainerGivenNoNamesIsRunAsBefore(t *testing.T) { +func testAContainerGivenNoNamesIsRunAsBefore(t *testing.T) { var ran []string run := func(_ context.Context, name string, args ...string) (string, error) { args = oldShape(name, args) @@ -1594,7 +1594,7 @@ func TestAContainerGivenNoNamesIsRunAsBefore(t *testing.T) { // waits: what depends on something being *usable* retries, which is what both example // provisioners do and is more robust than start ordering, because a dependency can also restart // long after everything was applied. -func TestResourcesAreAppliedInTheOrderTheyWereDeclared(t *testing.T) { +func testResourcesAreAppliedInTheOrderTheyWereDeclared(t *testing.T) { dir := t.TempDir() var order []string done := map[string]bool{} @@ -1656,7 +1656,7 @@ func TestResourcesAreAppliedInTheOrderTheyWereDeclared(t *testing.T) { // puts in a directory is itself a declared resource, and orphans are removed in reverse // declaration order — so what the mesh wrote is already gone by the time the directory is // reached. Anything still there was put there by something else. -func TestADirectoryHoldingAnythingTheMeshDidNotPutThereIsKept(t *testing.T) { +func testADirectoryHoldingAnythingTheMeshDidNotPutThereIsKept(t *testing.T) { root := t.TempDir() data := filepath.Join(root, "keycloak") @@ -1702,7 +1702,7 @@ func TestADirectoryHoldingAnythingTheMeshDidNotPutThereIsKept(t *testing.T) { } // An empty one is the mesh's own, and goes. -func TestAnEmptyDirectoryIsStillRemoved(t *testing.T) { +func testAnEmptyDirectoryIsStillRemoved(t *testing.T) { root := t.TempDir() mine := filepath.Join(root, "config") d := declare(t, `{"id":"c","type":"directory","path":"`+mine+`","mode":"0700"}`) @@ -1730,7 +1730,7 @@ func TestAnEmptyDirectoryIsStillRemoved(t *testing.T) { // replaced, and every check passes: the container is up, the spec matched, the machine reported // success. Making what a container reads part of what it is turns that from a tripwire into a // standing comparison. -func TestAContainerStaleFromAnEarlierApplyIsReplaced(t *testing.T) { +func testAContainerStaleFromAnEarlierApplyIsReplaced(t *testing.T) { dir := t.TempDir() conf := filepath.Join(dir, "db.env") // Already on disk with the current content, so this apply changes nothing at all. @@ -1781,7 +1781,7 @@ func TestAContainerStaleFromAnEarlierApplyIsReplaced(t *testing.T) { // A seed is written once. What grows in it afterwards is somebody else's work the mesh asked for, // and a reconcile leaves it alone — content, mode and owner — and says so (novox/hq issue 035). -func TestASeedIsCreatedOnceAndWhatGrowsInItIsKept(t *testing.T) { +func testASeedIsCreatedOnceAndWhatGrowsInItIsKept(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "acl.conf") d := parse(t, fmt.Sprintf(`{"declaration":1,"resources":[ @@ -1815,3 +1815,56 @@ func TestASeedIsCreatedOnceAndWhatGrowsInItIsKept(t *testing.T) { t.Fatalf("what grew in the seed was wiped: %q", grown) } } + +// TestApply runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestApply(t *testing.T) { + t.Run("ApplyingTwiceChangesNothingTheSecondTime", testApplyingTwiceChangesNothingTheSecondTime) + t.Run("ADriftedMachineIsReturned", testADriftedMachineIsReturned) + t.Run("ADroppedResourceIsRemoved", testADroppedResourceIsRemoved) + t.Run("NothingTheHostDidNotCreateIsTouched", testNothingTheHostDidNotCreateIsTouched) + t.Run("ARenameToTheSamePathDoesNotDeleteTheNewFile", testARenameToTheSamePathDoesNotDeleteTheNewFile) + t.Run("AFailedResourceFailsTheApplyAndWhatFollowsIsAttemptedByWhoseItIs", testAFailedResourceFailsTheApplyAndWhatFollowsIsAttemptedByWhoseItIs) + t.Run("NothingIsRecordedUntilItWorked", testNothingIsRecordedUntilItWorked) + t.Run("AModeIsMaintainedNotJustSet", testAModeIsMaintainedNotJustSet) + t.Run("AServiceIsReadBackNotAssumed", testAServiceIsReadBackNotAssumed) + t.Run("AnUnknownServiceStateIsRefusedNotGuessed", testAnUnknownServiceStateIsRefusedNotGuessed) + t.Run("ABootOneShotDeclaredStoppedIsSatisfiedAtRest", testABootOneShotDeclaredStoppedIsSatisfiedAtRest) + t.Run("ADroppedServiceIsGivenBackTheStateItWasFoundIn", testADroppedServiceIsGivenBackTheStateItWasFoundIn) + t.Run("AServiceRecordsTheStateItWasFoundInOnceAndCarriesIt", testAServiceRecordsTheStateItWasFoundInOnceAndCarriesIt) + t.Run("AUnitThatDoesNotExistIsNotStopped", testAUnitThatDoesNotExistIsNotStopped) + t.Run("AMaskedUnitIsRefused", testAMaskedUnitIsRefused) + t.Run("ForgettingAUnitThatIsGoneDoesNotStrandTheNode", testForgettingAUnitThatIsGoneDoesNotStrandTheNode) + t.Run("ABrokenPackageDatabaseIsNotReadAsNotInstalled", testABrokenPackageDatabaseIsNotReadAsNotInstalled) + t.Run("AnInstalledPackageIsNotReinstalled", testAnInstalledPackageIsNotReinstalled) + t.Run("APackageIsNeverUninstalled", testAPackageIsNeverUninstalled) + t.Run("AnActionThatIsAlreadyTrueDoesNotRun", testAnActionThatIsAlreadyTrueDoesNotRun) + t.Run("AnActionThatSucceedsAndDoesNothingFails", testAnActionThatSucceedsAndDoesNothingFails) + t.Run("AnActionRunsInsideTheContainerItNames", testAnActionRunsInsideTheContainerItNames) + t.Run("AContainerThatExitsImmediatelyFailsTheApply", testAContainerThatExitsImmediatelyFailsTheApply) + t.Run("AContainerWhoseDeclarationChangedIsReplaced", testAContainerWhoseDeclarationChangedIsReplaced) + t.Run("AContainerThatMatchesIsLeftAlone", testAContainerThatMatchesIsLeftAlone) + t.Run("AContainerIsRecreatedWhenARestartOnResourceChanged", testAContainerIsRecreatedWhenARestartOnResourceChanged) + t.Run("RestartOnFiresOnlyForResourcesThatChanged", testRestartOnFiresOnlyForResourcesThatChanged) + t.Run("AServiceIsEnabledAtBootWhenAsked", testAServiceIsEnabledAtBootWhenAsked) + t.Run("BootIsEnabledBeforeTheUnitIsStarted", testBootIsEnabledBeforeTheUnitIsStarted) + t.Run("AlreadyEnabledAndRunningIsUnchanged", testAlreadyEnabledAndRunningIsUnchanged) + t.Run("OmittingBootLeavesItAlone", testOmittingBootLeavesItAlone) + t.Run("AStaticUnitCannotBeEnabled", testAStaticUnitCannotBeEnabled) + t.Run("AnUnknownBootStateIsRefusedNotGuessed", testAnUnknownBootStateIsRefusedNotGuessed) + t.Run("TheRuntimeProbeIsPerRuntime", testTheRuntimeProbeIsPerRuntime) + t.Run("AContainerUsesTheRuntimeTheMachineHas", testAContainerUsesTheRuntimeTheMachineHas) + t.Run("NoRuntimeIsSaidPlainly", testNoRuntimeIsSaidPlainly) + t.Run("AServiceIsRestartedWhenWhatItReflectsChanges", testAServiceIsRestartedWhenWhatItReflectsChanges) + t.Run("AServiceIsNotRestartedByAChangeItDoesNotName", testAServiceIsNotRestartedByAChangeItDoesNotName) + t.Run("AFileChangedOnTheMachineIsCorrectedAndSaidSo", testAFileChangedOnTheMachineIsCorrectedAndSaidSo) + t.Run("TheMeshChangingItsMindIsNotDrift", testTheMeshChangingItsMindIsNotDrift) + t.Run("AnUntouchedFileIsStillUnchanged", testAnUntouchedFileIsStillUnchanged) + t.Run("AFailedActionStopsWhatFollows", testAFailedActionStopsWhatFollows) + t.Run("AContainerIsGivenTheMeshsNames", testAContainerIsGivenTheMeshsNames) + t.Run("AContainerGivenNoNamesIsRunAsBefore", testAContainerGivenNoNamesIsRunAsBefore) + t.Run("ResourcesAreAppliedInTheOrderTheyWereDeclared", testResourcesAreAppliedInTheOrderTheyWereDeclared) + t.Run("ADirectoryHoldingAnythingTheMeshDidNotPutThereIsKept", testADirectoryHoldingAnythingTheMeshDidNotPutThereIsKept) + t.Run("AnEmptyDirectoryIsStillRemoved", testAnEmptyDirectoryIsStillRemoved) + t.Run("AContainerStaleFromAnEarlierApplyIsReplaced", testAContainerStaleFromAnEarlierApplyIsReplaced) + t.Run("ASeedIsCreatedOnceAndWhatGrowsInItIsKept", testASeedIsCreatedOnceAndWhatGrowsInItIsKept) +} diff --git a/internal/apply/archive_removal_test.go b/internal/apply/archive_removal_test.go index 19475dd3..6f6783d2 100644 --- a/internal/apply/archive_removal_test.go +++ b/internal/apply/archive_removal_test.go @@ -27,7 +27,7 @@ func archiveDecl(t *testing.T, id, path string, files map[string]string, more st `","path":"` + path + `"}` + more, digest } -func TestUnassigningAnArchiveRemovesExactlyWhatItUnpacked(t *testing.T) { +func testUnassigningAnArchiveRemovesExactlyWhatItUnpacked(t *testing.T) { dir := t.TempDir() target := filepath.Join(dir, "bundles", "notes", "tools") archive, _ := archiveDecl(t, "notes.tools", target, @@ -71,7 +71,7 @@ func TestUnassigningAnArchiveRemovesExactlyWhatItUnpacked(t *testing.T) { } } -func TestADirectoryFoundBeforeTheArchiveKeepsWhatWasInIt(t *testing.T) { +func testADirectoryFoundBeforeTheArchiveKeepsWhatWasInIt(t *testing.T) { dir := t.TempDir() target := filepath.Join(dir, "powerlevel10k") if err := os.MkdirAll(filepath.Join(target, "lib"), 0o755); err != nil { @@ -134,7 +134,7 @@ func TestADirectoryFoundBeforeTheArchiveKeepsWhatWasInIt(t *testing.T) { // A file the archive would write over that the mesh did not put there refuses the archive, and the // directory is left exactly as it was. -func TestAnArchiveDoesNotWriteOverAFileItFound(t *testing.T) { +func testAnArchiveDoesNotWriteOverAFileItFound(t *testing.T) { dir := t.TempDir() target := filepath.Join(dir, "theme") os.MkdirAll(target, 0o755) @@ -247,7 +247,7 @@ func TestAnArchiveDoesNotWriteOverAFileItFound(t *testing.T) { } } -func TestADirectoryTheHostMadeGoesOnlyWhenEmpty(t *testing.T) { +func testADirectoryTheHostMadeGoesOnlyWhenEmpty(t *testing.T) { dir := t.TempDir() target := filepath.Join(dir, "theme") archive, _ := archiveDecl(t, "shell.theme", target, map[string]string{"p10k.zsh": "t", "lib/a.zsh": "a"}, "") @@ -278,7 +278,7 @@ func TestADirectoryTheHostMadeGoesOnlyWhenEmpty(t *testing.T) { // An archive recorded before the host kept what it unpacked cannot be told from anything else in // its directory: it is left in place, said and forgotten, and the apply goes on. -func TestAnArchiveRecordedBeforeItsFilesWereKeptIsLeftAndForgotten(t *testing.T) { +func testAnArchiveRecordedBeforeItsFilesWereKeptIsLeftAndForgotten(t *testing.T) { dir := t.TempDir() target := filepath.Join(dir, "tools") os.MkdirAll(target, 0o755) @@ -308,7 +308,7 @@ func TestAnArchiveRecordedBeforeItsFilesWereKeptIsLeftAndForgotten(t *testing.T) // One recorded before, still declared and unchanged, is read from its own bytes on the next apply, // so it can be undeclared from then on: the whole directory when it holds exactly the archive, only // the archive's files when it holds anything else. -func TestAnArchiveRecordedBeforeLearnsWhatItUnpacked(t *testing.T) { +func testAnArchiveRecordedBeforeLearnsWhatItUnpacked(t *testing.T) { for _, extra := range []bool{false, true} { dir := t.TempDir() target := filepath.Join(dir, "tools") @@ -352,3 +352,13 @@ func TestAnArchiveRecordedBeforeLearnsWhatItUnpacked(t *testing.T) { } } } + +// TestArchiveRemoval runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestArchiveRemoval(t *testing.T) { + t.Run("UnassigningAnArchiveRemovesExactlyWhatItUnpacked", testUnassigningAnArchiveRemovesExactlyWhatItUnpacked) + t.Run("ADirectoryFoundBeforeTheArchiveKeepsWhatWasInIt", testADirectoryFoundBeforeTheArchiveKeepsWhatWasInIt) + t.Run("AnArchiveDoesNotWriteOverAFileItFound", testAnArchiveDoesNotWriteOverAFileItFound) + t.Run("ADirectoryTheHostMadeGoesOnlyWhenEmpty", testADirectoryTheHostMadeGoesOnlyWhenEmpty) + t.Run("AnArchiveRecordedBeforeItsFilesWereKeptIsLeftAndForgotten", testAnArchiveRecordedBeforeItsFilesWereKeptIsLeftAndForgotten) + t.Run("AnArchiveRecordedBeforeLearnsWhatItUnpacked", testAnArchiveRecordedBeforeLearnsWhatItUnpacked) +} diff --git a/internal/apply/archive_replace_test.go b/internal/apply/archive_replace_test.go index 2982f1fd..0a0a5f4e 100644 --- a/internal/apply/archive_replace_test.go +++ b/internal/apply/archive_replace_test.go @@ -10,7 +10,7 @@ import ( // novox/hq issue 220: the tree on disk is exactly the archive. A file the previous archive had and // this one does not is gone, and nothing is left beside the directory. -func TestAnArchiveReplacesTheTreeItWasUnpackedOver(t *testing.T) { +func testAnArchiveReplacesTheTreeItWasUnpackedOver(t *testing.T) { dir := t.TempDir() first, firstDigest := anArchive(t, map[string]string{"index.js": "old", "node_modules/dep/index.js": "dep"}) d := declare(t, `{"id":"bundle-tools","type":"archive","source":"`+serving(t, first)+ @@ -44,7 +44,7 @@ func TestAnArchiveReplacesTheTreeItWasUnpackedOver(t *testing.T) { // A tree is replaced only by one that unpacked whole: an archive refused halfway leaves the old // tree as it was. -func TestARefusedArchiveLeavesTheTreeItWouldHaveReplaced(t *testing.T) { +func testARefusedArchiveLeavesTheTreeItWouldHaveReplaced(t *testing.T) { dir := t.TempDir() first, firstDigest := anArchive(t, map[string]string{"index.js": "old"}) d := declare(t, `{"id":"bundle-tools","type":"archive","source":"`+serving(t, first)+ @@ -66,3 +66,9 @@ func TestARefusedArchiveLeavesTheTreeItWouldHaveReplaced(t *testing.T) { t.Fatalf("%d entries beside the tree after a refused archive", len(entries)) } } + +// TestArchiveReplace runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestArchiveReplace(t *testing.T) { + t.Run("AnArchiveReplacesTheTreeItWasUnpackedOver", testAnArchiveReplacesTheTreeItWasUnpackedOver) + t.Run("ARefusedArchiveLeavesTheTreeItWouldHaveReplaced", testARefusedArchiveLeavesTheTreeItWouldHaveReplaced) +} diff --git a/internal/apply/block_test.go b/internal/apply/block_test.go index 51285f96..140e127c 100644 --- a/internal/apply/block_test.go +++ b/internal/apply/block_test.go @@ -75,7 +75,7 @@ const workstationHosts = "127.0.0.1\tlocalhost\n" + const meshNames = "10.42.0.1 ace\n10.42.0.2 novox\n" -func TestABlockKeepsEveryLineOutsideItsMarkers(t *testing.T) { +func testABlockKeepsEveryLineOutsideItsMarkers(t *testing.T) { path := filepath.Join(t.TempDir(), "hosts") if err := os.WriteFile(path, []byte(workstationHosts), 0o640); err != nil { t.Fatal(err) @@ -129,7 +129,7 @@ func TestABlockKeepsEveryLineOutsideItsMarkers(t *testing.T) { } } -func TestUndeclaringABlockAddedAtTheEndGivesTheFileBackExactly(t *testing.T) { +func testUndeclaringABlockAddedAtTheEndGivesTheFileBackExactly(t *testing.T) { for name, original := range map[string]string{ "ending in a line": "127.0.0.1 localhost\n", "ending in a blank line": "127.0.0.1 localhost\n\n", @@ -147,7 +147,7 @@ func TestUndeclaringABlockAddedAtTheEndGivesTheFileBackExactly(t *testing.T) { } } -func TestABlockAddedAtTheEndIsSetApartFromTheMachinesLines(t *testing.T) { +func testABlockAddedAtTheEndIsSetApartFromTheMachinesLines(t *testing.T) { for name, c := range map[string]struct{ before, after string }{ "no line end": {"127.0.0.1 localhost", "127.0.0.1 localhost\n\n" + marked(namesID, meshNames)}, "a line end": {"127.0.0.1 localhost\n", "127.0.0.1 localhost\n\n" + marked(namesID, meshNames)}, @@ -167,7 +167,7 @@ func TestABlockAddedAtTheEndIsSetApartFromTheMachinesLines(t *testing.T) { } } -func TestTheRegionEndsInExactlyOneLineEnd(t *testing.T) { +func testTheRegionEndsInExactlyOneLineEnd(t *testing.T) { for content, body := range map[string]string{ "10.42.0.1 ace": "10.42.0.1 ace\n", "10.42.0.1 ace\n": "10.42.0.1 ace\n", @@ -188,7 +188,7 @@ func TestTheRegionEndsInExactlyOneLineEnd(t *testing.T) { } } -func TestARegionAlreadyThereIsRewrittenInPlaceAndGivenBack(t *testing.T) { +func testARegionAlreadyThereIsRewrittenInPlaceAndGivenBack(t *testing.T) { path := filepath.Join(t.TempDir(), "hosts") before := "127.0.0.1 localhost\n" after := "# BEGIN devtool x\n127.0.0.1 x.test\n# END devtool x\n192.168.1.20 printer\n" @@ -218,7 +218,7 @@ func TestARegionAlreadyThereIsRewrittenInPlaceAndGivenBack(t *testing.T) { } } -func TestARegionWithNoRecordHoldingExactlyTheDeclaredLinesIsTheMeshs(t *testing.T) { +func testARegionWithNoRecordHoldingExactlyTheDeclaredLinesIsTheMeshs(t *testing.T) { // A host that wrote the region and died before saving its state: what is between the markers // is exactly what the mesh declares, and remembered as the machine's it would never go. path := filepath.Join(t.TempDir(), "hosts") @@ -234,7 +234,7 @@ func TestARegionWithNoRecordHoldingExactlyTheDeclaredLinesIsTheMeshs(t *testing. } } -func TestADriftedRegionIsCorrected(t *testing.T) { +func testADriftedRegionIsCorrected(t *testing.T) { path := filepath.Join(t.TempDir(), "hosts") _ = os.WriteFile(path, []byte(workstationHosts), 0o644) _, state := applyBlockDecl(t, blockDecl(t, path, meshNames), store.State{}) @@ -260,7 +260,7 @@ func TestADriftedRegionIsCorrected(t *testing.T) { } } -func TestTwoRegionsInOneFileAreEachTheirOwn(t *testing.T) { +func testTwoRegionsInOneFileAreEachTheirOwn(t *testing.T) { path := filepath.Join(t.TempDir(), "hosts") _ = os.WriteFile(path, []byte(workstationHosts), 0o644) raw := fmt.Sprintf(`{"declaration":1,"resources":[ @@ -290,7 +290,7 @@ func TestTwoRegionsInOneFileAreEachTheirOwn(t *testing.T) { } } -func TestABlockInAFileThatWasNotThereIsCreatedAndRemovedWithIt(t *testing.T) { +func testABlockInAFileThatWasNotThereIsCreatedAndRemovedWithIt(t *testing.T) { path := filepath.Join(t.TempDir(), "conf.d", "mesh.conf") report, state := applyBlockDecl(t, blockDecl(t, path, meshNames, `"mode":"0600"`), store.State{}) if got := readText(t, path); got != marked(namesID, meshNames) { @@ -322,7 +322,7 @@ func TestABlockInAFileThatWasNotThereIsCreatedAndRemovedWithIt(t *testing.T) { } } -func TestMarkersThatDoNotPairAreRefusedAndLeftAlone(t *testing.T) { +func testMarkersThatDoNotPairAreRefusedAndLeftAlone(t *testing.T) { for name, text := range map[string]string{ "a begin with no end": "a\n# BEGIN mesh " + namesID + "\nb\n", "an end with no begin": "a\n# END mesh " + namesID + "\n", @@ -343,7 +343,7 @@ func TestMarkersThatDoNotPairAreRefusedAndLeftAlone(t *testing.T) { } } -func TestAMarkerOfAnotherIDIsNotThisRegion(t *testing.T) { +func testAMarkerOfAnotherIDIsNotThisRegion(t *testing.T) { // The id is part of the marker: a region whose id merely starts with this one is not it. path := filepath.Join(t.TempDir(), "hosts") other := marked(namesID+"-extra", "10.9.9.9 other\n") @@ -358,7 +358,7 @@ func TestAMarkerOfAnotherIDIsNotThisRegion(t *testing.T) { } } -func TestABlockAtTheStartStandsAboveEverything(t *testing.T) { +func testABlockAtTheStartStandsAboveEverything(t *testing.T) { // dhcpcd scopes every line after `interface X` to that interface, so the mesh's global options // go above all of it. dhcpcd := "hostname\nduid\n\ninterface enp6s0\nstatic ip_address=192.168.1.5/24\n" @@ -399,7 +399,7 @@ func TestABlockAtTheStartStandsAboveEverything(t *testing.T) { }) } -func TestARegionAlreadyThereIsNotMovedWhereverAtSaysItGoes(t *testing.T) { +func testARegionAlreadyThereIsNotMovedWhereverAtSaysItGoes(t *testing.T) { for _, at := range []string{`"at":"start"`, `"at":"end"`} { path := filepath.Join(t.TempDir(), "dhcpcd.conf") original := "hostname\n" + marked(namesID, "old\n") + "interface enp6s0\n" @@ -412,7 +412,7 @@ func TestARegionAlreadyThereIsNotMovedWhereverAtSaysItGoes(t *testing.T) { } } -func TestAFileWrittenIntoABlockIsNeverHeldOnAnAdoptedNode(t *testing.T) { +func testAFileWrittenIntoABlockIsNeverHeldOnAnAdoptedNode(t *testing.T) { path := filepath.Join(t.TempDir(), "hosts") _ = os.WriteFile(path, []byte(workstationHosts), 0o644) resource := fmt.Sprintf(`{"id":%q,"type":"file","path":%q,"into":"block","content":%q}`, namesID, path, meshNames) @@ -450,7 +450,7 @@ func TestAFileWrittenIntoABlockIsNeverHeldOnAnAdoptedNode(t *testing.T) { } } -func TestTheRecordOfABlockSurvivesTheStateFile(t *testing.T) { +func testTheRecordOfABlockSurvivesTheStateFile(t *testing.T) { // What undeclaring needs is in the state a host saves, not only in memory. path := filepath.Join(t.TempDir(), "hosts") original := "a\n" + marked(namesID, "old\n") @@ -496,7 +496,7 @@ func applyKeepingIn(t *testing.T, raw string, known store.State, keepDir string) return report, state } -func TestAFileTheMeshWroteWholeAndMadeItselfKeepsOnlyItsLoopbackLines(t *testing.T) { +func testAFileTheMeshWroteWholeAndMadeItselfKeepsOnlyItsLoopbackLines(t *testing.T) { // Written whole into a file that was not there, then declared as a block under the same id: // the old names must not stay above the region, where a resolver would answer from them first. path := filepath.Join(t.TempDir(), "hosts") @@ -523,7 +523,7 @@ func TestAFileTheMeshWroteWholeAndMadeItselfKeepsOnlyItsLoopbackLines(t *testing } } -func TestAFileTheMeshWroteWholeOverAnOriginalGetsTheOriginalBack(t *testing.T) { +func testAFileTheMeshWroteWholeOverAnOriginalGetsTheOriginalBack(t *testing.T) { path := filepath.Join(t.TempDir(), "hosts") _ = os.WriteFile(path, []byte(workstationHosts), 0o644) keep := t.TempDir() @@ -544,7 +544,7 @@ func TestAFileTheMeshWroteWholeOverAnOriginalGetsTheOriginalBack(t *testing.T) { } } -func TestAFileTheMeshWroteWholeAndSomebodyChangedIsWrittenIntoAsItStands(t *testing.T) { +func testAFileTheMeshWroteWholeAndSomebodyChangedIsWrittenIntoAsItStands(t *testing.T) { path := filepath.Join(t.TempDir(), "hosts") _, state := applyKeepingIn(t, wholeDecl(path, oldWholeHosts), store.State{}, t.TempDir()) edited := oldWholeHosts + "192.168.1.20 printer\n" @@ -558,7 +558,7 @@ func TestAFileTheMeshWroteWholeAndSomebodyChangedIsWrittenIntoAsItStands(t *test } } -func TestALinkedFileStaysALink(t *testing.T) { +func testALinkedFileStaysALink(t *testing.T) { dir := t.TempDir() real := filepath.Join(dir, "static", "hosts") _ = os.MkdirAll(filepath.Dir(real), 0o755) @@ -583,7 +583,7 @@ func TestALinkedFileStaysALink(t *testing.T) { } } -func TestALastLineWithNoEndIsGivenBackWithNone(t *testing.T) { +func testALastLineWithNoEndIsGivenBackWithNone(t *testing.T) { path := filepath.Join(t.TempDir(), "hosts") _ = os.WriteFile(path, []byte("x"), 0o644) _, state := applyBlockDecl(t, blockDecl(t, path, meshNames), store.State{}) @@ -596,7 +596,7 @@ func TestALastLineWithNoEndIsGivenBackWithNone(t *testing.T) { } } -func TestAFailedBlockWriteKeepsItsHold(t *testing.T) { +func testAFailedBlockWriteKeepsItsHold(t *testing.T) { // Held from when it was declared whole, then declared as a block into a file whose markers do // not pair: the write is refused, and the hold — with where its original is — stays. path := filepath.Join(t.TempDir(), "hosts") @@ -616,3 +616,28 @@ func TestAFailedBlockWriteKeepsItsHold(t *testing.T) { t.Errorf("a failed write released the hold: %+v", state.Held) } } + +// TestBlock runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBlock(t *testing.T) { + t.Run("ABlockKeepsEveryLineOutsideItsMarkers", testABlockKeepsEveryLineOutsideItsMarkers) + t.Run("UndeclaringABlockAddedAtTheEndGivesTheFileBackExactly", testUndeclaringABlockAddedAtTheEndGivesTheFileBackExactly) + t.Run("ABlockAddedAtTheEndIsSetApartFromTheMachinesLines", testABlockAddedAtTheEndIsSetApartFromTheMachinesLines) + t.Run("TheRegionEndsInExactlyOneLineEnd", testTheRegionEndsInExactlyOneLineEnd) + t.Run("ARegionAlreadyThereIsRewrittenInPlaceAndGivenBack", testARegionAlreadyThereIsRewrittenInPlaceAndGivenBack) + t.Run("ARegionWithNoRecordHoldingExactlyTheDeclaredLinesIsTheMeshs", testARegionWithNoRecordHoldingExactlyTheDeclaredLinesIsTheMeshs) + t.Run("ADriftedRegionIsCorrected", testADriftedRegionIsCorrected) + t.Run("TwoRegionsInOneFileAreEachTheirOwn", testTwoRegionsInOneFileAreEachTheirOwn) + t.Run("ABlockInAFileThatWasNotThereIsCreatedAndRemovedWithIt", testABlockInAFileThatWasNotThereIsCreatedAndRemovedWithIt) + t.Run("MarkersThatDoNotPairAreRefusedAndLeftAlone", testMarkersThatDoNotPairAreRefusedAndLeftAlone) + t.Run("AMarkerOfAnotherIDIsNotThisRegion", testAMarkerOfAnotherIDIsNotThisRegion) + t.Run("ABlockAtTheStartStandsAboveEverything", testABlockAtTheStartStandsAboveEverything) + t.Run("ARegionAlreadyThereIsNotMovedWhereverAtSaysItGoes", testARegionAlreadyThereIsNotMovedWhereverAtSaysItGoes) + t.Run("AFileWrittenIntoABlockIsNeverHeldOnAnAdoptedNode", testAFileWrittenIntoABlockIsNeverHeldOnAnAdoptedNode) + t.Run("TheRecordOfABlockSurvivesTheStateFile", testTheRecordOfABlockSurvivesTheStateFile) + t.Run("AFileTheMeshWroteWholeAndMadeItselfKeepsOnlyItsLoopbackLines", testAFileTheMeshWroteWholeAndMadeItselfKeepsOnlyItsLoopbackLines) + t.Run("AFileTheMeshWroteWholeOverAnOriginalGetsTheOriginalBack", testAFileTheMeshWroteWholeOverAnOriginalGetsTheOriginalBack) + t.Run("AFileTheMeshWroteWholeAndSomebodyChangedIsWrittenIntoAsItStands", testAFileTheMeshWroteWholeAndSomebodyChangedIsWrittenIntoAsItStands) + t.Run("ALinkedFileStaysALink", testALinkedFileStaysALink) + t.Run("ALastLineWithNoEndIsGivenBackWithNone", testALastLineWithNoEndIsGivenBackWithNone) + t.Run("AFailedBlockWriteKeepsItsHold", testAFailedBlockWriteKeepsItsHold) +} diff --git a/internal/apply/busy_test.go b/internal/apply/busy_test.go index b9fa1494..575d6793 100644 --- a/internal/apply/busy_test.go +++ b/internal/apply/busy_test.go @@ -129,7 +129,7 @@ func applyBusy(t *testing.T, m *aBusyMachine, d *declaration.Declaration, known // The decision's first check: an apply that would replace a container whose busy command exits 0 leaves it // running, applies the rest, and replaces it on the first pass the command exits non-zero. -func TestABusyContainerIsLeftRunningAndReplacedOnTheFirstPassItSaysIdle(t *testing.T) { +func testABusyContainerIsLeftRunningAndReplacedOnTheFirstPassItSaysIdle(t *testing.T) { now := time.Date(2026, 10, 13, 1, 0, 0, 0, time.UTC) atClock(t, &now) m := newBusyMachine() @@ -206,7 +206,7 @@ func TestABusyContainerIsLeftRunningAndReplacedOnTheFirstPassItSaysIdle(t *testi } // An idle container is replaced at once, as one that declares nothing is: asked once, nothing waits. -func TestAnIdleContainerIsReplacedAtOnce(t *testing.T) { +func testAnIdleContainerIsReplacedAtOnce(t *testing.T) { m := newBusyMachine() _, state := applyBusy(t, m, twoContainers(t, "1", "1"), store.State{}) m.answer(false, "") @@ -228,7 +228,7 @@ func TestAnIdleContainerIsReplacedAtOnce(t *testing.T) { // Past the bound it is replaced anyway, the report carrying the command's last output — and the bound holds // across a restart of the node-engine: the wait is read back from the state on disk. -func TestABusyContainerIsReplacedAtTheBoundEvenAfterARestart(t *testing.T) { +func testABusyContainerIsReplacedAtTheBoundEvenAfterARestart(t *testing.T) { now := time.Date(2026, 10, 13, 1, 0, 0, 0, time.UTC) atClock(t, &now) m := newBusyMachine() @@ -274,7 +274,7 @@ func TestABusyContainerIsReplacedAtTheBoundEvenAfterARestart(t *testing.T) { // While one container waits, a send that changes another module on the same machine is applied at once: the // apply returns after one ask, and holds nothing for the wait. -func TestASendToAnotherModuleIsAppliedWhileOneWaits(t *testing.T) { +func testASendToAnotherModuleIsAppliedWhileOneWaits(t *testing.T) { now := time.Date(2026, 10, 13, 1, 0, 0, 0, time.UTC) atClock(t, &now) m := newBusyMachine() @@ -305,7 +305,7 @@ func TestASendToAnotherModuleIsAppliedWhileOneWaits(t *testing.T) { } // A container's busy is held to its shape where it arrives. -func TestBusyIsReadAndHeldToItsShape(t *testing.T) { +func testBusyIsReadAndHeldToItsShape(t *testing.T) { d := twoContainers(t, "1", "1") c := d.Resources[0].(*declaration.Container) if c.Busy == nil || c.Busy.Command != "mesh-builder busy" || c.Busy.Within() != 5*time.Second { @@ -330,7 +330,7 @@ func TestBusyIsReadAndHeldToItsShape(t *testing.T) { // directory (a service, an identity's or a library's change) is in no container's spec and counts as changed only // in the pass it changed, so the container must not read unchanged at the next pass and drop from the report as if // replaced (novox/hq ADR 0335). -func TestAReplacementOwedToARestartTriggerIsMadeOnceIdle(t *testing.T) { +func testAReplacementOwedToARestartTriggerIsMadeOnceIdle(t *testing.T) { now := time.Date(2026, 10, 13, 1, 0, 0, 0, time.UTC) atClock(t, &now) d := parse(t, `{"declaration":1,"resources":[ @@ -368,7 +368,7 @@ func TestAReplacementOwedToARestartTriggerIsMadeOnceIdle(t *testing.T) { } // A wait kept from a clock that later went back is never longer than the bound from now. -func TestAWaitFromAClockThatWentBackIsClampedToNow(t *testing.T) { +func testAWaitFromAClockThatWentBackIsClampedToNow(t *testing.T) { now := time.Date(2026, 10, 13, 1, 0, 0, 0, time.UTC) atClock(t, &now) m := newBusyMachine() @@ -384,7 +384,7 @@ func TestAWaitFromAClockThatWentBackIsClampedToNow(t *testing.T) { } // An ask that fails — no shell in the image, a timeout, a paused container — is not busy: replaced at once. -func TestAnAskThatFailsIsIdle(t *testing.T) { +func testAnAskThatFailsIsIdle(t *testing.T) { m := newBusyMachine() _, state := applyBusy(t, m, twoContainers(t, "1", "1"), store.State{}) failing := func(ctx context.Context, name string, args ...string) (string, error) { @@ -411,7 +411,7 @@ func TestAnAskThatFailsIsIdle(t *testing.T) { } // A stopped container holds no work: it is replaced without being asked. -func TestAStoppedContainerIsNotAsked(t *testing.T) { +func testAStoppedContainerIsNotAsked(t *testing.T) { m := newBusyMachine() _, state := applyBusy(t, m, twoContainers(t, "1", "1"), store.State{}) m.answer(true, "would say busy") @@ -432,3 +432,16 @@ func TestAStoppedContainerIsNotAsked(t *testing.T) { t.Fatalf("a stopped container was asked, or not replaced: %v", got) } } + +// TestBusy runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBusy(t *testing.T) { + t.Run("ABusyContainerIsLeftRunningAndReplacedOnTheFirstPassItSaysIdle", testABusyContainerIsLeftRunningAndReplacedOnTheFirstPassItSaysIdle) + t.Run("AnIdleContainerIsReplacedAtOnce", testAnIdleContainerIsReplacedAtOnce) + t.Run("ABusyContainerIsReplacedAtTheBoundEvenAfterARestart", testABusyContainerIsReplacedAtTheBoundEvenAfterARestart) + t.Run("ASendToAnotherModuleIsAppliedWhileOneWaits", testASendToAnotherModuleIsAppliedWhileOneWaits) + t.Run("BusyIsReadAndHeldToItsShape", testBusyIsReadAndHeldToItsShape) + t.Run("AReplacementOwedToARestartTriggerIsMadeOnceIdle", testAReplacementOwedToARestartTriggerIsMadeOnceIdle) + t.Run("AWaitFromAClockThatWentBackIsClampedToNow", testAWaitFromAClockThatWentBackIsClampedToNow) + t.Run("AnAskThatFailsIsIdle", testAnAskThatFailsIsIdle) + t.Run("AStoppedContainerIsNotAsked", testAStoppedContainerIsNotAsked) +} diff --git a/internal/apply/container_groups_test.go b/internal/apply/container_groups_test.go index ad880e9c..2042874f 100644 --- a/internal/apply/container_groups_test.go +++ b/internal/apply/container_groups_test.go @@ -14,7 +14,7 @@ func groupsContainer(groups ...int64) *declaration.Container { } // 1637/AC1: both run commands carry one --group-add per group, and none without groups. -func TestAContainerIsAddedItsSupplementaryGroups(t *testing.T) { +func testAContainerIsAddedItsSupplementaryGroups(t *testing.T) { with := groupsContainer(2000, 2001) for name, args := range map[string][]string{ "detached": detachedRunArgs(with, "x"), @@ -37,7 +37,7 @@ func TestAContainerIsAddedItsSupplementaryGroups(t *testing.T) { } // 1637/AC2: a changed set of groups recreates the container; no groups leaves the spec as it was. -func TestAChangeOfGroupsRecreatesTheContainer(t *testing.T) { +func testAChangeOfGroupsRecreatesTheContainer(t *testing.T) { none, a, b := groupsContainer(), groupsContainer(2000), groupsContainer(2000, 2001) if containerSpec(none, inputs{}) == containerSpec(a, inputs{}) || containerSpec(a, inputs{}) == containerSpec(b, inputs{}) { t.Error("1637/AC2: a change of groups does not change the container's spec") @@ -52,3 +52,9 @@ func TestAChangeOfGroupsRecreatesTheContainer(t *testing.T) { t.Error("1637/AC2: a container with no groups has its spec moved") } } + +// TestContainerGroups runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestContainerGroups(t *testing.T) { + t.Run("AContainerIsAddedItsSupplementaryGroups", testAContainerIsAddedItsSupplementaryGroups) + t.Run("AChangeOfGroupsRecreatesTheContainer", testAChangeOfGroupsRecreatesTheContainer) +} diff --git a/internal/apply/containers_kept_test.go b/internal/apply/containers_kept_test.go index 8549dace..5d8028aa 100644 --- a/internal/apply/containers_kept_test.go +++ b/internal/apply/containers_kept_test.go @@ -12,7 +12,7 @@ import ( // A taken container keeps a found network by a per-machine setting (novox/hq ADR 0163, rule 4): // joined once it runs, part of its spec, and refused when it cannot be joined. -func TestAContainerJoinsTheNetworksItKeeps(t *testing.T) { +func testAContainerJoinsTheNetworksItKeeps(t *testing.T) { var ran []string connectFails := false run := func(_ context.Context, name string, args ...string) (string, error) { @@ -78,7 +78,7 @@ func TestAContainerJoinsTheNetworksItKeeps(t *testing.T) { var specOfLast string -func TestACapabilityReachesTheRuntimeAndTheSpec(t *testing.T) { +func testACapabilityReachesTheRuntimeAndTheSpec(t *testing.T) { var ran []string run := func(_ context.Context, name string, args ...string) (string, error) { args = oldShape(name, args) @@ -119,7 +119,7 @@ func TestACapabilityReachesTheRuntimeAndTheSpec(t *testing.T) { // A package may be declared absent (novox/hq ADR 0180): removed when it is installed, read back, // left alone when it is not. -func TestAPackageDeclaredAbsentIsRemovedWhenPresentAndLeftWhenNot(t *testing.T) { +func testAPackageDeclaredAbsentIsRemovedWhenPresentAndLeftWhenNot(t *testing.T) { installed := true var ran []string run := func(_ context.Context, name string, args ...string) (string, error) { @@ -156,3 +156,10 @@ func TestAPackageDeclaredAbsentIsRemovedWhenPresentAndLeftWhenNot(t *testing.T) t.Fatalf("a package already absent was touched: %+v\n%v", report.Outcomes[0], ran) } } + +// TestContainersKept runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestContainersKept(t *testing.T) { + t.Run("AContainerJoinsTheNetworksItKeeps", testAContainerJoinsTheNetworksItKeeps) + t.Run("ACapabilityReachesTheRuntimeAndTheSpec", testACapabilityReachesTheRuntimeAndTheSpec) + t.Run("APackageDeclaredAbsentIsRemovedWhenPresentAndLeftWhenNot", testAPackageDeclaredAbsentIsRemovedWhenPresentAndLeftWhenNot) +} diff --git a/internal/apply/declared_home_test.go b/internal/apply/declared_home_test.go index ed6515af..d44073f7 100644 --- a/internal/apply/declared_home_test.go +++ b/internal/apply/declared_home_test.go @@ -27,7 +27,7 @@ func declaredHomeFixture(t *testing.T) (home string, user *declaration.User) { } // 1542/AC1: the .ssh of a declared account, owned by it, is refused by nothing. -func TestIssue1542ADeclaredAccountsSSHIsPlaced(t *testing.T) { +func testIssue1542ADeclaredAccountsSSHIsPlaced(t *testing.T) { home, user := declaredHomeFixture(t) ssh := &declaration.Directory{ID: "mesh-build-go.ssh-dir", Type: declaration.TypeDirectory, Path: home + "/.ssh", Mode: "0700", Owner: "mesh-build-go"} @@ -45,7 +45,7 @@ func TestIssue1542ADeclaredAccountsSSHIsPlaced(t *testing.T) { // 1542/AC2: another account's directory below the declared home is refused as below any home, and a .ssh below // no home of the machine or the declaration is refused with today's words. -func TestIssue1542OnlyTheDeclaredAccountsOwnIsPlaced(t *testing.T) { +func testIssue1542OnlyTheDeclaredAccountsOwnIsPlaced(t *testing.T) { home, user := declaredHomeFixture(t) other := &declaration.Directory{ID: "notes.ssh-dir", Type: declaration.TypeDirectory, Path: home + "/.ssh", Mode: "0700", Owner: "intruder"} @@ -76,7 +76,7 @@ func TestIssue1542OnlyTheDeclaredAccountsOwnIsPlaced(t *testing.T) { } // 1542/AC3: a declared account is no home to anyone but the directory placement guard. -func TestIssue1542DeclaredAccountsAreNotHomesToTheOtherGuards(t *testing.T) { +func testIssue1542DeclaredAccountsAreNotHomesToTheOtherGuards(t *testing.T) { home, user := declaredHomeFixture(t) _ = refusedPlaces([]declaration.Resource{user}) if _, ok := accountsOfHomes()[home]; ok { @@ -89,7 +89,7 @@ func TestIssue1542DeclaredAccountsAreNotHomesToTheOtherGuards(t *testing.T) { // A declared account is added as a home and never takes one over (reviewer, issue 1542): the person's own .ssh // stays refused to every other account, whatever a declaration says about a user. -func TestIssue1542ADeclaredAccountTakesNoExistingHome(t *testing.T) { +func testIssue1542ADeclaredAccountTakesNoExistingHome(t *testing.T) { dir := t.TempDir() passwd := filepath.Join(dir, "passwd") body := "root:x:0:0::/root:/bin/sh\njochen:x:1000:1000::/home/jochen:/bin/sh\n" + @@ -140,7 +140,7 @@ func TestIssue1542ADeclaredAccountTakesNoExistingHome(t *testing.T) { // The account the mesh made, as declared, is judged the same at the next apply (issue 1542): once it is in the // user database with exactly the declared home, its .ssh is still placed. -func TestIssue1542TheAccountTheMeshMadeIsStillPlacedAtTheNextApply(t *testing.T) { +func testIssue1542TheAccountTheMeshMadeIsStillPlacedAtTheNextApply(t *testing.T) { home, user := declaredHomeFixture(t) ssh := &declaration.Directory{ID: "mesh-build-go.ssh-dir", Type: declaration.TypeDirectory, Path: home + "/.ssh", Mode: "0700", Owner: "mesh-build-go"} @@ -156,3 +156,12 @@ func TestIssue1542TheAccountTheMeshMadeIsStillPlacedAtTheNextApply(t *testing.T) t.Fatalf("second apply, the account made as declared: %v", got) } } + +// TestDeclaredHome runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestDeclaredHome(t *testing.T) { + t.Run("Issue1542ADeclaredAccountsSSHIsPlaced", testIssue1542ADeclaredAccountsSSHIsPlaced) + t.Run("Issue1542OnlyTheDeclaredAccountsOwnIsPlaced", testIssue1542OnlyTheDeclaredAccountsOwnIsPlaced) + t.Run("Issue1542DeclaredAccountsAreNotHomesToTheOtherGuards", testIssue1542DeclaredAccountsAreNotHomesToTheOtherGuards) + t.Run("Issue1542ADeclaredAccountTakesNoExistingHome", testIssue1542ADeclaredAccountTakesNoExistingHome) + t.Run("Issue1542TheAccountTheMeshMadeIsStillPlacedAtTheNextApply", testIssue1542TheAccountTheMeshMadeIsStillPlacedAtTheNextApply) +} diff --git a/internal/apply/facts_test.go b/internal/apply/facts_test.go index 3e444e67..57de57bb 100644 --- a/internal/apply/facts_test.go +++ b/internal/apply/facts_test.go @@ -13,7 +13,7 @@ import ( // A take is a comparison (novox/hq ADR 0163): while a module's container is held, the host reports // the found image and its age beside the declared one, the networks and who else is on them, the // mounts and the ports — and says when the declared image is the older. -func TestAHeldContainerCarriesTheFactsATakeCompares(t *testing.T) { +func testAHeldContainerCarriesTheFactsATakeCompares(t *testing.T) { dir, page, m := predecessor(t) m.containers["hello-web"].image = "web:1.27" m.containers["hello-web"].imageID = "sha256:found" @@ -54,7 +54,7 @@ func TestAHeldContainerCarriesTheFactsATakeCompares(t *testing.T) { } // A declared image not yet on the machine leaves its age unknown and the comparison undecided. -func TestAnImageNotYetPulledLeavesTheDowngradeUndecided(t *testing.T) { +func testAnImageNotYetPulledLeavesTheDowngradeUndecided(t *testing.T) { dir, page, m := predecessor(t) m.containers["hello-web"].image = "web:1.27" m.containers["hello-web"].imageID = "sha256:found" @@ -66,7 +66,7 @@ func TestAnImageNotYetPulledLeavesTheDowngradeUndecided(t *testing.T) { } } -func TestTheDifferenceIsWhatIsLostAndWhatIsNew(t *testing.T) { +func testTheDifferenceIsWhatIsLostAndWhatIsNew(t *testing.T) { differs, lines := differenceOf("a\nprivate scope: local\nb\n", "a\nb\nupstream: public\n") if !differs || len(lines) != 2 || lines[0] != "- private scope: local" || lines[1] != "+ upstream: public" { t.Fatalf("got %v %v", differs, lines) @@ -77,7 +77,7 @@ func TestTheDifferenceIsWhatIsLostAndWhatIsNew(t *testing.T) { } // What runs on the machine that the mesh neither wrote nor holds is reported (ADR 0163). -func TestStraysAreWhatRunsHereThatNobodyAsked(t *testing.T) { +func testStraysAreWhatRunsHereThatNobodyAsked(t *testing.T) { m := &machine{containers: map[string]*fakeContainer{ "hello-web": {id: "ours", running: true, image: "web:1"}, "gitea-old": {id: "left-behind", running: true, image: "gitea:1.22"}, @@ -95,3 +95,11 @@ func TestStraysAreWhatRunsHereThatNobodyAsked(t *testing.T) { t.Fatalf("strays: %+v", strays) } } + +// TestFacts runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFacts(t *testing.T) { + t.Run("AHeldContainerCarriesTheFactsATakeCompares", testAHeldContainerCarriesTheFactsATakeCompares) + t.Run("AnImageNotYetPulledLeavesTheDowngradeUndecided", testAnImageNotYetPulledLeavesTheDowngradeUndecided) + t.Run("TheDifferenceIsWhatIsLostAndWhatIsNew", testTheDifferenceIsWhatIsLostAndWhatIsNew) + t.Run("StraysAreWhatRunsHereThatNobodyAsked", testStraysAreWhatRunsHereThatNobodyAsked) +} diff --git a/internal/apply/file_handover_test.go b/internal/apply/file_handover_test.go index 58a392cb..99d40dcf 100644 --- a/internal/apply/file_handover_test.go +++ b/internal/apply/file_handover_test.go @@ -51,7 +51,7 @@ func watching(t *testing.T, path string) Runner { } } -func TestAWholeFileIsHandedToItsNewOwnerNotRemoved(t *testing.T) { +func testAWholeFileIsHandedToItsNewOwnerNotRemoved(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "resolv.conf") if err := os.WriteFile(path, []byte(theOriginal), 0o644); err != nil { @@ -117,7 +117,7 @@ func TestAWholeFileIsHandedToItsNewOwnerNotRemoved(t *testing.T) { // A file the mesh made where there was none is handed over the same way, and is still the mesh's — // undeclared, it goes. -func TestAFileTheMeshMadeIsHandedOverAndStillGoesWithItsLastOwner(t *testing.T) { +func testAFileTheMeshMadeIsHandedOverAndStillGoesWithItsLastOwner(t *testing.T) { path := filepath.Join(t.TempDir(), "resolv.conf") run := watching(t, path) _, state, err := Apply(context.Background(), archHost(t), parse(t, heldBy(t, path, "resolv-conf", firstOwners)), @@ -144,7 +144,7 @@ func TestAFileTheMeshMadeIsHandedOverAndStillGoesWithItsLastOwner(t *testing.T) // A file edited on the machine since the first owner wrote it is still corrected and said so by the // new owner: the handover judges drift against what this host last wrote there. -func TestAHandedOverFileChangedOnTheMachineIsSaidCorrected(t *testing.T) { +func testAHandedOverFileChangedOnTheMachineIsSaidCorrected(t *testing.T) { path := filepath.Join(t.TempDir(), "resolv.conf") _, state, err := Apply(context.Background(), archHost(t), parse(t, heldBy(t, path, "resolv-conf", firstOwners)), store.State{}, store.OriginDeclared, recordingServices(new([]string)), nil, nil) @@ -165,7 +165,7 @@ func TestAHandedOverFileChangedOnTheMachineIsSaidCorrected(t *testing.T) { } // The preview says the same before it happens. -func TestThePlanHandsAFileOverRatherThanRemovingIt(t *testing.T) { +func testThePlanHandsAFileOverRatherThanRemovingIt(t *testing.T) { path := filepath.Join(t.TempDir(), "resolv.conf") _, state, err := Apply(context.Background(), archHost(t), parse(t, heldBy(t, path, "resolv-conf", firstOwners)), store.State{}, store.OriginDeclared, recordingServices(new([]string)), nil, nil) @@ -178,3 +178,11 @@ func TestThePlanHandsAFileOverRatherThanRemovingIt(t *testing.T) { } } } + +// TestFileHandover runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFileHandover(t *testing.T) { + t.Run("AWholeFileIsHandedToItsNewOwnerNotRemoved", testAWholeFileIsHandedToItsNewOwnerNotRemoved) + t.Run("AFileTheMeshMadeIsHandedOverAndStillGoesWithItsLastOwner", testAFileTheMeshMadeIsHandedOverAndStillGoesWithItsLastOwner) + t.Run("AHandedOverFileChangedOnTheMachineIsSaidCorrected", testAHandedOverFileChangedOnTheMachineIsSaidCorrected) + t.Run("ThePlanHandsAFileOverRatherThanRemovingIt", testThePlanHandsAFileOverRatherThanRemovingIt) +} diff --git a/internal/apply/filled_apply_test.go b/internal/apply/filled_apply_test.go index 86c76a1f..b0f8fd89 100644 --- a/internal/apply/filled_apply_test.go +++ b/internal/apply/filled_apply_test.go @@ -19,7 +19,7 @@ import ( // An apply leaves a filled file alone, whatever who owns it at runtime says: absent stays absent and is not // recorded, and what the verb wrote stays as it wrote it through every re-apply. -func TestAnApplyNeverWritesAFilledFile(t *testing.T) { +func testAnApplyNeverWritesAFilledFile(t *testing.T) { for _, c := range []struct{ name, fields, content string }{ {"owned", `"content":"","mode":"0640","owner-at-runtime":"owned"`, "port = 8080\n"}, {"seed", `"content":"","mode":"0600","owner-at-runtime":"seed"`, "user default on\n"}, @@ -78,7 +78,7 @@ func TestAnApplyNeverWritesAFilledFile(t *testing.T) { // What reads a filled file is moved by the verb's write, once, never again by an apply: a service under // restart-on is not restarted and a container reading it is not recreated by the re-apply. -func TestAnApplyMovesNothingForAFilledFile(t *testing.T) { +func testAnApplyMovesNothingForAFilledFile(t *testing.T) { env := filepath.Join(t.TempDir(), "forge.env") d := filledDecl(t, env, `"content":"","mode":"0600","owner-at-runtime":"owned"`, `{"id":"forge.server","type":"container","name":"forge","image":"`+pinned+`","env-file":["`+env+`"]}`) @@ -121,7 +121,7 @@ func TestAnApplyMovesNothingForAFilledFile(t *testing.T) { // A filled file the verb never placed is not the mesh's to remove: one found there, or put there by hand, stays // when the file leaves the declaration. -func TestAFilledFileTheVerbNeverPlacedIsNotRemoved(t *testing.T) { +func testAFilledFileTheVerbNeverPlacedIsNotRemoved(t *testing.T) { path := filepath.Join(t.TempDir(), "the-file") if err := os.WriteFile(path, []byte("the machine's own\n"), 0o644); err != nil { t.Fatal(err) @@ -151,7 +151,7 @@ func TestAFilledFileTheVerbNeverPlacedIsNotRemoved(t *testing.T) { // What the verb placed is the mesh's: when the file leaves the declaration it is removed as an orphan, as a file // an apply wrote is. -func TestAFilledFileTheVerbPlacedIsRemovedWhenItLeaves(t *testing.T) { +func testAFilledFileTheVerbPlacedIsRemovedWhenItLeaves(t *testing.T) { path := filepath.Join(t.TempDir(), "the-file") d := filledDecl(t, path, `"content":"","owner-at-runtime":"owned"`, "") _, state, err := Apply(context.Background(), archHost(t), d, store.State{}, store.OriginDeclared, noServices, @@ -184,7 +184,7 @@ func TestAFilledFileTheVerbPlacedIsRemovedWhenItLeaves(t *testing.T) { // A file the mesh wrote the old way and that is now filled keeps its record for the verb to judge against, and is // not written over by the apply that hands it to the client; a file at the same path recorded under another id // is handed to the filled one, not removed. -func TestAFileThatMovesToTheClientIsHandedNotRewritten(t *testing.T) { +func testAFileThatMovesToTheClientIsHandedNotRewritten(t *testing.T) { path := filepath.Join(t.TempDir(), "the-file") old := parseTrusted(t, fmt.Sprintf(`{"declaration":1,"resources":[{"id":"m.old","type":"file","path":%q,`+ `"content":"port = 1\n"}]}`, path)) @@ -216,3 +216,12 @@ func elsewhere(t *testing.T) *declaration.Declaration { return parseTrusted(t, fmt.Sprintf(`{"declaration":1,"resources":[{"id":"n.other","type":"file","path":%q,`+ `"content":"x\n"}]}`, filepath.Join(t.TempDir(), "other"))) } + +// TestFilledApply runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFilledApply(t *testing.T) { + t.Run("AnApplyNeverWritesAFilledFile", testAnApplyNeverWritesAFilledFile) + t.Run("AnApplyMovesNothingForAFilledFile", testAnApplyMovesNothingForAFilledFile) + t.Run("AFilledFileTheVerbNeverPlacedIsNotRemoved", testAFilledFileTheVerbNeverPlacedIsNotRemoved) + t.Run("AFilledFileTheVerbPlacedIsRemovedWhenItLeaves", testAFilledFileTheVerbPlacedIsRemovedWhenItLeaves) + t.Run("AFileThatMovesToTheClientIsHandedNotRewritten", testAFileThatMovesToTheClientIsHandedNotRewritten) +} diff --git a/internal/apply/filled_runtime_roots_test.go b/internal/apply/filled_runtime_roots_test.go index 947704ad..916e8c24 100644 --- a/internal/apply/filled_runtime_roots_test.go +++ b/internal/apply/filled_runtime_roots_test.go @@ -70,7 +70,7 @@ func refusedAsPlacement(t *testing.T, err error) { } // 1138/AC1: a filled write asks no runtime, and judges with the roots the last apply read. -func TestAFilledWriteAsksNoRuntimeAndUsesTheLastApplysRoots(t *testing.T) { +func testAFilledWriteAsksNoRuntimeAndUsesTheLastApplysRoots(t *testing.T) { root := filepath.Join(t.TempDir(), "docker-root") setRuntimeRoots(t, []string{root}) // as if an apply had just read it @@ -90,7 +90,7 @@ func TestAFilledWriteAsksNoRuntimeAndUsesTheLastApplysRoots(t *testing.T) { // 1138/AC2: given a real apply that read a runtime data root, a filled write below it is refused as today, with // no apply run again in between. -func TestAFilledWriteBelowARootARealApplyReadIsRefused(t *testing.T) { +func testAFilledWriteBelowARootARealApplyReadIsRefused(t *testing.T) { dir, root := aRuntimeConfig(t) t.Cleanup(func() { runtimeRootsMu.Lock() @@ -116,7 +116,7 @@ func TestAFilledWriteBelowARootARealApplyReadIsRefused(t *testing.T) { // 1138/AC3: with no apply having read the roots yet, a filled write judges by the runtimes' configuration files, // asking no runtime. -func TestAFilledWriteWithNoApplyYetUsesTheRuntimesConfigFiles(t *testing.T) { +func testAFilledWriteWithNoApplyYetUsesTheRuntimesConfigFiles(t *testing.T) { setRuntimeRoots(t, nil) // no apply has read the roots yet _, root := aRuntimeConfig(t) @@ -135,7 +135,7 @@ func TestAFilledWriteWithNoApplyYetUsesTheRuntimesConfigFiles(t *testing.T) { } // 1138/AC4: a full apply still asks each runtime once, at its start, whatever the number of files it writes. -func TestAFullApplyAsksEachRuntimeOnceRegardlessOfFileCount(t *testing.T) { +func testAFullApplyAsksEachRuntimeOnceRegardlessOfFileCount(t *testing.T) { dir := t.TempDir() var asked []string before := AskRuntimes @@ -166,3 +166,11 @@ func TestAFullApplyAsksEachRuntimeOnceRegardlessOfFileCount(t *testing.T) { t.Errorf("podman was asked %d times for one apply of 3 files; want 1: %v", got, asked) } } + +// TestFilledRuntimeRoots runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFilledRuntimeRoots(t *testing.T) { + t.Run("AFilledWriteAsksNoRuntimeAndUsesTheLastApplysRoots", testAFilledWriteAsksNoRuntimeAndUsesTheLastApplysRoots) + t.Run("AFilledWriteBelowARootARealApplyReadIsRefused", testAFilledWriteBelowARootARealApplyReadIsRefused) + t.Run("AFilledWriteWithNoApplyYetUsesTheRuntimesConfigFiles", testAFilledWriteWithNoApplyYetUsesTheRuntimesConfigFiles) + t.Run("AFullApplyAsksEachRuntimeOnceRegardlessOfFileCount", testAFullApplyAsksEachRuntimeOnceRegardlessOfFileCount) +} diff --git a/internal/apply/filled_test.go b/internal/apply/filled_test.go index ebaecade..d271a788 100644 --- a/internal/apply/filled_test.go +++ b/internal/apply/filled_test.go @@ -28,7 +28,7 @@ func filledDecl(t *testing.T, path, fields, more string) *declaration.Declaratio "filled_files":[%q],"resources":[{"id":"m.conf","type":"file","path":%q,%s}%s]}`, path, path, fields, more)) } -func TestAWriteOfAPathNotFilledIsRefused(t *testing.T) { +func testAWriteOfAPathNotFilledIsRefused(t *testing.T) { dir := t.TempDir() filled := filepath.Join(dir, "filled.conf") other := filepath.Join(dir, "other.conf") @@ -74,7 +74,7 @@ func TestAWriteOfAPathNotFilledIsRefused(t *testing.T) { // Each ownership is written by the write verb exactly as an apply of the declared file with the same content: the // same action, the same bytes on disk, the same mode. -func TestAFilledFileIsWrittenAsItsOwnershipSays(t *testing.T) { +func testAFilledFileIsWrittenAsItsOwnershipSays(t *testing.T) { for _, c := range []struct { name, fields, content, before, action string }{ @@ -166,7 +166,7 @@ func modeAt(t *testing.T, path string) os.FileMode { // A file that carried a secret keeps the mode a secret is written with: the client filled the value, and the file // is no more readable for it. -func TestAWriteUnderReloadOnReloadsItsProgramOnce(t *testing.T) { +func testAWriteUnderReloadOnReloadsItsProgramOnce(t *testing.T) { path := filepath.Join(t.TempDir(), "daemon.conf") d := filledDecl(t, path, `"content":"","owner-at-runtime":"owned"`, `{"id":"m.daemon","type":"service","unit":"m.service","state":"running","reload-on":["m.conf"]}, @@ -213,7 +213,7 @@ func TestAWriteUnderReloadOnReloadsItsProgramOnce(t *testing.T) { } } -func TestAWriteUnderRestartOnRestartsItsProgram(t *testing.T) { +func testAWriteUnderRestartOnRestartsItsProgram(t *testing.T) { path := filepath.Join(t.TempDir(), "daemon.conf") d := filledDecl(t, path, `"content":"","owner-at-runtime":"owned"`, `{"id":"m.daemon","type":"service","unit":"m.service","state":"running","restart-on":["m.conf"]}`) @@ -230,7 +230,7 @@ func TestAWriteUnderRestartOnRestartsItsProgram(t *testing.T) { } // A running container that reads the file at creation is recreated, as an apply recreates it for a changed file. -func TestAWriteOfAFileAContainerReadsRecreatesIt(t *testing.T) { +func testAWriteOfAFileAContainerReadsRecreatesIt(t *testing.T) { env := filepath.Join(t.TempDir(), "forge.env") d := filledDecl(t, env, `"content":"","mode":"0600","owner-at-runtime":"owned"`, `{"id":"forge.server","type":"container","name":"forge","image":"`+pinned+`","env-file":["`+env+`"]}`) @@ -269,3 +269,12 @@ func count(lines []string, prefix string) int { // Two resources declaring one filled path — two modules' blocks in one file — are refused: the request carries the // content only, so it cannot say whose block it is, and nothing is written. + +// TestFilled runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFilled(t *testing.T) { + t.Run("AWriteOfAPathNotFilledIsRefused", testAWriteOfAPathNotFilledIsRefused) + t.Run("AFilledFileIsWrittenAsItsOwnershipSays", testAFilledFileIsWrittenAsItsOwnershipSays) + t.Run("AWriteUnderReloadOnReloadsItsProgramOnce", testAWriteUnderReloadOnReloadsItsProgramOnce) + t.Run("AWriteUnderRestartOnRestartsItsProgram", testAWriteUnderRestartOnRestartsItsProgram) + t.Run("AWriteOfAFileAContainerReadsRecreatesIt", testAWriteOfAFileAContainerReadsRecreatesIt) +} diff --git a/internal/apply/found_is_said_test.go b/internal/apply/found_is_said_test.go index 5155cce8..3ae11454 100644 --- a/internal/apply/found_is_said_test.go +++ b/internal/apply/found_is_said_test.go @@ -12,7 +12,7 @@ import ( ) // A directory used as found is never quiet, and a person at the machine can hand it over (novox/hq issue 339). -func TestAFoundDirectoryIsSaidAndCanBeHandedOver(t *testing.T) { +func testAFoundDirectoryIsSaidAndCanBeHandedOver(t *testing.T) { dir := t.TempDir() found := filepath.Join(dir, "found") if err := os.Mkdir(found, 0o700); err != nil { @@ -60,7 +60,7 @@ func TestAFoundDirectoryIsSaidAndCanBeHandedOver(t *testing.T) { // The review's additions to the guard: the spool, /opt, the container runtimes' data wherever the runtime keeps // it, and an account's .ssh as an access or a mount, or as a directory anywhere but its own home. -func TestTheRuntimesDataAndAnySSHAreRefused(t *testing.T) { +func testTheRuntimesDataAndAnySSHAreRefused(t *testing.T) { cfg := filepath.Join(t.TempDir(), "daemon.json") if err := os.WriteFile(cfg, []byte(`{"data-root":"/storage/docker"}`), 0o644); err != nil { t.Fatal(err) @@ -90,7 +90,7 @@ func TestTheRuntimesDataAndAnySSHAreRefused(t *testing.T) { // When a directory was found is kept from the first apply that found it (novox/hq issue 339): the controller // tells a directory a send found from one found before it by that time, so it must not move with every apply. -func TestWhenADirectoryWasFoundIsKept(t *testing.T) { +func testWhenADirectoryWasFoundIsKept(t *testing.T) { dir := t.TempDir() found := filepath.Join(dir, "found") if err := os.Mkdir(found, 0o700); err != nil { @@ -118,7 +118,7 @@ func TestWhenADirectoryWasFoundIsKept(t *testing.T) { // A hand-over is for the resource that was used as found there: another declaration that later points another // resource at the same path is not handed anything (novox/hq issue 339). -func TestAHandOverIsForTheResourceThatAskedForIt(t *testing.T) { +func testAHandOverIsForTheResourceThatAskedForIt(t *testing.T) { dir := t.TempDir() found := filepath.Join(dir, "found") if err := os.Mkdir(found, 0o700); err != nil { @@ -141,7 +141,7 @@ func TestAHandOverIsForTheResourceThatAskedForIt(t *testing.T) { // hand-over refused a link when it was recorded; between then and the apply its parent is swapped for a link to // a victim tree. The apply refuses, and the victim's directory keeps its mode — and so does a directory whose own // name became a link, and one whose grandparent did. -func TestAHandedOverDirectoryIsChangedThroughNoLink(t *testing.T) { +func testAHandedOverDirectoryIsChangedThroughNoLink(t *testing.T) { for _, c := range []struct { swap string applyOnce bool @@ -229,7 +229,7 @@ func TestAHandedOverDirectoryIsChangedThroughNoLink(t *testing.T) { // The check at the moment of use, without the path's re-check: a component swapped for a link is refused by the // descriptor walk itself, whatever was resolved a moment before. -func TestGiveHandedOverFollowsNoLink(t *testing.T) { +func testGiveHandedOverFollowsNoLink(t *testing.T) { dir, err := filepath.EvalSymlinks(t.TempDir()) if err != nil { t.Fatal(err) @@ -255,3 +255,13 @@ func TestGiveHandedOverFollowsNoLink(t *testing.T) { t.Fatalf("the directory itself was not given its mode: %o", info.Mode().Perm()) } } + +// TestFoundIsSaid runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFoundIsSaid(t *testing.T) { + t.Run("AFoundDirectoryIsSaidAndCanBeHandedOver", testAFoundDirectoryIsSaidAndCanBeHandedOver) + t.Run("TheRuntimesDataAndAnySSHAreRefused", testTheRuntimesDataAndAnySSHAreRefused) + t.Run("WhenADirectoryWasFoundIsKept", testWhenADirectoryWasFoundIsKept) + t.Run("AHandOverIsForTheResourceThatAskedForIt", testAHandOverIsForTheResourceThatAskedForIt) + t.Run("AHandedOverDirectoryIsChangedThroughNoLink", testAHandedOverDirectoryIsChangedThroughNoLink) + t.Run("GiveHandedOverFollowsNoLink", testGiveHandedOverFollowsNoLink) +} diff --git a/internal/apply/found_test.go b/internal/apply/found_test.go index f46fe576..49537b92 100644 --- a/internal/apply/found_test.go +++ b/internal/apply/found_test.go @@ -44,7 +44,7 @@ func applyOn(t *testing.T, raw string, known store.State, m *machine) (Report, s return Apply(context.Background(), archHost(t), parse(t, raw), known, store.OriginDeclared, m.run, nil, nil) } -func TestAUnitWhoseFileTheMeshWroteIsStoppedWhateverItsRecordSays(t *testing.T) { +func testAUnitWhoseFileTheMeshWroteIsStoppedWhateverItsRecordSays(t *testing.T) { // The adoption guard's unit file is the mesh's own file resource, written where there was none. // Its service recorded before the host kept what it found has no Found, and forgetting it left // the guard's table loaded on a converged node and its unit file deleted from under it. @@ -110,7 +110,7 @@ func TestAUnitWhoseFileTheMeshWroteIsStoppedWhateverItsRecordSays(t *testing.T) } } -func TestOnlyAUnitsOwnFileTheMeshCreatedMakesItTheMeshs(t *testing.T) { +func testOnlyAUnitsOwnFileTheMeshCreatedMakesItTheMeshs(t *testing.T) { known := store.State{Resources: []store.Applied{ {ID: "a", Type: "file", Target: "/etc/systemd/system/made.service"}, {ID: "b", Type: "file", Target: "/run/systemd/system/runtime.service"}, @@ -129,7 +129,7 @@ func TestOnlyAUnitsOwnFileTheMeshCreatedMakesItTheMeshs(t *testing.T) { } } -func TestWhatWasFoundOutlivesAFirstApplyThatFailed(t *testing.T) { +func testWhatWasFoundOutlivesAFirstApplyThatFailed(t *testing.T) { // Enabled, then it would not start: no record. The next apply must not read the enable as // the machine's — or undeclaring leaves enabled a unit the mesh enabled. m := unitsMachine(map[string]*fakeUnit{"filter.service": {active: "inactive", enabled: "disabled", wontStart: true}}) @@ -177,7 +177,7 @@ func TestWhatWasFoundOutlivesAFirstApplyThatFailed(t *testing.T) { } } -func TestBootIsFoundTheFirstTimeTheMeshSetsIt(t *testing.T) { +func testBootIsFoundTheFirstTimeTheMeshSetsIt(t *testing.T) { // The declaration said nothing about boot at first, so the mesh never touched it: what is // there when a declaration first does is still the machine's. m := unitsMachine(map[string]*fakeUnit{"web.service": {active: "active", enabled: "disabled"}}) @@ -204,7 +204,7 @@ func TestBootIsFoundTheFirstTimeTheMeshSetsIt(t *testing.T) { } } -func TestAServiceOnceDeclaredWithNoStateIsFoundWhenFirstGivenOne(t *testing.T) { +func testAServiceOnceDeclaredWithNoStateIsFoundWhenFirstGivenOne(t *testing.T) { // Declared with no state (novox/hq ADR 0117), the mesh never started or stopped it — so what // is there when a declaration first gives it one is what the machine had. m := unitsMachine(map[string]*fakeUnit{"net.service": {active: "inactive", enabled: "disabled"}}) @@ -226,7 +226,7 @@ func TestAServiceOnceDeclaredWithNoStateIsFoundWhenFirstGivenOne(t *testing.T) { } } -func TestAUnitWrittenInTheSameApplyIsLoadedBeforeItIsRead(t *testing.T) { +func testAUnitWrittenInTheSameApplyIsLoadedBeforeItIsRead(t *testing.T) { // Read before the service manager is told about its new file, the unit is not there to find. dir := t.TempDir() m := unitsMachine(map[string]*fakeUnit{"fresh.service": {active: "inactive", enabled: "disabled"}}) @@ -251,7 +251,7 @@ func TestAUnitWrittenInTheSameApplyIsLoadedBeforeItIsRead(t *testing.T) { } } -func TestAServiceMovedToAnotherUnitGivesTheOldOneBackAndFindsTheNewOne(t *testing.T) { +func testAServiceMovedToAnotherUnitGivesTheOldOneBackAndFindsTheNewOne(t *testing.T) { m := unitsMachine(map[string]*fakeUnit{ "old.service": {active: "active", enabled: "enabled"}, "new.service": {active: "inactive", enabled: "disabled"}, @@ -278,7 +278,7 @@ func TestAServiceMovedToAnotherUnitGivesTheOldOneBackAndFindsTheNewOne(t *testin } } -func TestARemovalSaysWhatItDid(t *testing.T) { +func testARemovalSaysWhatItDid(t *testing.T) { cases := []struct { name string found *store.FoundUnit @@ -334,7 +334,7 @@ func TestARemovalSaysWhatItDid(t *testing.T) { } } -func TestAUnitTheMeshStartedIsStoppedWhenUndeclaredAndOneFoundRunningIsNot(t *testing.T) { +func testAUnitTheMeshStartedIsStoppedWhenUndeclaredAndOneFoundRunningIsNot(t *testing.T) { // End to end: found by the first apply, carried, given back. m := unitsMachine(map[string]*fakeUnit{ "filter.service": {active: "inactive", enabled: "disabled"}, @@ -361,7 +361,7 @@ func TestAUnitTheMeshStartedIsStoppedWhenUndeclaredAndOneFoundRunningIsNot(t *te } } -func TestAUnitHeldAndThenTakenIsFoundAsThePredecessorLeftIt(t *testing.T) { +func testAUnitHeldAndThenTakenIsFoundAsThePredecessorLeftIt(t *testing.T) { // Held while its module was untaken, nothing was applied and nothing found; taken, the first // apply finds the predecessor's unit — stopped, but started at boot — before starting it. dir := t.TempDir() @@ -386,3 +386,17 @@ func TestAUnitHeldAndThenTakenIsFoundAsThePredecessorLeftIt(t *testing.T) { t.Errorf("given back as %s and %s; the predecessor left it stopped and enabled", u.active, u.enabled) } } + +// TestFound runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFound(t *testing.T) { + t.Run("AUnitWhoseFileTheMeshWroteIsStoppedWhateverItsRecordSays", testAUnitWhoseFileTheMeshWroteIsStoppedWhateverItsRecordSays) + t.Run("OnlyAUnitsOwnFileTheMeshCreatedMakesItTheMeshs", testOnlyAUnitsOwnFileTheMeshCreatedMakesItTheMeshs) + t.Run("WhatWasFoundOutlivesAFirstApplyThatFailed", testWhatWasFoundOutlivesAFirstApplyThatFailed) + t.Run("BootIsFoundTheFirstTimeTheMeshSetsIt", testBootIsFoundTheFirstTimeTheMeshSetsIt) + t.Run("AServiceOnceDeclaredWithNoStateIsFoundWhenFirstGivenOne", testAServiceOnceDeclaredWithNoStateIsFoundWhenFirstGivenOne) + t.Run("AUnitWrittenInTheSameApplyIsLoadedBeforeItIsRead", testAUnitWrittenInTheSameApplyIsLoadedBeforeItIsRead) + t.Run("AServiceMovedToAnotherUnitGivesTheOldOneBackAndFindsTheNewOne", testAServiceMovedToAnotherUnitGivesTheOldOneBackAndFindsTheNewOne) + t.Run("ARemovalSaysWhatItDid", testARemovalSaysWhatItDid) + t.Run("AUnitTheMeshStartedIsStoppedWhenUndeclaredAndOneFoundRunningIsNot", testAUnitTheMeshStartedIsStoppedWhenUndeclaredAndOneFoundRunningIsNot) + t.Run("AUnitHeldAndThenTakenIsFoundAsThePredecessorLeftIt", testAUnitHeldAndThenTakenIsFoundAsThePredecessorLeftIt) +} diff --git a/internal/apply/giveback_test.go b/internal/apply/giveback_test.go index 94c5a52d..4680ac45 100644 --- a/internal/apply/giveback_test.go +++ b/internal/apply/giveback_test.go @@ -11,7 +11,7 @@ import ( // given back running and enabled when that declaration goes (the zfs module holds the distribution's // scrub timer stopped while its own timer scrubs the pool; unassigning it must not leave the pool with no // schedule at all). The report says so. -func TestAUnitTheMeshStoppedAndDisabledIsGivenBackRunningAndEnabled(t *testing.T) { +func testAUnitTheMeshStoppedAndDisabledIsGivenBackRunningAndEnabled(t *testing.T) { m := unitsMachine(map[string]*fakeUnit{ "zfs-scrub-weekly@storage.timer": {active: "active", enabled: "enabled"}, }) @@ -44,7 +44,7 @@ func TestAUnitTheMeshStoppedAndDisabledIsGivenBackRunningAndEnabled(t *testing.T // Only what the mesh's own declaration did is undone: a unit the mesh held stopped that was found stopped // stays stopped, and one found running that the mesh never stopped is left running as before. -func TestOnlyWhatTheMeshsDeclarationStoppedIsStartedAgain(t *testing.T) { +func testOnlyWhatTheMeshsDeclarationStoppedIsStartedAgain(t *testing.T) { m := unitsMachine(map[string]*fakeUnit{ "found-stopped.timer": {active: "inactive", enabled: "disabled"}, "left-running.timer": {active: "active", enabled: "enabled"}, @@ -69,7 +69,7 @@ func TestOnlyWhatTheMeshsDeclarationStoppedIsStartedAgain(t *testing.T) { // A record from before the host kept what it declared says nothing about who stopped the unit: it is // left as it is, never started. -func TestARecordWithoutWhatWasDeclaredStartsNothing(t *testing.T) { +func testARecordWithoutWhatWasDeclaredStartsNothing(t *testing.T) { m := unitsMachine(map[string]*fakeUnit{"old.timer": {active: "inactive", enabled: "disabled"}}) state := store.State{} state.Record(store.Applied{ID: "old", Type: "service", Target: "old.timer", Origin: store.OriginDeclared, @@ -83,7 +83,7 @@ func TestARecordWithoutWhatWasDeclaredStartsNothing(t *testing.T) { } // The plan says it before the apply does it. -func TestThePlanSaysAStoppedUnitIsStartedAgain(t *testing.T) { +func testThePlanSaysAStoppedUnitIsStartedAgain(t *testing.T) { m := unitsMachine(map[string]*fakeUnit{"zfs-scrub-weekly@storage.timer": {active: "active", enabled: "enabled"}}) _, state, err := applyOn(t, `{"declaration":1,"resources":[ {"id":"w","type":"service","unit":"zfs-scrub-weekly@storage.timer","state":"stopped","boot":"disabled"}]}`, @@ -105,7 +105,7 @@ func TestThePlanSaysAStoppedUnitIsStartedAgain(t *testing.T) { // Third review: on removal a unit is started again only when it is exactly as the mesh held it, stopped and // disabled. A masked unit, or one somebody started or enabled since, is left alone, and the report says why. -func TestAMaskedOrChangedUnitIsLeftAloneOnRemoval(t *testing.T) { +func testAMaskedOrChangedUnitIsLeftAloneOnRemoval(t *testing.T) { for _, c := range []struct { name, active, enabled, says string }{ @@ -141,7 +141,7 @@ func TestAMaskedOrChangedUnitIsLeftAloneOnRemoval(t *testing.T) { // A restore that fails — the start refused, or the unit not running after it — waits: the record stays, // the report says so, and no apply is made fatal by it. -func TestAFailedRestoreWaitsAndIsNeverFatal(t *testing.T) { +func testAFailedRestoreWaitsAndIsNeverFatal(t *testing.T) { m := unitsMachine(map[string]*fakeUnit{"w.timer": {active: "active", enabled: "enabled"}}) _, state, err := applyOn(t, `{"declaration":1,"resources":[ {"id":"w","type":"service","unit":"w.timer","state":"stopped","boot":"disabled"}]}`, store.State{}, m) @@ -169,3 +169,13 @@ func TestAFailedRestoreWaitsAndIsNeverFatal(t *testing.T) { state = next } } + +// TestGiveback runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestGiveback(t *testing.T) { + t.Run("AUnitTheMeshStoppedAndDisabledIsGivenBackRunningAndEnabled", testAUnitTheMeshStoppedAndDisabledIsGivenBackRunningAndEnabled) + t.Run("OnlyWhatTheMeshsDeclarationStoppedIsStartedAgain", testOnlyWhatTheMeshsDeclarationStoppedIsStartedAgain) + t.Run("ARecordWithoutWhatWasDeclaredStartsNothing", testARecordWithoutWhatWasDeclaredStartsNothing) + t.Run("ThePlanSaysAStoppedUnitIsStartedAgain", testThePlanSaysAStoppedUnitIsStartedAgain) + t.Run("AMaskedOrChangedUnitIsLeftAloneOnRemoval", testAMaskedOrChangedUnitIsLeftAloneOnRemoval) + t.Run("AFailedRestoreWaitsAndIsNeverFatal", testAFailedRestoreWaitsAndIsNeverFatal) +} diff --git a/internal/apply/groups_test.go b/internal/apply/groups_test.go index 78630ec0..863e4d7d 100644 --- a/internal/apply/groups_test.go +++ b/internal/apply/groups_test.go @@ -91,7 +91,7 @@ const ( shell = `{"id":"zsh.login","type":"user","name":"operator","groups":[]}` ) -func TestAModulePutsTheAccountInAGroupAndSaysANewLoginIsNeeded(t *testing.T) { +func testAModulePutsTheAccountInAGroupAndSaysANewLoginIsNeeded(t *testing.T) { g := newGroupDB([]string{"wheel", "plugdev"}, "openrazer") report, state, err := applyGroupsOf(t, g, store.State{}, shell, razer) if err != nil { @@ -126,7 +126,7 @@ func TestAModulePutsTheAccountInAGroupAndSaysANewLoginIsNeeded(t *testing.T) { } } -func TestAGroupTheAccountWasAlreadyInIsNeverTakenBack(t *testing.T) { +func testAGroupTheAccountWasAlreadyInIsNeverTakenBack(t *testing.T) { g := newGroupDB([]string{"wheel", "openrazer"}) _, state, err := applyGroupsOf(t, g, store.State{}, razer) if err != nil { @@ -143,7 +143,7 @@ func TestAGroupTheAccountWasAlreadyInIsNeverTakenBack(t *testing.T) { } } -func TestTheGroupTheMeshAddedIsGivenBackWhenItsModuleGoes(t *testing.T) { +func testTheGroupTheMeshAddedIsGivenBackWhenItsModuleGoes(t *testing.T) { g := newGroupDB([]string{"wheel"}, "openrazer") _, state, err := applyGroupsOf(t, g, store.State{}, razer) if err != nil { @@ -165,7 +165,7 @@ func TestTheGroupTheMeshAddedIsGivenBackWhenItsModuleGoes(t *testing.T) { } } -func TestAGroupAnotherResourceStillAsksForStays(t *testing.T) { +func testAGroupAnotherResourceStillAsksForStays(t *testing.T) { both := `{"id":"openrazer.account","type":"user","name":"operator","groups":["openrazer","video"]}` video := `{"id":"media.account","type":"user","name":"operator","groups":["video"]}` g := newGroupDB(nil, "openrazer", "video") @@ -185,7 +185,7 @@ func TestAGroupAnotherResourceStillAsksForStays(t *testing.T) { } } -func TestAGroupNoLongerDeclaredIsGivenBackWhileTheAccountStaysDeclared(t *testing.T) { +func testAGroupNoLongerDeclaredIsGivenBackWhileTheAccountStaysDeclared(t *testing.T) { g := newGroupDB(nil, "openrazer", "input") two := `{"id":"openrazer.account","type":"user","name":"operator","groups":["openrazer","input"]}` _, state, err := applyGroupsOf(t, g, store.State{}, two) @@ -204,7 +204,7 @@ func TestAGroupNoLongerDeclaredIsGivenBackWhileTheAccountStaysDeclared(t *testin } } -func TestAGroupThatDoesNotExistYetFailsTheResourceSayingSo(t *testing.T) { +func testAGroupThatDoesNotExistYetFailsTheResourceSayingSo(t *testing.T) { g := newGroupDB([]string{"wheel"}) _, _, err := applyGroupsOf(t, g, store.State{}, razer) if err == nil || !strings.Contains(err.Error(), "no such group yet") { @@ -217,7 +217,7 @@ func TestAGroupThatDoesNotExistYetFailsTheResourceSayingSo(t *testing.T) { } } -func TestAGroupAPersonTookTheAccountOutOfSinceIsPutBackWhileDeclared(t *testing.T) { +func testAGroupAPersonTookTheAccountOutOfSinceIsPutBackWhileDeclared(t *testing.T) { g := newGroupDB(nil, "openrazer") _, state, err := applyGroupsOf(t, g, store.State{}, razer) if err != nil { @@ -231,3 +231,14 @@ func TestAGroupAPersonTookTheAccountOutOfSinceIsPutBackWhileDeclared(t *testing. t.Errorf("a declared group was not put back: %q", got) } } + +// TestGroups runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestGroups(t *testing.T) { + t.Run("AModulePutsTheAccountInAGroupAndSaysANewLoginIsNeeded", testAModulePutsTheAccountInAGroupAndSaysANewLoginIsNeeded) + t.Run("AGroupTheAccountWasAlreadyInIsNeverTakenBack", testAGroupTheAccountWasAlreadyInIsNeverTakenBack) + t.Run("TheGroupTheMeshAddedIsGivenBackWhenItsModuleGoes", testTheGroupTheMeshAddedIsGivenBackWhenItsModuleGoes) + t.Run("AGroupAnotherResourceStillAsksForStays", testAGroupAnotherResourceStillAsksForStays) + t.Run("AGroupNoLongerDeclaredIsGivenBackWhileTheAccountStaysDeclared", testAGroupNoLongerDeclaredIsGivenBackWhileTheAccountStaysDeclared) + t.Run("AGroupThatDoesNotExistYetFailsTheResourceSayingSo", testAGroupThatDoesNotExistYetFailsTheResourceSayingSo) + t.Run("AGroupAPersonTookTheAccountOutOfSinceIsPutBackWhileDeclared", testAGroupAPersonTookTheAccountOutOfSinceIsPutBackWhileDeclared) +} diff --git a/internal/apply/handover_test.go b/internal/apply/handover_test.go index 15e538f1..5d145554 100644 --- a/internal/apply/handover_test.go +++ b/internal/apply/handover_test.go @@ -100,7 +100,7 @@ func onAMachine(t *testing.T) { t.Cleanup(func() { unitDir, daemonRoot = wasUnits, wasBundles }) } -func TestAContainerAProcessReplacesGoesOnlyOnceTheProcessRuns(t *testing.T) { +func testAContainerAProcessReplacesGoesOnlyOnceTheProcessRuns(t *testing.T) { onAMachine(t) body, digest := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"}) known, raw := theController(t, digest, serving(t, body), `,"replaces":["mesh-controller.server"]`) @@ -135,7 +135,7 @@ func TestAContainerAProcessReplacesGoesOnlyOnceTheProcessRuns(t *testing.T) { // The case the handover exists for: the replacement does not stay up. The container keeps // answering, stays recorded so a later apply hands it over, and the apply says why it failed. -func TestAContainerIsKeptWhenItsReplacementDoesNotRun(t *testing.T) { +func testAContainerIsKeptWhenItsReplacementDoesNotRun(t *testing.T) { onAMachine(t) body, digest := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"}) known, raw := theController(t, digest, serving(t, body), `,"replaces":["mesh-controller.server"]`) @@ -176,7 +176,7 @@ func TestAContainerIsKeptWhenItsReplacementDoesNotRun(t *testing.T) { // A replacement that never applied — its bundle is not what was declared — touches nothing, and // what it replaces keeps running. -func TestAContainerIsKeptWhenItsReplacementFailsToApply(t *testing.T) { +func testAContainerIsKeptWhenItsReplacementFailsToApply(t *testing.T) { onAMachine(t) body, _ := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"}) known, raw := theController(t, "sha256:"+strings.Repeat("b", 64), serving(t, body), @@ -201,7 +201,7 @@ func TestAContainerIsKeptWhenItsReplacementFailsToApply(t *testing.T) { // Without `replaces` nothing changes: an orphan goes before anything is applied, as it always has. // Kept as a test because it is the window the field exists to close. -func TestWithoutReplacesAnOrphanStillGoesFirst(t *testing.T) { +func testWithoutReplacesAnOrphanStillGoesFirst(t *testing.T) { onAMachine(t) body, digest := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"}) known, raw := theController(t, digest, serving(t, body), ``) @@ -218,7 +218,7 @@ func TestWithoutReplacesAnOrphanStillGoesFirst(t *testing.T) { // novox/hq issue 213, beyond what the oneshot unit (process_step_test.go) already holds: a step // written `./name` runs its own bundle's binary — the controller's preparation is its own binary — // and a step is started, never enabled. -func TestAStepRunsItsOwnBundlesBinaryAndIsNotEnabled(t *testing.T) { +func testAStepRunsItsOwnBundlesBinaryAndIsNotEnabled(t *testing.T) { onAMachine(t) body, digest := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"}) m := &aMachine{running: true} @@ -242,7 +242,7 @@ func TestAStepRunsItsOwnBundlesBinaryAndIsNotEnabled(t *testing.T) { } } -func TestAStepThatFailsGatesItsModule(t *testing.T) { +func testAStepThatFailsGatesItsModule(t *testing.T) { onAMachine(t) body, digest := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"}) src := serving(t, body) @@ -272,7 +272,7 @@ func TestAStepThatFailsGatesItsModule(t *testing.T) { // A completed step is done: applied again unchanged, it is not run again — its service is never up // between runs, and reading that as "a daemon that stopped" re-ran the controller's preparation on // every apply. Nor is a scheduled run started off its cadence; its timer is what is kept up. -func TestACompletedStepIsNotRunAgainAndAScheduleIsItsTimer(t *testing.T) { +func testACompletedStepIsNotRunAgainAndAScheduleIsItsTimer(t *testing.T) { onAMachine(t) body, digest := anArchive(t, map[string]string{"job": "#!/bin/sh\n"}) src := serving(t, body) @@ -302,7 +302,7 @@ func TestACompletedStepIsNotRunAgainAndAScheduleIsItsTimer(t *testing.T) { // A replacement crash-looping between its restarts is not up, though the service manager calls it // "activating" — the state the host's ordinary second look accepts as running. Removing the // container on that reading would leave nothing answering. -func TestAContainerIsKeptWhenItsReplacementIsCrashLooping(t *testing.T) { +func testAContainerIsKeptWhenItsReplacementIsCrashLooping(t *testing.T) { onAMachine(t) body, digest := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"}) known, raw := theController(t, digest, serving(t, body), `,"replaces":["mesh-controller.server"]`) @@ -319,3 +319,15 @@ func TestAContainerIsKeptWhenItsReplacementIsCrashLooping(t *testing.T) { t.Fatal("the container was forgotten") } } + +// TestHandover runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestHandover(t *testing.T) { + t.Run("AContainerAProcessReplacesGoesOnlyOnceTheProcessRuns", testAContainerAProcessReplacesGoesOnlyOnceTheProcessRuns) + t.Run("AContainerIsKeptWhenItsReplacementDoesNotRun", testAContainerIsKeptWhenItsReplacementDoesNotRun) + t.Run("AContainerIsKeptWhenItsReplacementFailsToApply", testAContainerIsKeptWhenItsReplacementFailsToApply) + t.Run("WithoutReplacesAnOrphanStillGoesFirst", testWithoutReplacesAnOrphanStillGoesFirst) + t.Run("AStepRunsItsOwnBundlesBinaryAndIsNotEnabled", testAStepRunsItsOwnBundlesBinaryAndIsNotEnabled) + t.Run("AStepThatFailsGatesItsModule", testAStepThatFailsGatesItsModule) + t.Run("ACompletedStepIsNotRunAgainAndAScheduleIsItsTimer", testACompletedStepIsNotRunAgainAndAScheduleIsItsTimer) + t.Run("AContainerIsKeptWhenItsReplacementIsCrashLooping", testAContainerIsKeptWhenItsReplacementIsCrashLooping) +} diff --git a/internal/apply/home_links_test.go b/internal/apply/home_links_test.go index aad8d102..954762b2 100644 --- a/internal/apply/home_links_test.go +++ b/internal/apply/home_links_test.go @@ -72,7 +72,7 @@ func modeOfPath(t *testing.T, p string) os.FileMode { return info.Mode().Perm() } -func TestADirectoryUnderAHomeThatIsALinkIsRefusedAndItsTargetUntouched(t *testing.T) { +func testADirectoryUnderAHomeThatIsALinkIsRefusedAndItsTargetUntouched(t *testing.T) { home, outside := aLinkedHome(t) link(t, outside, filepath.Join(home, ".claude")) err := applyOneResource(t, `{"id":"claude-code.agent-home","type":"directory","path":"`+ @@ -83,7 +83,7 @@ func TestADirectoryUnderAHomeThatIsALinkIsRefusedAndItsTargetUntouched(t *testin } } -func TestAFileThroughALinkedParentUnderAHomeIsRefused(t *testing.T) { +func testAFileThroughALinkedParentUnderAHomeIsRefused(t *testing.T) { home, outside := aLinkedHome(t) link(t, outside, filepath.Join(home, ".claude")) err := applyOneResource(t, `{"id":"m.f","type":"file","path":"`+filepath.Join(home, ".claude", "shadow")+ @@ -97,7 +97,7 @@ func TestAFileThroughALinkedParentUnderAHomeIsRefused(t *testing.T) { } } -func TestAFileThatIsItselfALinkUnderAHomeIsRefused(t *testing.T) { +func testAFileThatIsItselfALinkUnderAHomeIsRefused(t *testing.T) { home, outside := aLinkedHome(t) link(t, filepath.Join(outside, "shadow"), filepath.Join(home, ".zshrc")) err := applyOneResource(t, `{"id":"m.f","type":"file","path":"`+filepath.Join(home, ".zshrc")+ @@ -108,7 +108,7 @@ func TestAFileThatIsItselfALinkUnderAHomeIsRefused(t *testing.T) { } } -func TestADirectoryAndAFileUnderAHomeAreMadeAsBefore(t *testing.T) { +func testADirectoryAndAFileUnderAHomeAreMadeAsBefore(t *testing.T) { home, _ := aLinkedHome(t) dir := filepath.Join(home, ".claude") if err := applyOneResource(t, `{"id":"m.d","type":"directory","path":"`+dir+`","mode":"0700"}`); err != nil { @@ -127,7 +127,7 @@ func TestADirectoryAndAFileUnderAHomeAreMadeAsBefore(t *testing.T) { } // The descriptor half: a link put in place after any check is still not followed. -func TestTheDescriptorCallsFollowNoLinkBelowAHome(t *testing.T) { +func testTheDescriptorCallsFollowNoLinkBelowAHome(t *testing.T) { home, outside := aLinkedHome(t) link(t, outside, filepath.Join(home, ".claude")) mustBeLinkRefusal(t, chmodPath(filepath.Join(home, ".claude"), 0o777)) @@ -155,7 +155,7 @@ func TestTheDescriptorCallsFollowNoLinkBelowAHome(t *testing.T) { } } -func TestRemovalThroughALinkUnderAHomeIsRefused(t *testing.T) { +func testRemovalThroughALinkUnderAHomeIsRefused(t *testing.T) { home, outside := aLinkedHome(t) link(t, outside, filepath.Join(home, ".claude")) _, _, err := remove(context.Background(), archHost(t), store.Applied{ID: "m.f", Type: "file", @@ -166,7 +166,7 @@ func TestRemovalThroughALinkUnderAHomeIsRefused(t *testing.T) { } } -func TestAPathOutsideEveryHomeIsHandledAsBefore(t *testing.T) { +func testAPathOutsideEveryHomeIsHandledAsBefore(t *testing.T) { _, outside := aLinkedHome(t) elsewhere := filepath.Join(filepath.Dir(outside), "srv") if err := os.MkdirAll(elsewhere, 0o755); err != nil { @@ -181,7 +181,7 @@ func TestAPathOutsideEveryHomeIsHandledAsBefore(t *testing.T) { } } -func TestHomesAreAPersonsOrAnAgentsNotAServicesOrRoots(t *testing.T) { +func testHomesAreAPersonsOrAnAgentsNotAServicesOrRoots(t *testing.T) { dir := t.TempDir() passwd := filepath.Join(dir, "passwd") if err := os.WriteFile(passwd, []byte("root:x:0:0::/root:/bin/bash\n"+ @@ -207,7 +207,7 @@ func TestHomesAreAPersonsOrAnAgentsNotAServicesOrRoots(t *testing.T) { // A hard link below a home to a file the home's account does not own is never owned, chmodded or read by // name: fstat on the opened descriptor counts its links first (the re-review of 2026-10-08). -func TestAHardLinkedFileBelowAHomeIsRefused(t *testing.T) { +func testAHardLinkedFileBelowAHomeIsRefused(t *testing.T) { home, outside := aLinkedHome(t) shadow := filepath.Join(outside, "shadow") linked := filepath.Join(home, ".claude") @@ -233,7 +233,7 @@ func TestAHardLinkedFileBelowAHomeIsRefused(t *testing.T) { } } -func TestADirectoryWhereAFileWasExpectedAndAFifoAreRefused(t *testing.T) { +func testADirectoryWhereAFileWasExpectedAndAFifoAreRefused(t *testing.T) { home, _ := aLinkedHome(t) dir := filepath.Join(home, "d") if err := os.Mkdir(dir, 0o755); err != nil { @@ -253,3 +253,17 @@ func TestADirectoryWhereAFileWasExpectedAndAFifoAreRefused(t *testing.T) { t.Fatalf("a directory as a directory passes: %v", err) } } + +// TestHomeLinks runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestHomeLinks(t *testing.T) { + t.Run("ADirectoryUnderAHomeThatIsALinkIsRefusedAndItsTargetUntouched", testADirectoryUnderAHomeThatIsALinkIsRefusedAndItsTargetUntouched) + t.Run("AFileThroughALinkedParentUnderAHomeIsRefused", testAFileThroughALinkedParentUnderAHomeIsRefused) + t.Run("AFileThatIsItselfALinkUnderAHomeIsRefused", testAFileThatIsItselfALinkUnderAHomeIsRefused) + t.Run("ADirectoryAndAFileUnderAHomeAreMadeAsBefore", testADirectoryAndAFileUnderAHomeAreMadeAsBefore) + t.Run("TheDescriptorCallsFollowNoLinkBelowAHome", testTheDescriptorCallsFollowNoLinkBelowAHome) + t.Run("RemovalThroughALinkUnderAHomeIsRefused", testRemovalThroughALinkUnderAHomeIsRefused) + t.Run("APathOutsideEveryHomeIsHandledAsBefore", testAPathOutsideEveryHomeIsHandledAsBefore) + t.Run("HomesAreAPersonsOrAnAgentsNotAServicesOrRoots", testHomesAreAPersonsOrAnAgentsNotAServicesOrRoots) + t.Run("AHardLinkedFileBelowAHomeIsRefused", testAHardLinkedFileBelowAHomeIsRefused) + t.Run("ADirectoryWhereAFileWasExpectedAndAFifoAreRefused", testADirectoryWhereAFileWasExpectedAndAFifoAreRefused) +} diff --git a/internal/apply/home_parents_test.go b/internal/apply/home_parents_test.go index 8970633c..d3a3b175 100644 --- a/internal/apply/home_parents_test.go +++ b/internal/apply/home_parents_test.go @@ -50,7 +50,7 @@ func givenPaths(given map[string]string) []string { return paths } -func TestAFileUnderAHomeGivesTheParentsItMadeToItsOwner(t *testing.T) { +func testAFileUnderAHomeGivesTheParentsItMadeToItsOwner(t *testing.T) { home, owner, given := aHome(t) target := filepath.Join(home, ".config", "mesh", "environment.sh") d := parse(t, `{"declaration":1,"resources":[{"id":"shell.env","type":"file","path":"`+target+ @@ -70,7 +70,7 @@ func TestAFileUnderAHomeGivesTheParentsItMadeToItsOwner(t *testing.T) { } } -func TestAnArchiveUnderAHomeGivesTheParentsItMadeToItsOwner(t *testing.T) { +func testAnArchiveUnderAHomeGivesTheParentsItMadeToItsOwner(t *testing.T) { home, owner, given := aHome(t) body, digest := anArchive(t, map[string]string{"p10k.zsh": "theme"}) target := filepath.Join(home, ".local", "share", "powerlevel10k") @@ -87,7 +87,7 @@ func TestAnArchiveUnderAHomeGivesTheParentsItMadeToItsOwner(t *testing.T) { } } -func TestAParentThatWasThereIsHeldAsFound(t *testing.T) { +func testAParentThatWasThereIsHeldAsFound(t *testing.T) { home, owner, given := aHome(t) config := filepath.Join(home, ".config") if err := os.Mkdir(config, 0o700); err != nil { @@ -111,7 +111,7 @@ func TestAParentThatWasThereIsHeldAsFound(t *testing.T) { } } -func TestAParentOutsideTheHomeIsMadeAsBefore(t *testing.T) { +func testAParentOutsideTheHomeIsMadeAsBefore(t *testing.T) { _, owner, given := aHome(t) target := filepath.Join(t.TempDir(), "var", "lib", "module", "settings.conf") d := parse(t, `{"declaration":1,"resources":[{"id":"module.conf","type":"file","path":"`+target+ @@ -124,3 +124,11 @@ func TestAParentOutsideTheHomeIsMadeAsBefore(t *testing.T) { t.Errorf("parents outside the owner's home were given to it: %v", givenPaths(given)) } } + +// TestHomeParents runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestHomeParents(t *testing.T) { + t.Run("AFileUnderAHomeGivesTheParentsItMadeToItsOwner", testAFileUnderAHomeGivesTheParentsItMadeToItsOwner) + t.Run("AnArchiveUnderAHomeGivesTheParentsItMadeToItsOwner", testAnArchiveUnderAHomeGivesTheParentsItMadeToItsOwner) + t.Run("AParentThatWasThereIsHeldAsFound", testAParentThatWasThereIsHeldAsFound) + t.Run("AParentOutsideTheHomeIsMadeAsBefore", testAParentOutsideTheHomeIsMadeAsBefore) +} diff --git a/internal/apply/identities_test.go b/internal/apply/identities_test.go index ffce9515..18e1f586 100644 --- a/internal/apply/identities_test.go +++ b/internal/apply/identities_test.go @@ -155,7 +155,7 @@ func withIdentities(t *testing.T, identities, resources string) *declaration.Dec // Row 3: the account made as a system account with exactly its numbers, recorded, and removed — only what was // made — when no longer declared. -func TestAModulesIdentityIsMadeWithItsNumbersAndRemovedWhenUndeclared(t *testing.T) { +func testAModulesIdentityIsMadeWithItsNumbersAndRemovedWhenUndeclared(t *testing.T) { m := &accountsMachine{users: map[string][2]int{}, groups: map[string][2]int{}} dir := t.TempDir() d := withIdentities(t, `{"module":"radarr","name":"mesh-radarr","uid":61001,"gid":61001}`, @@ -207,7 +207,7 @@ func TestAModulesIdentityIsMadeWithItsNumbersAndRemovedWhenUndeclared(t *testing // Row 3: a name that exists with other numbers, or numbers another name holds, is refused naming whose, and the // module is not attempted; the rest of the machine is. -func TestAnIdentityWhoseNameOrNumbersAreAnothersIsRefused(t *testing.T) { +func testAnIdentityWhoseNameOrNumbersAreAnothersIsRefused(t *testing.T) { dir := t.TempDir() for _, tc := range []struct { users, groups map[string][2]int @@ -240,7 +240,7 @@ func TestAnIdentityWhoseNameOrNumbersAreAnothersIsRefused(t *testing.T) { // Row 11: a declaration naming a root group for an account or an image is refused with its reason, and nothing is // made or started. A number 0 is refused on arrival, by the parser. -func TestNoModuleIdentityIsRoot(t *testing.T) { +func testNoModuleIdentityIsRoot(t *testing.T) { was := RootGroupIDs RootGroupIDs = func() map[int]string { return map[int]string{10: "wheel"} } defer func() { RootGroupIDs = was }() @@ -279,7 +279,7 @@ func TestNoModuleIdentityIsRoot(t *testing.T) { // Row 3: a container declaring identity is told it — by the variables its image reads, or the runtime's user // option — and a changed identity is a container recreated. -func TestAContainerIsToldItsModulesIdentity(t *testing.T) { +func testAContainerIsToldItsModulesIdentity(t *testing.T) { env := &declaration.Container{ID: "radarr.app", Name: "radarr", Image: pinned, RunAs: &declaration.ContainerIdentity{ Mode: declaration.IdentityByEnv, UserEnv: "PUID", GroupEnv: "PGID", UID: 61001, GID: 61001}} run := &declaration.Container{ID: "plex.app", Name: "plex", Image: pinned, RunAs: &declaration.ContainerIdentity{ @@ -303,7 +303,7 @@ func TestAContainerIsToldItsModulesIdentity(t *testing.T) { // ADR 0325 §5 supersedes ADR 0312's group grant: what a grant put an account in is taken back on the first apply of // the access, and nothing is granted again. -func TestWhatAGroupGrantPutAnAccountInIsTakenBack(t *testing.T) { +func testWhatAGroupGrantPutAnAccountInIsTakenBack(t *testing.T) { dir := t.TempDir() groups := "nox media" var ran []string @@ -336,7 +336,7 @@ func TestWhatAGroupGrantPutAnAccountInIsTakenBack(t *testing.T) { } // Review L7: a group the grant put an account in that could not be left stays recorded, and is tried again. -func TestAGrantsGroupThatCouldNotBeLeftIsTriedAgain(t *testing.T) { +func testAGrantsGroupThatCouldNotBeLeftIsTriedAgain(t *testing.T) { dir := t.TempDir() refuse := true groups := "nox media" @@ -372,7 +372,7 @@ func TestAGrantsGroupThatCouldNotBeLeftIsTriedAgain(t *testing.T) { } // Every system the engine runs on that makes accounts makes module identities: arch and alpine alike. -func TestArchAndAlpineMakeModuleIdentities(t *testing.T) { +func testArchAndAlpineMakeModuleIdentities(t *testing.T) { for _, name := range []string{"arch", "alpine"} { sys, err := system.For(name) if err != nil { @@ -383,3 +383,14 @@ func TestArchAndAlpineMakeModuleIdentities(t *testing.T) { } } } + +// TestIdentities runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestIdentities(t *testing.T) { + t.Run("AModulesIdentityIsMadeWithItsNumbersAndRemovedWhenUndeclared", testAModulesIdentityIsMadeWithItsNumbersAndRemovedWhenUndeclared) + t.Run("AnIdentityWhoseNameOrNumbersAreAnothersIsRefused", testAnIdentityWhoseNameOrNumbersAreAnothersIsRefused) + t.Run("NoModuleIdentityIsRoot", testNoModuleIdentityIsRoot) + t.Run("AContainerIsToldItsModulesIdentity", testAContainerIsToldItsModulesIdentity) + t.Run("WhatAGroupGrantPutAnAccountInIsTakenBack", testWhatAGroupGrantPutAnAccountInIsTakenBack) + t.Run("AGrantsGroupThatCouldNotBeLeftIsTriedAgain", testAGrantsGroupThatCouldNotBeLeftIsTriedAgain) + t.Run("ArchAndAlpineMakeModuleIdentities", testArchAndAlpineMakeModuleIdentities) +} diff --git a/internal/apply/inspect_scope_test.go b/internal/apply/inspect_scope_test.go index 3fdb0516..1596315c 100644 --- a/internal/apply/inspect_scope_test.go +++ b/internal/apply/inspect_scope_test.go @@ -39,7 +39,7 @@ func dockerLikeByKind(containers map[string]bool) func(context.Context, string, } } -func TestContainerStateAsksTheContainerNamespaceNotTheBareForm(t *testing.T) { +func testContainerStateAsksTheContainerNamespaceNotTheBareForm(t *testing.T) { // "minio" exists only as a network in this scenario — never in `containers` — matching the // live failure this guards: a module's network and its container share a name, and the // container does not exist yet. @@ -55,7 +55,7 @@ func TestContainerStateAsksTheContainerNamespaceNotTheBareForm(t *testing.T) { } } -func TestInspectFoundAsksTheContainerNamespaceNotTheBareForm(t *testing.T) { +func testInspectFoundAsksTheContainerNamespaceNotTheBareForm(t *testing.T) { run := dockerLikeByKind(map[string]bool{"keycloak": true}) if _, exists, err := inspectFound(context.Background(), "minio", run); err != nil || exists { @@ -65,3 +65,9 @@ func TestInspectFoundAsksTheContainerNamespaceNotTheBareForm(t *testing.T) { t.Fatalf("a container that does exist should be found: exists=%v err=%v", exists, err) } } + +// TestInspectScope runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestInspectScope(t *testing.T) { + t.Run("ContainerStateAsksTheContainerNamespaceNotTheBareForm", testContainerStateAsksTheContainerNamespaceNotTheBareForm) + t.Run("InspectFoundAsksTheContainerNamespaceNotTheBareForm", testInspectFoundAsksTheContainerNamespaceNotTheBareForm) +} diff --git a/internal/apply/into_handover_test.go b/internal/apply/into_handover_test.go index fc533904..775b3cf1 100644 --- a/internal/apply/into_handover_test.go +++ b/internal/apply/into_handover_test.go @@ -39,7 +39,7 @@ func runtimeDecl(t *testing.T, path string, network bool) *declaration.Declarati return parse(t, `{"declaration":1,"resources":[`+strings.Join(resources, ",")+`]}`) } -func TestTheRegistryMovesToTheRuntimesModuleWithoutLeavingTheList(t *testing.T) { +func testTheRegistryMovesToTheRuntimesModuleWithoutLeavingTheList(t *testing.T) { path := filepath.Join(t.TempDir(), "daemon.json") if err := os.WriteFile(path, []byte(`{"insecure-registries":["192.0.2.7:5000"]}`), 0o644); err != nil { t.Fatal(err) @@ -115,7 +115,7 @@ func TestTheRegistryMovesToTheRuntimesModuleWithoutLeavingTheList(t *testing.T) // A unit two records name, under opposite conditions, passes between them (design 42 zfs-owns-zfs §2, answer A-21): the // going record is forgotten, the preview says so before it happens, and what it found of the unit before the mesh is what // the staying record gives back when its module leaves, not what the mesh made of it. -func TestARecordOfAUnitStillHeldIsForgottenAndPassesWhatItFound(t *testing.T) { +func testARecordOfAUnitStillHeldIsForgottenAndPassesWhatItFound(t *testing.T) { t.Run("the preview forgets it", func(t *testing.T) { path := filepath.Join(t.TempDir(), "daemon.json") var commands []string @@ -186,3 +186,9 @@ func TestARecordOfAUnitStillHeldIsForgottenAndPassesWhatItFound(t *testing.T) { } }) } + +// TestIntoHandover runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestIntoHandover(t *testing.T) { + t.Run("TheRegistryMovesToTheRuntimesModuleWithoutLeavingTheList", testTheRegistryMovesToTheRuntimesModuleWithoutLeavingTheList) + t.Run("ARecordOfAUnitStillHeldIsForgottenAndPassesWhatItFound", testARecordOfAUnitStillHeldIsForgottenAndPassesWhatItFound) +} diff --git a/internal/apply/into_test.go b/internal/apply/into_test.go index 536ab6d0..71dcb1c5 100644 --- a/internal/apply/into_test.go +++ b/internal/apply/into_test.go @@ -39,7 +39,7 @@ func readObject(t *testing.T, path string) map[string]any { // The machine's own runtime settings, the way a predecessor leaves them. const machinesOwn = `{"data-root":"/srv/docker","log-opts":{"max-size":"10m"},"insecure-registries":["192.0.2.7:5000"]}` -func TestWritingIntoKeepsEveryKeyTheMachineHad(t *testing.T) { +func testWritingIntoKeepsEveryKeyTheMachineHad(t *testing.T) { path := filepath.Join(t.TempDir(), "daemon.json") if err := os.WriteFile(path, []byte(machinesOwn), 0o600); err != nil { t.Fatal(err) @@ -90,7 +90,7 @@ func TestWritingIntoKeepsEveryKeyTheMachineHad(t *testing.T) { } } -func TestAFileWrittenIntoThatWasNotThereIsRemovedWhenOnlyTheMeshsKeysAreLeft(t *testing.T) { +func testAFileWrittenIntoThatWasNotThereIsRemovedWhenOnlyTheMeshsKeysAreLeft(t *testing.T) { path := filepath.Join(t.TempDir(), "daemon.json") d := parse(t, intoDecl(t, path, `{"insecure-registries":["10.42.0.1:5000"]}`)) report, state, err := Apply(context.Background(), archHost(t), d, store.State{}, store.OriginDeclared, nil, nil, nil) @@ -130,7 +130,7 @@ func TestAFileWrittenIntoThatWasNotThereIsRemovedWhenOnlyTheMeshsKeysAreLeft(t * } } -func TestAKeyNoLongerDeclaredGoesBackAndANewOneIsRemembered(t *testing.T) { +func testAKeyNoLongerDeclaredGoesBackAndANewOneIsRemembered(t *testing.T) { path := filepath.Join(t.TempDir(), "daemon.json") _ = os.WriteFile(path, []byte(machinesOwn), 0o644) first := parse(t, intoDecl(t, path, `{"insecure-registries":["10.42.0.1:5000"]}`)) @@ -151,7 +151,7 @@ func TestAKeyNoLongerDeclaredGoesBackAndANewOneIsRemembered(t *testing.T) { } } -func TestAFileThatIsNotAnObjectIsRefusedAndLeftAlone(t *testing.T) { +func testAFileThatIsNotAnObjectIsRefusedAndLeftAlone(t *testing.T) { path := filepath.Join(t.TempDir(), "daemon.json") _ = os.WriteFile(path, []byte("# not json at all\n"), 0o644) d := parse(t, intoDecl(t, path, `{"insecure-registries":["10.42.0.1:5000"]}`)) @@ -164,7 +164,7 @@ func TestAFileThatIsNotAnObjectIsRefusedAndLeftAlone(t *testing.T) { } } -func TestAFileWrittenIntoIsNeverHeldOnAnAdoptedNode(t *testing.T) { +func testAFileWrittenIntoIsNeverHeldOnAnAdoptedNode(t *testing.T) { path := filepath.Join(t.TempDir(), "daemon.json") _ = os.WriteFile(path, []byte(machinesOwn), 0o644) d := adopted(t, `{"taken":[],"untaken":{"networking":["networking.registry-trust"]}}`, @@ -184,7 +184,7 @@ func TestAFileWrittenIntoIsNeverHeldOnAnAdoptedNode(t *testing.T) { } } -func TestAServiceIsReloadedNotRestartedForWhatItReloadsOn(t *testing.T) { +func testAServiceIsReloadedNotRestartedForWhatItReloadsOn(t *testing.T) { path := filepath.Join(t.TempDir(), "daemon.json") d := parse(t, fmt.Sprintf(`{"declaration":1,"resources":[ {"id":"trust","type":"file","path":%q,"into":"json","content":%q}, @@ -212,7 +212,7 @@ func somethingElse(t *testing.T) *declaration.Declaration { ]}`, filepath.Join(t.TempDir(), "other"))) } -func TestAListIsAddedToNeverReplaced(t *testing.T) { +func testAListIsAddedToNeverReplaced(t *testing.T) { // The predecessor's own trusted registries are kept; the mesh adds its own and, undeclared, // takes back only what it added (novox/hq ADR 0102). path := filepath.Join(t.TempDir(), "daemon.json") @@ -272,7 +272,7 @@ func TestAListIsAddedToNeverReplaced(t *testing.T) { } } -func TestAListTheMeshCreatedGoesWhenEmptied(t *testing.T) { +func testAListTheMeshCreatedGoesWhenEmptied(t *testing.T) { path := filepath.Join(t.TempDir(), "daemon.json") _ = os.WriteFile(path, []byte(`{"data-root":"/srv/docker"}`), 0o644) d := parse(t, intoDecl(t, path, `{"insecure-registries":["10.42.0.1:5000"]}`)) @@ -288,7 +288,7 @@ func TestAListTheMeshCreatedGoesWhenEmptied(t *testing.T) { } } -func TestAHoldFromAWholeFileDoesNotKeepOutAnIntoWrite(t *testing.T) { +func testAHoldFromAWholeFileDoesNotKeepOutAnIntoWrite(t *testing.T) { // Declared whole before, the runtime's file was held; declared into now, it is written into. path := filepath.Join(t.TempDir(), "daemon.json") _ = os.WriteFile(path, []byte(machinesOwn), 0o644) @@ -309,7 +309,7 @@ func TestAHoldFromAWholeFileDoesNotKeepOutAnIntoWrite(t *testing.T) { } } -func TestAWriteWithNoRecordOfItIsTheMeshsOwn(t *testing.T) { +func testAWriteWithNoRecordOfItIsTheMeshsOwn(t *testing.T) { // A host that wrote into the file and died before saving its state comes back with no record // of it. What is there is then exactly what the mesh declares — and remembered as the // machine's it would never be given back (novox/hq ADR 0102). @@ -340,3 +340,17 @@ func TestAWriteWithNoRecordOfItIsTheMeshsOwn(t *testing.T) { t.Errorf("the machine did not get its file back: %v", o) } } + +// TestInto runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestInto(t *testing.T) { + t.Run("WritingIntoKeepsEveryKeyTheMachineHad", testWritingIntoKeepsEveryKeyTheMachineHad) + t.Run("AFileWrittenIntoThatWasNotThereIsRemovedWhenOnlyTheMeshsKeysAreLeft", testAFileWrittenIntoThatWasNotThereIsRemovedWhenOnlyTheMeshsKeysAreLeft) + t.Run("AKeyNoLongerDeclaredGoesBackAndANewOneIsRemembered", testAKeyNoLongerDeclaredGoesBackAndANewOneIsRemembered) + t.Run("AFileThatIsNotAnObjectIsRefusedAndLeftAlone", testAFileThatIsNotAnObjectIsRefusedAndLeftAlone) + t.Run("AFileWrittenIntoIsNeverHeldOnAnAdoptedNode", testAFileWrittenIntoIsNeverHeldOnAnAdoptedNode) + t.Run("AServiceIsReloadedNotRestartedForWhatItReloadsOn", testAServiceIsReloadedNotRestartedForWhatItReloadsOn) + t.Run("AListIsAddedToNeverReplaced", testAListIsAddedToNeverReplaced) + t.Run("AListTheMeshCreatedGoesWhenEmptied", testAListTheMeshCreatedGoesWhenEmptied) + t.Run("AHoldFromAWholeFileDoesNotKeepOutAnIntoWrite", testAHoldFromAWholeFileDoesNotKeepOutAnIntoWrite) + t.Run("AWriteWithNoRecordOfItIsTheMeshsOwn", testAWriteWithNoRecordOfItIsTheMeshsOwn) +} diff --git a/internal/apply/judge_directories_test.go b/internal/apply/judge_directories_test.go index 8b11e7ee..832d1a1b 100644 --- a/internal/apply/judge_directories_test.go +++ b/internal/apply/judge_directories_test.go @@ -14,7 +14,7 @@ import ( // changed. Who could replace the link is "every account", "the account X" or "the group X", by the account and the // directories the test runs as: the checker's isolated step runs as the account nobody, which owns / there (issue 1919, // R4g), so the test demands a who in any of the forms couldReplace and linkReplacer produce, not "every account" alone. -func TestJudgeDirectoriesSaysWhatTheWalkWouldRefuseAndChangesNothing(t *testing.T) { +func testJudgeDirectoriesSaysWhatTheWalkWouldRefuseAndChangesNothing(t *testing.T) { base := t.TempDir() plain := filepath.Join(base, "plain") if err := os.Mkdir(plain, 0o755); err != nil { @@ -56,7 +56,7 @@ func TestJudgeDirectoriesSaysWhatTheWalkWouldRefuseAndChangesNothing(t *testing. } // A link only root could have made is followed by the judgement as by the apply. -func TestJudgeDirectoriesFollowsARootOnlyLink(t *testing.T) { +func testJudgeDirectoriesFollowsARootOnlyLink(t *testing.T) { wasDirs, wasLinks := couldReplace, linkReplacer couldReplace = func(string, uint32, uint32, uint32) string { return "" } linkReplacer = func(string, uint32) string { return "" } @@ -73,3 +73,9 @@ func TestJudgeDirectoriesFollowsARootOnlyLink(t *testing.T) { t.Fatalf("a directory behind a root-only link is not said placed: %q", said) } } + +// TestJudgeDirectories runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestJudgeDirectories(t *testing.T) { + t.Run("JudgeDirectoriesSaysWhatTheWalkWouldRefuseAndChangesNothing", testJudgeDirectoriesSaysWhatTheWalkWouldRefuseAndChangesNothing) + t.Run("JudgeDirectoriesFollowsARootOnlyLink", testJudgeDirectoriesFollowsARootOnlyLink) +} diff --git a/internal/apply/library_test.go b/internal/apply/library_test.go index 73fa1666..a607abff 100644 --- a/internal/apply/library_test.go +++ b/internal/apply/library_test.go @@ -137,7 +137,7 @@ func statOf(t *testing.T, path string) unix.Stat_t { // Row 6: the root and every requested sub-path kept in the library's group with group rwx and setgid on every apply — // those folders alone, never what is in them; owner, owner's and others' bits unchanged. -func TestALibraryIsKeptInItsGroup(t *testing.T) { +func testALibraryIsKeptInItsGroup(t *testing.T) { gid := testGID(t) canSetGroups(t, gid) libraries(t, nil, nil) @@ -187,7 +187,7 @@ func TestALibraryIsKeptInItsGroup(t *testing.T) { } // Row 9: a missing sub-path is made with the root's owner, the library's group, group rwx and setgid. -func TestAMissingSubPathIsMadeAsTheRootIs(t *testing.T) { +func testAMissingSubPathIsMadeAsTheRootIs(t *testing.T) { gid := testGID(t) canSetGroups(t, gid) libraries(t, nil, nil) @@ -216,7 +216,7 @@ func TestAMissingSubPathIsMadeAsTheRootIs(t *testing.T) { } // Row 7 (keep wait) and §8: a root that holds data not in the group waits with reason keep, and nothing is changed. -func TestARootThatHoldsDataWaitsForTheOperatorsWord(t *testing.T) { +func testARootThatHoldsDataWaitsForTheOperatorsWord(t *testing.T) { gid := testGID(t) libraries(t, nil, nil) root := filepath.Join(t.TempDir(), "media") @@ -244,7 +244,7 @@ func TestARootThatHoldsDataWaitsForTheOperatorsWord(t *testing.T) { // Row 7, the act: group, group write and setgid set under the root; no link followed; no other filesystem entered; // a file with another name elsewhere left; owner, owner's and others' bits unchanged; nothing without a warrant // (the act's ask, internal/link); an undeclared library refused; a walk over its bound goes on from its cursor. -func TestTheTakeActSetsTheGroupUnderTheRoot(t *testing.T) { +func testTheTakeActSetsTheGroupUnderTheRoot(t *testing.T) { gid := testGID(t) canSetGroups(t, gid) libraries(t, nil, nil) @@ -330,7 +330,7 @@ func TestTheTakeActSetsTheGroupUnderTheRoot(t *testing.T) { } // Row 7, the act: another filesystem is not entered — a folder whose device is not the root's is passed by. -func TestTheTakeActEntersNoOtherFilesystem(t *testing.T) { +func testTheTakeActEntersNoOtherFilesystem(t *testing.T) { gid := testGID(t) root := t.TempDir() mount := filepath.Join(root, "elsewhere") @@ -358,7 +358,7 @@ func TestTheTakeActEntersNoOtherFilesystem(t *testing.T) { // Row 9: a root that is absent, or whose disk is not mounted, makes nothing, holds the containers that mount it, // and waits with reason disk; off its home, a mount that is not there holds them too. -func TestALibraryWhoseDiskIsNotThereHoldsItsContainers(t *testing.T) { +func testALibraryWhoseDiskIsNotThereHoldsItsContainers(t *testing.T) { gid := testGID(t) base := t.TempDir() disk := filepath.Join(base, "disk") @@ -409,7 +409,7 @@ func TestALibraryWhoseDiskIsNotThereHoldsItsContainers(t *testing.T) { // Row 3: the library's group made with its number; a name or number that is another's refused; what was made, and // only that, removed when no longer declared. -func TestALibrarysGroupIsMadeWithItsNumber(t *testing.T) { +func testALibrarysGroupIsMadeWithItsNumber(t *testing.T) { m := &accountsMachine{users: map[string][2]int{}, groups: map[string][2]int{"media": {2000, 0}}} d := withGroups(t, `{"name":"mesh-media","gid":62000}`, ``, ``) report, known, err := Apply(context.Background(), archHost(t), d, store.State{}, store.OriginDeclared, m.run, nil, nil) @@ -442,7 +442,7 @@ func TestALibrarysGroupIsMadeWithItsNumber(t *testing.T) { // Row 4: a module's user with its own group (its uid's number), its first library's group as primary and its other // libraries' as added groups. -func TestAModulesUserIsInItsLibrariesGroups(t *testing.T) { +func testAModulesUserIsInItsLibrariesGroups(t *testing.T) { m := &accountsMachine{users: map[string][2]int{}, groups: map[string][2]int{}} d := withGroups(t, `{"name":"mesh-media","gid":62000},{"name":"mesh-books","gid":62001}`, `{"module":"radarr","name":"mesh-radarr","uid":61001,"gid":62000,"groups":[62001]}`, ``) @@ -466,7 +466,7 @@ func TestAModulesUserIsInItsLibrariesGroups(t *testing.T) { // Row 11: the tool runner's account is put in each library's group once, its unit restarted for it (a change of // library:), and taken out once no library puts it there. -func TestTheToolRunnerIsInItsLibrariesGroups(t *testing.T) { +func testTheToolRunnerIsInItsLibrariesGroups(t *testing.T) { gid := testGID(t) libraries(t, []string{"/srv/media"}, nil) m := &accountsMachine{users: map[string][2]int{"nox": {1003, 1003}}, groups: map[string][2]int{"nox": {1003, 0}}} @@ -501,7 +501,7 @@ func TestTheToolRunnerIsInItsLibrariesGroups(t *testing.T) { // Row 15: a library group, an identity's added group or an image told a root group's number is refused with its // reason, and nothing is made or started. -func TestNoLibraryGroupIsRoot(t *testing.T) { +func testNoLibraryGroupIsRoot(t *testing.T) { was := RootGroupIDs RootGroupIDs = func() map[int]string { return map[int]string{10: "wheel"} } defer func() { RootGroupIDs = was }() @@ -531,7 +531,7 @@ func TestNoLibraryGroupIsRoot(t *testing.T) { } // A library's filesystem that cannot be named this time is unknown, never a move; another filesystem at the root is. -func TestALibraryNotNamedIsUnknownAndAnotherFilesystemIsAMove(t *testing.T) { +func testALibraryNotNamedIsUnknownAndAnotherFilesystemIsAMove(t *testing.T) { gid := testGID(t) canSetGroups(t, gid) base := t.TempDir() @@ -589,7 +589,7 @@ func TestALibraryNotNamedIsUnknownAndAnotherFilesystemIsAMove(t *testing.T) { // Old-shape parity: a controller older than ADR 0328 sends no groups, identities or libraries, and an access is // applied exactly as before ADR 0325 — mounted when present, refused when absent, nothing kept, made or held. -func TestAnOlderControllersDeclarationIsAppliedAsBefore(t *testing.T) { +func testAnOlderControllersDeclarationIsAppliedAsBefore(t *testing.T) { libraries(t, nil, nil) dir := t.TempDir() present := filepath.Join(dir, "library") @@ -628,7 +628,7 @@ func jsonInto(raw string, into any) error { return json.Unmarshal([]byte(raw), i // Row 4: a module that joins a library later is given its group as primary on the account the mesh made; an account // the mesh did not make is never changed, and is refused if it is not as declared. -func TestAModuleThatJoinsALibraryLaterIsGivenItsGroup(t *testing.T) { +func testAModuleThatJoinsALibraryLaterIsGivenItsGroup(t *testing.T) { m := &accountsMachine{users: map[string][2]int{}, groups: map[string][2]int{}} own := withGroups(t, `{"name":"mesh-media","gid":62000}`, `{"module":"radarr","name":"mesh-radarr","uid":61001,"gid":61001}`, ``) @@ -654,7 +654,7 @@ func TestAModuleThatJoinsALibraryLaterIsGivenItsGroup(t *testing.T) { } // A library's root is never in the machine's own trees, as an access's never is (novox/hq issue 339). -func TestALibraryIsNeverTheMachinesOwnTree(t *testing.T) { +func testALibraryIsNeverTheMachinesOwnTree(t *testing.T) { gid := testGID(t) libraries(t, nil, nil) for _, root := range []string{"/etc", "/usr/share", "/var/lib/mesh-host/x"} { @@ -670,7 +670,7 @@ func TestALibraryIsNeverTheMachinesOwnTree(t *testing.T) { // §7: a root in shape with old data beneath it not in the group is asked about, never kept without a warrant; a root // and sample all in shape are kept; once taken, never asked again on that filesystem. -func TestARootInShapeWithDataBelowNotInTheGroupWaits(t *testing.T) { +func testARootInShapeWithDataBelowNotInTheGroupWaits(t *testing.T) { gid := testGID(t) canSetGroups(t, gid) libraries(t, nil, nil) @@ -720,7 +720,7 @@ func TestARootInShapeWithDataBelowNotInTheGroupWaits(t *testing.T) { // Review: a file with another name that root owns is left as it is (its other name may be anywhere), and a setgid // file never keeps its setgid bit once regrouped. -func TestRootsLinkedFilesAreLeftAndSetgidIsNeverKept(t *testing.T) { +func testRootsLinkedFilesAreLeftAndSetgidIsNeverKept(t *testing.T) { gid := testGID(t) canSetGroups(t, gid) f, err := os.CreateTemp(t.TempDir(), "file") @@ -751,7 +751,7 @@ func TestRootsLinkedFilesAreLeftAndSetgidIsNeverKept(t *testing.T) { // Review: a sub-path asked for after the library was kept without a warrant, which holds data not in the group, // waits for the operator's word as the root would, and nothing of it is changed; an empty one is kept. -func TestASubPathHoldingOldDataWaitsForTheOperatorsWord(t *testing.T) { +func testASubPathHoldingOldDataWaitsForTheOperatorsWord(t *testing.T) { gid := testGID(t) canSetGroups(t, gid) libraries(t, nil, nil) @@ -789,7 +789,7 @@ func TestASubPathHoldingOldDataWaitsForTheOperatorsWord(t *testing.T) { } // Review: an apply does not wait for a take walk that is running: it leaves the library to it. -func TestAnApplyDoesNotWaitForATakeWalk(t *testing.T) { +func testAnApplyDoesNotWaitForATakeWalk(t *testing.T) { gid := testGID(t) libraries(t, nil, nil) root := filepath.Join(t.TempDir(), "media") @@ -818,7 +818,7 @@ func TestAnApplyDoesNotWaitForATakeWalk(t *testing.T) { // Review: a root in shape whose data beneath — in no requested sub-path — is not in the group waits: the sample, not // the root alone, says whether the data is the library's already (§7). -func TestTheSampleBeneathARootInShapeIsJudged(t *testing.T) { +func testTheSampleBeneathARootInShapeIsJudged(t *testing.T) { gid := testGID(t) canSetGroups(t, gid) libraries(t, nil, nil) @@ -846,7 +846,7 @@ func TestTheSampleBeneathARootInShapeIsJudged(t *testing.T) { // Review: an apply that finds the library's lock held by something that is no take walk (a take act about to be // refused) waits for it and judges the library as always: a library whose disk is not there still holds. -func TestAnApplyWaitsForALockThatIsNoWalk(t *testing.T) { +func testAnApplyWaitsForALockThatIsNoWalk(t *testing.T) { gid := testGID(t) libraries(t, nil, nil) root := filepath.Join(t.TempDir(), "gone", "media") @@ -861,7 +861,7 @@ func TestAnApplyWaitsForALockThatIsNoWalk(t *testing.T) { // ADR 0334 §2: the tool runner's account joins a module's own group once, its unit restarted for it (a change of // identity:), and is taken out once no identity names it; an account not here, or root's, is refused. -func TestTheToolRunnerJoinsAModulesOwnGroup(t *testing.T) { +func testTheToolRunnerJoinsAModulesOwnGroup(t *testing.T) { m := &accountsMachine{users: map[string][2]int{"nox": {1003, 1003}}, groups: map[string][2]int{"nox": {1003, 0}}} d := withGroups(t, ``, `{"module":"radarr","name":"mesh-radarr","uid":61001,"gid":61001,"runner":"nox"}`, ``) report, known, err := Apply(context.Background(), archHost(t), d, store.State{}, store.OriginDeclared, m.run, nil, nil) @@ -918,7 +918,7 @@ func TestTheToolRunnerJoinsAModulesOwnGroup(t *testing.T) { // ADR 0334 §2: a service naming identity: under restart-on is restarted when the tool runner joins the // module's own group, and not on an apply where nothing moved. -func TestTheToolRunnerIsRestartedOnceForTheOwnGroup(t *testing.T) { +func testTheToolRunnerIsRestartedOnceForTheOwnGroup(t *testing.T) { m := &accountsMachine{users: map[string][2]int{"nox": {1003, 1003}}, groups: map[string][2]int{"nox": {1003, 0}}} d := withGroups(t, ``, `{"module":"radarr","name":"mesh-radarr","uid":61001,"gid":61001,"runner":"nox"}`, `{"id":"node-tools.unit","type":"service","unit":"node-tools.service","state":"running",`+ @@ -958,7 +958,7 @@ func TestTheToolRunnerIsRestartedOnceForTheOwnGroup(t *testing.T) { // Review: a library's runner that is refused keeps the library's outcome, is said as runner:library:, and never // fails the apply; a runner that leaves a group restarts the tool runner once, in the apply it leaves. -func TestARefusedLibraryRunnerIsAWarningAndLeavingRestarts(t *testing.T) { +func testARefusedLibraryRunnerIsAWarningAndLeavingRestarts(t *testing.T) { gid := testGID(t) libraries(t, []string{"/srv/media"}, nil) m := &accountsMachine{users: map[string][2]int{"nox": {1003, 1003}}, groups: map[string][2]int{"nox": {1003, 0}}} @@ -1011,7 +1011,7 @@ func TestARefusedLibraryRunnerIsAWarningAndLeavingRestarts(t *testing.T) { // ADR 0334 §1: a module's own directory may carry the setgid bit, so what is made beneath it keeps its own group; // it is set, held across applies, put back and said when it is taken off. Setuid and sticky are refused. -func TestADirectorysSetgidBitIsKept(t *testing.T) { +func testADirectorysSetgidBitIsKept(t *testing.T) { dir := filepath.Join(t.TempDir(), "state") d := declare(t, `{"id":"radarr.state","type":"directory","path":"`+dir+`","mode":"2750"}`) if _, _, err := Apply(context.Background(), archHost(t), d, store.State{}, store.OriginDeclared, noServices, nil, @@ -1048,3 +1048,31 @@ func TestADirectorysSetgidBitIsKept(t *testing.T) { } } } + +// TestLibrary runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestLibrary(t *testing.T) { + t.Run("ALibraryIsKeptInItsGroup", testALibraryIsKeptInItsGroup) + t.Run("AMissingSubPathIsMadeAsTheRootIs", testAMissingSubPathIsMadeAsTheRootIs) + t.Run("ARootThatHoldsDataWaitsForTheOperatorsWord", testARootThatHoldsDataWaitsForTheOperatorsWord) + t.Run("TheTakeActSetsTheGroupUnderTheRoot", testTheTakeActSetsTheGroupUnderTheRoot) + t.Run("TheTakeActEntersNoOtherFilesystem", testTheTakeActEntersNoOtherFilesystem) + t.Run("ALibraryWhoseDiskIsNotThereHoldsItsContainers", testALibraryWhoseDiskIsNotThereHoldsItsContainers) + t.Run("ALibrarysGroupIsMadeWithItsNumber", testALibrarysGroupIsMadeWithItsNumber) + t.Run("AModulesUserIsInItsLibrariesGroups", testAModulesUserIsInItsLibrariesGroups) + t.Run("TheToolRunnerIsInItsLibrariesGroups", testTheToolRunnerIsInItsLibrariesGroups) + t.Run("NoLibraryGroupIsRoot", testNoLibraryGroupIsRoot) + t.Run("ALibraryNotNamedIsUnknownAndAnotherFilesystemIsAMove", testALibraryNotNamedIsUnknownAndAnotherFilesystemIsAMove) + t.Run("AnOlderControllersDeclarationIsAppliedAsBefore", testAnOlderControllersDeclarationIsAppliedAsBefore) + t.Run("AModuleThatJoinsALibraryLaterIsGivenItsGroup", testAModuleThatJoinsALibraryLaterIsGivenItsGroup) + t.Run("ALibraryIsNeverTheMachinesOwnTree", testALibraryIsNeverTheMachinesOwnTree) + t.Run("ARootInShapeWithDataBelowNotInTheGroupWaits", testARootInShapeWithDataBelowNotInTheGroupWaits) + t.Run("RootsLinkedFilesAreLeftAndSetgidIsNeverKept", testRootsLinkedFilesAreLeftAndSetgidIsNeverKept) + t.Run("ASubPathHoldingOldDataWaitsForTheOperatorsWord", testASubPathHoldingOldDataWaitsForTheOperatorsWord) + t.Run("AnApplyDoesNotWaitForATakeWalk", testAnApplyDoesNotWaitForATakeWalk) + t.Run("TheSampleBeneathARootInShapeIsJudged", testTheSampleBeneathARootInShapeIsJudged) + t.Run("AnApplyWaitsForALockThatIsNoWalk", testAnApplyWaitsForALockThatIsNoWalk) + t.Run("TheToolRunnerJoinsAModulesOwnGroup", testTheToolRunnerJoinsAModulesOwnGroup) + t.Run("TheToolRunnerIsRestartedOnceForTheOwnGroup", testTheToolRunnerIsRestartedOnceForTheOwnGroup) + t.Run("ARefusedLibraryRunnerIsAWarningAndLeavingRestarts", testARefusedLibraryRunnerIsAWarningAndLeavingRestarts) + t.Run("ADirectorysSetgidBitIsKept", testADirectorysSetgidBitIsKept) +} diff --git a/internal/apply/maintenance_window_test.go b/internal/apply/maintenance_window_test.go index d25646b9..1d2ed66c 100644 --- a/internal/apply/maintenance_window_test.go +++ b/internal/apply/maintenance_window_test.go @@ -78,7 +78,7 @@ func fireOnce(t *testing.T, d *declaration.Declaration, w *windowRun) { s.Wait() } -func TestAScheduledStepHoldsItsModulesContainerStillAndStartsItAgain(t *testing.T) { +func testAScheduledStepHoldsItsModulesContainerStillAndStartsItAgain(t *testing.T) { w := &windowRun{} fireOnce(t, aStoreWithACollector(t), w) @@ -103,7 +103,7 @@ func TestAScheduledStepHoldsItsModulesContainerStillAndStartsItAgain(t *testing. } // The one that matters: a step that fails must leave the service running. -func TestAFailedStepStillClosesTheWindow(t *testing.T) { +func testAFailedStepStillClosesTheWindow(t *testing.T) { w := &windowRun{failAt: "run"} fireOnce(t, aStoreWithACollector(t), w) @@ -120,7 +120,7 @@ func TestAFailedStepStillClosesTheWindow(t *testing.T) { // A container that will not come back is said loudly: it is down, and nothing else notices until // the next apply compares it. -func TestAContainerThatWillNotStartAgainIsSaidLoudly(t *testing.T) { +func testAContainerThatWillNotStartAgainIsSaidLoudly(t *testing.T) { w := &windowRun{wontGo: "mesh-registry"} var said []string clock := &fixedClock{now: time.Date(2026, 10, 2, 3, 29, 0, 0, time.UTC)} @@ -142,7 +142,7 @@ func TestAContainerThatWillNotStartAgainIsSaidLoudly(t *testing.T) { // Several containers come back in the reverse of the order they were stopped: a module names the // dependant first, and starting it before what it depends on is not bringing it back. -func TestTheWindowClosesInTheReverseOfTheOrderItOpened(t *testing.T) { +func testTheWindowClosesInTheReverseOfTheOrderItOpened(t *testing.T) { d := parseTrusted(t, `{"declaration":1,"resources":[ {"id":"web","type":"container","name":"web","image":"`+pinned+`"}, {"id":"db","type":"container","name":"db","image":"`+pinned+`"}, @@ -170,7 +170,7 @@ func TestTheWindowClosesInTheReverseOfTheOrderItOpened(t *testing.T) { } // And the refusals, each for what it says rather than that it says something. -func TestAMaintenanceWindowIsRefusedWhereItCannotMean(t *testing.T) { +func testAMaintenanceWindowIsRefusedWhereItCannotMean(t *testing.T) { for _, c := range []struct{ name, body, says string }{ { "a window with no schedule", @@ -205,7 +205,7 @@ func TestAMaintenanceWindowIsRefusedWhereItCannotMean(t *testing.T) { // the install is reported updated and re-established" (containerSpec). Which containers are held // still for the run is the same kind of statement, and a declaration that changed it while the // machine reported no change would be a machine quietly running the old window. -func TestAChangedWindowMovesTheSpec(t *testing.T) { +func testAChangedWindowMovesTheSpec(t *testing.T) { one := parseTrusted(t, `{"declaration":1,"resources":[ {"id":"store","type":"container","name":"mesh-registry","image":"`+pinned+`"}, {"id":"other","type":"container","name":"other","image":"`+pinned+`"}, @@ -379,7 +379,7 @@ func openAWindow(t *testing.T, d *declaration.Declaration, m *aRegistryMachine, return s } -func TestAnApplyDuringAWindowLeavesWhatItHoldsAlone(t *testing.T) { +func testAnApplyDuringAWindowLeavesWhatItHoldsAlone(t *testing.T) { d := aStoreWithACollector(t) want := containerSpec(d.Resources[0].(*declaration.Container), inputs{}) m := newRegistryMachine(want) @@ -446,7 +446,7 @@ func TestAnApplyDuringAWindowLeavesWhatItHoldsAlone(t *testing.T) { // A step that fails releases its hold like one that succeeds: the record is erased in the same // defer that starts the server again, and an apply afterwards does what it always did — here, to a // registry that would not come back, the one thing that brings it back. -func TestAFailedStepReleasesItsHold(t *testing.T) { +func testAFailedStepReleasesItsHold(t *testing.T) { d := aStoreWithACollector(t) m := newRegistryMachine(containerSpec(d.Resources[0].(*declaration.Container), inputs{})) m.failRun, m.wontGo = true, true @@ -479,7 +479,7 @@ func TestAFailedStepReleasesItsHold(t *testing.T) { // A window whose host died mid-step — crashed, or stood aside for a successor — holds nothing: // the process that would start the server again is gone, so the apply must be free to. And a window // nothing closed ends on its own. -func TestAWindowNothingClosesDoesNotHoldForEver(t *testing.T) { +func testAWindowNothingClosesDoesNotHoldForEver(t *testing.T) { dir := t.TempDir() alive := true windows := &Windows{dir: dir, alive: func(int) bool { return alive }} @@ -514,7 +514,7 @@ func TestAWindowNothingClosesDoesNotHoldForEver(t *testing.T) { // A window that cannot be recorded is not opened: an apply would not know, and would recreate the // server under the step. One night's collection is the cheaper loss. -func TestAWindowThatCannotBeRecordedIsNotOpened(t *testing.T) { +func testAWindowThatCannotBeRecordedIsNotOpened(t *testing.T) { notADir := filepath.Join(t.TempDir(), "state") if err := os.WriteFile(notADir, nil, 0o600); err != nil { t.Fatal(err) @@ -541,3 +541,17 @@ func TestAWindowThatCannotBeRecordedIsNotOpened(t *testing.T) { t.Errorf("the step not running was not said: %v", said) } } + +// TestMaintenanceWindow runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestMaintenanceWindow(t *testing.T) { + t.Run("AScheduledStepHoldsItsModulesContainerStillAndStartsItAgain", testAScheduledStepHoldsItsModulesContainerStillAndStartsItAgain) + t.Run("AFailedStepStillClosesTheWindow", testAFailedStepStillClosesTheWindow) + t.Run("AContainerThatWillNotStartAgainIsSaidLoudly", testAContainerThatWillNotStartAgainIsSaidLoudly) + t.Run("TheWindowClosesInTheReverseOfTheOrderItOpened", testTheWindowClosesInTheReverseOfTheOrderItOpened) + t.Run("AMaintenanceWindowIsRefusedWhereItCannotMean", testAMaintenanceWindowIsRefusedWhereItCannotMean) + t.Run("AChangedWindowMovesTheSpec", testAChangedWindowMovesTheSpec) + t.Run("AnApplyDuringAWindowLeavesWhatItHoldsAlone", testAnApplyDuringAWindowLeavesWhatItHoldsAlone) + t.Run("AFailedStepReleasesItsHold", testAFailedStepReleasesItsHold) + t.Run("AWindowNothingClosesDoesNotHoldForEver", testAWindowNothingClosesDoesNotHoldForEver) + t.Run("AWindowThatCannotBeRecordedIsNotOpened", testAWindowThatCannotBeRecordedIsNotOpened) +} diff --git a/internal/apply/mesh_dirs_gate_test.go b/internal/apply/mesh_dirs_gate_test.go index dfb64de4..a228d0b2 100644 --- a/internal/apply/mesh_dirs_gate_test.go +++ b/internal/apply/mesh_dirs_gate_test.go @@ -60,7 +60,7 @@ func holdsTheGate(t *testing.T, target, other string, report Report, err error) } // The link there when the apply begins: refused by the guard before anything is applied. -func TestADirectoryBehindALinkGatesItsModuleThroughApply(t *testing.T) { +func testADirectoryBehindALinkGatesItsModuleThroughApply(t *testing.T) { target, other, decl := aLinkedModule(t) report, _, err := Apply(context.Background(), archHost(t), declare(t, decl), store.State{}, store.OriginDeclared, noServices, nil, nil) @@ -70,7 +70,7 @@ func TestADirectoryBehindALinkGatesItsModuleThroughApply(t *testing.T) { // The link found only at the moment of use: refused by the walk during the apply, and still a refusal that gates its // module and what is below it. Simulated by trusting / for the guard's walk (two walks of /: one to the link, one // from its target) and not for the apply's. -func TestADirectoryRefusedDuringTheApplyGatesItsModule(t *testing.T) { +func testADirectoryRefusedDuringTheApplyGatesItsModule(t *testing.T) { target, other, decl := aLinkedModule(t) wasDirs, wasLinks := couldReplace, linkReplacer walksOfRoot := 0 @@ -93,3 +93,9 @@ func TestADirectoryRefusedDuringTheApplyGatesItsModule(t *testing.T) { } holdsTheGate(t, target, other, report, err) } + +// TestMeshDirsGate runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestMeshDirsGate(t *testing.T) { + t.Run("ADirectoryBehindALinkGatesItsModuleThroughApply", testADirectoryBehindALinkGatesItsModuleThroughApply) + t.Run("ADirectoryRefusedDuringTheApplyGatesItsModule", testADirectoryRefusedDuringTheApplyGatesItsModule) +} diff --git a/internal/apply/mesh_dirs_test.go b/internal/apply/mesh_dirs_test.go index 53df207b..0cfdbfab 100644 --- a/internal/apply/mesh_dirs_test.go +++ b/internal/apply/mesh_dirs_test.go @@ -18,7 +18,7 @@ import ( // A link only root could have made — itself root's, in directories no other account may write — is followed, as // /var/run to /run is on every node; relative or absolute. -func TestALinkOnlyRootCouldMakeIsFollowed(t *testing.T) { +func testALinkOnlyRootCouldMakeIsFollowed(t *testing.T) { for name, to := range map[string]func(base string) string{ "absolute": func(base string) string { return filepath.Join(base, "elsewhere") }, "relative": func(string) string { return "elsewhere" }, @@ -43,7 +43,7 @@ func TestALinkOnlyRootCouldMakeIsFollowed(t *testing.T) { } // A link another account owns refuses the directory even in directories root alone may write, naming the account. -func TestALinkAnotherAccountOwnsIsRefused(t *testing.T) { +func testALinkAnotherAccountOwnsIsRefused(t *testing.T) { rootAlone(t, "the account mallory (it owns the link)") base, r, previous := aMeshDirectory(t) target := swapParentForLink(t, base, filepath.Join(base, "elsewhere")) @@ -58,7 +58,7 @@ func TestALinkAnotherAccountOwnsIsRefused(t *testing.T) { } // A directory that is missing is made through the walk, below a link root alone could make. -func TestAMissingDirectoryIsMadeBehindARootOnlyLink(t *testing.T) { +func testAMissingDirectoryIsMadeBehindARootOnlyLink(t *testing.T) { rootAlone(t, "") base := t.TempDir() if err := os.Mkdir(filepath.Join(base, "real"), 0o755); err != nil { @@ -89,3 +89,10 @@ func rootAlone(t *testing.T, linkOwner string) { linkReplacer = func(string, uint32) string { return linkOwner } t.Cleanup(func() { couldReplace, linkReplacer = wasDirs, wasLinks }) } + +// TestMeshDirs runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestMeshDirs(t *testing.T) { + t.Run("ALinkOnlyRootCouldMakeIsFollowed", testALinkOnlyRootCouldMakeIsFollowed) + t.Run("ALinkAnotherAccountOwnsIsRefused", testALinkAnotherAccountOwnsIsRefused) + t.Run("AMissingDirectoryIsMadeBehindARootOnlyLink", testAMissingDirectoryIsMadeBehindARootOnlyLink) +} diff --git a/internal/apply/mesh_tree_found_test.go b/internal/apply/mesh_tree_found_test.go index 134403a2..247d3ead 100644 --- a/internal/apply/mesh_tree_found_test.go +++ b/internal/apply/mesh_tree_found_test.go @@ -19,7 +19,7 @@ import ( // directory in a tree that is the engine's (0755, root); on ace and novox /var/lib/mesh/postgres was there as // root:root 0700 before postgres's data directory was applied, and the engine left it to root, so the postgres // provider, running as the operator's account, could not reach its own files. -func TestADirectoryInTheMeshsOwnTreeMadeByTheEngineIsTheMeshs(t *testing.T) { +func testADirectoryInTheMeshsOwnTreeMadeByTheEngineIsTheMeshs(t *testing.T) { root := t.TempDir() before := meshDataRoot meshDataRoot = filepath.Join(root, "mesh") @@ -95,7 +95,7 @@ func TestADirectoryInTheMeshsOwnTreeMadeByTheEngineIsTheMeshs(t *testing.T) { // Review of issue 1873's fix: the tree is judged by where the path leads, not by its text. A root-only link inside the // mesh's tree pointing out of it (to /var/lib/systemd, say) would otherwise make a directory outside the tree, owned by // the engine's account, the mesh's to chown: issue 1873's fault again. It is used as found. -func TestALinkInTheMeshsTreeLeadingOutOfItIsNotTheTree(t *testing.T) { +func testALinkInTheMeshsTreeLeadingOutOfItIsNotTheTree(t *testing.T) { rootAlone(t, "") root := t.TempDir() before := meshDataRoot @@ -126,3 +126,9 @@ func TestALinkInTheMeshsTreeLeadingOutOfItIsNotTheTree(t *testing.T) { t.Errorf("the directory outside the tree was given mode %o (was 700)", got) } } + +// TestMeshTreeFound runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestMeshTreeFound(t *testing.T) { + t.Run("ADirectoryInTheMeshsOwnTreeMadeByTheEngineIsTheMeshs", testADirectoryInTheMeshsOwnTreeMadeByTheEngineIsTheMeshs) + t.Run("ALinkInTheMeshsTreeLeadingOutOfItIsNotTheTree", testALinkInTheMeshsTreeLeadingOutOfItIsNotTheTree) +} diff --git a/internal/apply/module_results_test.go b/internal/apply/module_results_test.go index 79d4dfb9..deb04c37 100644 --- a/internal/apply/module_results_test.go +++ b/internal/apply/module_results_test.go @@ -23,7 +23,7 @@ func twoModules(t *testing.T) *declaration.Declaration { // 1132/AC3: every resource of module A applied and one of module B failed: A is a success, B failed with the failing // resource and its error named; a module gated by another's failure is failed too. -func TestAnApplyIsGroupedPerModule(t *testing.T) { +func testAnApplyIsGroupedPerModule(t *testing.T) { d := twoModules(t) done := Report{Outcomes: []Outcome{ {ID: "a.dir", Action: "created"}, @@ -51,7 +51,7 @@ func TestAnApplyIsGroupedPerModule(t *testing.T) { } // 1132/AC3: an apply that did not fail is a success for every module the declaration names. -func TestACleanApplyIsASuccessForEveryModule(t *testing.T) { +func testACleanApplyIsASuccessForEveryModule(t *testing.T) { got := ModuleResults(twoModules(t), Report{}, nil) for _, m := range []string{"a", "b", "c"} { if r, ok := got[m]; !ok || r.Failed { @@ -62,7 +62,7 @@ func TestACleanApplyIsASuccessForEveryModule(t *testing.T) { // 1132/AC3: a step that belongs to no module stops the apply there; a module with a resource not attempted is not a // success. -func TestAModuleNotAttemptedIsNotASuccess(t *testing.T) { +func testAModuleNotAttemptedIsNotASuccess(t *testing.T) { d := twoModules(t) err := &Error{Resource: "boot", Err: errors.New("boom"), Stopped: true, Failures: []Failure{{Resource: "boot", Err: errors.New("boom")}}, Done: Report{Outcomes: []Outcome{{ID: "a.dir", Action: "created"}}}} @@ -74,3 +74,10 @@ func TestAModuleNotAttemptedIsNotASuccess(t *testing.T) { t.Errorf("b was not attempted: %+v", got["b"]) } } + +// TestModuleResults runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestModuleResults(t *testing.T) { + t.Run("AnApplyIsGroupedPerModule", testAnApplyIsGroupedPerModule) + t.Run("ACleanApplyIsASuccessForEveryModule", testACleanApplyIsASuccessForEveryModule) + t.Run("AModuleNotAttemptedIsNotASuccess", testAModuleNotAttemptedIsNotASuccess) +} diff --git a/internal/apply/module_scope_test.go b/internal/apply/module_scope_test.go index 1bdb768f..ed22a339 100644 --- a/internal/apply/module_scope_test.go +++ b/internal/apply/module_scope_test.go @@ -12,7 +12,7 @@ import ( // R6-A AC3: given two modules declaring one path, when one module's want changes, the shared path is neither removed // nor taken from the other module (novox/hq ADR 0539 §9). -func TestASharedPathIsNeitherRemovedNorTakenFromTheOtherModule(t *testing.T) { +func testASharedPathIsNeitherRemovedNorTakenFromTheOtherModule(t *testing.T) { dir := t.TempDir() shared := filepath.Join(dir, "shared.conf") own := filepath.Join(dir, "a-own.conf") @@ -56,7 +56,7 @@ func TestASharedPathIsNeitherRemovedNorTakenFromTheOtherModule(t *testing.T) { // R6-A AC4: given modules A and B on a node, when A's want is removed, only A's resources are removed and B is // untouched. -func TestARemovedModuleTakesOnlyItsOwnResources(t *testing.T) { +func testARemovedModuleTakesOnlyItsOwnResources(t *testing.T) { dir := t.TempDir() fa, fb := filepath.Join(dir, "a.conf"), filepath.Join(dir, "b.conf") d := declare(t, `{"id":"a.conf","type":"file","path":"`+fa+`","content":"a\n","module":"a"}, @@ -91,7 +91,7 @@ func TestARemovedModuleTakesOnlyItsOwnResources(t *testing.T) { } // A record from before the owner was kept is read by its id, so the first removal after the switch is the module's too. -func TestARecordWithoutAnOwnerBelongsToTheModuleItsIdNames(t *testing.T) { +func testARecordWithoutAnOwnerBelongsToTheModuleItsIdNames(t *testing.T) { dir := t.TempDir() fa, fb := filepath.Join(dir, "a.conf"), filepath.Join(dir, "b.conf") d := declare(t, `{"id":"a.conf","type":"file","path":"`+fa+`","content":"a\n"}, @@ -123,7 +123,7 @@ func TestARecordWithoutAnOwnerBelongsToTheModuleItsIdNames(t *testing.T) { // says why (issue 774, live on 2026-10-29 at 07:54 UTC on the bus node: the node's own composition, composed without what // it ran once the kept declaration was read no more, removed the bus server, the proxy and three held modules). Only its // want's removal lets it go. -func TestAResourceThatMovedToItsModulesCompositionIsLeftByTheNodesOwnApply(t *testing.T) { +func testAResourceThatMovedToItsModulesCompositionIsLeftByTheNodesOwnApply(t *testing.T) { for _, tc := range []struct { name string id string // the resource the node's own composition carried, and no longer does @@ -222,3 +222,11 @@ func TestAResourceThatMovedToItsModulesCompositionIsLeftByTheNodesOwnApply(t *te } func state0() store.State { return store.State{} } + +// TestModuleScope runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestModuleScope(t *testing.T) { + t.Run("ASharedPathIsNeitherRemovedNorTakenFromTheOtherModule", testASharedPathIsNeitherRemovedNorTakenFromTheOtherModule) + t.Run("ARemovedModuleTakesOnlyItsOwnResources", testARemovedModuleTakesOnlyItsOwnResources) + t.Run("ARecordWithoutAnOwnerBelongsToTheModuleItsIdNames", testARecordWithoutAnOwnerBelongsToTheModuleItsIdNames) + t.Run("AResourceThatMovedToItsModulesCompositionIsLeftByTheNodesOwnApply", testAResourceThatMovedToItsModulesCompositionIsLeftByTheNodesOwnApply) +} diff --git a/internal/apply/mount_waits_test.go b/internal/apply/mount_waits_test.go index 5e2c33d6..ccd71aac 100644 --- a/internal/apply/mount_waits_test.go +++ b/internal/apply/mount_waits_test.go @@ -17,7 +17,7 @@ import ( // a directory, and every fill after it failed with "is a directory". A container whose mount source is a file the // declaration declares, not yet there, is not created or replaced: it waits, and the write of that file (WriteFilled) // applies what reads it, the container among them (readsChange), once the file is there. -func TestAContainerWaitsForAFileItMountsAndIsMadeWhenTheFillLands(t *testing.T) { +func testAContainerWaitsForAFileItMountsAndIsMadeWhenTheFillLands(t *testing.T) { secret := filepath.Join(t.TempDir(), "postgres", "superuser.secret") d := filledDecl(t, secret, `"content":"","mode":"0600","owner-at-runtime":"owned"`, `{"id":"postgres.server","type":"container","name":"postgres","image":"`+pinned+`","volumes":["`+ @@ -54,7 +54,7 @@ func TestAContainerWaitsForAFileItMountsAndIsMadeWhenTheFillLands(t *testing.T) // directory in the mesh's own tree, the engine's account's, is the runtime's missing mount source: the engine // removes that empty directory and writes the file, and says so. A directory with anything in it, or one outside the // tree, is never removed: the write fails as before. -func TestAnEmptyDirectoryTheRuntimeLeftAtAFilesPathIsReplacedByTheFile(t *testing.T) { +func testAnEmptyDirectoryTheRuntimeLeftAtAFilesPathIsReplacedByTheFile(t *testing.T) { rootAlone(t, "") root := t.TempDir() before := meshDataRoot @@ -119,3 +119,9 @@ func TestAnEmptyDirectoryTheRuntimeLeftAtAFilesPathIsReplacedByTheFile(t *testin t.Errorf("a directory outside the tree, reached through a link in it, was replaced: %v %v", info, err) } } + +// TestMountWaits runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestMountWaits(t *testing.T) { + t.Run("AContainerWaitsForAFileItMountsAndIsMadeWhenTheFillLands", testAContainerWaitsForAFileItMountsAndIsMadeWhenTheFillLands) + t.Run("AnEmptyDirectoryTheRuntimeLeftAtAFilesPathIsReplacedByTheFile", testAnEmptyDirectoryTheRuntimeLeftAtAFilesPathIsReplacedByTheFile) +} diff --git a/internal/apply/move_out_test.go b/internal/apply/move_out_test.go index 21567add..90063236 100644 --- a/internal/apply/move_out_test.go +++ b/internal/apply/move_out_test.go @@ -77,7 +77,7 @@ func readList(t *testing.T, path string) []movedEntry { return list } -func TestAMoveOutDirectoryMovesOnlyWhatIsNotKnown(t *testing.T) { +func testAMoveOutDirectoryMovesOnlyWhatIsNotKnown(t *testing.T) { home := aMoveOutHome(t) dir := filepath.Join(home, ".ssh") outside := filepath.Join(t.TempDir(), "target") @@ -162,7 +162,7 @@ func TestAMoveOutDirectoryMovesOnlyWhatIsNotKnown(t *testing.T) { } } -func TestAMoveOutListIsWrittenBeforeTheMove(t *testing.T) { +func testAMoveOutListIsWrittenBeforeTheMove(t *testing.T) { home := aMoveOutHome(t) dir := filepath.Join(home, "d") put(t, filepath.Join(dir, "a"), "a", time.Hour) @@ -195,7 +195,7 @@ func TestAMoveOutListIsWrittenBeforeTheMove(t *testing.T) { } } -func TestAMoveOutThatMovedNothingMakesNothing(t *testing.T) { +func testAMoveOutThatMovedNothingMakesNothing(t *testing.T) { home := aMoveOutHome(t) dir := filepath.Join(home, "d") put(t, filepath.Join(dir, "known"), "k", time.Hour) @@ -222,7 +222,7 @@ func TestAMoveOutThatMovedNothingMakesNothing(t *testing.T) { } } -func TestAMoveOutOfANestedStrayThatFailsLeavesNoKeptFolder(t *testing.T) { +func testAMoveOutOfANestedStrayThatFailsLeavesNoKeptFolder(t *testing.T) { home := aMoveOutHome(t) dir := filepath.Join(home, "d") put(t, filepath.Join(dir, "x", "f"), "declared", time.Hour) @@ -242,7 +242,7 @@ func TestAMoveOutOfANestedStrayThatFailsLeavesNoKeptFolder(t *testing.T) { } // A link swapped into a parent folder, on either side, between the look and the move, is not followed. -func TestAMoveOutDoesNotFollowALinkSwappedIntoAParent(t *testing.T) { +func testAMoveOutDoesNotFollowALinkSwappedIntoAParent(t *testing.T) { for _, side := range []string{"from", "to"} { t.Run(side, func(t *testing.T) { home := aMoveOutHome(t) @@ -286,7 +286,7 @@ func TestAMoveOutDoesNotFollowALinkSwappedIntoAParent(t *testing.T) { } } -func TestOtherUnknownValuesAndNoValueMoveNothing(t *testing.T) { +func testOtherUnknownValuesAndNoValueMoveNothing(t *testing.T) { home := aMoveOutHome(t) for _, v := range []string{`,"unknown":"program"`, `,"unknown":"module"`, ``} { dir := filepath.Join(home, "d") @@ -300,7 +300,7 @@ func TestOtherUnknownValuesAndNoValueMoveNothing(t *testing.T) { } } -func TestAMoveOutArchiveKeepsWhatItUnpackedAndMovesAStray(t *testing.T) { +func testAMoveOutArchiveKeepsWhatItUnpackedAndMovesAStray(t *testing.T) { home := aMoveOutHome(t) dir := filepath.Join(home, "theme") put(t, filepath.Join(dir, "stray"), "s", time.Hour) @@ -320,7 +320,7 @@ func TestAMoveOutArchiveKeepsWhatItUnpackedAndMovesAStray(t *testing.T) { } } -func TestMoveOutNeedsAHome(t *testing.T) { +func testMoveOutNeedsAHome(t *testing.T) { aMoveOutHome(t) dir := filepath.Join(t.TempDir(), "elsewhere") put(t, filepath.Join(dir, "stray"), "s", time.Hour) @@ -333,7 +333,7 @@ func TestMoveOutNeedsAHome(t *testing.T) { } } -func TestMoveOutRefusesAnotherFileSystem(t *testing.T) { +func testMoveOutRefusesAnotherFileSystem(t *testing.T) { home := aMoveOutHome(t) dir := filepath.Join(home, "d") put(t, filepath.Join(dir, "stray"), "s", time.Hour) @@ -353,3 +353,16 @@ func TestMoveOutRefusesAnotherFileSystem(t *testing.T) { t.Error("something moved or was made") } } + +// TestMoveOut runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestMoveOut(t *testing.T) { + t.Run("AMoveOutDirectoryMovesOnlyWhatIsNotKnown", testAMoveOutDirectoryMovesOnlyWhatIsNotKnown) + t.Run("AMoveOutListIsWrittenBeforeTheMove", testAMoveOutListIsWrittenBeforeTheMove) + t.Run("AMoveOutThatMovedNothingMakesNothing", testAMoveOutThatMovedNothingMakesNothing) + t.Run("AMoveOutOfANestedStrayThatFailsLeavesNoKeptFolder", testAMoveOutOfANestedStrayThatFailsLeavesNoKeptFolder) + t.Run("AMoveOutDoesNotFollowALinkSwappedIntoAParent", testAMoveOutDoesNotFollowALinkSwappedIntoAParent) + t.Run("OtherUnknownValuesAndNoValueMoveNothing", testOtherUnknownValuesAndNoValueMoveNothing) + t.Run("AMoveOutArchiveKeepsWhatItUnpackedAndMovesAStray", testAMoveOutArchiveKeepsWhatItUnpackedAndMovesAStray) + t.Run("MoveOutNeedsAHome", testMoveOutNeedsAHome) + t.Run("MoveOutRefusesAnotherFileSystem", testMoveOutRefusesAnotherFileSystem) +} diff --git a/internal/apply/opening_test.go b/internal/apply/opening_test.go index f632299b..1ca4ec61 100644 --- a/internal/apply/opening_test.go +++ b/internal/apply/opening_test.go @@ -119,7 +119,7 @@ func applyWith(t *testing.T, d *declaration.Declaration, known store.State, run KeepIn(t.TempDir())) } -func TestAnOpeningOnAMachineWithNoFirewallChangesNothing(t *testing.T) { +func testAnOpeningOnAMachineWithNoFirewallChangesNothing(t *testing.T) { dir := t.TempDir() u := &ufwMachine{} report, state, err := applyWith(t, adopted(t, `{"taken":[]}`, busOpening+","+withConf(dir)), store.State{}, u.run) @@ -135,7 +135,7 @@ func TestAnOpeningOnAMachineWithNoFirewallChangesNothing(t *testing.T) { } } -func TestAnUnsupportedFirewallRefusesTheWholeDeclaration(t *testing.T) { +func testAnUnsupportedFirewallRefusesTheWholeDeclaration(t *testing.T) { dir := t.TempDir() u := &ufwMachine{ruleset: "table inet filter {\n\tchain input {\n\t\ttype filter hook input priority filter; policy drop;\n\t}\n}\n"} _, state, err := applyWith(t, adopted(t, `{"taken":[]}`, busOpening+","+withConf(dir)), store.State{}, u.run) @@ -150,7 +150,7 @@ func TestAnUnsupportedFirewallRefusesTheWholeDeclaration(t *testing.T) { } } -func TestConvergingRetiresTheFoundFirewallAndReturningRestoresIt(t *testing.T) { +func testConvergingRetiresTheFoundFirewallAndReturningRestoresIt(t *testing.T) { dir := t.TempDir() u := &ufwMachine{installed: true, active: true, rules: []string{"allow 22/tcp"}} @@ -238,7 +238,7 @@ func TestConvergingRetiresTheFoundFirewallAndReturningRestoresIt(t *testing.T) { } } -func TestAConvergedNodeThatWasNeverAdoptedNeverAsksAboutAFirewall(t *testing.T) { +func testAConvergedNodeThatWasNeverAdoptedNeverAsksAboutAFirewall(t *testing.T) { dir := t.TempDir() u := &ufwMachine{installed: true, active: true} if _, _, err := applyWith(t, parse(t, `{"declaration":1,"resources":[`+withConf(dir)+`]}`), store.State{}, u.run); err != nil { @@ -249,13 +249,13 @@ func TestAConvergedNodeThatWasNeverAdoptedNeverAsksAboutAFirewall(t *testing.T) } } -func TestAnOpeningOnAConvergedNodeIsRefused(t *testing.T) { +func testAnOpeningOnAConvergedNodeIsRefused(t *testing.T) { if _, err := declaration.Parse([]byte(`{"declaration":1,"resources":[` + busOpening + `]}`)); err == nil { t.Error("an opening was accepted on a node the declaration does not say is adopted") } } -func TestACarriedApplyOnAnAdoptedNodeLeavesItsFirewallInForce(t *testing.T) { +func testACarriedApplyOnAnAdoptedNodeLeavesItsFirewallInForce(t *testing.T) { // The bundle, re-applied by the installer or the one-shot CLI, never says a node is adopted. // That is not the controller converging it, so ufw must stay enabled (novox/hq ADR 0100). dir := t.TempDir() @@ -277,7 +277,7 @@ func TestACarriedApplyOnAnAdoptedNodeLeavesItsFirewallInForce(t *testing.T) { } } -func TestAFlipThatFailsKeepsTheGuardAndTheOpenings(t *testing.T) { +func testAFlipThatFailsKeepsTheGuardAndTheOpenings(t *testing.T) { // Converging a node removes its openings and its guard only once everything else applied and // the found firewall is retired. A flip that fails part-way keeps them, so the store is never // left unguarded behind a filter that did not load (novox/hq ADR 0103). @@ -339,7 +339,7 @@ func TestAFlipThatFailsKeepsTheGuardAndTheOpenings(t *testing.T) { } } -func TestAnOpeningAFoundRuleAnswersIsReportedSatisfied(t *testing.T) { +func testAnOpeningAFoundRuleAnswersIsReportedSatisfied(t *testing.T) { // novox/hq ADR 0103: the mesh adds nothing beside a rule ufw would take for the same one. dir := t.TempDir() u := &ufwMachine{installed: true, active: true, rules: []string{"allow 22/tcp", "allow 5671/tcp"}} @@ -358,7 +358,7 @@ func TestAnOpeningAFoundRuleAnswersIsReportedSatisfied(t *testing.T) { // Defends novox/hq ADR 0103: returned to adopted, the guard is up before the derived filter's // orphans go, and stays up if removing them fails. -func TestReturningToAdoptedLoadsTheGuardBeforeRemovingTheFilter(t *testing.T) { +func testReturningToAdoptedLoadsTheGuardBeforeRemovingTheFilter(t *testing.T) { dir := t.TempDir() guard := filepath.Join(dir, "guard.nft") guardFile := `{"id":"adoption.guard","type":"file","path":"` + guard + `","content":"table inet mesh_guard {}\n"}` @@ -419,7 +419,7 @@ func TestReturningToAdoptedLoadsTheGuardBeforeRemovingTheFilter(t *testing.T) { } } -func TestAStaleOpeningOnAnAdoptedNodeIsRemovedAsAnyOrphan(t *testing.T) { +func testAStaleOpeningOnAnAdoptedNodeIsRemovedAsAnyOrphan(t *testing.T) { // Only the flip defers the adoption's own orphans; an adopted node drops a stale opening at // once, before what replaces it is applied. dir := t.TempDir() @@ -438,7 +438,7 @@ func TestAStaleOpeningOnAnAdoptedNodeIsRemovedAsAnyOrphan(t *testing.T) { } } -func TestARetiredFirewallRetriedStillPutsBackTheForwardPolicy(t *testing.T) { +func testARetiredFirewallRetriedStillPutsBackTheForwardPolicy(t *testing.T) { // The forward policy is recorded before ufw is disabled, so a retirement that failed after // the disable restores what the machine had, not what the disable left (novox/hq ADR 0100). dir := t.TempDir() @@ -462,7 +462,7 @@ func TestARetiredFirewallRetriedStillPutsBackTheForwardPolicy(t *testing.T) { } } -func TestAGuardThatFailsLeavesTheDerivedFilterInForce(t *testing.T) { +func testAGuardThatFailsLeavesTheDerivedFilterInForce(t *testing.T) { // Returning to adopted: if the guard cannot be raised, the filter it replaces must not be // stopped — its stop deletes the mesh's table, and the node would have neither (novox/hq ADR 0103). dir := t.TempDir() @@ -500,7 +500,7 @@ func TestAGuardThatFailsLeavesTheDerivedFilterInForce(t *testing.T) { } } -func TestUfwIsNotRetiredUntilTheMeshsOwnFilterIsLoaded(t *testing.T) { +func testUfwIsNotRetiredUntilTheMeshsOwnFilterIsLoaded(t *testing.T) { // The flip retires the found firewall because the mesh's derived filter takes its place. If // that table is not loaded, retiring would leave the machine filtering nothing (novox/hq ADR 0100). dir := t.TempDir() @@ -530,7 +530,7 @@ func TestUfwIsNotRetiredUntilTheMeshsOwnFilterIsLoaded(t *testing.T) { // A front end that is no longer installed is recorded as removed, said once, and asked nothing of // (novox/hq ADR 0180). -func TestAnUninstalledFrontEndIsRetiredForGood(t *testing.T) { +func testAnUninstalledFrontEndIsRetiredForGood(t *testing.T) { dir := t.TempDir() u := &ufwMachine{installed: false, ruleset: "table inet mesh\n"} known := store.State{Firewall: &store.FoundFirewall{Kind: "ufw", WasActive: true, DisabledByMesh: true, @@ -557,3 +557,21 @@ func TestAnUninstalledFrontEndIsRetiredForGood(t *testing.T) { } } } + +// TestOpening runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestOpening(t *testing.T) { + t.Run("AnOpeningOnAMachineWithNoFirewallChangesNothing", testAnOpeningOnAMachineWithNoFirewallChangesNothing) + t.Run("AnUnsupportedFirewallRefusesTheWholeDeclaration", testAnUnsupportedFirewallRefusesTheWholeDeclaration) + t.Run("ConvergingRetiresTheFoundFirewallAndReturningRestoresIt", testConvergingRetiresTheFoundFirewallAndReturningRestoresIt) + t.Run("AConvergedNodeThatWasNeverAdoptedNeverAsksAboutAFirewall", testAConvergedNodeThatWasNeverAdoptedNeverAsksAboutAFirewall) + t.Run("AnOpeningOnAConvergedNodeIsRefused", testAnOpeningOnAConvergedNodeIsRefused) + t.Run("ACarriedApplyOnAnAdoptedNodeLeavesItsFirewallInForce", testACarriedApplyOnAnAdoptedNodeLeavesItsFirewallInForce) + t.Run("AFlipThatFailsKeepsTheGuardAndTheOpenings", testAFlipThatFailsKeepsTheGuardAndTheOpenings) + t.Run("AnOpeningAFoundRuleAnswersIsReportedSatisfied", testAnOpeningAFoundRuleAnswersIsReportedSatisfied) + t.Run("ReturningToAdoptedLoadsTheGuardBeforeRemovingTheFilter", testReturningToAdoptedLoadsTheGuardBeforeRemovingTheFilter) + t.Run("AStaleOpeningOnAnAdoptedNodeIsRemovedAsAnyOrphan", testAStaleOpeningOnAnAdoptedNodeIsRemovedAsAnyOrphan) + t.Run("ARetiredFirewallRetriedStillPutsBackTheForwardPolicy", testARetiredFirewallRetriedStillPutsBackTheForwardPolicy) + t.Run("AGuardThatFailsLeavesTheDerivedFilterInForce", testAGuardThatFailsLeavesTheDerivedFilterInForce) + t.Run("UfwIsNotRetiredUntilTheMeshsOwnFilterIsLoaded", testUfwIsNotRetiredUntilTheMeshsOwnFilterIsLoaded) + t.Run("AnUninstalledFrontEndIsRetiredForGood", testAnUninstalledFrontEndIsRetiredForGood) +} diff --git a/internal/apply/ownership_test.go b/internal/apply/ownership_test.go index 774cdd34..5b1e12a8 100644 --- a/internal/apply/ownership_test.go +++ b/internal/apply/ownership_test.go @@ -28,7 +28,7 @@ type ownershipCase struct { first, second string } -func TestEachOwnershipBehavesAsItsOldForm(t *testing.T) { +func testEachOwnershipBehavesAsItsOldForm(t *testing.T) { for _, c := range []ownershipCase{ { name: "owned is a whole file whose drift is written back", @@ -104,7 +104,7 @@ func applyThroughDrift(t *testing.T, c ownershipCase, fields string) (string, st // A seed said by the word alone, with no create-once beside it, is still kept once present: the word is // enough, and the file the program grew is not written back. -func TestASeedByTheWordAloneKeepsWhatGrew(t *testing.T) { +func testASeedByTheWordAloneKeepsWhatGrew(t *testing.T) { path := filepath.Join(t.TempDir(), "acl.conf") d := parse(t, fmt.Sprintf(`{"declaration":1,"resources":[ {"id":"acl","type":"file","path":%q,"content":"user default on\n","owner-at-runtime":"seed"} @@ -127,3 +127,9 @@ func TestASeedByTheWordAloneKeepsWhatGrew(t *testing.T) { t.Errorf("what grew in the seed was written over: %q", got) } } + +// TestOwnership runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestOwnership(t *testing.T) { + t.Run("EachOwnershipBehavesAsItsOldForm", testEachOwnershipBehavesAsItsOldForm) + t.Run("ASeedByTheWordAloneKeepsWhatGrew", testASeedByTheWordAloneKeepsWhatGrew) +} diff --git a/internal/apply/placement_guard_test.go b/internal/apply/placement_guard_test.go index 869dddd9..78a78989 100644 --- a/internal/apply/placement_guard_test.go +++ b/internal/apply/placement_guard_test.go @@ -30,7 +30,7 @@ func refusedFor339(t *testing.T, what string, err error) { } } -func TestNoDirectoryIsPlacedAtTheMachinesOwn(t *testing.T) { +func testNoDirectoryIsPlacedAtTheMachinesOwn(t *testing.T) { for _, path := range []string{"/", "/etc", "/etc/", "/usr", "/var", "/var/lib", "/home", "/run", "/boot", "/root", "/var/lib/mesh-host", "/var/lib/mesh-host/identity", "/proc/1/task", "/sys/kernel", "/dev/shm", "/root/.ssh", "/srv/../etc"} { @@ -46,7 +46,7 @@ func TestNoDirectoryIsPlacedAtTheMachinesOwn(t *testing.T) { refusedFor339(t, "a drop-in directory owned by another account", err) } -func TestNoAccessIsAtTheMachinesOwn(t *testing.T) { +func testNoAccessIsAtTheMachinesOwn(t *testing.T) { for _, path := range []string{"/", "/etc", "/etc/ssl", "/usr", "/var/lib", "/home", "/root", "/proc", "/var/lib/mesh-host", "/run/docker"} { _, _, err := applyOnce(t, `{"id":"notes.media","type":"access","path":"`+path+`"}`, nil, store.State{}) @@ -55,7 +55,7 @@ func TestNoAccessIsAtTheMachinesOwn(t *testing.T) { } // A container is never handed the machine's own as a mount, nor a directory or access the engine refused. -func TestNoContainerMountsTheMachinesOwn(t *testing.T) { +func testNoContainerMountsTheMachinesOwn(t *testing.T) { ran := false run := func(ctx context.Context, name string, args ...string) (string, error) { args = oldShape(name, args) @@ -85,7 +85,7 @@ func TestNoContainerMountsTheMachinesOwn(t *testing.T) { // The path is not followed: a link where a directory is declared, or a link on the way to it, is judged where // it leads. -func TestALinkIsNotFollowedToTheMachinesOwn(t *testing.T) { +func testALinkIsNotFollowedToTheMachinesOwn(t *testing.T) { dir := t.TempDir() target := filepath.Join(dir, "target") if err := os.Mkdir(target, 0o700); err != nil { @@ -113,7 +113,7 @@ func TestALinkIsNotFollowedToTheMachinesOwn(t *testing.T) { // A directory found here, that the mesh did not make, keeps its owner and mode; one the mesh made keeps the // declared mode, as before. -func TestAFoundDirectoryIsUsedAsFound(t *testing.T) { +func testAFoundDirectoryIsUsedAsFound(t *testing.T) { dir := t.TempDir() found := filepath.Join(dir, "found") if err := os.Mkdir(found, 0o700); err != nil { @@ -177,7 +177,7 @@ func TestAFoundDirectoryIsUsedAsFound(t *testing.T) { // The module's own directories keep being placed: below /var/lib, below /etc as root's, a container's mount of // the machine's docker socket. -func TestAModulesOwnPlacesAreStillPlaced(t *testing.T) { +func testAModulesOwnPlacesAreStillPlaced(t *testing.T) { // The paths below are judged as written: no link of them is followed on the machine the test runs on, whose mounts of them // (a share that does not answer) it does not depend on. was := evalSymlinks @@ -219,3 +219,13 @@ func TestAModulesOwnPlacesAreStillPlaced(t *testing.T) { } } } + +// TestPlacementGuard runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestPlacementGuard(t *testing.T) { + t.Run("NoDirectoryIsPlacedAtTheMachinesOwn", testNoDirectoryIsPlacedAtTheMachinesOwn) + t.Run("NoAccessIsAtTheMachinesOwn", testNoAccessIsAtTheMachinesOwn) + t.Run("NoContainerMountsTheMachinesOwn", testNoContainerMountsTheMachinesOwn) + t.Run("ALinkIsNotFollowedToTheMachinesOwn", testALinkIsNotFollowedToTheMachinesOwn) + t.Run("AFoundDirectoryIsUsedAsFound", testAFoundDirectoryIsUsedAsFound) + t.Run("AModulesOwnPlacesAreStillPlaced", testAModulesOwnPlacesAreStillPlaced) +} diff --git a/internal/apply/plan_test.go b/internal/apply/plan_test.go index 7ad86fb3..a812d766 100644 --- a/internal/apply/plan_test.go +++ b/internal/apply/plan_test.go @@ -32,7 +32,7 @@ func verbs(steps []Step) string { return strings.Join(out, ", ") } -func TestAPlanNamesAnActionAsAnAction(t *testing.T) { +func testAPlanNamesAnActionAsAnAction(t *testing.T) { d := trusted(t, `{"declaration":1,"resources":[ {"id":"init","type":"action","command":["createdb","mesh"],"verify":["psql","-c","select 1"]}]}`) steps := Plan(d, store.State{}, store.OriginCarried) @@ -44,7 +44,7 @@ func TestAPlanNamesAnActionAsAnAction(t *testing.T) { } } -func TestAPlanSaysWhatIsRecordedAndWhatIsNot(t *testing.T) { +func testAPlanSaysWhatIsRecordedAndWhatIsNot(t *testing.T) { d := parse(t, `{"declaration":1,"resources":[ {"id":"new","type":"file","path":"/tmp/new","content":"a\n"}, {"id":"same","type":"file","path":"/tmp/same","content":"b\n"}, @@ -63,7 +63,7 @@ func TestAPlanSaysWhatIsRecordedAndWhatIsNot(t *testing.T) { } } -func TestAPlanSaysTheFirewallAConvergingNodeRetires(t *testing.T) { +func testAPlanSaysTheFirewallAConvergingNodeRetires(t *testing.T) { d := parse(t, `{"declaration":1,"resources":[{"id":"a","type":"file","path":"/tmp/a","content":"x\n"}]}`) known := store.State{Firewall: &store.FoundFirewall{Kind: "ufw", WasActive: true, FoundAt: time.Now()}} known.Record(store.Applied{ID: "adoption.guard.table", Type: "file", Target: "/etc/guard", Origin: store.OriginDeclared}) @@ -79,7 +79,7 @@ func TestAPlanSaysTheFirewallAConvergingNodeRetires(t *testing.T) { } } -func TestAPlanHoldsWhatAnAdoptedNodeFound(t *testing.T) { +func testAPlanHoldsWhatAnAdoptedNodeFound(t *testing.T) { d := parse(t, `{"declaration":1,"adoption":{"taken":[],"untaken":{"hello-web":["hello-web.page","hello-web.server"]}}, "resources":[ {"id":"hello-web.page","type":"file","path":"/srv/index.html","content":"x\n"}, @@ -140,7 +140,7 @@ func write(t *testing.T, path, content string) { // Defends novox/hq issue 104: the plan is the apply, said first — the same resources in the same // order, and the one cutover ADR 0100 says must be previewed said as a cutover, not a hold. -func TestThePlanIsTheApplyInOrder(t *testing.T) { +func testThePlanIsTheApplyInOrder(t *testing.T) { dir := t.TempDir() guard, page, keep, old := filepath.Join(dir, "guard.nft"), filepath.Join(dir, "index.html"), filepath.Join(dir, "keep.html"), filepath.Join(dir, "old.conf") @@ -209,7 +209,7 @@ func TestThePlanIsTheApplyInOrder(t *testing.T) { } } -func TestAResourceRunInAHeldContainerIsPlannedAsItIsApplied(t *testing.T) { +func testAResourceRunInAHeldContainerIsPlannedAsItIsApplied(t *testing.T) { // A run-once step sharing a container's namespace runs in it, as an action's `in` does. img := "example/x@sha256:0000000000000000000000000000000000000000000000000000000000000000" d := parse(t, `{"declaration":1,"adoption":{"taken":["web"],"untaken":{"db":["db.server"]}},"resources":[ @@ -228,7 +228,7 @@ func TestAResourceRunInAHeldContainerIsPlannedAsItIsApplied(t *testing.T) { } } -func TestAPlanSaysAContainerIsRecreatedWhenAFileItReadsChanged(t *testing.T) { +func testAPlanSaysAContainerIsRecreatedWhenAFileItReadsChanged(t *testing.T) { // The apply recreates a container when the content of a file it reads at creation changed // (novox/hq 04-ISSUES/103); the plan says so from the record alone — what the container was // created reading, against what this apply will write. And a container recorded before the @@ -264,7 +264,7 @@ func TestAPlanSaysAContainerIsRecreatedWhenAFileItReadsChanged(t *testing.T) { } } -func TestAPlanSaysWhichUnitsAnUndeclareGivesBackAndWhichItLeaves(t *testing.T) { +func testAPlanSaysWhichUnitsAnUndeclareGivesBackAndWhichItLeaves(t *testing.T) { // novox/hq ADR 0118, said before it is done: "restore" only where removal may stop or disable // something, and a unit whose file the mesh wrote named as the mesh's. known := store.State{} @@ -302,3 +302,15 @@ func TestAPlanSaysWhichUnitsAnUndeclareGivesBackAndWhichItLeaves(t *testing.T) { } } } + +// TestPlan runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestPlan(t *testing.T) { + t.Run("APlanNamesAnActionAsAnAction", testAPlanNamesAnActionAsAnAction) + t.Run("APlanSaysWhatIsRecordedAndWhatIsNot", testAPlanSaysWhatIsRecordedAndWhatIsNot) + t.Run("APlanSaysTheFirewallAConvergingNodeRetires", testAPlanSaysTheFirewallAConvergingNodeRetires) + t.Run("APlanHoldsWhatAnAdoptedNodeFound", testAPlanHoldsWhatAnAdoptedNodeFound) + t.Run("ThePlanIsTheApplyInOrder", testThePlanIsTheApplyInOrder) + t.Run("AResourceRunInAHeldContainerIsPlannedAsItIsApplied", testAResourceRunInAHeldContainerIsPlannedAsItIsApplied) + t.Run("APlanSaysAContainerIsRecreatedWhenAFileItReadsChanged", testAPlanSaysAContainerIsRecreatedWhenAFileItReadsChanged) + t.Run("APlanSaysWhichUnitsAnUndeclareGivesBackAndWhichItLeaves", testAPlanSaysWhichUnitsAnUndeclareGivesBackAndWhichItLeaves) +} diff --git a/internal/apply/process_test.go b/internal/apply/process_test.go index 6168e2e4..9555dfe9 100644 --- a/internal/apply/process_test.go +++ b/internal/apply/process_test.go @@ -24,7 +24,7 @@ func aProcess() *declaration.Process { // The unit the mesh writes says what it runs, where, and that it comes back — and that it is the // mesh's: **generated whole and saying so**, because an edit that survives until the next declaration // and then vanishes is worse than one that is refused. The long-running mode stays up and is not a step. -func TestTheUnitRunsWhatTheDaemonSaid(t *testing.T) { +func testTheUnitRunsWhatTheDaemonSaid(t *testing.T) { unit := unitFor(aProcess()) if !strings.HasPrefix(unit, "#") { t.Fatalf("the unit does not open saying it is generated:\n%s", unit) @@ -77,7 +77,7 @@ func TestTheUnitRunsWhatTheDaemonSaid(t *testing.T) { // A process that runs as somebody says so, and one that does not says nothing — rather than naming // root explicitly, which would be a claim the mesh does not need to make. -func TestAProcessRunsAsWhoItSaid(t *testing.T) { +func testAProcessRunsAsWhoItSaid(t *testing.T) { as := aProcess() as.User = "greeter" if !strings.Contains(unitFor(as), "User=greeter") { @@ -145,7 +145,7 @@ func TestAProcessRunsAsWhoItSaid(t *testing.T) { // **Three modes, one kind.** A scheduled process is a timer plus a unit that finishes, not a unit // that stays up — and the difference has to be in what is written, or a schedule becomes a second // copy running continuously between fires. -func TestAScheduledProcessRunsOnItsCadenceRatherThanContinuously(t *testing.T) { +func testAScheduledProcessRunsOnItsCadenceRatherThanContinuously(t *testing.T) { every := aProcess() every.Schedule = "0 3 * * *" @@ -180,7 +180,7 @@ func TestAScheduledProcessRunsOnItsCadenceRatherThanContinuously(t *testing.T) { // **A unit file reinterprets a value in three ways nothing else does**, and a module's environment // routinely contains all three — a generated password is arbitrary bytes. -func TestAnEnvironmentValueMeansWhatTheDeclarationSaid(t *testing.T) { +func testAnEnvironmentValueMeansWhatTheDeclarationSaid(t *testing.T) { // A percent begins a specifier: %H is the hostname. A password containing one would be // silently replaced, failing as an authentication error nobody can explain from the // declaration. @@ -211,7 +211,7 @@ func TestAnEnvironmentValueMeansWhatTheDeclarationSaid(t *testing.T) { } } -func TestAnUndeclaredProcessIsRemovedWithItsUnitAndBundle(t *testing.T) { +func testAnUndeclaredProcessIsRemovedWithItsUnitAndBundle(t *testing.T) { // novox/hq ADR 0118: a process's unit and bundle are the host's own, so they go with the // declaration. Before, there was no way to remove a process at all, and one left undeclared // failed every apply on its node. @@ -269,7 +269,7 @@ func TestAnUndeclaredProcessIsRemovedWithItsUnitAndBundle(t *testing.T) { } } -func TestAProcessRecordedUnderAPathlikeNameIsRefusedNotRemoved(t *testing.T) { +func testAProcessRecordedUnderAPathlikeNameIsRefusedNotRemoved(t *testing.T) { // filepath.Join(daemonRoot, "..") is the mesh's own directory, and removal deletes what that // names, whole. A record is what some host wrote, perhaps under looser rules than today's, so // the removal holds the name to the declaration's rule again (novox/hq ADR 0118). @@ -304,7 +304,7 @@ func TestAProcessRecordedUnderAPathlikeNameIsRefusedNotRemoved(t *testing.T) { // novox/hq 04-ISSUES/210: the node's runtime was re-created — and restarted — on every reconcile, // because the host did not find what it wrote for a process the cycle before. Applying the same // process declaration twice must do no work the second time. -func TestAProcessAppliedAgainIsUnchangedAndNotRestarted(t *testing.T) { +func testAProcessAppliedAgainIsUnchangedAndNotRestarted(t *testing.T) { units, bundles := t.TempDir(), t.TempDir() wasUnits, wasBundles := unitDir, daemonRoot unitDir, daemonRoot = units, bundles @@ -415,7 +415,7 @@ func TestAProcessAppliedAgainIsUnchangedAndNotRestarted(t *testing.T) { // novox/hq ADR 0193: a bundle compiled to a binary runs itself — `./name` is that file in the // process's own unpacked bundle, made absolute because the service manager takes nothing relative. -func TestAProcessRunsItsOwnBundlesBinary(t *testing.T) { +func testAProcessRunsItsOwnBundlesBinary(t *testing.T) { unit := unitFor(&declaration.Process{Name: "node-tools", Run: []string{"./node-tools", "serve"}}) if !strings.Contains(unit, "ExecStart="+filepath.Join(daemonRoot, "node-tools", "node-tools")+" serve\n") { t.Errorf("the binary is not run from its bundle:\n%s", unit) @@ -425,3 +425,15 @@ func TestAProcessRunsItsOwnBundlesBinary(t *testing.T) { t.Errorf("a command found on the path was changed:\n%s", other) } } + +// TestProcess runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestProcess(t *testing.T) { + t.Run("TheUnitRunsWhatTheDaemonSaid", testTheUnitRunsWhatTheDaemonSaid) + t.Run("AProcessRunsAsWhoItSaid", testAProcessRunsAsWhoItSaid) + t.Run("AScheduledProcessRunsOnItsCadenceRatherThanContinuously", testAScheduledProcessRunsOnItsCadenceRatherThanContinuously) + t.Run("AnEnvironmentValueMeansWhatTheDeclarationSaid", testAnEnvironmentValueMeansWhatTheDeclarationSaid) + t.Run("AnUndeclaredProcessIsRemovedWithItsUnitAndBundle", testAnUndeclaredProcessIsRemovedWithItsUnitAndBundle) + t.Run("AProcessRecordedUnderAPathlikeNameIsRefusedNotRemoved", testAProcessRecordedUnderAPathlikeNameIsRefusedNotRemoved) + t.Run("AProcessAppliedAgainIsUnchangedAndNotRestarted", testAProcessAppliedAgainIsUnchangedAndNotRestarted) + t.Run("AProcessRunsItsOwnBundlesBinary", testAProcessRunsItsOwnBundlesBinary) +} diff --git a/internal/apply/process_witness_test.go b/internal/apply/process_witness_test.go index 0be3ba15..4ed16a36 100644 --- a/internal/apply/process_witness_test.go +++ b/internal/apply/process_witness_test.go @@ -17,7 +17,7 @@ import ( // A core process keeps the build before it while the new one is judged (novox/hq to-be 45 §8): the // applier places the new build where the unit runs it from, and moves the old one aside rather than // deleting it. A process nobody judges is replaced as ever. -func TestACoreProcessKeepsTheBuildBeforeItWhileTheNewOneIsJudged(t *testing.T) { +func testACoreProcessKeepsTheBuildBeforeItWhileTheNewOneIsJudged(t *testing.T) { units, bundles := t.TempDir(), t.TempDir() wasUnits, wasBundles := unitDir, daemonRoot unitDir, daemonRoot = units, bundles @@ -65,7 +65,7 @@ func TestACoreProcessKeepsTheBuildBeforeItWhileTheNewOneIsJudged(t *testing.T) { // A build rolled back on this machine is not placed again while the mesh still declares it; the // restored build keeps running, and the apply says why. -func TestARolledBackBuildIsNotPlacedAgain(t *testing.T) { +func testARolledBackBuildIsNotPlacedAgain(t *testing.T) { units, bundles := t.TempDir(), t.TempDir() wasUnits, wasBundles := unitDir, daemonRoot unitDir, daemonRoot = units, bundles @@ -112,7 +112,7 @@ func TestARolledBackBuildIsNotPlacedAgain(t *testing.T) { // process started in it failed with "getwd: no such file or directory". Here a process works in the // build's directory without running from it, as that `go version` did: the apply of a new build leaves // its directory in place, and the retired build goes once nothing works in it. -func TestAProcessNobodyJudgesKeepsItsDirectoryUntilItsRestart(t *testing.T) { +func testAProcessNobodyJudgesKeepsItsDirectoryUntilItsRestart(t *testing.T) { if _, err := os.Stat("/proc/self/cwd"); err != nil { t.Skip("which process works in a build is read from /proc") } @@ -181,3 +181,10 @@ func TestAProcessNobodyJudgesKeepsItsDirectoryUntilItsRestart(t *testing.T) { t.Fatalf("a retired build nothing works in was kept: %v", err) } } + +// TestProcessWitness runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestProcessWitness(t *testing.T) { + t.Run("ACoreProcessKeepsTheBuildBeforeItWhileTheNewOneIsJudged", testACoreProcessKeepsTheBuildBeforeItWhileTheNewOneIsJudged) + t.Run("ARolledBackBuildIsNotPlacedAgain", testARolledBackBuildIsNotPlacedAgain) + t.Run("AProcessNobodyJudgesKeepsItsDirectoryUntilItsRestart", testAProcessNobodyJudgesKeepsItsDirectoryUntilItsRestart) +} diff --git a/internal/apply/reads_test.go b/internal/apply/reads_test.go index ea2a5a40..b318c02a 100644 --- a/internal/apply/reads_test.go +++ b/internal/apply/reads_test.go @@ -30,7 +30,7 @@ func applyCarried(t *testing.T, d *declaration.Declaration, known store.State, m return report, state } -func TestAContainerIsRecreatedWhenItsEnvFileChanged(t *testing.T) { +func testAContainerIsRecreatedWhenItsEnvFileChanged(t *testing.T) { // The night of the issue: the store was given a new port, the host rewrote the forge's // environment file with it — and left the forge running with the old one. dir := t.TempDir() @@ -79,7 +79,7 @@ func TestAContainerIsRecreatedWhenItsEnvFileChanged(t *testing.T) { } } -func TestAnEnvFileTheHostDidNotWriteIsStillReadForWhatItHolds(t *testing.T) { +func testAnEnvFileTheHostDidNotWriteIsStillReadForWhatItHolds(t *testing.T) { // The host has no record of this file — a predecessor left it, or something else on the // machine maintains it — and the container still reads it once. Its content is read from the // disk, so a change is a recreate exactly as for a file the host wrote. @@ -107,7 +107,7 @@ func TestAnEnvFileTheHostDidNotWriteIsStillReadForWhatItHolds(t *testing.T) { } } -func TestAContainerIsRecreatedWhenAMountedSecretChanged(t *testing.T) { +func testAContainerIsRecreatedWhenAMountedSecretChanged(t *testing.T) { // A rotated credential has the same shape as a moved port: the host writes the file the // container mounts, and the process holds the value it was created with. dir := t.TempDir() @@ -132,7 +132,7 @@ func TestAContainerIsRecreatedWhenAMountedSecretChanged(t *testing.T) { } } -func TestAMountedDirectoryIsNotLookedInside(t *testing.T) { +func testAMountedDirectoryIsNotLookedInside(t *testing.T) { // A bind-mounted directory is not part of what a container is — not the data the service // grows in it, and not the files the host itself writes there either. Whether a service reads // a file under its directory once at start or watches it live is the service's business: the @@ -193,7 +193,7 @@ func TestAMountedDirectoryIsNotLookedInside(t *testing.T) { } } -func TestAContainerLabelledBeforeTheHostReadItsFilesIsAcceptedNotRecreated(t *testing.T) { +func testAContainerLabelledBeforeTheHostReadItsFilesIsAcceptedNotRecreated(t *testing.T) { // The first apply after the host upgrades finds every container carrying a label computed // without the file lines. Recreating them all would be a restart storm across the mesh in // declaration order, the store first. A label that matches the spec as it used to be computed @@ -247,7 +247,7 @@ func TestAContainerLabelledBeforeTheHostReadItsFilesIsAcceptedNotRecreated(t *te } } -func TestAContainerAdoptedUnderANewIdStillSaysWhichFileChanged(t *testing.T) { +func testAContainerAdoptedUnderANewIdStillSaysWhichFileChanged(t *testing.T) { // The bundle's `store` becomes the postgres module's `postgres.server`: the same container by // name, under a new id with no record of its own. A file change on that day is a real change, // and the record of what it read is under the old id — by name, it is found. @@ -274,7 +274,7 @@ func TestAContainerAdoptedUnderANewIdStillSaysWhichFileChanged(t *testing.T) { } } -func TestAHeldContainerIsNotRecreatedByAChangedHeldFile(t *testing.T) { +func testAHeldContainerIsNotRecreatedByAChangedHeldFile(t *testing.T) { // On an adopted node the predecessor's container and the file it reads are both held as // found (novox/hq ADR 0100). The predecessor rewriting its own file is reported on the file // — and is nothing to recreate the container for: it is not the host's to recreate. @@ -314,3 +314,14 @@ func TestAHeldContainerIsNotRecreatedByAChangedHeldFile(t *testing.T) { t.Errorf("a file change was charged to the container: %+v", h) } } + +// TestReads runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestReads(t *testing.T) { + t.Run("AContainerIsRecreatedWhenItsEnvFileChanged", testAContainerIsRecreatedWhenItsEnvFileChanged) + t.Run("AnEnvFileTheHostDidNotWriteIsStillReadForWhatItHolds", testAnEnvFileTheHostDidNotWriteIsStillReadForWhatItHolds) + t.Run("AContainerIsRecreatedWhenAMountedSecretChanged", testAContainerIsRecreatedWhenAMountedSecretChanged) + t.Run("AMountedDirectoryIsNotLookedInside", testAMountedDirectoryIsNotLookedInside) + t.Run("AContainerLabelledBeforeTheHostReadItsFilesIsAcceptedNotRecreated", testAContainerLabelledBeforeTheHostReadItsFilesIsAcceptedNotRecreated) + t.Run("AContainerAdoptedUnderANewIdStillSaysWhichFileChanged", testAContainerAdoptedUnderANewIdStillSaysWhichFileChanged) + t.Run("AHeldContainerIsNotRecreatedByAChangedHeldFile", testAHeldContainerIsNotRecreatedByAChangedHeldFile) +} diff --git a/internal/apply/references_test.go b/internal/apply/references_test.go index ec3f841b..18c9f790 100644 --- a/internal/apply/references_test.go +++ b/internal/apply/references_test.go @@ -35,7 +35,7 @@ func objectOf(body []byte) string { } // 1695/AC1: both forms apply: a file by reference becomes the inline file, an inline one is left as it is. -func TestAFileByReferenceBecomesTheInlineFile(t *testing.T) { +func testAFileByReferenceBecomesTheInlineFile(t *testing.T) { body := []byte(strings.Repeat("a line\n", 20000)) inline := &declaration.File{ID: "m.small", Type: declaration.TypeFile, Path: "/etc/small", Content: "x"} d := &declaration.Declaration{Resources: []declaration.Resource{inline, referenceTo(t, "/nowhere/big", body)}} @@ -53,7 +53,7 @@ func TestAFileByReferenceBecomesTheInlineFile(t *testing.T) { } // 1695/AC2: an object that differs by one byte, or in size, fails the whole resolve and gives no content. -func TestAnObjectThatDiffersFailsTheApply(t *testing.T) { +func testAnObjectThatDiffersFailsTheApply(t *testing.T) { body := []byte(strings.Repeat("x", 70000)) bad := append([]byte(nil), body...) bad[3] ^= 1 @@ -71,7 +71,7 @@ func TestAnObjectThatDiffersFailsTheApply(t *testing.T) { } // 1695/AC3: a missing object, or a node with no bus, fails the apply naming the file. -func TestAMissingObjectFailsTheApply(t *testing.T) { +func testAMissingObjectFailsTheApply(t *testing.T) { body := []byte(strings.Repeat("y", 70000)) d := &declaration.Declaration{Resources: []declaration.Resource{referenceTo(t, "/nowhere/big", body)}} var asked []string @@ -85,7 +85,7 @@ func TestAMissingObjectFailsTheApply(t *testing.T) { } // 1695/AC4: a file already on the machine that verifies is used and nothing is fetched; one that does not is fetched. -func TestAVerifiedFileOnTheMachineFetchesNothing(t *testing.T) { +func testAVerifiedFileOnTheMachineFetchesNothing(t *testing.T) { body := []byte(strings.Repeat("z", 70000)) path := filepath.Join(t.TempDir(), "big") if err := os.WriteFile(path, body, 0o644); err != nil { @@ -106,7 +106,7 @@ func TestAVerifiedFileOnTheMachineFetchesNothing(t *testing.T) { } // 1695/AC5: binary content comes back as bytes, and two files naming one digest fetch it once. -func TestBinaryContentAndOneFetchPerDigest(t *testing.T) { +func testBinaryContentAndOneFetchPerDigest(t *testing.T) { body := append([]byte{0xff, 0xfe, 0x00}, []byte(strings.Repeat("b", 70000))...) d := &declaration.Declaration{Resources: []declaration.Resource{referenceTo(t, "/n/a", body), referenceTo(t, "/n/b", body)}} var asked []string @@ -120,7 +120,7 @@ func TestBinaryContentAndOneFetchPerDigest(t *testing.T) { } // 1695/AC9: an unresolved reference reaching the apply is refused, never written as an empty file. -func TestAnUnresolvedReferenceIsNeverWrittenEmpty(t *testing.T) { +func testAnUnresolvedReferenceIsNeverWrittenEmpty(t *testing.T) { path := filepath.Join(t.TempDir(), "big") f := referenceTo(t, path, []byte(strings.Repeat("q", 70000))) if _, err := applyFile(f, store.Applied{}, nil, nil); err == nil || !strings.Contains(err.Error(), "not written empty") { @@ -130,3 +130,13 @@ func TestAnUnresolvedReferenceIsNeverWrittenEmpty(t *testing.T) { t.Error("1695/AC9: a file was written") } } + +// TestReferences runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestReferences(t *testing.T) { + t.Run("AFileByReferenceBecomesTheInlineFile", testAFileByReferenceBecomesTheInlineFile) + t.Run("AnObjectThatDiffersFailsTheApply", testAnObjectThatDiffersFailsTheApply) + t.Run("AMissingObjectFailsTheApply", testAMissingObjectFailsTheApply) + t.Run("AVerifiedFileOnTheMachineFetchesNothing", testAVerifiedFileOnTheMachineFetchesNothing) + t.Run("BinaryContentAndOneFetchPerDigest", testBinaryContentAndOneFetchPerDigest) + t.Run("AnUnresolvedReferenceIsNeverWrittenEmpty", testAnUnresolvedReferenceIsNeverWrittenEmpty) +} diff --git a/internal/apply/refused_directory_test.go b/internal/apply/refused_directory_test.go index f6ae9d0e..ee2e337f 100644 --- a/internal/apply/refused_directory_test.go +++ b/internal/apply/refused_directory_test.go @@ -45,7 +45,7 @@ func aRuntimeRoot(t *testing.T) string { return root } -func TestARefusedDirectoryGatesItsModule(t *testing.T) { +func testARefusedDirectoryGatesItsModule(t *testing.T) { root := aRuntimeRoot(t) b := newStepBed(t) elsewhere := filepath.Join(b.dir, "other.conf") @@ -86,7 +86,7 @@ func TestARefusedDirectoryGatesItsModule(t *testing.T) { // A file is judged as a directory is: refused in a tree nothing is placed in, and below a directory the // engine refused, whichever module declares it and in whatever order. -func TestAFileIsJudgedByTheSameGuardAsADirectory(t *testing.T) { +func testAFileIsJudgedByTheSameGuardAsADirectory(t *testing.T) { root := aRuntimeRoot(t) _, _, err := applyOnce(t, `{"id":"notes.conf","type":"file","path":"`+root+`/notes.conf","content":"x\n"}`, nil, store.State{}) @@ -130,7 +130,7 @@ func TestAFileIsJudgedByTheSameGuardAsADirectory(t *testing.T) { } // An archive below a refused path is refused with it, whichever module declares it and in whatever order. -func TestAnArchiveBelowARefusedPathIsRefused(t *testing.T) { +func testAnArchiveBelowARefusedPathIsRefused(t *testing.T) { dir := t.TempDir() home := filepath.Join(dir, "home", "alice") if err := os.MkdirAll(home, 0o755); err != nil { @@ -163,7 +163,7 @@ func TestAnArchiveBelowARefusedPathIsRefused(t *testing.T) { // Gated is per apply: a module gated behind its refused directory is tried again by the next apply, gated // again while the directory is refused, and applied whole once it is not. -func TestAGatedModuleIsTriedAgainByTheNextApply(t *testing.T) { +func testAGatedModuleIsTriedAgainByTheNextApply(t *testing.T) { root := aRuntimeRoot(t) b := newStepBed(t) declared := func() string { @@ -199,7 +199,7 @@ func TestAGatedModuleIsTriedAgainByTheNextApply(t *testing.T) { // A module gated behind its refused directory, then a step of no module that stops the machine: the report // names both, and says nothing after the step was attempted (novox/hq issue 495). -func TestAMachineStopAfterAGatedModuleSaysBoth(t *testing.T) { +func testAMachineStopAfterAGatedModuleSaysBoth(t *testing.T) { root := aRuntimeRoot(t) after := filepath.Join(t.TempDir(), "after.conf") _, _, err := Apply(context.Background(), archHost(t), parseTrusted(t, `{"declaration":1,"resources":[ @@ -220,3 +220,12 @@ func TestAMachineStopAfterAGatedModuleSaysBoth(t *testing.T) { t.Errorf("the report does not say both what was gated and that the machine stopped: %s", msg) } } + +// TestRefusedDirectory runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRefusedDirectory(t *testing.T) { + t.Run("ARefusedDirectoryGatesItsModule", testARefusedDirectoryGatesItsModule) + t.Run("AFileIsJudgedByTheSameGuardAsADirectory", testAFileIsJudgedByTheSameGuardAsADirectory) + t.Run("AnArchiveBelowARefusedPathIsRefused", testAnArchiveBelowARefusedPathIsRefused) + t.Run("AGatedModuleIsTriedAgainByTheNextApply", testAGatedModuleIsTriedAgainByTheNextApply) + t.Run("AMachineStopAfterAGatedModuleSaysBoth", testAMachineStopAfterAGatedModuleSaysBoth) +} diff --git a/internal/apply/removal_order_test.go b/internal/apply/removal_order_test.go index dd23aec3..ef6c7a10 100644 --- a/internal/apply/removal_order_test.go +++ b/internal/apply/removal_order_test.go @@ -16,7 +16,7 @@ import ( // its config directory and file, finds the configuration gone when it is stopped on unassignment and // only then removes its export file; on a restart or a push the configuration is still there and it // leaves the exports alone. -func TestAnUnassignedModulesProcessIsStoppedAfterTheConfigurationItReads(t *testing.T) { +func testAnUnassignedModulesProcessIsStoppedAfterTheConfigurationItReads(t *testing.T) { units, bundles := t.TempDir(), t.TempDir() wasUnits, wasBundles := unitDir, daemonRoot unitDir, daemonRoot = units, bundles @@ -82,7 +82,7 @@ func TestAnUnassignedModulesProcessIsStoppedAfterTheConfigurationItReads(t *test // one added in a later version of the module, or one whose first apply failed — is appended, so it // is removed first. A module that relies on the order declares the process from its first version and // keeps it applying; the test shows the flip so nobody reads the contract as stronger than it is. -func TestAProcessRecordedAfterItsConfigurationIsStoppedFirst(t *testing.T) { +func testAProcessRecordedAfterItsConfigurationIsStoppedFirst(t *testing.T) { units, bundles := t.TempDir(), t.TempDir() wasUnits, wasBundles := unitDir, daemonRoot unitDir, daemonRoot = units, bundles @@ -118,3 +118,9 @@ func TestAProcessRecordedAfterItsConfigurationIsStoppedFirst(t *testing.T) { t.Errorf("a process recorded after its configuration was not stopped first (seen at each stop: %v)", configAtStop) } } + +// TestRemovalOrder runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRemovalOrder(t *testing.T) { + t.Run("AnUnassignedModulesProcessIsStoppedAfterTheConfigurationItReads", testAnUnassignedModulesProcessIsStoppedAfterTheConfigurationItReads) + t.Run("AProcessRecordedAfterItsConfigurationIsStoppedFirst", testAProcessRecordedAfterItsConfigurationIsStoppedFirst) +} diff --git a/internal/apply/replace_image_test.go b/internal/apply/replace_image_test.go index a7fd05d5..7d13a784 100644 --- a/internal/apply/replace_image_test.go +++ b/internal/apply/replace_image_test.go @@ -14,7 +14,7 @@ import ( // Issue 1742: the engine removed a running container and only then found the replacement image // unobtainable, leaving the service down. The replacement image comes first. -func TestARunningContainerIsKeptWhenItsReplacementImageCannotBeObtained(t *testing.T) { +func testARunningContainerIsKeptWhenItsReplacementImageCannotBeObtained(t *testing.T) { d := parseTrusted(t, `{"declaration":1,"resources":[ {"id":"store","type":"container","name":"store","image":"`+pinned+`","env":{"PGDATA":"/data"}} ]}`) @@ -207,7 +207,7 @@ func TestARunningContainerIsKeptWhenItsReplacementImageCannotBeObtained(t *testi } } -func TestAReplacementImageIsPresentBeforeTheRunningContainerIsRemoved(t *testing.T) { +func testAReplacementImageIsPresentBeforeTheRunningContainerIsRemoved(t *testing.T) { d := parseTrusted(t, `{"declaration":1,"resources":[ {"id":"store","type":"container","name":"store","image":"`+pinned+`","env":{"PGDATA":"/data"}} ]}`) @@ -294,7 +294,7 @@ func asideRun(t *testing.T, want string, failRun bool, order *[]string) Runner { // removed before the new one runs, and started again under its name when the new one fails, the apply failing loudly. // Removed first, the bus's own container left novox without a bus when its replacement was never made (issue 1945, // live on 2026-10-25 at 11:23). -func TestAContainerWhoseReplacementFailsIsPutBack(t *testing.T) { +func testAContainerWhoseReplacementFailsIsPutBack(t *testing.T) { d := parseTrusted(t, `{"declaration":1,"resources":[ {"id":"store","type":"container","name":"store","image":"`+pinned+`","env":{"PGDATA":"/data"}} ]}`) @@ -315,7 +315,7 @@ func TestAContainerWhoseReplacementFailsIsPutBack(t *testing.T) { } // A replacement that runs removes the container set aside, and only after it runs. -func TestAReplacementThatRunsRemovesTheContainerSetAside(t *testing.T) { +func testAReplacementThatRunsRemovesTheContainerSetAside(t *testing.T) { d := parseTrusted(t, `{"declaration":1,"resources":[ {"id":"store","type":"container","name":"store","image":"`+pinned+`","env":{"PGDATA":"/data"}} ]}`) @@ -334,7 +334,7 @@ func TestAReplacementThatRunsRemovesTheContainerSetAside(t *testing.T) { // A container left set aside by an engine that stopped between setting it aside and running its replacement is the // set-aside one of the next apply: put back when the replacement fails, removed once it runs (the review of issue // 1945). -func TestAContainerLeftAsideIsPutBackOrRemovedByTheNextApply(t *testing.T) { +func testAContainerLeftAsideIsPutBackOrRemovedByTheNextApply(t *testing.T) { d := parseTrusted(t, `{"declaration":1,"resources":[ {"id":"store","type":"container","name":"store","image":"`+pinned+`","env":{"PGDATA":"/data"}} ]}`) @@ -385,3 +385,12 @@ func TestAContainerLeftAsideIsPutBackOrRemovedByTheNextApply(t *testing.T) { } } } + +// TestReplaceImage runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestReplaceImage(t *testing.T) { + t.Run("ARunningContainerIsKeptWhenItsReplacementImageCannotBeObtained", testARunningContainerIsKeptWhenItsReplacementImageCannotBeObtained) + t.Run("AReplacementImageIsPresentBeforeTheRunningContainerIsRemoved", testAReplacementImageIsPresentBeforeTheRunningContainerIsRemoved) + t.Run("AContainerWhoseReplacementFailsIsPutBack", testAContainerWhoseReplacementFailsIsPutBack) + t.Run("AReplacementThatRunsRemovesTheContainerSetAside", testAReplacementThatRunsRemovesTheContainerSetAside) + t.Run("AContainerLeftAsideIsPutBackOrRemovedByTheNextApply", testAContainerLeftAsideIsPutBackOrRemovedByTheNextApply) +} diff --git a/internal/apply/restart_order_test.go b/internal/apply/restart_order_test.go index 1cecd100..626b054a 100644 --- a/internal/apply/restart_order_test.go +++ b/internal/apply/restart_order_test.go @@ -17,7 +17,7 @@ import ( // configuration, the daemon could not read the zones file the same apply had not written yet, and // the apply failed on every machine (novox/hq issue 260). A service is restarted only once every // resource it names under restart-on has been applied. -func TestAServiceIsRestartedOnlyOnceEveryFileItNamesIsWritten(t *testing.T) { +func testAServiceIsRestartedOnlyOnceEveryFileItNamesIsWritten(t *testing.T) { dir := t.TempDir() conf := filepath.Join(dir, "resolver.conf") zones := filepath.Join(dir, "zones.conf") @@ -89,7 +89,7 @@ func TestAServiceIsRestartedOnlyOnceEveryFileItNamesIsWritten(t *testing.T) { // Only a service moves, and only to just after the last resource it names — under restart-on or // reload-on, in its own module or another's. Everything else keeps its declared place, and a name // not in the declaration is no reason to move. -func TestAServiceIsOrderedAfterWhatItNamesAndNothingElseMoves(t *testing.T) { +func testAServiceIsOrderedAfterWhatItNamesAndNothingElseMoves(t *testing.T) { d := parse(t, `{"declaration":1,"resources":[ {"id":"a.dir","type":"directory","path":"/tmp/a"}, {"id":"a.runtime","type":"service","unit":"docker.service","state":"running","reload-on":["b.daemon"]}, @@ -108,3 +108,9 @@ func TestAServiceIsOrderedAfterWhatItNamesAndNothingElseMoves(t *testing.T) { t.Errorf("ordered\n %s\nwant\n %s", strings.Join(got, " "), want) } } + +// TestRestartOrder runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRestartOrder(t *testing.T) { + t.Run("AServiceIsRestartedOnlyOnceEveryFileItNamesIsWritten", testAServiceIsRestartedOnlyOnceEveryFileItNamesIsWritten) + t.Run("AServiceIsOrderedAfterWhatItNamesAndNothingElseMoves", testAServiceIsOrderedAfterWhatItNamesAndNothingElseMoves) +} diff --git a/internal/apply/runonce_test.go b/internal/apply/runonce_test.go index ec82a65e..55109e7d 100644 --- a/internal/apply/runonce_test.go +++ b/internal/apply/runonce_test.go @@ -26,7 +26,7 @@ func nameOf(args []string) string { return "" } -func TestARunOnceStepIsRunToCompletionNotLeftRunning(t *testing.T) { +func testARunOnceStepIsRunToCompletionNotLeftRunning(t *testing.T) { // The difference between a step and a service is that a step is run in the foreground and its // exit code is the answer. So the host must not pass --detach (which returns before the // container exits) nor --restart (a step that is restarted is not a step). @@ -75,7 +75,7 @@ func TestARunOnceStepIsRunToCompletionNotLeftRunning(t *testing.T) { } } -func TestARunOnceStepThatExitsNonZeroFailsTheApply(t *testing.T) { +func testARunOnceStepThatExitsNonZeroFailsTheApply(t *testing.T) { // Run in the foreground, a non-zero exit is an error the runtime hands back. That must fail // the apply, not be swallowed — a seed that did not happen leaves the machine unready. run := func(ctx context.Context, name string, args ...string) (string, error) { @@ -106,7 +106,7 @@ func TestARunOnceStepThatExitsNonZeroFailsTheApply(t *testing.T) { } } -func TestAFailedRunOnceStepGatesWhatFollows(t *testing.T) { +func testAFailedRunOnceStepGatesWhatFollows(t *testing.T) { // The whole of how "before the broker starts" is enforced: the step is declared first, and a // step that did not complete stops the apply reaching the container that depends on it — the // mirror of a failed action stopping what follows. @@ -152,7 +152,7 @@ func TestAFailedRunOnceStepGatesWhatFollows(t *testing.T) { } } -func TestARunOnceStepAlreadyCompletedIsNotReRun(t *testing.T) { +func testARunOnceStepAlreadyCompletedIsNotReRun(t *testing.T) { // Its record of having happened is the digest of its declaration. A re-apply that finds the // digest already recorded does nothing — a step is not reconciled toward, it is run once. d := parseTrusted(t, `{"declaration":1,"resources":[ @@ -189,7 +189,7 @@ func TestARunOnceStepAlreadyCompletedIsNotReRun(t *testing.T) { } } -func TestARunOnceStepReRunsWhenItsDeclarationChanged(t *testing.T) { +func testARunOnceStepReRunsWhenItsDeclarationChanged(t *testing.T) { // The marker is the declaration's digest, so a changed image or environment moves it and the // step runs again — a migration or a seed that changed is a different step. d := parseTrusted(t, `{"declaration":1,"resources":[ @@ -222,7 +222,7 @@ func TestARunOnceStepReRunsWhenItsDeclarationChanged(t *testing.T) { } } -func TestARunOnceStepRunsAgainWhenWhatItReadsChanged(t *testing.T) { +func testARunOnceStepRunsAgainWhenWhatItReadsChanged(t *testing.T) { // A step that fetches a fact from a provider names the binding file it reads. What a // container reads is part of its digest, so when the provider moved and the mesh rewrote the // file, the step's marker no longer matches and it runs again (novox/hq ADR 0099) — the same @@ -277,7 +277,7 @@ func TestARunOnceStepRunsAgainWhenWhatItReadsChanged(t *testing.T) { } } -func TestAContainerNamingARunOnceStepIsRecreatedWhenItRan(t *testing.T) { +func testAContainerNamingARunOnceStepIsRecreatedWhenItRan(t *testing.T) { // The service that consumes what a step made names the step: when the step ran this pass — // fetched a new root — the running container holds the old one, and its spec did not move, // so restart-on is what brings it back with the new one (novox/hq ADR 0099). @@ -324,7 +324,7 @@ func TestAContainerNamingARunOnceStepIsRecreatedWhenItRan(t *testing.T) { } } -func TestAFailedStepGatesItsModuleAndNotTheMachine(t *testing.T) { +func testAFailedStepGatesItsModuleAndNotTheMachine(t *testing.T) { // **The blast radius of a step is its module** (novox/hq ADR 0136). A step exists to make // something true before the next thing in its own module needs it — a store seeded before the // broker starts, a schema prepared before the version that needs it runs. Stopping the whole @@ -383,7 +383,7 @@ func TestAFailedStepGatesItsModuleAndNotTheMachine(t *testing.T) { } } -func TestAResourcesOwnerIsReadToTheLastDot(t *testing.T) { +func testAResourcesOwnerIsReadToTheLastDot(t *testing.T) { // **A module's name may contain a dot.** `novox.be` is one on this mesh, so reading a resource's // owner to the first dot would make its resources belong to something called "novox" — and a gate // would skip whatever else happened to start that way. A resource's own id never contains one, @@ -406,3 +406,16 @@ func TestAResourcesOwnerIsReadToTheLastDot(t *testing.T) { } } } + +// TestRunonce runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRunonce(t *testing.T) { + t.Run("ARunOnceStepIsRunToCompletionNotLeftRunning", testARunOnceStepIsRunToCompletionNotLeftRunning) + t.Run("ARunOnceStepThatExitsNonZeroFailsTheApply", testARunOnceStepThatExitsNonZeroFailsTheApply) + t.Run("AFailedRunOnceStepGatesWhatFollows", testAFailedRunOnceStepGatesWhatFollows) + t.Run("ARunOnceStepAlreadyCompletedIsNotReRun", testARunOnceStepAlreadyCompletedIsNotReRun) + t.Run("ARunOnceStepReRunsWhenItsDeclarationChanged", testARunOnceStepReRunsWhenItsDeclarationChanged) + t.Run("ARunOnceStepRunsAgainWhenWhatItReadsChanged", testARunOnceStepRunsAgainWhenWhatItReadsChanged) + t.Run("AContainerNamingARunOnceStepIsRecreatedWhenItRan", testAContainerNamingARunOnceStepIsRecreatedWhenItRan) + t.Run("AFailedStepGatesItsModuleAndNotTheMachine", testAFailedStepGatesItsModuleAndNotTheMachine) + t.Run("AResourcesOwnerIsReadToTheLastDot", testAResourcesOwnerIsReadToTheLastDot) +} diff --git a/internal/apply/schedule_test.go b/internal/apply/schedule_test.go index 3f4b8e58..72f29a04 100644 --- a/internal/apply/schedule_test.go +++ b/internal/apply/schedule_test.go @@ -85,7 +85,7 @@ func scheduledContainer(t *testing.T, schedule string) *declaration.Container { // --- Requirement 4: installing a schedule does not run it, and the node is current at once. --- -func TestInstallingAScheduleDoesNotRunItAndReportsCurrent(t *testing.T) { +func testInstallingAScheduleDoesNotRunItAndReportsCurrent(t *testing.T) { // The deliberate inversion of run-once: the schedule is state that is present, so the apply is // current as soon as it is recorded. Installing it ensures the pinned image is present (a // scheduled step is never run at apply, so nothing else pulls it), but it NEVER runs the @@ -147,7 +147,7 @@ func TestInstallingAScheduleDoesNotRunItAndReportsCurrent(t *testing.T) { } } -func TestInstallingAScheduleEnsuresItsImageIsPresentWithoutStartingIt(t *testing.T) { +func testInstallingAScheduleEnsuresItsImageIsPresentWithoutStartingIt(t *testing.T) { // A scheduled step is never run at apply, so `docker run` — which is what pulls a service's or a // run-once step's image — never fetches it. Without an explicit pull the image is absent from the // node until the first scheduled fire, which then pays the whole pull latency and, until it runs, @@ -198,7 +198,7 @@ func TestInstallingAScheduleEnsuresItsImageIsPresentWithoutStartingIt(t *testing } } -func TestAScheduledStepDoesNotGateWhatFollows(t *testing.T) { +func testAScheduledStepDoesNotGateWhatFollows(t *testing.T) { // A run-once step gates: a failure halts what follows. A scheduled step is downstream of // convergence, so it never gates — a container declared after it is applied normally. d := parseTrusted(t, `{"declaration":1,"resources":[ @@ -241,7 +241,7 @@ func TestAScheduledStepDoesNotGateWhatFollows(t *testing.T) { // --- Requirement 5: the host fires the container when the cron is due, and not before. --- -func TestAScheduledStepRunsWhenDueAndNotBefore(t *testing.T) { +func testAScheduledStepRunsWhenDueAndNotBefore(t *testing.T) { clock := &fixedClock{now: time.Date(2026, 9, 7, 12, 0, 30, 0, time.UTC)} rec := &recordingRun{} s := NewScheduler(clock, rec.run, nil) @@ -288,7 +288,7 @@ func TestAScheduledStepRunsWhenDueAndNotBefore(t *testing.T) { // --- Requirement 6: a non-zero run is recorded and does not fail the apply or the node. --- -func TestAFailedRunIsRecordedAndDoesNotFailAnything(t *testing.T) { +func testAFailedRunIsRecordedAndDoesNotFailAnything(t *testing.T) { clock := &fixedClock{now: time.Date(2026, 9, 7, 12, 0, 30, 0, time.UTC)} var logged []string @@ -342,7 +342,7 @@ func TestAFailedRunIsRecordedAndDoesNotFailAnything(t *testing.T) { // --- Requirement 7: runs do not stack. --- -func TestASlowRunSkipsTheNextDueRunRatherThanStacking(t *testing.T) { +func testASlowRunSkipsTheNextDueRunRatherThanStacking(t *testing.T) { clock := &fixedClock{now: time.Date(2026, 9, 7, 12, 0, 30, 0, time.UTC)} started := make(chan struct{}) // fire() signals it entered the runner @@ -415,7 +415,7 @@ func TestASlowRunSkipsTheNextDueRunRatherThanStacking(t *testing.T) { // --- Sync re-establishes schedules from the declaration (novox/hq ADR 0018, 0053). --- -func TestSyncForgetsAScheduleTheDeclarationNoLongerNames(t *testing.T) { +func testSyncForgetsAScheduleTheDeclarationNoLongerNames(t *testing.T) { clock := &fixedClock{now: time.Date(2026, 9, 7, 12, 0, 30, 0, time.UTC)} rec := &recordingRun{} s := NewScheduler(clock, rec.run, nil) @@ -445,7 +445,7 @@ func TestSyncForgetsAScheduleTheDeclarationNoLongerNames(t *testing.T) { // Defends novox/hq ADR 0103: a scheduled step of a module not yet taken is not armed — run on its // cadence it would work on the predecessor's data. -func TestAScheduledStepOfAnUntakenModuleIsNotArmed(t *testing.T) { +func testAScheduledStepOfAnUntakenModuleIsNotArmed(t *testing.T) { clock := &fixedClock{now: time.Date(2026, 9, 7, 12, 0, 30, 0, time.UTC)} rec := &recordingRun{} var said []string @@ -487,3 +487,15 @@ func TestAScheduledStepOfAnUntakenModuleIsNotArmed(t *testing.T) { t.Error("a taken module's scheduled step never ran") } } + +// TestSchedule runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSchedule(t *testing.T) { + t.Run("InstallingAScheduleDoesNotRunItAndReportsCurrent", testInstallingAScheduleDoesNotRunItAndReportsCurrent) + t.Run("InstallingAScheduleEnsuresItsImageIsPresentWithoutStartingIt", testInstallingAScheduleEnsuresItsImageIsPresentWithoutStartingIt) + t.Run("AScheduledStepDoesNotGateWhatFollows", testAScheduledStepDoesNotGateWhatFollows) + t.Run("AScheduledStepRunsWhenDueAndNotBefore", testAScheduledStepRunsWhenDueAndNotBefore) + t.Run("AFailedRunIsRecordedAndDoesNotFailAnything", testAFailedRunIsRecordedAndDoesNotFailAnything) + t.Run("ASlowRunSkipsTheNextDueRunRatherThanStacking", testASlowRunSkipsTheNextDueRunRatherThanStacking) + t.Run("SyncForgetsAScheduleTheDeclarationNoLongerNames", testSyncForgetsAScheduleTheDeclarationNoLongerNames) + t.Run("AScheduledStepOfAnUntakenModuleIsNotArmed", testAScheduledStepOfAnUntakenModuleIsNotArmed) +} diff --git a/internal/apply/sealed_test.go b/internal/apply/sealed_test.go index 388a7ea2..9922117b 100644 --- a/internal/apply/sealed_test.go +++ b/internal/apply/sealed_test.go @@ -44,7 +44,7 @@ func sealedFile(t *testing.T, path, sealed string) *declaration.Declaration { return d } -func TestASealedFileIsOpenedAndWritten(t *testing.T) { +func testASealedFileIsOpenedAndWritten(t *testing.T) { key, err := identity.GenerateSealingKey() if err != nil { t.Fatal(err) @@ -70,7 +70,7 @@ func TestASealedFileIsOpenedAndWritten(t *testing.T) { } } -func TestASecretIsNotWorldReadableByDefault(t *testing.T) { +func testASecretIsNotWorldReadableByDefault(t *testing.T) { // An ordinary file defaults to 0644, which for a credential is the whole problem. The default // differs because the consequence differs; an explicit mode still wins, since a module may // need its own user to read it and only the module knows which. @@ -91,7 +91,7 @@ func TestASecretIsNotWorldReadableByDefault(t *testing.T) { } } -func TestSomethingSealedToAnotherNodeIsRefused(t *testing.T) { +func testSomethingSealedToAnotherNodeIsRefused(t *testing.T) { // Refused, not skipped, and refused before anything is written. A machine that quietly does // not apply the one resource carrying a credential looks configured and cannot connect. mine, _ := identity.GenerateSealingKey() @@ -110,7 +110,7 @@ func TestSomethingSealedToAnotherNodeIsRefused(t *testing.T) { } } -func TestANodeWithNoSealingKeyRefusesRatherThanSkipping(t *testing.T) { +func testANodeWithNoSealingKeyRefusesRatherThanSkipping(t *testing.T) { key, _ := identity.GenerateSealingKey() dir := t.TempDir() d := sealedFile(t, dir+"/db.json", sealedTo(t, key, "secret")) @@ -124,7 +124,7 @@ func TestANodeWithNoSealingKeyRefusesRatherThanSkipping(t *testing.T) { } } -func TestTheSecretIsNeverInWhatTheMeshIsToldBack(t *testing.T) { +func testTheSecretIsNeverInWhatTheMeshIsToldBack(t *testing.T) { // The node reports what it applied, and that report goes over the same broker the sealing was // for. A digest is a fact about the file; the file is not. key, _ := identity.GenerateSealingKey() @@ -144,7 +144,7 @@ func TestTheSecretIsNeverInWhatTheMeshIsToldBack(t *testing.T) { } } -func TestASealedFileStillNoticesAHandEdit(t *testing.T) { +func testASealedFileStillNoticesAHandEdit(t *testing.T) { // Drift detection must survive not holding the plaintext. It does, because what is recorded // is a digest of what was written rather than what was written. key, _ := identity.GenerateSealingKey() @@ -173,7 +173,7 @@ func TestASealedFileStillNoticesAHandEdit(t *testing.T) { } } -func TestContentAndSealedTogetherIsRefused(t *testing.T) { +func testContentAndSealedTogetherIsRefused(t *testing.T) { // Otherwise nobody can tell by looking whether what landed on the machine was the secret or // the placeholder. _, err := declaration.Parse([]byte(`{"declaration":1,"resources":[ @@ -185,3 +185,14 @@ func TestContentAndSealedTogetherIsRefused(t *testing.T) { t.Fatalf("unhelpful refusal: %v", err) } } + +// TestSealed runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSealed(t *testing.T) { + t.Run("ASealedFileIsOpenedAndWritten", testASealedFileIsOpenedAndWritten) + t.Run("ASecretIsNotWorldReadableByDefault", testASecretIsNotWorldReadableByDefault) + t.Run("SomethingSealedToAnotherNodeIsRefused", testSomethingSealedToAnotherNodeIsRefused) + t.Run("ANodeWithNoSealingKeyRefusesRatherThanSkipping", testANodeWithNoSealingKeyRefusesRatherThanSkipping) + t.Run("TheSecretIsNeverInWhatTheMeshIsToldBack", testTheSecretIsNeverInWhatTheMeshIsToldBack) + t.Run("ASealedFileStillNoticesAHandEdit", testASealedFileStillNoticesAHandEdit) + t.Run("ContentAndSealedTogetherIsRefused", testContentAndSealedTogetherIsRefused) +} diff --git a/internal/apply/stateless_test.go b/internal/apply/stateless_test.go index 896af58f..90492b8b 100644 --- a/internal/apply/stateless_test.go +++ b/internal/apply/stateless_test.go @@ -53,7 +53,7 @@ func touched(commands []string) []string { return changing } -func TestAStatelessServiceRunningIsReloadedForItsTrigger(t *testing.T) { +func testAStatelessServiceRunningIsReloadedForItsTrigger(t *testing.T) { path := filepath.Join(t.TempDir(), "mesh.conf") var commands []string report, _, err := Apply(context.Background(), archHost(t), @@ -76,7 +76,7 @@ func TestAStatelessServiceRunningIsReloadedForItsTrigger(t *testing.T) { } } -func TestAStatelessServiceNotRunningIsLeftSo(t *testing.T) { +func testAStatelessServiceNotRunningIsLeftSo(t *testing.T) { path := filepath.Join(t.TempDir(), "mesh.conf") for _, triggers := range []string{`"reload-on":["uplink.conf"]`, `"restart-on":["uplink.conf"]`} { var commands []string @@ -96,7 +96,7 @@ func TestAStatelessServiceNotRunningIsLeftSo(t *testing.T) { } } -func TestAStatelessServiceIsRestartedOnlyForItsRestartTrigger(t *testing.T) { +func testAStatelessServiceIsRestartedOnlyForItsRestartTrigger(t *testing.T) { path := filepath.Join(t.TempDir(), "mesh.conf") var commands []string d := parse(t, statelessDecl(path, "x\n", `"restart-on":["uplink.conf"]`)) @@ -123,7 +123,7 @@ func TestAStatelessServiceIsRestartedOnlyForItsRestartTrigger(t *testing.T) { } } -func TestAStatelessServiceUndeclaredIsForgottenNotStopped(t *testing.T) { +func testAStatelessServiceUndeclaredIsForgottenNotStopped(t *testing.T) { path := filepath.Join(t.TempDir(), "mesh.conf") var commands []string _, state, err := Apply(context.Background(), archHost(t), @@ -153,7 +153,7 @@ func TestAStatelessServiceUndeclaredIsForgottenNotStopped(t *testing.T) { } } -func TestAStatelessServiceIsNeverHeldOnAnAdoptedNode(t *testing.T) { +func testAStatelessServiceIsNeverHeldOnAnAdoptedNode(t *testing.T) { path := filepath.Join(t.TempDir(), "mesh.conf") resources := fmt.Sprintf(`{"id":"uplink.conf","type":"file","path":%q,"into":"block","content":"x\n"}, {"id":"uplink.manager","type":"service","unit":"NetworkManager.service","reload-on":["uplink.conf"]}`, path) @@ -190,3 +190,12 @@ func hasStep(steps []Step, verb, id string) bool { } return false } + +// TestStateless runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestStateless(t *testing.T) { + t.Run("AStatelessServiceRunningIsReloadedForItsTrigger", testAStatelessServiceRunningIsReloadedForItsTrigger) + t.Run("AStatelessServiceNotRunningIsLeftSo", testAStatelessServiceNotRunningIsLeftSo) + t.Run("AStatelessServiceIsRestartedOnlyForItsRestartTrigger", testAStatelessServiceIsRestartedOnlyForItsRestartTrigger) + t.Run("AStatelessServiceUndeclaredIsForgottenNotStopped", testAStatelessServiceUndeclaredIsForgottenNotStopped) + t.Run("AStatelessServiceIsNeverHeldOnAnAdoptedNode", testAStatelessServiceIsNeverHeldOnAnAdoptedNode) +} diff --git a/internal/apply/step_failed_test.go b/internal/apply/step_failed_test.go index aa73c89b..48fe25f4 100644 --- a/internal/apply/step_failed_test.go +++ b/internal/apply/step_failed_test.go @@ -92,7 +92,7 @@ func skippedIn(r Report, id string) bool { return false } -func TestAStepThatFailedRunsAgainAndKeepsItsModuleGated(t *testing.T) { +func testAStepThatFailedRunsAgainAndKeepsItsModuleGated(t *testing.T) { b := newStepBed(t) _, known, err := b.apply(store.State{}, "good") if err != nil || b.starts != 1 || b.after() != "good" { @@ -143,7 +143,7 @@ func TestAStepThatFailedRunsAgainAndKeepsItsModuleGated(t *testing.T) { } } -func TestAStepThatNeverFailedRunsNoMoreThanBefore(t *testing.T) { +func testAStepThatNeverFailedRunsNoMoreThanBefore(t *testing.T) { // Every node runs many steps: one that passes must run once per change, and not on every apply. b := newStepBed(t) _, known, err := b.apply(store.State{}, "one") @@ -161,7 +161,7 @@ func TestAStepThatNeverFailedRunsNoMoreThanBefore(t *testing.T) { } } -func TestAContainerStepThatFailedRunsAgain(t *testing.T) { +func testAContainerStepThatFailedRunsAgain(t *testing.T) { // A run-once container gates its module the same way (novox/hq ADR 0052, ADR 0136). It already ran // again before issue 467 was fixed, because what it is declared with is part of what it is run as: // held here so it stays that way. @@ -210,7 +210,7 @@ func TestAContainerStepThatFailedRunsAgain(t *testing.T) { } } -func TestAStepWhoseBundleCouldNotBeFetchedIsNotRunAgainForIt(t *testing.T) { +func testAStepWhoseBundleCouldNotBeFetchedIsNotRunAgainForIt(t *testing.T) { // A fetch that fails is a failure of the step, and gates its module, but the step was never started: // it did not refuse anything, and its last success stands. Cleared for it, every step on a machine // would run again once the artifact store came back from an outage. @@ -236,7 +236,7 @@ func TestAStepWhoseBundleCouldNotBeFetchedIsNotRunAgainForIt(t *testing.T) { } } -func TestAStepPassingAfterAFailureSaysItWasUpdated(t *testing.T) { +func testAStepPassingAfterAFailureSaysItWasUpdated(t *testing.T) { b := newStepBed(t) _, known, _ := b.apply(store.State{}, "good") b.refuse = true @@ -252,3 +252,12 @@ func TestAStepPassingAfterAFailureSaysItWasUpdated(t *testing.T) { } } } + +// TestStepFailed runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestStepFailed(t *testing.T) { + t.Run("AStepThatFailedRunsAgainAndKeepsItsModuleGated", testAStepThatFailedRunsAgainAndKeepsItsModuleGated) + t.Run("AStepThatNeverFailedRunsNoMoreThanBefore", testAStepThatNeverFailedRunsNoMoreThanBefore) + t.Run("AContainerStepThatFailedRunsAgain", testAContainerStepThatFailedRunsAgain) + t.Run("AStepWhoseBundleCouldNotBeFetchedIsNotRunAgainForIt", testAStepWhoseBundleCouldNotBeFetchedIsNotRunAgainForIt) + t.Run("AStepPassingAfterAFailureSaysItWasUpdated", testAStepPassingAfterAFailureSaysItWasUpdated) +} diff --git a/internal/apply/store_away_test.go b/internal/apply/store_away_test.go index 8dcea3ad..c6508b2d 100644 --- a/internal/apply/store_away_test.go +++ b/internal/apply/store_away_test.go @@ -126,7 +126,7 @@ func (s *saying) all() string { s.mu.Lock(); defer s.mu.Unlock(); return str // On the store's own machine: an apply that reaches the store's archives while the collector holds the // server still waits for the window, and applies once it closes — no failure, nothing held. -func TestAnApplyOnTheStoresMachineWaitsForItsWindow(t *testing.T) { +func testAnApplyOnTheStoresMachineWaitsForItsWindow(t *testing.T) { patiently(t, time.Second) body, digest := anArchive(t, map[string]string{"bin/postgres-tools": "#!/bin/sh"}) st := newPretendStore(t, body) @@ -180,7 +180,7 @@ func TestAnApplyOnTheStoresMachineWaitsForItsWindow(t *testing.T) { // And the order on the store's machine: a collector due while an apply is in flight opens its window only // once the apply ended — so an apply that started before it never finds the server stopped under it. -func TestAWindowOpensOnlyOnceTheApplyInFlightEnded(t *testing.T) { +func testAWindowOpensOnlyOnceTheApplyInFlightEnded(t *testing.T) { patiently(t, time.Second) d := aStoreWithACollector(t) m := newRegistryMachine(containerSpec(d.Resources[0].(*declaration.Container), inputs{})) @@ -237,7 +237,7 @@ func TestAWindowOpensOnlyOnceTheApplyInFlightEnded(t *testing.T) { // On every other machine the store's window is not known: a store that does not answer is fetched again // with backoff, and the bundle arrives once the store is back. -func TestAnApplyElsewhereWaitsABoundedWhileForTheStore(t *testing.T) { +func testAnApplyElsewhereWaitsABoundedWhileForTheStore(t *testing.T) { patiently(t, 5*time.Second) body, digest := anArchive(t, map[string]string{"bin/tools": "#!/bin/sh"}) st := newPretendStore(t, body) @@ -266,7 +266,7 @@ const aDigest = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa // A store really down costs one bounded wait per apply, not one per bundle; and an answer — a blob the // store does not have — fails at once, as it always did. -func TestAStoreThatStaysAwayCostsOneBoundedWait(t *testing.T) { +func testAStoreThatStaysAwayCostsOneBoundedWait(t *testing.T) { patiently(t, 80*time.Millisecond) st := newPretendStore(t, []byte("x")) st.stop() @@ -330,3 +330,11 @@ func TestAStoreThatStaysAwayCostsOneBoundedWait(t *testing.T) { t.Fatalf("other bytes told %q: want the declared digest forgotten once", told) } } + +// TestStoreAway runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestStoreAway(t *testing.T) { + t.Run("AnApplyOnTheStoresMachineWaitsForItsWindow", testAnApplyOnTheStoresMachineWaitsForItsWindow) + t.Run("AWindowOpensOnlyOnceTheApplyInFlightEnded", testAWindowOpensOnlyOnceTheApplyInFlightEnded) + t.Run("AnApplyElsewhereWaitsABoundedWhileForTheStore", testAnApplyElsewhereWaitsABoundedWhileForTheStore) + t.Run("AStoreThatStaysAwayCostsOneBoundedWait", testAStoreThatStaysAwayCostsOneBoundedWait) +} diff --git a/internal/apply/takeover_test.go b/internal/apply/takeover_test.go index 8c8a325f..11938141 100644 --- a/internal/apply/takeover_test.go +++ b/internal/apply/takeover_test.go @@ -73,7 +73,7 @@ func aHubInUse(t *testing.T) (dir, config, mesh, keyFile string, m *machine) { return dir, config, mesh, keyFile, m } -func TestTheFoundTunnelIsStoppedNeverFlushedAndItsConfigurationKept(t *testing.T) { +func testTheFoundTunnelIsStoppedNeverFlushedAndItsConfigurationKept(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) report, state := applyAdopted(t, aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1"), store.State{}, m, dir) @@ -132,7 +132,7 @@ func TestTheFoundTunnelIsStoppedNeverFlushedAndItsConfigurationKept(t *testing.T } } -func TestNothingIsStoppedUntilTheMeshsInterfaceCanReplaceTheFoundOne(t *testing.T) { +func testNothingIsStoppedUntilTheMeshsInterfaceCanReplaceTheFoundOne(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) otherKey := filepath.Join(dir, "other.key") k, _ := ecdh.X25519().GenerateKey(rand.Reader) @@ -170,7 +170,7 @@ func TestNothingIsStoppedUntilTheMeshsInterfaceCanReplaceTheFoundOne(t *testing. } } -func TestAMeshInterfaceThatFailsToStartGivesTheFoundOneBack(t *testing.T) { +func testAMeshInterfaceThatFailsToStartGivesTheFoundOneBack(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) m.units["wg-quick@mesh0"].wontStart = true report, _, err := ApplyKeeping(t.Context(), archHost(t), aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1"), @@ -190,7 +190,7 @@ func TestAMeshInterfaceThatFailsToStartGivesTheFoundOneBack(t *testing.T) { } } -func TestATakeoverIsSteadyAndAFoundUnitUpAgainIsSaidNotStopped(t *testing.T) { +func testATakeoverIsSteadyAndAFoundUnitUpAgainIsSaidNotStopped(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1") _, state := applyAdopted(t, d, store.State{}, m, dir) @@ -223,7 +223,7 @@ func TestATakeoverIsSteadyAndAFoundUnitUpAgainIsSaidNotStopped(t *testing.T) { } } -func TestAFoundInterfaceRaisedByHandIsRefusedNamingTheRemedy(t *testing.T) { +func testAFoundInterfaceRaisedByHandIsRefusedNamingTheRemedy(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) // The unit is not running, yet the interface is up: the predecessor raised it by hand. m.units["wg-quick@wg0"].active = "inactive" @@ -254,7 +254,7 @@ func TestAFoundInterfaceRaisedByHandIsRefusedNamingTheRemedy(t *testing.T) { } } -func TestATakeoverIsRefusedOnAConvergedDeclaration(t *testing.T) { +func testATakeoverIsRefusedOnAConvergedDeclaration(t *testing.T) { _, err := declaration.Parse([]byte(`{"declaration":1,"resources":[ {"id":"up","type":"service","unit":"wg-quick@mesh0","state":"running", "takes-over":{"interface":"wg0","unit":"wg-quick@wg0","config":"/etc/wireguard/wg0.conf"}}]}`)) @@ -272,7 +272,7 @@ const takesOverID = "mesh-wireguard.overlay-up.takes-over" // handshaken is `wg show mesh0 latest-handshakes` with one of the two peers through. const handshaken = "PEER-A=\t1790000000\nPEER-B=\t0\n" -func TestAProvenTakeRetiresTheFoundConfiguration(t *testing.T) { +func testAProvenTakeRetiresTheFoundConfiguration(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) m.handshakes = handshaken report, state := applyAdopted(t, aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1"), store.State{}, m, dir) @@ -307,7 +307,7 @@ func TestAProvenTakeRetiresTheFoundConfiguration(t *testing.T) { } } -func TestATakeNotProvenKeepsTheFoundConfigurationAndSaysSo(t *testing.T) { +func testATakeNotProvenKeepsTheFoundConfigurationAndSaysSo(t *testing.T) { cases := map[string]struct { handshakes string fail error @@ -351,7 +351,7 @@ func TestATakeNotProvenKeepsTheFoundConfigurationAndSaysSo(t *testing.T) { } } -func TestAFoundConfigurationWhoseKeptOriginalIsMissingIsNotRetired(t *testing.T) { +func testAFoundConfigurationWhoseKeptOriginalIsMissingIsNotRetired(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1") _, state := applyAdopted(t, d, store.State{}, m, dir) @@ -377,7 +377,7 @@ func TestAFoundConfigurationWhoseKeptOriginalIsMissingIsNotRetired(t *testing.T) } } -func TestAFoundConfigurationRewrittenSinceItWasFoundIsKeptAgainBeforeItGoes(t *testing.T) { +func testAFoundConfigurationRewrittenSinceItWasFoundIsKeptAgainBeforeItGoes(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1") _, state := applyAdopted(t, d, store.State{}, m, dir) @@ -407,7 +407,7 @@ func TestAFoundConfigurationRewrittenSinceItWasFoundIsKeptAgainBeforeItGoes(t *t } } -func TestARetiredTakeIsSteadyAndItsFoundUnitFindsNothingToDo(t *testing.T) { +func testARetiredTakeIsSteadyAndItsFoundUnitFindsNothingToDo(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) m.handshakes = handshaken d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1") @@ -449,7 +449,7 @@ func TestARetiredTakeIsSteadyAndItsFoundUnitFindsNothingToDo(t *testing.T) { } } -func TestUndeclaringThePrivateNetworkAfterRetirementBringsNothingBack(t *testing.T) { +func testUndeclaringThePrivateNetworkAfterRetirementBringsNothingBack(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) m.handshakes = handshaken d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1") @@ -481,7 +481,7 @@ func TestUndeclaringThePrivateNetworkAfterRetirementBringsNothingBack(t *testing } } -func TestAPlanSaysTheFoundConfigurationIsRetiredWhenTheTakeIsProven(t *testing.T) { +func testAPlanSaysTheFoundConfigurationIsRetiredWhenTheTakeIsProven(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1") @@ -524,7 +524,7 @@ func keptCopies(t *testing.T, dir string) []string { return kept } -func TestAConfigurationPutBackIsRetiredAgainOnItsFirstOriginalAndSettles(t *testing.T) { +func testAConfigurationPutBackIsRetiredAgainOnItsFirstOriginalAndSettles(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) m.handshakes = handshaken d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1") @@ -597,7 +597,7 @@ func TestAConfigurationPutBackIsRetiredAgainOnItsFirstOriginalAndSettles(t *test } } -func TestOnlyWgQuicksOwnConfigurationIsRetired(t *testing.T) { +func testOnlyWgQuicksOwnConfigurationIsRetired(t *testing.T) { // Not under the wireguard directory. dir, config, mesh, keyFile, m := aHubInUse(t) wireguardDir = filepath.Join(dir, "elsewhere") @@ -624,7 +624,7 @@ func TestOnlyWgQuicksOwnConfigurationIsRetired(t *testing.T) { } } -func TestAFoundConfigurationThatIsALinkIsKeptAndLeftToAPerson(t *testing.T) { +func testAFoundConfigurationThatIsALinkIsKeptAndLeftToAPerson(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) target := filepath.Join(dir, "predecessor", "hub.conf") if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil { @@ -657,7 +657,7 @@ func TestAFoundConfigurationThatIsALinkIsKeptAndLeftToAPerson(t *testing.T) { } } -func TestARetirementWhoseRecordWasNeverSavedIsRecordedByTheNextApply(t *testing.T) { +func testARetirementWhoseRecordWasNeverSavedIsRecordedByTheNextApply(t *testing.T) { dir, config, mesh, keyFile, m := aHubInUse(t) d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1") _, state := applyAdopted(t, d, store.State{}, m, dir) @@ -679,7 +679,7 @@ func TestARetirementWhoseRecordWasNeverSavedIsRecordedByTheNextApply(t *testing. } } -func TestARemovalThatFailsKeepsTheFileAndTheHold(t *testing.T) { +func testARemovalThatFailsKeepsTheFileAndTheHold(t *testing.T) { if os.Geteuid() == 0 { t.Skip("root removes from a directory it may not write to") } @@ -713,3 +713,25 @@ func TestARemovalThatFailsKeepsTheFileAndTheHold(t *testing.T) { t.Errorf("the failed removal is not said: %q", report.Tunnel.Note) } } + +// TestTakeover runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestTakeover(t *testing.T) { + t.Run("TheFoundTunnelIsStoppedNeverFlushedAndItsConfigurationKept", testTheFoundTunnelIsStoppedNeverFlushedAndItsConfigurationKept) + t.Run("NothingIsStoppedUntilTheMeshsInterfaceCanReplaceTheFoundOne", testNothingIsStoppedUntilTheMeshsInterfaceCanReplaceTheFoundOne) + t.Run("AMeshInterfaceThatFailsToStartGivesTheFoundOneBack", testAMeshInterfaceThatFailsToStartGivesTheFoundOneBack) + t.Run("ATakeoverIsSteadyAndAFoundUnitUpAgainIsSaidNotStopped", testATakeoverIsSteadyAndAFoundUnitUpAgainIsSaidNotStopped) + t.Run("AFoundInterfaceRaisedByHandIsRefusedNamingTheRemedy", testAFoundInterfaceRaisedByHandIsRefusedNamingTheRemedy) + t.Run("ATakeoverIsRefusedOnAConvergedDeclaration", testATakeoverIsRefusedOnAConvergedDeclaration) + t.Run("AProvenTakeRetiresTheFoundConfiguration", testAProvenTakeRetiresTheFoundConfiguration) + t.Run("ATakeNotProvenKeepsTheFoundConfigurationAndSaysSo", testATakeNotProvenKeepsTheFoundConfigurationAndSaysSo) + t.Run("AFoundConfigurationWhoseKeptOriginalIsMissingIsNotRetired", testAFoundConfigurationWhoseKeptOriginalIsMissingIsNotRetired) + t.Run("AFoundConfigurationRewrittenSinceItWasFoundIsKeptAgainBeforeItGoes", testAFoundConfigurationRewrittenSinceItWasFoundIsKeptAgainBeforeItGoes) + t.Run("ARetiredTakeIsSteadyAndItsFoundUnitFindsNothingToDo", testARetiredTakeIsSteadyAndItsFoundUnitFindsNothingToDo) + t.Run("UndeclaringThePrivateNetworkAfterRetirementBringsNothingBack", testUndeclaringThePrivateNetworkAfterRetirementBringsNothingBack) + t.Run("APlanSaysTheFoundConfigurationIsRetiredWhenTheTakeIsProven", testAPlanSaysTheFoundConfigurationIsRetiredWhenTheTakeIsProven) + t.Run("AConfigurationPutBackIsRetiredAgainOnItsFirstOriginalAndSettles", testAConfigurationPutBackIsRetiredAgainOnItsFirstOriginalAndSettles) + t.Run("OnlyWgQuicksOwnConfigurationIsRetired", testOnlyWgQuicksOwnConfigurationIsRetired) + t.Run("AFoundConfigurationThatIsALinkIsKeptAndLeftToAPerson", testAFoundConfigurationThatIsALinkIsKeptAndLeftToAPerson) + t.Run("ARetirementWhoseRecordWasNeverSavedIsRecordedByTheNextApply", testARetirementWhoseRecordWasNeverSavedIsRecordedByTheNextApply) + t.Run("ARemovalThatFailsKeepsTheFileAndTheHold", testARemovalThatFailsKeepsTheFileAndTheHold) +} diff --git a/internal/apply/user_test.go b/internal/apply/user_test.go index 8459c46f..fea60bd7 100644 --- a/internal/apply/user_test.go +++ b/internal/apply/user_test.go @@ -97,7 +97,7 @@ func userWith(shell string) string { return `{"id":"shell.login","type":"user","name":"operator","shell":"` + shell + `"}` } -func TestAnUndeclaredUserNoLongerStopsTheApply(t *testing.T) { +func testAnUndeclaredUserNoLongerStopsTheApply(t *testing.T) { // Before issue 228 the host had no removal for a user, the orphan failed with "no way to // remove", and an orphan's failure aborts the apply before its first resource — on every // apply after, since the record stayed. @@ -124,7 +124,7 @@ func TestAnUndeclaredUserNoLongerStopsTheApply(t *testing.T) { } } -func TestTheShellFoundIsGivenBackWhenTheUserIsUndeclared(t *testing.T) { +func testTheShellFoundIsGivenBackWhenTheUserIsUndeclared(t *testing.T) { dir := shellsOn(t, []string{"bash", "zsh"}) l := &logins{shells: map[string]string{"operator": dir + "/bash"}} _, state, err := applyUsers(t, l, store.State{}, userWith(dir+"/zsh")) @@ -153,7 +153,7 @@ func TestTheShellFoundIsGivenBackWhenTheUserIsUndeclared(t *testing.T) { } } -func TestAShellAPersonChangedSinceIsLeftAlone(t *testing.T) { +func testAShellAPersonChangedSinceIsLeftAlone(t *testing.T) { dir := shellsOn(t, []string{"bash", "zsh", "fish"}) l := &logins{shells: map[string]string{"operator": dir + "/bash"}} _, state, err := applyUsers(t, l, store.State{}, userWith(dir+"/zsh")) @@ -175,7 +175,7 @@ func TestAShellAPersonChangedSinceIsLeftAlone(t *testing.T) { } } -func TestAFoundShellThatIsGoneIsNotGivenBack(t *testing.T) { +func testAFoundShellThatIsGoneIsNotGivenBack(t *testing.T) { // Giving back a shell uninstalled since would break the logins the giving back is for. dir := shellsOn(t, []string{"bash", "zsh"}) l := &logins{shells: map[string]string{"operator": dir + "/bash"}} @@ -199,7 +199,7 @@ func TestAFoundShellThatIsGoneIsNotGivenBack(t *testing.T) { } } -func TestAShellThatIsMissingOrUnlistedIsRefusedBeforeItIsSet(t *testing.T) { +func testAShellThatIsMissingOrUnlistedIsRefusedBeforeItIsSet(t *testing.T) { dir := shellsOn(t, []string{"bash"}, "unlisted") for name, shell := range map[string]string{ "missing": dir + "/zsh", @@ -235,7 +235,7 @@ func TestAShellThatIsMissingOrUnlistedIsRefusedBeforeItIsSet(t *testing.T) { }) } -func TestAnAccountThatRefusesLoginsNeedNotBeListed(t *testing.T) { +func testAnAccountThatRefusesLoginsNeedNotBeListed(t *testing.T) { // A service's account has nologin, which no distribution lists among its shells; refusing it // would refuse the controller's own account. dir := shellsOn(t, []string{"bash"}, "nologin") @@ -248,7 +248,7 @@ func TestAnAccountThatRefusesLoginsNeedNotBeListed(t *testing.T) { } } -func TestACreatedAccountSurvivesItsRemoval(t *testing.T) { +func testACreatedAccountSurvivesItsRemoval(t *testing.T) { dir := shellsOn(t, []string{"zsh"}) l := &logins{shells: map[string]string{}} report, state, err := applyUsers(t, l, store.State{}, userWith(dir+"/zsh")) @@ -271,7 +271,7 @@ func TestACreatedAccountSurvivesItsRemoval(t *testing.T) { } } -func TestTheFoundShellIsNotOverwrittenByASecondChange(t *testing.T) { +func testTheFoundShellIsNotOverwrittenByASecondChange(t *testing.T) { // The holding moves from one shell module to another: what is given back in the end is the // shell from before the mesh, not the first module's. dir := shellsOn(t, []string{"bash", "zsh", "fish"}) @@ -297,7 +297,7 @@ func TestTheFoundShellIsNotOverwrittenByASecondChange(t *testing.T) { // An account declared never to become root is never a system account taken over (novox/hq ADR 0266): the // controller cannot tell a service's account from a free name, so the node-engine refuses it, touching nothing. -func TestARootNeverAccountIsNotASystemAccountTakenOver(t *testing.T) { +func testARootNeverAccountIsNotASystemAccountTakenOver(t *testing.T) { l := &logins{shells: map[string]string{}} run := func(ctx context.Context, name string, args ...string) (string, error) { if name == "getent" && args[len(args)-1] == "postgres" { @@ -323,3 +323,16 @@ func TestARootNeverAccountIsNotASystemAccountTakenOver(t *testing.T) { t.Fatalf("a login's account is taken: %v", err) } } + +// TestUser runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestUser(t *testing.T) { + t.Run("AnUndeclaredUserNoLongerStopsTheApply", testAnUndeclaredUserNoLongerStopsTheApply) + t.Run("TheShellFoundIsGivenBackWhenTheUserIsUndeclared", testTheShellFoundIsGivenBackWhenTheUserIsUndeclared) + t.Run("AShellAPersonChangedSinceIsLeftAlone", testAShellAPersonChangedSinceIsLeftAlone) + t.Run("AFoundShellThatIsGoneIsNotGivenBack", testAFoundShellThatIsGoneIsNotGivenBack) + t.Run("AShellThatIsMissingOrUnlistedIsRefusedBeforeItIsSet", testAShellThatIsMissingOrUnlistedIsRefusedBeforeItIsSet) + t.Run("AnAccountThatRefusesLoginsNeedNotBeListed", testAnAccountThatRefusesLoginsNeedNotBeListed) + t.Run("ACreatedAccountSurvivesItsRemoval", testACreatedAccountSurvivesItsRemoval) + t.Run("TheFoundShellIsNotOverwrittenByASecondChange", testTheFoundShellIsNotOverwrittenByASecondChange) + t.Run("ARootNeverAccountIsNotASystemAccountTakenOver", testARootNeverAccountIsNotASystemAccountTakenOver) +} diff --git a/internal/apply/userscope_test.go b/internal/apply/userscope_test.go index ad5a56d6..0cbe6299 100644 --- a/internal/apply/userscope_test.go +++ b/internal/apply/userscope_test.go @@ -157,7 +157,7 @@ func outcomeFor(r Report, id string) Outcome { return Outcome{} } -func TestAUserScopedUnitIsAppliedThroughTheAccountsManager(t *testing.T) { +func testAUserScopedUnitIsAppliedThroughTheAccountsManager(t *testing.T) { a := newAccount(t, true) report, known, err := applyAccount(t, declaring(watcher), store.State{}, a) if err != nil { @@ -179,7 +179,7 @@ func TestAUserScopedUnitIsAppliedThroughTheAccountsManager(t *testing.T) { } } -func TestASystemUnitIsUntouchedByTheScope(t *testing.T) { +func testASystemUnitIsUntouchedByTheScope(t *testing.T) { var commands []string decl := `{"declaration":1,"resources":[ {"id":"x.daemon","type":"service","unit":"sshd.service","state":"running","boot":"enabled"} @@ -197,7 +197,7 @@ func TestASystemUnitIsUntouchedByTheScope(t *testing.T) { // With nobody logged in and no lingering, the unit waits: not a failure, nothing recorded, and the // account's manager never asked — asking it would log the account in. -func TestAUserUnitWaitsForItsAccountsManagerAndIsAppliedWhenItRuns(t *testing.T) { +func testAUserUnitWaitsForItsAccountsManagerAndIsAppliedWhenItRuns(t *testing.T) { a := newAccount(t, false) report, known, err := applyAccount(t, declaring(watcher), store.State{}, a) if err != nil { @@ -233,7 +233,7 @@ func TestAUserUnitWaitsForItsAccountsManagerAndIsAppliedWhenItRuns(t *testing.T) // A unit applied before, its account since logged out: the record stays exactly as it was, what // was found included, so a later removal still gives back what was there before the mesh. -func TestAWaitingUnitKeepsItsRecord(t *testing.T) { +func testAWaitingUnitKeepsItsRecord(t *testing.T) { a := newAccount(t, true) _, known, err := applyAccount(t, declaring(watcher), store.State{}, a) if err != nil { @@ -253,7 +253,7 @@ func TestAWaitingUnitKeepsItsRecord(t *testing.T) { // A manager that says it runs and then does not answer — the person logged out mid-apply — is the // same absence, and is said the same way. -func TestAManagerThatStopsDuringTheApplyIsWaitedFor(t *testing.T) { +func testAManagerThatStopsDuringTheApplyIsWaitedFor(t *testing.T) { a := newAccount(t, true) a.busDown = true calls := 0 @@ -277,7 +277,7 @@ func TestAManagerThatStopsDuringTheApplyIsWaitedFor(t *testing.T) { } } -func TestAUserUnitOfAnAccountTheMachineDoesNotHaveIsRefused(t *testing.T) { +func testAUserUnitOfAnAccountTheMachineDoesNotHaveIsRefused(t *testing.T) { a := newAccount(t, true) a.name = "someone-else" _, _, err := applyAccount(t, declaring(watcher), store.State{}, a) @@ -288,7 +288,7 @@ func TestAUserUnitOfAnAccountTheMachineDoesNotHaveIsRefused(t *testing.T) { // Without a manager per account — OpenRC — a user-scoped unit would otherwise be applied as the // machine's service of the same name. Refused instead. -func TestAUserUnitIsRefusedWhereTheServiceManagerHasNoAccounts(t *testing.T) { +func testAUserUnitIsRefusedWhereTheServiceManagerHasNoAccounts(t *testing.T) { alpine, err := system.For("alpine") if err != nil { t.Fatal(err) @@ -306,7 +306,7 @@ func TestAUserUnitIsRefusedWhereTheServiceManagerHasNoAccounts(t *testing.T) { // **Removal is never fatal** (the issue 162/228 wedge): with the manager away the record stays and // the outcome says it waits; the first apply that finds the manager gives the unit back. -func TestRemovingAUserUnitWithItsManagerAwayWaitsAndIsNeverFatal(t *testing.T) { +func testRemovingAUserUnitWithItsManagerAwayWaitsAndIsNeverFatal(t *testing.T) { a := newAccount(t, true) _, known, err := applyAccount(t, declaring(watcher), store.State{}, a) if err != nil { @@ -342,7 +342,7 @@ func TestRemovingAUserUnitWithItsManagerAwayWaitsAndIsNeverFatal(t *testing.T) { } // "Failed to connect to bus" from a manager that said it ran is said and retried, never fatal. -func TestRemovingAUserUnitWhoseBusDoesNotAnswerIsNotFatal(t *testing.T) { +func testRemovingAUserUnitWhoseBusDoesNotAnswerIsNotFatal(t *testing.T) { a := newAccount(t, true) _, known, err := applyAccount(t, declaring(watcher), store.State{}, a) if err != nil { @@ -361,7 +361,7 @@ func TestRemovingAUserUnitWhoseBusDoesNotAnswerIsNotFatal(t *testing.T) { } } -func TestRemovingAUserUnitOfAnAccountThatIsGoneForgetsIt(t *testing.T) { +func testRemovingAUserUnitOfAnAccountThatIsGoneForgetsIt(t *testing.T) { a := newAccount(t, true) _, known, err := applyAccount(t, declaring(watcher), store.State{}, a) if err != nil { @@ -382,7 +382,7 @@ func TestRemovingAUserUnitOfAnAccountThatIsGoneForgetsIt(t *testing.T) { // A unit file the mesh wrote under the account's own unit directory makes the unit the mesh's — and // only the account's unit of that name, never the machine's. -func TestAUserUnitsFileTheMeshWroteMakesThatUnitAndNoOtherTheMeshs(t *testing.T) { +func testAUserUnitsFileTheMeshWroteMakesThatUnitAndNoOtherTheMeshs(t *testing.T) { home := t.TempDir() was := homeOf homeOf = func(name string) (string, error) { @@ -427,7 +427,7 @@ func TestAUserUnitsFileTheMeshWroteMakesThatUnitAndNoOtherTheMeshs(t *testing.T) // Undeclared together, the account's unit whose file the mesh wrote is stopped and disabled in the // account's manager — whatever was found — and a system unit of the same name is not touched. -func TestAMeshMadeUserUnitIsStoppedInItsAccountAndTheMachinesNamesakeIsNot(t *testing.T) { +func testAMeshMadeUserUnitIsStoppedInItsAccountAndTheMachinesNamesakeIsNot(t *testing.T) { a := newAccount(t, true) home := t.TempDir() was := homeOf @@ -460,7 +460,7 @@ func TestAMeshMadeUserUnitIsStoppedInItsAccountAndTheMachinesNamesakeIsNot(t *te // A service moved from the machine's manager into an account's is two units: the machine's is given // back as it was found, through the machine's manager, and the account's is read afresh. -func TestAServiceMovedIntoAnAccountGivesTheMachinesUnitBack(t *testing.T) { +func testAServiceMovedIntoAnAccountGivesTheMachinesUnitBack(t *testing.T) { a := newAccount(t, true) a.system["i3-reload-watcher.service"] = &fakeUnit{active: "active", enabled: "enabled"} known := store.State{Resources: []store.Applied{ @@ -485,7 +485,7 @@ func TestAServiceMovedIntoAnAccountGivesTheMachinesUnitBack(t *testing.T) { // Lingering is the account's (novox/hq ADR 0177): declared, set and read back; recorded with what // was found; given back on removal while the account still has what the mesh set. -func TestLingeringIsDeclaredOnTheAccountAndGivenBack(t *testing.T) { +func testLingeringIsDeclaredOnTheAccountAndGivenBack(t *testing.T) { a := newAccount(t, false) user := `{"id":"ops.login","type":"user","name":"ops","linger":true}` report, known, err := applyAccount(t, declaring(user), store.State{}, a) @@ -529,7 +529,7 @@ func TestLingeringIsDeclaredOnTheAccountAndGivenBack(t *testing.T) { } } -func TestLingeringTheOperatorChangedSinceIsLeft(t *testing.T) { +func testLingeringTheOperatorChangedSinceIsLeft(t *testing.T) { a := newAccount(t, false) known := store.State{Resources: []store.Applied{{ID: "ops.login", Type: "user", Target: "ops", Origin: store.OriginDeclared, Linger: &store.Lingering{Found: false, Set: true}}}} @@ -546,7 +546,7 @@ func TestLingeringTheOperatorChangedSinceIsLeft(t *testing.T) { } } -func TestLingeringIsRefusedWhereTheServiceManagerHasNoAccounts(t *testing.T) { +func testLingeringIsRefusedWhereTheServiceManagerHasNoAccounts(t *testing.T) { alpine, err := system.For("alpine") if err != nil { t.Fatal(err) @@ -559,3 +559,23 @@ func TestLingeringIsRefusedWhereTheServiceManagerHasNoAccounts(t *testing.T) { t.Fatalf("not refused: %v", err) } } + +// TestUserscope runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestUserscope(t *testing.T) { + t.Run("AUserScopedUnitIsAppliedThroughTheAccountsManager", testAUserScopedUnitIsAppliedThroughTheAccountsManager) + t.Run("ASystemUnitIsUntouchedByTheScope", testASystemUnitIsUntouchedByTheScope) + t.Run("AUserUnitWaitsForItsAccountsManagerAndIsAppliedWhenItRuns", testAUserUnitWaitsForItsAccountsManagerAndIsAppliedWhenItRuns) + t.Run("AWaitingUnitKeepsItsRecord", testAWaitingUnitKeepsItsRecord) + t.Run("AManagerThatStopsDuringTheApplyIsWaitedFor", testAManagerThatStopsDuringTheApplyIsWaitedFor) + t.Run("AUserUnitOfAnAccountTheMachineDoesNotHaveIsRefused", testAUserUnitOfAnAccountTheMachineDoesNotHaveIsRefused) + t.Run("AUserUnitIsRefusedWhereTheServiceManagerHasNoAccounts", testAUserUnitIsRefusedWhereTheServiceManagerHasNoAccounts) + t.Run("RemovingAUserUnitWithItsManagerAwayWaitsAndIsNeverFatal", testRemovingAUserUnitWithItsManagerAwayWaitsAndIsNeverFatal) + t.Run("RemovingAUserUnitWhoseBusDoesNotAnswerIsNotFatal", testRemovingAUserUnitWhoseBusDoesNotAnswerIsNotFatal) + t.Run("RemovingAUserUnitOfAnAccountThatIsGoneForgetsIt", testRemovingAUserUnitOfAnAccountThatIsGoneForgetsIt) + t.Run("AUserUnitsFileTheMeshWroteMakesThatUnitAndNoOtherTheMeshs", testAUserUnitsFileTheMeshWroteMakesThatUnitAndNoOtherTheMeshs) + t.Run("AMeshMadeUserUnitIsStoppedInItsAccountAndTheMachinesNamesakeIsNot", testAMeshMadeUserUnitIsStoppedInItsAccountAndTheMachinesNamesakeIsNot) + t.Run("AServiceMovedIntoAnAccountGivesTheMachinesUnitBack", testAServiceMovedIntoAnAccountGivesTheMachinesUnitBack) + t.Run("LingeringIsDeclaredOnTheAccountAndGivenBack", testLingeringIsDeclaredOnTheAccountAndGivenBack) + t.Run("LingeringTheOperatorChangedSinceIsLeft", testLingeringTheOperatorChangedSinceIsLeft) + t.Run("LingeringIsRefusedWhereTheServiceManagerHasNoAccounts", testLingeringIsRefusedWhereTheServiceManagerHasNoAccounts) +} diff --git a/internal/apply/vault_sealed_test.go b/internal/apply/vault_sealed_test.go index 17166dbd..26ae630d 100644 --- a/internal/apply/vault_sealed_test.go +++ b/internal/apply/vault_sealed_test.go @@ -50,7 +50,7 @@ func boxOpener(key identity.SealingKey) Unseal { return func(sealed string) ([]byte, error) { return key.Open(sealed) } } -func TestAFileTheVaultSealedToThisMachineIsOpenedAndWrittenUnreadableToOthers(t *testing.T) { +func testAFileTheVaultSealedToThisMachineIsOpenedAndWrittenUnreadableToOthers(t *testing.T) { key, err := identity.GenerateSealingKey() if err != nil { t.Fatal(err) @@ -78,7 +78,7 @@ func TestAFileTheVaultSealedToThisMachineIsOpenedAndWrittenUnreadableToOthers(t } } -func TestAVaultBoxSealedToAnotherMachineIsRefusedAndNothingWritten(t *testing.T) { +func testAVaultBoxSealedToAnotherMachineIsRefusedAndNothingWritten(t *testing.T) { mine, _ := identity.GenerateSealingKey() theirs, _ := identity.GenerateSealingKey() path := t.TempDir() + "/broker" @@ -92,7 +92,7 @@ func TestAVaultBoxSealedToAnotherMachineIsRefusedAndNothingWritten(t *testing.T) } } -func TestAVaultSealedFileSaysWhatIsInItOnce(t *testing.T) { +func testAVaultSealedFileSaysWhatIsInItOnce(t *testing.T) { key, _ := identity.GenerateSealingKey() box, _ := json.Marshal(vaultSealedTo(t, key, "x")) for what, extra := range map[string]string{ @@ -110,3 +110,10 @@ func TestAVaultSealedFileSaysWhatIsInItOnce(t *testing.T) { t.Error("a box of a version the SDK does not open was accepted") } } + +// TestVaultSealed runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestVaultSealed(t *testing.T) { + t.Run("AFileTheVaultSealedToThisMachineIsOpenedAndWrittenUnreadableToOthers", testAFileTheVaultSealedToThisMachineIsOpenedAndWrittenUnreadableToOthers) + t.Run("AVaultBoxSealedToAnotherMachineIsRefusedAndNothingWritten", testAVaultBoxSealedToAnotherMachineIsRefusedAndNothingWritten) + t.Run("AVaultSealedFileSaysWhatIsInItOnce", testAVaultSealedFileSaysWhatIsInItOnce) +} diff --git a/internal/apply/vocabulary_test.go b/internal/apply/vocabulary_test.go index bf2bcceb..7baab4c0 100644 --- a/internal/apply/vocabulary_test.go +++ b/internal/apply/vocabulary_test.go @@ -35,7 +35,7 @@ func declare(t *testing.T, resources string) *declaration.Declaration { return d } -func TestAFileMayBeBytesRatherThanText(t *testing.T) { +func testAFileMayBeBytesRatherThanText(t *testing.T) { // A wallpaper, a font, an icon. Stored as its own encoding it would be a wallpaper nothing // can open. dir := t.TempDir() @@ -56,7 +56,7 @@ func TestAFileMayBeBytesRatherThanText(t *testing.T) { } } -func TestAFileSaysWhatIsInItExactlyOnce(t *testing.T) { +func testAFileSaysWhatIsInItExactlyOnce(t *testing.T) { // Three ways of saying it and no precedence between them, so "what is in this file" is // answerable by looking rather than by knowing which field wins. _, err := declaration.Parse([]byte(`{"declaration":1,"resources":[ @@ -69,7 +69,7 @@ func TestAFileSaysWhatIsInItExactlyOnce(t *testing.T) { } } -func TestBytesThatAreNotBase64AreRefused(t *testing.T) { +func testBytesThatAreNotBase64AreRefused(t *testing.T) { dir := t.TempDir() d := declare(t, `{"id":"w","type":"file","path":"`+dir+`/x","bytes":"not base64!!"}`) _, _, err := Apply(context.Background(), archHost(t), d, store.State{}, @@ -118,7 +118,7 @@ func serving(t *testing.T, body []byte) string { return server.URL + "/theme.tar.gz" } -func TestAnArchiveIsUnpacked(t *testing.T) { +func testAnArchiveIsUnpacked(t *testing.T) { body, digest := anArchive(t, map[string]string{ "config/theme.conf": "dark", "config/icons/one.svg": "", }) @@ -143,7 +143,7 @@ func TestAnArchiveIsUnpacked(t *testing.T) { } } -func TestAnArchiveThatIsNotWhatWasDeclaredIsRefusedBeforeAnythingIsWritten(t *testing.T) { +func testAnArchiveThatIsNotWhatWasDeclaredIsRefusedBeforeAnythingIsWritten(t *testing.T) { // The only thing making bytes from a network the mesh does not control safe to unpack is // that they hash to what was declared. body, _ := anArchive(t, map[string]string{"a": "b"}) @@ -161,7 +161,7 @@ func TestAnArchiveThatIsNotWhatWasDeclaredIsRefusedBeforeAnythingIsWritten(t *te } } -func TestAnArchiveCannotWriteOutsideWhereItWasUnpacked(t *testing.T) { +func testAnArchiveCannotWriteOutsideWhereItWasUnpacked(t *testing.T) { // The oldest bug in unpacking. Checked against the resolved root rather than by looking for // "..", because there is more than one way to name a path that escapes. body, digest := anArchive(t, map[string]string{"../../escaped": "no"}) @@ -182,7 +182,7 @@ func TestAnArchiveCannotWriteOutsideWhereItWasUnpacked(t *testing.T) { } } -func TestAnUnpackedArchiveIsNotFetchedAgainForNothing(t *testing.T) { +func testAnUnpackedArchiveIsNotFetchedAgainForNothing(t *testing.T) { // The digest is the whole identity of an archive, so a matching record means the tree came // from these exact bytes. Applying twice must not report work. body, digest := anArchive(t, map[string]string{"a": "b"}) @@ -211,7 +211,7 @@ func TestAnUnpackedArchiveIsNotFetchedAgainForNothing(t *testing.T) { // The archive is the one path where a symlink could arrive without anybody declaring it, which is // why the refusal lives here. ADR 0012 was earned by production data loss through a symlink // resolved inside a container volume path. -func TestAnArchiveWithSomethingThatIsNotAFileIsRefused(t *testing.T) { +func testAnArchiveWithSomethingThatIsNotAFileIsRefused(t *testing.T) { // A theme needing a symlink would otherwise arrive silently incomplete, and a device node in // an archive is not something to unpack quietly onto a machine. var raw bytes.Buffer @@ -240,7 +240,7 @@ func TestAnArchiveWithSomethingThatIsNotAFileIsRefused(t *testing.T) { } } -func TestAnArchiveMustBePinned(t *testing.T) { +func testAnArchiveMustBePinned(t *testing.T) { _, err := declaration.Parse([]byte(`{"declaration":1,"resources":[ {"id":"t","type":"archive","source":"https://example.invalid/a.tgz","path":"/opt/t"}]}`)) if err == nil { @@ -255,7 +255,7 @@ func TestAnArchiveMustBePinned(t *testing.T) { // // The whole argument for widening the vocabulary is lifecycle — an action could create one and // nothing could ever take it away — so removal is the assertion that matters, not creation. -func TestANetworkIsCreatedAndThenRemovedWhenNoLongerDeclared(t *testing.T) { +func testANetworkIsCreatedAndThenRemovedWhenNoLongerDeclared(t *testing.T) { var calls []string there := map[string]bool{} run := func(_ context.Context, name string, args ...string) (string, error) { @@ -300,7 +300,7 @@ func TestANetworkIsCreatedAndThenRemovedWhenNoLongerDeclared(t *testing.T) { } // A network is created once and left alone when it is already there. -func TestANetworkAlreadyThereIsNotRebuilt(t *testing.T) { +func testANetworkAlreadyThereIsNotRebuilt(t *testing.T) { var created int run := func(_ context.Context, name string, args ...string) (string, error) { args = oldShape(name, args) @@ -327,7 +327,7 @@ func TestANetworkAlreadyThereIsNotRebuilt(t *testing.T) { // JSON document cannot be handed a file that is entirely a token, and the mesh cannot compose the // document because it discarded the value. So the module supplies the document with a hole, the // mesh delivers the value sealed, and the host is the only thing that ever holds both. -func TestASealedValueIsPutIntoTheFileThatNamesIt(t *testing.T) { +func testASealedValueIsPutIntoTheFileThatNamesIt(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "settings.json") d := declare(t, `{"id":"settings","type":"file","path":"`+path+`",`+ @@ -374,7 +374,7 @@ func TestASealedValueIsPutIntoTheFileThatNamesIt(t *testing.T) { // A declaration reaches a node over the broker and `env` is plain text in it, so a password there // is a password the broker sees. A sealed file arrives unreadable, the host writes it, and the // runtime reads it. -func TestAContainerIsGivenItsEnvironmentFiles(t *testing.T) { +func testAContainerIsGivenItsEnvironmentFiles(t *testing.T) { var ran []string run := func(_ context.Context, name string, args ...string) (string, error) { args = oldShape(name, args) @@ -410,7 +410,7 @@ func TestAContainerIsGivenItsEnvironmentFiles(t *testing.T) { // A container may name its resolvers and its own address — the shape a module shipping its own // validating DNS needs: the resolver pinned where its siblings can find it, the siblings pointed // at it. Both flags take addresses, so both reach the runtime verbatim. -func TestAContainerIsGivenItsResolverAndItsAddress(t *testing.T) { +func testAContainerIsGivenItsResolverAndItsAddress(t *testing.T) { var ran []string run := func(_ context.Context, name string, args ...string) (string, error) { args = oldShape(name, args) @@ -443,7 +443,7 @@ func TestAContainerIsGivenItsResolverAndItsAddress(t *testing.T) { // The resolver and address are part of the spec — a container whose dns or ip moved is a // different container, or the fields can never reach one that already runs. That is not // hypothetical: their first deployment compared equal and changed nothing. -func TestAChangedResolverOrAddressIsAChangedContainer(t *testing.T) { +func testAChangedResolverOrAddressIsAChangedContainer(t *testing.T) { base := &declaration.Container{ID: "c", Name: "x", Image: "a@sha256:00"} withDns := &declaration.Container{ID: "c", Name: "x", Image: "a@sha256:00", Dns: []string{"192.168.203.254"}} withIP := &declaration.Container{ID: "c", Name: "x", Image: "a@sha256:00", IP: "192.168.203.254"} @@ -455,3 +455,22 @@ func TestAChangedResolverOrAddressIsAChangedContainer(t *testing.T) { t.Error("adding an address did not change the spec, so it can never reach a running container") } } + +// TestVocabulary runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestVocabulary(t *testing.T) { + t.Run("AFileMayBeBytesRatherThanText", testAFileMayBeBytesRatherThanText) + t.Run("AFileSaysWhatIsInItExactlyOnce", testAFileSaysWhatIsInItExactlyOnce) + t.Run("BytesThatAreNotBase64AreRefused", testBytesThatAreNotBase64AreRefused) + t.Run("AnArchiveIsUnpacked", testAnArchiveIsUnpacked) + t.Run("AnArchiveThatIsNotWhatWasDeclaredIsRefusedBeforeAnythingIsWritten", testAnArchiveThatIsNotWhatWasDeclaredIsRefusedBeforeAnythingIsWritten) + t.Run("AnArchiveCannotWriteOutsideWhereItWasUnpacked", testAnArchiveCannotWriteOutsideWhereItWasUnpacked) + t.Run("AnUnpackedArchiveIsNotFetchedAgainForNothing", testAnUnpackedArchiveIsNotFetchedAgainForNothing) + t.Run("AnArchiveWithSomethingThatIsNotAFileIsRefused", testAnArchiveWithSomethingThatIsNotAFileIsRefused) + t.Run("AnArchiveMustBePinned", testAnArchiveMustBePinned) + t.Run("ANetworkIsCreatedAndThenRemovedWhenNoLongerDeclared", testANetworkIsCreatedAndThenRemovedWhenNoLongerDeclared) + t.Run("ANetworkAlreadyThereIsNotRebuilt", testANetworkAlreadyThereIsNotRebuilt) + t.Run("ASealedValueIsPutIntoTheFileThatNamesIt", testASealedValueIsPutIntoTheFileThatNamesIt) + t.Run("AContainerIsGivenItsEnvironmentFiles", testAContainerIsGivenItsEnvironmentFiles) + t.Run("AContainerIsGivenItsResolverAndItsAddress", testAContainerIsGivenItsResolverAndItsAddress) + t.Run("AChangedResolverOrAddressIsAChangedContainer", testAChangedResolverOrAddressIsAChangedContainer) +} diff --git a/internal/apply/whole_test.go b/internal/apply/whole_test.go index 54d2fd81..3b9d0639 100644 --- a/internal/apply/whole_test.go +++ b/internal/apply/whole_test.go @@ -34,7 +34,7 @@ func writtenOver(t *testing.T, content string, mode os.FileMode) (path string, s return path, state } -func TestAFileWrittenOverGetsItsKeptOriginalBackWhenUndeclared(t *testing.T) { +func testAFileWrittenOverGetsItsKeptOriginalBackWhenUndeclared(t *testing.T) { path, state := writtenOver(t, pacmanFound, 0o640) rec, _ := state.Find(namesID) if rec.Kept == "" || rec.KeptMode != "0640" { @@ -63,7 +63,7 @@ func TestAFileWrittenOverGetsItsKeptOriginalBackWhenUndeclared(t *testing.T) { } } -func TestAFileTheMeshMadeIsRemovedWhenUndeclared(t *testing.T) { +func testAFileTheMeshMadeIsRemovedWhenUndeclared(t *testing.T) { path := filepath.Join(t.TempDir(), "pacman.conf") _, state := applyKeepingIn(t, wholeDecl(path, pacmanMesh), store.State{}, t.TempDir()) if rec, _ := state.Find(namesID); rec.Kept != "" { @@ -78,7 +78,7 @@ func TestAFileTheMeshMadeIsRemovedWhenUndeclared(t *testing.T) { } } -func TestAFileWrittenOverAndChangedSinceIsLeftAsItStands(t *testing.T) { +func testAFileWrittenOverAndChangedSinceIsLeftAsItStands(t *testing.T) { path, state := writtenOver(t, pacmanFound, 0o644) edited := pacmanMesh + "IgnorePkg = linux\n" if err := os.WriteFile(path, []byte(edited), 0o644); err != nil { @@ -95,7 +95,7 @@ func TestAFileWrittenOverAndChangedSinceIsLeftAsItStands(t *testing.T) { } } -func TestAFileWhoseKeptOriginalIsMissingIsLeftAndSaysSo(t *testing.T) { +func testAFileWhoseKeptOriginalIsMissingIsLeftAndSaysSo(t *testing.T) { path, state := writtenOver(t, pacmanFound, 0o644) rec, _ := state.Find(namesID) if err := os.Remove(rec.Kept); err != nil { @@ -111,7 +111,7 @@ func TestAFileWhoseKeptOriginalIsMissingIsLeftAndSaysSo(t *testing.T) { } } -func TestAFileWrittenOverAndDeletedSinceIsNotBroughtBack(t *testing.T) { +func testAFileWrittenOverAndDeletedSinceIsNotBroughtBack(t *testing.T) { path, state := writtenOver(t, pacmanFound, 0o644) if err := os.Remove(path); err != nil { t.Fatal(err) @@ -125,7 +125,7 @@ func TestAFileWrittenOverAndDeletedSinceIsNotBroughtBack(t *testing.T) { } } -func TestAFileWhosePathMovedIsNeverGivenTheOldPathsOriginal(t *testing.T) { +func testAFileWhosePathMovedIsNeverGivenTheOldPathsOriginal(t *testing.T) { // The old path's original stays with the old path's record; the new path keeps its own. oldPath, state := writtenOver(t, pacmanFound, 0o644) newPath := filepath.Join(filepath.Dir(oldPath), "pacman.d.conf") @@ -151,7 +151,7 @@ func TestAFileWhosePathMovedIsNeverGivenTheOldPathsOriginal(t *testing.T) { } } -func TestARecordFromBeforeTheModeWasKeptPutsTheOriginalBackAsTheFileStands(t *testing.T) { +func testARecordFromBeforeTheModeWasKeptPutsTheOriginalBackAsTheFileStands(t *testing.T) { path, state := writtenOver(t, pacmanFound, 0o644) for i := range state.Resources { state.Resources[i].KeptMode, state.Resources[i].KeptOwner = "", "" @@ -171,3 +171,14 @@ func TestARecordFromBeforeTheModeWasKeptPutsTheOriginalBackAsTheFileStands(t *te t.Errorf("reported as %q", got) } } + +// TestWhole runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestWhole(t *testing.T) { + t.Run("AFileWrittenOverGetsItsKeptOriginalBackWhenUndeclared", testAFileWrittenOverGetsItsKeptOriginalBackWhenUndeclared) + t.Run("AFileTheMeshMadeIsRemovedWhenUndeclared", testAFileTheMeshMadeIsRemovedWhenUndeclared) + t.Run("AFileWrittenOverAndChangedSinceIsLeftAsItStands", testAFileWrittenOverAndChangedSinceIsLeftAsItStands) + t.Run("AFileWhoseKeptOriginalIsMissingIsLeftAndSaysSo", testAFileWhoseKeptOriginalIsMissingIsLeftAndSaysSo) + t.Run("AFileWrittenOverAndDeletedSinceIsNotBroughtBack", testAFileWrittenOverAndDeletedSinceIsNotBroughtBack) + t.Run("AFileWhosePathMovedIsNeverGivenTheOldPathsOriginal", testAFileWhosePathMovedIsNeverGivenTheOldPathsOriginal) + t.Run("ARecordFromBeforeTheModeWasKeptPutsTheOriginalBackAsTheFileStands", testARecordFromBeforeTheModeWasKeptPutsTheOriginalBackAsTheFileStands) +} diff --git a/internal/bootstrap/adopted_test.go b/internal/bootstrap/adopted_test.go index 040f8dbb..8a42ce65 100644 --- a/internal/bootstrap/adopted_test.go +++ b/internal/bootstrap/adopted_test.go @@ -26,7 +26,7 @@ table inet mesh_guard { } ` -func TestTheGuardIsExactlyThisTable(t *testing.T) { +func testTheGuardIsExactlyThisTable(t *testing.T) { if got := AsGuard([]int{15672, 5432}); got != goldenGuard { t.Fatalf("the guard changed:\n%s", got) } @@ -52,13 +52,13 @@ ExecStop=nft delete table inet mesh_guard WantedBy=multi-user.target ` -func TestTheGuardUnitIsExactlyThisUnit(t *testing.T) { +func testTheGuardUnitIsExactlyThisUnit(t *testing.T) { if got := guardUnitText(); got != goldenGuardUnit { t.Fatalf("the guard's unit changed:\n%s", got) } } -func TestTheGuardRefusesOnlyWhatIsAddressedToThisMachine(t *testing.T) { +func testTheGuardRefusesOnlyWhatIsAddressedToThisMachine(t *testing.T) { // A machine that routes for others — a predecessor's private-network hub — must not have a // packet for another machine's database port refused (novox/hq ADR 0103). for _, line := range strings.Split(AsGuard([]int{5432}), "\n") { @@ -68,7 +68,7 @@ func TestTheGuardRefusesOnlyWhatIsAddressedToThisMachine(t *testing.T) { } } -func TestAnAdoptedBundleLoadsNoDroppingTableAndExactlyTheGuard(t *testing.T) { +func testAnAdoptedBundleLoadsNoDroppingTableAndExactlyTheGuard(t *testing.T) { r := producedBundle(t) p := FoundationPorts{Store: 5433} if _, err := RewritePorts(&r, p, ""); err != nil { @@ -133,7 +133,7 @@ func TestAnAdoptedBundleLoadsNoDroppingTableAndExactlyTheGuard(t *testing.T) { } } -func TestAConvergedBundleIsNotMadeAnAdoptedOne(t *testing.T) { +func testAConvergedBundleIsNotMadeAnAdoptedOne(t *testing.T) { // The converged genesis keeps the foundation's filter, byte for byte (novox/hq ADR 0088). r := producedBundle(t) for _, res := range r.Declaration.Resources { @@ -146,7 +146,7 @@ func TestAConvergedBundleIsNotMadeAnAdoptedOne(t *testing.T) { } } -func TestAnAdoptedGenesisTakesTheMeshsOwnModulesBeforePushingThem(t *testing.T) { +func testAnAdoptedGenesisTakesTheMeshsOwnModulesBeforePushingThem(t *testing.T) { t.Setenv("TMPDIR", t.TempDir()) for _, c := range []struct { module string @@ -171,7 +171,7 @@ func TestAnAdoptedGenesisTakesTheMeshsOwnModulesBeforePushingThem(t *testing.T) } } -func TestAConvergedGenesisTakesNothing(t *testing.T) { +func testAConvergedGenesisTakesNothing(t *testing.T) { t.Setenv("TMPDIR", t.TempDir()) rec := &controlRecorder{settings: map[string]string{}} control := controlPlane{container: "temp-mesh-controller", run: rec.run, timeout: time.Second} @@ -184,7 +184,7 @@ func TestAConvergedGenesisTakesNothing(t *testing.T) { } } -func TestAnAdoptedGenesisOpensTheRegistryFromAnywhere(t *testing.T) { +func testAnAdoptedGenesisOpensTheRegistryFromAnywhere(t *testing.T) { t.Setenv("TMPDIR", t.TempDir()) rec := &controlRecorder{settings: map[string]string{}} control := controlPlane{container: "temp-mesh-controller", run: rec.run, timeout: time.Second} @@ -197,7 +197,7 @@ func TestAnAdoptedGenesisOpensTheRegistryFromAnywhere(t *testing.T) { } } -func TestAnAdoptedGenesisChoosesTheFilterAndLoadsNone(t *testing.T) { +func testAnAdoptedGenesisChoosesTheFilterAndLoadsNone(t *testing.T) { rec := &controlRecorder{settings: map[string]string{}} control := controlPlane{container: "mesh-controller", run: rec.run, timeout: time.Second} o := Options{Node: "anchor", Adopted: true, Answers: map[string]string{"packet-filter": "nftables"}} @@ -210,7 +210,7 @@ func TestAnAdoptedGenesisChoosesTheFilterAndLoadsNone(t *testing.T) { } } -func TestAnAdoptedNodeIsRecordedAdopted(t *testing.T) { +func testAnAdoptedNodeIsRecordedAdopted(t *testing.T) { stop := errors.New("stop here") runtime := &asked{answer: func(name string, args []string) (string, error) { joined := strings.Join(args, " ") @@ -231,3 +231,17 @@ func TestAnAdoptedNodeIsRecordedAdopted(t *testing.T) { t.Errorf("the node was not added adopted: %v", runtime.commands) } } + +// TestAdopted runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestAdopted(t *testing.T) { + t.Run("TheGuardIsExactlyThisTable", testTheGuardIsExactlyThisTable) + t.Run("TheGuardUnitIsExactlyThisUnit", testTheGuardUnitIsExactlyThisUnit) + t.Run("TheGuardRefusesOnlyWhatIsAddressedToThisMachine", testTheGuardRefusesOnlyWhatIsAddressedToThisMachine) + t.Run("AnAdoptedBundleLoadsNoDroppingTableAndExactlyTheGuard", testAnAdoptedBundleLoadsNoDroppingTableAndExactlyTheGuard) + t.Run("AConvergedBundleIsNotMadeAnAdoptedOne", testAConvergedBundleIsNotMadeAnAdoptedOne) + t.Run("AnAdoptedGenesisTakesTheMeshsOwnModulesBeforePushingThem", testAnAdoptedGenesisTakesTheMeshsOwnModulesBeforePushingThem) + t.Run("AConvergedGenesisTakesNothing", testAConvergedGenesisTakesNothing) + t.Run("AnAdoptedGenesisOpensTheRegistryFromAnywhere", testAnAdoptedGenesisOpensTheRegistryFromAnywhere) + t.Run("AnAdoptedGenesisChoosesTheFilterAndLoadsNone", testAnAdoptedGenesisChoosesTheFilterAndLoadsNone) + t.Run("AnAdoptedNodeIsRecordedAdopted", testAnAdoptedNodeIsRecordedAdopted) +} diff --git a/internal/bootstrap/apply_test.go b/internal/bootstrap/apply_test.go index 67766cbe..aef2b886 100644 --- a/internal/bootstrap/apply_test.go +++ b/internal/bootstrap/apply_test.go @@ -20,7 +20,7 @@ import ( // is the one it claims to be, by asking its package database about a package that is certainly // there. Getting this wrong installs with the wrong package manager and the wrong unit names. -func TestTheMachineIsAskedWhichSystemItIs(t *testing.T) { +func testTheMachineIsAskedWhichSystemItIs(t *testing.T) { // Only pacman answers, so this is the arch host and nothing had to be told so. onlyPacman := func(_ context.Context, name string, _ ...string) (string, error) { if name == "pacman" { @@ -40,7 +40,7 @@ func TestTheMachineIsAskedWhichSystemItIs(t *testing.T) { // A machine that is none of them is refused with what each of them said. "Unsupported system" is // a sentence nobody can act on; "pacman does not answer here" is. -func TestAMachineThatIsNoneOfThemIsRefusedWithWhatEachSaid(t *testing.T) { +func testAMachineThatIsNoneOfThemIsRefusedWithWhatEachSaid(t *testing.T) { nothing := func(context.Context, string, ...string) (string, error) { return "", errors.New("command not found") } @@ -58,7 +58,7 @@ func TestAMachineThatIsNoneOfThemIsRefusedWithWhatEachSaid(t *testing.T) { // And a machine that was TOLD what it is still has to prove it. Installing the arch half of the // host on Alpine must say so once, at the start, rather than failing later inside pacman. -func TestASystemThatWasNamedIsStillProved(t *testing.T) { +func testASystemThatWasNamedIsStillProved(t *testing.T) { onlyApk := func(_ context.Context, name string, _ ...string) (string, error) { if name == "apk" { return "apk-tools-2.14.0\n", nil @@ -75,7 +75,7 @@ func TestASystemThatWasNamedIsStillProved(t *testing.T) { } } -func TestASystemNobodyHasBuiltIsRefusedByName(t *testing.T) { +func testASystemNobodyHasBuiltIsRefusedByName(t *testing.T) { anything := func(context.Context, string, ...string) (string, error) { return "", nil } _, err := WorkOutSystem(context.Background(), anything, "debian") if err == nil { @@ -88,7 +88,7 @@ func TestASystemNobodyHasBuiltIsRefusedByName(t *testing.T) { // A foundation is applied before any mesh exists, so it can carry no secret the mesh sealed — there // is no key to open one with. Refused with a sentence rather than a nil dereference. -func TestASealedFileInAFoundationIsRefusedWithAReason(t *testing.T) { +func testASealedFileInAFoundationIsRefusedWithAReason(t *testing.T) { _, err := refuseSealed("anything") if err == nil { t.Fatal("a sealed file in a foundation bundle was accepted") @@ -100,7 +100,7 @@ func TestASealedFileInAFoundationIsRefusedWithAReason(t *testing.T) { // Defends novox/hq ADR 0100: the carried bundle keeps the original of a file it writes over that // the host has no record of — the distribution's own ruleset, say. -func TestTheBundleKeepsTheOriginalOfWhatItWritesOver(t *testing.T) { +func testTheBundleKeepsTheOriginalOfWhatItWritesOver(t *testing.T) { dir := t.TempDir() conf := filepath.Join(dir, "nftables.conf") if err := os.WriteFile(conf, []byte("# the distribution's own\n"), 0o644); err != nil { @@ -134,7 +134,7 @@ func TestTheBundleKeepsTheOriginalOfWhatItWritesOver(t *testing.T) { // Defends novox/hq issue 104: genesis consumes the bundle, recording the digest of what it applied // and the mode the operator raised the machine in, so the host's own `reconcile` never applies the // carried bytes over it. -func TestGenesisConsumesTheBundleAndRecordsTheMode(t *testing.T) { +func testGenesisConsumesTheBundleAndRecordsTheMode(t *testing.T) { dir := t.TempDir() raw := []byte(`{"declaration":1,"resources":[ {"id":"a","type":"file","path":"` + filepath.Join(dir, "a.conf") + `","content":"x\n"}]}`) @@ -180,3 +180,14 @@ func TestGenesisConsumesTheBundleAndRecordsTheMode(t *testing.T) { t.Errorf("a genesis re-run set the mode back to %q over the mesh's converged", known.Mode) } } + +// TestApply runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestApply(t *testing.T) { + t.Run("TheMachineIsAskedWhichSystemItIs", testTheMachineIsAskedWhichSystemItIs) + t.Run("AMachineThatIsNoneOfThemIsRefusedWithWhatEachSaid", testAMachineThatIsNoneOfThemIsRefusedWithWhatEachSaid) + t.Run("ASystemThatWasNamedIsStillProved", testASystemThatWasNamedIsStillProved) + t.Run("ASystemNobodyHasBuiltIsRefusedByName", testASystemNobodyHasBuiltIsRefusedByName) + t.Run("ASealedFileInAFoundationIsRefusedWithAReason", testASealedFileInAFoundationIsRefusedWithAReason) + t.Run("TheBundleKeepsTheOriginalOfWhatItWritesOver", testTheBundleKeepsTheOriginalOfWhatItWritesOver) + t.Run("GenesisConsumesTheBundleAndRecordsTheMode", testGenesisConsumesTheBundleAndRecordsTheMode) +} diff --git a/internal/bootstrap/build_test.go b/internal/bootstrap/build_test.go index 61d37f36..064ae2ae 100644 --- a/internal/bootstrap/build_test.go +++ b/internal/bootstrap/build_test.go @@ -11,7 +11,7 @@ import ( // **Exercised rather than assumed.** This is the refusal that stands between a person and a // machine left holding a store, a broker and no control plane — the failure the whole preflight // exists to prevent — and a refusal nothing tests is a refusal nobody has read. -func TestAnInstallerWithNothingToBuildRefuses(t *testing.T) { +func testAnInstallerWithNothingToBuildRefuses(t *testing.T) { err := Source{}.Check() if err == nil { t.Fatal("a source naming no repository was accepted; nothing would have been built") @@ -24,7 +24,7 @@ func TestAnInstallerWithNothingToBuildRefuses(t *testing.T) { } // A repository without a commit refuses too, because a branch is somebody else's moving target. -func TestABranchIsNotACommit(t *testing.T) { +func testABranchIsNotACommit(t *testing.T) { err := Source{Repository: "https://example.invalid/mesh-controller.git"}.Check() if err == nil { t.Fatal("a source with no ref was accepted; genesis would have built whatever a branch pointed at") @@ -35,7 +35,7 @@ func TestABranchIsNotACommit(t *testing.T) { } // And a repository with a commit is enough. -func TestARepositoryAndACommitIsEnough(t *testing.T) { +func testARepositoryAndACommitIsEnough(t *testing.T) { if err := (Source{Repository: "https://example.invalid/mesh-controller.git", Ref: "a1b2c3d4"}).Check(); err != nil { t.Fatalf("a repository and a commit were refused: %v", err) } @@ -46,7 +46,7 @@ func TestARepositoryAndACommitIsEnough(t *testing.T) { // it rebuilds the control plane from source, and a copy in the catalogue, which genesis read — and // nothing kept them equal (novox/hq 04-ISSUES/072). The builder already reports the manifest it // built, artifact resolved to the image; genesis takes it from there and reads no second copy. -func TestTheBuildHandsOverTheManifestTheMeshWillHold(t *testing.T) { +func testTheBuildHandsOverTheManifestTheMeshWillHold(t *testing.T) { manifest := `{"module":"mesh-controller","version":"1","resources":[` + `{"id":"server","type":"container","name":"mesh-controller","image":"` + builtImage + `"}]}` runtime := &asked{answer: aRepository(t, imageFormManifest, func(string, []string) (string, error) { @@ -68,7 +68,7 @@ func TestTheBuildHandsOverTheManifestTheMeshWillHold(t *testing.T) { // A result without a manifest is a build the installer cannot finish, and it is refused beside the // builder that said it rather than at step 9 with a message about a missing file. -func TestABuildReportingNoManifestIsRefused(t *testing.T) { +func testABuildReportingNoManifestIsRefused(t *testing.T) { runtime := &asked{answer: aRepository(t, imageFormManifest, func(string, []string) (string, error) { return `{"module":"mesh-controller","commit":"a1b2c3d4",` + `"made":[{"name":"server","kind":"image","reference":"` + builtImage + `"}]}`, nil @@ -81,7 +81,7 @@ func TestABuildReportingNoManifestIsRefused(t *testing.T) { } // And a manifest that does not name the image the build produced describes some other build. -func TestABuildWhoseManifestNamesAnotherImageIsRefused(t *testing.T) { +func testABuildWhoseManifestNamesAnotherImageIsRefused(t *testing.T) { runtime := &asked{answer: aRepository(t, imageFormManifest, func(string, []string) (string, error) { return `{"module":"mesh-controller","commit":"a1b2c3d4","manifest":{"module":"mesh-controller",` + `"resources":[{"id":"server","type":"container","image":"sha256:` + strings.Repeat("9", 64) + `"}]},` + @@ -93,3 +93,13 @@ func TestABuildWhoseManifestNamesAnotherImageIsRefused(t *testing.T) { t.Fatalf("a manifest naming another image was accepted, or refused for another reason: %v", err) } } + +// TestBuild runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBuild(t *testing.T) { + t.Run("AnInstallerWithNothingToBuildRefuses", testAnInstallerWithNothingToBuildRefuses) + t.Run("ABranchIsNotACommit", testABranchIsNotACommit) + t.Run("ARepositoryAndACommitIsEnough", testARepositoryAndACommitIsEnough) + t.Run("TheBuildHandsOverTheManifestTheMeshWillHold", testTheBuildHandsOverTheManifestTheMeshWillHold) + t.Run("ABuildReportingNoManifestIsRefused", testABuildReportingNoManifestIsRefused) + t.Run("ABuildWhoseManifestNamesAnotherImageIsRefused", testABuildWhoseManifestNamesAnotherImageIsRefused) +} diff --git a/internal/bootstrap/builder_test.go b/internal/bootstrap/builder_test.go index eb109a27..a8a8b8df 100644 --- a/internal/bootstrap/builder_test.go +++ b/internal/bootstrap/builder_test.go @@ -38,7 +38,7 @@ func recording(t *testing.T) (*controlRecorder, controlPlane) { return c, controlPlane{container: "temp-mesh-controller", run: c.run, timeout: time.Second} } -func TestTheBuilderOnTheDefaultPackagesPortIsToldNothing(t *testing.T) { +func testTheBuilderOnTheDefaultPackagesPortIsToldNothing(t *testing.T) { c, control := recording(t) o := Options{Node: "anchor", Wait: time.Second} if _, err := installModule(context.Background(), o, control, BuilderModule, @@ -67,7 +67,7 @@ func aCatalogueWith(t *testing.T, module, manifest string) string { const theForgesManifest = `{"module": "gitea", "version": "1"}` -func TestThePackagesPortIsTheForgeModulesSettingOnThisNode(t *testing.T) { +func testThePackagesPortIsTheForgeModulesSettingOnThisNode(t *testing.T) { c, control := recording(t) o := Options{Node: "anchor", Catalogue: aCatalogueWith(t, ForgeModule, theForgesManifest), Ports: FoundationPorts{Packages: 3100}, Wait: time.Second} @@ -104,7 +104,7 @@ func (k *knowingControl) run(ctx context.Context, name string, args ...string) ( return out, err } -func TestARerunDoesNotReplaceAForgeTheMeshAlreadyHas(t *testing.T) { +func testARerunDoesNotReplaceAForgeTheMeshAlreadyHas(t *testing.T) { t.Setenv("TMPDIR", t.TempDir()) k := &knowingControl{controlRecorder{settings: map[string]string{}}} control := controlPlane{container: "mesh-controller", run: k.run, timeout: time.Second} @@ -125,7 +125,7 @@ func TestARerunDoesNotReplaceAForgeTheMeshAlreadyHas(t *testing.T) { } } -func TestAGenesisOnTheCataloguesPackagesPortRegistersNoForge(t *testing.T) { +func testAGenesisOnTheCataloguesPackagesPortRegistersNoForge(t *testing.T) { c, control := recording(t) o := Options{Node: "anchor", Catalogue: aCatalogueWith(t, ForgeModule, theForgesManifest), Wait: time.Second} @@ -137,7 +137,7 @@ func TestAGenesisOnTheCataloguesPackagesPortRegistersNoForge(t *testing.T) { } } -func TestAForgeManifestTheCatalogueDoesNotHaveIsNamed(t *testing.T) { +func testAForgeManifestTheCatalogueDoesNotHaveIsNamed(t *testing.T) { _, control := recording(t) o := Options{Node: "anchor", Catalogue: t.TempDir(), Ports: FoundationPorts{Packages: 3100}, Wait: time.Second} @@ -182,7 +182,7 @@ func theCataloguesModule(t *testing.T, module string) []byte { // one-holder `builder` left the catalogue on 2026-10-03, and genesis stopped at step 13 asking for it. // The catalogue's own manifest is read, and the image the installer carried is put where the manifest // names the image it builds. -func TestGenesisInstallsTheCataloguesBuildAgent(t *testing.T) { +func testGenesisInstallsTheCataloguesBuildAgent(t *testing.T) { manifest := theCataloguesModule(t, BuilderModule) const reference = "127.0.0.1:5000/mesh-builder@sha256:" + "4444444444444444444444444444444444444444444444444444444444444444" pinned, places, err := pinTheCarriedBuilder(manifest, reference) @@ -221,7 +221,7 @@ func TestGenesisInstallsTheCataloguesBuildAgent(t *testing.T) { // A manifest that runs nothing from an image it builds has nowhere to put the carried builder, and is // refused rather than registered running nothing. -func TestABuildAgentManifestWithNowhereForTheCarriedBuilderIsRefused(t *testing.T) { +func testABuildAgentManifestWithNowhereForTheCarriedBuilderIsRefused(t *testing.T) { _, _, err := pinTheCarriedBuilder([]byte(`{"module":"build-agent","resources":[{"id":"server","type":"container","name":"x","artifact":"server"}],"build":{"artifacts":[{"name":"server","kind":"bundle"}]}}`), "127.0.0.1:5000/mesh-builder@sha256:"+strings.Repeat("4", 64)) if err == nil || !strings.Contains(err.Error(), "nowhere to put") { @@ -232,7 +232,7 @@ func TestABuildAgentManifestWithNowhereForTheCarriedBuilderIsRefused(t *testing. // 1151: the build agent's manifest lives in the controller's repository now (ADR 0420, issue 1019), and a merge check of // this repository has the controller cloned beside it, so a tree shaped like that check's, whose catalogue no longer holds // the build agent, is read from the controller. -func TestTheBuildAgentsManifestIsReadFromTheControllerBesideTheCheck(t *testing.T) { +func testTheBuildAgentsManifestIsReadFromTheControllerBesideTheCheck(t *testing.T) { beside := t.TempDir() for path, body := range map[string]string{ "mesh-catalog/modules/nats/module.json": `{"module":"nats"}`, @@ -254,3 +254,15 @@ func TestTheBuildAgentsManifestIsReadFromTheControllerBesideTheCheck(t *testing. t.Errorf("a module the catalogue holds was read as %s", got) } } + +// TestBuilder runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBuilder(t *testing.T) { + t.Run("TheBuilderOnTheDefaultPackagesPortIsToldNothing", testTheBuilderOnTheDefaultPackagesPortIsToldNothing) + t.Run("ThePackagesPortIsTheForgeModulesSettingOnThisNode", testThePackagesPortIsTheForgeModulesSettingOnThisNode) + t.Run("ARerunDoesNotReplaceAForgeTheMeshAlreadyHas", testARerunDoesNotReplaceAForgeTheMeshAlreadyHas) + t.Run("AGenesisOnTheCataloguesPackagesPortRegistersNoForge", testAGenesisOnTheCataloguesPackagesPortRegistersNoForge) + t.Run("AForgeManifestTheCatalogueDoesNotHaveIsNamed", testAForgeManifestTheCatalogueDoesNotHaveIsNamed) + t.Run("GenesisInstallsTheCataloguesBuildAgent", testGenesisInstallsTheCataloguesBuildAgent) + t.Run("ABuildAgentManifestWithNowhereForTheCarriedBuilderIsRefused", testABuildAgentManifestWithNowhereForTheCarriedBuilderIsRefused) + t.Run("TheBuildAgentsManifestIsReadFromTheControllerBesideTheCheck", testTheBuildAgentsManifestIsReadFromTheControllerBesideTheCheck) +} diff --git a/internal/bootstrap/bus_adoption_test.go b/internal/bootstrap/bus_adoption_test.go index 71a12c1c..191d7a1a 100644 --- a/internal/bootstrap/bus_adoption_test.go +++ b/internal/bootstrap/bus_adoption_test.go @@ -13,7 +13,7 @@ import ( // image, and the mesh replaces its bus only as a planned step. A plain push was refused — "sending anchor // would replace the bus … a planned step: `bus upgrade --why …`" — and genesis stopped at step 18. -func TestTheBrokerStepAdoptsTheBusThroughItsPlannedStep(t *testing.T) { +func testTheBrokerStepAdoptsTheBusThroughItsPlannedStep(t *testing.T) { catalogue := aCatalogue(t, map[string]string{BusModule: aBusModule(theModulesLayout)}) rewritten, err := Rewrite(theRealBundle(t), held) if err != nil { @@ -95,7 +95,7 @@ func TestTheBrokerStepAdoptsTheBusThroughItsPlannedStep(t *testing.T) { } // A planned step the controller ends failed is the broker step failing, with the controller's words. -func TestABusStepThatEndsFailedIsRefused(t *testing.T) { +func testABusStepThatEndsFailedIsRefused(t *testing.T) { aGenesisBusOnDisk(t) runtime := &asked{answer: func(name string, args []string) (string, error) { return "last step 1: not known → 53e51864 on anchor by installer (x): failed at 2026-10-13 11:59; snapshot s\n" + @@ -112,7 +112,7 @@ func TestABusStepThatEndsFailedIsRefused(t *testing.T) { // server release and is reversible as the step says (ADR 0333 §3). The module takes the server as an upstream // artifact, its image reference pinned by digest (issue 1641); it no longer builds an image on a NATS_BASE argument, // which this test read until issue 1875. -func TestTheBundlesBusRunsTheReleaseTheModulesImageIsBuiltOn(t *testing.T) { +func testTheBundlesBusRunsTheReleaseTheModulesImageIsBuiltOn(t *testing.T) { var m struct { Build struct { Artifacts []struct{ Name, Kind, From string } `json:"artifacts"` @@ -148,3 +148,10 @@ func TestTheBundlesBusRunsTheReleaseTheModulesImageIsBuiltOn(t *testing.T) { } } } + +// TestBusAdoption runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBusAdoption(t *testing.T) { + t.Run("TheBrokerStepAdoptsTheBusThroughItsPlannedStep", testTheBrokerStepAdoptsTheBusThroughItsPlannedStep) + t.Run("ABusStepThatEndsFailedIsRefused", testABusStepThatEndsFailedIsRefused) + t.Run("TheBundlesBusRunsTheReleaseTheModulesImageIsBuiltOn", testTheBundlesBusRunsTheReleaseTheModulesImageIsBuiltOn) +} diff --git a/internal/bootstrap/choices_test.go b/internal/bootstrap/choices_test.go index d5e6075c..6f0765c3 100644 --- a/internal/bootstrap/choices_test.go +++ b/internal/bootstrap/choices_test.go @@ -8,7 +8,7 @@ import ( func quietly(string) {} // A flag answers, and answers wrongly is refused naming what would have worked. -func TestAFlagAnswersAndAWrongOneIsRefused(t *testing.T) { +func testAFlagAnswersAndAWrongOneIsRefused(t *testing.T) { filter := Choice{Name: "packet-filter", Options: []string{"nftables", "ufw"}} got, err := decide(filter, "ufw", nil, quietly) @@ -27,7 +27,7 @@ func TestAFlagAnswersAndAWrongOneIsRefused(t *testing.T) { // A lone option answers itself — and says so, because "it chose for me" and "there was nothing to // choose" read identically afterwards unless one of them speaks. -func TestALoneOptionAnswersItselfAloud(t *testing.T) { +func testALoneOptionAnswersItselfAloud(t *testing.T) { var said []string got, err := decide(Choice{Name: "private-network", Options: []string{"wireguard"}}, "", nil, func(line string) { said = append(said, line) }) @@ -40,7 +40,7 @@ func TestALoneOptionAnswersItselfAloud(t *testing.T) { } // A terminal is asked; an empty answer takes the default when there is one. -func TestATerminalIsAskedAndEmptyTakesTheDefault(t *testing.T) { +func testATerminalIsAskedAndEmptyTakesTheDefault(t *testing.T) { asked := 0 prompt := func(c Choice) (string, error) { asked++; return "", nil } got, err := decide(Choice{Name: "extras", Default: "none"}, "", prompt, quietly) @@ -52,7 +52,7 @@ func TestATerminalIsAskedAndEmptyTakesTheDefault(t *testing.T) { // **Unattended and required is a refusal, not a guess.** The lab and any machine without a // terminal must be answerable by flags — and a required choice with no flag has to stop the run // naming the flag, because a guessed packet filter is a machine somebody else configured. -func TestUnattendedAndRequiredRefusesNamingTheFlag(t *testing.T) { +func testUnattendedAndRequiredRefusesNamingTheFlag(t *testing.T) { _, err := decide(Choice{Name: "packet-filter", Options: []string{"nftables", "ufw"}}, "", nil, quietly) if err == nil { @@ -62,3 +62,11 @@ func TestUnattendedAndRequiredRefusesNamingTheFlag(t *testing.T) { t.Fatalf("the refusal does not name the flag that answers it: %v", err) } } + +// TestChoices runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestChoices(t *testing.T) { + t.Run("AFlagAnswersAndAWrongOneIsRefused", testAFlagAnswersAndAWrongOneIsRefused) + t.Run("ALoneOptionAnswersItselfAloud", testALoneOptionAnswersItselfAloud) + t.Run("ATerminalIsAskedAndEmptyTakesTheDefault", testATerminalIsAskedAndEmptyTakesTheDefault) + t.Run("UnattendedAndRequiredRefusesNamingTheFlag", testUnattendedAndRequiredRefusesNamingTheFlag) +} diff --git a/internal/bootstrap/control_test.go b/internal/bootstrap/control_test.go index 2b6fd584..d7edf119 100644 --- a/internal/bootstrap/control_test.go +++ b/internal/bootstrap/control_test.go @@ -71,7 +71,7 @@ func theBuild(manifest string) Built { // which only the machine that built it can resolve; the mesh's record must name what the registry // assigned, `/@sha256:…`, or every other machine the module is pushed to // would go looking for an image nothing serves. -func TestTheControlPlaneIsPinnedToWhatThisMeshsRegistryAssigned(t *testing.T) { +func testTheControlPlaneIsPinnedToWhatThisMeshsRegistryAssigned(t *testing.T) { pinned, places, err := pinImage([]byte(theControlPlaneModule), builtImage, pushedReference, "mesh-controller") if err != nil { t.Fatal(err) @@ -90,7 +90,7 @@ func TestTheControlPlaneIsPinnedToWhatThisMeshsRegistryAssigned(t *testing.T) { // A manifest naming some other image describes some other build. Registering it would install a // control plane that is not the image this machine just published, which is the one thing this // step exists to guarantee. -func TestAManifestNamingAnotherBuildIsRefused(t *testing.T) { +func testAManifestNamingAnotherBuildIsRefused(t *testing.T) { other := strings.Replace(theControlPlaneModule, builtImage, "sha256:"+strings.Repeat("9", 64), 1) if _, _, err := pinImage([]byte(other), builtImage, pushedReference, "mesh-controller"); err == nil { t.Fatal("a manifest naming some other image was accepted") @@ -99,7 +99,7 @@ func TestAManifestNamingAnotherBuildIsRefused(t *testing.T) { // Every place moves. A manifest naming its image in a second resource — a migrate step beside the // server — would otherwise be left half pinned, and fail inside an apply rather than here. -func TestEveryPlaceTheManifestNamesTheImageIsPinned(t *testing.T) { +func testEveryPlaceTheManifestNamesTheImageIsPinned(t *testing.T) { twice := strings.Replace(theControlPlaneModule, `{"id": "mesh-state", "type": "directory", "path": "/var/lib/mesh/mesh-controller", "mode": "0700"},`, `{"id": "mesh-state", "type": "directory", "path": "/var/lib/mesh/mesh-controller", "mode": "0700"}, @@ -123,7 +123,7 @@ func TestEveryPlaceTheManifestNamesTheImageIsPinned(t *testing.T) { // and thirty-two random bytes in their place would leave the control plane unable to open a single // context. The pairing is read from the manifest so that whatever the catalogue calls these // secrets is what is delivered. -func TestTheStoreConnectionsComeFromTheBundleThatMadeThem(t *testing.T) { +func testTheStoreConnectionsComeFromTheBundleThatMadeThem(t *testing.T) { wanted, err := secretsByVariableIn([]byte(theControlPlaneModule)) if err != nil { t.Fatal(err) @@ -174,7 +174,7 @@ func TestTheStoreConnectionsComeFromTheBundleThatMadeThem(t *testing.T) { // A secret the foundation did not make is left for the mesh to make, and said so. Every other // secret in a mesh is one the mesh made; `secret accept` is only for what predates the mesh. -func TestASecretTheFoundationNeverMadeIsLeftToTheMesh(t *testing.T) { +func testASecretTheFoundationNeverMadeIsLeftToTheMesh(t *testing.T) { extra := strings.Replace(theControlPlaneModule, `"bus": "/var/lib/mesh/mesh-controller/bus"`, `"bus": "/var/lib/mesh/mesh-controller/bus", @@ -212,7 +212,7 @@ func TestASecretTheFoundationNeverMadeIsLeftToTheMesh(t *testing.T) { // A manifest whose container reads a file no own-secret writes is refused. The mesh would seal // nothing there and the control plane would find an empty file where a connection string has to // be — which presents as a control plane that will not start, three steps from the cause. -func TestAConnectionFileNothingWritesIsRefused(t *testing.T) { +func testAConnectionFileNothingWritesIsRefused(t *testing.T) { mismatched := strings.Replace(theControlPlaneModule, `"inventory": "/var/lib/mesh/mesh-controller/inventory",`, `"inventory": "/var/lib/mesh/mesh-controller/somewhere-else",`, 1) @@ -229,7 +229,7 @@ func TestAConnectionFileNothingWritesIsRefused(t *testing.T) { // A manifest asking for no store connections at all describes a control plane that can open // nothing, and the refusal says what shape the installer delivers into — because the manifest is // written in another repository and this is where the two have to agree. -func TestAManifestWantingNoStoresIsRefusedWithTheShapeItShouldHave(t *testing.T) { +func testAManifestWantingNoStoresIsRefusedWithTheShapeItShouldHave(t *testing.T) { rewritten, err := Rewrite(theRealBundle(t), held) if err != nil { t.Fatal(err) @@ -254,7 +254,7 @@ func TestAManifestWantingNoStoresIsRefusedWithTheShapeItShouldHave(t *testing.T) // The permanent control plane is asked a question, not merely looked at — the same question the // temporary one was asked at step 5, and for the same reason: `status` opens all three stores, so // a reply proves the sealed connections it was given are the ones the foundation made. -func TestThePermanentControlPlaneIsAskedTheSameQuestion(t *testing.T) { +func testThePermanentControlPlaneIsAskedTheSameQuestion(t *testing.T) { runtime := &asked{answer: aMeshThatAgrees(map[string]string{ "module list": "", "exec mesh-controller /mesh-controller": "1 node, 0 waiting\n", @@ -287,7 +287,7 @@ func TestThePermanentControlPlaneIsAskedTheSameQuestion(t *testing.T) { // The broker settings take the file shape too (novox/hq ADR 0086): a `MESH_BROKER_…_FILE` pointing // at a mounted own-secret is delivered as that secret, exactly as a store connection is. -func TestABrokerSettingReadFromAFileIsDeliveredToo(t *testing.T) { +func testABrokerSettingReadFromAFileIsDeliveredToo(t *testing.T) { manifest := `{ "module": "mesh-controller", "version": "1", "own-secrets": {"broker": "/var/lib/mesh/mesh-controller/broker", "inventory": "/var/lib/mesh/mesh-controller/inventory"}, @@ -311,7 +311,7 @@ func TestABrokerSettingReadFromAFileIsDeliveredToo(t *testing.T) { } // Step 9 with nothing built is a caller's fault, and it stops rather than pretending to pivot. -func TestTheControlPlaneCannotBeInstalledWithoutABuild(t *testing.T) { +func testTheControlPlaneCannotBeInstalledWithoutABuild(t *testing.T) { runtime := &asked{answer: aMeshThatAgrees(map[string]string{})} control := controlPlane{container: "temp-mesh-controller", run: runtime.run, timeout: time.Second} rewritten, err := Rewrite(theRealBundle(t), held) @@ -327,3 +327,17 @@ func TestTheControlPlaneCannotBeInstalledWithoutABuild(t *testing.T) { t.Error("something was registered without a manifest") } } + +// TestControl runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestControl(t *testing.T) { + t.Run("TheControlPlaneIsPinnedToWhatThisMeshsRegistryAssigned", testTheControlPlaneIsPinnedToWhatThisMeshsRegistryAssigned) + t.Run("AManifestNamingAnotherBuildIsRefused", testAManifestNamingAnotherBuildIsRefused) + t.Run("EveryPlaceTheManifestNamesTheImageIsPinned", testEveryPlaceTheManifestNamesTheImageIsPinned) + t.Run("TheStoreConnectionsComeFromTheBundleThatMadeThem", testTheStoreConnectionsComeFromTheBundleThatMadeThem) + t.Run("ASecretTheFoundationNeverMadeIsLeftToTheMesh", testASecretTheFoundationNeverMadeIsLeftToTheMesh) + t.Run("AConnectionFileNothingWritesIsRefused", testAConnectionFileNothingWritesIsRefused) + t.Run("AManifestWantingNoStoresIsRefusedWithTheShapeItShouldHave", testAManifestWantingNoStoresIsRefusedWithTheShapeItShouldHave) + t.Run("ThePermanentControlPlaneIsAskedTheSameQuestion", testThePermanentControlPlaneIsAskedTheSameQuestion) + t.Run("ABrokerSettingReadFromAFileIsDeliveredToo", testABrokerSettingReadFromAFileIsDeliveredToo) + t.Run("TheControlPlaneCannotBeInstalledWithoutABuild", testTheControlPlaneCannotBeInstalledWithoutABuild) +} diff --git a/internal/bootstrap/enrol_test.go b/internal/bootstrap/enrol_test.go index 031b8232..cf8bec80 100644 --- a/internal/bootstrap/enrol_test.go +++ b/internal/bootstrap/enrol_test.go @@ -53,7 +53,7 @@ func arch(t *testing.T) system.System { // A machine that has already enrolled is not enrolled again, and no token is spent on it. The // installer is run over and over; a second identity is one the mesh does not know, and the mesh // believes the first. -func TestAMachineThatHasAlreadyEnrolledIsNotEnrolledAgain(t *testing.T) { +func testAMachineThatHasAlreadyEnrolledIsNotEnrolledAgain(t *testing.T) { runtime := &asked{answer: func(name string, args []string) (string, error) { joined := strings.Join(args, " ") switch { @@ -99,7 +99,7 @@ func TestAMachineThatHasAlreadyEnrolledIsNotEnrolledAgain(t *testing.T) { // itself the thing that makes the mesh hear. Taken as proof of life it ends the step believing an // agent it never started, and everything after is the control plane being told things that never // reach the machine: the next push is accepted, recorded, and applied by nobody. -func TestAMeshThatHasHeardFromAMachineWithNoAgentStartsOne(t *testing.T) { +func testAMeshThatHasHeardFromAMachineWithNoAgentStartsOne(t *testing.T) { runtime := &asked{answer: func(name string, args []string) (string, error) { joined := strings.Join(args, " ") switch { @@ -135,7 +135,7 @@ func TestAMeshThatHasHeardFromAMachineWithNoAgentStartsOne(t *testing.T) { // A machine already enrolled under ANOTHER name is refused, with what to do about it. Re-enrolling // replaces the identity the mesh recorded, which is a deliberate act and not something an // installer does on its own. -func TestAMachineEnrolledUnderAnotherNameIsRefused(t *testing.T) { +func testAMachineEnrolledUnderAnotherNameIsRefused(t *testing.T) { runtime := &asked{answer: func(_ string, args []string) (string, error) { if strings.Contains(strings.Join(args, " "), "node list") { return "somewhere-else here 01J0\n", nil @@ -161,7 +161,7 @@ func TestAMachineEnrolledUnderAnotherNameIsRefused(t *testing.T) { // running and cannot reach the broker looks exactly like a successful install until the first push // silently applies nothing — which is the class of fault this whole program exists to stop being // found late. -func TestAHostThatIsRunningAndUnheardOfIsNotAnInstall(t *testing.T) { +func testAHostThatIsRunningAndUnheardOfIsNotAnInstall(t *testing.T) { previous := answerEvery answerEvery = time.Millisecond defer func() { answerEvery = previous }() @@ -198,7 +198,7 @@ func TestAHostThatIsRunningAndUnheardOfIsNotAnInstall(t *testing.T) { // A machine with no service to start is refused, and the refusal says what is missing rather than // inventing a unit file. What a unit says is a packaging decision, and an installer writing one // would put a file on the machine that whatever installed the host will disagree with. -func TestAMachineWithNoHostServiceIsRefusedRatherThanGivenOne(t *testing.T) { +func testAMachineWithNoHostServiceIsRefusedRatherThanGivenOne(t *testing.T) { runtime := &asked{answer: func(_ string, args []string) (string, error) { joined := strings.Join(args, " ") switch { @@ -231,7 +231,7 @@ func TestAMachineWithNoHostServiceIsRefusedRatherThanGivenOne(t *testing.T) { // A machine with no name is refused before anything is said to the mesh. The name is what the // record, the token, the assignment and the push all name, and one the installer invented would // match nothing anybody types anywhere else. -func TestAMachineWithNoNameIsRefusedBeforeAnythingIsAsked(t *testing.T) { +func testAMachineWithNoNameIsRefusedBeforeAnythingIsAsked(t *testing.T) { runtime := &asked{answer: func(string, []string) (string, error) { return "", fmt.Errorf("nothing should have been asked") }} @@ -247,7 +247,7 @@ func TestAMachineWithNoNameIsRefusedBeforeAnythingIsAsked(t *testing.T) { // The token is found in what the mesh said, by the rule the lab uses: the one long unbroken line. // The installer does not parse a format the control plane owns. -func TestTheTokenIsFoundInWhatTheMeshSaid(t *testing.T) { +func testTheTokenIsFoundInWhatTheMeshSaid(t *testing.T) { said := "a token for anchor, good once:\n\n " + strings.Repeat("t", 240) + "\n\n" + "carry it to the machine and run: mesh-host enrol --token \n" token, err := tokenIn(said) @@ -266,7 +266,7 @@ func TestTheTokenIsFoundInWhatTheMeshSaid(t *testing.T) { // A listing's name is matched as a whole word at the start of a line, so `registry` is not found // inside `registry-mirror`. A substring match would report a module installed that is not, and the // installer would skip creating it. -func TestAListingIsMatchedByNameAndNotBySubstring(t *testing.T) { +func testAListingIsMatchedByNameAndNotBySubstring(t *testing.T) { listing := "registry-mirror 1 built abc\nother 1 built def\n" if mentions(listing, "registry") { t.Error("registry-mirror was read as registry") @@ -280,7 +280,7 @@ func TestAListingIsMatchedByNameAndNotBySubstring(t *testing.T) { // 04-ISSUES/146). The enrolment account exists only in the mesh's records until somebody writes it // beside the bus; so does the node's own, minted as it enrols. Without the first, the machine is // refused by the bus it just raised; without the second, its agent is. -func TestAFirstNodeIsLetOntoTheBusItRaised(t *testing.T) { +func testAFirstNodeIsLetOntoTheBusItRaised(t *testing.T) { enrolled := false runtime := &asked{answer: func(name string, args []string) (string, error) { joined := strings.Join(args, " ") @@ -333,7 +333,7 @@ func TestAFirstNodeIsLetOntoTheBusItRaised(t *testing.T) { // controller's list again (novox/hq ADR 0331 §5, review of mesh-host #96). The apply just wrote the // bundle's list — the controller alone — over the one placed at enrolment; left so, the next time the // bus re-reads it every node and the enrolment account are refused. -func TestARerunOnAnEnrolledMachineWhoseBusIsNotAdoptedPlacesTheUsersAgain(t *testing.T) { +func testARerunOnAnEnrolledMachineWhoseBusIsNotAdoptedPlacesTheUsersAgain(t *testing.T) { runtime := &asked{answer: func(name string, args []string) (string, error) { joined := strings.Join(args, " ") switch { @@ -374,3 +374,17 @@ func TestARerunOnAnEnrolledMachineWhoseBusIsNotAdoptedPlacesTheUsersAgain(t *tes strings.Join(runtime.commands, "\n")) } } + +// TestEnrol runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestEnrol(t *testing.T) { + t.Run("AMachineThatHasAlreadyEnrolledIsNotEnrolledAgain", testAMachineThatHasAlreadyEnrolledIsNotEnrolledAgain) + t.Run("AMeshThatHasHeardFromAMachineWithNoAgentStartsOne", testAMeshThatHasHeardFromAMachineWithNoAgentStartsOne) + t.Run("AMachineEnrolledUnderAnotherNameIsRefused", testAMachineEnrolledUnderAnotherNameIsRefused) + t.Run("AHostThatIsRunningAndUnheardOfIsNotAnInstall", testAHostThatIsRunningAndUnheardOfIsNotAnInstall) + t.Run("AMachineWithNoHostServiceIsRefusedRatherThanGivenOne", testAMachineWithNoHostServiceIsRefusedRatherThanGivenOne) + t.Run("AMachineWithNoNameIsRefusedBeforeAnythingIsAsked", testAMachineWithNoNameIsRefusedBeforeAnythingIsAsked) + t.Run("TheTokenIsFoundInWhatTheMeshSaid", testTheTokenIsFoundInWhatTheMeshSaid) + t.Run("AListingIsMatchedByNameAndNotBySubstring", testAListingIsMatchedByNameAndNotBySubstring) + t.Run("AFirstNodeIsLetOntoTheBusItRaised", testAFirstNodeIsLetOntoTheBusItRaised) + t.Run("ARerunOnAnEnrolledMachineWhoseBusIsNotAdoptedPlacesTheUsersAgain", testARerunOnAnEnrolledMachineWhoseBusIsNotAdoptedPlacesTheUsersAgain) +} diff --git a/internal/bootstrap/genesis_form_test.go b/internal/bootstrap/genesis_form_test.go index b196c845..2c3dd9b4 100644 --- a/internal/bootstrap/genesis_form_test.go +++ b/internal/bootstrap/genesis_form_test.go @@ -67,7 +67,7 @@ func aRepository(t *testing.T, manifest string, then func(string, []string) (str // novox/hq issue 223: a controller declared as a process is raised at genesis as a container built // from its own Dockerfile, not by the builder — which has no Go toolchain at genesis and would refuse. -func TestAProcessFormControllerIsBuiltFromItsDockerfileAndRaisedAsAContainer(t *testing.T) { +func testAProcessFormControllerIsBuiltFromItsDockerfileAndRaisedAsAContainer(t *testing.T) { runtime := &asked{answer: aRepository(t, processFormManifest, func(name string, args []string) (string, error) { if name == "docker" && args[0] == "build" { return builtImage + "\n", nil @@ -152,7 +152,7 @@ func TestAProcessFormControllerIsBuiltFromItsDockerfileAndRaisedAsAContainer(t * } // An older controller — an image and a container — is still built by the builder, as before. -func TestAnImageFormControllerIsStillBuiltByTheBuilder(t *testing.T) { +func testAnImageFormControllerIsStillBuiltByTheBuilder(t *testing.T) { manifest := `{"module":"mesh-controller","version":"1","resources":[` + `{"id":"server","type":"container","name":"mesh-controller","image":"` + builtImage + `"}]}` runtime := &asked{answer: aRepository(t, imageFormManifest, func(name string, args []string) (string, error) { @@ -172,7 +172,7 @@ func TestAnImageFormControllerIsStillBuiltByTheBuilder(t *testing.T) { } } -func TestAProcessFormNamingNoOneReplacementIsRefused(t *testing.T) { +func testAProcessFormNamingNoOneReplacementIsRefused(t *testing.T) { for _, bad := range []string{`"replaces": []`, `"replaces": ["a", "b"]`} { raw := strings.Replace(processFormManifest, `"replaces": ["server"]`, bad, 1) if _, err := processFormOf([]byte(raw)); err == nil { @@ -204,7 +204,7 @@ func theStepNineSecretsOf(t *testing.T, manifest []byte) (map[string]string, err // window's settings reach the controller in a file its manifest declares from its settings // (MESH_MERGE_WINDOW_FILE, ADR 0276); genesis refused it as a secret nobody writes, and stopped at // step 11 of 24. -func TestAFileTheControllersManifestWritesIsNotASecret(t *testing.T) { +func testAFileTheControllersManifestWritesIsNotASecret(t *testing.T) { manifest := strings.Replace(processFormManifest, `{"id": "controller", "type": "process",`, `{"id": "merge-window", "type": "file", "path": "${dir:mesh-state}/merge-window.json", "mode": "0600", @@ -229,7 +229,7 @@ func TestAFileTheControllersManifestWritesIsNotASecret(t *testing.T) { } // And a `…_FILE` that neither an own-secret nor a file of the module writes is still refused. -func TestAFileNothingOfTheControllerWritesIsStillRefused(t *testing.T) { +func testAFileNothingOfTheControllerWritesIsStillRefused(t *testing.T) { manifest := strings.Replace(processFormManifest, `"MESH_BUS_NATS_FILE": "${dir:mesh-state}/bus"}`, `"MESH_BUS_NATS_FILE": "${dir:mesh-state}/bus", "MESH_MERGE_WINDOW_FILE": "${dir:mesh-state}/merge-window.json"}`, 1) @@ -237,3 +237,12 @@ func TestAFileNothingOfTheControllerWritesIsStillRefused(t *testing.T) { t.Fatalf("a file nothing writes was accepted, or refused without its name: %v", err) } } + +// TestGenesisForm runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestGenesisForm(t *testing.T) { + t.Run("AProcessFormControllerIsBuiltFromItsDockerfileAndRaisedAsAContainer", testAProcessFormControllerIsBuiltFromItsDockerfileAndRaisedAsAContainer) + t.Run("AnImageFormControllerIsStillBuiltByTheBuilder", testAnImageFormControllerIsStillBuiltByTheBuilder) + t.Run("AProcessFormNamingNoOneReplacementIsRefused", testAProcessFormNamingNoOneReplacementIsRefused) + t.Run("AFileTheControllersManifestWritesIsNotASecret", testAFileTheControllersManifestWritesIsNotASecret) + t.Run("AFileNothingOfTheControllerWritesIsStillRefused", testAFileNothingOfTheControllerWritesIsStillRefused) +} diff --git a/internal/bootstrap/genesis_registry_test.go b/internal/bootstrap/genesis_registry_test.go index 7cd34489..bd45b6fc 100644 --- a/internal/bootstrap/genesis_registry_test.go +++ b/internal/bootstrap/genesis_registry_test.go @@ -13,7 +13,7 @@ import ( // the base, so until then the packages step's genesis document is how the sdk and base steps reach the // forge. -func TestThePackagesStepSealsTheGenesisDocumentToTheBuildAgent(t *testing.T) { +func testThePackagesStepSealsTheGenesisDocumentToTheBuildAgent(t *testing.T) { if BuilderModule != "build-agent" { t.Fatalf("genesis installs %q; the document is the build agent's", BuilderModule) } @@ -42,7 +42,7 @@ func TestThePackagesStepSealsTheGenesisDocumentToTheBuildAgent(t *testing.T) { // What the retired builder was given and the build agent declares neither of: an `npm-password` // own-secret and a `serves` setting for its carried binding (ADR 0336 §3). -func TestNoStepGivesTheBuildAgentAServesSettingOrAnNpmPassword(t *testing.T) { +func testNoStepGivesTheBuildAgentAServesSettingOrAnNpmPassword(t *testing.T) { for _, module := range []string{BuilderModule} { c, control := recording(t) o := Options{Node: "anchor", Ports: FoundationPorts{Packages: 3100}, Wait: time.Second} @@ -63,3 +63,9 @@ func TestNoStepGivesTheBuildAgentAServesSettingOrAnNpmPassword(t *testing.T) { } } } + +// TestGenesisRegistry runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestGenesisRegistry(t *testing.T) { + t.Run("ThePackagesStepSealsTheGenesisDocumentToTheBuildAgent", testThePackagesStepSealsTheGenesisDocumentToTheBuildAgent) + t.Run("NoStepGivesTheBuildAgentAServesSettingOrAnNpmPassword", testNoStepGivesTheBuildAgentAServesSettingOrAnNpmPassword) +} diff --git a/internal/bootstrap/genesis_toolchains_test.go b/internal/bootstrap/genesis_toolchains_test.go index f1a81e30..e833d7a9 100644 --- a/internal/bootstrap/genesis_toolchains_test.go +++ b/internal/bootstrap/genesis_toolchains_test.go @@ -20,7 +20,7 @@ var genesisModules = []string{RegistryModule, BuilderModule, "postgres", BusModu // Every genesis module's bundles are compiled in a toolchain the base step builds, read from the real // catalogue's manifests: a module that gains a language genesis does not build fails here, not at a // genesis. -func TestTheBaseStepBuildsEveryToolchainAGenesisModuleIsCompiledIn(t *testing.T) { +func testTheBaseStepBuildsEveryToolchainAGenesisModuleIsCompiledIn(t *testing.T) { // ADR 0604 section 7: the catalog is the indexer's seat now, so genesis has no catalogue step and installs or takes no // mesh-catalog module. for _, step := range Steps { @@ -64,7 +64,7 @@ func TestTheBaseStepBuildsEveryToolchainAGenesisModuleIsCompiledIn(t *testing.T) } // And the base step asks for each toolchain's build: the base, then the Go toolchain beside it. -func TestTheBaseStepBuildsTheGoToolchainBesideTheBase(t *testing.T) { +func testTheBaseStepBuildsTheGoToolchainBesideTheBase(t *testing.T) { runtime := &asked{answer: aMeshThatAgrees(nil)} control := controlPlane{container: "mesh-controller", run: runtime.run, timeout: time.Second} o := Options{ToolsSource: Source{Repository: "git://192.0.2.30/mesh-tools.git"}} @@ -86,7 +86,7 @@ func TestTheBaseStepBuildsTheGoToolchainBesideTheBase(t *testing.T) { } } -func TestTheGoToolchainIsAsGivenOrBesideTheBase(t *testing.T) { +func testTheGoToolchainIsAsGivenOrBesideTheBase(t *testing.T) { for _, c := range []struct{ tools, given, want string }{ {"http://forge/novox/mesh-tools.git", "", "http://forge/novox/mesh-tools-go.git"}, {"http://forge/novox/mesh-tools", "", "http://forge/novox/mesh-tools-go"}, @@ -102,3 +102,10 @@ func TestTheGoToolchainIsAsGivenOrBesideTheBase(t *testing.T) { t.Errorf("a base not named mesh-tools, and no Go toolchain given, was not refused naming the flag: %v", err) } } + +// TestGenesisToolchains runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestGenesisToolchains(t *testing.T) { + t.Run("TheBaseStepBuildsEveryToolchainAGenesisModuleIsCompiledIn", testTheBaseStepBuildsEveryToolchainAGenesisModuleIsCompiledIn) + t.Run("TheBaseStepBuildsTheGoToolchainBesideTheBase", testTheBaseStepBuildsTheGoToolchainBesideTheBase) + t.Run("TheGoToolchainIsAsGivenOrBesideTheBase", testTheGoToolchainIsAsGivenOrBesideTheBase) +} diff --git a/internal/bootstrap/inuse_test.go b/internal/bootstrap/inuse_test.go index 594d334c..204ab722 100644 --- a/internal/bootstrap/inuse_test.go +++ b/internal/bootstrap/inuse_test.go @@ -38,7 +38,7 @@ func (m inUseRunner) run(_ context.Context, name string, args ...string) (string return m.ss, nil } -func TestAFreshMachineIsNotInUse(t *testing.T) { +func testAFreshMachineIsNotInUse(t *testing.T) { containers, listeners, err := InUse(context.Background(), inUseRunner{ss: inUseSockets}.run, func(string) bool { return false }) if err != nil { @@ -49,7 +49,7 @@ func TestAFreshMachineIsNotInUse(t *testing.T) { } } -func TestAMachineServingIsInUse(t *testing.T) { +func testAMachineServingIsInUse(t *testing.T) { m := inUseRunner{ps: "hello-web\t\nmesh-store\tabc123\n", ss: inUseSockets + servingSockets} containers, listeners, err := InUse(context.Background(), m.run, func(string) bool { return false }) if err != nil { @@ -67,7 +67,7 @@ func TestAMachineServingIsInUse(t *testing.T) { } } -func TestAConvergedGenesisRefusesAMachineInUseNamingEverything(t *testing.T) { +func testAConvergedGenesisRefusesAMachineInUseNamingEverything(t *testing.T) { o := Options{State: filepath.Join(t.TempDir(), "state.json")} m := inUseRunner{ps: "hello-web\t\n", ss: inUseSockets + servingSockets} err := RefuseAMachineInUse(context.Background(), o, m.run, quietly) @@ -86,7 +86,7 @@ func TestAConvergedGenesisRefusesAMachineInUseNamingEverything(t *testing.T) { } } -func TestARerunOfGenesisIsNotAMachineInUse(t *testing.T) { +func testARerunOfGenesisIsNotAMachineInUse(t *testing.T) { o := Options{State: filepath.Join(t.TempDir(), "state.json")} if err := store.Save(o.State, store.State{Resources: []store.Applied{{ID: "store", Type: "container", Target: "mesh-store"}}}); err != nil { t.Fatal(err) @@ -97,7 +97,7 @@ func TestARerunOfGenesisIsNotAMachineInUse(t *testing.T) { } } -func TestAFreshlyInstalledMachineAsMeasuredIsNotInUse(t *testing.T) { +func testAFreshlyInstalledMachineAsMeasuredIsNotInUse(t *testing.T) { // Captured with `ss -Hltunp` on a freshly installed lab machine: its resolver listens on TCP on // every address, which the record's words alone would count. raw, err := os.ReadFile("testdata/fresh-machine-listeners.txt") @@ -121,7 +121,7 @@ func TestAFreshlyInstalledMachineAsMeasuredIsNotInUse(t *testing.T) { // Defends novox/hq ADR 0103: a machine raised adopted stays adopted if genesis is run again. The // installer reads the mode from what the machine records, and refuses a flag that disagrees. -func TestARerunWithoutTheFlagOnAnAdoptedMachineIsRefused(t *testing.T) { +func testARerunWithoutTheFlagOnAnAdoptedMachineIsRefused(t *testing.T) { o := Options{State: filepath.Join(t.TempDir(), "state.json")} adoptedState := store.State{Resources: []store.Applied{ {ID: "store", Type: "container", Target: "mesh-store", Origin: store.OriginCarried}, @@ -141,7 +141,7 @@ func TestARerunWithoutTheFlagOnAnAdoptedMachineIsRefused(t *testing.T) { } } -func TestARerunWithTheFlagOnAConvergedMachineIsRefused(t *testing.T) { +func testARerunWithTheFlagOnAConvergedMachineIsRefused(t *testing.T) { o := Options{State: filepath.Join(t.TempDir(), "state.json"), Adopted: true} converged := store.State{Resources: []store.Applied{ {ID: "store", Type: "container", Target: "mesh-store", Origin: store.OriginCarried}, @@ -162,7 +162,7 @@ func TestARerunWithTheFlagOnAConvergedMachineIsRefused(t *testing.T) { } } -func TestOnlyTheDaemonsTheMeasurementFoundAreQuiet(t *testing.T) { +func testOnlyTheDaemonsTheMeasurementFoundAreQuiet(t *testing.T) { // novox/hq ADR 0101: the exempt daemons are the ones a fresh machine was measured to run — // the resolver and the network manager. A time client or a DHCP client listening beyond // loopback is something somebody put there, and that is a machine in use. @@ -177,3 +177,15 @@ udp UNCONN 0 0 0.0.0.0:68 0.0.0 t.Errorf("counted %d listener(s), want the time client and the DHCP client: %+v", len(listeners), listeners) } } + +// TestInuse runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestInuse(t *testing.T) { + t.Run("AFreshMachineIsNotInUse", testAFreshMachineIsNotInUse) + t.Run("AMachineServingIsInUse", testAMachineServingIsInUse) + t.Run("AConvergedGenesisRefusesAMachineInUseNamingEverything", testAConvergedGenesisRefusesAMachineInUseNamingEverything) + t.Run("ARerunOfGenesisIsNotAMachineInUse", testARerunOfGenesisIsNotAMachineInUse) + t.Run("AFreshlyInstalledMachineAsMeasuredIsNotInUse", testAFreshlyInstalledMachineAsMeasuredIsNotInUse) + t.Run("ARerunWithoutTheFlagOnAnAdoptedMachineIsRefused", testARerunWithoutTheFlagOnAnAdoptedMachineIsRefused) + t.Run("ARerunWithTheFlagOnAConvergedMachineIsRefused", testARerunWithTheFlagOnAConvergedMachineIsRefused) + t.Run("OnlyTheDaemonsTheMeasurementFoundAreQuiet", testOnlyTheDaemonsTheMeasurementFoundAreQuiet) +} diff --git a/internal/bootstrap/load_test.go b/internal/bootstrap/load_test.go index 27076030..7d1c3997 100644 --- a/internal/bootstrap/load_test.go +++ b/internal/bootstrap/load_test.go @@ -93,7 +93,7 @@ const ( // // So the image is identified by its TAG, which survives save and load unchanged, and the runtime // is asked what that tag resolves to. -func TestTheIdComesFromTheRuntimeAndNotFromTheArchive(t *testing.T) { +func testTheIdComesFromTheRuntimeAndNotFromTheArchive(t *testing.T) { runtime := &asked{} inspected := 0 runtime.answer = func(_ string, args []string) (string, error) { @@ -145,7 +145,7 @@ func TestTheIdComesFromTheRuntimeAndNotFromTheArchive(t *testing.T) { // indistinguishable from one that had never run. **Decided from what the runtime holds under the // tag, not from what the archive predicts** — a predicted id cannot answer this question at all on // a machine whose runtime rewrites configurations. -func TestAnImageThisMachineAlreadyHoldsIsNotLoadedAgain(t *testing.T) { +func testAnImageThisMachineAlreadyHoldsIsNotLoadedAgain(t *testing.T) { runtime := &asked{answer: func(_ string, args []string) (string, error) { if len(args) > 1 && args[0] == "image" && args[1] == "inspect" { return "sha256:" + runtimeDigest + "\n", nil @@ -178,7 +178,7 @@ func TestAnImageThisMachineAlreadyHoldsIsNotLoadedAgain(t *testing.T) { // A load that reported success and left nothing there is a failure, not a convergence // (novox/hq ADR 0018). Without the read-back it would surface later as the host refusing a bundle // naming an image nothing serves — a true message about the wrong thing. -func TestALoadThatLeftNothingBehindIsAFailure(t *testing.T) { +func testALoadThatLeftNothingBehindIsAFailure(t *testing.T) { runtime := &asked{answer: func(_ string, args []string) (string, error) { if len(args) > 1 && args[0] == "image" && args[1] == "inspect" { return "", errors.New("Error: No such image") @@ -201,7 +201,7 @@ func TestALoadThatLeftNothingBehindIsAFailure(t *testing.T) { // runtime has decided anything, and the id in the archive is a fact about a file rather than a // prediction about this machine. `--dry-run` still produces and checks the bundle's shape; what it // cannot promise is the one value that only a load can settle. -func TestADryRunLoadsNothingAndSaysTheIdIsUnconfirmed(t *testing.T) { +func testADryRunLoadsNothingAndSaysTheIdIsUnconfirmed(t *testing.T) { runtime := &asked{answer: func(_ string, args []string) (string, error) { if len(args) > 1 && args[0] == "image" && args[1] == "inspect" { return "", errors.New("Error: No such image") @@ -231,7 +231,7 @@ func TestADryRunLoadsNothingAndSaysTheIdIsUnconfirmed(t *testing.T) { // A dry run on a machine that already holds the image DOES know the id, because the runtime was // asked and answered. Reading is not changing, so a dry run is entitled to that. -func TestADryRunOnAMachineThatHoldsItKnowsTheRealId(t *testing.T) { +func testADryRunOnAMachineThatHoldsItKnowsTheRealId(t *testing.T) { runtime := &asked{answer: func(_ string, args []string) (string, error) { if len(args) > 1 && args[0] == "image" && args[1] == "inspect" { return "sha256:" + runtimeDigest + "\n", nil @@ -256,7 +256,7 @@ func TestADryRunOnAMachineThatHoldsItKnowsTheRealId(t *testing.T) { // there is no portable name to ask the runtime about, and the only thing left is scraping the // sentence `docker load` prints for a person — which differs between runtime versions and is // exactly the kind of guess this whole step exists to stop making. -func TestAnUntaggedArchiveIsRefused(t *testing.T) { +func testAnUntaggedArchiveIsRefused(t *testing.T) { runtime := &asked{answer: func(_ string, args []string) (string, error) { return "", fmt.Errorf("nothing should have been run: %v", args) }} @@ -276,7 +276,7 @@ func TestAnUntaggedArchiveIsRefused(t *testing.T) { // An installer built from a plain checkout carries no image, and says which build step is missing. // Discovered here, before a machine is touched, rather than after a bundle has been written. -func TestAnInstallerCarryingNoImageSaysSoRatherThanRaisingHalfAMesh(t *testing.T) { +func testAnInstallerCarryingNoImageSaysSoRatherThanRaisingHalfAMesh(t *testing.T) { if !image.IsEmpty() { t.Skip("this checkout has a saved image embedded") } @@ -296,7 +296,7 @@ func TestAnInstallerCarryingNoImageSaysSoRatherThanRaisingHalfAMesh(t *testing.T // rewrites an image's configuration as it loads. What is still worth refusing is an answer that is // not an id at all — that value becomes the name a bundle applies on a machine with no mesh to // check anything against, so it is checked where the refusal can say whose mistake it is. -func TestARuntimeAnsweringSomethingThatIsNotAnImageIdIsRefused(t *testing.T) { +func testARuntimeAnsweringSomethingThatIsNotAnImageIdIsRefused(t *testing.T) { for _, nonsense := range []string{ "mesh-controller:test", "sha256:" + strings.Repeat("9", 63), @@ -311,3 +311,15 @@ func TestARuntimeAnsweringSomethingThatIsNotAnImageIdIsRefused(t *testing.T) { } } } + +// TestLoad runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestLoad(t *testing.T) { + t.Run("TheIdComesFromTheRuntimeAndNotFromTheArchive", testTheIdComesFromTheRuntimeAndNotFromTheArchive) + t.Run("AnImageThisMachineAlreadyHoldsIsNotLoadedAgain", testAnImageThisMachineAlreadyHoldsIsNotLoadedAgain) + t.Run("ALoadThatLeftNothingBehindIsAFailure", testALoadThatLeftNothingBehindIsAFailure) + t.Run("ADryRunLoadsNothingAndSaysTheIdIsUnconfirmed", testADryRunLoadsNothingAndSaysTheIdIsUnconfirmed) + t.Run("ADryRunOnAMachineThatHoldsItKnowsTheRealId", testADryRunOnAMachineThatHoldsItKnowsTheRealId) + t.Run("AnUntaggedArchiveIsRefused", testAnUntaggedArchiveIsRefused) + t.Run("AnInstallerCarryingNoImageSaysSoRatherThanRaisingHalfAMesh", testAnInstallerCarryingNoImageSaysSoRatherThanRaisingHalfAMesh) + t.Run("ARuntimeAnsweringSomethingThatIsNotAnImageIdIsRefused", testARuntimeAnsweringSomethingThatIsNotAnImageIdIsRefused) +} diff --git a/internal/bootstrap/phase2_test.go b/internal/bootstrap/phase2_test.go index b1b46f32..65567481 100644 --- a/internal/bootstrap/phase2_test.go +++ b/internal/bootstrap/phase2_test.go @@ -7,7 +7,7 @@ import ( // The endpoint other machines dial defaults to the host they already dial — the broker's — on // WireGuard's port. One fact, not two that drift. -func TestTheEndpointDerivesFromTheBrokerAddress(t *testing.T) { +func testTheEndpointDerivesFromTheBrokerAddress(t *testing.T) { if got := derivedEndpoint("192.0.2.10:5671", 51820); got != "192.0.2.10:51820" { t.Fatalf("derived %q", got) } @@ -18,7 +18,7 @@ func TestTheEndpointDerivesFromTheBrokerAddress(t *testing.T) { // A manifest with artifacts builds; one without does not — which is what separates postgres (a // bundle to compile) from nftables (a package and a service). -func TestOnlyAManifestWithArtifactsBuilds(t *testing.T) { +func testOnlyAManifestWithArtifactsBuilds(t *testing.T) { if !builds([]byte(`{"build":{"artifacts":[{"name":"x"}]}}`)) { t.Fatal("a manifest with artifacts was not built") } @@ -29,7 +29,7 @@ func TestOnlyAManifestWithArtifactsBuilds(t *testing.T) { // Defends novox/hq ADR 0100: the hub's port is the node's, and the endpoint other machines dial // must name it — an endpoint on another port is an address nothing answers on. -func TestTheEndpointAgreesWithTheHubsPort(t *testing.T) { +func testTheEndpointAgreesWithTheHubsPort(t *testing.T) { if got, err := endpointAgrees("192.0.2.10:51820", 51820); err != nil || got != "192.0.2.10:51820" { t.Errorf("an endpoint on the hub's port: %q %v", got, err) } @@ -44,3 +44,10 @@ func TestTheEndpointAgreesWithTheHubsPort(t *testing.T) { t.Error("an endpoint whose port is not a number was accepted") } } + +// TestPhase2 runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestPhase2(t *testing.T) { + t.Run("TheEndpointDerivesFromTheBrokerAddress", testTheEndpointDerivesFromTheBrokerAddress) + t.Run("OnlyAManifestWithArtifactsBuilds", testOnlyAManifestWithArtifactsBuilds) + t.Run("TheEndpointAgreesWithTheHubsPort", testTheEndpointAgreesWithTheHubsPort) +} diff --git a/internal/bootstrap/phase3_test.go b/internal/bootstrap/phase3_test.go index c597a920..bb3f2f41 100644 --- a/internal/bootstrap/phase3_test.go +++ b/internal/bootstrap/phase3_test.go @@ -92,7 +92,7 @@ func busStep(t *testing.T, catalogue string) (*asked, error) { // The broker step adopts the foundation's bus as the nats module (novox/hq ADR 0331 §1): the module // the mesh goes on managing, registered from the catalogue — never lavinmq, which left it. -func TestTheBrokerStepAdoptsTheBusAsTheNatsModule(t *testing.T) { +func testTheBrokerStepAdoptsTheBusAsTheNatsModule(t *testing.T) { catalogue := aCatalogue(t, map[string]string{BusModule: aBusModule(theModulesLayout)}) runtime, err := busStep(t, catalogue) if err != nil { @@ -108,7 +108,7 @@ func TestTheBrokerStepAdoptsTheBusAsTheNatsModule(t *testing.T) { // A catalogue that holds no nats module fails the step by name, before anything is registered — // which is what today's step did for lavinmq, silently adopting a module that no longer exists. -func TestTheBrokerStepFailsForAModuleTheCatalogueDoesNotHold(t *testing.T) { +func testTheBrokerStepFailsForAModuleTheCatalogueDoesNotHold(t *testing.T) { catalogue := aCatalogue(t, map[string]string{"lavinmq": `{"module": "lavinmq", "version": "1"}`}) runtime, err := busStep(t, catalogue) if err == nil { @@ -126,7 +126,7 @@ func TestTheBrokerStepFailsForAModuleTheCatalogueDoesNotHold(t *testing.T) { // beside the first, or an empty one on other paths (novox/hq ADR 0333 §1). It is refused naming every // difference with both sides, before anything is registered. The layout is the one the bundle had // before ADR 0333, kept as a module's here: the refusal genesis stopped at, at step 18 (issue 590). -func TestABusModuleWhoseLayoutIsNotTheFoundationsIsRefused(t *testing.T) { +func testABusModuleWhoseLayoutIsNotTheFoundationsIsRefused(t *testing.T) { before := busLayout{Container: "mesh-broker", Streams: "mesh-broker-data", Conf: "/var/lib/mesh-bus-conf", Certificate: "mesh-broker-tls", Users: "/var/lib/mesh-bus-conf/accounts.conf"} catalogue := aCatalogue(t, map[string]string{BusModule: aBusModule(before)}) @@ -150,7 +150,7 @@ func TestABusModuleWhoseLayoutIsNotTheFoundationsIsRefused(t *testing.T) { // One field moved is refused as surely as all of them: a module whose streams are elsewhere would be // raised empty on the bus's own name. -func TestABusModuleWithItsStreamsElsewhereIsRefused(t *testing.T) { +func testABusModuleWithItsStreamsElsewhereIsRefused(t *testing.T) { moved := theModulesLayout moved.Streams = "/srv/nats" catalogue := aCatalogue(t, map[string]string{BusModule: aBusModule(moved)}) @@ -169,7 +169,7 @@ func TestABusModuleWithItsStreamsElsewhereIsRefused(t *testing.T) { // The node's bus port is kept (novox/hq ADR 0333 §2): the module declares 4222, and the broker step // gives it the setting that maps that to the port the bundle published, 5671 unless given — before the // push, so the first declaration already names it. -func TestTheBrokerStepGivesTheModuleTheNodesBusPort(t *testing.T) { +func testTheBrokerStepGivesTheModuleTheNodesBusPort(t *testing.T) { for _, c := range []struct { given int want string @@ -203,7 +203,7 @@ func TestTheBrokerStepGivesTheModuleTheNodesBusPort(t *testing.T) { // The one restart is said before it happens, and the step goes on only once the bus runs the module's // image and answers (novox/hq ADR 0333 §3). -func TestTheBrokerStepSaysTheRestartAndWaitsForTheBusToAnswer(t *testing.T) { +func testTheBrokerStepSaysTheRestartAndWaitsForTheBusToAnswer(t *testing.T) { previous := answerEvery answerEvery = time.Millisecond defer func() { answerEvery = previous }() @@ -266,7 +266,7 @@ func TestTheBrokerStepSaysTheRestartAndWaitsForTheBusToAnswer(t *testing.T) { // A bus still on the bundle's image when the wait runs out is refused, naming the image: every step after // this one reaches the mesh through that bus, and the push was not applied. -func TestABusTheNodeDidNotRecreateIsRefused(t *testing.T) { +func testABusTheNodeDidNotRecreateIsRefused(t *testing.T) { previous := answerEvery answerEvery = time.Millisecond defer func() { answerEvery = previous }() @@ -295,7 +295,7 @@ func TestABusTheNodeDidNotRecreateIsRefused(t *testing.T) { // A re-run after the adoption finds the bus on the module's image already, and says so rather than // announcing a restart that does not happen. -func TestARerunAfterTheAdoptionSaysTheBusIsTheModulesAlready(t *testing.T) { +func testARerunAfterTheAdoptionSaysTheBusIsTheModulesAlready(t *testing.T) { catalogue := aCatalogue(t, map[string]string{BusModule: aBusModule(theModulesLayout)}) runtime, fetch := aBusThatAdopts() o := installing(t, catalogue) @@ -341,7 +341,7 @@ func theCataloguesBusModule(t *testing.T) []byte { // manifest: the bus's container, its streams, its configuration, its certificate and its user list are // where the module keeps them, so adopting the bus keeps it. Before ADR 0333 the bundle raised // `mesh-broker` on volumes the module never mounts, and genesis stopped at step 18 (issue 590). -func TestTheBundleRaisesTheBusWhereTheCataloguesModuleKeepsIt(t *testing.T) { +func testTheBundleRaisesTheBusWhereTheCataloguesModuleKeepsIt(t *testing.T) { manifest := theCataloguesBusModule(t) rewritten, err := Rewrite(theRealBundle(t), held) if err != nil { @@ -377,7 +377,7 @@ func TestTheBundleRaisesTheBusWhereTheCataloguesModuleKeepsIt(t *testing.T) { // The bundle as the installer reads it agrees with the module's layout as this repository states it, // and with where the installer's bridge writes (ADR 0333 §4): the bridge places the users in the file the // bus reads, and makes the container that reads it re-read it. -func TestTheBridgeWritesWhereTheBundleRaisesTheBus(t *testing.T) { +func testTheBridgeWritesWhereTheBundleRaisesTheBus(t *testing.T) { rewritten, err := Rewrite(theRealBundle(t), held) if err != nil { t.Fatal(err) @@ -401,7 +401,7 @@ func TestTheBridgeWritesWhereTheBundleRaisesTheBus(t *testing.T) { // The bundle's bus configuration and user list are seeds (create-once): an installer run again after // the adoption applies the bundle again, and must not put the bundle's one user back over the users the // module writes there (ADR 0333 §4). -func TestTheBundlesBusFilesAreSeeds(t *testing.T) { +func testTheBundlesBusFilesAreSeeds(t *testing.T) { rewritten, err := Rewrite(theRealBundle(t), held) if err != nil { t.Fatal(err) @@ -445,3 +445,18 @@ func aGenesisBusOnDisk(t *testing.T) { // aCertificatePEM is a PEM block standing for the bus's certificate; its pin is the sha256 of these bytes. const aCertificatePEM = "-----BEGIN CERTIFICATE-----\nAAECAwQFBgcICQ==\n-----END CERTIFICATE-----\n" + +// TestPhase3 runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestPhase3(t *testing.T) { + t.Run("TheBrokerStepAdoptsTheBusAsTheNatsModule", testTheBrokerStepAdoptsTheBusAsTheNatsModule) + t.Run("TheBrokerStepFailsForAModuleTheCatalogueDoesNotHold", testTheBrokerStepFailsForAModuleTheCatalogueDoesNotHold) + t.Run("ABusModuleWhoseLayoutIsNotTheFoundationsIsRefused", testABusModuleWhoseLayoutIsNotTheFoundationsIsRefused) + t.Run("ABusModuleWithItsStreamsElsewhereIsRefused", testABusModuleWithItsStreamsElsewhereIsRefused) + t.Run("TheBrokerStepGivesTheModuleTheNodesBusPort", testTheBrokerStepGivesTheModuleTheNodesBusPort) + t.Run("TheBrokerStepSaysTheRestartAndWaitsForTheBusToAnswer", testTheBrokerStepSaysTheRestartAndWaitsForTheBusToAnswer) + t.Run("ABusTheNodeDidNotRecreateIsRefused", testABusTheNodeDidNotRecreateIsRefused) + t.Run("ARerunAfterTheAdoptionSaysTheBusIsTheModulesAlready", testARerunAfterTheAdoptionSaysTheBusIsTheModulesAlready) + t.Run("TheBundleRaisesTheBusWhereTheCataloguesModuleKeepsIt", testTheBundleRaisesTheBusWhereTheCataloguesModuleKeepsIt) + t.Run("TheBridgeWritesWhereTheBundleRaisesTheBus", testTheBridgeWritesWhereTheBundleRaisesTheBus) + t.Run("TheBundlesBusFilesAreSeeds", testTheBundlesBusFilesAreSeeds) +} diff --git a/internal/bootstrap/ports_test.go b/internal/bootstrap/ports_test.go index ed5bbb95..d2622ef0 100644 --- a/internal/bootstrap/ports_test.go +++ b/internal/bootstrap/ports_test.go @@ -46,7 +46,7 @@ func containerNamed(d *declaration.Declaration, name string) *declaration.Contai return nil } -func TestTheDefaultPortsLeaveTheBundleAsItWas(t *testing.T) { +func testTheDefaultPortsLeaveTheBundleAsItWas(t *testing.T) { r := producedBundle(t) before := string(r.Bundle) got, err := RewritePorts(&r, DefaultPorts(), DefaultOverlayRange) @@ -58,7 +58,7 @@ func TestTheDefaultPortsLeaveTheBundleAsItWas(t *testing.T) { } } -func TestGivenPortsMoveOnlyTheMachinesSide(t *testing.T) { +func testGivenPortsMoveOnlyTheMachinesSide(t *testing.T) { r := producedBundle(t) p := FoundationPorts{Store: 5433, Bus: 5771, Registry: 5100} got, err := RewritePorts(&r, p, "10.77.0.0/16") @@ -110,7 +110,7 @@ func TestGivenPortsMoveOnlyTheMachinesSide(t *testing.T) { } } -func TestATemplateThatDoesNotSayItsPortsAsExpectedIsRefused(t *testing.T) { +func testATemplateThatDoesNotSayItsPortsAsExpectedIsRefused(t *testing.T) { r := producedBundle(t) r.Bundle = []byte(strings.Replace(string(r.Bundle), `"ports": ["5432:5432"]`, `"ports": [ "5432:5432" ]`, 1)) if _, err := RewritePorts(&r, FoundationPorts{Store: 5433}, ""); err == nil { @@ -118,7 +118,7 @@ func TestATemplateThatDoesNotSayItsPortsAsExpectedIsRefused(t *testing.T) { } } -func TestTwoThingsOnOnePortAreRefused(t *testing.T) { +func testTwoThingsOnOnePortAreRefused(t *testing.T) { p := DefaultPorts() p.Registry = p.Store if err := p.Check(); err == nil { @@ -165,7 +165,7 @@ func (m machineRunner) run(_ context.Context, name string, args ...string) (stri func noneOurs(reachable.Reach) bool { return false } -func TestABusyPortIsRefusedNamingItsHolder(t *testing.T) { +func testABusyPortIsRefusedNamingItsHolder(t *testing.T) { m := machineRunner{ ss: "tcp LISTEN 0 4096 0.0.0.0:5000 0.0.0.0:* users:((\"docker-proxy\",pid=1,fd=7))\n" + "tcp LISTEN 0 4096 0.0.0.0:5671 0.0.0.0:* users:((\"beam.smp\",pid=2,fd=7))\n", @@ -187,7 +187,7 @@ func TestABusyPortIsRefusedNamingItsHolder(t *testing.T) { } } -func TestTheFoundationsOwnContainersAreNotCountedOnARerun(t *testing.T) { +func testTheFoundationsOwnContainersAreNotCountedOnARerun(t *testing.T) { m := machineRunner{ ss: "tcp LISTEN 0 4096 0.0.0.0:5432 0.0.0.0:* users:((\"docker-proxy\",pid=1,fd=7))\n", ps: "mesh-store\t0.0.0.0:5432->5432/tcp\n", @@ -198,7 +198,7 @@ func TestTheFoundationsOwnContainersAreNotCountedOnARerun(t *testing.T) { } } -func TestAnOverlappingTunnelIsRefusedNamingItsInterface(t *testing.T) { +func testAnOverlappingTunnelIsRefusedNamingItsInterface(t *testing.T) { m := machineRunner{ addrs: "1: lo inet 127.0.0.1/8 scope host lo\n5: wg0 inet 10.42.3.1/24 scope global wg0\n7: mesh0 inet 10.42.0.1/16 scope global mesh0\n", routes: "default via 192.0.2.1 dev eth0\n10.42.3.0/24 dev wg0 proto kernel scope link src 10.42.3.1\n", @@ -212,7 +212,7 @@ func TestAnOverlappingTunnelIsRefusedNamingItsInterface(t *testing.T) { } } -func TestAPredecessorsContainerUnderTheMeshsNameIsRefused(t *testing.T) { +func testAPredecessorsContainerUnderTheMeshsNameIsRefused(t *testing.T) { m := machineRunner{unlabelled: map[string]bool{"mesh-registry": true}, labelled: map[string]bool{"mesh-store": true}} err := NamesFree(context.Background(), m.run, []string{"mesh-store", "mesh-registry", "mesh-broker"}, store.State{}) if err == nil || !strings.Contains(err.Error(), "mesh-registry") || strings.Contains(err.Error(), "mesh-store") { @@ -258,7 +258,7 @@ func (c *controlRecorder) index(prefix string) int { return -1 } -func TestTheNodesPortsAreSetBeforeTheModuleIsPushed(t *testing.T) { +func testTheNodesPortsAreSetBeforeTheModuleIsPushed(t *testing.T) { t.Setenv("TMPDIR", t.TempDir()) c := &controlRecorder{settings: map[string]string{}} control := controlPlane{container: "temp-mesh-controller", run: c.run, timeout: time.Second} @@ -281,7 +281,7 @@ func TestTheNodesPortsAreSetBeforeTheModuleIsPushed(t *testing.T) { } } -func TestAGenesisOnTheDefaultsSetsNoSettings(t *testing.T) { +func testAGenesisOnTheDefaultsSetsNoSettings(t *testing.T) { t.Setenv("TMPDIR", t.TempDir()) c := &controlRecorder{settings: map[string]string{}} control := controlPlane{container: "temp-mesh-controller", run: c.run, timeout: time.Second} @@ -294,7 +294,7 @@ func TestAGenesisOnTheDefaultsSetsNoSettings(t *testing.T) { } } -func TestARerunOfGenesisFindsItsOwnPackageRegistry(t *testing.T) { +func testARerunOfGenesisFindsItsOwnPackageRegistry(t *testing.T) { // Raised by genesis itself with no label and no record, so a re-run finds it unlabelled. m := machineRunner{unlabelled: map[string]bool{giteaBootstrap: true}} rerun := store.State{Resources: []store.Applied{{ID: "store", Type: "container", Target: "mesh-store"}}} @@ -309,7 +309,7 @@ func TestARerunOfGenesisFindsItsOwnPackageRegistry(t *testing.T) { // novox/hq ADR 0105: an adopted genesis takes over the tunnel it finds — its port is the hub's, // its range the mesh's, and neither is refused for being held by it. -func TestAnAdoptedGenesisSettlesOnTheTunnelItFinds(t *testing.T) { +func testAnAdoptedGenesisSettlesOnTheTunnelItFinds(t *testing.T) { private, err := aFoundKey() if err != nil { t.Fatal(err) @@ -379,3 +379,19 @@ func aFoundKey() (string, error) { } return base64.StdEncoding.EncodeToString(k.Bytes()), nil } + +// TestPorts runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestPorts(t *testing.T) { + t.Run("TheDefaultPortsLeaveTheBundleAsItWas", testTheDefaultPortsLeaveTheBundleAsItWas) + t.Run("GivenPortsMoveOnlyTheMachinesSide", testGivenPortsMoveOnlyTheMachinesSide) + t.Run("ATemplateThatDoesNotSayItsPortsAsExpectedIsRefused", testATemplateThatDoesNotSayItsPortsAsExpectedIsRefused) + t.Run("TwoThingsOnOnePortAreRefused", testTwoThingsOnOnePortAreRefused) + t.Run("ABusyPortIsRefusedNamingItsHolder", testABusyPortIsRefusedNamingItsHolder) + t.Run("TheFoundationsOwnContainersAreNotCountedOnARerun", testTheFoundationsOwnContainersAreNotCountedOnARerun) + t.Run("AnOverlappingTunnelIsRefusedNamingItsInterface", testAnOverlappingTunnelIsRefusedNamingItsInterface) + t.Run("APredecessorsContainerUnderTheMeshsNameIsRefused", testAPredecessorsContainerUnderTheMeshsNameIsRefused) + t.Run("TheNodesPortsAreSetBeforeTheModuleIsPushed", testTheNodesPortsAreSetBeforeTheModuleIsPushed) + t.Run("AGenesisOnTheDefaultsSetsNoSettings", testAGenesisOnTheDefaultsSetsNoSettings) + t.Run("ARerunOfGenesisFindsItsOwnPackageRegistry", testARerunOfGenesisFindsItsOwnPackageRegistry) + t.Run("AnAdoptedGenesisSettlesOnTheTunnelItFinds", testAnAdoptedGenesisSettlesOnTheTunnelItFinds) +} diff --git a/internal/bootstrap/preflight_test.go b/internal/bootstrap/preflight_test.go index 4c4745bb..0a284f43 100644 --- a/internal/bootstrap/preflight_test.go +++ b/internal/bootstrap/preflight_test.go @@ -16,7 +16,7 @@ import ( // The refusal has to be plain, because the person reading it is standing in front of a machine // that will not work: it says what was asked, what came back, that re-running is safe, and names // the record that explains why an installed docker is not enough. -func TestPreflightRefusesPlainlyWhenTheRuntimeDoesNotAnswer(t *testing.T) { +func testPreflightRefusesPlainlyWhenTheRuntimeDoesNotAnswer(t *testing.T) { silent := func(context.Context, string, ...string) (string, error) { return "", errors.New("Cannot connect to the Docker daemon at unix:///var/run/docker.sock") } @@ -44,7 +44,7 @@ func TestPreflightRefusesPlainlyWhenTheRuntimeDoesNotAnswer(t *testing.T) { // Refusing on the first attempt would make a correct bootstrap fail for being observed too early — // and `docker load` against such a daemon blocks silently rather than failing, which is how one // became a 35-minute silence (04-ISSUES/024). -func TestARuntimeThatIsStillStartingIsWaitedFor(t *testing.T) { +func testARuntimeThatIsStillStartingIsWaitedFor(t *testing.T) { previous := runtimeAskEvery runtimeAskEvery = time.Millisecond defer func() { runtimeAskEvery = previous }() @@ -76,7 +76,7 @@ func TestARuntimeThatIsStillStartingIsWaitedFor(t *testing.T) { // The mesh's own image is carried and nothing serves it, so asking a registry about it would be // asking a question with no answer — which is the whole point of naming an image by the digest of // its own configuration. -func TestOnlyTheRegistriesTheBundleNamesAreAskedAbout(t *testing.T) { +func testOnlyTheRegistriesTheBundleNamesAreAskedAbout(t *testing.T) { parsed, err := declaration.ParseFileTrusted([]byte(`{"declaration":1,"resources":[ {"id":"store","type":"container","name":"mesh-store","image":"postgres@sha256:` + strings.Repeat("7", 64) + `"}, @@ -107,7 +107,7 @@ func TestOnlyTheRegistriesTheBundleNamesAreAskedAbout(t *testing.T) { // but preflight was reading that slot like any other and dialling it. The lab's template still // carried the address of a registry the lab no longer raises, so a correct install timed out in // preflight against a machine with a perfectly good network. -func TestTheControlPlanesOwnRegistryIsNeverAskedAbout(t *testing.T) { +func testTheControlPlanesOwnRegistryIsNeverAskedAbout(t *testing.T) { parsed, err := declaration.ParseFileTrusted([]byte(`{"declaration":1,"resources":[ {"id":"store","type":"container","name":"mesh-store","image":"postgres@sha256:` + strings.Repeat("7", 64) + `"}, @@ -125,7 +125,7 @@ func TestTheControlPlanesOwnRegistryIsNeverAskedAbout(t *testing.T) { } } -func TestWhereAnImageWouldBeFetchedFrom(t *testing.T) { +func testWhereAnImageWouldBeFetchedFrom(t *testing.T) { // The container runtime's own rule: the part before the first slash is a registry host if it // has a dot, a port, or is localhost. Getting this wrong means dialling a hostname that is // really the first half of a repository name, and refusing a machine that is fine. @@ -153,7 +153,7 @@ func TestWhereAnImageWouldBeFetchedFrom(t *testing.T) { // A template whose temporary control plane is given no bus is refused at preflight, before anything // is changed, rather than raised and waited on at the verify step until its timeout (novox/hq issue // 146, ADR 0331 §4): that control plane says it has no MESH_BUS_NATS every few seconds, for ever. -func TestATemplateWhoseControlPlaneHasNoBusIsRefusedBeforeAnythingIsRaised(t *testing.T) { +func testATemplateWhoseControlPlaneHasNoBusIsRefusedBeforeAnythingIsRaised(t *testing.T) { template := string(theRealBundle(t)) if _, err := CheckTemplate([]byte(template)); err != nil { t.Fatalf("the shipped bundle is refused at preflight: %v", err) @@ -167,3 +167,13 @@ func TestATemplateWhoseControlPlaneHasNoBusIsRefusedBeforeAnythingIsRaised(t *te t.Fatalf("a control plane with no bus was let through preflight: %v", err) } } + +// TestPreflight runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestPreflight(t *testing.T) { + t.Run("PreflightRefusesPlainlyWhenTheRuntimeDoesNotAnswer", testPreflightRefusesPlainlyWhenTheRuntimeDoesNotAnswer) + t.Run("ARuntimeThatIsStillStartingIsWaitedFor", testARuntimeThatIsStillStartingIsWaitedFor) + t.Run("OnlyTheRegistriesTheBundleNamesAreAskedAbout", testOnlyTheRegistriesTheBundleNamesAreAskedAbout) + t.Run("TheControlPlanesOwnRegistryIsNeverAskedAbout", testTheControlPlanesOwnRegistryIsNeverAskedAbout) + t.Run("WhereAnImageWouldBeFetchedFrom", testWhereAnImageWouldBeFetchedFrom) + t.Run("ATemplateWhoseControlPlaneHasNoBusIsRefusedBeforeAnythingIsRaised", testATemplateWhoseControlPlaneHasNoBusIsRefusedBeforeAnythingIsRaised) +} diff --git a/internal/bootstrap/publish_test.go b/internal/bootstrap/publish_test.go index 61201364..3579489d 100644 --- a/internal/bootstrap/publish_test.go +++ b/internal/bootstrap/publish_test.go @@ -36,7 +36,7 @@ func publishing(t *testing.T, fetch func(string) (int, string, error), // Nothing has ever been pushed under this name, so the registry says 404 — and that is an answer, // not a failure. An installer that treated it as one would refuse on the first run of the step it // exists to perform. -func TestAnImageNoRegistryHasEverHeldIsPushed(t *testing.T) { +func testAnImageNoRegistryHasEverHeldIsPushed(t *testing.T) { pushed := false o, d, runtime := publishing(t, func(string) (int, string, error) { @@ -76,7 +76,7 @@ func TestAnImageNoRegistryHasEverHeldIsPushed(t *testing.T) { // An image the registry already serves is not pushed again, and says so. Blobs are named by their // content, so re-pushing is asking a registry to store what it already has under the name it // already has — and the installer is run over and over. -func TestAnImageTheRegistryAlreadyServesIsNotPushedAgain(t *testing.T) { +func testAnImageTheRegistryAlreadyServesIsNotPushedAgain(t *testing.T) { o, d, runtime := publishing(t, func(string) (int, string, error) { return http.StatusOK, `{"name":"mesh-controller","tags":["genesis"]}`, nil @@ -104,7 +104,7 @@ func TestAnImageTheRegistryAlreadyServesIsNotPushedAgain(t *testing.T) { // to more than one registry has more than one entry, and element zero is whichever the runtime // listed first — which would pin this mesh's control plane to somebody else's registry, silently, // which is the dependency the whole pivot exists to remove. -func TestTheDigestComesFromThisMeshsOwnRegistry(t *testing.T) { +func testTheDigestComesFromThisMeshsOwnRegistry(t *testing.T) { elsewhere := "some.other.registry/mesh-controller@sha256:" + strings.Repeat("c", 64) ours := "127.0.0.1:5000/mesh-controller@sha256:" + strings.Repeat("d", 64) @@ -133,7 +133,7 @@ func TestTheDigestComesFromThisMeshsOwnRegistry(t *testing.T) { // depends on it. The next step names the control plane's module by that digest, so there would be // nothing to name — and finding that out one step later would mean registering a module pinned to // an empty string. -func TestAPushThatProducedNoDigestIsRefused(t *testing.T) { +func testAPushThatProducedNoDigestIsRefused(t *testing.T) { pushed := false o, d, _ := publishing(t, func(string) (int, string, error) { @@ -162,7 +162,7 @@ func TestAPushThatProducedNoDigestIsRefused(t *testing.T) { // A tag is not a pin. If the runtime answers with something that is not pinned by digest, it is // not used — a tag can be made to point at a different image, and this reference is applied on // machines with no mesh to ask about anything (novox/hq ADR 0006). -func TestATagIsNotAPin(t *testing.T) { +func testATagIsNotAPin(t *testing.T) { o, d, _ := publishing(t, func(string) (int, string, error) { return http.StatusOK, `{"tags":["genesis"]}`, nil @@ -182,7 +182,7 @@ func TestATagIsNotAPin(t *testing.T) { // A registry that cannot be reached at all is said so plainly rather than becoming a push that // fails for a reason nobody can read. -func TestARegistryThatCannotBeAskedIsSaidSo(t *testing.T) { +func testARegistryThatCannotBeAskedIsSaidSo(t *testing.T) { o, d, _ := publishing(t, func(string) (int, string, error) { return 0, "", errors.New("connection refused") @@ -197,3 +197,13 @@ func TestARegistryThatCannotBeAskedIsSaidSo(t *testing.T) { t.Errorf("the refusal does not say the registry could not be asked: %v", err) } } + +// TestPublish runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestPublish(t *testing.T) { + t.Run("AnImageNoRegistryHasEverHeldIsPushed", testAnImageNoRegistryHasEverHeldIsPushed) + t.Run("AnImageTheRegistryAlreadyServesIsNotPushedAgain", testAnImageTheRegistryAlreadyServesIsNotPushedAgain) + t.Run("TheDigestComesFromThisMeshsOwnRegistry", testTheDigestComesFromThisMeshsOwnRegistry) + t.Run("APushThatProducedNoDigestIsRefused", testAPushThatProducedNoDigestIsRefused) + t.Run("ATagIsNotAPin", testATagIsNotAPin) + t.Run("ARegistryThatCannotBeAskedIsSaidSo", testARegistryThatCannotBeAskedIsSaidSo) +} diff --git a/internal/bootstrap/push_places_users_test.go b/internal/bootstrap/push_places_users_test.go index d42912ae..e6cd7484 100644 --- a/internal/bootstrap/push_places_users_test.go +++ b/internal/bootstrap/push_places_users_test.go @@ -59,7 +59,7 @@ func placedAfterThePush(t *testing.T, commands []string) int { return placed } -func TestTheBusHearsTheBuildAgentsAccountAfterItsPush(t *testing.T) { +func testTheBusHearsTheBuildAgentsAccountAfterItsPush(t *testing.T) { t.Setenv("TMPDIR", t.TempDir()) runtime, control := placing(false) o := Options{Node: "anchor", Wait: time.Second} @@ -71,7 +71,7 @@ func TestTheBusHearsTheBuildAgentsAccountAfterItsPush(t *testing.T) { } } -func TestTheGenesisDocumentsPushIsHeardByTheBusToo(t *testing.T) { +func testTheGenesisDocumentsPushIsHeardByTheBusToo(t *testing.T) { t.Setenv("TMPDIR", t.TempDir()) runtime, control := placing(false) o := Options{Node: "anchor", Wait: time.Second} @@ -84,7 +84,7 @@ func TestTheGenesisDocumentsPushIsHeardByTheBusToo(t *testing.T) { } // From the adoption on the nats module writes the list, and the installer does not (ADR 0333 §4). -func TestOnceTheBusIsTheNatsModulesThePushPlacesNothing(t *testing.T) { +func testOnceTheBusIsTheNatsModulesThePushPlacesNothing(t *testing.T) { t.Setenv("TMPDIR", t.TempDir()) runtime, control := placing(true) o := Options{Node: "anchor", Wait: time.Second} @@ -99,7 +99,7 @@ func TestOnceTheBusIsTheNatsModulesThePushPlacesNothing(t *testing.T) { // Defends novox/hq issue 615: the packages step's push is waited for until the node applied it, because // the sdk step right after asks the build agent for a build that reads the genesis document from the // file that apply writes. A push that returned on sending let the ask race the apply. -func TestThePackagesStepWaitsUntilTheNodeAppliedTheGenesisDocument(t *testing.T) { +func testThePackagesStepWaitsUntilTheNodeAppliedTheGenesisDocument(t *testing.T) { t.Setenv("TMPDIR", t.TempDir()) runtime, control := placing(false) o := Options{Node: "anchor", Wait: 3 * time.Minute} @@ -119,7 +119,7 @@ func TestThePackagesStepWaitsUntilTheNodeAppliedTheGenesisDocument(t *testing.T) // Every other push of genesis still returns on sending: only a push whose content the next step reads on // the machine waits. -func TestAnOrdinaryPushDoesNotWait(t *testing.T) { +func testAnOrdinaryPushDoesNotWait(t *testing.T) { t.Setenv("TMPDIR", t.TempDir()) runtime, control := placing(false) o := Options{Node: "anchor", Wait: time.Second} @@ -132,3 +132,12 @@ func TestAnOrdinaryPushDoesNotWait(t *testing.T) { } } } + +// TestPushPlacesUsers runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestPushPlacesUsers(t *testing.T) { + t.Run("TheBusHearsTheBuildAgentsAccountAfterItsPush", testTheBusHearsTheBuildAgentsAccountAfterItsPush) + t.Run("TheGenesisDocumentsPushIsHeardByTheBusToo", testTheGenesisDocumentsPushIsHeardByTheBusToo) + t.Run("OnceTheBusIsTheNatsModulesThePushPlacesNothing", testOnceTheBusIsTheNatsModulesThePushPlacesNothing) + t.Run("ThePackagesStepWaitsUntilTheNodeAppliedTheGenesisDocument", testThePackagesStepWaitsUntilTheNodeAppliedTheGenesisDocument) + t.Run("AnOrdinaryPushDoesNotWait", testAnOrdinaryPushDoesNotWait) +} diff --git a/internal/bootstrap/registry_test.go b/internal/bootstrap/registry_test.go index 0fbc6765..062254e3 100644 --- a/internal/bootstrap/registry_test.go +++ b/internal/bootstrap/registry_test.go @@ -97,7 +97,7 @@ func installing(t *testing.T, catalogue string) Options { // A container that is up is not a registry that serves. `/v2/` is the registry API's own "yes, I // am one and I am ready", and the step after this pushes to it — so it is refused here rather than // discovered inside a `docker push`. -func TestARegistryContainerThatIsUpIsNotARegistryThatServes(t *testing.T) { +func testARegistryContainerThatIsUpIsNotARegistryThatServes(t *testing.T) { previous := answerEvery answerEvery = time.Millisecond defer func() { answerEvery = previous }() @@ -125,7 +125,7 @@ func TestARegistryContainerThatIsUpIsNotARegistryThatServes(t *testing.T) { } // The whole of step 7, against a mesh that agrees: registered, assigned, pushed, up, and answering. -func TestARegistryThatAnswersIsAccepted(t *testing.T) { +func testARegistryThatAnswersIsAccepted(t *testing.T) { runtime := &asked{answer: aMeshThatAgrees(nil)} deps := Deps{ Run: runtime.run, @@ -163,7 +163,7 @@ func TestARegistryThatAnswersIsAccepted(t *testing.T) { // placeholder digest would mean somebody had made this module buildable — which is the cycle // novox/hq 04-ISSUES/029 settled: a module that provides the artifact store cannot be delivered // through the artifact store. -func TestARegistryManifestThatWantsBuildingIsRefused(t *testing.T) { +func testARegistryManifestThatWantsBuildingIsRefused(t *testing.T) { wants := strings.Replace(upstreamRegistryManifest, "registry@sha256:a3d8aaa63ed8681a604f1dea0aa03f100d5895b6a58ace528858a7b332415373", "mesh-runtime-registry@"+placeholderDigest, 1) @@ -186,7 +186,7 @@ func TestARegistryManifestThatWantsBuildingIsRefused(t *testing.T) { // A catalogue that is not there is said plainly, with what --catalog is. This is the most likely // mistake anybody makes at this step and the least interesting to debug. -func TestACatalogueThatIsNotThereIsSaidPlainly(t *testing.T) { +func testACatalogueThatIsNotThereIsSaidPlainly(t *testing.T) { runtime := &asked{answer: aMeshThatAgrees(nil)} _, err := InstallRegistry(context.Background(), installing(t, filepath.Join(t.TempDir(), "nowhere")), @@ -203,7 +203,7 @@ func TestACatalogueThatIsNotThereIsSaidPlainly(t *testing.T) { // A refusal from the control plane is repeated verbatim. mesh-controller refuses in paragraphs — // "nothing provides route, wanted by registry" — and an installer that reported "exit status 1" // would throw away the only thing a person can act on. -func TestWhatTheMeshRefusedIsRepeated(t *testing.T) { +func testWhatTheMeshRefusedIsRepeated(t *testing.T) { refusal := "nothing provides \"route\", wanted by registry" runtime := &asked{answer: func(name string, args []string) (string, error) { if strings.Contains(strings.Join(args, " "), "push") { @@ -226,3 +226,12 @@ func TestWhatTheMeshRefusedIsRepeated(t *testing.T) { t.Errorf("the failure does not say a re-run continues from here:\n%v", err) } } + +// TestRegistry runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRegistry(t *testing.T) { + t.Run("ARegistryContainerThatIsUpIsNotARegistryThatServes", testARegistryContainerThatIsUpIsNotARegistryThatServes) + t.Run("ARegistryThatAnswersIsAccepted", testARegistryThatAnswersIsAccepted) + t.Run("ARegistryManifestThatWantsBuildingIsRefused", testARegistryManifestThatWantsBuildingIsRefused) + t.Run("ACatalogueThatIsNotThereIsSaidPlainly", testACatalogueThatIsNotThereIsSaidPlainly) + t.Run("WhatTheMeshRefusedIsRepeated", testWhatTheMeshRefusedIsRepeated) +} diff --git a/internal/bootstrap/retire_test.go b/internal/bootstrap/retire_test.go index 202d73e3..d07d2d6d 100644 --- a/internal/bootstrap/retire_test.go +++ b/internal/bootstrap/retire_test.go @@ -25,7 +25,7 @@ func produced(t *testing.T) []byte { } // The temporary control plane leaves the bundle, everything else stays, and what is left parses. -func TestTheTemporaryControlPlaneLeavesTheBundleAndNothingElseDoes(t *testing.T) { +func testTheTemporaryControlPlaneLeavesTheBundleAndNothingElseDoes(t *testing.T) { before, err := declaration.ParseFileTrusted(produced(t)) if err != nil { t.Fatal(err) @@ -61,7 +61,7 @@ func TestTheTemporaryControlPlaneLeavesTheBundleAndNothingElseDoes(t *testing.T) // `postgres://…` several times, and a scanner that read the rest of those lines as a comment // would lose braces and cut the wrong thing out — silently, because what it produced would still // look like a file. -func TestASchemeInsideAStringIsNotReadAsAComment(t *testing.T) { +func testASchemeInsideAStringIsNotReadAsAComment(t *testing.T) { shorter, err := removeResource(produced(t), ControlPlaneID) if err != nil { t.Fatal(err) @@ -86,7 +86,7 @@ func TestASchemeInsideAStringIsNotReadAsAComment(t *testing.T) { // Removing the FIRST element takes the comma after it rather than the comma before it, because // there is no comma before it. Getting this wrong produces a leading comma, which is JSON nothing // parses — and the file would already have been written. -func TestRemovingTheFirstResourceLeavesAValidList(t *testing.T) { +func testRemovingTheFirstResourceLeavesAValidList(t *testing.T) { shorter, err := removeResource(produced(t), "container-runtime") if err != nil { t.Fatal(err) @@ -105,7 +105,7 @@ func TestRemovingTheFirstResourceLeavesAValidList(t *testing.T) { // A bundle that declares no such resource is refused rather than silently returned unchanged. A // removal that removed nothing and reported success would leave the apply below with nothing to // do and the installer claiming a pivot it did not finish. -func TestRemovingSomethingThatIsNotThereIsRefused(t *testing.T) { +func testRemovingSomethingThatIsNotThereIsRefused(t *testing.T) { if _, err := removeResource(produced(t), "nothing-of-the-sort"); err == nil { t.Fatal("a bundle was reported to have had a resource removed that it never declared") } @@ -114,7 +114,7 @@ func TestRemovingSomethingThatIsNotThereIsRefused(t *testing.T) { // A re-run after the retirement finds a bundle with no control plane in it and says so, rather // than failing. This is the idempotence of the last step, and it is the one a person is most // likely to exercise: the pivot ends here, so a re-run to check ends here too. -func TestRetiringABundleThatAlreadyHasNoControlPlaneIsAlreadyDone(t *testing.T) { +func testRetiringABundleThatAlreadyHasNoControlPlaneIsAlreadyDone(t *testing.T) { shorter, err := removeResource(produced(t), ControlPlaneID) if err != nil { t.Fatal(err) @@ -136,7 +136,7 @@ func TestRetiringABundleThatAlreadyHasNoControlPlaneIsAlreadyDone(t *testing.T) // A container the runtime still knows about after the apply is a pivot that did not finish. Two // control planes on one mesh are both correct and neither is wrong — but the temporary one was // supposed to go, and saying it went when it did not is the fault this project keeps naming. -func TestAContainerStillThereAfterRemovalIsNotGone(t *testing.T) { +func testAContainerStillThereAfterRemovalIsNotGone(t *testing.T) { previous := answerEvery answerEvery = time.Millisecond defer func() { answerEvery = previous }() @@ -163,3 +163,13 @@ func TestAContainerStillThereAfterRemovalIsNotGone(t *testing.T) { t.Error("a container the runtime does not know about was not reported gone") } } + +// TestRetire runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRetire(t *testing.T) { + t.Run("TheTemporaryControlPlaneLeavesTheBundleAndNothingElseDoes", testTheTemporaryControlPlaneLeavesTheBundleAndNothingElseDoes) + t.Run("ASchemeInsideAStringIsNotReadAsAComment", testASchemeInsideAStringIsNotReadAsAComment) + t.Run("RemovingTheFirstResourceLeavesAValidList", testRemovingTheFirstResourceLeavesAValidList) + t.Run("RemovingSomethingThatIsNotThereIsRefused", testRemovingSomethingThatIsNotThereIsRefused) + t.Run("RetiringABundleThatAlreadyHasNoControlPlaneIsAlreadyDone", testRetiringABundleThatAlreadyHasNoControlPlaneIsAlreadyDone) + t.Run("AContainerStillThereAfterRemovalIsNotGone", testAContainerStillThereAfterRemovalIsNotGone) +} diff --git a/internal/bootstrap/rewrite_test.go b/internal/bootstrap/rewrite_test.go index bb4e6add..ff863e24 100644 --- a/internal/bootstrap/rewrite_test.go +++ b/internal/bootstrap/rewrite_test.go @@ -29,7 +29,7 @@ func theRealBundle(t *testing.T) []byte { return raw } -func TestTheControlPlaneIsNamedByTheImageThisMachineHolds(t *testing.T) { +func testTheControlPlaneIsNamedByTheImageThisMachineHolds(t *testing.T) { out, err := Rewrite(theRealBundle(t), held) if err != nil { t.Fatal(err) @@ -52,7 +52,7 @@ func TestTheControlPlaneIsNamedByTheImageThisMachineHolds(t *testing.T) { // action that runs `migrate` to create the contexts' schemas. Rewriting only the container leaves // the migration pointing at an image no registry serves, and the apply dies in the middle — after // the store is up and before the broker. This is the test that would have caught that. -func TestEveryPlaceTheBundleNamesTheControlPlaneIsRewritten(t *testing.T) { +func testEveryPlaceTheBundleNamesTheControlPlaneIsRewritten(t *testing.T) { template := theRealBundle(t) out, err := Rewrite(template, held) @@ -74,7 +74,7 @@ func TestEveryPlaceTheBundleNamesTheControlPlaneIsRewritten(t *testing.T) { // Third-party images are somebody else's, at somebody else's registry, and the installer has no // business touching them (novox/hq ADR 0006). -func TestPostgresAndTheBrokerAreLeftExactlyAsTheyWere(t *testing.T) { +func testPostgresAndTheBrokerAreLeftExactlyAsTheyWere(t *testing.T) { template := theRealBundle(t) out, err := Rewrite(template, held) @@ -107,7 +107,7 @@ func TestPostgresAndTheBrokerAreLeftExactlyAsTheyWere(t *testing.T) { // A bundle with no control plane raises a store and a broker and no mesh. Refused, because // applying it would succeed and leave a machine that looks bootstrapped. -func TestABundleThatNamesNoControlPlaneIsRefused(t *testing.T) { +func testABundleThatNamesNoControlPlaneIsRefused(t *testing.T) { template := []byte(`{"declaration":1,"resources":[ {"id":"store","type":"container","name":"mesh-store","image":"postgres@sha256:` + strings.Repeat("7", 64) + `"} @@ -124,7 +124,7 @@ func TestABundleThatNamesNoControlPlaneIsRefused(t *testing.T) { } } -func TestAControlPlaneThatIsNotAContainerIsRefused(t *testing.T) { +func testAControlPlaneThatIsNotAContainerIsRefused(t *testing.T) { template := []byte(`{"declaration":1,"resources":[ {"id":"control-plane","type":"package","package":"mesh-controller"} ]}`) @@ -136,7 +136,7 @@ func TestAControlPlaneThatIsNotAContainerIsRefused(t *testing.T) { // Idempotence. This program is run over and over while somebody gets a machine working, and the // second run must be able to say the bundle already names this image rather than reporting a // rewrite it did not perform. -func TestRewritingABundleThatAlreadyNamesTheImageChangesNothing(t *testing.T) { +func testRewritingABundleThatAlreadyNamesTheImageChangesNothing(t *testing.T) { first, err := Rewrite(theRealBundle(t), held) if err != nil { t.Fatal(err) @@ -159,7 +159,7 @@ func TestRewritingABundleThatAlreadyNamesTheImageChangesNothing(t *testing.T) { // A DIFFERENT image, though, must move — the ordinary case of a new control plane being installed // over an old one. "Already correct" must not be the same code path as "already ran". -func TestANewImageReplacesAnOlderHeldOne(t *testing.T) { +func testANewImageReplacesAnOlderHeldOne(t *testing.T) { first, err := Rewrite(theRealBundle(t), held) if err != nil { t.Fatal(err) @@ -177,7 +177,7 @@ func TestANewImageReplacesAnOlderHeldOne(t *testing.T) { // The produced bundle is meant to be READ. Re-serialising a parsed declaration would drop every // comment in the template, and the foundation example is mostly comments — each one recording why a // resource is the way it is, several of them paid for in the lab. -func TestTheProducedBundleKeepsTheTemplatesComments(t *testing.T) { +func testTheProducedBundleKeepsTheTemplatesComments(t *testing.T) { template := theRealBundle(t) out, err := Rewrite(template, held) if err != nil { @@ -191,7 +191,7 @@ func TestTheProducedBundleKeepsTheTemplatesComments(t *testing.T) { // The installer must refuse its own bad input in its own words, rather than writing a bundle and // letting the host refuse a declaration somebody did not write. -func TestSomethingThatIsNotAnImageIdIsRefused(t *testing.T) { +func testSomethingThatIsNotAnImageIdIsRefused(t *testing.T) { for _, bad := range []string{ "", "mesh-controller:latest", @@ -209,7 +209,7 @@ func TestSomethingThatIsNotAnImageIdIsRefused(t *testing.T) { // The address every enrolment token will carry is reported and never invented. It differs per // machine and it is silently fatal when wrong: a node enrols against a dead address and nothing // says so until it fails to come back. -func TestTheAddressNodesWillDialIsReportedAndNotRewritten(t *testing.T) { +func testTheAddressNodesWillDialIsReportedAndNotRewritten(t *testing.T) { template := theRealBundle(t) out, err := Rewrite(template, held) if err != nil { @@ -233,7 +233,7 @@ func TestTheAddressNodesWillDialIsReportedAndNotRewritten(t *testing.T) { // one container, and the host — which tracks what it owns — has no way to stop owning something // without destroying it. Nothing here invents such a mechanism. The foundation's container is // called `temp-mesh-controller` instead, and there are simply two containers. -func TestTheFoundationsControlPlaneMovesOutOfTheModulesWay(t *testing.T) { +func testTheFoundationsControlPlaneMovesOutOfTheModulesWay(t *testing.T) { out, err := Rewrite(theRealBundle(t), held) if err != nil { t.Fatal(err) @@ -263,7 +263,7 @@ func TestTheFoundationsControlPlaneMovesOutOfTheModulesWay(t *testing.T) { // The image reference contains the string `mesh-controller` too, and it is not a container name. A // substitution that caught it would produce `…/temp-mesh-controller@sha256:…`, which no registry // serves — and it would be found inside a pull rather than here. -func TestTheImageReferenceIsNotMistakenForTheContainerName(t *testing.T) { +func testTheImageReferenceIsNotMistakenForTheContainerName(t *testing.T) { out, err := Rewrite(theRealBundle(t), held) if err != nil { t.Fatal(err) @@ -276,7 +276,7 @@ func TestTheImageReferenceIsNotMistakenForTheContainerName(t *testing.T) { // Everything else keeps the name the foundation gave it. The store and the broker are containers // too, and a rename that moved them would leave a machine whose foundation the host cannot find. -func TestRenamingTheControlPlaneLeavesEveryOtherContainerAlone(t *testing.T) { +func testRenamingTheControlPlaneLeavesEveryOtherContainerAlone(t *testing.T) { before, err := declaration.ParseFileTrusted(theRealBundle(t)) if err != nil { t.Fatal(err) @@ -299,7 +299,7 @@ func TestRenamingTheControlPlaneLeavesEveryOtherContainerAlone(t *testing.T) { // A re-run against a bundle this installer produced renames nothing and says so. The installer is // run over and over while somebody gets a machine working, and a step that could not tell "already // done" from "just done" makes the second run indistinguishable from the first. -func TestRewritingABundleThisAlreadyProducedRenamesNothing(t *testing.T) { +func testRewritingABundleThisAlreadyProducedRenamesNothing(t *testing.T) { first, err := Rewrite(theRealBundle(t), held) if err != nil { t.Fatal(err) @@ -319,3 +319,21 @@ func TestRewritingABundleThisAlreadyProducedRenamesNothing(t *testing.T) { t.Error("rewriting a produced bundle changed it") } } + +// TestRewrite runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRewrite(t *testing.T) { + t.Run("TheControlPlaneIsNamedByTheImageThisMachineHolds", testTheControlPlaneIsNamedByTheImageThisMachineHolds) + t.Run("EveryPlaceTheBundleNamesTheControlPlaneIsRewritten", testEveryPlaceTheBundleNamesTheControlPlaneIsRewritten) + t.Run("PostgresAndTheBrokerAreLeftExactlyAsTheyWere", testPostgresAndTheBrokerAreLeftExactlyAsTheyWere) + t.Run("ABundleThatNamesNoControlPlaneIsRefused", testABundleThatNamesNoControlPlaneIsRefused) + t.Run("AControlPlaneThatIsNotAContainerIsRefused", testAControlPlaneThatIsNotAContainerIsRefused) + t.Run("RewritingABundleThatAlreadyNamesTheImageChangesNothing", testRewritingABundleThatAlreadyNamesTheImageChangesNothing) + t.Run("ANewImageReplacesAnOlderHeldOne", testANewImageReplacesAnOlderHeldOne) + t.Run("TheProducedBundleKeepsTheTemplatesComments", testTheProducedBundleKeepsTheTemplatesComments) + t.Run("SomethingThatIsNotAnImageIdIsRefused", testSomethingThatIsNotAnImageIdIsRefused) + t.Run("TheAddressNodesWillDialIsReportedAndNotRewritten", testTheAddressNodesWillDialIsReportedAndNotRewritten) + t.Run("TheFoundationsControlPlaneMovesOutOfTheModulesWay", testTheFoundationsControlPlaneMovesOutOfTheModulesWay) + t.Run("TheImageReferenceIsNotMistakenForTheContainerName", testTheImageReferenceIsNotMistakenForTheContainerName) + t.Run("RenamingTheControlPlaneLeavesEveryOtherContainerAlone", testRenamingTheControlPlaneLeavesEveryOtherContainerAlone) + t.Run("RewritingABundleThisAlreadyProducedRenamesNothing", testRewritingABundleThisAlreadyProducedRenamesNothing) +} diff --git a/internal/bootstrap/rootsecrets_test.go b/internal/bootstrap/rootsecrets_test.go index fa93ae2d..877a41a6 100644 --- a/internal/bootstrap/rootsecrets_test.go +++ b/internal/bootstrap/rootsecrets_test.go @@ -38,7 +38,7 @@ func theExample(t *testing.T) Rewritten { // file genesis made, and the controller's account on the bus is the made one in both places the // bundle names it — the address the control plane dials and the user list the bus is raised with // (novox/hq issue 071, ADR 0331 §3). -func TestTheProducedBundleCarriesNoWellKnownCredential(t *testing.T) { +func testTheProducedBundleCarriesNoWellKnownCredential(t *testing.T) { r := theExample(t) creds := testCredentials(t, "STORE-PW-40-characters-of-random-base64u", "BUS-PW-40-characters-of-random-base64uuu") got, err := RewriteRoot(&r, creds) @@ -109,7 +109,7 @@ func hashOf(t *testing.T, list, user string) string { // The bus's placeholders are what the installer looks for, and a template naming no bus connection // it knows is refused at preflight, naming the placeholder (novox/hq ADR 0331 §3, §4). -func TestABundleNamingNoBusConnectionItKnowsIsRefusedByItsPlaceholder(t *testing.T) { +func testABundleNamingNoBusConnectionItKnowsIsRefusedByItsPlaceholder(t *testing.T) { template, err := os.ReadFile("../../examples/foundation-first-node.lock") if err != nil { t.Skip("no example bundle beside this checkout") @@ -151,7 +151,7 @@ func TestABundleNamingNoBusConnectionItKnowsIsRefusedByItsPlaceholder(t *testing // The account is made once, with its hash, and a second run puts the same bytes in the bundle — a // hash salted afresh every run would rewrite the bus's user list every run. -func TestTheBusAccountIsKeptWithItsHash(t *testing.T) { +func testTheBusAccountIsKeptWithItsHash(t *testing.T) { dir := t.TempDir() first, err := rootSecretsAt(dir+"/store", dir+"/bus", dir+"/bus.bcrypt", false) if err != nil { @@ -171,7 +171,7 @@ func TestTheBusAccountIsKeptWithItsHash(t *testing.T) { } // Made once and kept: a second run reads the same value; a dry run writes nothing. -func TestRootSecretsAreKeptAcrossRuns(t *testing.T) { +func testRootSecretsAreKeptAcrossRuns(t *testing.T) { dir := t.TempDir() path := dir + "/superuser.secret" first, made, err := keptOrMade(path, false) @@ -195,7 +195,7 @@ func TestRootSecretsAreKeptAcrossRuns(t *testing.T) { } // Nothing the installer says after making the credentials contains them. -func TestTheTranscriptNeverSaysTheCredentials(t *testing.T) { +func testTheTranscriptNeverSaysTheCredentials(t *testing.T) { var said []string say := Masking(func(l string) { said = append(said, l) }, RootCredentials{Store: "STORE-PW", Bus: "BUS-PW"}) say("created context-schemas (docker run -e MESH_STORE_INVENTORY=postgres://postgres:STORE-PW@127.0.0.1:5432/inventory)") @@ -213,7 +213,7 @@ func TestTheTranscriptNeverSaysTheCredentials(t *testing.T) { // The foundation filters before anything listens: nftables is in place before the store, and its // rules refuse the store's and broker's client ports from outside while keeping ssh, the bus a node // enrols over and the registry a node pulls from (novox/hq issue 054). -func TestTheFoundationFiltersBeforeAnythingListens(t *testing.T) { +func testTheFoundationFiltersBeforeAnythingListens(t *testing.T) { r := theExample(t) if _, err := RewriteRoot(&r, testCredentials(t, "s", "b")); err != nil { t.Fatal(err) @@ -254,7 +254,7 @@ func TestTheFoundationFiltersBeforeAnythingListens(t *testing.T) { // /mesh (/var/lib/mesh/postgres), no longer in /var/lib/postgres, the postgresql package's own. A // directory genesis makes on the way keeps the mode the mesh's directories have (0755, so every module's account // reaches its own below it); only the credential's own directory is closed, 0700. -func TestTheStoreSuperuserFileLiesInTheModulesOwnDirectory(t *testing.T) { +func testTheStoreSuperuserFileLiesInTheModulesOwnDirectory(t *testing.T) { if StoreSuperuserFile != "/var/lib/mesh/postgres/superuser.secret" { t.Errorf("the store's superuser file is %s, not the postgres module's /var/lib/mesh/postgres/superuser.secret", StoreSuperuserFile) } @@ -273,3 +273,14 @@ func TestTheStoreSuperuserFileLiesInTheModulesOwnDirectory(t *testing.T) { } } } + +// TestRootsecrets runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRootsecrets(t *testing.T) { + t.Run("TheProducedBundleCarriesNoWellKnownCredential", testTheProducedBundleCarriesNoWellKnownCredential) + t.Run("ABundleNamingNoBusConnectionItKnowsIsRefusedByItsPlaceholder", testABundleNamingNoBusConnectionItKnowsIsRefusedByItsPlaceholder) + t.Run("TheBusAccountIsKeptWithItsHash", testTheBusAccountIsKeptWithItsHash) + t.Run("RootSecretsAreKeptAcrossRuns", testRootSecretsAreKeptAcrossRuns) + t.Run("TheTranscriptNeverSaysTheCredentials", testTheTranscriptNeverSaysTheCredentials) + t.Run("TheFoundationFiltersBeforeAnythingListens", testTheFoundationFiltersBeforeAnythingListens) + t.Run("TheStoreSuperuserFileLiesInTheModulesOwnDirectory", testTheStoreSuperuserFileLiesInTheModulesOwnDirectory) +} diff --git a/internal/bootstrap/store_layout_test.go b/internal/bootstrap/store_layout_test.go index 1f36b4d8..9157d5e1 100644 --- a/internal/bootstrap/store_layout_test.go +++ b/internal/bootstrap/store_layout_test.go @@ -29,7 +29,7 @@ func theStoreGenesisRaises(t *testing.T) *declaration.Container { // The bundle's store is exactly the catalogue's postgres module's server, read from the module's own // manifest (ADR 0338 §1): its name, its image (so a drift of either pin fails here), where its data is, // and the file its superuser password is read from, with the environment that says so. -func TestTheBundleRaisesTheStoreAsTheCataloguesPostgresModuleDeclaresIt(t *testing.T) { +func testTheBundleRaisesTheStoreAsTheCataloguesPostgresModuleDeclaresIt(t *testing.T) { manifest := theCataloguesModule(t, "postgres") var m struct { Resources []struct { @@ -90,7 +90,7 @@ func TestTheBundleRaisesTheStoreAsTheCataloguesPostgresModuleDeclaresIt(t *testi // The store's data directory is made by the bundle before the store starts, owned by the image's // postgres user, as the module declares it (ADR 0338 §1, and the measurement under its §5). -func TestTheBundleMakesTheStoresDataDirectoryAsTheModuleDoes(t *testing.T) { +func testTheBundleMakesTheStoresDataDirectoryAsTheModuleDoes(t *testing.T) { r := producedBundle(t) at, store := -1, -1 for i, res := range r.Declaration.Resources { @@ -111,7 +111,7 @@ func TestTheBundleMakesTheStoresDataDirectoryAsTheModuleDoes(t *testing.T) { // No step of the bundle and no step of the installer names `mesh-store`, which is the seat's name only // (ADR 0338 §2): every step that reaches the store reaches the container the bundle raised. -func TestNoStepReachesTheStoreByTheSeatsName(t *testing.T) { +func testNoStepReachesTheStoreByTheSeatsName(t *testing.T) { text := string(theRealBundle(t)) for _, by := range []string{`"in": "mesh-store"`, `container:mesh-store`, `exec mesh-store`, `"name": "mesh-store"`, `mesh-store-data`} { if strings.Contains(text, by) { @@ -132,7 +132,7 @@ func TestNoStepReachesTheStoreByTheSeatsName(t *testing.T) { // The installer's refusal to raise a store over data it cannot open looks where the store keeps its data // (ADR 0338 §2): a cluster there and no credential is refused; the old docker volume alone is not. -func TestTheRefusalOverExistingDataLooksInTheStoresDirectory(t *testing.T) { +func testTheRefusalOverExistingDataLooksInTheStoresDirectory(t *testing.T) { made := RootCredentials{Store: "s", Bus: "b", StoreMade: true} machine := func(cluster, volume bool) Runner { return func(_ context.Context, name string, args ...string) (string, error) { @@ -161,3 +161,11 @@ func TestTheRefusalOverExistingDataLooksInTheStoresDirectory(t *testing.T) { t.Fatalf("a kept credential was refused: %v", err) } } + +// TestStoreLayout runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestStoreLayout(t *testing.T) { + t.Run("TheBundleRaisesTheStoreAsTheCataloguesPostgresModuleDeclaresIt", testTheBundleRaisesTheStoreAsTheCataloguesPostgresModuleDeclaresIt) + t.Run("TheBundleMakesTheStoresDataDirectoryAsTheModuleDoes", testTheBundleMakesTheStoresDataDirectoryAsTheModuleDoes) + t.Run("NoStepReachesTheStoreByTheSeatsName", testNoStepReachesTheStoreByTheSeatsName) + t.Run("TheRefusalOverExistingDataLooksInTheStoresDirectory", testTheRefusalOverExistingDataLooksInTheStoresDirectory) +} diff --git a/internal/bootstrap/trust_test.go b/internal/bootstrap/trust_test.go index 9ec16d40..15b22331 100644 --- a/internal/bootstrap/trust_test.go +++ b/internal/bootstrap/trust_test.go @@ -109,7 +109,7 @@ func insecureIn(t *testing.T) (string, map[string]json.RawMessage) { return fmt.Sprint(list), o } -func TestGenesisTrustsTheRegistryByEveryNameBeforeItPushes(t *testing.T) { +func testGenesisTrustsTheRegistryByEveryNameBeforeItPushes(t *testing.T) { o, runtime, sys := trustSetup(t, `{"data-root":"/srv/docker","insecure-registries":["198.51.100.7:5000"]}`) names, err := TrustTheRegistry(context.Background(), o, sys, runtime.run, func(string) {}) @@ -143,7 +143,7 @@ func TestGenesisTrustsTheRegistryByEveryNameBeforeItPushes(t *testing.T) { // The port is the node's setting for the registry, not the module's default, whatever the operator // typed the address with — and loopback, which the runtime trusts already, is not written. -func TestTheRegistrysTrustNamesThePortTheNodeServesItOn(t *testing.T) { +func testTheRegistrysTrustNamesThePortTheNodeServesItOn(t *testing.T) { o := Options{Node: "anchor", Registry: "127.0.0.1:5100", Ports: FoundationPorts{Registry: 5100}} t.Setenv(internalSuffixVar, "") if got := fmt.Sprint(RegistryNames(o)); got != "[anchor.internal:5100]" { @@ -158,7 +158,7 @@ func TestTheRegistrysTrustNamesThePortTheNodeServesItOn(t *testing.T) { } // A runtime that still refuses after the write is refused here, with the names, before any push. -func TestGenesisRefusesARuntimeThatStillDoesNotTrustTheRegistry(t *testing.T) { +func testGenesisRefusesARuntimeThatStillDoesNotTrustTheRegistry(t *testing.T) { o, runtime, sys := trustSetup(t, "") runtime.ignoresReload = true _, err := TrustTheRegistry(context.Background(), o, sys, runtime.run, func(string) {}) @@ -176,7 +176,7 @@ func TestGenesisRefusesARuntimeThatStillDoesNotTrustTheRegistry(t *testing.T) { // change, the runtime is not reloaded, and the member it declares is recorded as the module's from // then on (a member found in a file with no record of it is the mesh's, ADR 0102), so the module // owns the trust it writes and taking the module away takes that member out. -func TestTheDockerModuleTakesTheTrustOverWithoutAChange(t *testing.T) { +func testTheDockerModuleTakesTheTrustOverWithoutAChange(t *testing.T) { o, runtime, sys := trustSetup(t, `{"live-restore":true}`) if _, err := TrustTheRegistry(context.Background(), o, sys, runtime.run, func(string) {}); err != nil { t.Fatal(err) @@ -209,7 +209,7 @@ func TestTheDockerModuleTakesTheTrustOverWithoutAChange(t *testing.T) { } } -func TestARangeTheRuntimeTrustsCoversAnAddressInIt(t *testing.T) { +func testARangeTheRuntimeTrustsCoversAnAddressInIt(t *testing.T) { missing, err := untrusted(`{"InsecureRegistryCIDRs":["10.42.0.0/16"],"IndexConfigs":{}}`, []string{"10.42.0.1:5000", "anchor.internal:5000"}) if err != nil { @@ -224,7 +224,7 @@ func TestARangeTheRuntimeTrustsCoversAnAddressInIt(t *testing.T) { // as dockerd does: a push to a registry it has not been told to trust is refused with the error the // first genesis met. The trust must be written and confirmed before anything is tagged or pushed; // moving the trust after the push, or dropping it, fails this test. -func TestNothingIsPushedToTheRegistryBeforeTheRuntimeTrustsIt(t *testing.T) { +func testNothingIsPushedToTheRegistryBeforeTheRuntimeTrustsIt(t *testing.T) { o, runtime, sys := trustSetup(t, `{"data-root":"/srv/docker"}`) // The store as distribution's manifest declares it: its container on this machine's loopback, its front not yet served, // and its state directory, where no credential is ever written (design 51 *On a fresh mesh*, a design limit of issue 1966). @@ -319,7 +319,7 @@ func TestNothingIsPushedToTheRegistryBeforeTheRuntimeTrustsIt(t *testing.T) { } // Preflight asks, without writing, what would stop the trust from taking at step 7. -func TestPreflightRefusesARuntimeThatCouldNotTakeTheTrust(t *testing.T) { +func testPreflightRefusesARuntimeThatCouldNotTakeTheTrust(t *testing.T) { proc := t.TempDir() was := procRoot procRoot = proc @@ -371,3 +371,14 @@ func TestPreflightRefusesARuntimeThatCouldNotTakeTheTrust(t *testing.T) { }) } } + +// TestTrust runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestTrust(t *testing.T) { + t.Run("GenesisTrustsTheRegistryByEveryNameBeforeItPushes", testGenesisTrustsTheRegistryByEveryNameBeforeItPushes) + t.Run("TheRegistrysTrustNamesThePortTheNodeServesItOn", testTheRegistrysTrustNamesThePortTheNodeServesItOn) + t.Run("GenesisRefusesARuntimeThatStillDoesNotTrustTheRegistry", testGenesisRefusesARuntimeThatStillDoesNotTrustTheRegistry) + t.Run("TheDockerModuleTakesTheTrustOverWithoutAChange", testTheDockerModuleTakesTheTrustOverWithoutAChange) + t.Run("ARangeTheRuntimeTrustsCoversAnAddressInIt", testARangeTheRuntimeTrustsCoversAnAddressInIt) + t.Run("NothingIsPushedToTheRegistryBeforeTheRuntimeTrustsIt", testNothingIsPushedToTheRegistryBeforeTheRuntimeTrustsIt) + t.Run("PreflightRefusesARuntimeThatCouldNotTakeTheTrust", testPreflightRefusesARuntimeThatCouldNotTakeTheTrust) +} diff --git a/internal/bootstrap/verify_test.go b/internal/bootstrap/verify_test.go index 3c7cb839..9671642b 100644 --- a/internal/bootstrap/verify_test.go +++ b/internal/bootstrap/verify_test.go @@ -23,7 +23,7 @@ func foundation(t *testing.T) *declaration.Declaration { // **A container that is up is not a control plane that replies**, and this project has paid for // that distinction more than once. A runtime reports a container running from the moment its // process starts — before it has opened a database, and before it has failed to. -func TestAContainerThatIsUpIsNotAControlPlaneThatReplies(t *testing.T) { +func testAContainerThatIsUpIsNotAControlPlaneThatReplies(t *testing.T) { previous := answerEvery answerEvery = time.Millisecond defer func() { answerEvery = previous }() @@ -53,7 +53,7 @@ func TestAContainerThatIsUpIsNotAControlPlaneThatReplies(t *testing.T) { // Exit zero and silence is not an answer either. A program that returns nothing has not been asked // anything, and treating it as success is the same fault one level down. -func TestAControlPlaneThatSaysNothingHasNotAnswered(t *testing.T) { +func testAControlPlaneThatSaysNothingHasNotAnswered(t *testing.T) { previous := answerEvery answerEvery = time.Millisecond defer func() { answerEvery = previous }() @@ -72,7 +72,7 @@ func TestAControlPlaneThatSaysNothingHasNotAnswered(t *testing.T) { } // The foundation answering is the whole point, and what it said is reported rather than asserted. -func TestAFoundationThatIsUpAndAnsweringIsAccepted(t *testing.T) { +func testAFoundationThatIsUpAndAnsweringIsAccepted(t *testing.T) { runtime := &asked{answer: func(_ string, args []string) (string, error) { if args[0] == "container" { return "true running\n", nil @@ -105,7 +105,7 @@ func TestAFoundationThatIsUpAndAnsweringIsAccepted(t *testing.T) { // A control plane that is still opening its stores is waited for, not refused. Refusing on the // first attempt would make a correct bootstrap fail for being observed too early. -func TestAControlPlaneThatIsStillStartingIsWaitedFor(t *testing.T) { +func testAControlPlaneThatIsStillStartingIsWaitedFor(t *testing.T) { previous := answerEvery answerEvery = time.Millisecond defer func() { answerEvery = previous }() @@ -130,7 +130,7 @@ func TestAControlPlaneThatIsStillStartingIsWaitedFor(t *testing.T) { // A container that exited is named with what it IS, so somebody can go and read its logs rather // than being told only that something is not what it should be. -func TestAContainerThatExitedIsNamedWithItsState(t *testing.T) { +func testAContainerThatExitedIsNamedWithItsState(t *testing.T) { runtime := &asked{answer: func(_ string, args []string) (string, error) { if args[0] == "container" && args[len(args)-1] == "mesh-broker-nats" { return "false exited\n", nil @@ -153,7 +153,7 @@ func TestAContainerThatExitedIsNamedWithItsState(t *testing.T) { // The control plane is asked by running the binary in its own image directly, because the image is // `FROM scratch` and has no shell for a command line to be interpreted by. -func TestTheControlPlaneIsAskedByRunningItsOwnBinary(t *testing.T) { +func testTheControlPlaneIsAskedByRunningItsOwnBinary(t *testing.T) { runtime := &asked{answer: func(_ string, args []string) (string, error) { if args[0] == "container" { return "true running\n", nil @@ -168,3 +168,13 @@ func TestTheControlPlaneIsAskedByRunningItsOwnBinary(t *testing.T) { t.Errorf("the control plane was never asked anything: %v", runtime.commands) } } + +// TestVerify runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestVerify(t *testing.T) { + t.Run("AContainerThatIsUpIsNotAControlPlaneThatReplies", testAContainerThatIsUpIsNotAControlPlaneThatReplies) + t.Run("AControlPlaneThatSaysNothingHasNotAnswered", testAControlPlaneThatSaysNothingHasNotAnswered) + t.Run("AFoundationThatIsUpAndAnsweringIsAccepted", testAFoundationThatIsUpAndAnsweringIsAccepted) + t.Run("AControlPlaneThatIsStillStartingIsWaitedFor", testAControlPlaneThatIsStillStartingIsWaitedFor) + t.Run("AContainerThatExitedIsNamedWithItsState", testAContainerThatExitedIsNamedWithItsState) + t.Run("TheControlPlaneIsAskedByRunningItsOwnBinary", testTheControlPlaneIsAskedByRunningItsOwnBinary) +} diff --git a/internal/buckets/buckets_test.go b/internal/buckets/buckets_test.go index 0fd64c32..ef2fd57a 100644 --- a/internal/buckets/buckets_test.go +++ b/internal/buckets/buckets_test.go @@ -11,7 +11,7 @@ import ( // The engine's own states are named _ by the manifest; a constant that drifts from it reads and writes a // bucket nobody else knows (ADR 0634 §1, finding F4: the holder's name is kept in code and held to the manifest by this row). -func TestTheOwnStatesAreTheManifestsStates(t *testing.T) { +func testTheOwnStatesAreTheManifestsStates(t *testing.T) { raw, err := os.ReadFile("../../module.json") if err != nil { t.Fatal(err) @@ -37,7 +37,7 @@ func TestTheOwnStatesAreTheManifestsStates(t *testing.T) { } // A group's candidate key is its name as a key part: a branch with a slash keeps it, a dot is escaped, and an empty group does not. -func TestACandidateKeyEscapesTheGroup(t *testing.T) { +func testACandidateKeyEscapesTheGroup(t *testing.T) { for _, group := range []string{"mesh-sdk#7", "fix/940-no-retire", "fix/1.2"} { key, err := CandidateKey(group) if err != nil { @@ -57,7 +57,7 @@ func TestACandidateKeyEscapesTheGroup(t *testing.T) { // The holders' buckets are the names the grants part grants and the holders' manifests declare: no client carries a // holder (ADR 0625 §4), so these rows are the one place the node-engine's code says them. -func TestTheHoldersBucketsAreTheirStatesBuckets(t *testing.T) { +func testTheHoldersBucketsAreTheirStatesBuckets(t *testing.T) { for name, c := range map[string][2]string{ "Assignments": {Assignments, "mesh-delivery-assigner_assignments"}, "ProposalCandidates": {ProposalCandidates, "mesh-delivery-assigner_candidates"}, "Wants": {Wants, "mesh-delivery-assigner_wants"}, "Modules": {Modules, "mesh-delivery-indexer_modules"}, @@ -70,3 +70,10 @@ func TestTheHoldersBucketsAreTheirStatesBuckets(t *testing.T) { } } } + +// TestBuckets runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBuckets(t *testing.T) { + t.Run("TheOwnStatesAreTheManifestsStates", testTheOwnStatesAreTheManifestsStates) + t.Run("ACandidateKeyEscapesTheGroup", testACandidateKeyEscapesTheGroup) + t.Run("TheHoldersBucketsAreTheirStatesBuckets", testTheHoldersBucketsAreTheirStatesBuckets) +} diff --git a/internal/bundle/bundle_test.go b/internal/bundle/bundle_test.go index 386f837c..1a569dce 100644 --- a/internal/bundle/bundle_test.go +++ b/internal/bundle/bundle_test.go @@ -8,7 +8,7 @@ import ( "git.novox.be/novox/mesh-sdk/go/declaration" ) -func TestADefaultBuildCarriesNothingAndSaysSo(t *testing.T) { +func testADefaultBuildCarriesNothingAndSaysSo(t *testing.T) { // The important one. A host built without a bundle that applied nothing and reported // success would look exactly like a host that raised a first node — and the difference // would surface as a mesh that never came up, with nothing to point at. @@ -24,7 +24,7 @@ func TestADefaultBuildCarriesNothingAndSaysSo(t *testing.T) { } } -func TestABundleWithContentIsParsedByTheSameParserTheLinkWillUse(t *testing.T) { +func testABundleWithContentIsParsedByTheSameParserTheLinkWillUse(t *testing.T) { // A bundle that reaches a machine and is then refused by the host carrying it would be a // build-time mistake found at the worst possible moment. // @@ -41,7 +41,7 @@ func TestABundleWithContentIsParsedByTheSameParserTheLinkWillUse(t *testing.T) { } } -func TestWhatValidatesIsWhatIsApplied(t *testing.T) { +func testWhatValidatesIsWhatIsApplied(t *testing.T) { // Found on a real machine. `mesh-host bundle` validated the carried bundle through Load, // which strips comments; `reconcile` handed the RAW bytes to the parser, which does not. // So the command whose whole job is to check the bundle said yes, and the command that @@ -56,7 +56,7 @@ func TestWhatValidatesIsWhatIsApplied(t *testing.T) { } } -func TestEverySystemHasABundleAndAndroidsRefuses(t *testing.T) { +func testEverySystemHasABundleAndAndroidsRefuses(t *testing.T) { // The bundle's contents are per system even though its mechanism is not (novox/hq ADR // 0060), so a host must find one built for it — and a host built for a system with no // bundle at all must say that rather than behave like an empty one. @@ -75,7 +75,7 @@ func TestEverySystemHasABundleAndAndroidsRefuses(t *testing.T) { } } -func TestAndroidsBundleSaysWhyThereIsNone(t *testing.T) { +func testAndroidsBundleSaysWhyThereIsNone(t *testing.T) { // Not a placeholder waiting to be filled in. An android host implements neither `package` // nor `container` nor `service`, so every step of the bootstrap is a shape it does not // have — a partial host can JOIN a mesh and cannot BE the first node. @@ -86,3 +86,12 @@ func TestAndroidsBundleSaysWhyThereIsNone(t *testing.T) { } } } + +// TestBundle runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBundle(t *testing.T) { + t.Run("ADefaultBuildCarriesNothingAndSaysSo", testADefaultBuildCarriesNothingAndSaysSo) + t.Run("ABundleWithContentIsParsedByTheSameParserTheLinkWillUse", testABundleWithContentIsParsedByTheSameParserTheLinkWillUse) + t.Run("WhatValidatesIsWhatIsApplied", testWhatValidatesIsWhatIsApplied) + t.Run("EverySystemHasABundleAndAndroidsRefuses", testEverySystemHasABundleAndAndroidsRefuses) + t.Run("AndroidsBundleSaysWhyThereIsNone", testAndroidsBundleSaysWhyThereIsNone) +} diff --git a/internal/compose/credentials_test.go b/internal/compose/credentials_test.go index 96de579f..ba85c8c5 100644 --- a/internal/compose/credentials_test.go +++ b/internal/compose/credentials_test.go @@ -45,7 +45,7 @@ func withAssistant(t *testing.T) Input { // Own secrets (plan.go renderingFor, novox/hq issue 275 and 401): one held and sealed to the machine's key is carried; one not held is // foreseen in the Foreseeing mode and left out in the Reading mode, and nothing is made. -func TestAnOwnSecretHeldIsCarriedAndOneNotHeldIsForeseenOrLeftOut(t *testing.T) { +func testAnOwnSecretHeldIsCarriedAndOneNotHeldIsForeseenOrLeftOut(t *testing.T) { mk := func() Input { in := withAssistant(t) in.OwnSecrets = []OwnSecretRow{{Node: "laptop", Module: "assistant", Name: "password", Origin: "made", @@ -93,7 +93,7 @@ func TestAnOwnSecretHeldIsCarriedAndOneNotHeldIsForeseenOrLeftOut(t *testing.T) // An own secret issued outside the mesh that nobody gave is never made (novox/hq issue 401, ADR 0228): nothing is composed or // foreseen for it; a value the mesh made for it is not one a person gave; a value given is placed once it is sealed to the key held now. -func TestAnOutsideSecretIsPlacedOnlyOnceAPersonGaveIt(t *testing.T) { +func testAnOutsideSecretIsPlacedOnlyOnceAPersonGaveIt(t *testing.T) { in := withAssistant(t) key := nodeOf(t, &in, "laptop").SealingKey for _, mode := range []Mode{Reading, Foreseeing} { @@ -120,7 +120,7 @@ func TestAnOutsideSecretIsPlacedOnlyOnceAPersonGaveIt(t *testing.T) { // controller's words. No secret value is in an error. A bus account not yet issued is foreseen, issued or not (issue 774: the vault // mints it once the assignment is written on the Approve, ADR 0561 §1, ADR 0567 §5; mesh-self-check's proposal on ace was refused // "has no bus credential: nothing was issued for ace.mesh-self-check"). -func TestTheSendsRefusalsAreRefusedInTheSendsWords(t *testing.T) { +func testTheSendsRefusalsAreRefusedInTheSendsWords(t *testing.T) { broker := catalogue.Manifest{Module: "mesh-self-check", Version: "1", RunsAs: "mesh-self-check", OwnSecrets: catalogue.OwnSecrets{"broker": {Path: "/var/lib/mesh/mesh-self-check/broker", Taken: catalogue.TakenAtStart}}} in := withAssistant(t) @@ -168,7 +168,7 @@ func aGrantMesh(t *testing.T) Input { // A credential made for a consumer is a grant on its provider's machine, carrying the consumer's values and the sealed copy; without // the sealed copy a stand-in is composed and named (novox/hq plan.go grantsFor). -func TestAGrantIsCreatedForEachCredentialMadeForAConsumer(t *testing.T) { +func testAGrantIsCreatedForEachCredentialMadeForAConsumer(t *testing.T) { in := aGrantMesh(t) // 1126 (ADR 0550 §5): the credentials each node's composition reads, by their ends: laptop's files consumes anchor's // s3-bucket, and anchor grants it; the node composing its own asks the vault for exactly these. @@ -211,7 +211,7 @@ func TestAGrantIsCreatedForEachCredentialMadeForAConsumer(t *testing.T) { // 1364/AC2: a consumer the grants leave out because its identity overflows the provision's bound is returned beside them, naming the // consumer and the provision (novox/hq ADR 0225), and is not granted. -func TestAConsumerWhoseIdentityOverflowsIsLeftOutOfTheGrantsAndNamed(t *testing.T) { +func testAConsumerWhoseIdentityOverflowsIsLeftOutOfTheGrantsAndNamed(t *testing.T) { in := aGrantMesh(t) in.Nodes[1].Name = "a-machine-with-a-very-long-name" in.Issued[0].Consumer = "a-machine-with-a-very-long-name" @@ -231,7 +231,7 @@ func TestAConsumerWhoseIdentityOverflowsIsLeftOutOfTheGrantsAndNamed(t *testing. // 1364/AC3: a credential on record for a consumer that its own resolution binds to another provider is withdrawn, named with where it is // bound (novox/hq issue 274): the grant stays, with no consumer module asking. -func TestACredentialBoundToAnotherProviderIsWithdrawnAndSaidWhereItIsBound(t *testing.T) { +func testACredentialBoundToAnotherProviderIsWithdrawnAndSaidWhereItIsBound(t *testing.T) { in := aGrantMesh(t) second := objects() second.Module = "objects2" @@ -264,7 +264,7 @@ func aCertificateMesh(t *testing.T) Input { // 1364/AC4: with no certificate and authority in the Input a stand-in is composed and named; given them, the composition carries them as // given. A machine that never reported a serving key, and one not on the private network, are refused in the controller's words. -func TestACertificateIsCarriedAsGivenOrStoodInForAndNamed(t *testing.T) { +func testACertificateIsCarriedAsGivenOrStoodInForAndNamed(t *testing.T) { in := aCertificateMesh(t) laptop := nodeOf(t, &in, "laptop") if _, err := Render(in, "laptop", Foreseeing); err == nil || err.Error() != "laptop wants a certificate and has never told the mesh what key it serves with; it joins again to report one" { @@ -291,7 +291,7 @@ func aValidKey(t *testing.T, name string) string { return keyOf(t, name) } // 1364/AC5 and AC6: a core credential the node needs and the Input holds no box for is composed with a stand-in and returned as one // to keep; a kept box sealed to the key held now is carried; a node-engine below the vault-box contract is sent none (and nothing is // asked of it); a machine with no sealing key has its core module left out, said. -func TestACoreBoxTheInputHoldsNoneOfIsReturnedToKeepAndNothingIsWritten(t *testing.T) { +func testACoreBoxTheInputHoldsNoneOfIsReturnedToKeepAndNothingIsWritten(t *testing.T) { mk := func() Input { in := aMesh(t) in.Catalogue["nats"] = catalogue.Manifest{Module: "nats", Version: "1", CoreCredentials: true, @@ -337,7 +337,7 @@ func TestACoreBoxTheInputHoldsNoneOfIsReturnedToKeepAndNothingIsWritten(t *testi // 1364/AC1: the bus's user list is carried for the machine that runs the bus and for no other; without it a stand-in is composed and // named; the users left out for want of a credential are said; each machine's membership is carried. (The list is composed by the // controller from the bus records, which stay the controller's: see the commit message.) -func TestTheBusUserListIsCarriedForTheMachineThatRunsTheBus(t *testing.T) { +func testTheBusUserListIsCarriedForTheMachineThatRunsTheBus(t *testing.T) { in := aMesh(t) in.Catalogue["bus"] = catalogue.Manifest{Module: "bus", Version: "1", BusUsers: "/etc/bus/accounts.conf", Claims: []catalogue.Claim{{Name: "mesh-broker", Scope: catalogue.ScopeMesh}}} @@ -364,7 +364,7 @@ func TestTheBusUserListIsCarriedForTheMachineThatRunsTheBus(t *testing.T) { } // 1364/AC7: nothing the composition says carries a secret value the Input holds. -func TestNoSecretValueOfTheInputIsInWhatTheCompositionSays(t *testing.T) { +func testNoSecretValueOfTheInputIsInWhatTheCompositionSays(t *testing.T) { in := aGrantMesh(t) in.Issued[0].ForProvider = secretValue laptop := nodeOf(t, &in, "laptop") @@ -387,7 +387,7 @@ func TestNoSecretValueOfTheInputIsInWhatTheCompositionSays(t *testing.T) { // the vault mints or takes in; an offer of form none has no credential (issue 1126, 2026-11-02: mesh-cli on ace held for // "the grant of mcp-endpoint", whose provider node-tools offers form none): its grant carries the consumer and no // credential, nothing stands in on either side, and neither end asks the vault for one. -func TestAConsumerNoCredentialWasMadeForYetIsGrantedWithAStandInUnlessItsOfferHasNone(t *testing.T) { +func testAConsumerNoCredentialWasMadeForYetIsGrantedWithAStandInUnlessItsOfferHasNone(t *testing.T) { for _, tc := range []struct { form string cred *catalogue.OfferCredential @@ -458,7 +458,7 @@ func TestAConsumerNoCredentialWasMadeForYetIsGrantedWithAStandInUnlessItsOfferHa } // And a consumer whose identity overflows the provision's bound is judged before any credential is made for it (issue 263). -func TestAnOverflowingConsumerNoCredentialWasMadeForYetIsWithheld(t *testing.T) { +func testAnOverflowingConsumerNoCredentialWasMadeForYetIsWithheld(t *testing.T) { in := aGrantMesh(t) in.Issued = nil in.Catalogue["resolver"] = storeManifests()[1] @@ -473,7 +473,7 @@ func TestAnOverflowingConsumerNoCredentialWasMadeForYetIsWithheld(t *testing.T) } // The grants come in the order the controller reads them, whatever order the Input gives its rows. -func TestGrantsComeInTheOrderOfProvisionConsumerModuleAndLocal(t *testing.T) { +func testGrantsComeInTheOrderOfProvisionConsumerModuleAndLocal(t *testing.T) { in := aGrantMesh(t) in.Issued = []Issued{ {Provision: "s3-bucket", Consumer: "laptop", ConsumerModule: "files", Local: "b", Provider: "anchor", ForProvider: "x"}, @@ -488,7 +488,7 @@ func TestGrantsComeInTheOrderOfProvisionConsumerModuleAndLocal(t *testing.T) { // Round 1, finding 4: a member of a secret family a person gave, whose sealed value the Input does not carry, is placed with a // stand-in and named foreseen, not dropped as if nobody gave it. -func TestAGivenFamilyMemberWithoutItsValueIsAStandInAndNamedForeseen(t *testing.T) { +func testAGivenFamilyMemberWithoutItsValueIsAStandInAndNamedForeseen(t *testing.T) { in := aMesh(t) in.Catalogue["mailer"] = catalogue.Manifest{Module: "mailer", Version: "1", OwnSecrets: catalogue.OwnSecrets{"credential-*": {Path: "/var/lib/mailer/credential-*.secret", Taken: catalogue.TakenAtStart, IssuedBy: catalogue.IssuedOutside}}} @@ -510,7 +510,7 @@ func TestAGivenFamilyMemberWithoutItsValueIsAStandInAndNamedForeseen(t *testing. } // Round 1, finding 5: the suffix internal names end in is a field of the Input, and the environment is never read. -func TestTheInternalSuffixIsTheInputsAndNeverTheEnvironments(t *testing.T) { +func testTheInternalSuffixIsTheInputsAndNeverTheEnvironments(t *testing.T) { t.Setenv(overlay.SuffixVar, "from-the-environment") in := aGrantMesh(t) got := rendered(t, in, "anchor", Foreseeing) @@ -532,7 +532,7 @@ func TestTheInternalSuffixIsTheInputsAndNeverTheEnvironments(t *testing.T) { } // Round 2: a need answered on the same machine is a grant too (catalogue resolve.go gives it From: the node's own name). -func TestAConsumerOnTheProvidersOwnNodeIsGrantedWithAStandInAndNamedForeseen(t *testing.T) { +func testAConsumerOnTheProvidersOwnNodeIsGrantedWithAStandInAndNamedForeseen(t *testing.T) { in := aGrantMesh(t) in.Issued = nil laptop, anchor := nodeOf(t, &in, "laptop"), nodeOf(t, &in, "anchor") @@ -546,3 +546,23 @@ func TestAConsumerOnTheProvidersOwnNodeIsGrantedWithAStandInAndNamedForeseen(t * t.Errorf("foreseen %v", got.Foreseen) } } + +// TestCredentials runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestCredentials(t *testing.T) { + t.Run("AnOwnSecretHeldIsCarriedAndOneNotHeldIsForeseenOrLeftOut", testAnOwnSecretHeldIsCarriedAndOneNotHeldIsForeseenOrLeftOut) + t.Run("AnOutsideSecretIsPlacedOnlyOnceAPersonGaveIt", testAnOutsideSecretIsPlacedOnlyOnceAPersonGaveIt) + t.Run("TheSendsRefusalsAreRefusedInTheSendsWords", testTheSendsRefusalsAreRefusedInTheSendsWords) + t.Run("AGrantIsCreatedForEachCredentialMadeForAConsumer", testAGrantIsCreatedForEachCredentialMadeForAConsumer) + t.Run("AConsumerWhoseIdentityOverflowsIsLeftOutOfTheGrantsAndNamed", testAConsumerWhoseIdentityOverflowsIsLeftOutOfTheGrantsAndNamed) + t.Run("ACredentialBoundToAnotherProviderIsWithdrawnAndSaidWhereItIsBound", testACredentialBoundToAnotherProviderIsWithdrawnAndSaidWhereItIsBound) + t.Run("ACertificateIsCarriedAsGivenOrStoodInForAndNamed", testACertificateIsCarriedAsGivenOrStoodInForAndNamed) + t.Run("ACoreBoxTheInputHoldsNoneOfIsReturnedToKeepAndNothingIsWritten", testACoreBoxTheInputHoldsNoneOfIsReturnedToKeepAndNothingIsWritten) + t.Run("TheBusUserListIsCarriedForTheMachineThatRunsTheBus", testTheBusUserListIsCarriedForTheMachineThatRunsTheBus) + t.Run("NoSecretValueOfTheInputIsInWhatTheCompositionSays", testNoSecretValueOfTheInputIsInWhatTheCompositionSays) + t.Run("AConsumerNoCredentialWasMadeForYetIsGrantedWithAStandInUnlessItsOfferHasNone", testAConsumerNoCredentialWasMadeForYetIsGrantedWithAStandInUnlessItsOfferHasNone) + t.Run("AnOverflowingConsumerNoCredentialWasMadeForYetIsWithheld", testAnOverflowingConsumerNoCredentialWasMadeForYetIsWithheld) + t.Run("GrantsComeInTheOrderOfProvisionConsumerModuleAndLocal", testGrantsComeInTheOrderOfProvisionConsumerModuleAndLocal) + t.Run("AGivenFamilyMemberWithoutItsValueIsAStandInAndNamedForeseen", testAGivenFamilyMemberWithoutItsValueIsAStandInAndNamedForeseen) + t.Run("TheInternalSuffixIsTheInputsAndNeverTheEnvironments", testTheInternalSuffixIsTheInputsAndNeverTheEnvironments) + t.Run("AConsumerOnTheProvidersOwnNodeIsGrantedWithAStandInAndNamedForeseen", testAConsumerOnTheProvidersOwnNodeIsGrantedWithAStandInAndNamedForeseen) +} diff --git a/internal/compose/network_test.go b/internal/compose/network_test.go index 47a8553f..2730716e 100644 --- a/internal/compose/network_test.go +++ b/internal/compose/network_test.go @@ -33,7 +33,7 @@ func onTheTunnel(t *testing.T, in *Input, replaced bool) { // novox/hq ADR 0105 (mesh-controller network_test.go TestTheOverlaysRangeIsTheAdoptedTunnels): the range every address is // composed from is the adopted tunnel's, read from the tunnel the hub holds, never stored anywhere else. The environment // value of the controller is Input.OverlayCIDR here. -func TestTheOverlaysRangeIsTheAdoptedTunnels(t *testing.T) { +func testTheOverlaysRangeIsTheAdoptedTunnels(t *testing.T) { in := aMesh(t) in.OverlayCIDR = "10.99.0.0/16" if got := newComposer(in).overlayRange(); got != "10.99.0.0/16" { @@ -83,7 +83,7 @@ func TestTheOverlaysRangeIsTheAdoptedTunnels(t *testing.T) { // A takeover is composed only for a hub whose assignment agrees with the tunnel (mesh-controller network_test.go // TestATakeoverIsNotComposedForAHubPlacedOffItsTunnel): an address or an endpoint port that differs would have the host stop // the found interface and raise the mesh's where no peer is listening. -func TestATakeoverIsNotComposedForAHubPlacedOffItsTunnel(t *testing.T) { +func testATakeoverIsNotComposedForAHubPlacedOffItsTunnel(t *testing.T) { in := aMesh(t) onTheTunnel(t, &in, false) // aMesh placed anchor at 10.77.0.1 on :51820, the record of a hub placed before it took the tunnel over. @@ -105,7 +105,7 @@ func TestATakeoverIsNotComposedForAHubPlacedOffItsTunnel(t *testing.T) { // 1360/AC2: the generator gives the addresses, peers and names of aMesh: anchor the hub at 10.77.0.1, laptop at 10.77.0.2 // peering through it, both written for their machines. -func TestTheGeneratorGivesTheMeshItsAddressesAndPeers(t *testing.T) { +func testTheGeneratorGivesTheMeshItsAddressesAndPeers(t *testing.T) { in := aMesh(t) gens, err := Generators(in) if err != nil { @@ -139,7 +139,7 @@ func TestTheGeneratorGivesTheMeshItsAddressesAndPeers(t *testing.T) { // 1360/AC3: a node not on the private network (it runs nothing that puts it there) gets no address and no network, and the // one that stayed keeps its own. -func TestANodeNotOnThePrivateNetworkGetsNoAddressAndNoNetwork(t *testing.T) { +func testANodeNotOnThePrivateNetworkGetsNoAddressAndNoNetwork(t *testing.T) { in := aMesh(t) nodeOf(t, &in, "laptop").Assigned = nil // it keeps its place and its address, and stops running the network gens, err := Generators(in) @@ -161,7 +161,7 @@ func TestANodeNotOnThePrivateNetworkGetsNoAddressAndNoNetwork(t *testing.T) { // 1360/AC3: a node whose resolution is refused is said with today's words: the network missing its hub names the // machine that could not be resolved, which is almost always why. The hub here holds no complete place (no key): a refused // machine with one keeps it on the network (issue 1833), so only one without is missing from it. -func TestARefusedNodeIsSaidWhenTheNetworkCannotBeComposed(t *testing.T) { +func testARefusedNodeIsSaidWhenTheNetworkCannotBeComposed(t *testing.T) { in := aMesh(t) nodeOf(t, &in, "anchor").Place.Key = "" in.Catalogue["rival-one"] = catalogue.Manifest{Module: "rival-one", Version: "1", Resources: []map[string]any{{"id": "r", "type": "directory", "path": "/var/lib/the-same", "mode": "0700"}}} @@ -180,7 +180,7 @@ func TestARefusedNodeIsSaidWhenTheNetworkCannotBeComposed(t *testing.T) { } // 1360/AC4: Generators changes nothing in its Input. -func TestGeneratorsChangesNothingInItsInput(t *testing.T) { +func testGeneratorsChangesNothingInItsInput(t *testing.T) { unchanged(t, func() Input { in := aMesh(t) onTheTunnel(t, &in, true) @@ -194,7 +194,7 @@ func TestGeneratorsChangesNothingInItsInput(t *testing.T) { } // Each field of Input that the network reads reaches the generator: change it and the generator changes. -func TestEachFieldOfTheInputReachesTheGenerator(t *testing.T) { +func testEachFieldOfTheInputReachesTheGenerator(t *testing.T) { addressesOf := func(in Input) map[string]string { t.Helper() gens, err := Generators(in) @@ -302,3 +302,14 @@ func TestEachFieldOfTheInputReachesTheGenerator(t *testing.T) { } }) } + +// TestNetwork runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestNetwork(t *testing.T) { + t.Run("TheOverlaysRangeIsTheAdoptedTunnels", testTheOverlaysRangeIsTheAdoptedTunnels) + t.Run("ATakeoverIsNotComposedForAHubPlacedOffItsTunnel", testATakeoverIsNotComposedForAHubPlacedOffItsTunnel) + t.Run("TheGeneratorGivesTheMeshItsAddressesAndPeers", testTheGeneratorGivesTheMeshItsAddressesAndPeers) + t.Run("ANodeNotOnThePrivateNetworkGetsNoAddressAndNoNetwork", testANodeNotOnThePrivateNetworkGetsNoAddressAndNoNetwork) + t.Run("ARefusedNodeIsSaidWhenTheNetworkCannotBeComposed", testARefusedNodeIsSaidWhenTheNetworkCannotBeComposed) + t.Run("GeneratorsChangesNothingInItsInput", testGeneratorsChangesNothingInItsInput) + t.Run("EachFieldOfTheInputReachesTheGenerator", testEachFieldOfTheInputReachesTheGenerator) +} diff --git a/internal/compose/node_test.go b/internal/compose/node_test.go index 15b97fee..57e56e0a 100644 --- a/internal/compose/node_test.go +++ b/internal/compose/node_test.go @@ -46,7 +46,7 @@ func aSmallMesh(t *testing.T) Input { // 1298/AC1: each node of a small mesh composes, its body is accepted by the node-engine's validator, and it names the resources the // controller composes for the same case: the private network's files on the nodes that run it, the provider's received file, the // consumer's file. -func TestEachNodeOfASmallMeshComposesAndItsBodyIsAcceptedByTheValidator(t *testing.T) { +func testEachNodeOfASmallMeshComposesAndItsBodyIsAcceptedByTheValidator(t *testing.T) { in := aSmallMesh(t) want := map[string][]string{ "anchor": {"package:mesh-wireguard.overlay-tools", "file:mesh-wireguard.overlay-config", "service:mesh-wireguard.overlay-up", "file:objects.received-s3-bucket"}, @@ -85,7 +85,7 @@ func TestEachNodeOfASmallMeshComposesAndItsBodyIsAcceptedByTheValidator(t *testi // 1298/AC2 (mesh-controller merge_gate_integration_test.go TestIssue236AManifestTheNodeEngineRefusesFailsThePullRequest, the manifest): // a service that omits its state is accepted by the catalogue's check and refused by the node-engine; Compose returns the validator's // problems in the node-engine's words and no error. -func TestAManifestTheNodeEngineRefusesComesBackAsProblemsAndNoError(t *testing.T) { +func testAManifestTheNodeEngineRefusesComesBackAsProblemsAndNoError(t *testing.T) { in := aMesh(t) var lemurs catalogue.Manifest if err := json.Unmarshal([]byte(`{"module":"lemurs","version":"1","capabilities":["systemd"], @@ -113,7 +113,7 @@ func TestAManifestTheNodeEngineRefusesComesBackAsProblemsAndNoError(t *testing.T } // 1298/AC4: composing the same Input twice gives byte-identical bodies, and the Input is unchanged. -func TestComposingTwiceGivesTheSameBytesAndChangesNothing(t *testing.T) { +func testComposingTwiceGivesTheSameBytesAndChangesNothing(t *testing.T) { mk := func() Input { in := aSmallMesh(t) nodeOf(t, &in, "anchor").Account = "jochens" @@ -147,7 +147,7 @@ func TestComposingTwiceGivesTheSameBytesAndChangesNothing(t *testing.T) { // 1298/AC5: what a send would make is named in the result as foreseen and never invented: an own secret, a port, a core box, a grant's // sealed copy. -func TestWhatASendWouldMakeIsNamedAsForeseenAndNeverInvented(t *testing.T) { +func testWhatASendWouldMakeIsNamedAsForeseenAndNeverInvented(t *testing.T) { in := aGrantMesh(t) in.Issued[0].ForProvider = "" in.Catalogue["assistant"] = anAssistant() @@ -183,7 +183,7 @@ func TestWhatASendWouldMakeIsNamedAsForeseenAndNeverInvented(t *testing.T) { // 1298/AC6: the body carries the sequence, epoch and generation the Input gives, and the module of each resource and the carried builds // only to a node whose Input says it reads modules (novox/hq issue 1145). -func TestTheBodyCarriesTheOrderTheInputGivesAndTheBuildsOnlyToAnEngineThatReadsThem(t *testing.T) { +func testTheBodyCarriesTheOrderTheInputGivesAndTheBuildsOnlyToAnEngineThatReadsThem(t *testing.T) { in := aSmallMesh(t) laptop := nodeOf(t, &in, "laptop") laptop.Sequence, laptop.Epoch, laptop.Generation = 42, 57, 9 @@ -246,7 +246,7 @@ func TestTheBodyCarriesTheOrderTheInputGivesAndTheBuildsOnlyToAnEngineThatReadsT } // A module left out of a build set keeps the build it was last sent (novox/hq issue 259): the machine keeps that one. -func TestAModuleLeftOutKeepsTheBuildItWasLastSent(t *testing.T) { +func testAModuleLeftOutKeepsTheBuildItWasLastSent(t *testing.T) { c := newComposer(Input{CurrentBuilds: map[string]string{"a": "new-a", "b": "new-b"}}) plan := catalogue.Resolution{Modules: []catalogue.Manifest{{Module: "a"}, {Module: "b"}, {Module: "c"}}} node := Node{SentBuilds: map[string]string{"b": "old-b", "c": "old-c"}, SentKnown: true} @@ -262,7 +262,7 @@ func TestAModuleLeftOutKeepsTheBuildItWasLastSent(t *testing.T) { // An adopted node is told which modules were taken and, for every module it runs that is not, the ids of its resources // (novox/hq ADR 0100 and 0103); a converged node is told nothing, and its body is as it was before adoption. -func TestAnAdoptedNodeIsToldWhatWasTakenAndWhatIsKept(t *testing.T) { +func testAnAdoptedNodeIsToldWhatWasTakenAndWhatIsKept(t *testing.T) { in := aSmallMesh(t) d, _, err := Compose(in, "laptop") if err != nil || d.Adoption != nil { @@ -286,7 +286,7 @@ func TestAnAdoptedNodeIsToldWhatWasTakenAndWhatIsKept(t *testing.T) { // Issue 263 (merge_gate_integration_test.go TestIssue263AnIdentityARealMachineNameOverflows...): a change makes the network manager // require the object store's provision; on a machine whose name is six characters its identity is 26 against a bound of 20. The // composition of the provider returns the refusal, naming the module and the provision. -func TestIssue263AnIdentityARealMachineNameOverflowsIsARefusal(t *testing.T) { +func testIssue263AnIdentityARealMachineNameOverflowsIsARefusal(t *testing.T) { in := aGrantMesh(t) in.Catalogue["resolver"] = storeManifests()[1] in.Catalogue["networkmanager"] = catalogue.Manifest{Module: "networkmanager", Version: "1", Requires: []string{"wildcard-resolution", "s3-bucket"}} @@ -311,7 +311,7 @@ func TestIssue263AnIdentityARealMachineNameOverflowsIsARefusal(t *testing.T) { // Round 1, finding 1 (plan.go keepRecorded): a recorded module kept at the build a machine runs is that machine's own resolution // and no other's; the commit carried for it is the kept one. -func TestAKeptModuleChangesOnlyTheResolutionOfTheNodeThatKeepsIt(t *testing.T) { +func testAKeptModuleChangesOnlyTheResolutionOfTheNodeThatKeepsIt(t *testing.T) { in := aSmallMesh(t) in.Catalogue["tool"] = catalogue.Manifest{Module: "tool", Version: "2"} for _, name := range []string{"anchor", "laptop"} { @@ -356,7 +356,7 @@ func TestAKeptModuleChangesOnlyTheResolutionOfTheNodeThatKeepsIt(t *testing.T) { // Another node's kept build changes neither the rest of the mesh nor who is on the network: the controller reads both with the // current manifests, and only then keeps a recorded module for the node it composes (recorded_kept.go keepRecorded). -func TestAnotherNodesKeptBuildDoesNotChangeTheRestOfTheMeshOrWhoIsOnTheNetwork(t *testing.T) { +func testAnotherNodesKeptBuildDoesNotChangeTheRestOfTheMeshOrWhoIsOnTheNetwork(t *testing.T) { in := threeNodes(t) nodeOf(t, &in, "anchor").Kept = map[string]catalogue.Manifest{"objects": {Module: "objects", Version: "0"}, overlayName(): {Module: overlayName(), Version: "0"}} w, _, _, err := TheRestOfTheMesh(in, "laptop") @@ -373,7 +373,7 @@ func overlayName() string { return overlay.Name } // Round 1, finding 6: the nodes the composition did not count as on the network are returned, said, not lost. laptop holds no // complete place (no key): one that does keeps it on the network (issue 1833) and is counted. -func TestANodeNotCountedAsOnTheNetworkIsSaidInTheResult(t *testing.T) { +func testANodeNotCountedAsOnTheNetworkIsSaidInTheResult(t *testing.T) { in := aMesh(t) nodeOf(t, &in, "laptop").Place.Key = "" in.Catalogue["rival-one"] = catalogue.Manifest{Module: "rival-one", Version: "1", Resources: []map[string]any{{"id": "r", "type": "directory", "path": "/var/lib/the-same", "mode": "0700"}}} @@ -406,3 +406,18 @@ func TestANodeNotCountedAsOnTheNetworkIsSaidInTheResult(t *testing.T) { t.Errorf("said %d times: %v", n, d.Said) } } + +// TestNode runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestNode(t *testing.T) { + t.Run("EachNodeOfASmallMeshComposesAndItsBodyIsAcceptedByTheValidator", testEachNodeOfASmallMeshComposesAndItsBodyIsAcceptedByTheValidator) + t.Run("AManifestTheNodeEngineRefusesComesBackAsProblemsAndNoError", testAManifestTheNodeEngineRefusesComesBackAsProblemsAndNoError) + t.Run("ComposingTwiceGivesTheSameBytesAndChangesNothing", testComposingTwiceGivesTheSameBytesAndChangesNothing) + t.Run("WhatASendWouldMakeIsNamedAsForeseenAndNeverInvented", testWhatASendWouldMakeIsNamedAsForeseenAndNeverInvented) + t.Run("TheBodyCarriesTheOrderTheInputGivesAndTheBuildsOnlyToAnEngineThatReadsThem", testTheBodyCarriesTheOrderTheInputGivesAndTheBuildsOnlyToAnEngineThatReadsThem) + t.Run("AModuleLeftOutKeepsTheBuildItWasLastSent", testAModuleLeftOutKeepsTheBuildItWasLastSent) + t.Run("AnAdoptedNodeIsToldWhatWasTakenAndWhatIsKept", testAnAdoptedNodeIsToldWhatWasTakenAndWhatIsKept) + t.Run("Issue263AnIdentityARealMachineNameOverflowsIsARefusal", testIssue263AnIdentityARealMachineNameOverflowsIsARefusal) + t.Run("AKeptModuleChangesOnlyTheResolutionOfTheNodeThatKeepsIt", testAKeptModuleChangesOnlyTheResolutionOfTheNodeThatKeepsIt) + t.Run("AnotherNodesKeptBuildDoesNotChangeTheRestOfTheMeshOrWhoIsOnTheNetwork", testAnotherNodesKeptBuildDoesNotChangeTheRestOfTheMeshOrWhoIsOnTheNetwork) + t.Run("ANodeNotCountedAsOnTheNetworkIsSaidInTheResult", testANodeNotCountedAsOnTheNetworkIsSaidInTheResult) +} diff --git a/internal/compose/one_machine_alone_test.go b/internal/compose/one_machine_alone_test.go index 1ad5f631..76d12c6c 100644 --- a/internal/compose/one_machine_alone_test.go +++ b/internal/compose/one_machine_alone_test.go @@ -55,7 +55,7 @@ func placesOf(g *overlay.Generator) map[string]overlay.Node { // 1833/AC1: four machines, the hub's own set does not resolve; the other three compose their declarations, and the hub alone is // refused, with an error that is its own set failing and names what could not be resolved. -func TestOneMachineThatDoesNotResolveIsRefusedAlone(t *testing.T) { +func testOneMachineThatDoesNotResolveIsRefusedAlone(t *testing.T) { in := fourOnTheNetwork(t) unresolvableBy(t, &in, "anchor") for _, node := range []string{"laptop", "ace", "box"} { @@ -79,7 +79,7 @@ func TestOneMachineThatDoesNotResolveIsRefusedAlone(t *testing.T) { // 1833/AC2: the private network is composed with every machine on it: the hub that does not resolve keeps its place (key, // address, endpoint, site, hub role), so every other machine keeps its path through it. -func TestAMachineThatDoesNotResolveKeepsItsPlaceOnTheNetwork(t *testing.T) { +func testAMachineThatDoesNotResolveKeepsItsPlaceOnTheNetwork(t *testing.T) { in := fourOnTheNetwork(t) unresolvableBy(t, &in, "anchor") got := placesOf(networkOf(t, in)) @@ -107,7 +107,7 @@ func TestAMachineThatDoesNotResolveKeepsItsPlaceOnTheNetwork(t *testing.T) { // 1833/AC3: a machine that does not resolve and was never placed (a new machine: no key, no address) is left off the network, // which is composed from the rest -- here with the hub that does not resolve on its last place -- and that machine alone is refused. -func TestANewMachineThatDoesNotResolveIsLeftOffAndRefusedAlone(t *testing.T) { +func testANewMachineThatDoesNotResolveIsLeftOffAndRefusedAlone(t *testing.T) { in := fourOnTheNetwork(t) unresolvableBy(t, &in, "anchor") in.Nodes = append(in.Nodes, Node{Name: "fresh", Place: Place{Site: "there"}, @@ -126,7 +126,7 @@ func TestANewMachineThatDoesNotResolveIsLeftOffAndRefusedAlone(t *testing.T) { // 1833/AC4: a network that truly cannot be composed from what remains still fails: the hub does not resolve and has no // complete place (no key), so nothing is the hub; the refusal is today's, naming the machine that could not be resolved. -func TestANetworkThatCannotBeComposedFromWhatRemainsStillFails(t *testing.T) { +func testANetworkThatCannotBeComposedFromWhatRemainsStillFails(t *testing.T) { in := fourOnTheNetwork(t) unresolvableBy(t, &in, "anchor") nodeOf(t, &in, "anchor").Place.Key = "" @@ -147,7 +147,7 @@ func TestANetworkThatCannotBeComposedFromWhatRemainsStillFails(t *testing.T) { // 1833/AC2, a failure the composition's unchecked pass refuses too (two modules claiming one seat on the hub, the 1360/AC3 // shape): the hub keeps its place in what every other machine is sent besides the tunnel -- its internal name and its address // among the sources "from the mesh" -- and another machine still composes. -func TestAMachineThatDoesNotResolveKeepsItsNameAndItsAddressInTheMesh(t *testing.T) { +func testAMachineThatDoesNotResolveKeepsItsNameAndItsAddressInTheMesh(t *testing.T) { in := fourOnTheNetwork(t) in.Catalogue["rival-one"] = catalogue.Manifest{Module: "rival-one", Version: "1", Resources: []map[string]any{{"id": "r", "type": "directory", "path": "/var/lib/the-same", "mode": "0700"}}} in.Catalogue["rival-two"] = catalogue.Manifest{Module: "rival-two", Version: "1", Resources: []map[string]any{{"id": "r", "type": "directory", "path": "/var/lib/the-same", "mode": "0700"}}} @@ -167,3 +167,12 @@ func TestAMachineThatDoesNotResolveKeepsItsNameAndItsAddressInTheMesh(t *testing t.Errorf("another machine does not compose: %v %v", err, problems) } } + +// TestOneMachineAlone runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestOneMachineAlone(t *testing.T) { + t.Run("OneMachineThatDoesNotResolveIsRefusedAlone", testOneMachineThatDoesNotResolveIsRefusedAlone) + t.Run("AMachineThatDoesNotResolveKeepsItsPlaceOnTheNetwork", testAMachineThatDoesNotResolveKeepsItsPlaceOnTheNetwork) + t.Run("ANewMachineThatDoesNotResolveIsLeftOffAndRefusedAlone", testANewMachineThatDoesNotResolveIsLeftOffAndRefusedAlone) + t.Run("ANetworkThatCannotBeComposedFromWhatRemainsStillFails", testANetworkThatCannotBeComposedFromWhatRemainsStillFails) + t.Run("AMachineThatDoesNotResolveKeepsItsNameAndItsAddressInTheMesh", testAMachineThatDoesNotResolveKeepsItsNameAndItsAddressInTheMesh) +} diff --git a/internal/compose/rendering_test.go b/internal/compose/rendering_test.go index 8777d324..00c5e19a 100644 --- a/internal/compose/rendering_test.go +++ b/internal/compose/rendering_test.go @@ -41,7 +41,7 @@ func placed(t *testing.T, in Input, node string) Placed { // 1363/AC1 and AC2: a port the Input holds as allocated on the node is the one composed; with none, no number is invented: the // manifest's own is composed and the port is named foreseen, as the Foreseeing mode does. -func TestAnAllocatedPortIsComposedAndAnUnallocatedOneIsNamedForeseenNotInvented(t *testing.T) { +func testAnAllocatedPortIsComposedAndAnUnallocatedOneIsNamedForeseenNotInvented(t *testing.T) { mk := func() Input { in := aMesh(t) in.Catalogue["web"] = aWebModule() @@ -81,7 +81,7 @@ func TestAnAllocatedPortIsComposedAndAnUnallocatedOneIsNamedForeseenNotInvented( // 1363/AC3: a port the operator gave is used, over the allocated one, and a consumer elsewhere is told it // (mesh-controller sendable_integration_test.go TestConsumersAreToldTheGivenPort). -func TestAPortTheOperatorGaveIsUsedAndNotReallocated(t *testing.T) { +func testAPortTheOperatorGaveIsUsedAndNotReallocated(t *testing.T) { in := aMesh(t) in.Catalogue["store"] = aStoreModule() in.Catalogue["app"] = catalogue.Manifest{Module: "app", Version: "1", Requires: []string{"database"}} @@ -131,7 +131,7 @@ func TestAPortTheOperatorGaveIsUsedAndNotReallocated(t *testing.T) { // 1363/AC4: the seats held and taken reach the Rendering: where each mesh-scoped seat's holder put its ports, from the node's // given and assigned ports, never the manifest's own; and on an adopted node a holder assigned but not taken counts only by its // given ports (novox/hq ADR 0100). -func TestSeatsHeldAndTakenReachTheRendering(t *testing.T) { +func testSeatsHeldAndTakenReachTheRendering(t *testing.T) { in := aMesh(t) holder := aStoreModule() holder.Claims = []catalogue.Claim{{Name: "mesh-store", Scope: catalogue.ScopeMesh}} @@ -163,7 +163,7 @@ func TestSeatsHeldAndTakenReachTheRendering(t *testing.T) { // 1363/AC4: local networks and outward links (mesh-controller local_network_test.go TestNodeShowsWhichAttachedNetworksCountAndWhy, // the values): a private network on a link facing outside counts, a public subnet and the private network's own link never do; a // machine that said none judges to nothing. -func TestLocalNetworksAndOutwardLinksReachTheRendering(t *testing.T) { +func testLocalNetworksAndOutwardLinksReachTheRendering(t *testing.T) { in := aMesh(t) laptop := nodeOf(t, &in, "laptop") laptop.OutwardLinks = []string{"eth0", "eth1"} @@ -184,7 +184,7 @@ func TestLocalNetworksAndOutwardLinksReachTheRendering(t *testing.T) { } // 1363/AC4: accounts, the names of the mesh, the mesh range and the operator's export reach the Rendering. -func TestAccountsNamesAndTheOperatorsExportReachTheRendering(t *testing.T) { +func testAccountsNamesAndTheOperatorsExportReachTheRendering(t *testing.T) { in := aMesh(t) nodeOf(t, &in, "anchor").Account = "jochens" in.OperatorExport = &catalogue.KeptExport{} @@ -223,7 +223,7 @@ func TestAccountsNamesAndTheOperatorsExportReachTheRendering(t *testing.T) { // The names the operator gave to peers of an adopted tunnel answer until they enrol (novox/hq issue 112); a node of the mesh owns // its name. -func TestACarriedPeerIsNamedUntilItEnrols(t *testing.T) { +func testACarriedPeerIsNamedUntilItEnrols(t *testing.T) { in := aMesh(t) in.CarriedPeers = []CarriedPeer{{PublicKey: "K1", Address: "192.0.2.5", Named: "printer"}, {PublicKey: "K2", Address: "192.0.2.6", Named: "laptop"}, {PublicKey: "K3", Address: "192.0.2.7", Named: "late", EnrolledAs: "late"}} @@ -234,7 +234,7 @@ func TestACarriedPeerIsNamedUntilItEnrols(t *testing.T) { } // A node-engine older than a contract is not sent the field it would refuse (novox/hq ADR 0240 and after). -func TestTheNodeEnginesContractGatesWhatItIsSent(t *testing.T) { +func testTheNodeEnginesContractGatesWhatItIsSent(t *testing.T) { in := aMesh(t) laptop := nodeOf(t, &in, "laptop") if r := placed(t, in, "laptop").Rendering; r.ReadsHealth || r.JudgesRoot || r.ReadsBusy || r.Hands { @@ -252,7 +252,7 @@ func TestTheNodeEnginesContractGatesWhatItIsSent(t *testing.T) { // The artifact store as a node reaches it: over the private network by its holder's name and the port it put it on, or on loopback // for the holder alone while nothing is on the network (novox/hq 04-ISSUES/102). -func TestTheArtifactStoreIsReachedOverTheNetworkOrOnLoopbackForItsHolder(t *testing.T) { +func testTheArtifactStoreIsReachedOverTheNetworkOrOnLoopbackForItsHolder(t *testing.T) { in := aMesh(t) in.Catalogue["artifacts"] = catalogue.Manifest{Module: "artifacts", Version: "1", Claims: []catalogue.Claim{{Name: "container-image-registry", Scope: catalogue.ScopeMesh}}, @@ -295,7 +295,7 @@ func TestTheArtifactStoreIsReachedOverTheNetworkOrOnLoopbackForItsHolder(t *test // The store's address is the image seat's holder's listen open to the mesh, on the port its node put it on, and every // name of the store answers it (novox/hq ADR 0632 §1): a module serving the retired provision artifact-store is no store, // and a holder opening two listens to the mesh says which is the store by no guess. -func TestTheStoreIsFoundByTheImageSeatsHolderAndItsListen(t *testing.T) { +func testTheStoreIsFoundByTheImageSeatsHolderAndItsListen(t *testing.T) { in := aMesh(t) in.Catalogue["old"] = catalogue.Manifest{Module: "old", Version: "1", Serves: map[string]map[string]any{catalogue.ArtifactStoreProvision: {"port": 5100}}} @@ -409,7 +409,7 @@ func TestTheStoreIsFoundByTheImageSeatsHolderAndItsListen(t *testing.T) { // A zone a module declares is placed where the mesh put it: settled from that node's settings, at the node's private address, on // the port the answering listen is published on there (novox/hq ADR 0199); the same zone declared twice is refused, by name. -func TestAZoneIsPlacedWhereTheMeshPutItAndTheSameZoneTwiceIsRefused(t *testing.T) { +func testAZoneIsPlacedWhereTheMeshPutItAndTheSameZoneTwiceIsRefused(t *testing.T) { in := aMesh(t) lab := catalogue.Manifest{Module: "lab", Version: "1", Zone: &catalogue.Zone{Name: "${setting:zone}", Listen: "dns"}, Listens: []catalogue.Listening{{Name: "dns", Port: 53, Protocol: "udp", From: catalogue.FromMesh}}} @@ -432,7 +432,7 @@ func TestAZoneIsPlacedWhereTheMeshPutItAndTheSameZoneTwiceIsRefused(t *testing.T // Every holder of a replicated seat is listed by internal name at its private address (novox/hq ADR 0223): the holders on record, // and only the sole claimant when there are none; a holder off the private network is left out. -func TestEveryHolderOfAReplicatedSeatIsListedOnTheNetwork(t *testing.T) { +func testEveryHolderOfAReplicatedSeatIsListedOnTheNetwork(t *testing.T) { in := aMesh(t) resolver := catalogue.Manifest{Module: "resolver", Version: "1", Provides: []catalogue.Offer{{Name: "wildcard-resolution", Scope: catalogue.ScopeMesh}}, @@ -460,3 +460,18 @@ func TestEveryHolderOfAReplicatedSeatIsListedOnTheNetwork(t *testing.T) { t.Errorf("a holder off the network is listed: %v", got) } } + +// TestRendering runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRendering(t *testing.T) { + t.Run("AnAllocatedPortIsComposedAndAnUnallocatedOneIsNamedForeseenNotInvented", testAnAllocatedPortIsComposedAndAnUnallocatedOneIsNamedForeseenNotInvented) + t.Run("APortTheOperatorGaveIsUsedAndNotReallocated", testAPortTheOperatorGaveIsUsedAndNotReallocated) + t.Run("SeatsHeldAndTakenReachTheRendering", testSeatsHeldAndTakenReachTheRendering) + t.Run("LocalNetworksAndOutwardLinksReachTheRendering", testLocalNetworksAndOutwardLinksReachTheRendering) + t.Run("AccountsNamesAndTheOperatorsExportReachTheRendering", testAccountsNamesAndTheOperatorsExportReachTheRendering) + t.Run("ACarriedPeerIsNamedUntilItEnrols", testACarriedPeerIsNamedUntilItEnrols) + t.Run("TheNodeEnginesContractGatesWhatItIsSent", testTheNodeEnginesContractGatesWhatItIsSent) + t.Run("TheArtifactStoreIsReachedOverTheNetworkOrOnLoopbackForItsHolder", testTheArtifactStoreIsReachedOverTheNetworkOrOnLoopbackForItsHolder) + t.Run("TheStoreIsFoundByTheImageSeatsHolderAndItsListen", testTheStoreIsFoundByTheImageSeatsHolderAndItsListen) + t.Run("AZoneIsPlacedWhereTheMeshPutItAndTheSameZoneTwiceIsRefused", testAZoneIsPlacedWhereTheMeshPutItAndTheSameZoneTwiceIsRefused) + t.Run("EveryHolderOfAReplicatedSeatIsListedOnTheNetwork", testEveryHolderOfAReplicatedSeatIsListedOnTheNetwork) +} diff --git a/internal/compose/resolution/accesses_test.go b/internal/compose/resolution/accesses_test.go index 5bfc9f3e..a40ff30e 100644 --- a/internal/compose/resolution/accesses_test.go +++ b/internal/compose/resolution/accesses_test.go @@ -15,7 +15,7 @@ import ( // Declared as accesses to an operator-owned path (novox/hq ADR 0051), they co-resolve. An access // is not a resource and never enters the duplicate-owner map, so this is the exact case the // resolver refuses above when the same path is owned — and does not, when it is merely accessed. -func TestTwoModulesAccessingOnePathCoResolve(t *testing.T) { +func testTwoModulesAccessingOnePathCoResolve(t *testing.T) { a := mod("a", nil, nil, nil) a.Accesses = []mcat.Access{{Path: "/services/media/downloads", Mode: mcat.AccessReadWrite}} b := mod("b", nil, nil, nil) @@ -41,7 +41,7 @@ func TestTwoModulesAccessingOnePathCoResolve(t *testing.T) { // The mirror of the case above, so the sharing vocabulary does not weaken the rule it sits beside: // two modules OWNING one path is still refused, exactly as before accesses existed. -func TestTwoModulesOwningOnePathAreStillRefused(t *testing.T) { +func testTwoModulesOwningOnePathAreStillRefused(t *testing.T) { a := mod("a", nil, nil, nil) a.Resources = []map[string]any{ {"id": "lib", "type": "directory", "path": "/services/media/movies", "mode": "0755"}} @@ -62,7 +62,7 @@ func TestTwoModulesOwningOnePathAreStillRefused(t *testing.T) { // another module was told to expect the operator to provide would create and chown it — and the // two intentions cannot both hold, so it is refused by name. This is what keeps the distinction // machine-checkable rather than a convention nobody enforces. -func TestAModuleMayNotOwnWhatAnotherAccesses(t *testing.T) { +func testAModuleMayNotOwnWhatAnotherAccesses(t *testing.T) { owns := mod("owns", nil, nil, nil) owns.Resources = []map[string]any{ {"id": "lib", "type": "directory", "path": "/services/media/movies", "mode": "0755"}} @@ -78,3 +78,10 @@ func TestAModuleMayNotOwnWhatAnotherAccesses(t *testing.T) { t.Errorf("the refusal does not explain the ownership conflict: %v", err) } } + +// TestAccesses runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestAccesses(t *testing.T) { + t.Run("TwoModulesAccessingOnePathCoResolve", testTwoModulesAccessingOnePathCoResolve) + t.Run("TwoModulesOwningOnePathAreStillRefused", testTwoModulesOwningOnePathAreStillRefused) + t.Run("AModuleMayNotOwnWhatAnotherAccesses", testAModuleMayNotOwnWhatAnotherAccesses) +} diff --git a/internal/compose/resolution/adoption_test.go b/internal/compose/resolution/adoption_test.go index d7048840..c1a52cbc 100644 --- a/internal/compose/resolution/adoption_test.go +++ b/internal/compose/resolution/adoption_test.go @@ -76,7 +76,7 @@ func byID(resources []map[string]any) map[string]map[string]any { return out } -func TestAnAdoptedNodeIsDeclaredOpeningsFromTheSameInputsAsTheFilter(t *testing.T) { +func testAnAdoptedNodeIsDeclaredOpeningsFromTheSameInputsAsTheFilter(t *testing.T) { composed, err := Compose(anAdoptedAnchor(), anchorRendering(true)) if err != nil { t.Fatal(err) @@ -134,7 +134,7 @@ func TestAnAdoptedNodeIsDeclaredOpeningsFromTheSameInputsAsTheFilter(t *testing. } } -func TestAnAdoptedNodeLoadsNoFilterOfTheMeshs(t *testing.T) { +func testAnAdoptedNodeLoadsNoFilterOfTheMeshs(t *testing.T) { composed, err := Compose(anAdoptedAnchor(), anchorRendering(true)) if err != nil { t.Fatal(err) @@ -193,7 +193,7 @@ func TestAnAdoptedNodeLoadsNoFilterOfTheMeshs(t *testing.T) { } } -func TestAConvergedNodeIsDeclaredItsFilterAndNoOpenings(t *testing.T) { +func testAConvergedNodeIsDeclaredItsFilterAndNoOpenings(t *testing.T) { composed, err := Compose(anAdoptedAnchor(), anchorRendering(false)) if err != nil { t.Fatal(err) @@ -219,7 +219,7 @@ func TestAConvergedNodeIsDeclaredItsFilterAndNoOpenings(t *testing.T) { } // The table the installer raises and the controller declares, character for character. -func TestTheGuardIsExactlyThisTable(t *testing.T) { +func testTheGuardIsExactlyThisTable(t *testing.T) { const golden = `table inet mesh_guard {} delete table inet mesh_guard table inet mesh_guard { @@ -263,7 +263,7 @@ func keys[V any](m map[string]V) []string { // novox/hq ADR 0100: the foundation's ports are the node's. Given 5433 for the store, every place // that uses the port reads it from there: the container, the filter, the openings, the guard. -func TestAGivenPortIsUsedEverywhereThePortIs(t *testing.T) { +func testAGivenPortIsUsedEverywhereThePortIs(t *testing.T) { given := map[string]map[int]int{"postgres": {5432: 5433}, "lavinmq": {15672: 15673}} for _, adopted := range []bool{true, false} { with := anchorRendering(adopted) @@ -301,7 +301,7 @@ func TestAGivenPortIsUsedEverywhereThePortIs(t *testing.T) { // module publishes that the filter admits from the private network only, and the ports its // manifest guards. A module assigned but not taken is not guarded: its port may still be the // predecessor's. -func TestTheGuardIsDerivedFromTakenModulesOnly(t *testing.T) { +func testTheGuardIsDerivedFromTakenModulesOnly(t *testing.T) { guardOf := func(with mcat.Rendering) string { t.Helper() composed, err := Compose(anAdoptedAnchor(), with) @@ -351,7 +351,7 @@ func TestTheGuardIsDerivedFromTakenModulesOnly(t *testing.T) { // novox/hq ADR 0038: only a published port is the mesh's to move. A module that binds the machine // itself listens where its software was told to, so giving it a machine port is refused. -func TestAGivenPortIsRefusedForAPortNoContainerPublishes(t *testing.T) { +func testAGivenPortIsRefusedForAPortNoContainerPublishes(t *testing.T) { onTheMachine := mcat.Manifest{Module: "daemon", Listens: []mcat.Listening{{Port: 9000, From: mcat.FromMesh}}, Guards: []int{9000}} layers := []mcat.Layer{{From: "node anchor", @@ -364,7 +364,7 @@ func TestAGivenPortIsRefusedForAPortNoContainerPublishes(t *testing.T) { // novox/hq ADR 0103: a guarded port this node is told to open to everyone is opened, not guarded. // An opening from everywhere beside a guard dropping it is one statement refusing the other. -func TestAGuardedPortOpenedToEveryoneIsNotGuarded(t *testing.T) { +func testAGuardedPortOpenedToEveryoneIsNotGuarded(t *testing.T) { with := anchorRendering(true) with.Settings["postgres"] = []mcat.Layer{{From: "node anchor", Placement: map[string]any{mcat.ExposeSetting: map[string]any{"5432": mcat.FromEverywhere}}}} @@ -420,7 +420,7 @@ func portsAsThePlanWould(m mcat.Manifest, given map[int]int) map[int]int { // novox/hq ADR 0100 and 0038: the machine side of a long-form mapping is a port the module // publishes, so a node may move it — and a module may name a mapping by either end. -func TestAGivenPortNamesEitherEndOfWhatTheModulePublishes(t *testing.T) { +func testAGivenPortNamesEitherEndOfWhatTheModulePublishes(t *testing.T) { forge := aForge() node := func(v any) []mcat.Layer { return []mcat.Layer{{From: "node anchor", Placement: map[string]any{mcat.PortsSetting: v}}} @@ -516,7 +516,7 @@ func TestAGivenPortNamesEitherEndOfWhatTheModulePublishes(t *testing.T) { // And the number reaches everything derived from it. The fault this is written against moved the // container's mapping alone: the filter opened the port the software had left, the adopted node's // opening named it too, the guard refused it, and a consumer was sent to it. -func TestAGivenMachineSideReachesTheFilterTheOpeningAndTheConsumer(t *testing.T) { +func testAGivenMachineSideReachesTheFilterTheOpeningAndTheConsumer(t *testing.T) { forge := aForge() given, err := GivenPorts(forge, []mcat.Layer{{From: "node anchor", Placement: map[string]any{mcat.PortsSetting: map[string]any{"2222": float64(222)}}}}) @@ -587,7 +587,7 @@ func TestAGivenMachineSideReachesTheFilterTheOpeningAndTheConsumer(t *testing.T) // And the mapping itself moves under either name, because Rendering.Given is a map anybody // composing a declaration hands in: keyed by the machine side, which is what a module declaring // 2222 calls its port, only the outside moves and the container's own port stays as written. -func TestAMappingIsMovedUnderEitherOfItsNames(t *testing.T) { +func testAMappingIsMovedUnderEitherOfItsNames(t *testing.T) { for _, c := range []struct { written string given map[int]int @@ -608,7 +608,7 @@ func TestAMappingIsMovedUnderEitherOfItsNames(t *testing.T) { // The same on a node that was given nothing, which is where the derivation was never at fault: // a long-form mapping is published where the manifest put it, and an adopted node opens that port // on the forwarded path like any other. What broke it was the number reaching only the mapping. -func TestALongFormPortIsOpenedWhereTheManifestPublishesIt(t *testing.T) { +func testALongFormPortIsOpenedWhereTheManifestPublishesIt(t *testing.T) { forge := aForge() r := mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{forge}} composed, err := Compose(r, mcat.Rendering{ @@ -627,3 +627,19 @@ func TestALongFormPortIsOpenedWhereTheManifestPublishesIt(t *testing.T) { t.Fatalf("no opening for the forge's published ssh port: %v", keys(got)) } } + +// TestAdoption runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestAdoption(t *testing.T) { + t.Run("AnAdoptedNodeIsDeclaredOpeningsFromTheSameInputsAsTheFilter", testAnAdoptedNodeIsDeclaredOpeningsFromTheSameInputsAsTheFilter) + t.Run("AnAdoptedNodeLoadsNoFilterOfTheMeshs", testAnAdoptedNodeLoadsNoFilterOfTheMeshs) + t.Run("AConvergedNodeIsDeclaredItsFilterAndNoOpenings", testAConvergedNodeIsDeclaredItsFilterAndNoOpenings) + t.Run("TheGuardIsExactlyThisTable", testTheGuardIsExactlyThisTable) + t.Run("AGivenPortIsUsedEverywhereThePortIs", testAGivenPortIsUsedEverywhereThePortIs) + t.Run("TheGuardIsDerivedFromTakenModulesOnly", testTheGuardIsDerivedFromTakenModulesOnly) + t.Run("AGivenPortIsRefusedForAPortNoContainerPublishes", testAGivenPortIsRefusedForAPortNoContainerPublishes) + t.Run("AGuardedPortOpenedToEveryoneIsNotGuarded", testAGuardedPortOpenedToEveryoneIsNotGuarded) + t.Run("AGivenPortNamesEitherEndOfWhatTheModulePublishes", testAGivenPortNamesEitherEndOfWhatTheModulePublishes) + t.Run("AGivenMachineSideReachesTheFilterTheOpeningAndTheConsumer", testAGivenMachineSideReachesTheFilterTheOpeningAndTheConsumer) + t.Run("AMappingIsMovedUnderEitherOfItsNames", testAMappingIsMovedUnderEitherOfItsNames) + t.Run("ALongFormPortIsOpenedWhereTheManifestPublishesIt", testALongFormPortIsOpenedWhereTheManifestPublishesIt) +} diff --git a/internal/compose/resolution/agent_account_test.go b/internal/compose/resolution/agent_account_test.go index a54e6282..d549e2c2 100644 --- a/internal/compose/resolution/agent_account_test.go +++ b/internal/compose/resolution/agent_account_test.go @@ -6,7 +6,7 @@ import ( mcat "git.novox.be/novox/mesh-sdk/go/catalogue" ) -func TestTheAgentAccountFactFallsBackToTheOperatorAndIsNeverRootOnlyWhenItsOwn(t *testing.T) { +func testTheAgentAccountFactFallsBackToTheOperatorAndIsNeverRootOnlyWhenItsOwn(t *testing.T) { facts := machineFacts(mcat.Resolution{Node: "anchor", Account: "ops"}, nil, "") if facts["agent-account"] != "ops" || facts["agent-home"] != "/home/ops" || facts["agent-root"] != "" { t.Errorf("with no agent account named, agents run as the operator: %v", facts) @@ -40,7 +40,7 @@ const agentModule = `{"module": "agent", "version": "1", "resources": [ "owner": "${machine:agent-account}"} ]}` -func TestTheAgentAccountIsDeclaredNeverRootOnlyToAnEngineThatJudgesIt(t *testing.T) { +func testTheAgentAccountIsDeclaredNeverRootOnlyToAnEngineThatJudgesIt(t *testing.T) { m, err := decodeForTest([]byte(agentModule)) if err != nil { t.Fatal(err) @@ -81,3 +81,9 @@ func TestTheAgentAccountIsDeclaredNeverRootOnlyToAnEngineThatJudgesIt(t *testing t.Errorf("with no agent account, the agent's directory is the operator's: %v", home) } } + +// TestAgentAccount runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestAgentAccount(t *testing.T) { + t.Run("TheAgentAccountFactFallsBackToTheOperatorAndIsNeverRootOnlyWhenItsOwn", testTheAgentAccountFactFallsBackToTheOperatorAndIsNeverRootOnlyWhenItsOwn) + t.Run("TheAgentAccountIsDeclaredNeverRootOnlyToAnEngineThatJudgesIt", testTheAgentAccountIsDeclaredNeverRootOnlyToAnEngineThatJudgesIt) +} diff --git a/internal/compose/resolution/artifacts_test.go b/internal/compose/resolution/artifacts_test.go index a43e0837..7f62477b 100644 --- a/internal/compose/resolution/artifacts_test.go +++ b/internal/compose/resolution/artifacts_test.go @@ -10,7 +10,7 @@ import ( var digest = "sha256:" + strings.Repeat("d", 64) // **The address is composed into a declaration, and the record never carries it.** -func TestAnImageTheMeshBuiltIsRoutedThroughTheStoreWhenDeclared(t *testing.T) { +func testAnImageTheMeshBuiltIsRoutedThroughTheStoreWhenDeclared(t *testing.T) { m := mcat.Manifest{Module: "gitea", Version: "1", Resources: []map[string]any{ {"id": "server", "type": "container", "name": "mesh-gitea", "artifact": "server"}, {"id": "config", "type": "archive", "path": "/etc/gitea", "artifact": "config"}, @@ -95,7 +95,7 @@ func TestAnImageTheMeshBuiltIsRoutedThroughTheStoreWhenDeclared(t *testing.T) { } } -func TestAnImageInTheStoreWithNoStoreToFetchItFromIsRefused(t *testing.T) { +func testAnImageInTheStoreWithNoStoreToFetchItFromIsRefused(t *testing.T) { m := mcat.Manifest{Module: "gitea", Version: "1", Resources: []map[string]any{ {"id": "server", "type": "container", "name": "mesh-gitea", "image": mcat.ArtifactStoreScheme + "gitea/server@" + digest}, @@ -109,7 +109,7 @@ func TestAnImageInTheStoreWithNoStoreToFetchItFromIsRefused(t *testing.T) { // **A reference recorded with an address before this follows the store too** — when the mesh // built it. A module running an image straight from a public registry under its own name is left // exactly where it says: `quay.io/keycloak/keycloak` is not the mesh's, whatever it is called. -func TestAReferenceRecordedWithAnAddressFollowsTheStoreWhenTheMeshBuiltIt(t *testing.T) { +func testAReferenceRecordedWithAnAddressFollowsTheStoreWhenTheMeshBuiltIt(t *testing.T) { m := mcat.Manifest{Module: "keycloak", Version: "1", Resources: []map[string]any{ {"id": "server", "type": "container", "name": "mesh-keycloak", "image": "anchor.internal:5100/keycloak/server@" + digest}, @@ -139,3 +139,10 @@ func TestAReferenceRecordedWithAnAddressFollowsTheStoreWhenTheMeshBuiltIt(t *tes t.Errorf("with no build record, a reference was rewritten: %v", got) } } + +// TestArtifacts runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestArtifacts(t *testing.T) { + t.Run("AnImageTheMeshBuiltIsRoutedThroughTheStoreWhenDeclared", testAnImageTheMeshBuiltIsRoutedThroughTheStoreWhenDeclared) + t.Run("AnImageInTheStoreWithNoStoreToFetchItFromIsRefused", testAnImageInTheStoreWithNoStoreToFetchItFromIsRefused) + t.Run("AReferenceRecordedWithAnAddressFollowsTheStoreWhenTheMeshBuiltIt", testAReferenceRecordedWithAnAddressFollowsTheStoreWhenTheMeshBuiltIt) +} diff --git a/internal/compose/resolution/backup_placement_test.go b/internal/compose/resolution/backup_placement_test.go index 9035fc19..d7b77b6d 100644 --- a/internal/compose/resolution/backup_placement_test.go +++ b/internal/compose/resolution/backup_placement_test.go @@ -50,7 +50,7 @@ func gammaLeftOut(with mcat.Rendering) mcat.Rendering { return with } -func TestTheBackupPlacementIsTheTextTheOldPlaceholdersRender(t *testing.T) { +func testTheBackupPlacementIsTheTextTheOldPlaceholdersRender(t *testing.T) { // The old form is an unmoved holder: its placeholders are the controller's alone. oldHolder := strings.Replace(backupHolder, `"moved":true,`, "", 1) all := []mcat.Manifest{held(t, oldHolder, builtWith("restic", map[string]string{"backups": oldBackupText, "data": oldDataText}))} @@ -88,7 +88,7 @@ func TestTheBackupPlacementIsTheTextTheOldPlaceholdersRender(t *testing.T) { } } -func TestAnUnknownBackupKeyIsRefused(t *testing.T) { +func testAnUnknownBackupKeyIsRefused(t *testing.T) { r := backupsOn(t, "${backup:rows}", placedDataTxt, backupModules...) if _, err := Compose(r, handingTo("store:5000")); err == nil || !strings.Contains(err.Error(), "backup:rows") { t.Errorf("handed, an unknown key is %v", err) @@ -112,3 +112,9 @@ func fileOf(t *testing.T, r mcat.Resolution, with mcat.Rendering, id string) str t.Fatalf("%s was not composed", id) return "" } + +// TestBackupPlacement runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBackupPlacement(t *testing.T) { + t.Run("TheBackupPlacementIsTheTextTheOldPlaceholdersRender", testTheBackupPlacementIsTheTextTheOldPlaceholdersRender) + t.Run("AnUnknownBackupKeyIsRefused", testAnUnknownBackupKeyIsRefused) +} diff --git a/internal/compose/resolution/bound_into_files_test.go b/internal/compose/resolution/bound_into_files_test.go index 0da5176f..169f652f 100644 --- a/internal/compose/resolution/bound_into_files_test.go +++ b/internal/compose/resolution/bound_into_files_test.go @@ -13,7 +13,7 @@ import ( // Everything needed for one now reaches the file that needs it: the address and port from what the // provider serves, the name to present from what the mesh decided, the database name from what the // module itself contributed, and the password through the sealed hole the host fills. -func TestAConsumerCanWriteAConnectionString(t *testing.T) { +func testAConsumerCanWriteAConnectionString(t *testing.T) { r := mcat.Resolution{ Node: "workstation", Modules: []mcat.Manifest{{ @@ -66,7 +66,7 @@ func TestAConsumerCanWriteAConnectionString(t *testing.T) { // provider is not published. Cross-node consumers already got this (the plan re-derives the served // facts with the provider's assignment); the same-node need was settled before the assignment and // carried the declared port until now. -func TestASameNodeProviderIsAnnouncedAtThePortItIsPublishedOn(t *testing.T) { +func testASameNodeProviderIsAnnouncedAtThePortItIsPublishedOn(t *testing.T) { provider := mcat.Manifest{ Module: "postgres", Version: "1", Provides: mcat.FromAnywhere("postgres-database"), @@ -121,7 +121,7 @@ func TestASameNodeProviderIsAnnouncedAtThePortItIsPublishedOn(t *testing.T) { // A port is 5432, not 5432.000000 — which is what a number decoded from JSON would write, and what // every connection string in the world would refuse. -func TestAPortIsWrittenAsAPort(t *testing.T) { +func testAPortIsWrittenAsAPort(t *testing.T) { if got := plainly(float64(5432)); got != "5432" { t.Errorf("a port was rendered as %q", got) } @@ -132,7 +132,7 @@ func TestAPortIsWrittenAsAPort(t *testing.T) { // The name the provider will create is the name the consumer is told to present. One derivation, // so the two agree by construction rather than by two conventions written on the same day. -func TestTheProviderAndTheConsumerAgreeOnTheName(t *testing.T) { +func testTheProviderAndTheConsumerAgreeOnTheName(t *testing.T) { provider, err := Resolve(shelf(mcat.Manifest{ Module: "postgres", Version: "1", Provides: mcat.FromAnywhere("postgres-database"), Grants: map[string]string{"postgres-database": "/var/lib/postgres/grants"}, @@ -167,7 +167,7 @@ func TestTheProviderAndTheConsumerAgreeOnTheName(t *testing.T) { } // A binding the module does not have is a typo, refused where it was written. -func TestAFileCannotNameABindingTheModuleDoesNotHave(t *testing.T) { +func testAFileCannotNameABindingTheModuleDoesNotHave(t *testing.T) { r := mcat.Resolution{ Node: "workstation", Modules: []mcat.Manifest{{ @@ -190,7 +190,7 @@ func TestAFileCannotNameABindingTheModuleDoesNotHave(t *testing.T) { // A key the provider does not serve is refused too. Written through, the literal placeholder // becomes a hostname, and the failure names neither the module nor the mesh. -func TestAKeyTheProviderDoesNotServeIsRefused(t *testing.T) { +func testAKeyTheProviderDoesNotServeIsRefused(t *testing.T) { r := mcat.Resolution{ Node: "workstation", Modules: []mcat.Manifest{{ @@ -217,7 +217,7 @@ func TestAKeyTheProviderDoesNotServeIsRefused(t *testing.T) { // A machine's resolver configuration must name its resolver by address — it cannot resolve the name // of the thing it resolves names with (novox/hq ADR 0194). So a binding offers the providing // machine's private address beside its name, and only when the machine has one. -func TestABindingOffersTheProvidersAddress(t *testing.T) { +func testABindingOffersTheProvidersAddress(t *testing.T) { consumer := func() mcat.Resolution { return mcat.Resolution{ Node: "workstation", @@ -244,3 +244,14 @@ func TestABindingOffersTheProvidersAddress(t *testing.T) { t.Fatal("a file naming an address the mesh does not have was composed") } } + +// TestBoundIntoFiles runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBoundIntoFiles(t *testing.T) { + t.Run("AConsumerCanWriteAConnectionString", testAConsumerCanWriteAConnectionString) + t.Run("ASameNodeProviderIsAnnouncedAtThePortItIsPublishedOn", testASameNodeProviderIsAnnouncedAtThePortItIsPublishedOn) + t.Run("APortIsWrittenAsAPort", testAPortIsWrittenAsAPort) + t.Run("TheProviderAndTheConsumerAgreeOnTheName", testTheProviderAndTheConsumerAgreeOnTheName) + t.Run("AFileCannotNameABindingTheModuleDoesNotHave", testAFileCannotNameABindingTheModuleDoesNotHave) + t.Run("AKeyTheProviderDoesNotServeIsRefused", testAKeyTheProviderDoesNotServeIsRefused) + t.Run("ABindingOffersTheProvidersAddress", testABindingOffersTheProvidersAddress) +} diff --git a/internal/compose/resolution/bound_test.go b/internal/compose/resolution/bound_test.go index 98df9cbb..e1f30fe6 100644 --- a/internal/compose/resolution/bound_test.go +++ b/internal/compose/resolution/bound_test.go @@ -65,7 +65,7 @@ func boundFrom(t *testing.T, r mcat.Resolution, consumer, provision string) mcat return mcat.Needed{} } -func TestTheIncidentAMachinesOwnStoreKeepsItsConsumersWhenTheSeatIsHeldElsewhere(t *testing.T) { +func testTheIncidentAMachinesOwnStoreKeepsItsConsumersWhenTheSeatIsHeldElsewhere(t *testing.T) { got, err := Resolve(storeMesh(), homeAssigned(), home, storeWorld()) if err != nil { t.Fatal(err) @@ -84,7 +84,7 @@ func TestTheIncidentAMachinesOwnStoreKeepsItsConsumersWhenTheSeatIsHeldElsewhere } } -func TestTheIncidentWithEveryConsumerOnRecordStillMovesNothing(t *testing.T) { +func testTheIncidentWithEveryConsumerOnRecordStillMovesNothing(t *testing.T) { w := storeWorld() w.Bound = map[string]map[string]mcat.Chosen{} for _, c := range incidentConsumers { @@ -104,7 +104,7 @@ func TestTheIncidentWithEveryConsumerOnRecordStillMovesNothing(t *testing.T) { } } -func TestAPinElsewhereStillMovesAStoresConsumers(t *testing.T) { +func testAPinElsewhereStillMovesAStoresConsumers(t *testing.T) { w := storeWorld() w.Pinned = map[string]mcat.Chosen{"postgres-database": {Node: "anchor", Module: "store"}} w.Bound = map[string]map[string]mcat.Chosen{"board": {"postgres-database": {Node: "home", Module: "store"}}} @@ -131,7 +131,7 @@ func laptopWorld(holder string) mcat.World { var laptop = mcat.Node{Name: "laptop", At: "laptop.internal"} -func TestABoundConsumerStaysWhenTheSeatsHolderChanges(t *testing.T) { +func testABoundConsumerStaysWhenTheSeatsHolderChanges(t *testing.T) { w := laptopWorld("home") w.Bound = map[string]map[string]mcat.Chosen{"board": {"postgres-database": {Node: "anchor", Module: "store"}}} got, err := Resolve(storeMesh(), []string{"board"}, laptop, w) @@ -166,7 +166,7 @@ func TestABoundConsumerStaysWhenTheSeatsHolderChanges(t *testing.T) { } } -func TestABoundConsumerWhoseProviderIsGoneIsRefusedNotMoved(t *testing.T) { +func testABoundConsumerWhoseProviderIsGoneIsRefusedNotMoved(t *testing.T) { w := laptopWorld("anchor") w.Offered["postgres-database"] = w.Offered["postgres-database"][:1] // only anchor's store is left w.Bound = map[string]map[string]mcat.Chosen{"board": {"postgres-database": {Node: "home", Module: "store"}}} @@ -182,7 +182,7 @@ func TestABoundConsumerWhoseProviderIsGoneIsRefusedNotMoved(t *testing.T) { } } -func TestAMachinesOwnStoreUnassignedRefusesItsBoundConsumers(t *testing.T) { +func testAMachinesOwnStoreUnassignedRefusesItsBoundConsumers(t *testing.T) { w := storeWorld() w.Bound = map[string]map[string]mcat.Chosen{"board": {"postgres-database": {Node: "home", Module: "store"}}} _, err := Resolve(storeMesh(), []string{"board"}, home, w) @@ -192,7 +192,7 @@ func TestAMachinesOwnStoreUnassignedRefusesItsBoundConsumers(t *testing.T) { } // The first pass asks only what a machine offers, and is never refused by a binding. -func TestTheFirstPassKeepsNoBinding(t *testing.T) { +func testTheFirstPassKeepsNoBinding(t *testing.T) { w := storeWorld() w.Unchecked = true w.Bound = map[string]map[string]mcat.Chosen{"board": {"postgres-database": {Node: "gone", Module: "store"}}} @@ -203,7 +203,7 @@ func TestTheFirstPassKeepsNoBinding(t *testing.T) { // An offer saying it keeps nothing is answered by the seat's holder as the resolver is, even where it // grants a credential. -func TestAStoreSayingItKeepsNothingFollowsTheSeat(t *testing.T) { +func testAStoreSayingItKeepsNothingFollowsTheSeat(t *testing.T) { shelf := storeMesh() no := false s := shelf["store"] @@ -217,3 +217,15 @@ func TestAStoreSayingItKeepsNothingFollowsTheSeat(t *testing.T) { t.Errorf("bound to %s; it keeps nothing, and the seat is held on anchor", n.From) } } + +// TestBound runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBound(t *testing.T) { + t.Run("TheIncidentAMachinesOwnStoreKeepsItsConsumersWhenTheSeatIsHeldElsewhere", testTheIncidentAMachinesOwnStoreKeepsItsConsumersWhenTheSeatIsHeldElsewhere) + t.Run("TheIncidentWithEveryConsumerOnRecordStillMovesNothing", testTheIncidentWithEveryConsumerOnRecordStillMovesNothing) + t.Run("APinElsewhereStillMovesAStoresConsumers", testAPinElsewhereStillMovesAStoresConsumers) + t.Run("ABoundConsumerStaysWhenTheSeatsHolderChanges", testABoundConsumerStaysWhenTheSeatsHolderChanges) + t.Run("ABoundConsumerWhoseProviderIsGoneIsRefusedNotMoved", testABoundConsumerWhoseProviderIsGoneIsRefusedNotMoved) + t.Run("AMachinesOwnStoreUnassignedRefusesItsBoundConsumers", testAMachinesOwnStoreUnassignedRefusesItsBoundConsumers) + t.Run("TheFirstPassKeepsNoBinding", testTheFirstPassKeepsNoBinding) + t.Run("AStoreSayingItKeepsNothingFollowsTheSeat", testAStoreSayingItKeepsNothingFollowsTheSeat) +} diff --git a/internal/compose/resolution/broker_seat_test.go b/internal/compose/resolution/broker_seat_test.go index 524f3905..e43c92b5 100644 --- a/internal/compose/resolution/broker_seat_test.go +++ b/internal/compose/resolution/broker_seat_test.go @@ -14,7 +14,7 @@ import ( // and the property that matters is that a second one anywhere is refused *when it is assigned*, // not discovered later as two servers holding different halves of the mesh's traffic. A second // bus is not a degraded mesh; it is two meshes that both believe they are the one. -func TestASecondMeshBusAnywhereIsRefusedByName(t *testing.T) { +func testASecondMeshBusAnywhereIsRefusedByName(t *testing.T) { nats := catalogueManifest(t, "nats") if _, err := Resolve(shelf(nats), []string{"nats"}, workstation(), mcat.World{}); err != nil { @@ -37,7 +37,7 @@ func TestASecondMeshBusAnywhereIsRefusedByName(t *testing.T) { // The seat is the server's role, not the product's name (novox/hq ADR 0079). A different // implementation of the bus claims the same seat, and the mesh refuses it for the same reason — // which is the property that lets the bus be replaced at all. -func TestTheSeatRefusesADifferentBusToo(t *testing.T) { +func testTheSeatRefusesADifferentBusToo(t *testing.T) { nats := catalogueManifest(t, "nats") held := mcat.World{Held: []mcat.Held{{Claim: "mesh-broker", Scope: mcat.ScopeMesh, Node: "anchor", Module: "some-other-broker"}}} @@ -47,3 +47,9 @@ func TestTheSeatRefusesADifferentBusToo(t *testing.T) { t.Fatal("the seat admitted a second holder because the module's name differed") } } + +// TestBrokerSeat runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBrokerSeat(t *testing.T) { + t.Run("ASecondMeshBusAnywhereIsRefusedByName", testASecondMeshBusAnywhereIsRefusedByName) + t.Run("TheSeatRefusesADifferentBusToo", testTheSeatRefusesADifferentBusToo) +} diff --git a/internal/compose/resolution/brokered_test.go b/internal/compose/resolution/brokered_test.go index 2932a084..38177261 100644 --- a/internal/compose/resolution/brokered_test.go +++ b/internal/compose/resolution/brokered_test.go @@ -29,7 +29,7 @@ func brokeredShelf() map[string]mcat.Manifest { return shelf(mcat.Manifest{Module: "postgres", Version: "1", Provides: mcat.FromAnywhere("postgres-database")}, mcat.Manifest{Module: "meshboard", Version: "1", Requires: []string{"postgres-database"}}) } -func TestADatabaseIsNotInstalledOnEveryMachineThatUsesOne(t *testing.T) { +func testADatabaseIsNotInstalledOnEveryMachineThatUsesOne(t *testing.T) { // The fault this whole distinction exists for. got, err := Resolve(brokeredShelf(), []string{"meshboard"}, reachable(), mcat.World{Offered: onNetwork("anchor")}) if err != nil { @@ -40,7 +40,7 @@ func TestADatabaseIsNotInstalledOnEveryMachineThatUsesOne(t *testing.T) { } } -func TestWhatAMachineTakesFromElsewhereIsRecorded(t *testing.T) { +func testWhatAMachineTakesFromElsewhereIsRecorded(t *testing.T) { // It is the only part of a node's set that stops working when a *different* machine goes // away, and it is where a credential will have to be handed back. got, err := Resolve(brokeredShelf(), []string{"meshboard"}, reachable(), mcat.World{Offered: onNetwork("anchor")}) @@ -58,7 +58,7 @@ func TestWhatAMachineTakesFromElsewhereIsRecorded(t *testing.T) { } } -func TestNothingInTheMeshProvidingItIsRefusedWithSomewhereToPutIt(t *testing.T) { +func testNothingInTheMeshProvidingItIsRefusedWithSomewhereToPutIt(t *testing.T) { // Refused rather than installed here. Choosing a machine to put a database on is a decision // with consequences, and nothing resolving a web application should make it silently. _, err := Resolve(brokeredShelf(), []string{"meshboard"}, workstation(), mcat.World{}) @@ -70,7 +70,7 @@ func TestNothingInTheMeshProvidingItIsRefusedWithSomewhereToPutIt(t *testing.T) } } -func TestTwoNodesProvidingItIsRefusedRatherThanPicked(t *testing.T) { +func testTwoNodesProvidingItIsRefusedRatherThanPicked(t *testing.T) { // Same rule as everywhere else. Picking one would be a guess about which database a person // meant, and the wrong guess is somebody's data in the wrong place. _, err := Resolve(brokeredShelf(), []string{"meshboard"}, reachable(), mcat.World{Offered: onNetwork("anchor", "archive")}) @@ -84,7 +84,7 @@ func TestTwoNodesProvidingItIsRefusedRatherThanPicked(t *testing.T) { } } -func TestSayingWhichOneSettlesIt(t *testing.T) { +func testSayingWhichOneSettlesIt(t *testing.T) { got, err := Resolve(brokeredShelf(), []string{"meshboard"}, reachable(), mcat.World{ Offered: onNetwork("anchor", "archive"), Pinned: map[string]mcat.Chosen{"postgres-database": {Node: "archive", Module: "postgres"}}, @@ -97,7 +97,7 @@ func TestSayingWhichOneSettlesIt(t *testing.T) { } } -func TestBeingPointedAtAMachineThatDoesNotProvideItIsRefused(t *testing.T) { +func testBeingPointedAtAMachineThatDoesNotProvideItIsRefused(t *testing.T) { // Rather than falling back to one that does. A fallback would quietly move somebody's data to // a machine they did not choose, which is the whole reason the question is asked. _, err := Resolve(brokeredShelf(), []string{"meshboard"}, reachable(), mcat.World{ @@ -112,7 +112,7 @@ func TestBeingPointedAtAMachineThatDoesNotProvideItIsRefused(t *testing.T) { } } -func TestOneProviderDoesNotOverruleAChoice(t *testing.T) { +func testOneProviderDoesNotOverruleAChoice(t *testing.T) { // A single answer is normally taken silently. Not when somebody said they wanted a different // one -- that is the mesh overruling a person, which it does nowhere else. _, err := Resolve(brokeredShelf(), []string{"meshboard"}, reachable(), mcat.World{ @@ -127,7 +127,7 @@ func TestOneProviderDoesNotOverruleAChoice(t *testing.T) { } } -func TestACatalogueThatDisagreesAboutScopeIsRefused(t *testing.T) { +func testACatalogueThatDisagreesAboutScopeIsRefused(t *testing.T) { // If one module says a database is local and another says it is anywhere, the same // requirement means two things depending on which one happens to answer it. _, err := Resolve(shelf(mcat.Manifest{Module: "postgres", Version: "1", Provides: mcat.FromAnywhere("postgres-database")}, mcat.Manifest{Module: "sqlite", Version: "1", Provides: mcat.Offers("postgres-database")}, mcat.Manifest{Module: "meshboard", Version: "1", Requires: []string{"postgres-database"}}), []string{"meshboard"}, workstation(), mcat.World{}) @@ -139,7 +139,7 @@ func TestACatalogueThatDisagreesAboutScopeIsRefused(t *testing.T) { } } -func TestALocalRequirementIsStillAnsweredLocally(t *testing.T) { +func testALocalRequirementIsStillAnsweredLocally(t *testing.T) { // The change must not have made everything brokered. A shell is still installed here. got, err := Resolve(shelf(mcat.Manifest{Module: "zsh", Version: "1", Provides: mcat.Offers("shell")}, mcat.Manifest{Module: "tools", Version: "1", Requires: []string{"shell"}}), []string{"tools"}, workstation(), mcat.World{}) if err != nil { @@ -173,7 +173,7 @@ func binding(t *testing.T, out []map[string]any) map[string]any { return nil } -func TestAnAppIsToldWhereItsDatabaseIs(t *testing.T) { +func testAnAppIsToldWhereItsDatabaseIs(t *testing.T) { // Knowing it needs the anchor's database is useless to the program that needs it unless the // program is told. This is the whole point of the field. got, err := Resolve(boundShelf(), []string{"meshboard"}, reachable(), mcat.World{Offered: map[string][]mcat.Provider{"postgres-database": {{Node: "anchor", At: "anchor.internal", @@ -191,7 +191,7 @@ func TestAnAppIsToldWhereItsDatabaseIs(t *testing.T) { } } -func TestItSaysWhereTheCredentialIsInstead(t *testing.T) { +func testItSaysWhereTheCredentialIsInstead(t *testing.T) { // A missing field looks like a bug; a stated absence looks like a boundary. Somebody wiring // this up must not spend an afternoon looking for the password field. // @@ -211,7 +211,7 @@ func TestItSaysWhereTheCredentialIsInstead(t *testing.T) { } } -func TestTwoMachinesThatCannotReachEachOtherAreRefused(t *testing.T) { +func testTwoMachinesThatCannotReachEachOtherAreRefused(t *testing.T) { // An app on one machine and a database on another that share no private network is a mesh // that reports itself configured and does not work. Said here rather than discovered as a // connection timing out. @@ -228,7 +228,7 @@ func TestTwoMachinesThatCannotReachEachOtherAreRefused(t *testing.T) { } } -func TestTheProviderBeingOffTheNetworkIsAlsoRefused(t *testing.T) { +func testTheProviderBeingOffTheNetworkIsAlsoRefused(t *testing.T) { // Both directions, because the failure is identical from either end and the remedy differs. _, err := Resolve(boundShelf(), []string{"meshboard"}, reachable(), mcat.World{Offered: map[string][]mcat.Provider{"postgres-database": {{Node: "anchor"}}}}) if err == nil { @@ -239,7 +239,7 @@ func TestTheProviderBeingOffTheNetworkIsAlsoRefused(t *testing.T) { } } -func TestBindingSomethingAnsweredHereWritesNothing(t *testing.T) { +func testBindingSomethingAnsweredHereWritesNothing(t *testing.T) { // A file saying "it is on this node" is a fact nobody needs and one more thing to keep true. got, err := Resolve(shelf(mcat.Manifest{Module: "zsh", Version: "1", Provides: mcat.Offers("shell")}, mcat.Manifest{Module: "tools", Version: "1", Requires: []string{"shell"}, Binds: map[string]string{"shell": "/etc/tools/shell.json"}}, @@ -253,3 +253,21 @@ func TestBindingSomethingAnsweredHereWritesNothing(t *testing.T) { } } } + +// TestBrokered runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBrokered(t *testing.T) { + t.Run("ADatabaseIsNotInstalledOnEveryMachineThatUsesOne", testADatabaseIsNotInstalledOnEveryMachineThatUsesOne) + t.Run("WhatAMachineTakesFromElsewhereIsRecorded", testWhatAMachineTakesFromElsewhereIsRecorded) + t.Run("NothingInTheMeshProvidingItIsRefusedWithSomewhereToPutIt", testNothingInTheMeshProvidingItIsRefusedWithSomewhereToPutIt) + t.Run("TwoNodesProvidingItIsRefusedRatherThanPicked", testTwoNodesProvidingItIsRefusedRatherThanPicked) + t.Run("SayingWhichOneSettlesIt", testSayingWhichOneSettlesIt) + t.Run("BeingPointedAtAMachineThatDoesNotProvideItIsRefused", testBeingPointedAtAMachineThatDoesNotProvideItIsRefused) + t.Run("OneProviderDoesNotOverruleAChoice", testOneProviderDoesNotOverruleAChoice) + t.Run("ACatalogueThatDisagreesAboutScopeIsRefused", testACatalogueThatDisagreesAboutScopeIsRefused) + t.Run("ALocalRequirementIsStillAnsweredLocally", testALocalRequirementIsStillAnsweredLocally) + t.Run("AnAppIsToldWhereItsDatabaseIs", testAnAppIsToldWhereItsDatabaseIs) + t.Run("ItSaysWhereTheCredentialIsInstead", testItSaysWhereTheCredentialIsInstead) + t.Run("TwoMachinesThatCannotReachEachOtherAreRefused", testTwoMachinesThatCannotReachEachOtherAreRefused) + t.Run("TheProviderBeingOffTheNetworkIsAlsoRefused", testTheProviderBeingOffTheNetworkIsAlsoRefused) + t.Run("BindingSomethingAnsweredHereWritesNothing", testBindingSomethingAnsweredHereWritesNothing) +} diff --git a/internal/compose/resolution/bucket_shares_test.go b/internal/compose/resolution/bucket_shares_test.go index 4c5a2cc8..b84f2c67 100644 --- a/internal/compose/resolution/bucket_shares_test.go +++ b/internal/compose/resolution/bucket_shares_test.go @@ -46,7 +46,7 @@ func sharesOf(t *testing.T, values map[string]any) string { const sortedSharesJSON = `[{"methods":["get","put"],"to":"print-and-scan"},{"methods":["put"],"to":"seat:node-files"}]` // 1591/AC3: the values a consumer gives carry the shares sorted by `to`, remote (grant) and co-located alike. -func TestTheGrantCarriesTheSharesSorted(t *testing.T) { +func testTheGrantCarriesTheSharesSorted(t *testing.T) { m := mustParse(t, filesWithShares) remote := mcat.Resolution{Node: "laptop", Modules: []mcat.Manifest{m}} values, asks, err := ContributionsFrom(remote, "s3-bucket", "files", mcat.SettingsBy{}) @@ -88,7 +88,7 @@ func TestTheGrantCarriesTheSharesSorted(t *testing.T) { } // 1591/AC5: a consumer whose contributes to s3-bucket names `shares` itself is refused. -func TestAConsumerCannotContributeSharesItself(t *testing.T) { +func testAConsumerCannotContributeSharesItself(t *testing.T) { _, err := decodeForTest([]byte(`{"module":"files","version":"1", "contributes":{"s3-bucket":{"shares":"x"}}, "requires":[{"name":"s3-bucket","shares":[{"to":"a","methods":["get"]}]}]}`)) @@ -103,3 +103,9 @@ func TestAConsumerCannotContributeSharesItself(t *testing.T) { t.Error("a contributed `shares` reached the grant") } } + +// TestBucketShares runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestBucketShares(t *testing.T) { + t.Run("TheGrantCarriesTheSharesSorted", testTheGrantCarriesTheSharesSorted) + t.Run("AConsumerCannotContributeSharesItself", testAConsumerCannotContributeSharesItself) +} diff --git a/internal/compose/resolution/co_located_test.go b/internal/compose/resolution/co_located_test.go index 0b39a17b..d7349040 100644 --- a/internal/compose/resolution/co_located_test.go +++ b/internal/compose/resolution/co_located_test.go @@ -77,7 +77,7 @@ func routeProxy() mcat.Manifest { // // The consequence is silent and total: route-proxy wrote an empty CA bundle, fell back to the // system trust store, could not verify the internal authority, and no certificate was ever issued. -func TestACoLocatedProvidersServedValuesReachItsConsumer(t *testing.T) { +func testACoLocatedProvidersServedValuesReachItsConsumer(t *testing.T) { r, err := Resolve(shelf(stepCAWithItsRoot(), routeProxy()), []string{"step-ca", "route-proxy"}, reachable(), mcat.World{}) if err != nil { @@ -105,7 +105,7 @@ func TestACoLocatedProvidersServedValuesReachItsConsumer(t *testing.T) { // And the binding file says the same thing, for a consumer that reads the binding rather than a // substituted placeholder. The two are one fact and must not be able to disagree. -func TestACoLocatedConsumersBindingCarriesTheSettledValues(t *testing.T) { +func testACoLocatedConsumersBindingCarriesTheSettledValues(t *testing.T) { r, err := Resolve(shelf(stepCAWithItsRoot(), routeProxy()), []string{"step-ca", "route-proxy"}, reachable(), mcat.World{}) if err != nil { @@ -147,7 +147,7 @@ func TestACoLocatedConsumersBindingCarriesTheSettledValues(t *testing.T) { // the time the requirement came up — so which path a co-located binding took depended on the order // a person happened to assign things in. Settling after the closure is known removes that: both // orders now produce the same file. -func TestACoLocatedProviderIsSettledWhicheverWayItWasPulledIn(t *testing.T) { +func testACoLocatedProviderIsSettledWhicheverWayItWasPulledIn(t *testing.T) { for _, assigned := range [][]string{ {"step-ca", "route-proxy"}, {"route-proxy", "step-ca"}, @@ -178,7 +178,7 @@ func TestACoLocatedProviderIsSettledWhicheverWayItWasPulledIn(t *testing.T) { // // The redirect uses the CONTRIBUTING module's assignment: the port belongs to the workload, and // using the provider's map would move it to wherever the proxy happens to be published. -func TestASameNodeContributionNamesThePortTheMachinePublishes(t *testing.T) { +func testASameNodeContributionNamesThePortTheMachinePublishes(t *testing.T) { gitea := mcat.Manifest{ Module: "gitea", Version: "1", Listens: []mcat.Listening{{Port: 3000, Protocol: "tcp", From: mcat.FromMesh}}, @@ -232,7 +232,7 @@ func TestASameNodeContributionNamesThePortTheMachinePublishes(t *testing.T) { // Its port belongs to that machine's assignment, which this node's map knows nothing about — // applying this node's map to it would move a remote workload's port to wherever a local module of // the same name happens to be published, which is worse than the fault being fixed. -func TestAContributionFromAnotherMachineKeepsItsOwnPort(t *testing.T) { +func testAContributionFromAnotherMachineKeepsItsOwnPort(t *testing.T) { r, err := Resolve(shelf(routeProxy(), stepCA()), []string{"route-proxy", "step-ca"}, reachable(), mcat.World{}) if err != nil { @@ -270,7 +270,7 @@ func TestAContributionFromAnotherMachineKeepsItsOwnPort(t *testing.T) { // consumer's declared port until the CONSUMER's machine's assignments are applied to it. The // declaration layer cannot do it — those assignments are not this machine's, which is the line the // test above holds — so the grant layer is handed them and does it there. -func TestAContributionIsRedirectedToWhereItsOwnMachinePublishedIt(t *testing.T) { +func testAContributionIsRedirectedToWhereItsOwnMachinePublishedIt(t *testing.T) { published := map[int]int{3000: 20000} got := AtPublishedPort(map[string]any{"name": "git.example.tld", "port": 3000}, "forge", published) @@ -304,3 +304,13 @@ func asStrings(v any) []string { } return out } + +// TestCoLocated runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestCoLocated(t *testing.T) { + t.Run("ACoLocatedProvidersServedValuesReachItsConsumer", testACoLocatedProvidersServedValuesReachItsConsumer) + t.Run("ACoLocatedConsumersBindingCarriesTheSettledValues", testACoLocatedConsumersBindingCarriesTheSettledValues) + t.Run("ACoLocatedProviderIsSettledWhicheverWayItWasPulledIn", testACoLocatedProviderIsSettledWhicheverWayItWasPulledIn) + t.Run("ASameNodeContributionNamesThePortTheMachinePublishes", testASameNodeContributionNamesThePortTheMachinePublishes) + t.Run("AContributionFromAnotherMachineKeepsItsOwnPort", testAContributionFromAnotherMachineKeepsItsOwnPort) + t.Run("AContributionIsRedirectedToWhereItsOwnMachinePublishedIt", testAContributionIsRedirectedToWhereItsOwnMachinePublishedIt) +} diff --git a/internal/compose/resolution/collections_bar_test.go b/internal/compose/resolution/collections_bar_test.go index c00debd2..2aa941c0 100644 --- a/internal/compose/resolution/collections_bar_test.go +++ b/internal/compose/resolution/collections_bar_test.go @@ -34,7 +34,7 @@ func collectedBarsOn(t *testing.T, caps map[string]bool) mcat.Resolution { return r } -func TestACollectorMayNameTheBarsBlocksAsACollectionAndNoOtherDataKind(t *testing.T) { +func testACollectorMayNameTheBarsBlocksAsACollectionAndNoOtherDataKind(t *testing.T) { bars := held(t, collectedBars, builtWith("bars", map[string]string{"bars": collectedBarsText})) if _, err := Compose(collectedBarsOn(t, nil), handingTo("store:5000")); err != nil { t.Fatalf("the handed collector is refused: %v", err) @@ -59,7 +59,7 @@ func TestACollectorMayNameTheBarsBlocksAsACollectionAndNoOtherDataKind(t *testin // composed before it, for a machine with neither capability, the battery, the power meter and both. Where the // collector is not handed the controller fills the files; where it is, it names the items for the client, which // fills the same files (mesh-catalog's provisioner client holds that half against the same golden files). -func TestTheBarsOfTheCatalogueAreTheSameHandedOrNot(t *testing.T) { +func testTheBarsOfTheCatalogueAreTheSameHandedOrNot(t *testing.T) { read := func(name string) string { b, err := os.ReadFile(filepath.Join("testdata", "bars", name)) if err != nil { @@ -108,3 +108,9 @@ func TestTheBarsOfTheCatalogueAreTheSameHandedOrNot(t *testing.T) { } } } + +// TestCollectionsBar runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestCollectionsBar(t *testing.T) { + t.Run("ACollectorMayNameTheBarsBlocksAsACollectionAndNoOtherDataKind", testACollectorMayNameTheBarsBlocksAsACollectionAndNoOtherDataKind) + t.Run("TheBarsOfTheCatalogueAreTheSameHandedOrNot", testTheBarsOfTheCatalogueAreTheSameHandedOrNot) +} diff --git a/internal/compose/resolution/computed_test.go b/internal/compose/resolution/computed_test.go index ed7e4f72..45e0d753 100644 --- a/internal/compose/resolution/computed_test.go +++ b/internal/compose/resolution/computed_test.go @@ -31,7 +31,7 @@ func computedShelf() map[string]mcat.Manifest { Provides: mcat.Offers("private-network")}) } -func TestAComputedModuleIsAskedAboutTheNodeItIsFor(t *testing.T) { +func testAComputedModuleIsAskedAboutTheNodeItIsFor(t *testing.T) { // The generator gets a node name, not a plan. Everything it needs is the whole mesh, which // it was built with — this is the one thing a node could never work out for itself. got, err := Resolve(computedShelf(), []string{"mesh-network"}, workstation(), mcat.World{}) @@ -51,7 +51,7 @@ func TestAComputedModuleIsAskedAboutTheNodeItIsFor(t *testing.T) { } } -func TestAMachineNobodyGaveItGetsNothing(t *testing.T) { +func testAMachineNobodyGaveItGetsNothing(t *testing.T) { // The whole point of making the network a module. Before this, every machine with an address // was on the private network and there was no way to say one should stay off. got, err := Resolve(computedShelf(), nil, workstation(), mcat.World{}) @@ -71,7 +71,7 @@ func TestAMachineNobodyGaveItGetsNothing(t *testing.T) { } } -func TestAssignedAndNotYetPartOfItIsNotAFailure(t *testing.T) { +func testAssignedAndNotYetPartOfItIsNotAFailure(t *testing.T) { // A machine given the network module before it has a place on it. Brief and ordinary — the // answer is "nothing yet", and treating it as an error would make an ordering a fault. got, _ := Resolve(computedShelf(), []string{"mesh-network"}, workstation(), mcat.World{}) @@ -85,7 +85,7 @@ func TestAssignedAndNotYetPartOfItIsNotAFailure(t *testing.T) { } } -func TestAGeneratorThisControlPlaneDoesNotHaveIsRefused(t *testing.T) { +func testAGeneratorThisControlPlaneDoesNotHaveIsRefused(t *testing.T) { // Sending a machine a module with no files would look like it worked. Named in the message, // because the only fix is a control plane that has it. got, _ := Resolve(shelf(mcat.Manifest{Module: "weather", Computed: "the-weather"}), []string{"weather"}, workstation(), mcat.World{}) @@ -99,7 +99,7 @@ func TestAGeneratorThisControlPlaneDoesNotHaveIsRefused(t *testing.T) { } } -func TestSettingsApplyToAComputedModuleToo(t *testing.T) { +func testSettingsApplyToAComputedModuleToo(t *testing.T) { // Being computed is about where the files come from, not about whether they are configurable. // A line drawn there would be arbitrary and nobody could predict it. got, _ := Resolve(computedShelf(), []string{"mesh-network"}, workstation(), mcat.World{}) @@ -121,7 +121,7 @@ func TestSettingsApplyToAComputedModuleToo(t *testing.T) { } } -func TestTwoWaysToBeOnAPrivateNetworkRefuseAndNameBoth(t *testing.T) { +func testTwoWaysToBeOnAPrivateNetworkRefuseAndNameBoth(t *testing.T) { // WireGuard is one way. The refusing rule is what makes a second one safe to add: assigning // both is caught rather than producing a machine on two networks that each half-work. _, err := Resolve(shelf(mcat.Manifest{Module: "mesh-network", Computed: "mesh-network", @@ -152,7 +152,7 @@ func (reloading) Resources(node string) ([]map[string]any, bool, error) { }, true, nil } -func TestWhatAServiceIsReloadedOnIsNamedAsTheHostWillSeeIt(t *testing.T) { +func testWhatAServiceIsReloadedOnIsNamedAsTheHostWillSeeIt(t *testing.T) { // Ids are prefixed with their module on the way out. An unprefixed reload-on would name a // resource the host never sees, and the runtime would never be reloaded for its trust. got, err := Resolve(computedShelf(), []string{"mesh-network"}, workstation(), mcat.World{}) @@ -182,3 +182,14 @@ func TestWhatAServiceIsReloadedOnIsNamedAsTheHostWillSeeIt(t *testing.T) { t.Errorf("reload-on names %v, the file is %v", service["reload-on"], file["id"]) } } + +// TestComputed runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestComputed(t *testing.T) { + t.Run("AComputedModuleIsAskedAboutTheNodeItIsFor", testAComputedModuleIsAskedAboutTheNodeItIsFor) + t.Run("AMachineNobodyGaveItGetsNothing", testAMachineNobodyGaveItGetsNothing) + t.Run("AssignedAndNotYetPartOfItIsNotAFailure", testAssignedAndNotYetPartOfItIsNotAFailure) + t.Run("AGeneratorThisControlPlaneDoesNotHaveIsRefused", testAGeneratorThisControlPlaneDoesNotHaveIsRefused) + t.Run("SettingsApplyToAComputedModuleToo", testSettingsApplyToAComputedModuleToo) + t.Run("TwoWaysToBeOnAPrivateNetworkRefuseAndNameBoth", testTwoWaysToBeOnAPrivateNetworkRefuseAndNameBoth) + t.Run("WhatAServiceIsReloadedOnIsNamedAsTheHostWillSeeIt", testWhatAServiceIsReloadedOnIsNamedAsTheHostWillSeeIt) +} diff --git a/internal/compose/resolution/config_test.go b/internal/compose/resolution/config_test.go index d731c9d0..1ff6a0b2 100644 --- a/internal/compose/resolution/config_test.go +++ b/internal/compose/resolution/config_test.go @@ -84,7 +84,7 @@ const configDunst = `{"module": "dunst", "version": "1", // ${config:} fills exactly as ${setting:} does: the module rewritten from settings to config composes // to the same bytes, with no layer, with the node's, and with the mesh's under the node's. -func TestAModuleRewrittenFromSettingsToConfigComposesByteIdentically(t *testing.T) { +func testAModuleRewrittenFromSettingsToConfigComposesByteIdentically(t *testing.T) { composed := func(manifest string, layers []mcat.Layer) []byte { t.Helper() m, err := decodeForTest([]byte(manifest)) @@ -128,7 +128,7 @@ func TestAModuleRewrittenFromSettingsToConfigComposesByteIdentically(t *testing. // A required value nothing sets is refused at composition in the config form's words: ${config:} and the // config verb, never `settings set` (review of mesh-controller#320). The settings form's words are unchanged. -func TestAnUnsetRequiredValueIsRefusedInTheConfigFormsWords(t *testing.T) { +func testAnUnsetRequiredValueIsRefusedInTheConfigFormsWords(t *testing.T) { m, err := parseRaw(t, inConfigForm()) if err != nil { t.Fatal(err) @@ -179,3 +179,9 @@ func TestAnUnsetRequiredValueIsRefusedInTheConfigFormsWords(t *testing.T) { t.Fatalf("the settings form's refusal changed: %v", err) } } + +// TestConfig runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestConfig(t *testing.T) { + t.Run("AModuleRewrittenFromSettingsToConfigComposesByteIdentically", testAModuleRewrittenFromSettingsToConfigComposesByteIdentically) + t.Run("AnUnsetRequiredValueIsRefusedInTheConfigFormsWords", testAnUnsetRequiredValueIsRefusedInTheConfigFormsWords) +} diff --git a/internal/compose/resolution/contributes_test.go b/internal/compose/resolution/contributes_test.go index 44f9b9c1..af691a54 100644 --- a/internal/compose/resolution/contributes_test.go +++ b/internal/compose/resolution/contributes_test.go @@ -49,7 +49,7 @@ func received(t *testing.T, out []map[string]any) []mcat.Contribution { return nil } -func TestTheFileTheProviderGetsIsMachineReadable(t *testing.T) { +func testTheFileTheProviderGetsIsMachineReadable(t *testing.T) { // It is written for a program, and the first version put a `//` header above the JSON — a // file that says "do not edit" to a person and fails to parse for the thing meant to read it. got, _ := Resolve(shelf(proxy(), published("board", "board", 8080)), []string{"board"}, workstation(), mcat.World{}) @@ -72,7 +72,7 @@ func TestTheFileTheProviderGetsIsMachineReadable(t *testing.T) { t.Fatal("no received file") } -func TestAModuleTellsItsProviderWhatItNeeds(t *testing.T) { +func testAModuleTellsItsProviderWhatItNeeds(t *testing.T) { got, err := Resolve(shelf(proxy(), published("board", "board", 8080)), []string{"board"}, workstation(), mcat.World{}) if err != nil { @@ -91,7 +91,7 @@ func TestAModuleTellsItsProviderWhatItNeeds(t *testing.T) { } } -func TestContributingToSomethingIsRequiringIt(t *testing.T) { +func testContributingToSomethingIsRequiringIt(t *testing.T) { // Asking to be published means a publisher must exist. A module that had to say both would // eventually say one, and the failure would be a machine where nothing serves the route. got, err := Resolve(shelf(proxy(), published("board", "board", 8080)), []string{"board"}, workstation(), mcat.World{}) @@ -104,7 +104,7 @@ func TestContributingToSomethingIsRequiringIt(t *testing.T) { } } -func TestNothingToContributeToIsRefused(t *testing.T) { +func testNothingToContributeToIsRefused(t *testing.T) { _, err := Resolve(shelf(published("board", "board", 8080)), []string{"board"}, workstation(), mcat.World{}) if err == nil { @@ -115,7 +115,7 @@ func TestNothingToContributeToIsRefused(t *testing.T) { } } -func TestEveryPublisherOnTheMachineIsInOneFile(t *testing.T) { +func testEveryPublisherOnTheMachineIsInOneFile(t *testing.T) { got, err := Resolve(shelf(proxy(), published("board", "board", 8080), published("archive", "archive", 9000), @@ -135,7 +135,7 @@ func TestEveryPublisherOnTheMachineIsInOneFile(t *testing.T) { } } -func TestAProviderWithNoConsumersStillGetsTheFile(t *testing.T) { +func testAProviderWithNoConsumersStillGetsTheFile(t *testing.T) { // Empty rather than absent. A provider that finds no file cannot tell "nothing asked for me" // from "the mesh never wrote it", and those want completely different responses — the same // rule the host follows about a service that does not exist. @@ -148,7 +148,7 @@ func TestAProviderWithNoConsumersStillGetsTheFile(t *testing.T) { } } -func TestTheProviderCanReloadWhenTheRoutesChange(t *testing.T) { +func testTheProviderCanReloadWhenTheRoutesChange(t *testing.T) { // A proxy that got a new route and did not reload is a route that silently does not work. // The same fault the private network had when a peer list changed under a running interface, // which is why the received file has a name a module can point at. @@ -171,7 +171,7 @@ func TestTheProviderCanReloadWhenTheRoutesChange(t *testing.T) { t.Fatal("no service in the declaration") } -func TestARouteCanBeSetPerMesh(t *testing.T) { +func testARouteCanBeSetPerMesh(t *testing.T) { // The hostname is exactly the kind of thing that differs between one mesh and the next. A // module whose route could not be set would have to be edited to be reused anywhere. got, _ := Resolve(shelf(proxy(), published("board", "board", 8080)), []string{"board"}, workstation(), mcat.World{}) @@ -191,7 +191,7 @@ func TestARouteCanBeSetPerMesh(t *testing.T) { } } -func TestASettingReachesAContributionOnlyWhereItDeclaresTheKey(t *testing.T) { +func testASettingReachesAContributionOnlyWhereItDeclaresTheKey(t *testing.T) { // novox/hq 04-ISSUES/173: the mail module's site name, set so its environment file could read // it, arrived in every route it contributed. A setting overrides a key the contribution // declares and adds none — the provider reads the contribution as a contract. @@ -238,7 +238,7 @@ func grantedTo(t *testing.T, out []map[string]any) []mcat.Contribution { return nil } -func TestAConsumersOwnContributionsAreStillThere(t *testing.T) { +func testAConsumersOwnContributionsAreStillThere(t *testing.T) { // Cross-node grants are merged in with this machine's own, because from the provider's side // they are the same thing — somebody wanting something — and a provider that had to read two // lists would read one of them. @@ -253,7 +253,7 @@ func TestAConsumersOwnContributionsAreStillThere(t *testing.T) { } } -func TestARequireOnlyConsumerOfAParameterlessProvisionStillAsks(t *testing.T) { +func testARequireOnlyConsumerOfAParameterlessProvisionStillAsks(t *testing.T) { // A consumer that requires a parameterless provision (one whose serves names no consumer key — // redis-cache, amqp) contributes no payload, but it still ASKS for the provision and must be // granted a credential. Keying "asks" on contributions alone gave its grant From="" — read as @@ -277,7 +277,7 @@ func TestARequireOnlyConsumerOfAParameterlessProvisionStillAsks(t *testing.T) { } } -func TestAConsumerThatStoppedAskingIsWithdrawn(t *testing.T) { +func testAConsumerThatStoppedAskingIsWithdrawn(t *testing.T) { // Withdrawal is how a credential is taken away. The provisioner removes what nobody asks for, // and it can only do that if the mesh stops asking — a consumer that was unassigned would // otherwise keep a working login for ever, and nothing would say so. @@ -309,3 +309,19 @@ func TestAConsumerThatStoppedAskingIsWithdrawn(t *testing.T) { } } } + +// TestContributes runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestContributes(t *testing.T) { + t.Run("TheFileTheProviderGetsIsMachineReadable", testTheFileTheProviderGetsIsMachineReadable) + t.Run("AModuleTellsItsProviderWhatItNeeds", testAModuleTellsItsProviderWhatItNeeds) + t.Run("ContributingToSomethingIsRequiringIt", testContributingToSomethingIsRequiringIt) + t.Run("NothingToContributeToIsRefused", testNothingToContributeToIsRefused) + t.Run("EveryPublisherOnTheMachineIsInOneFile", testEveryPublisherOnTheMachineIsInOneFile) + t.Run("AProviderWithNoConsumersStillGetsTheFile", testAProviderWithNoConsumersStillGetsTheFile) + t.Run("TheProviderCanReloadWhenTheRoutesChange", testTheProviderCanReloadWhenTheRoutesChange) + t.Run("ARouteCanBeSetPerMesh", testARouteCanBeSetPerMesh) + t.Run("ASettingReachesAContributionOnlyWhereItDeclaresTheKey", testASettingReachesAContributionOnlyWhereItDeclaresTheKey) + t.Run("AConsumersOwnContributionsAreStillThere", testAConsumersOwnContributionsAreStillThere) + t.Run("ARequireOnlyConsumerOfAParameterlessProvisionStillAsks", testARequireOnlyConsumerOfAParameterlessProvisionStillAsks) + t.Run("AConsumerThatStoppedAskingIsWithdrawn", testAConsumerThatStoppedAskingIsWithdrawn) +} diff --git a/internal/compose/resolution/contribution_dependencies_test.go b/internal/compose/resolution/contribution_dependencies_test.go index 10fd91d6..43d623f4 100644 --- a/internal/compose/resolution/contribution_dependencies_test.go +++ b/internal/compose/resolution/contribution_dependencies_test.go @@ -7,7 +7,7 @@ import ( mcat "git.novox.be/novox/mesh-sdk/go/catalogue" ) -func TestAContributionDependsOnTheSeatThatPlacesIt(t *testing.T) { +func testAContributionDependsOnTheSeatThatPlacesIt(t *testing.T) { env := mod("theme", nil, nil, nil) env.Environment = &mcat.Environment{Variables: map[string]string{"GTK_THEME": "Adwaita:dark"}} path := mod("toolchain", nil, nil, nil) @@ -43,7 +43,7 @@ func TestAContributionDependsOnTheSeatThatPlacesIt(t *testing.T) { } } -func TestAHolderMeetsItsOwnContribution(t *testing.T) { +func testAHolderMeetsItsOwnContribution(t *testing.T) { // The display server's module contributes nothing to its own seat today, but the zsh module's // environment contributions do go to another seat: a claim meets only the seat it names. zsh := mod("zsh", nil, nil, nil, mcat.Claim{Name: mcat.LoginShellSeat}) @@ -56,3 +56,9 @@ func TestAHolderMeetsItsOwnContribution(t *testing.T) { t.Errorf("zsh alone: unheld %v, want only %s (its shell code is its own seat's)", unheld, mcat.EnvironmentSeat) } } + +// TestContributionDependencies runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestContributionDependencies(t *testing.T) { + t.Run("AContributionDependsOnTheSeatThatPlacesIt", testAContributionDependsOnTheSeatThatPlacesIt) + t.Run("AHolderMeetsItsOwnContribution", testAHolderMeetsItsOwnContribution) +} diff --git a/internal/compose/resolution/derived_for_consumer_test.go b/internal/compose/resolution/derived_for_consumer_test.go index f2e58607..a8d9cc6c 100644 --- a/internal/compose/resolution/derived_for_consumer_test.go +++ b/internal/compose/resolution/derived_for_consumer_test.go @@ -59,7 +59,7 @@ func pics() mcat.Manifest { // The three places the derived value lands must agree, because agreeing is the whole point: the // consumer's own file, the binding it reads as JSON, and the provider's contributions entry. -func TestADerivedValueReachesBothEndsAndAgrees(t *testing.T) { +func testADerivedValueReachesBothEndsAndAgrees(t *testing.T) { r, err := Resolve(shelf(store(), files()), []string{"store", "files"}, reachable(), mcat.World{}) if err != nil { t.Fatal(err) @@ -122,7 +122,7 @@ func TestADerivedValueReachesBothEndsAndAgrees(t *testing.T) { } // Two consumers of one provider on one machine get two buckets, and neither gets the other's. -func TestTwoConsumersOfOneProviderGetTheirOwnDerivation(t *testing.T) { +func testTwoConsumersOfOneProviderGetTheirOwnDerivation(t *testing.T) { r, err := Resolve(shelf(store(), files(), pics()), []string{"store", "files", "pics"}, reachable(), mcat.World{}) if err != nil { @@ -160,7 +160,7 @@ func TestTwoConsumersOfOneProviderGetTheirOwnDerivation(t *testing.T) { // An operator may still set what the provider serves where its definition asks (${setting:…}), and // the mesh still derives the rest: the setting is filled first, then the consumer's half. (Until // novox/hq issue 696 the layer replaced the served bucket whole; a layer replaces no served key now.) -func TestASettingComposesWithADerivedValue(t *testing.T) { +func testASettingComposesWithADerivedValue(t *testing.T) { prefixed := store() prefixed.Serves["s3-bucket"]["bucket"] = "${setting:bucket-prefix}${consumer:as:dns}" r, err := Resolve(shelf(prefixed, files()), []string{"store", "files"}, reachable(), mcat.World{}) @@ -186,7 +186,7 @@ func TestASettingComposesWithADerivedValue(t *testing.T) { } // `dns` is checked against an identity the mesh actually mints, not an invented string. -func TestTheDNSAlphabetIsTheMintedIdentityWithItsSeparatorRewritten(t *testing.T) { +func testTheDNSAlphabetIsTheMintedIdentityWithItsSeparatorRewritten(t *testing.T) { as := mcat.ConsumerIdentity("anchor", mcat.IdentitySource("ncloud", "nextcloud")) if err := mcat.CheckIdentity("anchor", mcat.IdentitySource("ncloud", "nextcloud")); err != nil { t.Fatalf("the mesh would not mint this identity at all: %v", err) @@ -203,7 +203,7 @@ func TestTheDNSAlphabetIsTheMintedIdentityWithItsSeparatorRewritten(t *testing.T // The check that would have caught the one wrong instance: a consumer that writes the derived // value into its own definition instead of asking for it is refused, whether it transcribed the // right answer or a predecessor's. -func TestAConsumerThatTranscribesWhatItsProviderDerivesIsRefused(t *testing.T) { +func testAConsumerThatTranscribesWhatItsProviderDerivesIsRefused(t *testing.T) { as := mcat.ConsumerIdentity("workstation", mcat.IdentitySource("files", "files")) transcribed := strings.ReplaceAll(as, "_", "-") @@ -278,7 +278,7 @@ func storeGrants(t *testing.T, out []map[string]any) []mcat.Contribution { // // Refused, loudly, at the one place that can see both halves. Lifting it means giving the // consumer's side a local dimension, which is a decision and not an omission. -func TestAConsumerWithSeveralHoldersOfADerivingProviderIsRefused(t *testing.T) { +func testAConsumerWithSeveralHoldersOfADerivingProviderIsRefused(t *testing.T) { m := files() // Two holders of the one provision, the shape ADR 0094 gives a module that keeps several. m.Secrets = nil @@ -310,3 +310,13 @@ func TestAConsumerWithSeveralHoldersOfADerivingProviderIsRefused(t *testing.T) { } } } + +// TestDerivedForConsumer runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestDerivedForConsumer(t *testing.T) { + t.Run("ADerivedValueReachesBothEndsAndAgrees", testADerivedValueReachesBothEndsAndAgrees) + t.Run("TwoConsumersOfOneProviderGetTheirOwnDerivation", testTwoConsumersOfOneProviderGetTheirOwnDerivation) + t.Run("ASettingComposesWithADerivedValue", testASettingComposesWithADerivedValue) + t.Run("TheDNSAlphabetIsTheMintedIdentityWithItsSeparatorRewritten", testTheDNSAlphabetIsTheMintedIdentityWithItsSeparatorRewritten) + t.Run("AConsumerThatTranscribesWhatItsProviderDerivesIsRefused", testAConsumerThatTranscribesWhatItsProviderDerivesIsRefused) + t.Run("AConsumerWithSeveralHoldersOfADerivingProviderIsRefused", testAConsumerWithSeveralHoldersOfADerivingProviderIsRefused) +} diff --git a/internal/compose/resolution/dir_into_test.go b/internal/compose/resolution/dir_into_test.go index 4f897a8b..a6be142b 100644 --- a/internal/compose/resolution/dir_into_test.go +++ b/internal/compose/resolution/dir_into_test.go @@ -22,7 +22,7 @@ func placedModule() mcat.Manifest { } } -func TestAPathlessDirectoryResolvesUnderTheNodesRoot(t *testing.T) { +func testAPathlessDirectoryResolvesUnderTheNodesRoot(t *testing.T) { m := placedModule() dirs := dirsFor(m, mcat.Rendering{}) if dirs["data"] != "/var/lib/photos/data" { @@ -34,7 +34,7 @@ func TestAPathlessDirectoryResolvesUnderTheNodesRoot(t *testing.T) { } } -func TestDirReferencesBecomeThePlaceInEveryField(t *testing.T) { +func testDirReferencesBecomeThePlaceInEveryField(t *testing.T) { m := placedModule() dirs := dirsFor(m, mcat.Rendering{}) @@ -72,7 +72,7 @@ func TestDirReferencesBecomeThePlaceInEveryField(t *testing.T) { } } -func TestAStatedPathIsThePlacementAndStillAnswersByName(t *testing.T) { +func testAStatedPathIsThePlacementAndStillAnswersByName(t *testing.T) { m := placedModule() // The adopted-machine case: data that must sit where the predecessor already put it. m.Resources[0]["path"] = "/services/mssql/data/" @@ -89,7 +89,7 @@ func TestAStatedPathIsThePlacementAndStillAnswersByName(t *testing.T) { } } -func TestFillingForOneNodeLeaksIntoNoOther(t *testing.T) { +func testFillingForOneNodeLeaksIntoNoOther(t *testing.T) { m := placedModule() first := shallowCopy(m.Resources[2]) if err := dirInto(first, dirsFor(m, mcat.Rendering{DataRoot: "/first"}), m.Module); err != nil { @@ -107,7 +107,7 @@ func TestFillingForOneNodeLeaksIntoNoOther(t *testing.T) { } } -func TestAReferenceToNoDirectoryRefusesAtCompositionToo(t *testing.T) { +func testAReferenceToNoDirectoryRefusesAtCompositionToo(t *testing.T) { m := placedModule() container := shallowCopy(m.Resources[2]) container["env"] = map[string]any{"DATA": "${dir:date}"} @@ -117,7 +117,7 @@ func TestAReferenceToNoDirectoryRefusesAtCompositionToo(t *testing.T) { } } -func TestTheAssignmentsOwnRootIsAPlace(t *testing.T) { +func testTheAssignmentsOwnRootIsAPlace(t *testing.T) { m := mcat.Manifest{Module: "mailu", Resources: []map[string]any{ {"id": "state", "type": "directory", "place": ".", "mode": "0700"}, {"id": "data-mail", "type": "directory"}, @@ -141,7 +141,7 @@ func TestTheAssignmentsOwnRootIsAPlace(t *testing.T) { } } -func TestTheManifestsMapsArePlaced(t *testing.T) { +func testTheManifestsMapsArePlaced(t *testing.T) { m := mcat.Manifest{ Module: "photos", Resources: []map[string]any{ @@ -173,7 +173,7 @@ func TestTheManifestsMapsArePlaced(t *testing.T) { } } -func TestTheMeshsDirectoryForAModuleIsAPlace(t *testing.T) { +func testTheMeshsDirectoryForAModuleIsAPlace(t *testing.T) { // novox/hq issue 174. What the mesh writes for a module — its bus credential, its bindings — // is the mesh's plumbing under /mesh/, and the definition names it by id. m := mcat.Manifest{Module: "umami", @@ -210,7 +210,7 @@ func TestTheMeshsDirectoryForAModuleIsAPlace(t *testing.T) { } } -func TestTwoModulesPlacedRootsAreNoCollision(t *testing.T) { +func testTwoModulesPlacedRootsAreNoCollision(t *testing.T) { a := mcat.Manifest{Module: "gitea", Resources: []map[string]any{ {"id": "state", "type": "directory", "place": "."}, {"id": "env", "type": "file", "path": "${dir:state}/server.env", "content": ""}, @@ -240,7 +240,7 @@ func shallowCopy(resource map[string]any) map[string]any { return copied } -func TestADirectoryBeneathAPlacedOneIsPlacedWithIt(t *testing.T) { +func testADirectoryBeneathAPlacedOneIsPlacedWithIt(t *testing.T) { // An adopted layout keeps a subdirectory the predecessor made under the mesh's directory // (issue 174: a forge's runtime state, a manager's output). Stated as beneath the placed one, // it moves with it — a node's root moves both, and the definition names no host path. @@ -269,3 +269,17 @@ func TestADirectoryBeneathAPlacedOneIsPlacedWithIt(t *testing.T) { t.Fatalf("a reference to the subdirectory resolves whole; got %v", container["volumes"]) } } + +// TestDirInto runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestDirInto(t *testing.T) { + t.Run("APathlessDirectoryResolvesUnderTheNodesRoot", testAPathlessDirectoryResolvesUnderTheNodesRoot) + t.Run("DirReferencesBecomeThePlaceInEveryField", testDirReferencesBecomeThePlaceInEveryField) + t.Run("AStatedPathIsThePlacementAndStillAnswersByName", testAStatedPathIsThePlacementAndStillAnswersByName) + t.Run("FillingForOneNodeLeaksIntoNoOther", testFillingForOneNodeLeaksIntoNoOther) + t.Run("AReferenceToNoDirectoryRefusesAtCompositionToo", testAReferenceToNoDirectoryRefusesAtCompositionToo) + t.Run("TheAssignmentsOwnRootIsAPlace", testTheAssignmentsOwnRootIsAPlace) + t.Run("TheManifestsMapsArePlaced", testTheManifestsMapsArePlaced) + t.Run("TheMeshsDirectoryForAModuleIsAPlace", testTheMeshsDirectoryForAModuleIsAPlace) + t.Run("TwoModulesPlacedRootsAreNoCollision", testTwoModulesPlacedRootsAreNoCollision) + t.Run("ADirectoryBeneathAPlacedOneIsPlacedWithIt", testADirectoryBeneathAPlacedOneIsPlacedWithIt) +} diff --git a/internal/compose/resolution/domain_test.go b/internal/compose/resolution/domain_test.go index 12dbc592..2da255cf 100644 --- a/internal/compose/resolution/domain_test.go +++ b/internal/compose/resolution/domain_test.go @@ -19,7 +19,7 @@ func networkingShelf(extra ...mcat.Manifest) map[string]mcat.Manifest { return shelf(append(base, extra...)...) } -func TestOneWordBringsUpTheNetwork(t *testing.T) { +func testOneWordBringsUpTheNetwork(t *testing.T) { // The case that has to stay easy. Nothing is asked, because with one answer to each // requirement there was never a question. got, err := Resolve(networkingShelf(), []string{"networking"}, workstation(), mcat.World{}) @@ -34,7 +34,7 @@ func TestOneWordBringsUpTheNetwork(t *testing.T) { } } -func TestASecondVPNTurnsItIntoAChoice(t *testing.T) { +func testASecondVPNTurnsItIntoAChoice(t *testing.T) { // And the choice is offered rather than made. A default here would be the flavor field coming // back under another name. _, err := Resolve(networkingShelf(mcat.Manifest{Module: "tailscale", Provides: mcat.Offers("private-network"), @@ -51,7 +51,7 @@ func TestASecondVPNTurnsItIntoAChoice(t *testing.T) { } } -func TestChoosingIsAssigning(t *testing.T) { +func testChoosingIsAssigning(t *testing.T) { // No second verb. Assigning the one you want answers the requirement, and the bundle takes it. got, err := Resolve(networkingShelf(mcat.Manifest{Module: "tailscale", Provides: mcat.Offers("private-network", "name-resolution"), @@ -70,7 +70,7 @@ func TestChoosingIsAssigning(t *testing.T) { } } -func TestChoosingOneVPNCannotDragTheOtherBackIn(t *testing.T) { +func testChoosingOneVPNCannotDragTheOtherBackIn(t *testing.T) { // This happened. The person chose tailscale; the names module required the mesh's own // addressing; only WireGuard provides that; so both were installed and nobody was told. // @@ -88,7 +88,7 @@ func TestChoosingOneVPNCannotDragTheOtherBackIn(t *testing.T) { } } -func TestNamesNeedTheMeshsOwnAddresses(t *testing.T) { +func testNamesNeedTheMeshsOwnAddresses(t *testing.T) { // Names are computed from addresses the mesh handed out. Over a VPN that hands out its own, // the mesh has nothing to write, so the names module requires the addressing rather than a // private network in general — otherwise a machine gets a hosts file full of addresses that @@ -105,7 +105,7 @@ func TestNamesNeedTheMeshsOwnAddresses(t *testing.T) { } } -func TestARequirementWantedTwiceIsReportedOnce(t *testing.T) { +func testARequirementWantedTwiceIsReportedOnce(t *testing.T) { // Two identical lines make a person hunt for the difference between them before realising // there is none. _, err := Resolve(shelf(mcat.Manifest{Module: "one", Requires: []string{"shell"}}, mcat.Manifest{Module: "two", Requires: []string{"shell"}}, mcat.Manifest{Module: "bash", Provides: mcat.Offers("shell")}, mcat.Manifest{Module: "zsh", Provides: mcat.Offers("shell")}), []string{"one", "two"}, workstation(), mcat.World{}) @@ -117,3 +117,13 @@ func TestARequirementWantedTwiceIsReportedOnce(t *testing.T) { t.Fatalf("the same requirement was reported %d times:\n%v", n, err) } } + +// TestDomain runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestDomain(t *testing.T) { + t.Run("OneWordBringsUpTheNetwork", testOneWordBringsUpTheNetwork) + t.Run("ASecondVPNTurnsItIntoAChoice", testASecondVPNTurnsItIntoAChoice) + t.Run("ChoosingIsAssigning", testChoosingIsAssigning) + t.Run("ChoosingOneVPNCannotDragTheOtherBackIn", testChoosingOneVPNCannotDragTheOtherBackIn) + t.Run("NamesNeedTheMeshsOwnAddresses", testNamesNeedTheMeshsOwnAddresses) + t.Run("ARequirementWantedTwiceIsReportedOnce", testARequirementWantedTwiceIsReportedOnce) +} diff --git a/internal/compose/resolution/endpoint_test.go b/internal/compose/resolution/endpoint_test.go index ed009b93..b0da2271 100644 --- a/internal/compose/resolution/endpoint_test.go +++ b/internal/compose/resolution/endpoint_test.go @@ -31,7 +31,7 @@ func aMediaServer() mcat.Manifest { // And the routed set is read through the name, so the endpoint the proxy serves is known without a // reader joining two numbers. -func TestTheRoutedEndpointIsFoundByName(t *testing.T) { +func testTheRoutedEndpointIsFoundByName(t *testing.T) { routed := RoutedPorts(aMediaServer()) if !routed[80] { t.Fatalf("the routed endpoint was not found by name: %v", routed) @@ -45,7 +45,7 @@ func TestTheRoutedEndpointIsFoundByName(t *testing.T) { // **Two endpoints of different shapes, configured as themselves.** The web endpoint's reach asks for // names and leaves its port to the proxy; the stream endpoint's reach governs its port, because // clients dial it and there is no name. -func TestTwoEndpointsOfDifferentShapesAreConfiguredSeparately(t *testing.T) { +func testTwoEndpointsOfDifferentShapesAreConfiguredSeparately(t *testing.T) { m := aMediaServer() settings := mcat.SettingsBy{"media": {{From: "node anchor", Values: map[string]any{mcat.ReachSetting: map[string]any{"80": mcat.ReachBoth, "32400": mcat.ReachPublic}}}}} @@ -92,7 +92,7 @@ func TestTwoEndpointsOfDifferentShapesAreConfiguredSeparately(t *testing.T) { // // Caught after the catalogue had already been changed to name endpoints, and before the mesh picked // those manifests up — which is the only reason nothing broke. -func TestARouteNamingAnEndpointStillCarriesItsPort(t *testing.T) { +func testARouteNamingAnEndpointStillCarriesItsPort(t *testing.T) { m := aMediaServer() r := mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{m}, PublicDomain: "example.test", At: "anchor.internal"} @@ -119,7 +119,7 @@ func TestARouteNamingAnEndpointStillCarriesItsPort(t *testing.T) { // And the declared port, not the machine one: the redirection to where the machine published it // happens later and is keyed on the declared number, so filling the machine port in here would be // redirected twice or not at all. -func TestTheEndpointsDeclaredPortIsFilledInNotTheMachineOne(t *testing.T) { +func testTheEndpointsDeclaredPortIsFilledInNotTheMachineOne(t *testing.T) { m := aMediaServer() values := map[string]any{mcat.RouteEndpoint: "web", "label": "media"} portOfEndpoint(values, endpointPorts(m)) @@ -134,10 +134,19 @@ func TestTheEndpointsDeclaredPortIsFilledInNotTheMachineOne(t *testing.T) { } // A route that repeats a port keeps it, because that is the older shape and still read. -func TestARouteThatRepeatsItsPortKeepsIt(t *testing.T) { +func testARouteThatRepeatsItsPortKeepsIt(t *testing.T) { values := map[string]any{mcat.RouteEndpoint: "web", "port": 8080} portOfEndpoint(values, map[string]int{"web": 80}) if got, _ := asPort(values["port"]); got != 8080 { t.Fatalf("the port it stated was overwritten with %d", got) } } + +// TestEndpoint runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestEndpoint(t *testing.T) { + t.Run("TheRoutedEndpointIsFoundByName", testTheRoutedEndpointIsFoundByName) + t.Run("TwoEndpointsOfDifferentShapesAreConfiguredSeparately", testTwoEndpointsOfDifferentShapesAreConfiguredSeparately) + t.Run("ARouteNamingAnEndpointStillCarriesItsPort", testARouteNamingAnEndpointStillCarriesItsPort) + t.Run("TheEndpointsDeclaredPortIsFilledInNotTheMachineOne", testTheEndpointsDeclaredPortIsFilledInNotTheMachineOne) + t.Run("ARouteThatRepeatsItsPortKeepsIt", testARouteThatRepeatsItsPortKeepsIt) +} diff --git a/internal/compose/resolution/endpoints_setting_test.go b/internal/compose/resolution/endpoints_setting_test.go index dfce9155..88cc3c72 100644 --- a/internal/compose/resolution/endpoints_setting_test.go +++ b/internal/compose/resolution/endpoints_setting_test.go @@ -15,7 +15,7 @@ func configured(block map[string]any) mcat.SettingsBy { // **One block per endpoint, saying all three things.** The machine port, the subdomain and the reach // were `ports`, the route's label and `reach`, each keyed by a port number, so configuring a module // with two endpoints of different shapes meant knowing which number was which. -func TestAnEndpointsBlockSaysPortLabelAndReach(t *testing.T) { +func testAnEndpointsBlockSaysPortLabelAndReach(t *testing.T) { m := aMediaServer() // stream's reach NARROWS what the manifest says — the manifest has it from anywhere, the // assignment says internal. Chosen deliberately: a reach that agrees with the manifest proves @@ -68,7 +68,7 @@ func TestAnEndpointsBlockSaysPortLabelAndReach(t *testing.T) { // A block that says only a reach leaves the port to the mesh and the label to the module, which is the // ordinary case and must not require writing the other two. -func TestABlockMaySayOnlyAReach(t *testing.T) { +func testABlockMaySayOnlyAReach(t *testing.T) { m := aMediaServer() settings := configured(map[string]any{"web": map[string]any{"reach": mcat.ReachInternal}}) r := mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{m}, @@ -89,10 +89,17 @@ func TestABlockMaySayOnlyAReach(t *testing.T) { } // **Two places giving one endpoint a machine port is the confusion this key exists to end.** -func TestAnEndpointGivenAPortTwiceIsRefused(t *testing.T) { +func testAnEndpointGivenAPortTwiceIsRefused(t *testing.T) { m := aMediaServer() _, err := GivenPorts(m, []mcat.Layer{{From: "node anchor", Placement: map[string]any{mcat.EndpointsSetting: map[string]any{"web": map[string]any{"port": 20009}}, mcat.PortsSetting: map[string]any{"80": 30000}}}}) if err == nil || !strings.Contains(err.Error(), "published once") { t.Fatalf("an endpoint given two machine ports was accepted: %v", err) } } + +// TestEndpointsSetting runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestEndpointsSetting(t *testing.T) { + t.Run("AnEndpointsBlockSaysPortLabelAndReach", testAnEndpointsBlockSaysPortLabelAndReach) + t.Run("ABlockMaySayOnlyAReach", testABlockMaySayOnlyAReach) + t.Run("AnEndpointGivenAPortTwiceIsRefused", testAnEndpointGivenAPortTwiceIsRefused) +} diff --git a/internal/compose/resolution/environment_into_integration_test.go b/internal/compose/resolution/environment_into_integration_test.go index d63fa7ea..ecdac913 100644 --- a/internal/compose/resolution/environment_into_integration_test.go +++ b/internal/compose/resolution/environment_into_integration_test.go @@ -46,7 +46,7 @@ func TestTheServiceManagerReadsTheSystemdRenderingAsMeant(t *testing.T) { if _, err := os.Stat(generator); err != nil { t.Skip("NOT JUDGED: no environment.d generator on this machine, so the service manager's reading " + "of the rendering is judged only where systemd runs; the rendering itself is held byte for byte " + - "by TestTheEnvironmentRendersForTheServiceManagerByteForByte") + "by testTheEnvironmentRendersForTheServiceManagerByteForByte") } const base = "/usr/bin:/bin" read := func(conf string) map[string]string { diff --git a/internal/compose/resolution/environment_into_test.go b/internal/compose/resolution/environment_into_test.go index f4ef2bc1..de82999d 100644 --- a/internal/compose/resolution/environment_into_test.go +++ b/internal/compose/resolution/environment_into_test.go @@ -74,7 +74,7 @@ PATH=/home/op/go/bin:/usr/local/go/bin:/home/op/.local/bin:/home/op/bin${PATH:+: PATH=${PATH:+$PATH:}/opt/agent/bin:/opt/scripts ` -func TestTheEnvironmentRendersForAPOSIXShellByteForByte(t *testing.T) { +func testTheEnvironmentRendersForAPOSIXShellByteForByte(t *testing.T) { env, err := environmentOn(contributors(), operatorFacts) if err != nil { t.Fatal(err) @@ -84,7 +84,7 @@ func TestTheEnvironmentRendersForAPOSIXShellByteForByte(t *testing.T) { } } -func TestTheEnvironmentRendersForTheServiceManagerByteForByte(t *testing.T) { +func testTheEnvironmentRendersForTheServiceManagerByteForByte(t *testing.T) { env, err := environmentOn(contributors(), operatorFacts) if err != nil { t.Fatal(err) @@ -95,7 +95,7 @@ func TestTheEnvironmentRendersForTheServiceManagerByteForByte(t *testing.T) { } // Nothing contributed renders nothing, in both formats — not an empty `export PATH`. -func TestNoContributionsRenderNothing(t *testing.T) { +func testNoContributionsRenderNothing(t *testing.T) { env, err := environmentOn([]mcat.Manifest{{Module: "postgres"}}, operatorFacts) if err != nil { t.Fatal(err) @@ -106,7 +106,7 @@ func TestNoContributionsRenderNothing(t *testing.T) { } // A ${machine:…} fact the machine does not have is refused naming the module, as a file's is. -func TestAContributedFactTheMachineLacksIsRefused(t *testing.T) { +func testAContributedFactTheMachineLacksIsRefused(t *testing.T) { _, err := environmentOn(contributors(), map[string]string{"name": "server"}) if err == nil || !strings.Contains(err.Error(), "go-toolchain sets GOPATH") || !strings.Contains(err.Error(), "${machine:account-home}") { @@ -115,7 +115,7 @@ func TestAContributedFactTheMachineLacksIsRefused(t *testing.T) { } // ADR 0203 §5: two modules setting one variable are refused, both named — neither silently wins. -func TestAVariableTwoModulesSetIsRefusedNamingBoth(t *testing.T) { +func testAVariableTwoModulesSetIsRefusedNamingBoth(t *testing.T) { modules := append(contributors(), mcat.Manifest{Module: "neovim", Environment: &mcat.Environment{ Variables: map[string]string{"EDITOR": "nvim"}}}) _, err := environmentOn(modules, operatorFacts) @@ -171,7 +171,7 @@ func zshHolder() mcat.Manifest { // byte, because the shell's code is placed after every other placeholder pass and in one pass — a // scanner for the mesh's placeholders that ran after it would read `${XDG_CACHE_HOME:-…}` and // `${(%):-%n}` as the mesh's, or fill a `${machine:…}` some module wrote for its shell to see. -func TestShellCodeReachesTheHoldersFileByteForByte(t *testing.T) { +func testShellCodeReachesTheHoldersFileByteForByte(t *testing.T) { modules := append(shells(), zshHolder(), mcat.Manifest{Module: "sly", Shell: []mcat.ShellCode{ {For: "zsh", Slot: "last", Code: "echo ${machine:account-home} ${secret:x} ${shell:zsh:first} ${environment:posix}"}, }}) @@ -212,7 +212,7 @@ func TestShellCodeReachesTheHoldersFileByteForByte(t *testing.T) { } // The holder of node-environment places both renderings, and they are the same as rendered alone. -func TestTheEnvironmentHolderPlacesBothRenderings(t *testing.T) { +func testTheEnvironmentHolderPlacesBothRenderings(t *testing.T) { holder := mcat.Manifest{Module: "node-env", Claims: []mcat.Claim{{Name: mcat.EnvironmentSeat, Scope: mcat.ScopeNode}}, Resources: []map[string]any{ {"id": "posix", "type": "file", "path": "${machine:account-home}/.config/mesh/environment.sh", @@ -236,3 +236,14 @@ func TestTheEnvironmentHolderPlacesBothRenderings(t *testing.T) { t.Fatalf("the environment.d file is\n%v", by["node-env.systemd"]) } } + +// TestEnvironmentInto runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestEnvironmentInto(t *testing.T) { + t.Run("TheEnvironmentRendersForAPOSIXShellByteForByte", testTheEnvironmentRendersForAPOSIXShellByteForByte) + t.Run("TheEnvironmentRendersForTheServiceManagerByteForByte", testTheEnvironmentRendersForTheServiceManagerByteForByte) + t.Run("NoContributionsRenderNothing", testNoContributionsRenderNothing) + t.Run("AContributedFactTheMachineLacksIsRefused", testAContributedFactTheMachineLacksIsRefused) + t.Run("AVariableTwoModulesSetIsRefusedNamingBoth", testAVariableTwoModulesSetIsRefusedNamingBoth) + t.Run("ShellCodeReachesTheHoldersFileByteForByte", testShellCodeReachesTheHoldersFileByteForByte) + t.Run("TheEnvironmentHolderPlacesBothRenderings", testTheEnvironmentHolderPlacesBothRenderings) +} diff --git a/internal/compose/resolution/filtering_test.go b/internal/compose/resolution/filtering_test.go index 46eb3b63..5abfd27f 100644 --- a/internal/compose/resolution/filtering_test.go +++ b/internal/compose/resolution/filtering_test.go @@ -13,7 +13,7 @@ import ( // A machine that has not said which links face outside is sent no filter, and the refusal names the // module that would have loaded it so the reader knows what is being withheld. -func TestAMachineThatNamedNoOutwardLinkIsSentNoFilter(t *testing.T) { +func testAMachineThatNamedNoOutwardLinkIsSentNoFilter(t *testing.T) { r := mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{ {Module: "nftables", Filtering: &mcat.Filtering{Into: "/etc/mesh/filter.nft"}}, {Module: "web", Listens: []mcat.Listening{{Port: 443, From: mcat.FromEverywhere}}}, @@ -35,7 +35,7 @@ func TestAMachineThatNamedNoOutwardLinkIsSentNoFilter(t *testing.T) { } // The rule set is the machine's, not the asking module's. -func TestTheModuleAskingForTheRuleSetGetsEveryModulesPorts(t *testing.T) { +func testTheModuleAskingForTheRuleSetGetsEveryModulesPorts(t *testing.T) { r := mcat.Resolution{Modules: []mcat.Manifest{ {Module: "firewall", Filtering: &mcat.Filtering{Into: "/etc/mesh/filter.nft"}}, {Module: "web", Listens: []mcat.Listening{{Port: 443, From: mcat.FromEverywhere}}}, @@ -191,7 +191,7 @@ func TestTheModuleAskingForTheRuleSetGetsEveryModulesPorts(t *testing.T) { // a credential, a rule set. Written after the service, the service is applied first, fails, and // the next reconcile fixes it. A fault that repairs itself on the second attempt is worse than one // that does not: what gets remembered is that it works. -func TestWhatTheMeshComputesIsAppliedBeforeWhatTheModuleDeclared(t *testing.T) { +func testWhatTheMeshComputesIsAppliedBeforeWhatTheModuleDeclared(t *testing.T) { r := mcat.Resolution{Modules: []mcat.Manifest{{ Module: "firewall", Filtering: &mcat.Filtering{Into: "/etc/nftables.conf"}, @@ -219,7 +219,7 @@ func TestWhatTheMeshComputesIsAppliedBeforeWhatTheModuleDeclared(t *testing.T) { // The same, for a module whose resources are computed elsewhere — that branch replaces the // module's resources wholesale, and merging in the wrong place would throw away its credentials. -func TestAComputedModuleStillGetsWhatTheMeshMadeForIt(t *testing.T) { +func testAComputedModuleStillGetsWhatTheMeshMadeForIt(t *testing.T) { r := mcat.Resolution{Modules: []mcat.Manifest{{ Module: "networking", Computed: "mesh-network", OwnSecrets: mcat.OwnSecrets{"key": {Path: "/var/lib/mesh/key"}}, @@ -253,7 +253,7 @@ func (computedOnce) Resources(string) ([]map[string]any, bool, error) { // binding carries what the provider said a consumer must know, which is the port. A build machine // sharing a node with the registry it pushes to sat in a loop saying it could not read its own // binding, because none was written. -func TestSomethingAnsweredOnThisMachineIsStillBound(t *testing.T) { +func testSomethingAnsweredOnThisMachineIsStillBound(t *testing.T) { r := mcat.Resolution{ Node: "anchor", At: "anchor.internal", Modules: []mcat.Manifest{ @@ -285,7 +285,7 @@ func TestSomethingAnsweredOnThisMachineIsStillBound(t *testing.T) { } // And a machine not on the private network still reaches itself. -func TestAMachineOffTheNetworkIsBoundToItselfByAnAddressThatWorks(t *testing.T) { +func testAMachineOffTheNetworkIsBoundToItselfByAnAddressThatWorks(t *testing.T) { r := mcat.Resolution{ Node: "alone", Modules: []mcat.Manifest{ @@ -325,7 +325,7 @@ func (cannotSay) Listens(string) ([]mcat.Listening, error) { // // Closing a port on the evidence of a failure to look is how a machine is severed by a fault // somewhere else entirely — and the machine it would sever is the hub. -func TestAGeneratorThatCannotSayRefusesTheRuleSet(t *testing.T) { +func testAGeneratorThatCannotSayRefusesTheRuleSet(t *testing.T) { _, err := Filtering(mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{{Module: "networking", Computed: "mesh-network"}}, }, map[string]mcat.Generator{"mesh-network": cannotSay{}}, nil, nil) @@ -342,7 +342,7 @@ func TestAGeneratorThatCannotSayRefusesTheRuleSet(t *testing.T) { // The case this exists for: a resolver restarting when the mesh rewrites the names. Those are // computed by the mesh and belong to its module, not to the daemon's — so without this the // daemon would serve the names it started with for ever, while every check reported success. -func TestAServiceCanReflectAnotherModulesFile(t *testing.T) { +func testAServiceCanReflectAnotherModulesFile(t *testing.T) { out, err := Declaration(mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{{ Module: "dnsmasq", Resources: []map[string]any{ @@ -387,7 +387,7 @@ func TestAServiceCanReflectAnotherModulesFile(t *testing.T) { // walks outward from what was assigned, which puts a consumer first — and a service that reads a // file another module writes then starts before the file exists, fails, and is fixed by the next // reconcile. That is the worst shape a fault can take: what gets remembered is that it works. -func TestWhatAnsweredARequirementIsAppliedFirst(t *testing.T) { +func testWhatAnsweredARequirementIsAppliedFirst(t *testing.T) { got, err := Resolve(map[string]mcat.Manifest{ "dnsmasq": {Module: "dnsmasq", Requires: []string{"resolver-data"}}, "data": {Module: "data", Provides: []mcat.Offer{{Name: "resolver-data"}}}, @@ -401,7 +401,7 @@ func TestWhatAnsweredARequirementIsAppliedFirst(t *testing.T) { } // Through a chain, not only one step: a machine applies what the thing it needs needs, first. -func TestAChainOfRequirementsIsAppliedFromTheBottom(t *testing.T) { +func testAChainOfRequirementsIsAppliedFromTheBottom(t *testing.T) { got, err := Resolve(map[string]mcat.Manifest{ "top": {Module: "top", Requires: []string{"middle-thing"}}, "middle": {Module: "middle", Provides: []mcat.Offer{{Name: "middle-thing"}}, Requires: []string{"bottom-thing"}}, @@ -419,7 +419,7 @@ func TestAChainOfRequirementsIsAppliedFromTheBottom(t *testing.T) { // Modules with no relation keep the order selection gave them — assigned first, then what they // pulled in. A sort that reshuffled unrelated modules would make every declaration's diff // unreadable for no gain. -func TestUnrelatedModulesKeepTheirOrder(t *testing.T) { +func testUnrelatedModulesKeepTheirOrder(t *testing.T) { got, err := Resolve(map[string]mcat.Manifest{ "one": {Module: "one"}, "two": {Module: "two"}, @@ -436,7 +436,7 @@ func TestUnrelatedModulesKeepTheirOrder(t *testing.T) { // Two modules requiring each other are both applied rather than refused: a cycle here is not a // machine that cannot work, and refusing would make a cooperating pair impossible to assign. -func TestTwoModulesRequiringEachOtherAreStillApplied(t *testing.T) { +func testTwoModulesRequiringEachOtherAreStillApplied(t *testing.T) { got, err := Resolve(map[string]mcat.Manifest{ "a": {Module: "a", Provides: []mcat.Offer{{Name: "from-a"}}, Requires: []string{"from-b"}}, "b": {Module: "b", Provides: []mcat.Offer{{Name: "from-b"}}, Requires: []string{"from-a"}}, @@ -460,7 +460,7 @@ func named(r mcat.Resolution) []string { // A port's source is a per-node setting, not a manifest constant: the same module is internal on // one machine and public on another (novox/hq ADR 0046). postgres listens from the mesh by default; // a setting on one node exposes it to anywhere, and the rule set follows. -func TestExposureSettingOverridesAListensSource(t *testing.T) { +func testExposureSettingOverridesAListensSource(t *testing.T) { postgres := mcat.Manifest{Module: "postgres", Version: "1", Listens: []mcat.Listening{{Port: 5432, From: mcat.FromMesh, Why: "the database"}}} @@ -484,7 +484,7 @@ func TestExposureSettingOverridesAListensSource(t *testing.T) { // Exposure refuses a setting that names a port the module does not listen on, or a source that is // not a real one — a setting reaching nothing is worse than none (novox/hq ADR 0043/0046). -func TestExposureRefusesAPortNotListenedOnAndABadSource(t *testing.T) { +func testExposureRefusesAPortNotListenedOnAndABadSource(t *testing.T) { postgres := mcat.Manifest{Module: "postgres", Listens: []mcat.Listening{{Port: 5432, From: mcat.FromMesh}}} layer := func(port, source string) []mcat.Layer { return []mcat.Layer{{From: "node", Placement: map[string]any{mcat.ExposeSetting: map[string]any{port: source}}}} @@ -500,3 +500,21 @@ func TestExposureRefusesAPortNotListenedOnAndABadSource(t *testing.T) { t.Error("a source that is not mesh/anywhere/machine was accepted") } } + +// TestFiltering runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFiltering(t *testing.T) { + t.Run("AMachineThatNamedNoOutwardLinkIsSentNoFilter", testAMachineThatNamedNoOutwardLinkIsSentNoFilter) + t.Run("TheModuleAskingForTheRuleSetGetsEveryModulesPorts", testTheModuleAskingForTheRuleSetGetsEveryModulesPorts) + t.Run("WhatTheMeshComputesIsAppliedBeforeWhatTheModuleDeclared", testWhatTheMeshComputesIsAppliedBeforeWhatTheModuleDeclared) + t.Run("AComputedModuleStillGetsWhatTheMeshMadeForIt", testAComputedModuleStillGetsWhatTheMeshMadeForIt) + t.Run("SomethingAnsweredOnThisMachineIsStillBound", testSomethingAnsweredOnThisMachineIsStillBound) + t.Run("AMachineOffTheNetworkIsBoundToItselfByAnAddressThatWorks", testAMachineOffTheNetworkIsBoundToItselfByAnAddressThatWorks) + t.Run("AGeneratorThatCannotSayRefusesTheRuleSet", testAGeneratorThatCannotSayRefusesTheRuleSet) + t.Run("AServiceCanReflectAnotherModulesFile", testAServiceCanReflectAnotherModulesFile) + t.Run("WhatAnsweredARequirementIsAppliedFirst", testWhatAnsweredARequirementIsAppliedFirst) + t.Run("AChainOfRequirementsIsAppliedFromTheBottom", testAChainOfRequirementsIsAppliedFromTheBottom) + t.Run("UnrelatedModulesKeepTheirOrder", testUnrelatedModulesKeepTheirOrder) + t.Run("TwoModulesRequiringEachOtherAreStillApplied", testTwoModulesRequiringEachOtherAreStillApplied) + t.Run("ExposureSettingOverridesAListensSource", testExposureSettingOverridesAListensSource) + t.Run("ExposureRefusesAPortNotListenedOnAndABadSource", testExposureRefusesAPortNotListenedOnAndABadSource) +} diff --git a/internal/compose/resolution/foundation_manifests_test.go b/internal/compose/resolution/foundation_manifests_test.go index f495d152..165874b6 100644 --- a/internal/compose/resolution/foundation_manifests_test.go +++ b/internal/compose/resolution/foundation_manifests_test.go @@ -36,7 +36,7 @@ func catalogueManifest(t *testing.T, module string) mcat.Manifest { return m } -func TestTheForgesPortIsGivenLikeAnyOtherProvidersPort(t *testing.T) { +func testTheForgesPortIsGivenLikeAnyOtherProvidersPort(t *testing.T) { forge := catalogueManifest(t, "gitea") // The catalogue's number is a default and the node's setting moves it. @@ -66,7 +66,7 @@ func TestTheForgesPortIsGivenLikeAnyOtherProvidersPort(t *testing.T) { // The forge holds the seats it answers for (novox/hq ADR 0110, 0111), parsed by the real parser — // which refuses a delivering seat claimed by a module that does not provide what it delivers. -func TestTheForgeHoldsTheNpmAndGitSeats(t *testing.T) { +func testTheForgeHoldsTheNpmAndGitSeats(t *testing.T) { forge := catalogueManifest(t, "gitea") holds := map[string]bool{} for _, c := range forge.Claims { @@ -96,7 +96,7 @@ func TestTheForgeHoldsTheNpmAndGitSeats(t *testing.T) { // wrong on every node whose assignment differs, and wrong for a second reason on a node given the // port (ADR 0100). Composed through the whole path, because what proves the placeholder resolves // in an `env` at all is a declaration, not a manifest. -func TestTheForgesOwnAddressFollowsThePortTheNodeGaveIt(t *testing.T) { +func testTheForgesOwnAddressFollowsThePortTheNodeGaveIt(t *testing.T) { forge, err := catalogueManifest(t, "gitea").Resolve(forgeBuilt(catalogueManifest(t, "gitea"))) if err != nil { t.Fatalf("the forge's manifest does not resolve against its own build: %v", err) @@ -187,7 +187,7 @@ func declaredGiteaSsh(t *testing.T, given map[int]int) map[string]any { // `222` is the mesh's own public convention for the forge's ssh, written directly in the // manifest's `ports` — every node the forge has run on used the same number, so it needs no // per-node setting to reach it. -func TestTheForgesSshPortIsTheMeshsFixedConventionByDefault(t *testing.T) { +func testTheForgesSshPortIsTheMeshsFixedConventionByDefault(t *testing.T) { forge := catalogueManifest(t, "gitea") // Nothing was given — no node moved this port — which is the ordinary answer: the mesh only // reports what a setting moved, and the manifest's own `222:22` needs no move to be reached. @@ -208,7 +208,7 @@ func TestTheForgesSshPortIsTheMeshsFixedConventionByDefault(t *testing.T) { // there.** The setting names the port the module itself listens on — 22, gitea's own sshd, the // same number `listens` uses — not the mesh's own default machine-side number, so moving it does // not require guessing what the manifest happens to default to. -func TestANodeMayGiveTheForgesSshPortADifferentNumber(t *testing.T) { +func testANodeMayGiveTheForgesSshPortADifferentNumber(t *testing.T) { forge := catalogueManifest(t, "gitea") given, err := GivenPorts(forge, []mcat.Layer{{From: "anchor", Placement: map[string]any{mcat.PortsSetting: map[string]any{"22": float64(9022)}}}}) @@ -268,3 +268,12 @@ func catalogueResolved(t *testing.T, module string, built ...mcat.Built) mcat.Ma } return held } + +// TestFoundationManifests runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFoundationManifests(t *testing.T) { + t.Run("TheForgesPortIsGivenLikeAnyOtherProvidersPort", testTheForgesPortIsGivenLikeAnyOtherProvidersPort) + t.Run("TheForgeHoldsTheNpmAndGitSeats", testTheForgeHoldsTheNpmAndGitSeats) + t.Run("TheForgesOwnAddressFollowsThePortTheNodeGaveIt", testTheForgesOwnAddressFollowsThePortTheNodeGaveIt) + t.Run("TheForgesSshPortIsTheMeshsFixedConventionByDefault", testTheForgesSshPortIsTheMeshsFixedConventionByDefault) + t.Run("ANodeMayGiveTheForgesSshPortADifferentNumber", testANodeMayGiveTheForgesSshPortADifferentNumber) +} diff --git a/internal/compose/resolution/generated_collision_test.go b/internal/compose/resolution/generated_collision_test.go index 58d46d36..d502f7ca 100644 --- a/internal/compose/resolution/generated_collision_test.go +++ b/internal/compose/resolution/generated_collision_test.go @@ -16,7 +16,7 @@ func runtimesOwn() mcat.Manifest { }} } -func TestAGeneratedResourceCollidingWithAModulesIsRefused(t *testing.T) { +func testAGeneratedResourceCollidingWithAModulesIsRefused(t *testing.T) { r := mcat.Resolution{Node: "workstation", Modules: []mcat.Manifest{ {Module: "mesh-network", Computed: "mesh-network", Provides: mcat.Offers("private-network")}, runtimesOwn(), @@ -32,7 +32,7 @@ func TestAGeneratedResourceCollidingWithAModulesIsRefused(t *testing.T) { } } -func TestAGeneratedResourceBesideAModulesOwnIsComposed(t *testing.T) { +func testAGeneratedResourceBesideAModulesOwnIsComposed(t *testing.T) { r := mcat.Resolution{Node: "workstation", Modules: []mcat.Manifest{ {Module: "mesh-network", Computed: "mesh-network", Provides: mcat.Offers("private-network")}, runtimesOwn(), @@ -52,7 +52,7 @@ func TestAGeneratedResourceBesideAModulesOwnIsComposed(t *testing.T) { } // The catalogue's container runtime module states the mesh's registry itself (ADR 0222). -func TestTheRuntimesModuleTrustsTheMeshsRegistry(t *testing.T) { +func testTheRuntimesModuleTrustsTheMeshsRegistry(t *testing.T) { docker := catalogueManifest(t, "docker") r := mcat.Resolution{Node: "workstation", Modules: []mcat.Manifest{docker}} out, err := Declaration(r, mcat.Rendering{ @@ -81,3 +81,10 @@ func TestTheRuntimesModuleTrustsTheMeshsRegistry(t *testing.T) { t.Fatalf("with no store on the network, the runtime is told %q", content) } } + +// TestGeneratedCollision runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestGeneratedCollision(t *testing.T) { + t.Run("AGeneratedResourceCollidingWithAModulesIsRefused", testAGeneratedResourceCollidingWithAModulesIsRefused) + t.Run("AGeneratedResourceBesideAModulesOwnIsComposed", testAGeneratedResourceBesideAModulesOwnIsComposed) + t.Run("TheRuntimesModuleTrustsTheMeshsRegistry", testTheRuntimesModuleTrustsTheMeshsRegistry) +} diff --git a/internal/compose/resolution/grant_secret_owner_test.go b/internal/compose/resolution/grant_secret_owner_test.go index 37f1142c..c31f0a43 100644 --- a/internal/compose/resolution/grant_secret_owner_test.go +++ b/internal/compose/resolution/grant_secret_owner_test.go @@ -23,7 +23,7 @@ func aProviderWithABundle() mcat.Manifest { } } -func TestAGrantSecretIsOwnedByTheAccountThatProvisions(t *testing.T) { +func testAGrantSecretIsOwnedByTheAccountThatProvisions(t *testing.T) { r, err := Resolve(shelf(aProviderWithABundle()), []string{"mongodb"}, reachable(), mcat.World{}) if err != nil { t.Fatal(err) @@ -72,7 +72,7 @@ func TestAGrantSecretIsOwnedByTheAccountThatProvisions(t *testing.T) { // And a provider whose code still runs in a container keeps the owner it declares, so this // changes nothing for the modules the runtime has not taken. -func TestAContainerProvidersGrantSecretKeepsItsDeclaredOwner(t *testing.T) { +func testAContainerProvidersGrantSecretKeepsItsDeclaredOwner(t *testing.T) { m := aProviderWithABundle() m.Bundles = nil m.SecretsOwner = "65534:65534" @@ -103,3 +103,9 @@ func fmtPath(r map[string]any) string { p, _ := r["path"].(string) return p } + +// TestGrantSecretOwner runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestGrantSecretOwner(t *testing.T) { + t.Run("AGrantSecretIsOwnedByTheAccountThatProvisions", testAGrantSecretIsOwnedByTheAccountThatProvisions) + t.Run("AContainerProvidersGrantSecretKeepsItsDeclaredOwner", testAContainerProvidersGrantSecretKeepsItsDeclaredOwner) +} diff --git a/internal/compose/resolution/graphical_session_test.go b/internal/compose/resolution/graphical_session_test.go index a5d94465..828d097f 100644 --- a/internal/compose/resolution/graphical_session_test.go +++ b/internal/compose/resolution/graphical_session_test.go @@ -21,7 +21,7 @@ func windowManager() mcat.Manifest { } // §3: a display is resolved on the requiring module's own node. -func TestAMachineReachRequirementResolvesToTheProviderOnItsOwnNode(t *testing.T) { +func testAMachineReachRequirementResolvesToTheProviderOnItsOwnNode(t *testing.T) { cat := shelf(windowManager(), displayServer("xorg", "x11-display", mcat.DisplayServerSeat)) got, err := Resolve(cat, []string{"xorg", "i3"}, workstation(), mcat.World{}) if err != nil { @@ -33,7 +33,7 @@ func TestAMachineReachRequirementResolvesToTheProviderOnItsOwnNode(t *testing.T) } // §3: never answered by installing a provider, and never by another machine's. -func TestAMachineReachRequirementIsNotPulledInNorAnsweredFromAnotherNode(t *testing.T) { +func testAMachineReachRequirementIsNotPulledInNorAnsweredFromAnotherNode(t *testing.T) { cat := shelf(windowManager(), displayServer("xorg", "x11-display", mcat.DisplayServerSeat), displayServer("xwayland", "x11-display")) @@ -65,10 +65,17 @@ func TestAMachineReachRequirementIsNotPulledInNorAnsweredFromAnotherNode(t *test } } -func TestACatalogueDisagreeingAboutAProvisionsReachIsRefused(t *testing.T) { +func testACatalogueDisagreeingAboutAProvisionsReachIsRefused(t *testing.T) { cat := shelf(windowManager(), displayServer("xorg", "x11-display"), mcat.Manifest{Module: "fake-x", Provides: mcat.Offers("x11-display")}) _, err := Resolve(cat, []string{"xorg", "i3"}, workstation(), mcat.World{}) if err == nil || !strings.Contains(err.Error(), `the catalogue disagrees about "x11-display"`) { t.Fatalf("a provision with and without the machine's reach gave %v", err) } } + +// TestGraphicalSession runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestGraphicalSession(t *testing.T) { + t.Run("AMachineReachRequirementResolvesToTheProviderOnItsOwnNode", testAMachineReachRequirementResolvesToTheProviderOnItsOwnNode) + t.Run("AMachineReachRequirementIsNotPulledInNorAnsweredFromAnotherNode", testAMachineReachRequirementIsNotPulledInNorAnsweredFromAnotherNode) + t.Run("ACatalogueDisagreeingAboutAProvisionsReachIsRefused", testACatalogueDisagreeingAboutAProvisionsReachIsRefused) +} diff --git a/internal/compose/resolution/groups_test.go b/internal/compose/resolution/groups_test.go index c1d299d3..8489dfe9 100644 --- a/internal/compose/resolution/groups_test.go +++ b/internal/compose/resolution/groups_test.go @@ -14,7 +14,7 @@ func aContainerWithGroups(groups ...any) map[string]any { } // 1636/AC3: a manifest container with groups: ["${setting:media-gid}"] resolves to the number the setting says. -func TestAContainersGroupIsFilledFromTheSetting(t *testing.T) { +func testAContainersGroupIsFilledFromTheSetting(t *testing.T) { r := aContainerWithGroups("${setting:media-gid}", float64(2001)) layers := []mcat.Layer{{From: "ace", Values: map[string]any{"media-gid": float64(2000)}}} if err := settingInto(r, layers, "n8n"); err != nil { @@ -34,7 +34,7 @@ func TestAContainersGroupIsFilledFromTheSetting(t *testing.T) { } // 1636/AC3: an unset value refuses the module by name, and the key and the remedy are named; nothing is dropped. -func TestAnUnsetGroupRefusesTheModuleByName(t *testing.T) { +func testAnUnsetGroupRefusesTheModuleByName(t *testing.T) { r := aContainerWithGroups("${setting:media-gid}") err := settingInto(r, nil, "n8n") if err == nil || !strings.Contains(err.Error(), "n8n") || !strings.Contains(err.Error(), "media-gid") { @@ -46,7 +46,7 @@ func TestAnUnsetGroupRefusesTheModuleByName(t *testing.T) { } // 1636/AC2: a value that is not a whole number above zero cannot be a group. -func TestAGroupThatIsNotAWholeNumberAboveZeroIsRefused(t *testing.T) { +func testAGroupThatIsNotAWholeNumberAboveZeroIsRefused(t *testing.T) { for _, bad := range []any{"media", "-1", "0", float64(0), float64(2000.5), "2000:2000", "", true} { r := aContainerWithGroups("${setting:media-gid}") err := settingInto(r, []mcat.Layer{{From: "ace", Values: map[string]any{"media-gid": bad}}}, "n8n") @@ -58,7 +58,7 @@ func TestAGroupThatIsNotAWholeNumberAboveZeroIsRefused(t *testing.T) { // 1636/AC3 composed for a machine, the way a push writes it: n8n's group is the number the machine's config value // says, written as a number, and the module is left out by name when the machine says none. -func TestAComposedMachineGetsTheGroupTheConfigValueNames(t *testing.T) { +func testAComposedMachineGetsTheGroupTheConfigValueNames(t *testing.T) { manifest, err := parseRaw(t, map[string]any{ "module": "n8n", "version": "1", "config": map[string]any{"media-gid": map[string]any{"type": "number", "minimum": 1, "required": true, @@ -98,7 +98,7 @@ func TestAComposedMachineGetsTheGroupTheConfigValueNames(t *testing.T) { // The node-engine reads a container's groups only when it reports the capability (novox/hq ADR 0480 clause 7, issue 1638): // a module with a container that names groups is hosted on a machine that reports container-groups, and left out of one // that does not, the capability named, so the field is never sent to an engine that would refuse it. -func TestAModuleWhoseContainerNamesGroupsIsHeldOnAMachineThatDoesNotReadThem(t *testing.T) { +func testAModuleWhoseContainerNamesGroupsIsHeldOnAMachineThatDoesNotReadThem(t *testing.T) { n8n := mcat.Manifest{Module: "n8n", Resources: []map[string]any{aContainerWithGroups("${config:media-gid}")}} plain := mcat.Manifest{Module: "plain", Resources: []map[string]any{ {"id": "server", "type": "container", "name": "p", "image": "x@sha256:" + strings.Repeat("b", 64)}}} @@ -125,3 +125,12 @@ func TestAModuleWhoseContainerNamesGroupsIsHeldOnAMachineThatDoesNotReadThem(t * t.Errorf("the module without groups is not the one hosted: %v", h) } } + +// TestGroups runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestGroups(t *testing.T) { + t.Run("AContainersGroupIsFilledFromTheSetting", testAContainersGroupIsFilledFromTheSetting) + t.Run("AnUnsetGroupRefusesTheModuleByName", testAnUnsetGroupRefusesTheModuleByName) + t.Run("AGroupThatIsNotAWholeNumberAboveZeroIsRefused", testAGroupThatIsNotAWholeNumberAboveZeroIsRefused) + t.Run("AComposedMachineGetsTheGroupTheConfigValueNames", testAComposedMachineGetsTheGroupTheConfigValueNames) + t.Run("AModuleWhoseContainerNamesGroupsIsHeldOnAMachineThatDoesNotReadThem", testAModuleWhoseContainerNamesGroupsIsHeldOnAMachineThatDoesNotReadThem) +} diff --git a/internal/compose/resolution/handed_bound_test.go b/internal/compose/resolution/handed_bound_test.go index a74af229..a0408824 100644 --- a/internal/compose/resolution/handed_bound_test.go +++ b/internal/compose/resolution/handed_bound_test.go @@ -47,7 +47,7 @@ func withDatabase(t *testing.T, raw, text string, moved bool) mcat.Resolution { // The forge's server.env composes for a handed module when what it requires has moved, its plan entry carrying the // provider's address, machine and the consumer's identity as today's binding file gives them; and is refused with the // text it has always had when the provider has not. -func TestAHandedModuleMayNameWhatItRequiresWhereItsProviderHasMoved(t *testing.T) { +func testAHandedModuleMayNameWhatItRequiresWhereItsProviderHasMoved(t *testing.T) { c, got := composeWith(t, databaseConsumer(t, "", true), handingTo("store:5000")) if strings.Contains(got, "sealed") { t.Fatalf("a handed module's declaration carries a sealed value: %s", got) @@ -79,7 +79,7 @@ func TestAHandedModuleMayNameWhatItRequiresWhereItsProviderHasMoved(t *testing.T // A handed module's credentials the vault keeps as one login per local name (issue 793): gitea's internal token and // admin password, which the `secret` provision hands as `${secret:}`. Each is a plan entry naming its local, // its file declared placed and without a value; the template naming the local is allowed. -func TestAHandedModulesLocalCredentialsOfTheVaultAreNamedByLocalInItsPlan(t *testing.T) { +func testAHandedModulesLocalCredentialsOfTheVaultAreNamedByLocalInItsPlan(t *testing.T) { raw := strings.Replace(botMoved(), `"own-secrets":{"token":"${dir:state}/token"}`, `"requires":["secret"],"secrets":{"secret":{"internal-token":"${dir:state}/internal-token.secret",`+ `"admin":"${dir:state}/admin.secret"}},"own-secrets":{"token":"${dir:state}/token"}`, 1) @@ -117,7 +117,7 @@ func TestAHandedModulesLocalCredentialsOfTheVaultAreNamedByLocalInItsPlan(t *tes // 1966); where it does not the node-engine must fill it from what the provider serves statically, cannot, and refuses // it as a handed module not handed, saying why the machine does not take it (issue 1966), where an unmarked module is // refused with the keys the binding says and that it is not moved. -func TestAHandedModuleNamingARunTimeBoundKeyComposesOnlyWhereItIsHanded(t *testing.T) { +func testAHandedModuleNamingARunTimeBoundKeyComposesOnlyWhereItIsHanded(t *testing.T) { text := "Host ${bound:postgres-database:at}\n KnownHost ${bound:postgres-database:known_host}\n" moved := strings.Replace(botMoved(), `"own-secrets":{"token":"${dir:state}/token"}`, `"requires":["postgres-database"],"own-secrets":{"token":"${dir:state}/token"}`, 1) @@ -166,3 +166,10 @@ func TestAHandedModuleNamingARunTimeBoundKeyComposesOnlyWhereItIsHanded(t *testi t.Errorf("the impossible branch says %q (handed file %v)", why, handedFile) } } + +// TestHandedBound runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestHandedBound(t *testing.T) { + t.Run("AHandedModuleMayNameWhatItRequiresWhereItsProviderHasMoved", testAHandedModuleMayNameWhatItRequiresWhereItsProviderHasMoved) + t.Run("AHandedModulesLocalCredentialsOfTheVaultAreNamedByLocalInItsPlan", testAHandedModulesLocalCredentialsOfTheVaultAreNamedByLocalInItsPlan) + t.Run("AHandedModuleNamingARunTimeBoundKeyComposesOnlyWhereItIsHanded", testAHandedModuleNamingARunTimeBoundKeyComposesOnlyWhereItIsHanded) +} diff --git a/internal/compose/resolution/handed_providers_test.go b/internal/compose/resolution/handed_providers_test.go index 7ae1a41f..1ef10252 100644 --- a/internal/compose/resolution/handed_providers_test.go +++ b/internal/compose/resolution/handed_providers_test.go @@ -52,7 +52,7 @@ func consumerOn(t *testing.T, m mcat.Manifest, w mcat.World) mcat.Resolution { // binding file names as `${bound::name|internal-name|name-|internal-name-}`, so a moved // provider's helper copies them into the consumer's entry and the client fills the same text. A consumer // contributing no label has the entry it had. -func TestAHandedModulesPlanEntryCarriesTheNamesComposedForIt(t *testing.T) { +func testAHandedModulesPlanEntryCarriesTheNamesComposedForIt(t *testing.T) { m := notifierConsumer(t, true, false) m.ContributesMany = map[string]map[string]map[string]any{ "postgres-database": {"web": {"label": "git"}, "api": {"label": "git-api"}}} @@ -82,7 +82,7 @@ func TestAHandedModulesPlanEntryCarriesTheNamesComposedForIt(t *testing.T) { // A plan entry names the tool of an offer whose credential the provider's software issues (issue 928), so the vault // asks that tool for each holder; an offer of any other form names none. -func TestAHandedModulesPlanNamesTheCredentialToolOfASoftwareIssuedOffer(t *testing.T) { +func testAHandedModulesPlanNamesTheCredentialToolOfASoftwareIssuedOffer(t *testing.T) { for credential, want := range map[string]string{ ``: "", `,"credential":{"own":"admin"}`: "", @@ -109,3 +109,9 @@ func TestAHandedModulesPlanNamesTheCredentialToolOfASoftwareIssuedOffer(t *testi } } } + +// TestHandedProviders runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestHandedProviders(t *testing.T) { + t.Run("AHandedModulesPlanEntryCarriesTheNamesComposedForIt", testAHandedModulesPlanEntryCarriesTheNamesComposedForIt) + t.Run("AHandedModulesPlanNamesTheCredentialToolOfASoftwareIssuedOffer", testAHandedModulesPlanNamesTheCredentialToolOfASoftwareIssuedOffer) +} diff --git a/internal/compose/resolution/health_test.go b/internal/compose/resolution/health_test.go index e7bb79ba..184b4e0e 100644 --- a/internal/compose/resolution/health_test.go +++ b/internal/compose/resolution/health_test.go @@ -41,7 +41,7 @@ func healthManifest(t *testing.T, on string, health map[string]any, more ...map[ return raw } -func TestHealthIsComposedAsThePortThisMachineGaveTheEndpoint(t *testing.T) { +func testHealthIsComposedAsThePortThisMachineGaveTheEndpoint(t *testing.T) { m, err := decodeForTest(healthManifest(t, "server", map[string]any{"kind": "http", "endpoint": "web", "path": "/healthz", "needs": "postgres-database"})) if err != nil { @@ -82,7 +82,7 @@ func TestHealthIsComposedAsThePortThisMachineGaveTheEndpoint(t *testing.T) { // What the controller composes the node-engine takes: every kind, composed for an engine that reads it, // passes the engine's own validator (mesh-host/validate) — one set of words on both sides. -func TestEveryComposedHealthIsOneTheNodeEngineTakes(t *testing.T) { +func testEveryComposedHealthIsOneTheNodeEngineTakes(t *testing.T) { for _, h := range []map[string]any{ {"kind": "http", "endpoint": "web", "path": "/healthz", "status": 200, "body": "ok", "needs": "postgres-database"}, {"kind": "tcp", "endpoint": "web", "interval": "10s", "timeout": "2s", "looks": 2, "grace": "0s"}, @@ -102,3 +102,9 @@ func TestEveryComposedHealthIsOneTheNodeEngineTakes(t *testing.T) { } } } + +// TestHealth runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestHealth(t *testing.T) { + t.Run("HealthIsComposedAsThePortThisMachineGaveTheEndpoint", testHealthIsComposedAsThePortThisMachineGaveTheEndpoint) + t.Run("EveryComposedHealthIsOneTheNodeEngineTakes", testEveryComposedHealthIsOneTheNodeEngineTakes) +} diff --git a/internal/compose/resolution/holdings_test.go b/internal/compose/resolution/holdings_test.go index 953111bb..824f7bca 100644 --- a/internal/compose/resolution/holdings_test.go +++ b/internal/compose/resolution/holdings_test.go @@ -25,7 +25,7 @@ func newBroker() mcat.Manifest { } // Nothing on record: exactly the old rule. One claimant holds; two are refused. -func TestWithNoHolderOnRecordTheSoleClaimantHoldsAndTwoAreRefused(t *testing.T) { +func testWithNoHolderOnRecordTheSoleClaimantHoldsAndTwoAreRefused(t *testing.T) { busSeatDelivering(t, "mesh-bus") node := mcat.Node{Name: "anchor"} @@ -45,7 +45,7 @@ func TestWithNoHolderOnRecordTheSoleClaimantHoldsAndTwoAreRefused(t *testing.T) } // With a holder on record, the other eligible assignment is silent: not refused, and not holding. -func TestTheHolderOnRecordHoldsAndTheOtherClaimantStandsBesideIt(t *testing.T) { +func testTheHolderOnRecordHoldsAndTheOtherClaimantStandsBesideIt(t *testing.T) { busSeatDelivering(t, "mesh-bus") node := mcat.Node{Name: "anchor"} record := []mcat.Held{{Claim: "mesh-broker", Scope: mcat.ScopeMesh, Node: "anchor", Module: "new-broker"}} @@ -61,7 +61,7 @@ func TestTheHolderOnRecordHoldsAndTheOtherClaimantStandsBesideIt(t *testing.T) { // The record names a node too: an eligible module on another machine holds nothing, and its // machine's set still resolves. -func TestAHolderOnRecordElsewhereLeavesThisMachinesClaimantSilent(t *testing.T) { +func testAHolderOnRecordElsewhereLeavesThisMachinesClaimantSilent(t *testing.T) { busSeatDelivering(t, "mesh-bus") record := []mcat.Held{{Claim: "mesh-broker", Scope: mcat.ScopeMesh, Node: "anchor", Module: "new-broker"}} @@ -74,7 +74,7 @@ func TestAHolderOnRecordElsewhereLeavesThisMachinesClaimantSilent(t *testing.T) // A machine being moved is handed its membership for the new bus as a sealed file in its own // declaration — the machine's, not any module's (design 28, task 5.2). -func TestAMembershipForTheNewBusIsComposedAsASealedFile(t *testing.T) { +func testAMembershipForTheNewBusIsComposedAsASealedFile(t *testing.T) { r := mcat.Resolution{Node: "anchor"} got, err := Compose(r, mcat.Rendering{BusMembership: "sealed-blob"}) if err != nil { @@ -101,7 +101,7 @@ func TestAMembershipForTheNewBusIsComposedAsASealedFile(t *testing.T) { } } -func TestARefusalWithNothingOnRecordNamesTheHandover(t *testing.T) { +func testARefusalWithNothingOnRecordNamesTheHandover(t *testing.T) { busSeatDelivering(t, "mesh-bus") elsewhere := []mcat.Held{{Claim: "mesh-broker", Scope: mcat.ScopeMesh, Node: "anchor", Module: "old-broker"}} @@ -126,3 +126,12 @@ func brokerVerbs() []string { } return out } + +// TestHoldings runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestHoldings(t *testing.T) { + t.Run("WithNoHolderOnRecordTheSoleClaimantHoldsAndTwoAreRefused", testWithNoHolderOnRecordTheSoleClaimantHoldsAndTwoAreRefused) + t.Run("TheHolderOnRecordHoldsAndTheOtherClaimantStandsBesideIt", testTheHolderOnRecordHoldsAndTheOtherClaimantStandsBesideIt) + t.Run("AHolderOnRecordElsewhereLeavesThisMachinesClaimantSilent", testAHolderOnRecordElsewhereLeavesThisMachinesClaimantSilent) + t.Run("AMembershipForTheNewBusIsComposedAsASealedFile", testAMembershipForTheNewBusIsComposedAsASealedFile) + t.Run("ARefusalWithNothingOnRecordNamesTheHandover", testARefusalWithNothingOnRecordNamesTheHandover) +} diff --git a/internal/compose/resolution/jails_into_test.go b/internal/compose/resolution/jails_into_test.go index a42cd7eb..98905eb8 100644 --- a/internal/compose/resolution/jails_into_test.go +++ b/internal/compose/resolution/jails_into_test.go @@ -9,7 +9,7 @@ import ( // A node's fail2ban jails are composed from the modules it runs (novox/hq to-be 31): the holder // (jailing) gathers every module's declared jail into one jail file and a filter file per jail. -func TestJailsAreComposedFromTheNodesModules(t *testing.T) { +func testJailsAreComposedFromTheNodesModules(t *testing.T) { modules := []mcat.Manifest{ {Module: "fail2ban", Jailing: &mcat.Jailing{Into: "/etc/fail2ban/jail.d/mesh-composed.conf", FilterInto: "/etc/fail2ban/filter.d"}}, {Module: "postgres", Jails: []mcat.Jail{{Name: "postgres-auth", Failregex: "auth failed from ", Jail: "port = 5432\nmaxretry = 5"}}}, @@ -40,7 +40,7 @@ func TestJailsAreComposedFromTheNodesModules(t *testing.T) { // A holder whose node runs no jail-declaring module still gets the file, empty — so removing the // last jail is a change the service restarts on, not a file that vanishes. -func TestTheComposedJailFileIsWrittenEvenWhenEmpty(t *testing.T) { +func testTheComposedJailFileIsWrittenEvenWhenEmpty(t *testing.T) { files := jailsInto([]mcat.Manifest{{Module: "fail2ban"}}, &mcat.Jailing{Into: "/x", FilterInto: "/f"}) if len(files) != 1 || files[0]["id"] != mcat.ComposedJailsID() { t.Fatalf("the empty composed jail file was not written alone: %v", files) @@ -50,7 +50,7 @@ func TestTheComposedJailFileIsWrittenEvenWhenEmpty(t *testing.T) { // A changed pattern restarts fail2ban (novox/hq issue 191's rollout): the service restarts when the // composed jail file changes, and the filter is a file of its own, so the jail file names the // filter's digest. Changing only the failregex must change the jail file; the same pattern must not. -func TestAChangedFilterChangesTheJailFile(t *testing.T) { +func testAChangedFilterChangesTheJailFile(t *testing.T) { jailFile := func(failregex string) string { modules := []mcat.Manifest{ {Module: "fail2ban", Jailing: &mcat.Jailing{Into: "/etc/fail2ban/jail.d/mesh.conf", FilterInto: "/etc/fail2ban/filter.d"}}, @@ -72,3 +72,10 @@ func TestAChangedFilterChangesTheJailFile(t *testing.T) { t.Errorf("a changed pattern left the jail file as it was, so fail2ban keeps the old filter:\n%s", after) } } + +// TestJailsInto runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestJailsInto(t *testing.T) { + t.Run("JailsAreComposedFromTheNodesModules", testJailsAreComposedFromTheNodesModules) + t.Run("TheComposedJailFileIsWrittenEvenWhenEmpty", testTheComposedJailFileIsWrittenEvenWhenEmpty) + t.Run("AChangedFilterChangesTheJailFile", testAChangedFilterChangesTheJailFile) +} diff --git a/internal/compose/resolution/licence_test.go b/internal/compose/resolution/licence_test.go index 64bea19d..2082e098 100644 --- a/internal/compose/resolution/licence_test.go +++ b/internal/compose/resolution/licence_test.go @@ -19,7 +19,7 @@ func aModelUser() mcat.Manifest { // internet, so the rule that refuses two ends sharing no private network must not apply. This // node is deliberately not on the private network at all — under the old rule that alone would // refuse it. -func TestAProvisionAnsweredByARecordDoesNotNeedAPrivateNetwork(t *testing.T) { +func testAProvisionAnsweredByARecordDoesNotNeedAPrivateNetwork(t *testing.T) { got, err := Resolve( map[string]mcat.Manifest{"assistant": aModelUser()}, []string{"assistant"}, mcat.Node{Name: "workstation"}, mcat.World{ @@ -45,7 +45,7 @@ func TestAProvisionAnsweredByARecordDoesNotNeedAPrivateNetwork(t *testing.T) { // Refused when the consumer has not said which — and the refusal names the candidates and the // command, because ADR 0024 warns this will be felt: a mesh holding three ways to reach a model // refuses every consumer that has not chosen. -func TestAConsumerThatHasNotSaidWhichLicenceIsRefusedWithTheCandidates(t *testing.T) { +func testAConsumerThatHasNotSaidWhichLicenceIsRefusedWithTheCandidates(t *testing.T) { _, err := Resolve( map[string]mcat.Manifest{"assistant": aModelUser()}, []string{"assistant"}, mcat.Node{Name: "workstation"}, mcat.World{Licences: map[string][]mcat.Record{"model-access": { @@ -63,7 +63,7 @@ func TestAConsumerThatHasNotSaidWhichLicenceIsRefusedWithTheCandidates(t *testin } // A model the mesh runs itself answers it locally, and a record is not consulted. -func TestAModelInTheMeshsOwnSetAnswersItWithoutALicence(t *testing.T) { +func testAModelInTheMeshsOwnSetAnswersItWithoutALicence(t *testing.T) { got, err := Resolve( map[string]mcat.Manifest{ "assistant": aModelUser(), @@ -85,7 +85,7 @@ func TestAModelInTheMeshsOwnSetAnswersItWithoutALicence(t *testing.T) { // // The mesh discarded the plaintext when the key was accepted and cannot seal another, so a // machine that resolved cleanly would receive no file and fail at whatever read it. -func TestAModuleOnALicenceWithNoKeyIsRefusedRatherThanLeftEmpty(t *testing.T) { +func testAModuleOnALicenceWithNoKeyIsRefusedRatherThanLeftEmpty(t *testing.T) { r := mcat.Resolution{ Node: "workstation", Modules: []mcat.Manifest{aModelUser()}, @@ -101,7 +101,7 @@ func TestAModuleOnALicenceWithNoKeyIsRefusedRatherThanLeftEmpty(t *testing.T) { } // And with a key, both files arrive: what is public, and what is not. -func TestALicenceDeliversWhatIsPublicAndWhatIsSealed(t *testing.T) { +func testALicenceDeliversWhatIsPublicAndWhatIsSealed(t *testing.T) { r := mcat.Resolution{ Node: "workstation", Modules: []mcat.Manifest{aModelUser()}, @@ -151,7 +151,7 @@ func TestALicenceDeliversWhatIsPublicAndWhatIsSealed(t *testing.T) { // nothing — so refusing an unanswerable requirement there makes the machine disappear, and every // other machine is then told, wrongly, that the two of them share no network. A wrong answer about // a machine nobody asked about, caused by a fault on a third. -func TestAnUnanswerableRequirementDoesNotRemoveAMachineFromTheMesh(t *testing.T) { +func testAnUnanswerableRequirementDoesNotRemoveAMachineFromTheMesh(t *testing.T) { shelf := map[string]mcat.Manifest{ "assistant": aModelUser(), "networking": {Module: "networking", @@ -187,7 +187,7 @@ func TestAnUnanswerableRequirementDoesNotRemoveAMachineFromTheMesh(t *testing.T) // consumer's needs — node scope set `local`, not `brokered`, so the delivering branch was skipped — // and the consumer's file was refused for naming a provision it "did not require". The endpoint is // keyless, but a port is still a fact nobody can invent. -func TestAKeylessSameNodeProviderStillDeliversWhatItServes(t *testing.T) { +func testAKeylessSameNodeProviderStillDeliversWhatItServes(t *testing.T) { provider := mcat.Manifest{Module: "local-model", Provides: []mcat.Offer{{Name: "model-access", Scope: mcat.ScopeNode}}, Serves: map[string]map[string]any{ @@ -257,3 +257,14 @@ func TestAKeylessSameNodeProviderStillDeliversWhatItServes(t *testing.T) { t.Fatalf("the bound file was not filled with the served endpoint, want %q:\n%s", want, env) } } + +// TestLicence runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestLicence(t *testing.T) { + t.Run("AProvisionAnsweredByARecordDoesNotNeedAPrivateNetwork", testAProvisionAnsweredByARecordDoesNotNeedAPrivateNetwork) + t.Run("AConsumerThatHasNotSaidWhichLicenceIsRefusedWithTheCandidates", testAConsumerThatHasNotSaidWhichLicenceIsRefusedWithTheCandidates) + t.Run("AModelInTheMeshsOwnSetAnswersItWithoutALicence", testAModelInTheMeshsOwnSetAnswersItWithoutALicence) + t.Run("AModuleOnALicenceWithNoKeyIsRefusedRatherThanLeftEmpty", testAModuleOnALicenceWithNoKeyIsRefusedRatherThanLeftEmpty) + t.Run("ALicenceDeliversWhatIsPublicAndWhatIsSealed", testALicenceDeliversWhatIsPublicAndWhatIsSealed) + t.Run("AnUnanswerableRequirementDoesNotRemoveAMachineFromTheMesh", testAnUnanswerableRequirementDoesNotRemoveAMachineFromTheMesh) + t.Run("AKeylessSameNodeProviderStillDeliversWhatItServes", testAKeylessSameNodeProviderStillDeliversWhatItServes) +} diff --git a/internal/compose/resolution/localnetwork_test.go b/internal/compose/resolution/localnetwork_test.go index 8fe35db7..737db46b 100644 --- a/internal/compose/resolution/localnetwork_test.go +++ b/internal/compose/resolution/localnetwork_test.go @@ -25,7 +25,7 @@ func judged(t *testing.T) []mcat.LocalNetwork { // **A public subnet never counts** (ADR 0340 §2), and only a private one on a link facing outside does // (§3): the tunnel's and a bridge's are this machine's own, whatever their addresses. -func TestOnlyAPrivateNetworkOnALinkFacingOutsideCounts(t *testing.T) { +func testOnlyAPrivateNetworkOnALinkFacingOutsideCounts(t *testing.T) { got := CountedLocalNetworks(judged(t)) want := []string{"192.168.1.0/24", "fd12:3456:789a::/64"} if strings.Join(got, " ") != strings.Join(want, " ") { @@ -79,7 +79,7 @@ func TestOnlyAPrivateNetworkOnALinkFacingOutsideCounts(t *testing.T) { // **The filter admits the local network on that port's rule alone** (§5), beside the private network, // in both chains, and never the public subnet. -func TestALocalNetworkPortIsAdmittedFromItsNetworksAndTheMesh(t *testing.T) { +func testALocalNetworkPortIsAdmittedFromItsNetworksAndTheMesh(t *testing.T) { rules := []mcat.Rule{ {Port: 1883, Protocol: "tcp", From: mcat.FromLocalNetwork, Because: []string{"mosquitto"}}, {Port: 5432, Protocol: "tcp", From: mcat.FromMesh, Because: []string{"postgres"}}, @@ -153,7 +153,7 @@ func TestALocalNetworkPortIsAdmittedFromItsNetworksAndTheMesh(t *testing.T) { // **A fourth reach** (§4, changing ADR 0138 §4): `internal` with the local networks added to what the // filter opens — the internal name, not the public one. -func TestTheLocalNetworkReachIsInternalWithTheLocalNetworkAdded(t *testing.T) { +func testTheLocalNetworkReachIsInternalWithTheLocalNetworkAdded(t *testing.T) { public, internal := namesFor(t, aRoutedWeb(), reachSet(mcat.ReachLocalNetwork)) if public != "" || internal != "app.anchor.internal" { t.Fatalf("names are %q and %q, want the internal name only", public, internal) @@ -172,7 +172,7 @@ func TestTheLocalNetworkReachIsInternalWithTheLocalNetworkAdded(t *testing.T) { // Two modules wanting one port, one from the mesh and one from the local network, render one rule from // the local network: it covers the mesh, and anywhere covers it. -func TestTheLocalNetworkSitsBetweenTheMeshAndAnywhere(t *testing.T) { +func testTheLocalNetworkSitsBetweenTheMeshAndAnywhere(t *testing.T) { got := widest([]mcat.Rule{ {Port: 53, Protocol: "udp", From: mcat.FromMesh, Because: []string{"a"}}, {Port: 53, Protocol: "udp", From: mcat.FromLocalNetwork, Because: []string{"b"}}, @@ -188,9 +188,18 @@ func TestTheLocalNetworkSitsBetweenTheMeshAndAnywhere(t *testing.T) { // On an adopted node the opening is the private network's part only: the found firewall admits the // local network, and an opening that widened to everywhere would open the port to the internet. -func TestAnAdoptedNodeOpensTheLocalNetworkPortToTheMeshOnly(t *testing.T) { +func testAnAdoptedNodeOpensTheLocalNetworkPortToTheMeshOnly(t *testing.T) { out := Openings([]mcat.Rule{{Port: 1883, Protocol: "tcp", From: mcat.FromLocalNetwork}}, nil, nil) if len(out) != 1 || out[0]["from"] != mcat.OpeningFromMesh { t.Fatalf("openings %v", out) } } + +// TestLocalnetwork runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestLocalnetwork(t *testing.T) { + t.Run("OnlyAPrivateNetworkOnALinkFacingOutsideCounts", testOnlyAPrivateNetworkOnALinkFacingOutsideCounts) + t.Run("ALocalNetworkPortIsAdmittedFromItsNetworksAndTheMesh", testALocalNetworkPortIsAdmittedFromItsNetworksAndTheMesh) + t.Run("TheLocalNetworkReachIsInternalWithTheLocalNetworkAdded", testTheLocalNetworkReachIsInternalWithTheLocalNetworkAdded) + t.Run("TheLocalNetworkSitsBetweenTheMeshAndAnywhere", testTheLocalNetworkSitsBetweenTheMeshAndAnywhere) + t.Run("AnAdoptedNodeOpensTheLocalNetworkPortToTheMeshOnly", testAnAdoptedNodeOpensTheLocalNetworkPortToTheMeshOnly) +} diff --git a/internal/compose/resolution/machine_into_files_test.go b/internal/compose/resolution/machine_into_files_test.go index 0b7acee9..eeb0768d 100644 --- a/internal/compose/resolution/machine_into_files_test.go +++ b/internal/compose/resolution/machine_into_files_test.go @@ -27,7 +27,7 @@ func authority() mcat.Manifest { } } -func TestAModuleNamesTheMachineItWasAssignedTo(t *testing.T) { +func testAModuleNamesTheMachineItWasAssignedTo(t *testing.T) { got, err := Resolve(shelf(authority()), []string{"authority"}, anchored(), mcat.World{}) if err != nil { t.Fatal(err) @@ -54,7 +54,7 @@ func TestAModuleNamesTheMachineItWasAssignedTo(t *testing.T) { // A machine not on the private network has no such address, and a module asking to be reached at // one is named here rather than left to fail later as a certificate nobody can verify. -func TestAnAddressAMachineDoesNotHaveIsRefused(t *testing.T) { +func testAnAddressAMachineDoesNotHaveIsRefused(t *testing.T) { got, err := Resolve(shelf(authority()), []string{"authority"}, workstation(), mcat.World{}) if err != nil { t.Fatal(err) @@ -70,7 +70,7 @@ func TestAnAddressAMachineDoesNotHaveIsRefused(t *testing.T) { // the container runtime at itself, whose list of resolvers cannot be a name — says // ${machine:address}, and gets what the machine's name resolves to on the private network: the same // address every other machine's hosts file carries for it. -func TestAModuleNamesTheAddressBehindItsMachinesName(t *testing.T) { +func testAModuleNamesTheAddressBehindItsMachinesName(t *testing.T) { pointing := mcat.Manifest{Module: "pointing", Version: "1", Resources: []map[string]any{{ "id": "runtime", "type": "file", "path": "/etc/runtime.json", "content": `{"dns":["${machine:address}"]}`, @@ -101,7 +101,7 @@ func TestAModuleNamesTheAddressBehindItsMachinesName(t *testing.T) { // The mesh's private range is offered as ${machine:mesh-range}, so a module names it rather than // hardcoding a value it cannot know (novox/hq ADR 0112) — the fail2ban ignoreip is the case. -func TestAModuleNamesTheMeshRange(t *testing.T) { +func testAModuleNamesTheMeshRange(t *testing.T) { facts := machineFacts(mcat.Resolution{Node: "anchor", At: "anchor.internal"}, map[string]string{"anchor.internal": "10.10.0.1"}, "10.10.0.0/24") if facts["mesh-range"] != "10.10.0.0/24" { t.Fatalf("the mesh range is not a machine fact: %v", facts) @@ -120,3 +120,11 @@ func TestAModuleNamesTheMeshRange(t *testing.T) { t.Fatal("a mesh with no range still offered one") } } + +// TestMachineIntoFiles runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestMachineIntoFiles(t *testing.T) { + t.Run("AModuleNamesTheMachineItWasAssignedTo", testAModuleNamesTheMachineItWasAssignedTo) + t.Run("AnAddressAMachineDoesNotHaveIsRefused", testAnAddressAMachineDoesNotHaveIsRefused) + t.Run("AModuleNamesTheAddressBehindItsMachinesName", testAModuleNamesTheAddressBehindItsMachinesName) + t.Run("AModuleNamesTheMeshRange", testAModuleNamesTheMeshRange) +} diff --git a/internal/compose/resolution/needs_test.go b/internal/compose/resolution/needs_test.go index 7740b694..75d2c626 100644 --- a/internal/compose/resolution/needs_test.go +++ b/internal/compose/resolution/needs_test.go @@ -17,7 +17,7 @@ func needy() mcat.Manifest { } } -func TestAModulesOwnSecretLandsSealed(t *testing.T) { +func testAModulesOwnSecretLandsSealed(t *testing.T) { got, err := Resolve(shelf(needy()), []string{"postgres"}, reachable(), mcat.World{}) if err != nil { t.Fatal(err) @@ -43,7 +43,7 @@ func TestAModulesOwnSecretLandsSealed(t *testing.T) { t.Fatalf("no secret was written: %v", out) } -func TestADeclaredNeedThatWasNotMadeIsRefused(t *testing.T) { +func testADeclaredNeedThatWasNotMadeIsRefused(t *testing.T) { // Skipping it would start a database with no password it knows, which fails to authenticate // three layers from the machine reporting it. got, _ := Resolve(shelf(needy()), []string{"postgres"}, reachable(), mcat.World{}) @@ -56,7 +56,7 @@ func TestADeclaredNeedThatWasNotMadeIsRefused(t *testing.T) { } } -func TestAModuleMayNeedSeveralThings(t *testing.T) { +func testAModuleMayNeedSeveralThings(t *testing.T) { // A password and a token, say. Telling them apart is the module's business, not the mesh's. m := needy() m.OwnSecrets["replication"] = mcat.OwnSecret{Path: "/var/lib/mesh/postgres/replication"} @@ -77,3 +77,10 @@ func TestAModuleMayNeedSeveralThings(t *testing.T) { t.Fatalf("two needs did not land as two secrets: %v", seen) } } + +// TestNeeds runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestNeeds(t *testing.T) { + t.Run("AModulesOwnSecretLandsSealed", testAModulesOwnSecretLandsSealed) + t.Run("ADeclaredNeedThatWasNotMadeIsRefused", testADeclaredNeedThatWasNotMadeIsRefused) + t.Run("AModuleMayNeedSeveralThings", testAModuleMayNeedSeveralThings) +} diff --git a/internal/compose/resolution/node_resolver_test.go b/internal/compose/resolution/node_resolver_test.go index 363b1fb1..a43f8cd6 100644 --- a/internal/compose/resolution/node_resolver_test.go +++ b/internal/compose/resolution/node_resolver_test.go @@ -23,7 +23,7 @@ func splitDNSLaptop() mcat.Node { // Where a module holds node-resolver, the machine is composed one resolver file, the holder's, naming // the machine's own address; the uplink's holder composes everything else it declares, and not that file. -func TestWhereTheResolverIsHeldItWritesTheFileAndTheUplinkStepsBack(t *testing.T) { +func testWhereTheResolverIsHeldItWritesTheFileAndTheUplinkStepsBack(t *testing.T) { shelf := resolverShelf(t) shelf["local-resolver"] = localResolver() got, err := Resolve(shelf, []string{"dnsmasq", "systemd-networkd", "local-resolver"}, splitDNSLaptop(), mcat.World{}) @@ -65,7 +65,7 @@ func TestWhereTheResolverIsHeldItWritesTheFileAndTheUplinkStepsBack(t *testing.T // Where nobody holds it, nothing changes: the uplink's holder writes the file, listing the mesh's // resolvers (ADR 0223) — every machine but the one that requires split-dns. -func TestWithoutTheResolverTheUplinkWritesTheFileAsBefore(t *testing.T) { +func testWithoutTheResolverTheUplinkWritesTheFileAsBefore(t *testing.T) { got, err := Resolve(resolverShelf(t), []string{"dnsmasq", "systemd-networkd"}, splitDNSLaptop(), mcat.World{}) if err != nil { t.Fatal(err) @@ -86,7 +86,7 @@ func TestWithoutTheResolverTheUplinkWritesTheFileAsBefore(t *testing.T) { // Only the uplink's holder steps back. A third module rendering or declaring the file beside the // resolver's is two owners of one path, refused as before; and a module rendering it without holding // the seat is not the resolver, so the uplink's holder does not step back for it. -func TestOnlyTheUplinkStepsBackForTheResolver(t *testing.T) { +func testOnlyTheUplinkStepsBackForTheResolver(t *testing.T) { uplink := mcat.Manifest{Module: "uplink", Version: "1", Claims: []mcat.Claim{{Name: "node-uplink"}}, Facts: map[string]mcat.RosterFile{"resolvers": {Path: mcat.ResolverFile, Template: "nameserver 10.42.0.1\n"}}} if p := checkResources([]mcat.Manifest{uplink, localResolver()}); len(p) != 0 { @@ -119,7 +119,7 @@ func TestOnlyTheUplinkStepsBackForTheResolver(t *testing.T) { // (its header is how the uplink's verb and the node-engine read a file as the mesh's), and provides // split-dns at the machine's reach — a requirement is answered only on the same machine and never pulls // the resolver in. Skipped while the catalogue has no holder. -func TestTheCataloguesResolverHoldersWriteTheFileAndProvideSplitDNS(t *testing.T) { +func testTheCataloguesResolverHoldersWriteTheFileAndProvideSplitDNS(t *testing.T) { held := 0 for _, m := range theCatalogue(t) { if !holdsSeat(m, mcat.ResolverSeat) { @@ -148,7 +148,7 @@ func TestTheCataloguesResolverHoldersWriteTheFileAndProvideSplitDNS(t *testing.T // The catalogue's systemd-resolved, composed on a machine beside its uplink: the resolver file names the // machine's own private address alone, its kept copy is the same file, and resolved is given every mesh // resolver as its default route and the private address to listen on. Skipped without the catalogue. -func TestTheCataloguesResolverComposesOnAMachine(t *testing.T) { +func testTheCataloguesResolverComposesOnAMachine(t *testing.T) { shelf := resolverShelf(t) shelf["systemd-resolved"] = catalogueManifest(t, "systemd-resolved") // The options line is the catalogue's own template's, never a literal of it here (design 50 resolver-wait §3). @@ -192,3 +192,12 @@ func TestTheCataloguesResolverComposesOnAMachine(t *testing.T) { t.Errorf("the mesh's domain is rendered as %q", s) } } + +// TestNodeResolver runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestNodeResolver(t *testing.T) { + t.Run("WhereTheResolverIsHeldItWritesTheFileAndTheUplinkStepsBack", testWhereTheResolverIsHeldItWritesTheFileAndTheUplinkStepsBack) + t.Run("WithoutTheResolverTheUplinkWritesTheFileAsBefore", testWithoutTheResolverTheUplinkWritesTheFileAsBefore) + t.Run("OnlyTheUplinkStepsBackForTheResolver", testOnlyTheUplinkStepsBackForTheResolver) + t.Run("TheCataloguesResolverHoldersWriteTheFileAndProvideSplitDNS", testTheCataloguesResolverHoldersWriteTheFileAndProvideSplitDNS) + t.Run("TheCataloguesResolverComposesOnAMachine", testTheCataloguesResolverComposesOnAMachine) +} diff --git a/internal/compose/resolution/optional_requirements_test.go b/internal/compose/resolution/optional_requirements_test.go index c8c60811..19cf58b2 100644 --- a/internal/compose/resolution/optional_requirements_test.go +++ b/internal/compose/resolution/optional_requirements_test.go @@ -16,7 +16,7 @@ func optionalShelf() map[string]mcat.Manifest { ) } -func TestAnOptionalRequirementWithNoProviderIsAbsentAndNothingIsInstalled(t *testing.T) { +func testAnOptionalRequirementWithNoProviderIsAbsentAndNothingIsInstalled(t *testing.T) { // Exactly one catalogue module could answer each — the case where a hard requirement installs it. // Brokered (influxdb-api, from anywhere) and on this machine (shell); both passes. for _, world := range []mcat.World{{}, {Unchecked: true}} { @@ -40,7 +40,7 @@ func TestAnOptionalRequirementWithNoProviderIsAbsentAndNothingIsInstalled(t *tes } } -func TestAnOptionalRequirementWithAProviderBindsAsAHardOne(t *testing.T) { +func testAnOptionalRequirementWithAProviderBindsAsAHardOne(t *testing.T) { world := mcat.World{Offered: map[string][]mcat.Provider{"influxdb-api": { {Node: "anchor", At: "anchor.internal", Module: "influxdb", Serves: map[string]any{"port": 8086}}}}} got, err := Resolve(optionalShelf(), []string{"grafana", "zsh"}, reachable(), world) @@ -64,7 +64,7 @@ func TestAnOptionalRequirementWithAProviderBindsAsAHardOne(t *testing.T) { } } -func TestOneConsumersOptionalRequirementIsAnothersHardOne(t *testing.T) { +func testOneConsumersOptionalRequirementIsAnothersHardOne(t *testing.T) { // telegraf wants influxdb-api hard: with nothing offering it, the assignment is refused as // before, naming what to assign — grafana's optional does not soften telegraf's. _, err := Resolve(optionalShelf(), []string{"grafana", "telegraf"}, reachable(), mcat.World{}) @@ -91,7 +91,7 @@ func TestOneConsumersOptionalRequirementIsAnothersHardOne(t *testing.T) { } } -func TestAHardRequirementWithNoProviderIsStillRefused(t *testing.T) { +func testAHardRequirementWithNoProviderIsStillRefused(t *testing.T) { _, err := Resolve(optionalShelf(), []string{"telegraf"}, reachable(), mcat.World{}) if err == nil || !strings.Contains(err.Error(), "influxdb") { t.Fatalf("got %v", err) @@ -124,7 +124,7 @@ func absentGrafana(t *testing.T, absent bool) mcat.Resolution { return r } -func TestAnAbsentRequirementIsComposedWithItsDefaultsAndWithoutItsFiles(t *testing.T) { +func testAnAbsentRequirementIsComposedWithItsDefaultsAndWithoutItsFiles(t *testing.T) { out, err := Declaration(absentGrafana(t, true), mcat.Rendering{}) if err != nil { t.Fatal(err) @@ -145,7 +145,7 @@ func TestAnAbsentRequirementIsComposedWithItsDefaultsAndWithoutItsFiles(t *testi } } -func TestABoundOptionalRequirementIsComposedAsAHardOne(t *testing.T) { +func testABoundOptionalRequirementIsComposedAsAHardOne(t *testing.T) { out, err := Declaration(absentGrafana(t, false), mcat.Rendering{}) if err != nil { t.Fatal(err) @@ -166,3 +166,13 @@ func TestABoundOptionalRequirementIsComposedAsAHardOne(t *testing.T) { } } } + +// TestOptionalRequirements runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestOptionalRequirements(t *testing.T) { + t.Run("AnOptionalRequirementWithNoProviderIsAbsentAndNothingIsInstalled", testAnOptionalRequirementWithNoProviderIsAbsentAndNothingIsInstalled) + t.Run("AnOptionalRequirementWithAProviderBindsAsAHardOne", testAnOptionalRequirementWithAProviderBindsAsAHardOne) + t.Run("OneConsumersOptionalRequirementIsAnothersHardOne", testOneConsumersOptionalRequirementIsAnothersHardOne) + t.Run("AHardRequirementWithNoProviderIsStillRefused", testAHardRequirementWithNoProviderIsStillRefused) + t.Run("AnAbsentRequirementIsComposedWithItsDefaultsAndWithoutItsFiles", testAnAbsentRequirementIsComposedWithItsDefaultsAndWithoutItsFiles) + t.Run("ABoundOptionalRequirementIsComposedAsAHardOne", testABoundOptionalRequirementIsComposedAsAHardOne) +} diff --git a/internal/compose/resolution/outside_not_given_test.go b/internal/compose/resolution/outside_not_given_test.go index a23838da..22923430 100644 --- a/internal/compose/resolution/outside_not_given_test.go +++ b/internal/compose/resolution/outside_not_given_test.go @@ -44,7 +44,7 @@ func resourceNamed(out []map[string]any, name string) map[string]any { return nil } -func TestAnOutsideSecretNotGivenIsNoFileAndAFileNamingItSaysEmpty(t *testing.T) { +func testAnOutsideSecretNotGivenIsNoFileAndAFileNamingItSaysEmpty(t *testing.T) { r := mcat.Resolution{Node: "server", Modules: []mcat.Manifest{outsideManifest(t)}} out, err := Declaration(r, mcat.Rendering{Needed: map[string]map[string]string{"assistant": {"password": "sealed-password"}}}) if err != nil { @@ -70,7 +70,7 @@ func TestAnOutsideSecretNotGivenIsNoFileAndAFileNamingItSaysEmpty(t *testing.T) } } -func TestAnOutsideSecretGivenIsPlacedAndFilled(t *testing.T) { +func testAnOutsideSecretGivenIsPlacedAndFilled(t *testing.T) { r := mcat.Resolution{Node: "server", Modules: []mcat.Manifest{outsideManifest(t)}} out, err := Declaration(r, mcat.Rendering{Needed: map[string]map[string]string{"assistant": { "password": "sealed-password", "vendor-key": "sealed-vendor-key"}}}) @@ -95,10 +95,17 @@ func TestAnOutsideSecretGivenIsPlacedAndFilled(t *testing.T) { } // A secret the mesh makes is still refused when it was not made: only an outside one is left out. -func TestAnOwnSecretTheMeshMakesIsStillRefusedWhenNotMade(t *testing.T) { +func testAnOwnSecretTheMeshMakesIsStillRefusedWhenNotMade(t *testing.T) { r := mcat.Resolution{Node: "server", Modules: []mcat.Manifest{outsideManifest(t)}} _, err := Declaration(r, mcat.Rendering{}) if nm, ok := err.(*NotMadeError); !ok || nm.Name != "password" { t.Fatalf("a secret the mesh makes, not made: %v", err) } } + +// TestOutsideNotGiven runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestOutsideNotGiven(t *testing.T) { + t.Run("AnOutsideSecretNotGivenIsNoFileAndAFileNamingItSaysEmpty", testAnOutsideSecretNotGivenIsNoFileAndAFileNamingItSaysEmpty) + t.Run("AnOutsideSecretGivenIsPlacedAndFilled", testAnOutsideSecretGivenIsPlacedAndFilled) + t.Run("AnOwnSecretTheMeshMakesIsStillRefusedWhenNotMade", testAnOwnSecretTheMeshMakesIsStillRefusedWhenNotMade) +} diff --git a/internal/compose/resolution/own_name_test.go b/internal/compose/resolution/own_name_test.go index 3eabe073..6792bc5b 100644 --- a/internal/compose/resolution/own_name_test.go +++ b/internal/compose/resolution/own_name_test.go @@ -55,7 +55,7 @@ func fileAt(t *testing.T, out []map[string]any, path string) string { return "" } -func TestAModuleIsToldTheNameItsProviderServes(t *testing.T) { +func testAModuleIsToldTheNameItsProviderServes(t *testing.T) { got, err := Resolve(shelf(servingProxy(), selfAware("git")), []string{"traefik", "board"}, onBoth("example.tld"), mcat.World{}) if err != nil { @@ -83,7 +83,7 @@ func TestAModuleIsToldTheNameItsProviderServes(t *testing.T) { } } -func TestTheNameAModuleIsToldFollowsTheNodesDomain(t *testing.T) { +func testTheNameAModuleIsToldFollowsTheNodesDomain(t *testing.T) { // The whole point: the same definition, two machines, two names — nothing edited. for _, domain := range []string{"example.tld", "other.example"} { got, err := Resolve(shelf(servingProxy(), selfAware("git")), []string{"traefik", "board"}, @@ -98,7 +98,7 @@ func TestTheNameAModuleIsToldFollowsTheNodesDomain(t *testing.T) { } } -func TestAModuleWithNoPublicNameIsNotToldOne(t *testing.T) { +func testAModuleWithNoPublicNameIsNotToldOne(t *testing.T) { // No public domain on the node: nothing composed, so no `name` — and a file asking for one is // refused rather than rendered with a placeholder or an empty host. m := selfAware("git") @@ -113,7 +113,7 @@ func TestAModuleWithNoPublicNameIsNotToldOne(t *testing.T) { } } -func TestAModuleIsToldItsNameByANodeScopedProviderToo(t *testing.T) { +func testAModuleIsToldItsNameByANodeScopedProviderToo(t *testing.T) { m := selfAware("git") m.Resources[0]["content"] = "root = https://${bound:reverse-proxy:name}/\n" got, err := Resolve(shelf(nodeProxy(), m), []string{"board"}, @@ -126,3 +126,11 @@ func TestAModuleIsToldItsNameByANodeScopedProviderToo(t *testing.T) { t.Fatalf("a same-machine, node-scoped answer did not tell the module its name: %q", conf) } } + +// TestOwnName runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestOwnName(t *testing.T) { + t.Run("AModuleIsToldTheNameItsProviderServes", testAModuleIsToldTheNameItsProviderServes) + t.Run("TheNameAModuleIsToldFollowsTheNodesDomain", testTheNameAModuleIsToldFollowsTheNodesDomain) + t.Run("AModuleWithNoPublicNameIsNotToldOne", testAModuleWithNoPublicNameIsNotToldOne) + t.Run("AModuleIsToldItsNameByANodeScopedProviderToo", testAModuleIsToldItsNameByANodeScopedProviderToo) +} diff --git a/internal/compose/resolution/own_secret_owner_test.go b/internal/compose/resolution/own_secret_owner_test.go index 9942f1e5..e0c2b7ad 100644 --- a/internal/compose/resolution/own_secret_owner_test.go +++ b/internal/compose/resolution/own_secret_owner_test.go @@ -26,7 +26,7 @@ func mailSenderManifest(t *testing.T, own string) mcat.Manifest { // 1170/AC1: a family owned by the module's own account lands at 0600, owned by that account — and a module's // other own secrets (no per-secret owner declared) keep secrets-owner, unchanged. -func TestAnOwnSecretsOwnerIsGivenToItsFiles(t *testing.T) { +func testAnOwnSecretsOwnerIsGivenToItsFiles(t *testing.T) { // ADR 0680 §1, §4: the owner is the account the manifest names: one the module makes, the operator account // (`${machine:account}`, filled with the machine's account) or root. for _, c := range []struct{ name, owner, account, want string }{ @@ -79,7 +79,7 @@ func TestAnOwnSecretsOwnerIsGivenToItsFiles(t *testing.T) { // 1170/AC3: a manifest with no owner on any own secret composes exactly as it did before this clause existed: // every secret file belongs to the module's secrets-owner (or nothing, when that is absent too). -func TestNoOwnerOnAnySecretComposesAsMainDoes(t *testing.T) { +func testNoOwnerOnAnySecretComposesAsMainDoes(t *testing.T) { m := mailSenderManifest(t, "") r := mcat.Resolution{Node: "novox", Modules: []mcat.Manifest{m}} out, err := Declaration(r, mcat.Rendering{ @@ -101,3 +101,9 @@ func TestNoOwnerOnAnySecretComposesAsMainDoes(t *testing.T) { t.Fatalf("the family member was not composed at all: %v", out) } } + +// TestOwnSecretOwner runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestOwnSecretOwner(t *testing.T) { + t.Run("AnOwnSecretsOwnerIsGivenToItsFiles", testAnOwnSecretsOwnerIsGivenToItsFiles) + t.Run("NoOwnerOnAnySecretComposesAsMainDoes", testNoOwnerOnAnySecretComposesAsMainDoes) +} diff --git a/internal/compose/resolution/pin_names_module_test.go b/internal/compose/resolution/pin_names_module_test.go index 8deae85a..b936a58d 100644 --- a/internal/compose/resolution/pin_names_module_test.go +++ b/internal/compose/resolution/pin_names_module_test.go @@ -21,7 +21,7 @@ func twoIssuersOnOneNode() map[string][]mcat.Provider { }} } -func TestTwoProvidersOnOneNodeAreRefusedWithBothNamed(t *testing.T) { +func testTwoProvidersOnOneNodeAreRefusedWithBothNamed(t *testing.T) { // The refusal must name the pair, because a node alone cannot tell them apart. _, err := Resolve(issuerShelf(), []string{"route-proxy"}, reachable(), mcat.World{Offered: twoIssuersOnOneNode()}) if err == nil { @@ -34,7 +34,7 @@ func TestTwoProvidersOnOneNodeAreRefusedWithBothNamed(t *testing.T) { } } -func TestAPinNamesTheModule(t *testing.T) { +func testAPinNamesTheModule(t *testing.T) { got, err := Resolve(issuerShelf(), []string{"route-proxy"}, reachable(), mcat.World{Offered: twoIssuersOnOneNode(), Pinned: map[string]mcat.Chosen{"acme-ca": {Node: "novox", Module: "public-acme"}}}) if err != nil { @@ -45,7 +45,7 @@ func TestAPinNamesTheModule(t *testing.T) { } } -func TestARecordNamingOnlyTheNodeIsRefusedWhenThatNodeAnswersTwice(t *testing.T) { +func testARecordNamingOnlyTheNodeIsRefusedWhenThatNodeAnswersTwice(t *testing.T) { // A pin from before the module was asked for. It once took the last one listed — a coin flip. _, err := Resolve(issuerShelf(), []string{"route-proxy"}, reachable(), mcat.World{Offered: twoIssuersOnOneNode(), Pinned: map[string]mcat.Chosen{"acme-ca": {Node: "novox"}}}) if err == nil { @@ -56,14 +56,14 @@ func TestARecordNamingOnlyTheNodeIsRefusedWhenThatNodeAnswersTwice(t *testing.T) } } -func TestAPinNamingAModuleThatDoesNotProvideItIsRefused(t *testing.T) { +func testAPinNamingAModuleThatDoesNotProvideItIsRefused(t *testing.T) { _, err := Resolve(issuerShelf(), []string{"route-proxy"}, reachable(), mcat.World{Offered: twoIssuersOnOneNode(), Pinned: map[string]mcat.Chosen{"acme-ca": {Node: "novox", Module: "gitea"}}}) if err == nil || !strings.Contains(err.Error(), "novox/gitea does not provide it") { t.Fatalf("a module that does not provide it was not refused by name: %v", err) } } -func TestTwoProvidersBesideTheConsumerAreRefusedUntilOneIsNamed(t *testing.T) { +func testTwoProvidersBesideTheConsumerAreRefusedUntilOneIsNamed(t *testing.T) { // The same ambiguity on the consumer's own machine. This was settled by a map walk — random, // per plan — which is how novox's own proxy got its issuer. _, err := Resolve(issuerShelf(), []string{"route-proxy", "public-acme", "step-ca"}, reachable(), mcat.World{}) @@ -75,7 +75,7 @@ func TestTwoProvidersBesideTheConsumerAreRefusedUntilOneIsNamed(t *testing.T) { } } -func TestAPinSettlesTwoProvidersBesideTheConsumer(t *testing.T) { +func testAPinSettlesTwoProvidersBesideTheConsumer(t *testing.T) { got, err := Resolve(issuerShelf(), []string{"route-proxy", "public-acme", "step-ca"}, reachable(), mcat.World{Pinned: map[string]mcat.Chosen{"acme-ca": {Node: "workstation", Module: "public-acme"}}}) if err != nil { t.Fatal(err) @@ -94,7 +94,7 @@ func TestAPinSettlesTwoProvidersBesideTheConsumer(t *testing.T) { } } -func TestTheFirstPassDoesNotRefuseTwoProvidersBesideTheConsumer(t *testing.T) { +func testTheFirstPassDoesNotRefuseTwoProvidersBesideTheConsumer(t *testing.T) { // The first pass answers only what a node offers. Refused there, the node vanishes from every // other node's world — and the whole mesh loses its vault for an ambiguity one machine has to // settle. The second pass is where it is refused, and the test above proves it is. @@ -102,3 +102,14 @@ func TestTheFirstPassDoesNotRefuseTwoProvidersBesideTheConsumer(t *testing.T) { t.Fatalf("the first pass refused what only the second may: %v", err) } } + +// TestPinNamesModule runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestPinNamesModule(t *testing.T) { + t.Run("TwoProvidersOnOneNodeAreRefusedWithBothNamed", testTwoProvidersOnOneNodeAreRefusedWithBothNamed) + t.Run("APinNamesTheModule", testAPinNamesTheModule) + t.Run("ARecordNamingOnlyTheNodeIsRefusedWhenThatNodeAnswersTwice", testARecordNamingOnlyTheNodeIsRefusedWhenThatNodeAnswersTwice) + t.Run("APinNamingAModuleThatDoesNotProvideItIsRefused", testAPinNamingAModuleThatDoesNotProvideItIsRefused) + t.Run("TwoProvidersBesideTheConsumerAreRefusedUntilOneIsNamed", testTwoProvidersBesideTheConsumerAreRefusedUntilOneIsNamed) + t.Run("APinSettlesTwoProvidersBesideTheConsumer", testAPinSettlesTwoProvidersBesideTheConsumer) + t.Run("TheFirstPassDoesNotRefuseTwoProvidersBesideTheConsumer", testTheFirstPassDoesNotRefuseTwoProvidersBesideTheConsumer) +} diff --git a/internal/compose/resolution/port_into_test.go b/internal/compose/resolution/port_into_test.go index c5a2e576..c8ff449e 100644 --- a/internal/compose/resolution/port_into_test.go +++ b/internal/compose/resolution/port_into_test.go @@ -16,7 +16,7 @@ import ( // the machine with nothing to rewrite, so without a way to ask, every process binds the number in // its own configuration and two modules declaring the same one collide — which is the whole // problem ADR 0038 exists to prevent, reintroduced by the resource kind that most needs it. -func TestAModuleIsToldWhichPortItWasGiven(t *testing.T) { +func testAModuleIsToldWhichPortItWasGiven(t *testing.T) { file := map[string]any{ "type": "file", "id": "settings", "content": "LISTEN=${port:8080}\n", @@ -34,7 +34,7 @@ func TestAModuleIsToldWhichPortItWasGiven(t *testing.T) { // With nothing assigned yet, it is told the port it asked about — so a mesh that has not made an // assignment still composes something coherent rather than writing a zero. -func TestWithNoAssignmentAModuleIsToldWhatItAskedFor(t *testing.T) { +func testWithNoAssignmentAModuleIsToldWhatItAskedFor(t *testing.T) { file := map[string]any{"type": "file", "content": "LISTEN=${port:8080}\n"} if err := portInto(file, "showcase", []mcat.Listening{{Port: 8080}}, mcat.Rendering{}); err != nil { t.Fatal(err) @@ -47,7 +47,7 @@ func TestWithNoAssignmentAModuleIsToldWhatItAskedFor(t *testing.T) { // **Asking about a port it never declared is refused**, and the refusal says what it did declare. // The module is asking about something the mesh has no opinion on, and answering would be a guess // written into a configuration file as a port number. -func TestAskingAboutAnUndeclaredPortIsRefused(t *testing.T) { +func testAskingAboutAnUndeclaredPortIsRefused(t *testing.T) { file := map[string]any{"type": "file", "content": "LISTEN=${port:9999}\n"} err := portInto(file, "showcase", []mcat.Listening{{Port: 8080}}, mcat.Rendering{}) if err == nil { @@ -59,7 +59,7 @@ func TestAskingAboutAnUndeclaredPortIsRefused(t *testing.T) { } // And a file mentioning no port is left exactly as it was. -func TestAFileWithNoPortIsUntouched(t *testing.T) { +func testAFileWithNoPortIsUntouched(t *testing.T) { file := map[string]any{"type": "file", "content": "GREETING=hello\n"} if err := portInto(file, "showcase", nil, mcat.Rendering{}); err != nil { t.Fatal(err) @@ -76,7 +76,7 @@ func TestAFileWithNoPortIsUntouched(t *testing.T) { // caller: the caller dials the machine, so it must be given the machine's number — here one the // node was given rather than one the mesh assigned, which is the case that makes the literal wrong // even on a mesh that never allocates (ADR 0100). -func TestAContainerIsToldWhichPortItWasGiven(t *testing.T) { +func testAContainerIsToldWhichPortItWasGiven(t *testing.T) { sidecar := map[string]any{ "type": "container", "id": "runtime", "name": "mesh-gitea", "env": map[string]any{ @@ -106,7 +106,7 @@ func TestAContainerIsToldWhichPortItWasGiven(t *testing.T) { // around it is a shallow copy. Filled in place, the first node composed would write its own port // into the catalogue and every node composed after it would be told that one — a fault that is // invisible in a single composition and wrong in every mesh with two machines. -func TestFillingAContainersEnvironmentLeavesTheManifestAlone(t *testing.T) { +func testFillingAContainersEnvironmentLeavesTheManifestAlone(t *testing.T) { env := map[string]any{"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}"} manifest := map[string]any{"type": "container", "id": "runtime", "name": "mesh-gitea", "env": env} @@ -132,7 +132,7 @@ func TestFillingAContainersEnvironmentLeavesTheManifestAlone(t *testing.T) { // Asking in an environment about a port it never declared is refused exactly as a file's is, and // the refusal names the container and the variable — there is no line number to go on. -func TestAContainerAskingAboutAnUndeclaredPortIsRefused(t *testing.T) { +func testAContainerAskingAboutAnUndeclaredPortIsRefused(t *testing.T) { sidecar := map[string]any{ "type": "container", "id": "runtime", "name": "mesh-gitea", "env": map[string]any{"MESH_GITEA_URL": "http://127.0.0.1:${port:9999}"}, @@ -150,7 +150,7 @@ func TestAContainerAskingAboutAnUndeclaredPortIsRefused(t *testing.T) { // And a container naming no port keeps the environment it was written with — the same map, so // nothing is copied and no other node's composition is disturbed. -func TestAContainerWithNoPortPlaceholderKeepsItsEnvironment(t *testing.T) { +func testAContainerWithNoPortPlaceholderKeepsItsEnvironment(t *testing.T) { env := map[string]any{"MESH_GITEA_URL": "http://gitea:3000", "PORT": 3000} sidecar := map[string]any{"type": "container", "name": "mesh-gitea", "env": env} if err := portInto(sidecar, "gitea", []mcat.Listening{{Port: 3000}}, mcat.Rendering{ @@ -170,3 +170,15 @@ func TestAContainerWithNoPortPlaceholderKeepsItsEnvironment(t *testing.T) { t.Fatalf("a container that asked for nothing had its environment rebuilt: %v", sidecar["env"]) } } + +// TestPortInto runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestPortInto(t *testing.T) { + t.Run("AModuleIsToldWhichPortItWasGiven", testAModuleIsToldWhichPortItWasGiven) + t.Run("WithNoAssignmentAModuleIsToldWhatItAskedFor", testWithNoAssignmentAModuleIsToldWhatItAskedFor) + t.Run("AskingAboutAnUndeclaredPortIsRefused", testAskingAboutAnUndeclaredPortIsRefused) + t.Run("AFileWithNoPortIsUntouched", testAFileWithNoPortIsUntouched) + t.Run("AContainerIsToldWhichPortItWasGiven", testAContainerIsToldWhichPortItWasGiven) + t.Run("FillingAContainersEnvironmentLeavesTheManifestAlone", testFillingAContainersEnvironmentLeavesTheManifestAlone) + t.Run("AContainerAskingAboutAnUndeclaredPortIsRefused", testAContainerAskingAboutAnUndeclaredPortIsRefused) + t.Run("AContainerWithNoPortPlaceholderKeepsItsEnvironment", testAContainerWithNoPortPlaceholderKeepsItsEnvironment) +} diff --git a/internal/compose/resolution/process_env_test.go b/internal/compose/resolution/process_env_test.go index 92a4ace1..beed8ad8 100644 --- a/internal/compose/resolution/process_env_test.go +++ b/internal/compose/resolution/process_env_test.go @@ -26,7 +26,7 @@ func processModule(env map[string]any) mcat.Manifest { } } -func TestAProcessIsToldItsPortAndItsPlaceInItsEnvironment(t *testing.T) { +func testAProcessIsToldItsPortAndItsPlaceInItsEnvironment(t *testing.T) { env := map[string]any{ "SHOWCASE_URL": "http://127.0.0.1:${port:8080}", "SHOWCASE_DATA": "${dir:data}/objects", @@ -62,7 +62,7 @@ func TestAProcessIsToldItsPortAndItsPlaceInItsEnvironment(t *testing.T) { // An unknown reference in a process's environment is refused as a container's is, naming the // process and the variable — left alone, it would reach the machine as a literal. -func TestAProcessAskingAboutAnUndeclaredPortIsRefused(t *testing.T) { +func testAProcessAskingAboutAnUndeclaredPortIsRefused(t *testing.T) { env := map[string]any{"SHOWCASE_URL": "http://127.0.0.1:${port:9999}"} _, err := Declaration(mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{processModule(env)}}, mcat.Rendering{}) if err == nil { @@ -80,3 +80,9 @@ func TestAProcessAskingAboutAnUndeclaredPortIsRefused(t *testing.T) { t.Fatalf("a process naming no directory of its module was not refused: %v", err) } } + +// TestProcessEnv runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestProcessEnv(t *testing.T) { + t.Run("AProcessIsToldItsPortAndItsPlaceInItsEnvironment", testAProcessIsToldItsPortAndItsPlaceInItsEnvironment) + t.Run("AProcessAskingAboutAnUndeclaredPortIsRefused", testAProcessAskingAboutAnUndeclaredPortIsRefused) +} diff --git a/internal/compose/resolution/proofs_test.go b/internal/compose/resolution/proofs_test.go index cd174e42..72aab40e 100644 --- a/internal/compose/resolution/proofs_test.go +++ b/internal/compose/resolution/proofs_test.go @@ -44,7 +44,7 @@ func twoMergeableFiles(app, sidecar []any) mcat.Manifest { } // The indexer's judge's proofs, items 1 to 13 of its list. -func TestTheJudgesProofsOfAComposition(t *testing.T) { +func testTheJudgesProofsOfAComposition(t *testing.T) { runtimeWith := mcat.Rendering{ArtifactStore: "anchor.internal:5101", Needed: map[string]map[string]string{"node-tools": {"broker": "sealed-credential"}, "dash": {"token": "sealed-token"}}} processOf := func(out []map[string]any) map[string]any { @@ -350,7 +350,7 @@ func TestTheJudgesProofsOfAComposition(t *testing.T) { } // route-proxy's proofs, items 1 to 3 of its list. -func TestRouteProxysProofsOfAComposition(t *testing.T) { +func testRouteProxysProofsOfAComposition(t *testing.T) { proxy := mcat.Manifest{Module: "route-proxy", Version: "1", Provides: []mcat.Offer{{Name: "route", Scope: mcat.ScopeMesh, AnsweredBy: mcat.AnsweredByHelper}}} world := mcat.World{Offered: map[string][]mcat.Provider{"route": {{Node: "anchor", At: "anchor.internal", Module: "route-proxy"}}}} @@ -474,3 +474,9 @@ func TestRouteProxysProofsOfAComposition(t *testing.T) { } }) } + +// TestProofs runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestProofs(t *testing.T) { + t.Run("TheJudgesProofsOfAComposition", testTheJudgesProofsOfAComposition) + t.Run("RouteProxysProofsOfAComposition", testRouteProxysProofsOfAComposition) +} diff --git a/internal/compose/resolution/reach_test.go b/internal/compose/resolution/reach_test.go index c92dae0c..186e182b 100644 --- a/internal/compose/resolution/reach_test.go +++ b/internal/compose/resolution/reach_test.go @@ -46,7 +46,7 @@ func namesFor(t *testing.T, m mcat.Manifest, settings mcat.SettingsBy) (public, // A routed endpoint's port is how the proxy reaches it and nothing else (ADR 0045): a public service // listens from the mesh, only the proxy reaches it, and it is exposed by name. So on a routed // endpoint the reach asks for a name and the port keeps what the manifest said. -func TestAnUnroutedEndpointsPortFollowsItsReach(t *testing.T) { +func testAnUnroutedEndpointsPortFollowsItsReach(t *testing.T) { // The same module with its route taken away: now the port is the only way in, so reach governs it. bare := aRoutedWeb() bare.Contributes = nil @@ -81,7 +81,7 @@ func TestAnUnroutedEndpointsPortFollowsItsReach(t *testing.T) { // // A module whose routed name must be public and whose machine-side port must not be had no way to say // so while one value drove both. Under one value it could not be expressed; the port would reopen. -func TestAPublicNameLeavesARoutedPortAsTheManifestSaid(t *testing.T) { +func testAPublicNameLeavesARoutedPortAsTheManifestSaid(t *testing.T) { r := mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{aRoutedWeb()}, PublicDomain: "example.test", At: "anchor.internal"} rules, err := Rules(r, mcat.Rendering{Settings: reachSet(mcat.ReachPublic)}) @@ -103,7 +103,7 @@ func TestAPublicNameLeavesARoutedPortAsTheManifestSaid(t *testing.T) { // A reach for a port the module does not listen on reaches nothing, and is refused where it is // written rather than accepted and ignored. -func TestAReachForAPortTheModuleDoesNotListenOnIsRefused(t *testing.T) { +func testAReachForAPortTheModuleDoesNotListenOnIsRefused(t *testing.T) { _, err := Reaches(aRoutedWeb(), []mcat.Layer{{From: "node anchor", Placement: map[string]any{mcat.ReachSetting: map[string]any{"9999": mcat.ReachInternal}}}}) if err == nil || !strings.Contains(err.Error(), "reaches nothing") { @@ -114,7 +114,7 @@ func TestAReachForAPortTheModuleDoesNotListenOnIsRefused(t *testing.T) { // A value that is not a reach is refused, and the refusal names the four so a reader is one edit from // right. "mesh" is the tempting wrong answer, because that is the filter's word for nearly the same // thing. -func TestAValueThatIsNotAReachIsRefused(t *testing.T) { +func testAValueThatIsNotAReachIsRefused(t *testing.T) { for _, wrong := range []string{"mesh", "anywhere", "private", "true"} { _, err := Reaches(aRoutedWeb(), []mcat.Layer{{From: "node anchor", Placement: map[string]any{mcat.ReachSetting: map[string]any{"3000": wrong}}}}) @@ -127,7 +127,7 @@ func TestAValueThatIsNotAReachIsRefused(t *testing.T) { // **A port that says both reach and expose is refused.** They say the same thing in different words, // and accepting both would have the filter follow one while the names followed the other — the // disagreement ADR 0138 exists to remove, reintroduced by the migration away from the older word. -func TestReachAndExposeForOnePortAreRefused(t *testing.T) { +func testReachAndExposeForOnePortAreRefused(t *testing.T) { _, err := Reaches(aRoutedWeb(), []mcat.Layer{{From: "node anchor", Placement: map[string]any{mcat.ReachSetting: map[string]any{"3000": mcat.ReachInternal}, mcat.ExposeSetting: map[string]any{"3000": mcat.FromEverywhere}}}}) if err == nil || !strings.Contains(err.Error(), "same thing in different") { t.Fatalf("a port set both ways was accepted: %v", err) @@ -136,7 +136,7 @@ func TestReachAndExposeForOnePortAreRefused(t *testing.T) { // A path-level refusal carries no port: it is a rule about a name, not an endpoint, and it inherits // whatever that name turned out to be. Narrowing the endpoint must not silently drop it. -func TestARuleWithNoPortIsLeftAlone(t *testing.T) { +func testARuleWithNoPortIsLeftAlone(t *testing.T) { m := aRoutedWeb() m.ContributesMany = map[string]map[string]map[string]any{ "route": {"refused": {"label": "app", "path": "/internal", "deny": true}}, @@ -161,3 +161,13 @@ func TestARuleWithNoPortIsLeftAlone(t *testing.T) { t.Fatal("the path rule was dropped") } } + +// TestReach runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestReach(t *testing.T) { + t.Run("AnUnroutedEndpointsPortFollowsItsReach", testAnUnroutedEndpointsPortFollowsItsReach) + t.Run("APublicNameLeavesARoutedPortAsTheManifestSaid", testAPublicNameLeavesARoutedPortAsTheManifestSaid) + t.Run("AReachForAPortTheModuleDoesNotListenOnIsRefused", testAReachForAPortTheModuleDoesNotListenOnIsRefused) + t.Run("AValueThatIsNotAReachIsRefused", testAValueThatIsNotAReachIsRefused) + t.Run("ReachAndExposeForOnePortAreRefused", testReachAndExposeForOnePortAreRefused) + t.Run("ARuleWithNoPortIsLeftAlone", testARuleWithNoPortIsLeftAlone) +} diff --git a/internal/compose/resolution/reads_test.go b/internal/compose/resolution/reads_test.go index cfe475bc..9e4a60e1 100644 --- a/internal/compose/resolution/reads_test.go +++ b/internal/compose/resolution/reads_test.go @@ -11,7 +11,7 @@ import ( // novox/hq ADR 0310 §5: the holder is told, by the composition, where its node keeps a secret — the directory // of every module's own secret, every credential file and grant directory, the vault's directories and the // place the operator-sealed secrets are kept — and no other module is told. -func TestTheHolderOfNodeReadsIsToldWhereItsNodeKeepsASecret(t *testing.T) { +func testTheHolderOfNodeReadsIsToldWhereItsNodeKeepsASecret(t *testing.T) { with := mcat.Rendering{ArtifactStore: "anchor.internal:5101", Needed: map[string]map[string]string{"node-tools": {"broker": "sealed-credential"}, "reads": {"broker": "own"}, "desk": {"broker": "own"}}} goRuntime := mcat.Manifest{Module: "node-tools", Version: "1", ToolRunner: true, @@ -67,7 +67,7 @@ func TestTheHolderOfNodeReadsIsToldWhereItsNodeKeepsASecret(t *testing.T) { // The review of #257: a secret place the controller cannot resolve fails the composition, naming the module, // rather than leaving the list one place shorter. -func TestASecretPlaceThatCannotBeResolvedFailsTheComposition(t *testing.T) { +func testASecretPlaceThatCannotBeResolvedFailsTheComposition(t *testing.T) { r := mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{ {Module: "app", Version: "1", Keeps: "${dir:keep}/sealed"}, }} @@ -79,3 +79,9 @@ func TestASecretPlaceThatCannotBeResolvedFailsTheComposition(t *testing.T) { t.Error("a relative place was dropped") } } + +// TestReads runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestReads(t *testing.T) { + t.Run("TheHolderOfNodeReadsIsToldWhereItsNodeKeepsASecret", testTheHolderOfNodeReadsIsToldWhereItsNodeKeepsASecret) + t.Run("ASecretPlaceThatCannotBeResolvedFailsTheComposition", testASecretPlaceThatCannotBeResolvedFailsTheComposition) +} diff --git a/internal/compose/resolution/resolve_test.go b/internal/compose/resolution/resolve_test.go index 757292cf..ca943ea4 100644 --- a/internal/compose/resolution/resolve_test.go +++ b/internal/compose/resolution/resolve_test.go @@ -34,7 +34,7 @@ func names(r mcat.Resolution) []string { return out } -func TestARequirementWithOneAnswerIsTakenSilently(t *testing.T) { +func testARequirementWithOneAnswerIsTakenSilently(t *testing.T) { // `install i3` should bring in xorg without asking anybody anything, because there was no // choice to make. This is what keeps the refusing rule from being tiresome. got, err := Resolve(shelf( @@ -58,7 +58,7 @@ func TestARequirementWithOneAnswerIsTakenSilently(t *testing.T) { // only optional consumers want is left absent (ADR 0330 §3); several answers are still the node's refusal, naming them (the // mesh does not pick: a default would be a choice made for somebody who finds out later); and a node whose every module is held, // or an assigned name nobody wants, is still refused. -func TestARequirementNoOneAnswersHoldsItsConsumersAndSeveralAnswersRefuseTheNode(t *testing.T) { +func testARequirementNoOneAnswersHoldsItsConsumersAndSeveralAnswersRefuseTheNode(t *testing.T) { optional := mod("viewer", nil, []string{"codec"}, nil) optional.OptionalRequires = map[string]bool{"codec": true} hard := mod("player", nil, []string{"codec"}, nil) @@ -125,7 +125,7 @@ func TestARequirementNoOneAnswersHoldsItsConsumersAndSeveralAnswersRefuseTheNode } } -func TestSeveralModulesMayProvideTheSameThingAndCoexist(t *testing.T) { +func testSeveralModulesMayProvideTheSameThingAndCoexist(t *testing.T) { // Shells. Nothing is claimed, so any number may be assigned — which is the case that made // "flavor" look necessary and turns out to need nothing at all. got, err := Resolve(shelf( @@ -142,7 +142,7 @@ func TestSeveralModulesMayProvideTheSameThingAndCoexist(t *testing.T) { } } -func TestTwoModulesClaimingOneThingAreRefused(t *testing.T) { +func testTwoModulesClaimingOneThingAreRefused(t *testing.T) { // xorg and wayland. Neither knows the other exists — the refusal comes from both claiming // the seat, which is what lets a third display server be added without editing either. _, err := Resolve(shelf( @@ -158,7 +158,7 @@ func TestTwoModulesClaimingOneThingAreRefused(t *testing.T) { } } -func TestAThirdModuleNeedsNoChangeToTheOthers(t *testing.T) { +func testAThirdModuleNeedsNoChangeToTheOthers(t *testing.T) { // The property claims exist for. A third display server says what it claims and nothing else // in the catalogue is touched — where pairwise exclusion would need xorg and wayland edited // to know about it, and the edits would grow as the square of the count. @@ -177,7 +177,7 @@ func TestAThirdModuleNeedsNoChangeToTheOthers(t *testing.T) { } } -func TestADirectlyAssignedModuleTheMachineCannotHostIsReportedNotRefused(t *testing.T) { +func testADirectlyAssignedModuleTheMachineCannotHostIsReportedNotRefused(t *testing.T) { // A person put a display server on a seatless machine. The remedy differs from a missing module // and the message has to say which — nothing can be installed to give a server a seat. But it is // one module on the wrong machine, not a reason the whole node fails to resolve: it is kept out @@ -215,7 +215,7 @@ func TestADirectlyAssignedModuleTheMachineCannotHostIsReportedNotRefused(t *test } } -func TestAnUnhostableModuleSomethingRequiresRefusesTheNode(t *testing.T) { +func testAnUnhostableModuleSomethingRequiresRefusesTheNode(t *testing.T) { // The other side of the distinction. A module the machine cannot host that is *required* by // something running here makes the set incoherent: the requiring module cannot have its // requirement met on this machine, so it is refused rather than quietly declared without it. @@ -233,7 +233,7 @@ func TestAnUnhostableModuleSomethingRequiresRefusesTheNode(t *testing.T) { } } -func TestOneUnhostableAssignmentDoesNotTakeDownTheHealthyModules(t *testing.T) { +func testOneUnhostableAssignmentDoesNotTakeDownTheHealthyModules(t *testing.T) { // The bug the whole-mesh dry-run found: fail2ban declares a capability the host lacks, and its // one un-hostable assignment refused the entire node's resolution — so a push refused to send // the healthy modules beside it too. The healthy modules must still resolve and converge; the @@ -268,7 +268,7 @@ func TestOneUnhostableAssignmentDoesNotTakeDownTheHealthyModules(t *testing.T) { } } -func TestAMeshWideClaimIsHeldByOneNode(t *testing.T) { +func testAMeshWideClaimIsHeldByOneNode(t *testing.T) { // The hub, said as a claim rather than hard-coded. Another node already holds it, so this one // cannot. _, err := Resolve(shelf(mod("hub", nil, nil, nil, mcat.Claim{Name: "the-hub", Scope: mcat.ScopeMesh})), @@ -281,7 +281,7 @@ func TestAMeshWideClaimIsHeldByOneNode(t *testing.T) { } } -func TestAFoundationModuleCannotBeRaisedOnASecondNode(t *testing.T) { +func testAFoundationModuleCannotBeRaisedOnASecondNode(t *testing.T) { // novox/hq 04-ISSUES/056. The store and broker are adopted in place on the control-node; each // foundation module claims a mesh-scoped seat named after its server — the same mechanism that // keeps one controller — so a second `assign` to another node is refused rather than silently @@ -303,7 +303,7 @@ func TestAFoundationModuleCannotBeRaisedOnASecondNode(t *testing.T) { } } -func TestASiteClaimOnlyCollidesWithinThatSite(t *testing.T) { +func testASiteClaimOnlyCollidesWithinThatSite(t *testing.T) { // A DHCP server per segment. Two of them is a fault at one site and perfectly ordinary // across two, and treating site as mesh would forbid the ordinary case. catalogue := shelf(mod("dhcp", nil, nil, nil, mcat.Claim{Name: "dhcp", Scope: mcat.ScopeSite})) @@ -319,7 +319,7 @@ func TestASiteClaimOnlyCollidesWithinThatSite(t *testing.T) { } } -func TestTwoModulesWritingOneFileAreRefusedWithoutAnyClaim(t *testing.T) { +func testTwoModulesWritingOneFileAreRefusedWithoutAnyClaim(t *testing.T) { // This conflict costs no manifest field: the mesh already holds every resource of every // module, so two declaring one path are visible without either knowing the other exists. a := mod("a", nil, nil, nil) @@ -336,7 +336,7 @@ func TestTwoModulesWritingOneFileAreRefusedWithoutAnyClaim(t *testing.T) { } } -func TestResourceIdentitiesCarryTheirModule(t *testing.T) { +func testResourceIdentitiesCarryTheirModule(t *testing.T) { // Two modules may reasonably both call something "config". Without the prefix the second // would silently replace the first, and the node would apply one of them and report success. a := mod("a", nil, nil, nil) @@ -361,7 +361,7 @@ func TestResourceIdentitiesCarryTheirModule(t *testing.T) { } } -func TestWhatAServiceReflectsIsQualifiedToo(t *testing.T) { +func testWhatAServiceReflectsIsQualifiedToo(t *testing.T) { // Otherwise it names a resource that no longer exists under that identity, and the service // quietly stops being restarted when its own configuration changes. m := mod("thing", nil, nil, nil) @@ -385,7 +385,7 @@ func TestWhatAServiceReflectsIsQualifiedToo(t *testing.T) { t.Error("the service is missing from the declaration") } -func TestEveryReasonIsGivenAtOnce(t *testing.T) { +func testEveryReasonIsGivenAtOnce(t *testing.T) { // Somebody resolving these fixes them in one pass or in three. Every reason that genuinely // refuses the set is collected, rather than only the first: a claim two modules both take, a // requirement nothing answers, and a requirement several answer without anybody choosing. @@ -406,7 +406,7 @@ func TestEveryReasonIsGivenAtOnce(t *testing.T) { } } -func TestACycleStopsRatherThanRunsAway(t *testing.T) { +func testACycleStopsRatherThanRunsAway(t *testing.T) { // Two modules requiring each other is a mistake somebody makes, and it must produce an answer // rather than a stack overflow. got, err := Resolve(shelf( @@ -422,7 +422,7 @@ func TestACycleStopsRatherThanRunsAway(t *testing.T) { } } -func TestChoosingOneSatisfiesTheRequirement(t *testing.T) { +func testChoosingOneSatisfiesTheRequirement(t *testing.T) { // The other half of refusing. "Choose one and assign it" has to actually work, or the remedy // names three modules and then ignores the one you pick — which is how this read the first // time it was used on a real mesh. @@ -441,7 +441,7 @@ func TestChoosingOneSatisfiesTheRequirement(t *testing.T) { } } -func TestChoosingSeveralIsStillFine(t *testing.T) { +func testChoosingSeveralIsStillFine(t *testing.T) { // And the choice is not exclusive. Nothing is claimed, so a person may have all three and // the requirement is answered by whichever they picked. got, err := Resolve(shelf( @@ -459,7 +459,7 @@ func TestChoosingSeveralIsStillFine(t *testing.T) { } } -func TestARequirementNamingAModuleMeansThatModule(t *testing.T) { +func testARequirementNamingAModuleMeansThatModule(t *testing.T) { // i3 requires xorg and means xorg, not "anything calling itself a display server". Otherwise // assigning wayland would silently satisfy i3 and the machine would come up with a window // manager talking to nothing. @@ -495,7 +495,7 @@ func mustDeclare(t *testing.T, r mcat.Resolution) []map[string]any { // // It went unnoticed because everything proven until then was cross-machine, which is the // interesting case for a mesh and the rare one in practice. -func TestSomethingAnsweredOnThisMachineIsStillANeed(t *testing.T) { +func testSomethingAnsweredOnThisMachineIsStillANeed(t *testing.T) { provider := mcat.Manifest{ Module: "postgres", Version: "1", Provides: mcat.FromAnywhere("postgres-database"), @@ -526,7 +526,7 @@ func TestSomethingAnsweredOnThisMachineIsStillANeed(t *testing.T) { } // A name nothing grants is unchanged: answered here means answered, and nothing more is owed. -func TestSomethingOrdinaryAnsweredHereNeedsNothing(t *testing.T) { +func testSomethingOrdinaryAnsweredHereNeedsNothing(t *testing.T) { got, err := Resolve(shelf( mod("zsh", []string{"shell"}, nil, nil), mod("editor-user", nil, []string{"shell"}, nil), @@ -538,3 +538,28 @@ func TestSomethingOrdinaryAnsweredHereNeedsNothing(t *testing.T) { t.Fatalf("a shell answered on this machine produced %d need(s)", len(got.Needs)) } } + +// TestResolve runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestResolve(t *testing.T) { + t.Run("ARequirementWithOneAnswerIsTakenSilently", testARequirementWithOneAnswerIsTakenSilently) + t.Run("ARequirementNoOneAnswersHoldsItsConsumersAndSeveralAnswersRefuseTheNode", testARequirementNoOneAnswersHoldsItsConsumersAndSeveralAnswersRefuseTheNode) + t.Run("SeveralModulesMayProvideTheSameThingAndCoexist", testSeveralModulesMayProvideTheSameThingAndCoexist) + t.Run("TwoModulesClaimingOneThingAreRefused", testTwoModulesClaimingOneThingAreRefused) + t.Run("AThirdModuleNeedsNoChangeToTheOthers", testAThirdModuleNeedsNoChangeToTheOthers) + t.Run("ADirectlyAssignedModuleTheMachineCannotHostIsReportedNotRefused", testADirectlyAssignedModuleTheMachineCannotHostIsReportedNotRefused) + t.Run("AnUnhostableModuleSomethingRequiresRefusesTheNode", testAnUnhostableModuleSomethingRequiresRefusesTheNode) + t.Run("OneUnhostableAssignmentDoesNotTakeDownTheHealthyModules", testOneUnhostableAssignmentDoesNotTakeDownTheHealthyModules) + t.Run("AMeshWideClaimIsHeldByOneNode", testAMeshWideClaimIsHeldByOneNode) + t.Run("AFoundationModuleCannotBeRaisedOnASecondNode", testAFoundationModuleCannotBeRaisedOnASecondNode) + t.Run("ASiteClaimOnlyCollidesWithinThatSite", testASiteClaimOnlyCollidesWithinThatSite) + t.Run("TwoModulesWritingOneFileAreRefusedWithoutAnyClaim", testTwoModulesWritingOneFileAreRefusedWithoutAnyClaim) + t.Run("ResourceIdentitiesCarryTheirModule", testResourceIdentitiesCarryTheirModule) + t.Run("WhatAServiceReflectsIsQualifiedToo", testWhatAServiceReflectsIsQualifiedToo) + t.Run("EveryReasonIsGivenAtOnce", testEveryReasonIsGivenAtOnce) + t.Run("ACycleStopsRatherThanRunsAway", testACycleStopsRatherThanRunsAway) + t.Run("ChoosingOneSatisfiesTheRequirement", testChoosingOneSatisfiesTheRequirement) + t.Run("ChoosingSeveralIsStillFine", testChoosingSeveralIsStillFine) + t.Run("ARequirementNamingAModuleMeansThatModule", testARequirementNamingAModuleMeansThatModule) + t.Run("SomethingAnsweredOnThisMachineIsStillANeed", testSomethingAnsweredOnThisMachineIsStillANeed) + t.Run("SomethingOrdinaryAnsweredHereNeedsNothing", testSomethingOrdinaryAnsweredHereNeedsNothing) +} diff --git a/internal/compose/resolution/resolved_path_test.go b/internal/compose/resolution/resolved_path_test.go index ec7c7c4d..fe25bb76 100644 --- a/internal/compose/resolution/resolved_path_test.go +++ b/internal/compose/resolution/resolved_path_test.go @@ -6,7 +6,7 @@ import ( mcat "git.novox.be/novox/mesh-sdk/go/catalogue" ) -func TestTheMeshsPlaceForDockerIsAccepted(t *testing.T) { +func testTheMeshsPlaceForDockerIsAccepted(t *testing.T) { // The fix #205 needed: the mesh's own directory for the module, /mesh/docker. m, err := decodeForTest([]byte(`{"module": "docker", "version": "1", "resources": [ {"id": "state", "type": "directory", "place": "mesh"}, @@ -19,7 +19,7 @@ func TestTheMeshsPlaceForDockerIsAccepted(t *testing.T) { } } -func TestComposingAMachineIsNeverStoppedByOneModulesPath(t *testing.T) { +func testComposingAMachineIsNeverStoppedByOneModulesPath(t *testing.T) { // A module registered from outside the catalogue never passes the gate. Refusing its path while a machine's // declaration is composed would fail the whole declaration and freeze every module on that machine; the // node-engine fails only the one resource. So composition leaves it to the engine. @@ -30,3 +30,9 @@ func TestComposingAMachineIsNeverStoppedByOneModulesPath(t *testing.T) { t.Fatalf("the machine's declaration failed for one module's path: %v", err) } } + +// TestResolvedPath runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestResolvedPath(t *testing.T) { + t.Run("TheMeshsPlaceForDockerIsAccepted", testTheMeshsPlaceForDockerIsAccepted) + t.Run("ComposingAMachineIsNeverStoppedByOneModulesPath", testComposingAMachineIsNeverStoppedByOneModulesPath) +} diff --git a/internal/compose/resolution/resolver_file_is_the_uplinks_test.go b/internal/compose/resolution/resolver_file_is_the_uplinks_test.go index 9f555acd..842a16c7 100644 --- a/internal/compose/resolution/resolver_file_is_the_uplinks_test.go +++ b/internal/compose/resolution/resolver_file_is_the_uplinks_test.go @@ -7,7 +7,7 @@ import ( mcat "git.novox.be/novox/mesh-sdk/go/catalogue" ) -func TestTheResolverConfigSeatIsGone(t *testing.T) { +func testTheResolverConfigSeatIsGone(t *testing.T) { if _, known := mcat.SeatNamed("node-resolver-config"); known { t.Error("node-resolver-config is still in the mesh's set; the uplink's holder writes the resolver file") } @@ -19,7 +19,7 @@ func TestTheResolverConfigSeatIsGone(t *testing.T) { // The catalogue as it is: nothing claims the retired seat, and every manager the mesh knows holds the // uplink and writes the resolver file; beside them only a holder of node-resolver does (ADR 0247). -func TestTheCataloguesUplinksWriteTheResolverFileAndNothingElseDoes(t *testing.T) { +func testTheCataloguesUplinksWriteTheResolverFileAndNothingElseDoes(t *testing.T) { cat := map[string]mcat.Manifest{} for _, m := range theCatalogue(t) { cat[m.Module] = m @@ -55,3 +55,9 @@ func TestTheCataloguesUplinksWriteTheResolverFileAndNothingElseDoes(t *testing.T } } } + +// TestResolverFileIsTheUplinks runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestResolverFileIsTheUplinks(t *testing.T) { + t.Run("TheResolverConfigSeatIsGone", testTheResolverConfigSeatIsGone) + t.Run("TheCataloguesUplinksWriteTheResolverFileAndNothingElseDoes", testTheCataloguesUplinksWriteTheResolverFileAndNothingElseDoes) +} diff --git a/internal/compose/resolution/resolver_manifests_test.go b/internal/compose/resolution/resolver_manifests_test.go index 5a8d3b11..4ed1160e 100644 --- a/internal/compose/resolution/resolver_manifests_test.go +++ b/internal/compose/resolution/resolver_manifests_test.go @@ -30,7 +30,7 @@ var twoMachines = map[string]string{"anchor.internal": "10.42.0.1", "laptop.inte // mesh's account of every machine as a wildcard, the suffix kept local, the daemon restarting on // that file, the machine pointed at the resolver by address, and the runtime given no resolver of // its own but kept running across a restart (ADR 0196). -func TestTheResolverAndWhatAsksItComposeOnOneMachine(t *testing.T) { +func testTheResolverAndWhatAsksItComposeOnOneMachine(t *testing.T) { got, err := Resolve(resolverShelf(t), []string{"dnsmasq", "systemd-networkd", "docker"}, mcat.Node{Name: "anchor", At: "anchor.internal", Capabilities: map[string]bool{ "package-manager": true, "service-manager": true, "privileged": true, "uplink-systemd-networkd": true}}, mcat.World{}) @@ -158,7 +158,7 @@ func TestTheResolverAndWhatAsksItComposeOnOneMachine(t *testing.T) { // Two modules deciding what a machine asks are refused on one machine, as before — now that the file // is the uplink's (novox/hq ADR 0223), by two things: a machine runs one network manager, and no other // module may write the resolver file beside the uplink's, as a file or as a rendered fact. -func TestTwoThingsDecidingWhatAMachineAsksAreRefused(t *testing.T) { +func testTwoThingsDecidingWhatAMachineAsksAreRefused(t *testing.T) { shelf := resolverShelf(t) shelf["networkmanager"] = catalogueManifest(t, "networkmanager") node := mcat.Node{Name: "anchor", At: "anchor.internal", Capabilities: map[string]bool{ @@ -189,7 +189,7 @@ func TestTwoThingsDecidingWhatAMachineAsksAreRefused(t *testing.T) { // A machine that is not on the private network has no address for the runtime to be pointed at. // Refused where the module and the machine are both named, rather than a placeholder written into // the runtime's file and read as an address. -func TestTheResolverOnAMachineOffTheNetworkIsRefused(t *testing.T) { +func testTheResolverOnAMachineOffTheNetworkIsRefused(t *testing.T) { got, err := Resolve(resolverShelf(t), []string{"dnsmasq"}, mcat.Node{Name: "anchor"}, mcat.World{}) if err != nil { t.Fatal(err) @@ -230,3 +230,10 @@ func daemonKeysDeclared(t *testing.T) map[string]bool { t.Fatal("the docker module declares no daemon.json") return nil } + +// TestResolverManifests runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestResolverManifests(t *testing.T) { + t.Run("TheResolverAndWhatAsksItComposeOnOneMachine", testTheResolverAndWhatAsksItComposeOnOneMachine) + t.Run("TwoThingsDecidingWhatAMachineAsksAreRefused", testTwoThingsDecidingWhatAMachineAsksAreRefused) + t.Run("TheResolverOnAMachineOffTheNetworkIsRefused", testTheResolverOnAMachineOffTheNetworkIsRefused) +} diff --git a/internal/compose/resolution/routing_test.go b/internal/compose/resolution/routing_test.go index 1ed52810..119e80eb 100644 --- a/internal/compose/resolution/routing_test.go +++ b/internal/compose/resolution/routing_test.go @@ -22,7 +22,7 @@ func withDomain(domain string) mcat.Node { return n } -func TestALabelComposesWithTheNodesPublicDomain(t *testing.T) { +func testALabelComposesWithTheNodesPublicDomain(t *testing.T) { got, err := Resolve(shelf(proxy(), labelled("board", "git", 8080)), []string{"board"}, withDomain("example.tld"), mcat.World{}) if err != nil { @@ -42,7 +42,7 @@ func TestALabelComposesWithTheNodesPublicDomain(t *testing.T) { } } -func TestTheApexLabelComposesToTheBareDomain(t *testing.T) { +func testTheApexLabelComposesToTheBareDomain(t *testing.T) { got, err := Resolve(shelf(proxy(), labelled("board", "@", 4000)), []string{"board"}, withDomain("example.tld"), mcat.World{}) if err != nil { @@ -58,7 +58,7 @@ func TestTheApexLabelComposesToTheBareDomain(t *testing.T) { } } -func TestOneNodeSettingMovesTheCatalogueBetweenDomains(t *testing.T) { +func testOneNodeSettingMovesTheCatalogueBetweenDomains(t *testing.T) { // The ADR's name-agnostic check: the same catalogue resolves against two different public // domains by changing one node setting and nothing else. one, err := Resolve(shelf(proxy(), labelled("board", "git", 8080)), @@ -87,7 +87,7 @@ func TestOneNodeSettingMovesTheCatalogueBetweenDomains(t *testing.T) { } } -func TestALegacyFullNameContributionPassesThroughUnchanged(t *testing.T) { +func testALegacyFullNameContributionPassesThroughUnchanged(t *testing.T) { // Backward compatibility: a contribution that still carries a full `name` and no `label` is // granted that name as-is, even on a node that has a public domain. This is what lets the // catalogue migrate one module at a time while the running mesh keeps working. @@ -108,7 +108,7 @@ func TestALegacyFullNameContributionPassesThroughUnchanged(t *testing.T) { } } -func TestALabelWithNoPublicDomainComposesNothing(t *testing.T) { +func testALabelWithNoPublicDomainComposesNothing(t *testing.T) { // A routed module on a node with no public domain has nothing to join its label to. It composes // no name — which reads downstream exactly as a route that named no host, the same as before // this existed — rather than an fabricated `git.` with a dangling dot. @@ -134,7 +134,7 @@ func withPrivateAddress(at string) mcat.Node { return n } -func TestALabelComposesWithTheNodesPrivateAddressToo(t *testing.T) { +func testALabelComposesWithTheNodesPrivateAddressToo(t *testing.T) { // A predecessor proxy answered a route on both a public and a private-network hostname for the // same convenience the mesh restores here: reaching a service over the VPN without a public TLS // round trip. Composed independently of the public name, from the node's own `At`. @@ -149,7 +149,7 @@ func TestALabelComposesWithTheNodesPrivateAddressToo(t *testing.T) { } } -func TestThePublicAndInternalNamesComposeIndependently(t *testing.T) { +func testThePublicAndInternalNamesComposeIndependently(t *testing.T) { // A node with both a public domain and a private address gets both names from one label; a // node with only one of the two gets only the matching one — neither composition depends on // the other being possible. @@ -180,7 +180,7 @@ func TestThePublicAndInternalNamesComposeIndependently(t *testing.T) { } } -func TestTheApexLabelComposesToTheBarePrivateAddress(t *testing.T) { +func testTheApexLabelComposesToTheBarePrivateAddress(t *testing.T) { got, err := Resolve(shelf(proxy(), labelled("board", "@", 4000)), []string{"board"}, withPrivateAddress("anchor.internal"), mcat.World{}) if err != nil { @@ -196,7 +196,7 @@ func TestTheApexLabelComposesToTheBarePrivateAddress(t *testing.T) { // machine's roster mapped to the node that serves it, beside the `.internal` names, and the // machine's resolver answers it to every container. Nothing is written into the container itself — // a routed name that moved would otherwise be wrong inside every container until each was recreated. -func TestARoutedNameResolvesToTheServingNode(t *testing.T) { +func testARoutedNameResolvesToTheServingNode(t *testing.T) { names := map[string]string{ "anchor.internal": "10.42.0.1", "git.example.tld": "10.42.0.1", @@ -228,7 +228,7 @@ func TestARoutedNameResolvesToTheServingNode(t *testing.T) { // be the one whose proxy answers it. Composed under the consumer's own name, a route served from // another machine got an internal name that resolved to a machine with nothing listening, while the // public name — published at the serving node's address — worked. -func TestARoutesInternalNameIsComposedUnderTheNodeThatServesIt(t *testing.T) { +func testARoutesInternalNameIsComposedUnderTheNodeThatServesIt(t *testing.T) { hub := proxy() hub.Provides = mcat.FromAnywhere("reverse-proxy") got, err := Resolve(shelf(hub, labelled("board", "git", 8080)), []string{"board"}, @@ -248,3 +248,17 @@ func TestARoutesInternalNameIsComposedUnderTheNodeThatServesIt(t *testing.T) { t.Fatalf("the internal name does not say where the request arrives: %v", values) } } + +// TestRouting runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRouting(t *testing.T) { + t.Run("ALabelComposesWithTheNodesPublicDomain", testALabelComposesWithTheNodesPublicDomain) + t.Run("TheApexLabelComposesToTheBareDomain", testTheApexLabelComposesToTheBareDomain) + t.Run("OneNodeSettingMovesTheCatalogueBetweenDomains", testOneNodeSettingMovesTheCatalogueBetweenDomains) + t.Run("ALegacyFullNameContributionPassesThroughUnchanged", testALegacyFullNameContributionPassesThroughUnchanged) + t.Run("ALabelWithNoPublicDomainComposesNothing", testALabelWithNoPublicDomainComposesNothing) + t.Run("ALabelComposesWithTheNodesPrivateAddressToo", testALabelComposesWithTheNodesPrivateAddressToo) + t.Run("ThePublicAndInternalNamesComposeIndependently", testThePublicAndInternalNamesComposeIndependently) + t.Run("TheApexLabelComposesToTheBarePrivateAddress", testTheApexLabelComposesToTheBarePrivateAddress) + t.Run("ARoutedNameResolvesToTheServingNode", testARoutedNameResolvesToTheServingNode) + t.Run("ARoutesInternalNameIsComposedUnderTheNodeThatServesIt", testARoutesInternalNameIsComposedUnderTheNodeThatServesIt) +} diff --git a/internal/compose/resolution/runtime_test.go b/internal/compose/resolution/runtime_test.go index 8d44248a..8fb59b4a 100644 --- a/internal/compose/resolution/runtime_test.go +++ b/internal/compose/resolution/runtime_test.go @@ -43,7 +43,7 @@ func theRuntime(t *testing.T) mcat.Manifest { return resolved } -func TestEveryToolsBundleIsDeliveredWhereTheRuntimeRuns(t *testing.T) { +func testEveryToolsBundleIsDeliveredWhereTheRuntimeRuns(t *testing.T) { store := mcat.Rendering{ArtifactStore: "anchor.internal:5101", Needed: map[string]map[string]string{"node-tools": {"broker": "sealed-credential"}}} nftables := aToolsModule(t, "nftables", "tools/index.js") @@ -111,7 +111,7 @@ func ids(out []map[string]any) []string { // One process per machine runs the runtime from its own bundle, told what it serves and from where, // where its credential is, and who the operator is — restarted when any of that changes. -func TestTheMachineRunsOneRuntimeLoadingEveryDeliveredBundle(t *testing.T) { +func testTheMachineRunsOneRuntimeLoadingEveryDeliveredBundle(t *testing.T) { with := mcat.Rendering{ArtifactStore: "anchor.internal:5101", Needed: map[string]map[string]string{"node-tools": {"broker": "sealed-credential"}}} nftables := aToolsModule(t, "nftables", "tools/index.js") @@ -239,7 +239,7 @@ func TestTheMachineRunsOneRuntimeLoadingEveryDeliveredBundle(t *testing.T) { // novox/hq ADR 0193: the runtime is told the launcher a build wrote, and the entrypoint itself for a // build from before launchers — so the move needs no flag day. -func TestTheRuntimeStartsTheLauncherWhereTheBuildWroteOne(t *testing.T) { +func testTheRuntimeStartsTheLauncherWhereTheBuildWroteOne(t *testing.T) { with := mcat.Rendering{ArtifactStore: "anchor.internal:5101", Needed: map[string]map[string]string{"node-tools": {"broker": "sealed-credential"}}} launched := mcat.Manifest{Module: "dash", Version: "1", Tools: []string{"status"}, @@ -264,7 +264,7 @@ func TestTheRuntimeStartsTheLauncherWhereTheBuildWroteOne(t *testing.T) { } // novox/hq ADR 0193: a runtime compiled to a binary runs itself from its own unpacked bundle. -func TestARuntimeCompiledToABinaryRunsItself(t *testing.T) { +func testARuntimeCompiledToABinaryRunsItself(t *testing.T) { with := mcat.Rendering{ArtifactStore: "anchor.internal:5101", Needed: map[string]map[string]string{"node-tools": {"broker": "sealed-credential"}}} goRuntime := mcat.Manifest{Module: "node-tools", Version: "1", ToolRunner: true, @@ -293,7 +293,7 @@ func TestARuntimeCompiledToABinaryRunsItself(t *testing.T) { // novox/hq ADR 0259 §8: a module of its own account is served by a runtime of its own — the machine's // runtime program, as that account, on that module's own credential — and never by the machine's runtime, // which runs as the operator's account and is given none of its words. -func TestAModuleOfItsOwnAccountIsServedByARuntimeOfItsOwn(t *testing.T) { +func testAModuleOfItsOwnAccountIsServedByARuntimeOfItsOwn(t *testing.T) { with := mcat.Rendering{ArtifactStore: "anchor.internal:5101", Needed: map[string]map[string]string{"node-tools": {"broker": "sealed-credential"}, "telegram": {"broker": "own"}}} goRuntime := mcat.Manifest{Module: "node-tools", Version: "1", ToolRunner: true, @@ -395,7 +395,7 @@ func TestAModuleOfItsOwnAccountIsServedByARuntimeOfItsOwn(t *testing.T) { // The review of 2026-10-09 (L4): a module of its own account never runs as the node's operator account, nor // as the account agents run as there — either would hand what it holds back to the accounts it is kept from. -func TestAModuleOfItsOwnAccountIsRefusedTheOperatorsAndTheAgentsAccount(t *testing.T) { +func testAModuleOfItsOwnAccountIsRefusedTheOperatorsAndTheAgentsAccount(t *testing.T) { with := mcat.Rendering{ArtifactStore: "anchor.internal:5101", Needed: map[string]map[string]string{"node-tools": {"broker": "sealed-credential"}, "telegram": {"broker": "own"}}} goRuntime := mcat.Manifest{Module: "node-tools", Version: "1", ToolRunner: true, @@ -421,7 +421,7 @@ func TestAModuleOfItsOwnAccountIsRefusedTheOperatorsAndTheAgentsAccount(t *testi // Issue 723: the vault runs as its own account, so what the mesh writes for it — the export it keeps, the grant // files it holds for its consumers, and what its words name — belongs to that account, never the operator's. -func TestWhatAModuleOfItsOwnAccountReadsIsItsAccounts(t *testing.T) { +func testWhatAModuleOfItsOwnAccountReadsIsItsAccounts(t *testing.T) { with := mcat.Rendering{ArtifactStore: "anchor.internal:5101", Needed: map[string]map[string]string{"node-tools": {"broker": "sealed-credential"}, "vault": {"broker": "own"}}, Kept: &mcat.KeptExport{Export: 1, OperatorKey: "k"}, @@ -474,3 +474,14 @@ func TestWhatAModuleOfItsOwnAccountReadsIsItsAccounts(t *testing.T) { } } } + +// TestRuntime runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRuntime(t *testing.T) { + t.Run("EveryToolsBundleIsDeliveredWhereTheRuntimeRuns", testEveryToolsBundleIsDeliveredWhereTheRuntimeRuns) + t.Run("TheMachineRunsOneRuntimeLoadingEveryDeliveredBundle", testTheMachineRunsOneRuntimeLoadingEveryDeliveredBundle) + t.Run("TheRuntimeStartsTheLauncherWhereTheBuildWroteOne", testTheRuntimeStartsTheLauncherWhereTheBuildWroteOne) + t.Run("ARuntimeCompiledToABinaryRunsItself", testARuntimeCompiledToABinaryRunsItself) + t.Run("AModuleOfItsOwnAccountIsServedByARuntimeOfItsOwn", testAModuleOfItsOwnAccountIsServedByARuntimeOfItsOwn) + t.Run("AModuleOfItsOwnAccountIsRefusedTheOperatorsAndTheAgentsAccount", testAModuleOfItsOwnAccountIsRefusedTheOperatorsAndTheAgentsAccount) + t.Run("WhatAModuleOfItsOwnAccountReadsIsItsAccounts", testWhatAModuleOfItsOwnAccountReadsIsItsAccounts) +} diff --git a/internal/compose/resolution/seat_contributions_test.go b/internal/compose/resolution/seat_contributions_test.go index 8243e2db..5e278762 100644 --- a/internal/compose/resolution/seat_contributions_test.go +++ b/internal/compose/resolution/seat_contributions_test.go @@ -13,7 +13,7 @@ func hotkeysHolder() mcat.Manifest { }} } -func TestAContributionReachesTheHoldersFileInModuleOrderNamedByModule(t *testing.T) { +func testAContributionReachesTheHoldersFileInModuleOrderNamedByModule(t *testing.T) { laptop := mcat.Manifest{Module: "laptop", Contributions: []mcat.SeatContribution{ {Seat: mcat.HotkeysSeat, Kind: "trigger", Content: "KEY_PROG1 1 play ${machine:account-home}"}, {Seat: mcat.HotkeysSeat, Kind: "trigger", Content: "KEY_F21 1 touchpad\n"}, @@ -48,7 +48,7 @@ func TestAContributionReachesTheHoldersFileInModuleOrderNamedByModule(t *testing } } -func TestNoContributionPlacesNothing(t *testing.T) { +func testNoContributionPlacesNothing(t *testing.T) { r := mcat.Resolution{Node: "laptop", Account: "op", Modules: []mcat.Manifest{hotkeysHolder()}} out, err := Declaration(r, mcat.Rendering{}) if err != nil { @@ -60,3 +60,9 @@ func TestNoContributionPlacesNothing(t *testing.T) { } } } + +// TestSeatContributions runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSeatContributions(t *testing.T) { + t.Run("AContributionReachesTheHoldersFileInModuleOrderNamedByModule", testAContributionReachesTheHoldersFileInModuleOrderNamedByModule) + t.Run("NoContributionPlacesNothing", testNoContributionPlacesNothing) +} diff --git a/internal/compose/resolution/seat_data_test.go b/internal/compose/resolution/seat_data_test.go index 4a55517e..9b8ab964 100644 --- a/internal/compose/resolution/seat_data_test.go +++ b/internal/compose/resolution/seat_data_test.go @@ -55,7 +55,7 @@ func composedFile(t *testing.T, r mcat.Resolution, id string) string { return "" } -func TestResolveCarriesTheMachinesCapabilities(t *testing.T) { +func testResolveCarriesTheMachinesCapabilities(t *testing.T) { node := workstation() node.Capabilities["battery"] = true r, err := Resolve(shelf(mcat.Manifest{Module: "a"}), []string{"a"}, node, mcat.World{}) @@ -67,7 +67,7 @@ func TestResolveCarriesTheMachinesCapabilities(t *testing.T) { } } -func TestAPieceTheHolderCannotRenderIsLeftOutAndNamedNotTheMachine(t *testing.T) { +func testAPieceTheHolderCannotRenderIsLeftOutAndNamedNotTheMachine(t *testing.T) { // A shows the shape gained after the holder's template was written: built here, past the check. power := mcat.Manifest{Module: "power", Contributions: []mcat.SeatContribution{ block(`{"bar":"bottom","place":"status","shows":"gpu"}`), @@ -89,7 +89,7 @@ func TestAPieceTheHolderCannotRenderIsLeftOutAndNamedNotTheMachine(t *testing.T) } } -func TestAnOfferedBlockMakesNoDependencyOnTheBar(t *testing.T) { +func testAnOfferedBlockMakesNoDependencyOnTheBar(t *testing.T) { power := mcat.Manifest{Module: "power", Contributions: []mcat.SeatContribution{ block(`{"bar":"bottom","place":"status","shows":"battery"}`), {Seat: mcat.HotkeysSeat, Kind: "trigger", Content: "x"}, @@ -106,3 +106,10 @@ func TestAnOfferedBlockMakesNoDependencyOnTheBar(t *testing.T) { t.Fatal(err) } } + +// TestSeatData runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSeatData(t *testing.T) { + t.Run("ResolveCarriesTheMachinesCapabilities", testResolveCarriesTheMachinesCapabilities) + t.Run("APieceTheHolderCannotRenderIsLeftOutAndNamedNotTheMachine", testAPieceTheHolderCannotRenderIsLeftOutAndNamedNotTheMachine) + t.Run("AnOfferedBlockMakesNoDependencyOnTheBar", testAnOfferedBlockMakesNoDependencyOnTheBar) +} diff --git a/internal/compose/resolution/seat_dependencies_test.go b/internal/compose/resolution/seat_dependencies_test.go index 806fdf7e..dd55ec27 100644 --- a/internal/compose/resolution/seat_dependencies_test.go +++ b/internal/compose/resolution/seat_dependencies_test.go @@ -40,7 +40,7 @@ func coreThree() []mcat.Manifest { } } -func TestADependencyIsDerivedFromEachResourceTypeThatAppliesThroughASeat(t *testing.T) { +func testADependencyIsDerivedFromEachResourceTypeThatAppliesThroughASeat(t *testing.T) { cases := map[string][]string{ "service": {mcat.ServiceManagerSeat}, "package": {mcat.PackageManagerSeat}, @@ -65,7 +65,7 @@ func TestADependencyIsDerivedFromEachResourceTypeThatAppliesThroughASeat(t *test } } -func TestStatusIsToldOfAnUnmetDependencyAndTheNodeStillResolves(t *testing.T) { +func testStatusIsToldOfAnUnmetDependencyAndTheNodeStillResolves(t *testing.T) { // Before the switch (the state the mesh ran in until every node held the three seats). enforceSeatDependencies = false defer func() { enforceSeatDependencies = true }() @@ -81,7 +81,7 @@ func TestStatusIsToldOfAnUnmetDependencyAndTheNodeStillResolves(t *testing.T) { } } -func TestWithTheSwitchFlippedAnUnmetDependencyRefusesTheNode(t *testing.T) { +func testWithTheSwitchFlippedAnUnmetDependencyRefusesTheNode(t *testing.T) { enforceSeatDependencies = true defer func() { enforceSeatDependencies = true }() web := withResources(mod("web", nil, nil, nil), res("container", "web")) @@ -96,7 +96,7 @@ func TestWithTheSwitchFlippedAnUnmetDependencyRefusesTheNode(t *testing.T) { } } -func TestTheFoundationHostIsTheEntryThatClaimsTheNodeEngineSeat(t *testing.T) { +func testTheFoundationHostIsTheEntryThatClaimsTheNodeEngineSeat(t *testing.T) { svc := res("service", "x") // Whatever its name, the entry claiming the seat is the foundation's: nothing to depend on. engine := withResources(mod("the-engine", nil, nil, nil, mcat.Claim{Name: "node-engine"}), svc) @@ -109,3 +109,11 @@ func TestTheFoundationHostIsTheEntryThatClaimsTheNodeEngineSeat(t *testing.T) { t.Errorf("a module merely named mesh-host depends on %v, want the service manager seat", got) } } + +// TestSeatDependencies runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSeatDependencies(t *testing.T) { + t.Run("ADependencyIsDerivedFromEachResourceTypeThatAppliesThroughASeat", testADependencyIsDerivedFromEachResourceTypeThatAppliesThroughASeat) + t.Run("StatusIsToldOfAnUnmetDependencyAndTheNodeStillResolves", testStatusIsToldOfAnUnmetDependencyAndTheNodeStillResolves) + t.Run("WithTheSwitchFlippedAnUnmetDependencyRefusesTheNode", testWithTheSwitchFlippedAnUnmetDependencyRefusesTheNode) + t.Run("TheFoundationHostIsTheEntryThatClaimsTheNodeEngineSeat", testTheFoundationHostIsTheEntryThatClaimsTheNodeEngineSeat) +} diff --git a/internal/compose/resolution/seat_into_test.go b/internal/compose/resolution/seat_into_test.go index 41e3a080..3c96b67f 100644 --- a/internal/compose/resolution/seat_into_test.go +++ b/internal/compose/resolution/seat_into_test.go @@ -8,7 +8,7 @@ import ( mcat "git.novox.be/novox/mesh-sdk/go/catalogue" ) -func TestASeatPlaceholderAnswersWhereThisMachinePutTheHolder(t *testing.T) { +func testASeatPlaceholderAnswersWhereThisMachinePutTheHolder(t *testing.T) { control := map[string]any{ "type": "container", "id": "server", "name": "mesh-controller", "env": map[string]any{ @@ -39,7 +39,7 @@ func TestASeatPlaceholderAnswersWhereThisMachinePutTheHolder(t *testing.T) { // with nothing, so the port genesis wrote into the connection string stands. Not the software's // own port: on a node given a port at genesis before the store's module exists, that would // override the right number with the catalogue's. -func TestASeatTheMeshCannotPlaceAnswersWithNothing(t *testing.T) { +func testASeatTheMeshCannotPlaceAnswersWithNothing(t *testing.T) { control := map[string]any{ "type": "container", "id": "server", "name": "mesh-controller", "env": map[string]any{"MESH_STORE_INVENTORY_PORT": "${seat:mesh-store:5432}"}, @@ -59,14 +59,14 @@ func TestASeatTheMeshCannotPlaceAnswersWithNothing(t *testing.T) { } } -func TestASeatPlaceholderNamingNoPortIsRefused(t *testing.T) { +func testASeatPlaceholderNamingNoPortIsRefused(t *testing.T) { file := map[string]any{"type": "file", "content": "${seat:mesh-store:99999}"} if err := seatInto(file, "x", mcat.Rendering{}); err == nil { t.Fatal("99999 was accepted as a port") } } -func TestFillingASeatLeavesTheManifestAlone(t *testing.T) { +func testFillingASeatLeavesTheManifestAlone(t *testing.T) { env := map[string]any{"MESH_STORE_INVENTORY_PORT": "${seat:mesh-store:5432}"} manifest := map[string]any{"type": "container", "id": "server", "env": env} for _, at := range []int{6852, 5432} { @@ -91,7 +91,7 @@ func runtimeTrust() map[string]any { } } -func TestASeatsReachIsWhereThisMachineReachesItsHolder(t *testing.T) { +func testASeatsReachIsWhereThisMachineReachesItsHolder(t *testing.T) { file := runtimeTrust() with := mcat.Rendering{SeatReach: map[string]string{"mesh-artifact-store": "anchor.internal:5100"}} if err := seatInto(file, "docker", with); err != nil { @@ -128,7 +128,7 @@ func TestASeatsReachIsWhereThisMachineReachesItsHolder(t *testing.T) { // With no holder reachable, the runtime is not told to trust "": the member is dropped, and the // list with it when nothing else is in it. -func TestAnUnansweredReachAddsNothingToAList(t *testing.T) { +func testAnUnansweredReachAddsNothingToAList(t *testing.T) { file := runtimeTrust() if err := seatInto(file, "docker", mcat.Rendering{}); err != nil { t.Fatal(err) @@ -147,7 +147,7 @@ func TestAnUnansweredReachAddsNothingToAList(t *testing.T) { } } -func TestAReachTheMeshDoesNotAnswerIsRefused(t *testing.T) { +func testAReachTheMeshDoesNotAnswerIsRefused(t *testing.T) { file := map[string]any{"type": "file", "content": "${seat:mesh-store:reach}"} err := seatInto(file, "x", mcat.Rendering{SeatReach: map[string]string{"mesh-store": "anchor.internal:5432"}}) if err == nil || !strings.Contains(err.Error(), "mesh-artifact-store") { @@ -156,7 +156,7 @@ func TestAReachTheMeshDoesNotAnswerIsRefused(t *testing.T) { } // Through the whole composition, as the container runtime's module declares it. -func TestTheRuntimesTrustIsComposedFromTheSeatsReach(t *testing.T) { +func testTheRuntimesTrustIsComposedFromTheSeatsReach(t *testing.T) { r := mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{{ Module: "docker", Resources: []map[string]any{runtimeTrust()}, }}} @@ -174,3 +174,15 @@ func TestTheRuntimesTrustIsComposedFromTheSeatsReach(t *testing.T) { t.Fatalf("the runtime's file says %q", got) } } + +// TestSeatInto runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSeatInto(t *testing.T) { + t.Run("ASeatPlaceholderAnswersWhereThisMachinePutTheHolder", testASeatPlaceholderAnswersWhereThisMachinePutTheHolder) + t.Run("ASeatTheMeshCannotPlaceAnswersWithNothing", testASeatTheMeshCannotPlaceAnswersWithNothing) + t.Run("ASeatPlaceholderNamingNoPortIsRefused", testASeatPlaceholderNamingNoPortIsRefused) + t.Run("FillingASeatLeavesTheManifestAlone", testFillingASeatLeavesTheManifestAlone) + t.Run("ASeatsReachIsWhereThisMachineReachesItsHolder", testASeatsReachIsWhereThisMachineReachesItsHolder) + t.Run("AnUnansweredReachAddsNothingToAList", testAnUnansweredReachAddsNothingToAList) + t.Run("AReachTheMeshDoesNotAnswerIsRefused", testAReachTheMeshDoesNotAnswerIsRefused) + t.Run("TheRuntimesTrustIsComposedFromTheSeatsReach", testTheRuntimesTrustIsComposedFromTheSeatsReach) +} diff --git a/internal/compose/resolution/seat_paths_test.go b/internal/compose/resolution/seat_paths_test.go index 82b7e222..4b478414 100644 --- a/internal/compose/resolution/seat_paths_test.go +++ b/internal/compose/resolution/seat_paths_test.go @@ -15,7 +15,7 @@ func (writesHosts) Resources(string) ([]map[string]any, bool, error) { } // The controller is bound too: what it generates for a machine on a seat's path is refused at composition. -func TestAGeneratedResourceOnASeatsPathIsRefused(t *testing.T) { +func testAGeneratedResourceOnASeatsPathIsRefused(t *testing.T) { r := mcat.Resolution{Node: "workstation", Modules: []mcat.Manifest{ {Module: "mesh-names", Computed: "mesh-names"}, }} @@ -53,7 +53,7 @@ func TestAGeneratedResourceOnASeatsPathIsRefused(t *testing.T) { // The stepping back comes from the seat, and is of a rendered file only: an uplink holder declaring the // resolver file as a resource beside a node-resolver holder is two writers of one path, refused when the // machine is resolved — never composed twice — as before the seat named its paths. -func TestAnUplinkDeclaringTheResolverFileAsAResourceIsRefusedBesideTheResolver(t *testing.T) { +func testAnUplinkDeclaringTheResolverFileAsAResourceIsRefusedBesideTheResolver(t *testing.T) { shelf := resolverShelf(t) uplink := shelf["systemd-networkd"] uplink.Facts = nil @@ -74,3 +74,9 @@ func TestAnUplinkDeclaringTheResolverFileAsAResourceIsRefusedBesideTheResolver(t t.Errorf("the uplink's holder renders %v beside the resolver", got.Facts) } } + +// TestSeatPaths runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSeatPaths(t *testing.T) { + t.Run("AGeneratedResourceOnASeatsPathIsRefused", testAGeneratedResourceOnASeatsPathIsRefused) + t.Run("AnUplinkDeclaringTheResolverFileAsAResourceIsRefusedBesideTheResolver", testAnUplinkDeclaringTheResolverFileAsAResourceIsRefusedBesideTheResolver) +} diff --git a/internal/compose/resolution/seats_test.go b/internal/compose/resolution/seats_test.go index 73a0c89b..f33da240 100644 --- a/internal/compose/resolution/seats_test.go +++ b/internal/compose/resolution/seats_test.go @@ -30,7 +30,7 @@ func giteaHoldsTheSeat() []mcat.Held { return []mcat.Held{{Claim: "npm-package-registry", Scope: mcat.ScopeMesh, Node: "anchor", Module: "gitea"}} } -func TestTheSeatsHolderAnswersWhenSeveralProvide(t *testing.T) { +func testTheSeatsHolderAnswersWhenSeveralProvide(t *testing.T) { // The whole point: a second registry beside the holder harms nothing, and nobody pins. got, err := Resolve(registryShelf(), []string{"builder"}, reachable(), mcat.World{Offered: twoRegistries(), Held: giteaHoldsTheSeat()}) if err != nil { @@ -41,7 +41,7 @@ func TestTheSeatsHolderAnswersWhenSeveralProvide(t *testing.T) { } } -func TestAPinStillWinsOverTheSeat(t *testing.T) { +func testAPinStillWinsOverTheSeat(t *testing.T) { // A consumer coupled to one provider's contents has said so, and the seat does not overrule it. got, err := Resolve(registryShelf(), []string{"builder"}, reachable(), mcat.World{Offered: twoRegistries(), Held: giteaHoldsTheSeat(), Pinned: map[string]mcat.Chosen{"npm-package-registry": {Node: "archive", Module: "verdaccio"}}}) @@ -53,7 +53,7 @@ func TestAPinStillWinsOverTheSeat(t *testing.T) { } } -func TestWithTheSeatUnheldSeveralProvidersAreStillRefused(t *testing.T) { +func testWithTheSeatUnheldSeveralProvidersAreStillRefused(t *testing.T) { // No seat held is no choice made, and ADR 0009's rule stands: never guessed. _, err := Resolve(registryShelf(), []string{"builder"}, reachable(), mcat.World{Offered: twoRegistries()}) if err == nil { @@ -64,7 +64,7 @@ func TestWithTheSeatUnheldSeveralProvidersAreStillRefused(t *testing.T) { } } -func TestTheHolderIsTheModuleNotTheMachine(t *testing.T) { +func testTheHolderIsTheModuleNotTheMachine(t *testing.T) { // Two modules on one machine could provide the same thing; only the one holding the seat // answers. A holder matched by node alone would send consumers to whichever came first. providers := []mcat.Provider{ @@ -165,3 +165,11 @@ func verbCopies(t *testing.T, name string, src any) []string { }) return out } + +// TestSeats runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSeats(t *testing.T) { + t.Run("TheSeatsHolderAnswersWhenSeveralProvide", testTheSeatsHolderAnswersWhenSeveralProvide) + t.Run("APinStillWinsOverTheSeat", testAPinStillWinsOverTheSeat) + t.Run("WithTheSeatUnheldSeveralProvidersAreStillRefused", testWithTheSeatUnheldSeveralProvidersAreStillRefused) + t.Run("TheHolderIsTheModuleNotTheMachine", testTheHolderIsTheModuleNotTheMachine) +} diff --git a/internal/compose/resolution/secret_restart_test.go b/internal/compose/resolution/secret_restart_test.go index c8fb993e..2de2c30a 100644 --- a/internal/compose/resolution/secret_restart_test.go +++ b/internal/compose/resolution/secret_restart_test.go @@ -12,7 +12,7 @@ import ( // issue 206): the build machine kept an hour-old credential open because its manifest restarted it // on its environment file alone. Composed, so a manifest need not say it; a scheduled process is // left alone, because the host refuses a restart-on for one and it reads the file afresh each run. -func TestAContainerReadingAnOwnSecretIsRestartedWhenItChanges(t *testing.T) { +func testAContainerReadingAnOwnSecretIsRestartedWhenItChanges(t *testing.T) { m := mcat.Manifest{Module: "agent", Version: "1", OwnSecrets: mcat.OwnSecrets{"broker": {Path: "/var/lib/mesh/agent/broker"}}, Resources: []map[string]any{ @@ -55,7 +55,7 @@ func TestAContainerReadingAnOwnSecretIsRestartedWhenItChanges(t *testing.T) { // A member of a secret family is an own secret too (novox/hq issue 405, ADR 0283 decision 6): a container that // reads a member given is restarted when it changes, as for a secret declared by name. A member not given is no // file, so nothing is restarted on it. -func TestAContainerReadingAFamilyMemberIsRestartedWhenItChanges(t *testing.T) { +func testAContainerReadingAFamilyMemberIsRestartedWhenItChanges(t *testing.T) { m := mcat.Manifest{Module: "mounts", Version: "1", OwnSecrets: mcat.OwnSecrets{"smb-password-*": {Path: "/var/lib/mesh/mounts/smb-password-*.secret", IssuedBy: mcat.IssuedOutside}}, Resources: []map[string]any{ @@ -88,3 +88,9 @@ func TestAContainerReadingAFamilyMemberIsRestartedWhenItChanges(t *testing.T) { t.Fatalf("a container reading a member not given was given a restart-on naming nothing: %v", by["mounts.library"]["restart-on"]) } } + +// TestSecretRestart runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSecretRestart(t *testing.T) { + t.Run("AContainerReadingAnOwnSecretIsRestartedWhenItChanges", testAContainerReadingAnOwnSecretIsRestartedWhenItChanges) + t.Run("AContainerReadingAFamilyMemberIsRestartedWhenItChanges", testAContainerReadingAFamilyMemberIsRestartedWhenItChanges) +} diff --git a/internal/compose/resolution/secrets_into_files_test.go b/internal/compose/resolution/secrets_into_files_test.go index eb3f1fe2..5938f470 100644 --- a/internal/compose/resolution/secrets_into_files_test.go +++ b/internal/compose/resolution/secrets_into_files_test.go @@ -18,7 +18,7 @@ func fileNamed(out []map[string]any, id string) map[string]any { // A module's own credential, put into a file it wrote: the value sealed to the node, or, in a composition asked ahead of // the send or for a plan alone, the stand-in its own file has (issue 774: baserow's config.json refused ace's plans). -func TestAFileGetsTheSecretItsContentAsksFor(t *testing.T) { +func testAFileGetsTheSecretItsContentAsksFor(t *testing.T) { for _, row := range []struct { name string with mcat.Rendering @@ -57,7 +57,7 @@ func TestAFileGetsTheSecretItsContentAsksFor(t *testing.T) { // The gap this exists for: a granted credential arrives as a bare password, and the program that // needs it reads KEY=value. -func TestAGrantedCredentialCanBeShapedIntoAnEnvFile(t *testing.T) { +func testAGrantedCredentialCanBeShapedIntoAnEnvFile(t *testing.T) { r := mcat.Resolution{ Node: "anchor", Modules: []mcat.Manifest{{ @@ -87,7 +87,7 @@ func TestAGrantedCredentialCanBeShapedIntoAnEnvFile(t *testing.T) { // ${secret:…} file — not whichever need happened to come last. This is the placeholder-path twin of // the guard novox/hq 04-ISSUES/022 put on the secrets:-map path; without it, a node with baserow and // letta both consuming postgres gave baserow letta's password and authentication failed. -func TestTwoConsumersOfOneProvisionEachGetTheirOwnInAPlaceholderFile(t *testing.T) { +func testTwoConsumersOfOneProvisionEachGetTheirOwnInAPlaceholderFile(t *testing.T) { r := mcat.Resolution{ Node: "anchor", Modules: []mcat.Manifest{ @@ -130,7 +130,7 @@ func TestTwoConsumersOfOneProvisionEachGetTheirOwnInAPlaceholderFile(t *testing. } // A name nothing declared is a typo, and it is refused here rather than on the machine. -func TestAFileNamingASecretTheModuleDoesNotHaveIsRefused(t *testing.T) { +func testAFileNamingASecretTheModuleDoesNotHaveIsRefused(t *testing.T) { r := mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{{ Module: "gitea", OwnSecrets: mcat.OwnSecrets{"admin": {Path: "/var/lib/gitea/admin.env"}}, @@ -152,7 +152,7 @@ func TestAFileNamingASecretTheModuleDoesNotHaveIsRefused(t *testing.T) { } // One module may not read another's credential by guessing its name. -func TestAFileCannotNameAnotherModulesSecret(t *testing.T) { +func testAFileCannotNameAnotherModulesSecret(t *testing.T) { r := mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{ {Module: "postgres", OwnSecrets: mcat.OwnSecrets{"superuser": {Path: "/var/lib/postgres/su.env"}}}, {Module: "gitea", Resources: []map[string]any{{ @@ -174,7 +174,7 @@ func TestAFileCannotNameAnotherModulesSecret(t *testing.T) { // attribute inside a JSON file in a home directory, not from an environment variable. The module // ships an empty document, a setting says which attribute, and the credential never passes // through the mesh in the open. -func TestASettingThatCarriesAPlaceholderIsStillFilled(t *testing.T) { +func testASettingThatCarriesAPlaceholderIsStillFilled(t *testing.T) { r := mcat.Resolution{Node: "workstation", Modules: []mcat.Manifest{{ Module: "chat", OwnSecrets: mcat.OwnSecrets{"api-token": {Path: "/home/operator/.config/chat/token"}}, @@ -205,7 +205,7 @@ func TestASettingThatCarriesAPlaceholderIsStillFilled(t *testing.T) { } // An own secret and a requirement of the same name would make ${secret:x} mean either. -func TestANameMeaningTwoThingsIsRefused(t *testing.T) { +func testANameMeaningTwoThingsIsRefused(t *testing.T) { r := mcat.Resolution{ Node: "anchor", Modules: []mcat.Manifest{{ @@ -225,7 +225,7 @@ func TestANameMeaningTwoThingsIsRefused(t *testing.T) { // A file with no placeholder is not given a secrets map. The host refuses a secret its content // never asks for, so an empty map added helpfully would break every file that has none. -func TestAFileWithNoPlaceholderIsLeftAlone(t *testing.T) { +func testAFileWithNoPlaceholderIsLeftAlone(t *testing.T) { r := mcat.Resolution{Node: "anchor", Modules: []mcat.Manifest{{ Module: "gitea", OwnSecrets: mcat.OwnSecrets{"admin": {Path: "/var/lib/gitea/admin.env"}}, @@ -243,3 +243,15 @@ func TestAFileWithNoPlaceholderIsLeftAlone(t *testing.T) { t.Error("a file that asks for nothing was given a secrets map, which the host refuses") } } + +// TestSecretsIntoFiles runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSecretsIntoFiles(t *testing.T) { + t.Run("AFileGetsTheSecretItsContentAsksFor", testAFileGetsTheSecretItsContentAsksFor) + t.Run("AGrantedCredentialCanBeShapedIntoAnEnvFile", testAGrantedCredentialCanBeShapedIntoAnEnvFile) + t.Run("TwoConsumersOfOneProvisionEachGetTheirOwnInAPlaceholderFile", testTwoConsumersOfOneProvisionEachGetTheirOwnInAPlaceholderFile) + t.Run("AFileNamingASecretTheModuleDoesNotHaveIsRefused", testAFileNamingASecretTheModuleDoesNotHaveIsRefused) + t.Run("AFileCannotNameAnotherModulesSecret", testAFileCannotNameAnotherModulesSecret) + t.Run("ASettingThatCarriesAPlaceholderIsStillFilled", testASettingThatCarriesAPlaceholderIsStillFilled) + t.Run("ANameMeaningTwoThingsIsRefused", testANameMeaningTwoThingsIsRefused) + t.Run("AFileWithNoPlaceholderIsLeftAlone", testAFileWithNoPlaceholderIsLeftAlone) +} diff --git a/internal/compose/resolution/served_own_names_test.go b/internal/compose/resolution/served_own_names_test.go index b29f4b8d..e93f8e3f 100644 --- a/internal/compose/resolution/served_own_names_test.go +++ b/internal/compose/resolution/served_own_names_test.go @@ -23,7 +23,7 @@ func aForgeManifest(t *testing.T) mcat.Manifest { return m } -func TestAProviderServesItsOwnComposedName(t *testing.T) { +func testAProviderServesItsOwnComposedName(t *testing.T) { m := aForgeManifest(t) r := mcat.Resolution{Node: "home", PublicDomain: "example.org"} got, said, err := ServedOwnNames(r, m, "npm-package-registry", m.Serves["npm-package-registry"], nil) @@ -42,7 +42,7 @@ func TestAProviderServesItsOwnComposedName(t *testing.T) { } // On the provider's own machine the consumer is served the same name (ADR 0346 §2). -func TestAConsumerBesideTheProviderIsServedItsName(t *testing.T) { +func testAConsumerBesideTheProviderIsServedItsName(t *testing.T) { m := aForgeManifest(t) consumer := mcat.Manifest{Module: "lab", Version: "1", Requires: []string{"npm-package-registry"}, Binds: map[string]string{"npm-package-registry": "/var/lib/lab/package-registry.json"}} @@ -103,7 +103,7 @@ func TestAConsumerBesideTheProviderIsServedItsName(t *testing.T) { // From another machine, the provider's served values carry what that machine composed, and a key it // left out is said on the consumer's need (ADR 0346 §2, §3). -func TestAConsumerElsewhereIsToldWhatTheProviderLeftOut(t *testing.T) { +func testAConsumerElsewhereIsToldWhatTheProviderLeftOut(t *testing.T) { consumer := mcat.Manifest{Module: "lab", Version: "1", Requires: []string{"npm-package-registry"}, Binds: map[string]string{"npm-package-registry": "/var/lib/lab/package-registry.json"}} node := workstation() @@ -128,7 +128,7 @@ func TestAConsumerElsewhereIsToldWhatTheProviderLeftOut(t *testing.T) { // The provider's contributions file carries no own name on a consumer's entry (ADR 0346 §4): only what // is derived for that consumer is there (ADR 0202 §5), and the provider reads its own names in its files. -func TestAProvidersOwnNameIsNotOnItsConsumersEntry(t *testing.T) { +func testAProvidersOwnNameIsNotOnItsConsumersEntry(t *testing.T) { m := aForgeManifest(t) r := mcat.Resolution{Node: "home", PublicDomain: "example.org", Modules: []mcat.Manifest{m}} derived, err := resolutionDerivedFor(r, "npm-package-registry", "lab_home", "lab", "", nil) @@ -139,3 +139,11 @@ func TestAProvidersOwnNameIsNotOnItsConsumersEntry(t *testing.T) { t.Fatalf("a consumer's entry carries only what was derived for it: %v", derived) } } + +// TestServedOwnNames runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestServedOwnNames(t *testing.T) { + t.Run("AProviderServesItsOwnComposedName", testAProviderServesItsOwnComposedName) + t.Run("AConsumerBesideTheProviderIsServedItsName", testAConsumerBesideTheProviderIsServedItsName) + t.Run("AConsumerElsewhereIsToldWhatTheProviderLeftOut", testAConsumerElsewhereIsToldWhatTheProviderLeftOut) + t.Run("AProvidersOwnNameIsNotOnItsConsumersEntry", testAProvidersOwnNameIsNotOnItsConsumersEntry) +} diff --git a/internal/compose/resolution/setting_defaults_test.go b/internal/compose/resolution/setting_defaults_test.go index efe655c3..536b8623 100644 --- a/internal/compose/resolution/setting_defaults_test.go +++ b/internal/compose/resolution/setting_defaults_test.go @@ -19,7 +19,7 @@ func notifier() mcat.Manifest { } } -func TestAnUnsetPreferenceTakesItsDefault(t *testing.T) { +func testAnUnsetPreferenceTakesItsDefault(t *testing.T) { t.Run("the node over the mesh over the default", theNodeOverTheMeshOverTheDefault) m := notifier() for _, layers := range [][]mcat.Layer{nil, {{From: mcat.MeshWideLayer, Values: map[string]any{}}}} { @@ -63,7 +63,7 @@ func theNodeOverTheMeshOverTheDefault(t *testing.T) { // Composed for a machine, the way a push writes it: the default reaches the file, and the node's // layer overrides it. -func TestAComposedMachineGetsTheDefaultAndTheNodesValue(t *testing.T) { +func testAComposedMachineGetsTheDefaultAndTheNodesValue(t *testing.T) { r := anAdoptedAnchor() n := notifier() n.Resources = append(n.Resources, map[string]any{"id": "daemon", "type": "process", "name": "notifier", @@ -101,7 +101,7 @@ func TestAComposedMachineGetsTheDefaultAndTheNodesValue(t *testing.T) { } // A default fills ${setting:…} only: it never becomes a key of a mergeable file (issue 168). -func TestADefaultIsNotMergedIntoAJSONFile(t *testing.T) { +func testADefaultIsNotMergedIntoAJSONFile(t *testing.T) { m := notifier() m.Resources = append(m.Resources, map[string]any{"id": "other", "type": "file", "path": "/x/other.json", "merge": mcat.MergeJSON, "content": `{"keep": 1}`}) @@ -115,7 +115,7 @@ func TestADefaultIsNotMergedIntoAJSONFile(t *testing.T) { } // A value that is the operator's has no default: no layer setting it is refused by name, as before. -func TestAnOperatorsValueWithoutADefaultIsStillRefused(t *testing.T) { +func testAnOperatorsValueWithoutADefaultIsStillRefused(t *testing.T) { m := notifier() m.Resources[0]["content"] = "font = Inter ${setting:font-size}\nwidth = ${setting:width}\nfrom = ${setting:domain}\n" err := JudgeSettings(m, nil, false) @@ -127,7 +127,7 @@ func TestAnOperatorsValueWithoutADefaultIsStillRefused(t *testing.T) { } } -func TestEveryValueSaysWhereItCameFrom(t *testing.T) { +func testEveryValueSaysWhereItCameFrom(t *testing.T) { m := notifier() m.Resources[0]["content"] = m.Resources[0]["content"].(string) + "x = ${setting:position}\n" got := Effective(m, []mcat.Layer{ @@ -154,7 +154,7 @@ func TestEveryValueSaysWhereItCameFrom(t *testing.T) { // A node may be called `default`. Its layer is a node's like any other: it overrides the module's // default, it merges into a mergeable file, and it is named among what is set. -func TestANodeCalledDefaultIsANodesLayer(t *testing.T) { +func testANodeCalledDefaultIsANodesLayer(t *testing.T) { m := notifier() node := []mcat.Layer{{From: mcat.DefaultLayer, Values: map[string]any{"font-size": float64(13)}}} file := map[string]any{"type": "file", "content": m.Resources[0]["content"]} @@ -178,7 +178,7 @@ func TestANodeCalledDefaultIsANodesLayer(t *testing.T) { // A default fills ${setting:…} in what a module contributes and serves, and never replaces a value a // contribution states itself. -func TestADefaultFillsAContributionAndAServedFactButNotALiteral(t *testing.T) { +func testADefaultFillsAContributionAndAServedFactButNotALiteral(t *testing.T) { m := notifier() m.Settings["site-title"] = mcat.SettingDeclaration{Kind: mcat.KindPreference, Default: "Notes", Why: "x"} contribution := map[string]any{"title": "${setting:site-title}", "width": "fixed", "port": float64(8080)} @@ -201,3 +201,14 @@ func TestADefaultFillsAContributionAndAServedFactButNotALiteral(t *testing.T) { t.Fatal("a served fact without the defaults was filled") } } + +// TestSettingDefaults runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSettingDefaults(t *testing.T) { + t.Run("AnUnsetPreferenceTakesItsDefault", testAnUnsetPreferenceTakesItsDefault) + t.Run("AComposedMachineGetsTheDefaultAndTheNodesValue", testAComposedMachineGetsTheDefaultAndTheNodesValue) + t.Run("ADefaultIsNotMergedIntoAJSONFile", testADefaultIsNotMergedIntoAJSONFile) + t.Run("AnOperatorsValueWithoutADefaultIsStillRefused", testAnOperatorsValueWithoutADefaultIsStillRefused) + t.Run("EveryValueSaysWhereItCameFrom", testEveryValueSaysWhereItCameFrom) + t.Run("ANodeCalledDefaultIsANodesLayer", testANodeCalledDefaultIsANodesLayer) + t.Run("ADefaultFillsAContributionAndAServedFactButNotALiteral", testADefaultFillsAContributionAndAServedFactButNotALiteral) +} diff --git a/internal/compose/resolution/setting_in_owner_test.go b/internal/compose/resolution/setting_in_owner_test.go index 2adf317f..620586bd 100644 --- a/internal/compose/resolution/setting_in_owner_test.go +++ b/internal/compose/resolution/setting_in_owner_test.go @@ -28,7 +28,7 @@ func copied(r map[string]any) map[string]any { // The node's identity reaches the directory's owner, the node's layer over the mesh's, a number given // as a string or as a JSON number alike. -func TestASettingOwnsADirectory(t *testing.T) { +func testASettingOwnsADirectory(t *testing.T) { m := recycler() layers := []mcat.Layer{ {From: "the mesh", Values: map[string]any{"puid": "1000", "pgid": "1000"}}, @@ -50,7 +50,7 @@ func TestASettingOwnsADirectory(t *testing.T) { // Composed for a machine, the way a push writes it: the directory reaches the node-engine owned by the // number the node's settings name, never by the placeholder. -func TestAComposedMachineGetsTheOwnerTheSettingNames(t *testing.T) { +func testAComposedMachineGetsTheOwnerTheSettingNames(t *testing.T) { r := anAdoptedAnchor() r.Modules = append(r.Modules, recycler()) with := anchorRendering(false) @@ -70,7 +70,7 @@ func TestAComposedMachineGetsTheOwnerTheSettingNames(t *testing.T) { // Only a whole number owns a directory: an account's name, text, a sign, a fraction or a value past the // kernel's ids is refused by name, and the directory is left as it was. So is a key nothing sets. -func TestAnOwnerSettingThatIsNoNumberIsRefused(t *testing.T) { +func testAnOwnerSettingThatIsNoNumberIsRefused(t *testing.T) { m := recycler() for _, bad := range []any{"abc", "root", "", "-1", "+5", "1000:1000", "10 00", "1000\nx", float64(1.5), float64(-3), "4294967295", "99999999999", true} { @@ -95,7 +95,7 @@ func TestAnOwnerSettingThatIsNoNumberIsRefused(t *testing.T) { // An owner is written as the number parsed: "0001" and "00" reach the node-engine as 1 and 0, never as text. // Uid 0 is allowed, because a key an owner asks for is the terminal's alone. -func TestAnOwnerSettingIsWrittenAsTheNumber(t *testing.T) { +func testAnOwnerSettingIsWrittenAsTheNumber(t *testing.T) { m := recycler() r := copied(m.Resources[0]) if err := settingInto(r, []mcat.Layer{{From: "ace", Values: map[string]any{"puid": "0001", "pgid": "00"}}}, m.Module); err != nil { @@ -105,3 +105,11 @@ func TestAnOwnerSettingIsWrittenAsTheNumber(t *testing.T) { t.Fatalf("owned by %q, not 1:0", r["owner"]) } } + +// TestSettingInOwner runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSettingInOwner(t *testing.T) { + t.Run("ASettingOwnsADirectory", testASettingOwnsADirectory) + t.Run("AComposedMachineGetsTheOwnerTheSettingNames", testAComposedMachineGetsTheOwnerTheSettingNames) + t.Run("AnOwnerSettingThatIsNoNumberIsRefused", testAnOwnerSettingThatIsNoNumberIsRefused) + t.Run("AnOwnerSettingIsWrittenAsTheNumber", testAnOwnerSettingIsWrittenAsTheNumber) +} diff --git a/internal/compose/resolution/setting_in_unit_test.go b/internal/compose/resolution/setting_in_unit_test.go index 5c5d36de..046890f7 100644 --- a/internal/compose/resolution/setting_in_unit_test.go +++ b/internal/compose/resolution/setting_in_unit_test.go @@ -23,7 +23,7 @@ func scrubber() mcat.Manifest { } } -func TestASettingNamesAServicesUnit(t *testing.T) { +func testASettingNamesAServicesUnit(t *testing.T) { m := scrubber() layers := WithDefaults(m, []mcat.Layer{{From: "ace", Values: map[string]any{"scrub-pool": "storage", "scrub-cadence": "monthly"}}}) for i, want := range []string{"zfs-scrub-weekly@storage.timer", "zfs-scrub-monthly@storage.timer"} { @@ -42,7 +42,7 @@ func TestASettingNamesAServicesUnit(t *testing.T) { // Composed for a machine, the way a push writes it: the operator's pool and cadence reach the units' names // and the file. -func TestAComposedMachineGetsTheUnitTheSettingNames(t *testing.T) { +func testAComposedMachineGetsTheUnitTheSettingNames(t *testing.T) { r := anAdoptedAnchor() r.Modules = append(r.Modules, scrubber()) with := anchorRendering(false) @@ -69,7 +69,7 @@ func TestAComposedMachineGetsTheUnitTheSettingNames(t *testing.T) { // A value that would not make a unit's name is refused by name, never written: a space, a slash, a // newline that would begin a directive, or a second suffix. -func TestASettingThatMakesNoUnitNameIsRefused(t *testing.T) { +func testASettingThatMakesNoUnitNameIsRefused(t *testing.T) { m := scrubber() for _, bad := range []string{"", "stor age", "a/b", "storage\nExecStart=/bin/sh", "a@b", "$(x)", "*", `a\\x2d`} { r := map[string]any{} @@ -93,7 +93,7 @@ func TestASettingThatMakesNoUnitNameIsRefused(t *testing.T) { } } -func TestAnInstanceValueMayNotLeadWithADashNorBeLong(t *testing.T) { +func testAnInstanceValueMayNotLeadWithADashNorBeLong(t *testing.T) { m := scrubber() for _, bad := range []string{"-storage", "--help", strings.Repeat("a", 65)} { r := map[string]any{} @@ -113,3 +113,11 @@ func TestAnInstanceValueMayNotLeadWithADashNorBeLong(t *testing.T) { t.Errorf("64 characters: %v", err) } } + +// TestSettingInUnit runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSettingInUnit(t *testing.T) { + t.Run("ASettingNamesAServicesUnit", testASettingNamesAServicesUnit) + t.Run("AComposedMachineGetsTheUnitTheSettingNames", testAComposedMachineGetsTheUnitTheSettingNames) + t.Run("ASettingThatMakesNoUnitNameIsRefused", testASettingThatMakesNoUnitNameIsRefused) + t.Run("AnInstanceValueMayNotLeadWithADashNorBeLong", testAnInstanceValueMayNotLeadWithADashNorBeLong) +} diff --git a/internal/compose/resolution/setting_into_test.go b/internal/compose/resolution/setting_into_test.go index 9b7dd551..6dae7136 100644 --- a/internal/compose/resolution/setting_into_test.go +++ b/internal/compose/resolution/setting_into_test.go @@ -13,7 +13,7 @@ import ( // ADR 0155), and a value nothing set is refused by name; and a resource under `if-config` is declared only while a // config value holds (design 42 zfs-owns-zfs §2, ADR 0679 §16 (b)). One table of the two, each row its layers, what it // does to a resource and what comes of it. -func TestAConfigValueReachesAResourceAndDecidesWhetherItIsDeclared(t *testing.T) { +func testAConfigValueReachesAResourceAndDecidesWhetherItIsDeclared(t *testing.T) { filled := func(content string) func([]mcat.Layer) (string, error) { return func(layers []mcat.Layer) (string, error) { file := map[string]any{"id": "env", "type": "file", "path": "/x/mail.env", "content": content} @@ -120,7 +120,7 @@ var errKeyKept = errors.New("the if-config key was kept in a declared resource") // The composition takes a resource out while its condition does not hold, and a value going from set to unset takes it // out of the next composition, which the node-engine removes as it removes any resource that left (design 42 §2). -func TestAConfigConditionedResourceIsComposedWhileItsValueHolds(t *testing.T) { +func testAConfigConditionedResourceIsComposedWhileItsValueHolds(t *testing.T) { m := mustParse(t, `{"module":"zfs","version":"1","config":{"zed":{"type":"string","default":"off"},"mods":{"type":"list"}},"resources":[ {"id":"opts","type":"file","path":"/etc/modprobe.d/zfs.conf","content":"${config-lines:mods:options zfs }\n${config-json}\n"}, {"id":"conf","type":"file","path":"/etc/zfs/mesh.conf","content":"x\n"}, @@ -149,3 +149,9 @@ func TestAConfigConditionedResourceIsComposedWhileItsValueHolds(t *testing.T) { } } } + +// TestSettingInto runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSettingInto(t *testing.T) { + t.Run("AConfigValueReachesAResourceAndDecidesWhetherItIsDeclared", testAConfigValueReachesAResourceAndDecidesWhetherItIsDeclared) + t.Run("AConfigConditionedResourceIsComposedWhileItsValueHolds", testAConfigConditionedResourceIsComposedWhileItsValueHolds) +} diff --git a/internal/compose/resolution/settings_test.go b/internal/compose/resolution/settings_test.go index cf9352b7..e6da7521 100644 --- a/internal/compose/resolution/settings_test.go +++ b/internal/compose/resolution/settings_test.go @@ -20,7 +20,7 @@ func file(content string, protected ...string) map[string]any { return r } -func TestAProtectedKeyIsRefusedNotIgnored(t *testing.T) { +func testAProtectedKeyIsRefusedNotIgnored(t *testing.T) { // A setting quietly dropped is somebody believing they changed something. Refusing says so // while they are looking at it. _, err := ApplySettings(file(`{"socket":"/run/thing.sock","log":"info"}`, "socket"), @@ -33,7 +33,7 @@ func TestAProtectedKeyIsRefusedNotIgnored(t *testing.T) { } } -func TestTheSameSettingsAlwaysProduceTheSameBytes(t *testing.T) { +func testTheSameSettingsAlwaysProduceTheSameBytes(t *testing.T) { // A file whose lines move for no reason makes every reconcile look like a change, and a // service reflecting it would restart for ever. // @@ -59,7 +59,7 @@ func TestTheSameSettingsAlwaysProduceTheSameBytes(t *testing.T) { } } -func TestAFileThatDoesNotMergeIsLeftAlone(t *testing.T) { +func testAFileThatDoesNotMergeIsLeftAlone(t *testing.T) { plain := map[string]any{"id": "conf", "type": "file", "path": "/etc/thing", "content": "not structured at all\n"} out, err := ApplySettings(plain, []mcat.Layer{{From: "node", Values: map[string]any{"x": 1}}}) @@ -71,7 +71,7 @@ func TestAFileThatDoesNotMergeIsLeftAlone(t *testing.T) { } } -func TestContentThatIsNotJSONIsRefusedWhereSomebodyIsLooking(t *testing.T) { +func testContentThatIsNotJSONIsRefusedWhereSomebodyIsLooking(t *testing.T) { // Rather than on the machine, at apply time, as a file the program cannot read. _, err := ApplySettings(file(`this is not json`), nil) if err == nil { @@ -81,7 +81,7 @@ func TestContentThatIsNotJSONIsRefusedWhereSomebodyIsLooking(t *testing.T) { // No layer replaces a value the vault fills, at any depth (novox/hq issue 610): searxng's server.secret_key // sits under `server`, a key its file takes, and a layer reaching it was let through by a top-level-only check. -func TestNoLayerReplacesAVaultSecretAtAnyDepth(t *testing.T) { +func testNoLayerReplacesAVaultSecretAtAnyDepth(t *testing.T) { file := map[string]any{"id": "settings", "type": "file", "merge": mcat.MergeJSON, "content": `{"server": {"secret_key": "${secret:secret}", "port": 8080}, "ui": {"theme": "simple"}, "token": "${secret:token}"}`} layer := func(values map[string]any) []mcat.Layer { return []mcat.Layer{{From: "anchor", Values: values}} } @@ -104,3 +104,12 @@ func TestNoLayerReplacesAVaultSecretAtAnyDepth(t *testing.T) { } } } + +// TestSettings runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSettings(t *testing.T) { + t.Run("AProtectedKeyIsRefusedNotIgnored", testAProtectedKeyIsRefusedNotIgnored) + t.Run("TheSameSettingsAlwaysProduceTheSameBytes", testTheSameSettingsAlwaysProduceTheSameBytes) + t.Run("AFileThatDoesNotMergeIsLeftAlone", testAFileThatDoesNotMergeIsLeftAlone) + t.Run("ContentThatIsNotJSONIsRefusedWhereSomebodyIsLooking", testContentThatIsNotJSONIsRefusedWhereSomebodyIsLooking) + t.Run("NoLayerReplacesAVaultSecretAtAnyDepth", testNoLayerReplacesAVaultSecretAtAnyDepth) +} diff --git a/internal/compose/resolution/several_contributions_test.go b/internal/compose/resolution/several_contributions_test.go index 0bdcedae..741551d7 100644 --- a/internal/compose/resolution/several_contributions_test.go +++ b/internal/compose/resolution/several_contributions_test.go @@ -17,7 +17,7 @@ func minimalRouteProxy() mcat.Manifest { } } -func TestAModuleWithTwoRoutesGivesTheProviderTwoContributions(t *testing.T) { +func testAModuleWithTwoRoutesGivesTheProviderTwoContributions(t *testing.T) { minio, err := decodeForTest([]byte(twoRoutes)) if err != nil { t.Fatal(err) @@ -62,7 +62,7 @@ func TestAModuleWithTwoRoutesGivesTheProviderTwoContributions(t *testing.T) { // A module with the ordinary, single-contribution shape resolves exactly as it did before — // ContributesMany being empty must change nothing about it. -func TestASingleRouteStillResolvesTheOrdinaryWay(t *testing.T) { +func testASingleRouteStillResolvesTheOrdinaryWay(t *testing.T) { got, err := Resolve(shelf(proxy(), published("board", "board", 8080)), []string{"board"}, workstation(), mcat.World{}) if err != nil { t.Fatal(err) @@ -80,7 +80,7 @@ func TestASingleRouteStillResolvesTheOrdinaryWay(t *testing.T) { // grant and collide with that same contribution's own entry from contributions(), which is // exactly the duplicate a live plan against minio surfaced (files-api appearing once with a // credential, once without, while files got neither). -func TestContributionsFromHasNoSingleValueWhenAModuleContributesSeveralTimes(t *testing.T) { +func testContributionsFromHasNoSingleValueWhenAModuleContributesSeveralTimes(t *testing.T) { minio, err := decodeForTest([]byte(twoRoutes)) if err != nil { t.Fatal(err) @@ -102,7 +102,7 @@ func TestContributionsFromHasNoSingleValueWhenAModuleContributesSeveralTimes(t * } // The ordinary, single-contribution case is unchanged: exactly one match still settles to it. -func TestContributionsFromReturnsTheOneValueForAnOrdinaryContribution(t *testing.T) { +func testContributionsFromReturnsTheOneValueForAnOrdinaryContribution(t *testing.T) { got, err := Resolve(shelf(proxy(), published("board", "board", 8080)), []string{"board"}, workstation(), mcat.World{}) if err != nil { t.Fatal(err) @@ -115,3 +115,11 @@ func TestContributionsFromReturnsTheOneValueForAnOrdinaryContribution(t *testing t.Fatalf("the ordinary single contribution should still settle to its own value: %+v", values) } } + +// TestSeveralContributions runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSeveralContributions(t *testing.T) { + t.Run("AModuleWithTwoRoutesGivesTheProviderTwoContributions", testAModuleWithTwoRoutesGivesTheProviderTwoContributions) + t.Run("ASingleRouteStillResolvesTheOrdinaryWay", testASingleRouteStillResolvesTheOrdinaryWay) + t.Run("ContributionsFromHasNoSingleValueWhenAModuleContributesSeveralTimes", testContributionsFromHasNoSingleValueWhenAModuleContributesSeveralTimes) + t.Run("ContributionsFromReturnsTheOneValueForAnOrdinaryContribution", testContributionsFromReturnsTheOneValueForAnOrdinaryContribution) +} diff --git a/internal/compose/resolution/several_secrets_test.go b/internal/compose/resolution/several_secrets_test.go index dadd4314..5754e52b 100644 --- a/internal/compose/resolution/several_secrets_test.go +++ b/internal/compose/resolution/several_secrets_test.go @@ -24,7 +24,7 @@ func vaultAndCA() map[string]mcat.Manifest { return shelf(vault, cache, ca) } -func TestEachLocalNameIsANeedAFileAndAHolderOfItsOwn(t *testing.T) { +func testEachLocalNameIsANeedAFileAndAHolderOfItsOwn(t *testing.T) { got, err := Resolve(vaultAndCA(), []string{"mesh-vault", "cache", "ca"}, workstation(), mcat.World{}) if err != nil { t.Fatal(err) @@ -62,7 +62,7 @@ func TestEachLocalNameIsANeedAFileAndAHolderOfItsOwn(t *testing.T) { } } -func TestAProviderSeesEachLocalNameAsAHolderOfItsOwn(t *testing.T) { +func testAProviderSeesEachLocalNameAsAHolderOfItsOwn(t *testing.T) { r := mcat.Resolution{Modules: []mcat.Manifest{vaultAndCA()["mesh-vault"]}} got, err := resolutionContributions(r, mcat.SettingsBy{}, []mcat.Grant{ {Provision: "secret", Consumer: "workstation", From: "ca", Local: "root-key", Sealed: "x"}, @@ -85,7 +85,7 @@ func TestAProviderSeesEachLocalNameAsAHolderOfItsOwn(t *testing.T) { // And on the provider's machine, two files with two ids — the lab's first run had the declaration // refused for two resources with one identity. -func TestAProviderKeepsOneFilePerHolder(t *testing.T) { +func testAProviderKeepsOneFilePerHolder(t *testing.T) { got, err := Resolve(vaultAndCA(), []string{"mesh-vault", "cache", "ca"}, workstation(), mcat.World{}) if err != nil { t.Fatal(err) @@ -110,7 +110,7 @@ func TestAProviderKeepsOneFilePerHolder(t *testing.T) { // One file under a local name is still a local name (review C1): the need carries it, the file // is written, and ${secret:} is filled. -func TestOneLocalNameIsStillALocalName(t *testing.T) { +func testOneLocalNameIsStillALocalName(t *testing.T) { only, _ := decodeForTest([]byte(`{"module":"one","version":"1","requires":["secret"], "secrets":{"secret":{"only":"/var/lib/one/only"}}}`)) vault := vaultAndCA()["mesh-vault"] @@ -142,3 +142,11 @@ func TestOneLocalNameIsStillALocalName(t *testing.T) { t.Fatal("the file under the one local name was not written") } } + +// TestSeveralSecrets runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSeveralSecrets(t *testing.T) { + t.Run("EachLocalNameIsANeedAFileAndAHolderOfItsOwn", testEachLocalNameIsANeedAFileAndAHolderOfItsOwn) + t.Run("AProviderSeesEachLocalNameAsAHolderOfItsOwn", testAProviderSeesEachLocalNameAsAHolderOfItsOwn) + t.Run("AProviderKeepsOneFilePerHolder", testAProviderKeepsOneFilePerHolder) + t.Run("OneLocalNameIsStillALocalName", testOneLocalNameIsStillALocalName) +} diff --git a/internal/compose/resolution/shared_account_test.go b/internal/compose/resolution/shared_account_test.go index f4ae90eb..618920c8 100644 --- a/internal/compose/resolution/shared_account_test.go +++ b/internal/compose/resolution/shared_account_test.go @@ -15,7 +15,7 @@ func userResource(fields map[string]any) map[string]any { return r } -func TestAShellAndAGroupOnOneAccountFromTwoModulesResolve(t *testing.T) { +func testAShellAndAGroupOnOneAccountFromTwoModulesResolve(t *testing.T) { zsh := mcat.Manifest{Module: "zsh", Resources: []map[string]any{userResource(map[string]any{"shell": "/usr/bin/zsh"})}} docker := mcat.Manifest{Module: "docker", Resources: []map[string]any{userResource(map[string]any{"groups": []any{"docker"}})}} other := mcat.Manifest{Module: "media", Resources: []map[string]any{userResource(map[string]any{"groups": []any{"video"}})}} @@ -27,7 +27,7 @@ func TestAShellAndAGroupOnOneAccountFromTwoModulesResolve(t *testing.T) { } } -func TestTwoModulesSettingOneAccountsShellOrHomeAreRefused(t *testing.T) { +func testTwoModulesSettingOneAccountsShellOrHomeAreRefused(t *testing.T) { for _, field := range []string{"shell", "home"} { a := mcat.Manifest{Module: "zsh", Resources: []map[string]any{userResource(map[string]any{field: "/one"})}} b := mcat.Manifest{Module: "fish", Resources: []map[string]any{userResource(map[string]any{field: "/two", "groups": []any{"x"}})}} @@ -41,7 +41,7 @@ func TestTwoModulesSettingOneAccountsShellOrHomeAreRefused(t *testing.T) { // An account a module declares only to put in a group is applied where it is written, after the package // that makes the group (novox/hq ADR 0252); one that says how it logs in still goes first (issue 213). -func TestAnAccountOnlyGivenGroupsKeepsItsWrittenPlace(t *testing.T) { +func testAnAccountOnlyGivenGroupsKeepsItsWrittenPlace(t *testing.T) { compose := func(raw string) []map[string]any { t.Helper() m, err := decodeForTest([]byte(raw)) @@ -69,3 +69,10 @@ func TestAnAccountOnlyGivenGroupsKeepsItsWrittenPlace(t *testing.T) { t.Fatalf("an account with a shell is no longer first (%d, package %d): %v", acct, pkg, out) } } + +// TestSharedAccount runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSharedAccount(t *testing.T) { + t.Run("AShellAndAGroupOnOneAccountFromTwoModulesResolve", testAShellAndAGroupOnOneAccountFromTwoModulesResolve) + t.Run("TwoModulesSettingOneAccountsShellOrHomeAreRefused", testTwoModulesSettingOneAccountsShellOrHomeAreRefused) + t.Run("AnAccountOnlyGivenGroupsKeepsItsWrittenPlace", testAnAccountOnlyGivenGroupsKeepsItsWrittenPlace) +} diff --git a/internal/compose/resolution/terminal_settings_test.go b/internal/compose/resolution/terminal_settings_test.go index 0c867e2c..251016d8 100644 --- a/internal/compose/resolution/terminal_settings_test.go +++ b/internal/compose/resolution/terminal_settings_test.go @@ -9,7 +9,7 @@ import ( // A line break, a carriage return or a NUL in any string of any setting is refused, at any depth, keys too — // where a layer is judged, which is both where it is kept and where it is composed (novox/hq issue 339). -func TestASettingHoldsOneLine(t *testing.T) { +func testASettingHoldsOneLine(t *testing.T) { m := mcat.Manifest{Module: "mailu"} for _, v := range []any{"a\nDEBUG=1", "a\rb", "a\x00b", []any{"ok", "x\ny"}, map[string]any{"k": []any{"ok", map[string]any{"deep": "x\ny"}}}, map[string]any{"k\nx": "v"}} { @@ -30,7 +30,7 @@ func TestASettingHoldsOneLine(t *testing.T) { // Lines are allowed in one setting only: step-ca's `root`, as certificates that encoding/pem decodes and // x509.ParseCertificate parses (novox/hq issue 339). Any other module or key, another label, or a block that is // not a certificate is refused like any other line break. -func TestOnlyTheAuthoritysRootMayHoldLines(t *testing.T) { +func testOnlyTheAuthoritysRootMayHoldLines(t *testing.T) { ca := mcat.Manifest{Module: "step-ca"} judge := func(m mcat.Manifest, key, v string) error { return JudgeSettings(m, []mcat.Layer{{From: "anchor", Values: map[string]any{key: v}}}, false) @@ -66,7 +66,7 @@ func TestOnlyTheAuthoritysRootMayHoldLines(t *testing.T) { // Every character a reader takes as the end of a line is refused, not only \n and \r: vertical tab, form feed, // NEL and the Unicode line and paragraph separators (novox/hq issue 339). -func TestEveryLineEndIsRefused(t *testing.T) { +func testEveryLineEndIsRefused(t *testing.T) { m := mcat.Manifest{Module: "mailu"} for _, v := range []string{"a\vb", "a\fb", "a\u0085b", "a\u2028b", "a\u2029b"} { if err := JudgeSettings(m, []mcat.Layer{{From: "home", Values: map[string]any{"v": v}}}, false); err == nil || @@ -75,3 +75,10 @@ func TestEveryLineEndIsRefused(t *testing.T) { } } } + +// TestTerminalSettings runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestTerminalSettings(t *testing.T) { + t.Run("ASettingHoldsOneLine", testASettingHoldsOneLine) + t.Run("OnlyTheAuthoritysRootMayHoldLines", testOnlyTheAuthoritysRootMayHoldLines) + t.Run("EveryLineEndIsRefused", testEveryLineEndIsRefused) +} diff --git a/internal/compose/resolution/toolchain_manifests_test.go b/internal/compose/resolution/toolchain_manifests_test.go index 5c2b7f65..3e09cb76 100644 --- a/internal/compose/resolution/toolchain_manifests_test.go +++ b/internal/compose/resolution/toolchain_manifests_test.go @@ -34,7 +34,7 @@ func toolchainShelf(t *testing.T) map[string]mcat.Manifest { return m } -func TestAModuleNeedingAToolchainIsRefusedOnANodeWithoutIt(t *testing.T) { +func testAModuleNeedingAToolchainIsRefusedOnANodeWithoutIt(t *testing.T) { for _, c := range []struct{ module, provision string }{ {"mesh-build-go", "go-toolchain"}, {"mesh-build-node", "node-toolchain"}, @@ -53,7 +53,7 @@ func TestAModuleNeedingAToolchainIsRefusedOnANodeWithoutIt(t *testing.T) { } } -func TestAModuleNeedingAToolchainComposesOnANodeWithIt(t *testing.T) { +func testAModuleNeedingAToolchainComposesOnANodeWithIt(t *testing.T) { for _, c := range []struct{ module, owner string }{ {"mesh-build-go", "go"}, {"mesh-build-node", "nodejs"}, @@ -76,3 +76,9 @@ func TestAModuleNeedingAToolchainComposesOnANodeWithIt(t *testing.T) { } } } + +// TestToolchainManifests runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestToolchainManifests(t *testing.T) { + t.Run("AModuleNeedingAToolchainIsRefusedOnANodeWithoutIt", testAModuleNeedingAToolchainIsRefusedOnANodeWithoutIt) + t.Run("AModuleNeedingAToolchainComposesOnANodeWithIt", testAModuleNeedingAToolchainComposesOnANodeWithIt) +} diff --git a/internal/compose/resolution/two_consumers_test.go b/internal/compose/resolution/two_consumers_test.go index bf2e95e4..ee414f85 100644 --- a/internal/compose/resolution/two_consumers_test.go +++ b/internal/compose/resolution/two_consumers_test.go @@ -18,7 +18,7 @@ func threeConsumers() map[string]mcat.Manifest { ) } -func TestEveryConsumerOnANodeGetsItsOwnCredential(t *testing.T) { +func testEveryConsumerOnANodeGetsItsOwnCredential(t *testing.T) { got, err := Resolve(threeConsumers(), []string{"gitea", "keycloak", "umami"}, reachable(), mcat.World{Offered: onNetwork("anchor")}) if err != nil { @@ -44,7 +44,7 @@ func TestEveryConsumerOnANodeGetsItsOwnCredential(t *testing.T) { // Each consumer's own credential reaches its own file. Matching on the provision alone, every // consumer took whichever need was last — a module handed somebody else's password, which is a // valid credential and therefore fails in a way that looks like a configuration error. -func TestEachConsumerGetsItsOwnCredentialAndNotAnothersFile(t *testing.T) { +func testEachConsumerGetsItsOwnCredentialAndNotAnothersFile(t *testing.T) { got, err := Resolve(threeConsumers(), []string{"gitea", "keycloak", "umami"}, reachable(), mcat.World{Offered: onNetwork("anchor")}) if err != nil { @@ -75,7 +75,7 @@ func TestEachConsumerGetsItsOwnCredentialAndNotAnothersFile(t *testing.T) { } // The provider is told about all three, separately, and names each grant after the module. -func TestAProviderIsToldAboutEveryConsumerOnOneMachine(t *testing.T) { +func testAProviderIsToldAboutEveryConsumerOnOneMachine(t *testing.T) { provider, err := Resolve(shelf(mcat.Manifest{ Module: "postgres", Version: "1", Provides: mcat.FromAnywhere("postgres-database"), Grants: map[string]string{"postgres-database": "/var/lib/postgres/grants"}, @@ -126,3 +126,10 @@ func TestAProviderIsToldAboutEveryConsumerOnOneMachine(t *testing.T) { } } } + +// TestTwoConsumers runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestTwoConsumers(t *testing.T) { + t.Run("EveryConsumerOnANodeGetsItsOwnCredential", testEveryConsumerOnANodeGetsItsOwnCredential) + t.Run("EachConsumerGetsItsOwnCredentialAndNotAnothersFile", testEachConsumerGetsItsOwnCredentialAndNotAnothersFile) + t.Run("AProviderIsToldAboutEveryConsumerOnOneMachine", testAProviderIsToldAboutEveryConsumerOnOneMachine) +} diff --git a/internal/compose/resolution/two_resolvers_test.go b/internal/compose/resolution/two_resolvers_test.go index db216348..2c6f1328 100644 --- a/internal/compose/resolution/two_resolvers_test.go +++ b/internal/compose/resolution/two_resolvers_test.go @@ -62,7 +62,7 @@ func worldWithout(node string) mcat.World { // The requirement stays with what writes the file (ADR 0223 part 1): a machine is refused when nothing // in the mesh resolves, rather than given a file listing nothing. -func TestEveryUplinkRequiresTheMeshsResolver(t *testing.T) { +func testEveryUplinkRequiresTheMeshsResolver(t *testing.T) { for _, uplink := range uplinks { found := false for _, r := range catalogueManifest(t, uplink).Requires { @@ -79,7 +79,7 @@ func TestEveryUplinkRequiresTheMeshsResolver(t *testing.T) { } // A holder answers its own requirement, even though the other holder sorts first (issue 258 kept). -func TestAHolderAnswersItsOwnRequirement(t *testing.T) { +func testAHolderAnswersItsOwnRequirement(t *testing.T) { got, err := Resolve(twoResolverShelf(t), []string{"dnsmasq", "networkmanager"}, managing("home"), worldWithout("home")) if err != nil { @@ -94,7 +94,7 @@ func TestAHolderAnswersItsOwnRequirement(t *testing.T) { // A seat held once is still held once: a second claimant on another machine is refused while // nothing is on record, and a store recording two holders of it is refused, naming the seat. -func TestASingleHolderMeshSeatStillRefusesASecondHolder(t *testing.T) { +func testASingleHolderMeshSeatStillRefusesASecondHolder(t *testing.T) { store := shelf(mod("postgres", nil, nil, nil, mcat.Claim{Name: "mesh-store", Scope: mcat.ScopeMesh})) other := mcat.Held{Claim: "mesh-store", Scope: mcat.ScopeMesh, Node: "anchor", Module: "postgres"} if _, err := Resolve(store, []string{"postgres"}, workstation(), mcat.World{Held: []mcat.Held{other}}); err == nil || @@ -110,7 +110,7 @@ func TestASingleHolderMeshSeatStillRefusesASecondHolder(t *testing.T) { // Replicated is not "whoever is assigned": two claimants with nothing on record are refused, as for // any mesh seat, and each holder is added by an act. -func TestTwoUnrecordedClaimantsOfTheReplicatedSeatAreRefused(t *testing.T) { +func testTwoUnrecordedClaimantsOfTheReplicatedSeatAreRefused(t *testing.T) { w := worldWithout("home") w.Holdings = nil _, err := Resolve(twoResolverShelf(t), []string{"dnsmasq"}, mcat.Node{Name: "home", At: "home.internal"}, w) @@ -120,7 +120,7 @@ func TestTwoUnrecordedClaimantsOfTheReplicatedSeatAreRefused(t *testing.T) { } // Every consumer is bound to the same holder whatever order the mesh resolved its machines in. -func TestTheFirstHolderIsTheFirstProvider(t *testing.T) { +func testTheFirstHolderIsTheFirstProvider(t *testing.T) { providers := []mcat.Provider{{Node: "anchor", Module: "dnsmasq"}, {Node: "home", Module: "dnsmasq"}} for _, held := range [][]mcat.Held{bothResolvers, {bothResolvers[1], bothResolvers[0]}} { if p, ok := HolderAmong("wildcard-resolution", providers, held); !ok || p.Node != "anchor" { @@ -132,7 +132,7 @@ func TestTheFirstHolderIsTheFirstProvider(t *testing.T) { // One host record per machine, beside its wildcard (novox/hq issue 262): a name with a host record // says it exists and has no IPv6 address, where the wildcard alone said there is no such name, and // musl reads that as final. -func TestTheResolverHasOneHostRecordPerMachine(t *testing.T) { +func testTheResolverHasOneHostRecordPerMachine(t *testing.T) { got, err := Resolve(twoResolverShelf(t), []string{"dnsmasq"}, mcat.Node{Name: "anchor", At: "anchor.internal"}, mcat.World{}) if err != nil { t.Fatal(err) @@ -158,3 +158,13 @@ func TestTheResolverHasOneHostRecordPerMachine(t *testing.T) { t.Errorf("%d host records for %d machines:\n%s", len(records), len(resolverMachines), content) } } + +// TestTwoResolvers runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestTwoResolvers(t *testing.T) { + t.Run("EveryUplinkRequiresTheMeshsResolver", testEveryUplinkRequiresTheMeshsResolver) + t.Run("AHolderAnswersItsOwnRequirement", testAHolderAnswersItsOwnRequirement) + t.Run("ASingleHolderMeshSeatStillRefusesASecondHolder", testASingleHolderMeshSeatStillRefusesASecondHolder) + t.Run("TwoUnrecordedClaimantsOfTheReplicatedSeatAreRefused", testTwoUnrecordedClaimantsOfTheReplicatedSeatAreRefused) + t.Run("TheFirstHolderIsTheFirstProvider", testTheFirstHolderIsTheFirstProvider) + t.Run("TheResolverHasOneHostRecordPerMachine", testTheResolverHasOneHostRecordPerMachine) +} diff --git a/internal/compose/resolution/unconsumed_placeholder_test.go b/internal/compose/resolution/unconsumed_placeholder_test.go index 082bcdc3..503d5f15 100644 --- a/internal/compose/resolution/unconsumed_placeholder_test.go +++ b/internal/compose/resolution/unconsumed_placeholder_test.go @@ -21,7 +21,7 @@ const shellsOperators = "${PORT:-8080} ${SHELL:-/bin/sh} ${SECRET:?unset} ${dir: // Composition refuses the same placeholders in the same words — a manifest the store already holds // was never parsed by this binary — and a namespace the mesh knows, written in a field its pass does // not read, is refused there too, because it would reach the machine as the same literal text. -func TestAMisspelledPlaceholderIsRefusedAtComposition(t *testing.T) { +func testAMisspelledPlaceholderIsRefusedAtComposition(t *testing.T) { for _, c := range []struct { field string r map[string]any @@ -75,7 +75,7 @@ func contentOf(t *testing.T, out []map[string]any, id string) string { // ${setting:…}, and a JSON setting `${level:upper}` merged into a mergeable file, reach the machine as // set — software that templates its own configuration (Log4j's `${env:…}`, Spring's `${timeout:30}`) // is configured exactly this way. -func TestAValueHoldingAPlaceholderShapeComposesUnchanged(t *testing.T) { +func testAValueHoldingAPlaceholderShapeComposesUnchanged(t *testing.T) { m := mcat.Manifest{Module: "templater", Version: "1", Resources: []map[string]any{ {"id": "conf", "type": "file", "path": "/etc/templater.conf", "content": "template=${setting:template}\n"}, {"id": "json", "type": "file", "path": "/etc/templater.json", "merge": mcat.MergeJSON, "content": `{"fmt":"plain"}`}, @@ -97,7 +97,7 @@ func TestAValueHoldingAPlaceholderShapeComposesUnchanged(t *testing.T) { // Contributed shell code is the shell's, and no pass reads it (novox/hq ADR 0204): zsh's own // `${path:t}` is namespace-shaped, and reaches the holder's file untouched. -func TestContributedShellCodeIsNotSwept(t *testing.T) { +func testContributedShellCodeIsNotSwept(t *testing.T) { modules := []mcat.Manifest{zshHolder(), {Module: "modifier", Shell: []mcat.ShellCode{ {For: "zsh", Slot: "normal", Code: "echo ${path:t} ${shel:zsh:first}"}, }}} @@ -109,3 +109,10 @@ func TestContributedShellCodeIsNotSwept(t *testing.T) { t.Fatalf("the contributed code did not reach the holder's file as written: %q", got) } } + +// TestUnconsumedPlaceholder runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestUnconsumedPlaceholder(t *testing.T) { + t.Run("AMisspelledPlaceholderIsRefusedAtComposition", testAMisspelledPlaceholderIsRefusedAtComposition) + t.Run("AValueHoldingAPlaceholderShapeComposesUnchanged", testAValueHoldingAPlaceholderShapeComposesUnchanged) + t.Run("ContributedShellCodeIsNotSwept", testContributedShellCodeIsNotSwept) +} diff --git a/internal/compose/resolution/zones_test.go b/internal/compose/resolution/zones_test.go index 18d47f33..e7578a9d 100644 --- a/internal/compose/resolution/zones_test.go +++ b/internal/compose/resolution/zones_test.go @@ -9,7 +9,7 @@ import ( // The zone is the operator's (a setting) and the port is where this machine publishes the listen — // neither is the definition's to state. -func TestAZoneIsPlacedFromTheNodesSettingAndPublishedPort(t *testing.T) { +func testAZoneIsPlacedFromTheNodesSettingAndPublishedPort(t *testing.T) { m := mcat.Manifest{Module: "lab", Zone: &mcat.Zone{Name: "${setting:zone}", Listen: "dns"}, Listens: []mcat.Listening{{Name: "dns", Port: 5353, From: mcat.FromMesh}}} z, err := ZoneOn(m, []mcat.Layer{{From: "node", Values: map[string]any{"zone": "Incus."}}}, @@ -26,7 +26,7 @@ func TestAZoneIsPlacedFromTheNodesSettingAndPublishedPort(t *testing.T) { } // One module answers a zone, and none may shadow the mesh's names or a public domain. -func TestTheMeshRefusesAZoneTwiceOrOneThatShadows(t *testing.T) { +func testTheMeshRefusesAZoneTwiceOrOneThatShadows(t *testing.T) { one := mcat.ZoneAt{Zone: "incus", Node: "workstation", Module: "lab", Address: "10.77.0.3", Port: 53} if p := ZonesProblems([]mcat.ZoneAt{one}, "internal", []string{"example.tld"}); len(p) != 0 { t.Fatalf("one ordinary zone was refused: %v", p) @@ -45,3 +45,9 @@ func TestTheMeshRefusesAZoneTwiceOrOneThatShadows(t *testing.T) { } } } + +// TestZones runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestZones(t *testing.T) { + t.Run("AZoneIsPlacedFromTheNodesSettingAndPublishedPort", testAZoneIsPlacedFromTheNodesSettingAndPublishedPort) + t.Run("TheMeshRefusesAZoneTwiceOrOneThatShadows", testTheMeshRefusesAZoneTwiceOrOneThatShadows) +} diff --git a/internal/compose/resolve_test.go b/internal/compose/resolve_test.go index a78dd83f..fbc64c58 100644 --- a/internal/compose/resolve_test.go +++ b/internal/compose/resolve_test.go @@ -62,7 +62,7 @@ func theStoreMesh(t *testing.T) Input { // 1362/AC7 and AC4 (bindings_integration_test.go): a consumer of a provision that keeps its data stays beside its data, one that // does not follows the seat; the laptop's store taken away, the consumer bound there on record is refused, not moved to the // anchor's empty one; a person's pin moves it. -func TestAConsumerStaysBesideItsDataUntilAPersonPinsIt(t *testing.T) { +func testAConsumerStaysBesideItsDataUntilAPersonPinsIt(t *testing.T) { in := theStoreMesh(t) got, err := Resolve(in, "laptop") if err != nil { @@ -99,7 +99,7 @@ func TestAConsumerStaysBesideItsDataUntilAPersonPinsIt(t *testing.T) { // 1362/AC4: a data-keeping consumer bound on record to a provider elsewhere is kept on that provider, and the resolution says // so (Resolution.Kept) when the mesh would answer it otherwise. -func TestADataKeepingConsumerBoundElsewhereIsKeptThereAndSaid(t *testing.T) { +func testADataKeepingConsumerBoundElsewhereIsKeptThereAndSaid(t *testing.T) { in := theStoreMesh(t) laptop := nodeOf(t, &in, "laptop") laptop.Assigned = []string{overlay.Name, "resolver", "network", "board"} // no store of its own @@ -153,7 +153,7 @@ func theFilesNeed(t *testing.T, got Resolved) catalogue.Needed { // 1362/AC1: a pair credential the Input names as existing with no value, and one it names not at all, are composed with a // stand-in and named foreseen, and nothing is made; one with a value is composed with it and foreseen is empty. -func TestAPairCredentialNotHeldIsComposedWithAStandInAndNamedForeseen(t *testing.T) { +func testAPairCredentialNotHeldIsComposedWithAStandInAndNamedForeseen(t *testing.T) { mk := func() Input { return theObjectsMesh(t, objects()) } for name, creds := range map[string][]Credential{ "no entry": nil, @@ -192,7 +192,7 @@ func TestAPairCredentialNotHeldIsComposedWithAStandInAndNamedForeseen(t *testing // 1362/AC2: a credential only a person gives and nobody has is not given and not made: the consumer still resolves without it // (novox/hq ADR 0337 clause 4), said with the controller's words; one given is composed with it. -func TestACredentialOnlyAPersonGivesIsNotMadeAndTheConsumerStillResolves(t *testing.T) { +func testACredentialOnlyAPersonGivesIsNotMadeAndTheConsumerStillResolves(t *testing.T) { for name, creds := range map[string][]Credential{ "no entry": nil, "to be made (never, for one issued outside)": {{Provision: "s3-bucket", Consumer: "laptop", ConsumerModule: "files", Provider: "anchor", State: CredentialWouldMake}}, @@ -227,7 +227,7 @@ func TestACredentialOnlyAPersonGivesIsNotMadeAndTheConsumerStillResolves(t *test // 1362/AC3, issue 1966: a fault of one module's own, a credential the send would refuse (a given value sealed to a key a machine no // longer has) or a second claimant of a seat held once, costs that module and not the machine: it is held with the send's words, its // declaration says it left out, and every other module of the machine composes. Not a node whose set does not compose. -func TestAModuleWhoseCredentialOrClaimFailsIsHeldAndTheMachineComposes(t *testing.T) { +func testAModuleWhoseCredentialOrClaimFailsIsHeldAndTheMachineComposes(t *testing.T) { why := "files's \"s3-bucket\" credential from anchor was accepted from a person, and a sealing key at one end has changed since. " + "The mesh cannot re-seal a value it does not hold: accept it again with `secret accept laptop files s3-bucket --provider anchor`" for _, c := range []struct{ name, module, said string }{ @@ -261,7 +261,7 @@ func TestAModuleWhoseCredentialOrClaimFailsIsHeldAndTheMachineComposes(t *testin // A record-answered need is filled with the licence key sealed to this holder, and the manager holder is handed the manager node's // public sealing key (novox/hq ADR 0050) and no other. -func TestARecordAnsweredNeedGetsItsKeyAndTheManagerItsPublicKey(t *testing.T) { +func testARecordAnsweredNeedGetsItsKeyAndTheManagerItsPublicKey(t *testing.T) { in := aMesh(t) in.Catalogue["assistant"] = catalogue.Manifest{Module: "assistant", Version: "1", Requires: []string{LicenceProvision}} laptop := nodeOf(t, &in, "laptop") @@ -293,7 +293,7 @@ func TestARecordAnsweredNeedGetsItsKeyAndTheManagerItsPublicKey(t *testing.T) { } // 1362/AC5: a node whose own set does not compose returns an error callers can tell from an unreadable Input. -func TestANodeWhoseOwnSetDoesNotComposeIsToldApartFromAnUnreadableInput(t *testing.T) { +func testANodeWhoseOwnSetDoesNotComposeIsToldApartFromAnUnreadableInput(t *testing.T) { in := aMesh(t) in.Catalogue["rival-one"] = catalogue.Manifest{Module: "rival-one", Version: "1", Requires: []string{"two-give-this"}} in.Catalogue["giver-a"] = catalogue.Manifest{Module: "giver-a", Version: "1", Provides: catalogue.Offers("two-give-this")} @@ -320,7 +320,7 @@ func TestANodeWhoseOwnSetDoesNotComposeIsToldApartFromAnUnreadableInput(t *testi } // 1362/AC6: settings are returned for every resolved module that has layers in the Input, including one pulled in by another. -func TestSettingsAreReturnedForEveryResolvedModuleIncludingOneThatWasPulledIn(t *testing.T) { +func testSettingsAreReturnedForEveryResolvedModuleIncludingOneThatWasPulledIn(t *testing.T) { in := aMesh(t) in.Catalogue["lib"] = catalogue.Manifest{Module: "lib", Version: "1", Provides: catalogue.Offers("blob")} in.Catalogue["app"] = catalogue.Manifest{Module: "app", Version: "1", Requires: []string{"blob"}} @@ -355,7 +355,7 @@ func TestSettingsAreReturnedForEveryResolvedModuleIncludingOneThatWasPulledIn(t // Round 1, finding 3: a licence key the Input does not carry (Keys not given) is composed with a stand-in and named foreseen, so the // node still composes; Keys given that lack the holder is the mesh holding none, and the need stays empty. -func TestALicenceKeyTheInputDoesNotCarryIsAStandInAndNamedForeseen(t *testing.T) { +func testALicenceKeyTheInputDoesNotCarryIsAStandInAndNamedForeseen(t *testing.T) { in := aMesh(t) in.Catalogue["assistant"] = catalogue.Manifest{Module: "assistant", Version: "1", Requires: []string{LicenceProvision}} laptop := nodeOf(t, &in, "laptop") @@ -388,7 +388,7 @@ func TestALicenceKeyTheInputDoesNotCarryIsAStandInAndNamedForeseen(t *testing.T) // A consumer not handed of a provision whose provider's offer says the helper answers it has that provision in a plan of // its own (issue 774: grafana's route): the composition marks the need answered by the helper, and the plan keys it. -func TestANeedAnsweredByTheHelperIsInTheConsumersPlan(t *testing.T) { +func testANeedAnsweredByTheHelperIsInTheConsumersPlan(t *testing.T) { in := theStoreMesh(t) store := in.Catalogue["store"] store.Provides = []catalogue.Offer{{Name: "postgres-database", Scope: catalogue.ScopeMesh, AnsweredBy: catalogue.AnsweredByHelper}} @@ -413,3 +413,17 @@ func TestANeedAnsweredByTheHelperIsInTheConsumersPlan(t *testing.T) { t.Fatalf("board's plan is %+v", c.Plans["board"]) } } + +// TestResolve runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestResolve(t *testing.T) { + t.Run("AConsumerStaysBesideItsDataUntilAPersonPinsIt", testAConsumerStaysBesideItsDataUntilAPersonPinsIt) + t.Run("ADataKeepingConsumerBoundElsewhereIsKeptThereAndSaid", testADataKeepingConsumerBoundElsewhereIsKeptThereAndSaid) + t.Run("APairCredentialNotHeldIsComposedWithAStandInAndNamedForeseen", testAPairCredentialNotHeldIsComposedWithAStandInAndNamedForeseen) + t.Run("ACredentialOnlyAPersonGivesIsNotMadeAndTheConsumerStillResolves", testACredentialOnlyAPersonGivesIsNotMadeAndTheConsumerStillResolves) + t.Run("AModuleWhoseCredentialOrClaimFailsIsHeldAndTheMachineComposes", testAModuleWhoseCredentialOrClaimFailsIsHeldAndTheMachineComposes) + t.Run("ARecordAnsweredNeedGetsItsKeyAndTheManagerItsPublicKey", testARecordAnsweredNeedGetsItsKeyAndTheManagerItsPublicKey) + t.Run("ANodeWhoseOwnSetDoesNotComposeIsToldApartFromAnUnreadableInput", testANodeWhoseOwnSetDoesNotComposeIsToldApartFromAnUnreadableInput) + t.Run("SettingsAreReturnedForEveryResolvedModuleIncludingOneThatWasPulledIn", testSettingsAreReturnedForEveryResolvedModuleIncludingOneThatWasPulledIn) + t.Run("ALicenceKeyTheInputDoesNotCarryIsAStandInAndNamedForeseen", testALicenceKeyTheInputDoesNotCarryIsAStandInAndNamedForeseen) + t.Run("ANeedAnsweredByTheHelperIsInTheConsumersPlan", testANeedAnsweredByTheHelperIsInTheConsumersPlan) +} diff --git a/internal/compose/rest_test.go b/internal/compose/rest_test.go index 8ba82ad0..fcd81229 100644 --- a/internal/compose/rest_test.go +++ b/internal/compose/rest_test.go @@ -48,7 +48,7 @@ func providers(w catalogue.World, provision string) []string { // 1361/AC1: three nodes each offering a provision; the rest of the mesh, for one of them, offers every other node's and none of its // own, and holds what they hold. -func TestTheRestOfTheMeshOffersEveryOtherNodesProvisionsAndNoneOfTheExcluded(t *testing.T) { +func testTheRestOfTheMeshOffersEveryOtherNodesProvisionsAndNoneOfTheExcluded(t *testing.T) { in := threeNodes(t) w, passes, left, err := TheRestOfTheMesh(in, "laptop") if err != nil || len(left) != 0 || len(passes.Passes) != 0 { @@ -87,7 +87,7 @@ func TestTheRestOfTheMeshOffersEveryOtherNodesProvisionsAndNoneOfTheExcluded(t * } // 1361/AC2: a node whose assigned set does not resolve is left out and named with today's reason, and the others still offer. -func TestANodeWhoseSetDoesNotResolveIsLeftOutAndTheOthersStillOffer(t *testing.T) { +func testANodeWhoseSetDoesNotResolveIsLeftOutAndTheOthersStillOffer(t *testing.T) { in := threeNodes(t) rivalOne := catalogue.Manifest{Module: "rival-one", Version: "1", Resources: []map[string]any{{"id": "r", "type": "directory", "path": "/var/lib/the-same", "mode": "0700"}}} rivalTwo := catalogue.Manifest{Module: "rival-two", Version: "1", Resources: []map[string]any{{"id": "r", "type": "directory", "path": "/var/lib/the-same", "mode": "0700"}}} @@ -125,7 +125,7 @@ func TestANodeWhoseSetDoesNotResolveIsLeftOutAndTheOthersStillOffer(t *testing.T // 1361/AC3 and AC4 (mesh-controller seat_pass_test.go TestACompositionPassesTheSeatAndWritesOneHandActByTheController, in // the part that is not a write): a seat held once whose holder on record is assigned nowhere and one claimant: the seat // passes to that claimant in the World, and is returned as a pass; Input's holdings are unchanged. -func TestASeatWhoseHolderIsAssignedNowhereGoesToItsOnlyClaimant(t *testing.T) { +func testASeatWhoseHolderIsAssignedNowhereGoesToItsOnlyClaimant(t *testing.T) { withSeat(t) mk := func() Input { return Input{ @@ -159,7 +159,7 @@ func TestASeatWhoseHolderIsAssignedNowhereGoesToItsOnlyClaimant(t *testing.T) { // 1317/AC2 (seat_pass_test.go TestACompositionWithTwoClaimantsRecordsNoneAndSaysSo): two claimants, no pass, the refusal said with // both and the remedy. 1317/AC3 and AC4 (TestACompositionChangesNothingWhileTheHolderIsAssignedOrNobodyClaims): nothing changes while // the holder is assigned, nor with no claimant. -func TestNoSeatIsPassedForTwoClaimantsAnAssignedHolderOrNoClaimant(t *testing.T) { +func testNoSeatIsPassedForTwoClaimantsAnAssignedHolderOrNoClaimant(t *testing.T) { withSeat(t) held := []catalogue.Held{{Claim: "mesh-broker", Scope: catalogue.ScopeMesh, Node: "novox", Module: "old-broker"}} shelf := map[string]catalogue.Manifest{"gate": aBrokerClaiming("gate"), "other": aBrokerClaiming("other"), "old-broker": aBrokerClaiming("old-broker")} @@ -180,7 +180,7 @@ func TestNoSeatIsPassedForTwoClaimantsAnAssignedHolderOrNoClaimant(t *testing.T) } // seat_pass_test.go TestAHolderAssignedButNotOnTheShelfIsNotTakenForGone. -func TestAHolderAssignedButNotOnTheShelfIsNotTakenForGone(t *testing.T) { +func testAHolderAssignedButNotOnTheShelfIsNotTakenForGone(t *testing.T) { withSeat(t) as := (&composer{}).assignmentsOf(map[string][]string{"novox": {"gate", "old-broker"}}) passes, _ := catalogue.SeatsToPassOn( @@ -215,7 +215,7 @@ func TestAHolderAssignedButNotOnTheShelfIsNotTakenForGone(t *testing.T) { // The not-resolving node of a view with a holder on record: holdings reach the first pass (novox/hq ADR 0131), so a node running // the next holder beside the current one is not refused as a second holder. -func TestAHolderOnRecordSettlesTheSeatInTheRestOfTheMesh(t *testing.T) { +func testAHolderOnRecordSettlesTheSeatInTheRestOfTheMesh(t *testing.T) { withSeat(t) in := Input{ Catalogue: map[string]catalogue.Manifest{"old-broker": aBrokerClaiming("old-broker"), "gate": aBrokerClaiming("gate")}, @@ -238,7 +238,7 @@ func TestAHolderOnRecordSettlesTheSeatInTheRestOfTheMesh(t *testing.T) { // Each machine is resolved in the second pass with its own pins, as its plan is (novox/hq issue 188): a pin to a provider that // does not answer is its own refusal, so the machine is left out for it; the same machine without the pin is not. -func TestEachNodeIsResolvedWithItsOwnPinsInTheRestOfTheMesh(t *testing.T) { +func testEachNodeIsResolvedWithItsOwnPinsInTheRestOfTheMesh(t *testing.T) { in := threeNodes(t) in.Nodes = append(in.Nodes, Node{Name: "newt", Place: Place{Site: "there", Address: "10.77.0.4"}, Assigned: []string{overlay.Name, "files"}, Capabilities: map[string]bool{}}) _, _, left, err := TheRestOfTheMesh(in, "") @@ -254,7 +254,7 @@ func TestEachNodeIsResolvedWithItsOwnPinsInTheRestOfTheMesh(t *testing.T) { // ADR 0660: a holder on record that is still assigned, whose manifest no longer claims the seat, has left it; the seat is // composed with the one claimant, the pass is returned and said, and Input's holdings (the record) are not written. -func TestAHolderWhoseManifestDroppedTheSeatGoesToItsOnlyClaimant(t *testing.T) { +func testAHolderWhoseManifestDroppedTheSeatGoesToItsOnlyClaimant(t *testing.T) { withSeat(t) mk := func(claimants ...string) Input { cat := map[string]catalogue.Manifest{"old-broker": {Module: "old-broker"}} @@ -301,3 +301,15 @@ func TestAHolderWhoseManifestDroppedTheSeatGoesToItsOnlyClaimant(t *testing.T) { t.Fatalf("the answer does not say the pass: %v %q", err, said) } } + +// TestRest runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRest(t *testing.T) { + t.Run("TheRestOfTheMeshOffersEveryOtherNodesProvisionsAndNoneOfTheExcluded", testTheRestOfTheMeshOffersEveryOtherNodesProvisionsAndNoneOfTheExcluded) + t.Run("ANodeWhoseSetDoesNotResolveIsLeftOutAndTheOthersStillOffer", testANodeWhoseSetDoesNotResolveIsLeftOutAndTheOthersStillOffer) + t.Run("ASeatWhoseHolderIsAssignedNowhereGoesToItsOnlyClaimant", testASeatWhoseHolderIsAssignedNowhereGoesToItsOnlyClaimant) + t.Run("NoSeatIsPassedForTwoClaimantsAnAssignedHolderOrNoClaimant", testNoSeatIsPassedForTwoClaimantsAnAssignedHolderOrNoClaimant) + t.Run("AHolderAssignedButNotOnTheShelfIsNotTakenForGone", testAHolderAssignedButNotOnTheShelfIsNotTakenForGone) + t.Run("AHolderOnRecordSettlesTheSeatInTheRestOfTheMesh", testAHolderOnRecordSettlesTheSeatInTheRestOfTheMesh) + t.Run("EachNodeIsResolvedWithItsOwnPinsInTheRestOfTheMesh", testEachNodeIsResolvedWithItsOwnPinsInTheRestOfTheMesh) + t.Run("AHolderWhoseManifestDroppedTheSeatGoesToItsOnlyClaimant", testAHolderWhoseManifestDroppedTheSeatGoesToItsOnlyClaimant) +} diff --git a/internal/composer/composer_test.go b/internal/composer/composer_test.go index 12c26527..8d167b52 100644 --- a/internal/composer/composer_test.go +++ b/internal/composer/composer_test.go @@ -36,7 +36,7 @@ func withInput(t *testing.T, r Request, in compose.Input) Request { } // The seats a node's assigned modules claim are held there when the request says the holdings come from the claims. -func TestHoldingsComeFromTheClaims(t *testing.T) { +func testHoldingsComeFromTheClaims(t *testing.T) { m, err := catalogue.Decode([]byte(demo)) if err != nil { t.Fatal(err) @@ -48,7 +48,7 @@ func TestHoldingsComeFromTheClaims(t *testing.T) { } // A request the command cannot run is refused, never answered as a verdict: a case named twice, an unknown depth. -func TestARequestItCannotRunIsRefused(t *testing.T) { +func testARequestItCannotRunIsRefused(t *testing.T) { if _, err := Run(Request{V: Version, Cases: []Case{{Name: "a"}, {Name: "a"}}}); err == nil { t.Error("a case named twice runs") } @@ -408,7 +408,7 @@ func TestARequestItCannotRunIsRefused(t *testing.T) { // The composer judges no manifest (novox/hq ADR 0578 §5): xterm's module.json from mesh-catalog at 835bf22b, whose // config value falls back to "font-size", is read whatever list of predefined keys a request carries (a group touching // xterm failed its composition on this, group check 18df81380db3), and accepted by being in the case (design 47 H, H-A-112). -func TestTheComposerJudgesNoManifest(t *testing.T) { +func testTheComposerJudgesNoManifest(t *testing.T) { raw, err := os.ReadFile("testdata/catalogue-835bf22b-xterm.module.json") if err != nil { t.Fatal(err) @@ -423,3 +423,10 @@ func TestTheComposerJudgesNoManifest(t *testing.T) { t.Fatalf("xterm: %+v, want accepted", got) } } + +// TestComposer runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestComposer(t *testing.T) { + t.Run("HoldingsComeFromTheClaims", testHoldingsComeFromTheClaims) + t.Run("ARequestItCannotRunIsRefused", testARequestItCannotRunIsRefused) + t.Run("TheComposerJudgesNoManifest", testTheComposerJudgesNoManifest) +} diff --git a/internal/filling/filling_test.go b/internal/filling/filling_test.go index b7828369..96acd6b1 100644 --- a/internal/filling/filling_test.go +++ b/internal/filling/filling_test.go @@ -66,7 +66,7 @@ func newEngine(t *testing.T, raw string, lock sync.Locker) *engine { return e } -func TestAWriteFromTheProvisionersAccountOfAFilledPathIsPlaced(t *testing.T) { +func testAWriteFromTheProvisionersAccountOfAFilledPathIsPlaced(t *testing.T) { e := newEngine(t, withAccount, &sync.Mutex{}) if err := e.Accepts(provisionerUID); err != nil { t.Fatal(err) @@ -77,7 +77,7 @@ func TestAWriteFromTheProvisionersAccountOfAFilledPathIsPlaced(t *testing.T) { } } -func TestAnUndeclaredPathIsRefused(t *testing.T) { +func testAnUndeclaredPathIsRefused(t *testing.T) { e := newEngine(t, withAccount, &sync.Mutex{}) for _, path := range []string{"/etc/m/other.conf", "/etc/m/none.conf", "/etc/passwd"} { a := e.Write(context.Background(), provisionerUID, Request{Path: path, Content: []byte("evil")}) @@ -230,7 +230,7 @@ func TestAnUndeclaredPathIsRefused(t *testing.T) { }) } -func TestAnotherAccountIsRefused(t *testing.T) { +func testAnotherAccountIsRefused(t *testing.T) { e := newEngine(t, withAccount, &sync.Mutex{}) for _, uid := range []uint32{0, 1000, provisionerUID + 1} { if err := e.Accepts(uid); err == nil { @@ -246,7 +246,7 @@ func TestAnotherAccountIsRefused(t *testing.T) { } } -func TestEveryWriteIsRefusedWhileTheDeclarationNamesNoAccount(t *testing.T) { +func testEveryWriteIsRefusedWhileTheDeclarationNamesNoAccount(t *testing.T) { e := newEngine(t, withoutAccount, &sync.Mutex{}) if err := e.Accepts(provisionerUID); err == nil || !strings.Contains(err.Error(), "names no provisioner") { t.Errorf("accepted with no account named: %v", err) @@ -257,7 +257,7 @@ func TestEveryWriteIsRefusedWhileTheDeclarationNamesNoAccount(t *testing.T) { } } -func TestAnAccountThatIsRootHereIsRefused(t *testing.T) { +func testAnAccountThatIsRootHereIsRefused(t *testing.T) { e := newEngine(t, withAccount, &sync.Mutex{}) e.UIDOf = func(string) (uint32, error) { return 0, nil } if err := e.Accepts(0); err == nil || !strings.Contains(err.Error(), "root") { @@ -265,7 +265,7 @@ func TestAnAccountThatIsRootHereIsRefused(t *testing.T) { } } -func TestAnUncleanPathIsRefused(t *testing.T) { +func testAnUncleanPathIsRefused(t *testing.T) { e := newEngine(t, withAccount, &sync.Mutex{}) for _, path := range []string{"", "etc/m/m.conf", "m.conf", "/etc//m/m.conf", "/etc/m/../m/m.conf", "/etc/m/./m.conf", "/etc/m/m.conf/"} { @@ -280,7 +280,7 @@ func TestAnUncleanPathIsRefused(t *testing.T) { } // A write waits for an apply holding the apply's lock, and writes only once it is let go. -func TestAWriteWaitsForTheApply(t *testing.T) { +func testAWriteWaitsForTheApply(t *testing.T) { var applying sync.Mutex e := newEngine(t, withAccount, &applying) applying.Lock() @@ -377,7 +377,7 @@ func ask(t *testing.T, socket string, req Request) Answer { } // Over a real socket, the kernel says who is asking: this test's own account is the provisioner's here. -func TestTheSocketWritesForTheAccountTheKernelSays(t *testing.T) { +func testTheSocketWritesForTheAccountTheKernelSays(t *testing.T) { w := &fixed{uid: uint32(os.Getuid())} socket, said := serve(t, w) a := ask(t, socket, Request{Path: "/etc/m/m.conf", Content: []byte("secret value")}) @@ -391,7 +391,7 @@ func TestTheSocketWritesForTheAccountTheKernelSays(t *testing.T) { } } -func TestTheSocketRefusesAnotherAccountBeforeReadingItsRequest(t *testing.T) { +func testTheSocketRefusesAnotherAccountBeforeReadingItsRequest(t *testing.T) { w := &fixed{uid: uint32(os.Getuid()) + 1} socket, said := serve(t, w) conn, err := net.Dial("unix", socket) @@ -432,7 +432,7 @@ func floodersAreAnother(t *testing.T) { // A flood of connections from another account, each saying nothing and held open, does not stop the client's write: // each is refused and closed before it holds anything. -func TestAFloodFromAnotherAccountDoesNotStopTheClient(t *testing.T) { +func testAFloodFromAnotherAccountDoesNotStopTheClient(t *testing.T) { floodersAreAnother(t) w := &fixed{uid: uint32(os.Getuid())} socket, _ := serve(t, w) @@ -472,7 +472,7 @@ func TestAFloodFromAnotherAccountDoesNotStopTheClient(t *testing.T) { func busyWaitingCap() int { return busyWaitingAtOnce } // A client that connects and says nothing holds one slot only until within, and another write goes on meanwhile. -func TestASilentClientDoesNotHoldTheSocket(t *testing.T) { +func testASilentClientDoesNotHoldTheSocket(t *testing.T) { was := within within = 300 * time.Millisecond t.Cleanup(func() { within = was }) @@ -494,7 +494,7 @@ func TestASilentClientDoesNotHoldTheSocket(t *testing.T) { } // A request carrying more than the path and the content is refused: it says what the declaration says. -func TestARequestWithAnUnknownFieldIsRefused(t *testing.T) { +func testARequestWithAnUnknownFieldIsRefused(t *testing.T) { w := &fixed{uid: uint32(os.Getuid())} socket, _ := serve(t, w) conn, err := net.Dial("unix", socket) @@ -515,7 +515,7 @@ func TestARequestWithAnUnknownFieldIsRefused(t *testing.T) { } // An accept that fails is said, waited for and tried again: the socket goes on serving. -func TestTheSocketGoesOnAfterAnAcceptFails(t *testing.T) { +func testTheSocketGoesOnAfterAnAcceptFails(t *testing.T) { wasAccept, wasBackoff := acceptFrom, acceptBackoff failures := 3 var mu sync.Mutex @@ -541,7 +541,7 @@ func TestTheSocketGoesOnAfterAnAcceptFails(t *testing.T) { } // The socket's directory is given the mode the socket needs. -func TestTheSocketsDirectoryIsOpenedToEveryAccount(t *testing.T) { +func testTheSocketsDirectoryIsOpenedToEveryAccount(t *testing.T) { dir, err := os.MkdirTemp("", "fill") if err != nil { t.Fatal(err) @@ -574,7 +574,7 @@ func TestTheSocketsDirectoryIsOpenedToEveryAccount(t *testing.T) { // The first refusal of each kind for each account is said at once; what follows within the time is counted, and the // count is said when the time is up, even when the account has stopped. -func TestRefusalsAreSaidOnceAndTheirCountIsNeverLost(t *testing.T) { +func testRefusalsAreSaidOnceAndTheirCountIsNeverLost(t *testing.T) { var mu sync.Mutex var said []string r := &refusalWords{say: func(s string) { mu.Lock(); said = append(said, s); mu.Unlock() }} @@ -652,7 +652,7 @@ func refusingSocket(t *testing.T, every time.Duration) (func(int), func() string } // Refusals counted while the socket serves are said on its timer, though the account has stopped asking. -func TestTheSocketSaysItsCountedRefusalsOnATimer(t *testing.T) { +func testTheSocketSaysItsCountedRefusalsOnATimer(t *testing.T) { refuse, all, _ := refusingSocket(t, 200*time.Millisecond) refuse(3) // "more writes", not a number: a tick may fall between two refusals and split the count. @@ -666,7 +666,7 @@ func TestTheSocketSaysItsCountedRefusalsOnATimer(t *testing.T) { } // Refusals counted when the socket stops are said as it stops. -func TestTheSocketSaysItsCountedRefusalsWhenItStops(t *testing.T) { +func testTheSocketSaysItsCountedRefusalsWhenItStops(t *testing.T) { refuse, all, stop := refusingSocket(t, time.Hour) refuse(5) if strings.Contains(all(), "4 more") { @@ -679,7 +679,7 @@ func TestTheSocketSaysItsCountedRefusalsWhenItStops(t *testing.T) { } // A connection over the bound of those waiting to be judged is closed unread, and said. -func TestAConnectionOverTheWaitingBoundIsClosedUnread(t *testing.T) { +func testAConnectionOverTheWaitingBoundIsClosedUnread(t *testing.T) { was := judgeWaiting judgeWaiting = 0 t.Cleanup(func() { judgeWaiting = was }) @@ -699,3 +699,25 @@ func TestAConnectionOverTheWaitingBoundIsClosedUnread(t *testing.T) { t.Errorf("writes %v, said %q", w.writes, said()) } } + +// TestFilling runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFilling(t *testing.T) { + t.Run("AWriteFromTheProvisionersAccountOfAFilledPathIsPlaced", testAWriteFromTheProvisionersAccountOfAFilledPathIsPlaced) + t.Run("AnUndeclaredPathIsRefused", testAnUndeclaredPathIsRefused) + t.Run("AnotherAccountIsRefused", testAnotherAccountIsRefused) + t.Run("EveryWriteIsRefusedWhileTheDeclarationNamesNoAccount", testEveryWriteIsRefusedWhileTheDeclarationNamesNoAccount) + t.Run("AnAccountThatIsRootHereIsRefused", testAnAccountThatIsRootHereIsRefused) + t.Run("AnUncleanPathIsRefused", testAnUncleanPathIsRefused) + t.Run("AWriteWaitsForTheApply", testAWriteWaitsForTheApply) + t.Run("TheSocketWritesForTheAccountTheKernelSays", testTheSocketWritesForTheAccountTheKernelSays) + t.Run("TheSocketRefusesAnotherAccountBeforeReadingItsRequest", testTheSocketRefusesAnotherAccountBeforeReadingItsRequest) + t.Run("AFloodFromAnotherAccountDoesNotStopTheClient", testAFloodFromAnotherAccountDoesNotStopTheClient) + t.Run("ASilentClientDoesNotHoldTheSocket", testASilentClientDoesNotHoldTheSocket) + t.Run("ARequestWithAnUnknownFieldIsRefused", testARequestWithAnUnknownFieldIsRefused) + t.Run("TheSocketGoesOnAfterAnAcceptFails", testTheSocketGoesOnAfterAnAcceptFails) + t.Run("TheSocketsDirectoryIsOpenedToEveryAccount", testTheSocketsDirectoryIsOpenedToEveryAccount) + t.Run("RefusalsAreSaidOnceAndTheirCountIsNeverLost", testRefusalsAreSaidOnceAndTheirCountIsNeverLost) + t.Run("TheSocketSaysItsCountedRefusalsOnATimer", testTheSocketSaysItsCountedRefusalsOnATimer) + t.Run("TheSocketSaysItsCountedRefusalsWhenItStops", testTheSocketSaysItsCountedRefusalsWhenItStops) + t.Run("AConnectionOverTheWaitingBoundIsClosedUnread", testAConnectionOverTheWaitingBoundIsClosedUnread) +} diff --git a/internal/firewall/filters_test.go b/internal/firewall/filters_test.go index 79de0637..0aff0251 100644 --- a/internal/firewall/filters_test.go +++ b/internal/firewall/filters_test.go @@ -28,7 +28,7 @@ func ownerOf(filters []Filter, where string) string { // captured from three machines of the first mesh. The control node: a ban list reached through the // runtime's user chain is a ban; a refusal left in that chain, and a chain a retired front end left // behind, are *other*; the runtime's own and the mesh's own are theirs. -func TestTheControlNodesRefusalsAreClassified(t *testing.T) { +func testTheControlNodesRefusalsAreClassified(t *testing.T) { got := Filters(fixture(t, "control-node.nft"), nil, false) for where, want := range map[string]string{ "table ip filter, chain f2b-recidive": OwnerBan, @@ -62,7 +62,7 @@ func TestTheControlNodesRefusalsAreClassified(t *testing.T) { // The laptop: the runtime's forward policy and bridge guards, a virtualisation host and an endpoint // agent that refuse nothing, and the mesh — filtered by the mesh alone. -func TestTheLaptopIsFilteredByTheMeshAlone(t *testing.T) { +func testTheLaptopIsFilteredByTheMeshAlone(t *testing.T) { got := Filters(fixture(t, "laptop.nft"), nil, false) for where, want := range map[string]string{ "table ip filter, chain FORWARD": OwnerRuntime, @@ -86,7 +86,7 @@ func TestTheLaptopIsFilteredByTheMeshAlone(t *testing.T) { // The home server: its rules are in the legacy filter, where a predecessor's chain still drops what // arrives on the outward link for the forwarded path — invisible to the mesh until now (issue 144). -func TestThePredecessorsChainInTheLegacyFilterIsOther(t *testing.T) { +func testThePredecessorsChainInTheLegacyFilterIsOther(t *testing.T) { mesh := "table inet mesh {\n\tchain forward {\n\t\ttype filter hook forward priority filter; policy drop;\n\t}\n}\n" got := Filters(mesh, map[string]string{"iptables-legacy": fixture(t, "home-server-legacy-S.txt")}, false) for where, want := range map[string]string{ @@ -115,7 +115,7 @@ func TestThePredecessorsChainInTheLegacyFilterIsOther(t *testing.T) { // With the front end in force, its chains are its own; retired, a chain it left behind that still // refuses is nobody's and said so. -func TestAFrontEndsChainsAreItsWhileItIsInForce(t *testing.T) { +func testAFrontEndsChainsAreItsWhileItIsInForce(t *testing.T) { ruleset := dockerOnly(t) + ufwChains for _, f := range Filters(ruleset, nil, true) { if strings.Contains(f.Where, "ufw") && f.Owner != OwnerFoundFirewall { @@ -128,3 +128,11 @@ func TestAFrontEndsChainsAreItsWhileItIsInForce(t *testing.T) { } } } + +// TestFilters runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFilters(t *testing.T) { + t.Run("TheControlNodesRefusalsAreClassified", testTheControlNodesRefusalsAreClassified) + t.Run("TheLaptopIsFilteredByTheMeshAlone", testTheLaptopIsFilteredByTheMeshAlone) + t.Run("ThePredecessorsChainInTheLegacyFilterIsOther", testThePredecessorsChainInTheLegacyFilterIsOther) + t.Run("AFrontEndsChainsAreItsWhileItIsInForce", testAFrontEndsChainsAreItsWhileItIsInForce) +} diff --git a/internal/firewall/firewall_test.go b/internal/firewall/firewall_test.go index a64cfd6e..7fb1a315 100644 --- a/internal/firewall/firewall_test.go +++ b/internal/firewall/firewall_test.go @@ -67,26 +67,26 @@ table inet mesh_guard { } ` -func TestTheContainerRuntimesOwnRulesAreNotAFirewall(t *testing.T) { +func testTheContainerRuntimesOwnRulesAreNotAFirewall(t *testing.T) { if got := Refusing(dockerOnly(t), false); len(got) != 0 { t.Errorf("the runtime's own rules read as a firewall: %v", got) } } -func TestTheMeshsOwnTablesAreNotAFirewall(t *testing.T) { +func testTheMeshsOwnTablesAreNotAFirewall(t *testing.T) { if got := Refusing(dockerOnly(t)+theMeshsOwn, false); len(got) != 0 { t.Errorf("the mesh's own tables read as a found firewall: %v", got) } } -func TestATableThatDropsIsAFirewall(t *testing.T) { +func testATableThatDropsIsAFirewall(t *testing.T) { got := Refusing(dockerOnly(t)+aDroppingTable, false) if len(got) != 1 || got[0] != "table inet filter" { t.Errorf("a dropping table was not named: %v", got) } } -func TestUfwsOwnChainsAreUfwsWhenItIsActive(t *testing.T) { +func testUfwsOwnChainsAreUfwsWhenItIsActive(t *testing.T) { if got := Refusing(dockerOnly(t)+ufwChains, true); len(got) != 0 { t.Errorf("ufw's own chains read as a second firewall: %v", got) } @@ -95,7 +95,7 @@ func TestUfwsOwnChainsAreUfwsWhenItIsActive(t *testing.T) { } } -func TestLegacyIptablesThatRefusesIsAFirewall(t *testing.T) { +func testLegacyIptablesThatRefusesIsAFirewall(t *testing.T) { docker := "-P INPUT ACCEPT\n-P FORWARD DROP\n-P OUTPUT ACCEPT\n-N DOCKER\n-A DOCKER -i docker0 -j DROP\n" if got := RefusingLegacy(docker); len(got) != 0 { t.Errorf("the runtime's legacy rules read as a firewall: %v", got) @@ -282,7 +282,7 @@ func opening(id string, port int, from, path string, to int) *declaration.Openin From: from, Path: path, To: to} } -func TestAnOpeningBecomesTheUfwRuleForItsPathAndOrigin(t *testing.T) { +func testAnOpeningBecomesTheUfwRuleForItsPathAndOrigin(t *testing.T) { for _, c := range []struct { o *declaration.Opening want string @@ -298,7 +298,7 @@ func TestAnOpeningBecomesTheUfwRuleForItsPathAndOrigin(t *testing.T) { } } -func TestAnOpeningIsAddedOnceAndMarkedAsTheMeshs(t *testing.T) { +func testAnOpeningIsAddedOnceAndMarkedAsTheMeshs(t *testing.T) { f := &fakeUFW{installed: true, active: true, rules: []string{"allow 22/tcp"}} o := opening("adoption.opening-tcp-5671-incoming", 5671, "everywhere", "incoming", 0) @@ -318,7 +318,7 @@ func TestAnOpeningIsAddedOnceAndMarkedAsTheMeshs(t *testing.T) { } } -func TestAnOpeningLostToAReloadIsAddedAgain(t *testing.T) { +func testAnOpeningLostToAReloadIsAddedAgain(t *testing.T) { f := &fakeUFW{installed: true, active: true} o := opening("adoption.x", 5671, "everywhere", "incoming", 0) if _, err := Converge(context.Background(), f.run, o); err != nil { @@ -331,7 +331,7 @@ func TestAnOpeningLostToAReloadIsAddedAgain(t *testing.T) { } } -func TestAChangedOpeningReplacesOnlyItsOwnRule(t *testing.T) { +func testAChangedOpeningReplacesOnlyItsOwnRule(t *testing.T) { f := &fakeUFW{installed: true, active: true, rules: []string{"allow 22/tcp", "allow 8080/tcp comment 'someone else'"}} if _, err := Converge(context.Background(), f.run, opening("adoption.x", 5671, "everywhere", "incoming", 0)); err != nil { t.Fatal(err) @@ -346,7 +346,7 @@ func TestAChangedOpeningReplacesOnlyItsOwnRule(t *testing.T) { } } -func TestRemovingAnOpeningRemovesOnlyWhatWasMarkedForIt(t *testing.T) { +func testRemovingAnOpeningRemovesOnlyWhatWasMarkedForIt(t *testing.T) { f := &fakeUFW{installed: true, active: true, rules: []string{"allow 22/tcp", "allow 8080/tcp"}} for _, o := range []*declaration.Opening{ opening("adoption.a", 5671, "everywhere", "incoming", 0), @@ -366,7 +366,7 @@ func TestRemovingAnOpeningRemovesOnlyWhatWasMarkedForIt(t *testing.T) { } } -func TestEnableAndDisableReadBack(t *testing.T) { +func testEnableAndDisableReadBack(t *testing.T) { f := &fakeUFW{installed: true, active: true} if err := Disable(context.Background(), f.run, nil); err != nil || f.active { t.Fatalf("disable: %v", err) @@ -381,7 +381,7 @@ func TestEnableAndDisableReadBack(t *testing.T) { } } -func TestDetectingTheFoundFirewall(t *testing.T) { +func testDetectingTheFoundFirewall(t *testing.T) { for _, c := range []struct { name string f *fakeUFW @@ -411,7 +411,7 @@ func TestDetectingTheFoundFirewall(t *testing.T) { // ufw prints a rule back in its own shorter form, so the mark in the comment is the only thing the // host relies on. -func TestTheMarksAreReadFromWhatUfwReallyPrints(t *testing.T) { +func testTheMarksAreReadFromWhatUfwReallyPrints(t *testing.T) { raw, err := os.ReadFile("testdata/ufw-show-added.txt") if err != nil { t.Fatal(err) @@ -438,7 +438,7 @@ func TestTheMarksAreReadFromWhatUfwReallyPrints(t *testing.T) { } } -func TestEveryRealRuleIsDeletedInTheFormUfwAccepts(t *testing.T) { +func testEveryRealRuleIsDeletedInTheFormUfwAccepts(t *testing.T) { raw, err := os.ReadFile("testdata/ufw-show-added.txt") if err != nil { t.Fatal(err) @@ -470,7 +470,7 @@ func TestEveryRealRuleIsDeletedInTheFormUfwAccepts(t *testing.T) { } } -func TestARealUfwRulesetIsUfw(t *testing.T) { +func testARealUfwRulesetIsUfw(t *testing.T) { raw, err := os.ReadFile("testdata/ufw-active.nft") if err != nil { t.Fatal(err) @@ -490,7 +490,7 @@ func TestARealUfwRulesetIsUfw(t *testing.T) { } } -func TestRetiringUfwKeepsTheMachineFromRoutingForOthers(t *testing.T) { +func testRetiringUfwKeepsTheMachineFromRoutingForOthers(t *testing.T) { // Captured on a lab machine running the container runtime with a published port: ufw active, // then `ufw disable`. Disabling set the forward policy the runtime had set to drop to accept. before, err := os.ReadFile("testdata/ufw-disable-iptables-before.txt") @@ -521,7 +521,7 @@ func TestRetiringUfwKeepsTheMachineFromRoutingForOthers(t *testing.T) { } } -func TestRetiringUfwOnAMachineWithoutIptablesStillRetiresIt(t *testing.T) { +func testRetiringUfwOnAMachineWithoutIptablesStillRetiresIt(t *testing.T) { f := &fakeUFW{installed: true, active: true} if err := Disable(context.Background(), f.run, nil); err != nil || f.active { t.Fatalf("disable: %v, active %v", err, f.active) @@ -540,7 +540,7 @@ func captured(t *testing.T, name string) string { return string(raw) } -func TestFail2bansBansAreNotAFirewall(t *testing.T) { +func testFail2bansBansAreNotAFirewall(t *testing.T) { for _, name := range []string{"fail2ban-nftables.nft", "fail2ban-iptables.nft"} { ruleset := captured(t, name) if !strings.Contains(ruleset, "192.0.2.55") { @@ -559,7 +559,7 @@ func TestFail2bansBansAreNotAFirewall(t *testing.T) { } } -func TestARefusalOfEveryoneButSomeIsStillAFirewall(t *testing.T) { +func testARefusalOfEveryoneButSomeIsStillAFirewall(t *testing.T) { // A ban names the sources it refuses. A table that refuses every source but some, or every // port but some, closes what the mesh would open, whatever its policy says. for name, table := range map[string]string{ @@ -581,7 +581,7 @@ func TestARefusalOfEveryoneButSomeIsStillAFirewall(t *testing.T) { // Defends novox/hq ADR 0103: an opening a found rule already answers is not added, because ufw // takes two rules differing only in their comment for one (testdata/ufw-comment-only.txt). -func TestUfwTakesTheMeshsRuleAndTheOperatorsForOne(t *testing.T) { +func testUfwTakesTheMeshsRuleAndTheOperatorsForOne(t *testing.T) { // The capture: each mesh rule answered "Rule updated" beside the operator's equivalent. raw := captured(t, "ufw-comment-only.txt") if strings.Count(raw, "Rule updated\n") != 3 { @@ -606,7 +606,7 @@ func TestUfwTakesTheMeshsRuleAndTheOperatorsForOne(t *testing.T) { } } -func TestEveryCapturedRuleFormIsRead(t *testing.T) { +func testEveryCapturedRuleFormIsRead(t *testing.T) { want := map[string]string{ "allow 22/tcp": "tcp 22 in= from=any", "allow 9200": " 9200 in= from=any", "allow from 192.0.2.0/24 to any port 9300 proto tcp": "tcp 9300 in= from=192.0.2.0/24", @@ -643,7 +643,7 @@ func TestEveryCapturedRuleFormIsRead(t *testing.T) { } } -func TestAnOpeningAFoundRuleAnswersIsNotAddedAndItsRemovalLeavesTheRule(t *testing.T) { +func testAnOpeningAFoundRuleAnswersIsNotAddedAndItsRemovalLeavesTheRule(t *testing.T) { for _, c := range []struct { name, operators string o *declaration.Opening @@ -671,7 +671,7 @@ func TestAnOpeningAFoundRuleAnswersIsNotAddedAndItsRemovalLeavesTheRule(t *testi } } -func TestARuleThatDoesNotAnswerTheOpeningLeavesItToBeAdded(t *testing.T) { +func testARuleThatDoesNotAnswerTheOpeningLeavesItToBeAdded(t *testing.T) { for _, operators := range []string{ "allow from 192.0.2.0/24 to any port 5671 proto tcp", // narrower: from one range "allow in on eth0 to any port 5671 proto tcp", // narrower: one interface @@ -687,7 +687,7 @@ func TestARuleThatDoesNotAnswerTheOpeningLeavesItToBeAdded(t *testing.T) { } } -func TestAnOpeningWhoseFoundRuleIsGoneIsAddedAgain(t *testing.T) { +func testAnOpeningWhoseFoundRuleIsGoneIsAddedAgain(t *testing.T) { f := &fakeUFW{installed: true, active: true, rules: []string{"allow 5671/tcp"}} o := opening("adoption.bus", 5671, "everywhere", "incoming", 0) if done, err := Converge(context.Background(), f.run, o); err != nil || done.SatisfiedBy == "" { @@ -699,7 +699,7 @@ func TestAnOpeningWhoseFoundRuleIsGoneIsAddedAgain(t *testing.T) { } } -func TestARuleUfwWouldMergeThatDoesOtherThanAllowRefusesTheOpening(t *testing.T) { +func testARuleUfwWouldMergeThatDoesOtherThanAllowRefusesTheOpening(t *testing.T) { // ufw takes two rules differing only in action or log type for one, and adding the mesh's // would turn the operator's refusal into an allow (novox/hq ADR 0103). for _, operators := range []string{ @@ -721,7 +721,7 @@ func TestARuleUfwWouldMergeThatDoesOtherThanAllowRefusesTheOpening(t *testing.T) } } -func TestALogTypeIsReadInEitherPlace(t *testing.T) { +func testALogTypeIsReadInEitherPlace(t *testing.T) { for rule, want := range map[string]string{ "allow log 22/tcp": "allow log 22 tcp in=", "allow in log-all on mesh0 to any port 5432 proto tcp": "allow log-all 5432 tcp in=mesh0", @@ -735,7 +735,7 @@ func TestALogTypeIsReadInEitherPlace(t *testing.T) { } } -func TestAnOutgoingRuleNeverAnswersAnOpening(t *testing.T) { +func testAnOutgoingRuleNeverAnswersAnOpening(t *testing.T) { // `ufw allow out 5671/tcp` lets this machine reach others; nothing arrives through it, and // ufw keeps it as a rule of its own — captured in testdata/ufw-direction.txt. raw := captured(t, "ufw-direction.txt") @@ -756,7 +756,7 @@ func TestAnOutgoingRuleNeverAnswersAnOpening(t *testing.T) { } } -func TestIncomingIsUfwsDefaultDirection(t *testing.T) { +func testIncomingIsUfwsDefaultDirection(t *testing.T) { // Captured: `deny in 9006/tcp` and `allow 9006/tcp` are one rule to ufw, so the mesh must read // them as one too, or it would take an operator's refusal over. raw := captured(t, "ufw-direction.txt") @@ -769,7 +769,7 @@ func TestIncomingIsUfwsDefaultDirection(t *testing.T) { } } -func TestAMachineWithIptablesRulesAndNoNftIsNotReadAsUnfiltered(t *testing.T) { +func testAMachineWithIptablesRulesAndNoNftIsNotReadAsUnfiltered(t *testing.T) { // nft is not installed, and iptables-nft holds a firewall of somebody's. Read as "nothing // filters here" the mesh would adopt it, open nothing, and be unreachable (novox/hq ADR 0100). rules := "-P INPUT DROP\n-P FORWARD DROP\n-P OUTPUT ACCEPT\n-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT\n" @@ -787,3 +787,36 @@ func TestAMachineWithIptablesRulesAndNoNftIsNotReadAsUnfiltered(t *testing.T) { t.Errorf("a machine with only the runtime's rules read as %s: %v", kind, err) } } + +// TestFirewall runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFirewall(t *testing.T) { + t.Run("TheContainerRuntimesOwnRulesAreNotAFirewall", testTheContainerRuntimesOwnRulesAreNotAFirewall) + t.Run("TheMeshsOwnTablesAreNotAFirewall", testTheMeshsOwnTablesAreNotAFirewall) + t.Run("ATableThatDropsIsAFirewall", testATableThatDropsIsAFirewall) + t.Run("UfwsOwnChainsAreUfwsWhenItIsActive", testUfwsOwnChainsAreUfwsWhenItIsActive) + t.Run("LegacyIptablesThatRefusesIsAFirewall", testLegacyIptablesThatRefusesIsAFirewall) + t.Run("AnOpeningBecomesTheUfwRuleForItsPathAndOrigin", testAnOpeningBecomesTheUfwRuleForItsPathAndOrigin) + t.Run("AnOpeningIsAddedOnceAndMarkedAsTheMeshs", testAnOpeningIsAddedOnceAndMarkedAsTheMeshs) + t.Run("AnOpeningLostToAReloadIsAddedAgain", testAnOpeningLostToAReloadIsAddedAgain) + t.Run("AChangedOpeningReplacesOnlyItsOwnRule", testAChangedOpeningReplacesOnlyItsOwnRule) + t.Run("RemovingAnOpeningRemovesOnlyWhatWasMarkedForIt", testRemovingAnOpeningRemovesOnlyWhatWasMarkedForIt) + t.Run("EnableAndDisableReadBack", testEnableAndDisableReadBack) + t.Run("DetectingTheFoundFirewall", testDetectingTheFoundFirewall) + t.Run("TheMarksAreReadFromWhatUfwReallyPrints", testTheMarksAreReadFromWhatUfwReallyPrints) + t.Run("EveryRealRuleIsDeletedInTheFormUfwAccepts", testEveryRealRuleIsDeletedInTheFormUfwAccepts) + t.Run("ARealUfwRulesetIsUfw", testARealUfwRulesetIsUfw) + t.Run("RetiringUfwKeepsTheMachineFromRoutingForOthers", testRetiringUfwKeepsTheMachineFromRoutingForOthers) + t.Run("RetiringUfwOnAMachineWithoutIptablesStillRetiresIt", testRetiringUfwOnAMachineWithoutIptablesStillRetiresIt) + t.Run("Fail2bansBansAreNotAFirewall", testFail2bansBansAreNotAFirewall) + t.Run("ARefusalOfEveryoneButSomeIsStillAFirewall", testARefusalOfEveryoneButSomeIsStillAFirewall) + t.Run("UfwTakesTheMeshsRuleAndTheOperatorsForOne", testUfwTakesTheMeshsRuleAndTheOperatorsForOne) + t.Run("EveryCapturedRuleFormIsRead", testEveryCapturedRuleFormIsRead) + t.Run("AnOpeningAFoundRuleAnswersIsNotAddedAndItsRemovalLeavesTheRule", testAnOpeningAFoundRuleAnswersIsNotAddedAndItsRemovalLeavesTheRule) + t.Run("ARuleThatDoesNotAnswerTheOpeningLeavesItToBeAdded", testARuleThatDoesNotAnswerTheOpeningLeavesItToBeAdded) + t.Run("AnOpeningWhoseFoundRuleIsGoneIsAddedAgain", testAnOpeningWhoseFoundRuleIsGoneIsAddedAgain) + t.Run("ARuleUfwWouldMergeThatDoesOtherThanAllowRefusesTheOpening", testARuleUfwWouldMergeThatDoesOtherThanAllowRefusesTheOpening) + t.Run("ALogTypeIsReadInEitherPlace", testALogTypeIsReadInEitherPlace) + t.Run("AnOutgoingRuleNeverAnswersAnOpening", testAnOutgoingRuleNeverAnswersAnOpening) + t.Run("IncomingIsUfwsDefaultDirection", testIncomingIsUfwsDefaultDirection) + t.Run("AMachineWithIptablesRulesAndNoNftIsNotReadAsUnfiltered", testAMachineWithIptablesRulesAndNoNftIsNotReadAsUnfiltered) +} diff --git a/internal/firewall/neighbour_ban_test.go b/internal/firewall/neighbour_ban_test.go index 1e1a241e..2e517c35 100644 --- a/internal/firewall/neighbour_ban_test.go +++ b/internal/firewall/neighbour_ban_test.go @@ -11,7 +11,7 @@ import ( // chain is jumped to from INPUT, whose policy accepts, and from the container runtime's user chain, // which hangs off a FORWARD the runtime set to DROP. Requiring every path to come from an accepting // built-in made the machine report "NOT the mesh alone" about a chain the mesh had just written. -func TestTheMeshsOwnBanChainIsABanBehindADroppingForward(t *testing.T) { +func testTheMeshsOwnBanChainIsABanBehindADroppingForward(t *testing.T) { legacy, err := os.ReadFile("testdata/home-server-bans-S.txt") if err != nil { t.Fatal(err) @@ -46,7 +46,7 @@ func TestTheMeshsOwnBanChainIsABanBehindADroppingForward(t *testing.T) { // A chain that accepts anything is doing more than banning, and is still not a ban — which is what // keeps a predecessor's allow-and-drop chain classified as something the operator must look at. -func TestAChainThatAcceptsIsNotABan(t *testing.T) { +func testAChainThatAcceptsIsNotABan(t *testing.T) { rules := "-P INPUT ACCEPT\n" + "-A INPUT -j HAL-MESH-ONLY\n" + "-N HAL-MESH-ONLY\n" + @@ -58,3 +58,9 @@ func TestAChainThatAcceptsIsNotABan(t *testing.T) { } } } + +// TestNeighbourBan runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestNeighbourBan(t *testing.T) { + t.Run("TheMeshsOwnBanChainIsABanBehindADroppingForward", testTheMeshsOwnBanChainIsABanBehindADroppingForward) + t.Run("AChainThatAcceptsIsNotABan", testAChainThatAcceptsIsNotABan) +} diff --git a/internal/identity/identity_test.go b/internal/identity/identity_test.go index 8a1e4b6b..70d2be58 100644 --- a/internal/identity/identity_test.go +++ b/internal/identity/identity_test.go @@ -11,7 +11,7 @@ import ( "testing" ) -func TestAMachineThatHasNotJoinedHasNoIdentityAndThatIsNotAFault(t *testing.T) { +func testAMachineThatHasNotJoinedHasNoIdentityAndThatIsNotAFault(t *testing.T) { // A hosted machine has a host running and no identity. That is a real state, and confusing // it with a fault would have every fresh install look broken. _, err := Load(Path(filepath.Join(t.TempDir(), "state.json"))) @@ -20,7 +20,7 @@ func TestAMachineThatHasNotJoinedHasNoIdentityAndThatIsNotAFault(t *testing.T) { } } -func TestAnUnreadableIdentityIsNotTheSameAsHavingNone(t *testing.T) { +func testAnUnreadableIdentityIsNotTheSameAsHavingNone(t *testing.T) { // The distinction that matters most here. "None" leads to enrolling; if an unreadable // identity took that path, a node would discard the identity the mesh still believes and // need a person with a new token to get back. @@ -61,7 +61,7 @@ func joined(t *testing.T, name string) Identity { return made } -func TestSaveRefusesWhatLoadWouldRefuse(t *testing.T) { +func testSaveRefusesWhatLoadWouldRefuse(t *testing.T) { // The two must agree, or a caller can write a file that cannot be read back — and it would // be read back on the next start, on a machine nobody is watching, by which time the token // that could have fixed it is spent. @@ -78,7 +78,7 @@ func TestSaveRefusesWhatLoadWouldRefuse(t *testing.T) { } } -func TestWhatIsSavedIsWhatIsLoaded(t *testing.T) { +func testWhatIsSavedIsWhatIsLoaded(t *testing.T) { path := Path(filepath.Join(t.TempDir(), "state.json")) made := joined(t, "workstation") if err := Save(path, made); err != nil { @@ -101,7 +101,7 @@ func TestWhatIsSavedIsWhatIsLoaded(t *testing.T) { } } -func TestTheIdentityIsNotReadableByAnybodyElse(t *testing.T) { +func testTheIdentityIsNotReadableByAnybodyElse(t *testing.T) { // It is the only secret on the machine that identifies it. A mode that let another user on // this machine read it would make "compromise of a node is compromise of that node" false in // the other direction — any local user could become the node. @@ -120,7 +120,7 @@ func TestTheIdentityIsNotReadableByAnybodyElse(t *testing.T) { } } -func TestSavingLeavesNoHalfWrittenIdentity(t *testing.T) { +func testSavingLeavesNoHalfWrittenIdentity(t *testing.T) { // Written and renamed, so power lost mid-write keeps the old identity rather than producing // half of one. A node cannot regenerate its way out of a broken identity — the mesh believes // the old public key, and a new one needs a person with a new token. @@ -144,7 +144,7 @@ func TestSavingLeavesNoHalfWrittenIdentity(t *testing.T) { } } -func TestAnIdentityOfTheWrongShapeIsRefused(t *testing.T) { +func testAnIdentityOfTheWrongShapeIsRefused(t *testing.T) { // The one that would load happily and fail at the moment it signs, which is during enrolment // against a mesh, far from here. path := Path(filepath.Join(t.TempDir(), "state.json")) @@ -160,7 +160,7 @@ func TestAnIdentityOfTheWrongShapeIsRefused(t *testing.T) { } } -func TestSigningProvesTheNodeIsThatNode(t *testing.T) { +func testSigningProvesTheNodeIsThatNode(t *testing.T) { made, err := Generate("workstation") if err != nil { t.Fatal(err) @@ -195,7 +195,7 @@ func completeToken(t *testing.T) string { return base64.RawURLEncoding.EncodeToString(raw) } -func TestTheWireFormatIsExactlyTheseFieldNames(t *testing.T) { +func testTheWireFormatIsExactlyTheseFieldNames(t *testing.T) { // The contract with the control plane, which defines this format separately because the host // requires nothing present and does not import it (novox/hq ADR 0005). There is a matching // test on the other side. Rename a field on either and both fail, which is the point — the @@ -237,7 +237,7 @@ func TestTheWireFormatIsExactlyTheseFieldNames(t *testing.T) { // A complete token parses, a pasted one tolerates whitespace, and one of another version is refused (three tests merged; the // token's shape is mesh-sdk's since ADR 0587 §3). -func TestACompleteTokenParsesAPastedOneToleratesWhitespaceAndAnotherVersionIsRefused(t *testing.T) { +func testACompleteTokenParsesAPastedOneToleratesWhitespaceAndAnotherVersionIsRefused(t *testing.T) { got, err := ParseToken(completeToken(t)) if err != nil { t.Fatal(err) @@ -253,7 +253,7 @@ func TestACompleteTokenParsesAPastedOneToleratesWhitespaceAndAnotherVersionIsRef } } -func TestAnIncompleteTokenIsRefusedWholeAndSaysWhatIsMissing(t *testing.T) { +func testAnIncompleteTokenIsRefusedWholeAndSaysWhatIsMissing(t *testing.T) { // Not a reduced capability — an unsafe one. Without the fingerprint this node would connect // to whatever answers; without the signing key it could not tell a declaration from a // forgery, and it applies whatever the link delivers. @@ -274,7 +274,7 @@ func TestAnIncompleteTokenIsRefusedWholeAndSaysWhatIsMissing(t *testing.T) { } } -func TestGarbageIsRefused(t *testing.T) { +func testGarbageIsRefused(t *testing.T) { for _, bad := range []string{"", "!!!not base64!!!", "aGVsbG8"} { if _, err := ParseToken(bad); err == nil { t.Errorf("%q parsed as a token", bad) @@ -291,7 +291,7 @@ func base64Key(t *testing.T) string { return base64.StdEncoding.EncodeToString(public) } -func TestAnIdentityThatCannotBeReadIsNotReportedAsAbsent(t *testing.T) { +func testAnIdentityThatCannotBeReadIsNotReportedAsAbsent(t *testing.T) { // The other half of the distinction above, and the one that was untested: a file that exists // and cannot be read. The corrupt case is caught when it fails to parse; this one never gets // that far, so it needs its own check — and without it a permissions accident would look @@ -321,7 +321,7 @@ func TestAnIdentityThatCannotBeReadIsNotReportedAsAbsent(t *testing.T) { } } -func TestASealingKeyOpensOnlyWhatWasSealedToIt(t *testing.T) { +func testASealingKeyOpensOnlyWhatWasSealedToIt(t *testing.T) { mine, err := GenerateSealingKey() if err != nil { t.Fatal(err) @@ -347,7 +347,7 @@ func TestASealingKeyOpensOnlyWhatWasSealedToIt(t *testing.T) { } // Sealing is randomised and a node with no sealing key is told what to do (two tests merged). -func TestSealingIsRandomisedAndANodeWithNoSealingKeySaysWhatToDo(t *testing.T) { +func testSealingIsRandomisedAndANodeWithNoSealingKeySaysWhatToDo(t *testing.T) { // Sealed boxes are randomised, so an observer cannot tell that two nodes were given the same // password, nor that a rotation changed nothing. Worth asserting because the alternative is // a subtle leak nobody would look for. @@ -368,7 +368,7 @@ func TestSealingIsRandomisedAndANodeWithNoSealingKeySaysWhatToDo(t *testing.T) { } } -func TestASealingKeyOnDiskSurvivesATrailingNewline(t *testing.T) { +func testASealingKeyOnDiskSurvivesATrailingNewline(t *testing.T) { // It is written with one, the way every other key file here is, and reading it back has to // cope — otherwise the key works until the first restart. key, _ := GenerateSealingKey() @@ -385,7 +385,7 @@ func TestASealingKeyOnDiskSurvivesATrailingNewline(t *testing.T) { } } -func TestATokenSaysWhatTheMeshCallsThisMachine(t *testing.T) { +func testATokenSaysWhatTheMeshCallsThisMachine(t *testing.T) { // The node cannot work its own name out. The broker account it authenticates as is named // after it and exists before this machine has been told anything — so without the name in the // token, enrolment is a connection refused with an empty username, which names nothing about @@ -406,7 +406,7 @@ func TestATokenSaysWhatTheMeshCallsThisMachine(t *testing.T) { // A token through the tunnel carries the one peer, in the field names the controller writes // (novox/hq ADR 0169), and an incomplete tunnel is refused naming what is missing. -func TestATokenThroughTheTunnelParsesAndAPartOneIsRefused(t *testing.T) { +func testATokenThroughTheTunnelParsesAndAPartOneIsRefused(t *testing.T) { whole := map[string]any{"v": 1, "node": "n", "broker": "10.42.0.1:4222", "fingerprint": "sha256:x", "signer": make([]byte, 32), "secret": "s", "tunnel": map[string]any{"key": "k", "address": "10.42.0.9/32", "range": "10.42.0.0/16", @@ -426,3 +426,25 @@ func TestATokenThroughTheTunnelParsesAndAPartOneIsRefused(t *testing.T) { t.Fatalf("a token with half a tunnel was taken: %v", err) } } + +// TestIdentity runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestIdentity(t *testing.T) { + t.Run("AMachineThatHasNotJoinedHasNoIdentityAndThatIsNotAFault", testAMachineThatHasNotJoinedHasNoIdentityAndThatIsNotAFault) + t.Run("AnUnreadableIdentityIsNotTheSameAsHavingNone", testAnUnreadableIdentityIsNotTheSameAsHavingNone) + t.Run("SaveRefusesWhatLoadWouldRefuse", testSaveRefusesWhatLoadWouldRefuse) + t.Run("WhatIsSavedIsWhatIsLoaded", testWhatIsSavedIsWhatIsLoaded) + t.Run("TheIdentityIsNotReadableByAnybodyElse", testTheIdentityIsNotReadableByAnybodyElse) + t.Run("SavingLeavesNoHalfWrittenIdentity", testSavingLeavesNoHalfWrittenIdentity) + t.Run("AnIdentityOfTheWrongShapeIsRefused", testAnIdentityOfTheWrongShapeIsRefused) + t.Run("SigningProvesTheNodeIsThatNode", testSigningProvesTheNodeIsThatNode) + t.Run("TheWireFormatIsExactlyTheseFieldNames", testTheWireFormatIsExactlyTheseFieldNames) + t.Run("ACompleteTokenParsesAPastedOneToleratesWhitespaceAndAnotherVersionIsRefused", testACompleteTokenParsesAPastedOneToleratesWhitespaceAndAnotherVersionIsRefused) + t.Run("AnIncompleteTokenIsRefusedWholeAndSaysWhatIsMissing", testAnIncompleteTokenIsRefusedWholeAndSaysWhatIsMissing) + t.Run("GarbageIsRefused", testGarbageIsRefused) + t.Run("AnIdentityThatCannotBeReadIsNotReportedAsAbsent", testAnIdentityThatCannotBeReadIsNotReportedAsAbsent) + t.Run("ASealingKeyOpensOnlyWhatWasSealedToIt", testASealingKeyOpensOnlyWhatWasSealedToIt) + t.Run("SealingIsRandomisedAndANodeWithNoSealingKeySaysWhatToDo", testSealingIsRandomisedAndANodeWithNoSealingKeySaysWhatToDo) + t.Run("ASealingKeyOnDiskSurvivesATrailingNewline", testASealingKeyOnDiskSurvivesATrailingNewline) + t.Run("ATokenSaysWhatTheMeshCallsThisMachine", testATokenSaysWhatTheMeshCallsThisMachine) + t.Run("ATokenThroughTheTunnelParsesAndAPartOneIsRefused", testATokenThroughTheTunnelParsesAndAPartOneIsRefused) +} diff --git a/internal/identity/serving_test.go b/internal/identity/serving_test.go index 15b5bf04..e3f58699 100644 --- a/internal/identity/serving_test.go +++ b/internal/identity/serving_test.go @@ -15,7 +15,7 @@ import ( // A key in this host's own encoding is intact, unusable, and indistinguishable from a working one // until the moment a client connects — the mesh delivers the certificate, the file is there with // the right permissions, and the server will not start. -func TestTheServingKeyIsWrittenInTheFormatAServerReads(t *testing.T) { +func testTheServingKeyIsWrittenInTheFormatAServerReads(t *testing.T) { made, err := GenerateServingKey() if err != nil { t.Fatal(err) @@ -52,7 +52,7 @@ func TestTheServingKeyIsWrittenInTheFormatAServerReads(t *testing.T) { // The old encoding is refused by name, because the remedy is different from a corrupt file and // the difference is invisible from the outside. -func TestAServingKeyInTheOldEncodingIsNamedRatherThanCalledCorrupt(t *testing.T) { +func testAServingKeyInTheOldEncodingIsNamedRatherThanCalledCorrupt(t *testing.T) { made, err := GenerateServingKey() if err != nil { t.Fatal(err) @@ -69,3 +69,9 @@ func TestAServingKeyInTheOldEncodingIsNamedRatherThanCalledCorrupt(t *testing.T) t.Fatalf("refused without naming the remedy: %v", err) } } + +// TestServing runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestServing(t *testing.T) { + t.Run("TheServingKeyIsWrittenInTheFormatAServerReads", testTheServingKeyIsWrittenInTheFormatAServerReads) + t.Run("AServingKeyInTheOldEncodingIsNamedRatherThanCalledCorrupt", testAServingKeyInTheOldEncodingIsNamedRatherThanCalledCorrupt) +} diff --git a/internal/image/image_test.go b/internal/image/image_test.go index ef4d0ddc..0ccf7c6c 100644 --- a/internal/image/image_test.go +++ b/internal/image/image_test.go @@ -50,7 +50,7 @@ func manifest(t *testing.T, config string, tags ...string) string { // // It is still read and still checked, because it is what says which build somebody embedded — and // because printing it beside the runtime's answer is how a person sees that the two differ. -func TestTheArchivesOwnIdIsReadFromTheSavedFile(t *testing.T) { +func testTheArchivesOwnIdIsReadFromTheSavedFile(t *testing.T) { digest := strings.Repeat("a", 64) // Both layouts `docker save` has used. The older one names the config `.json`; the OCI // one names it `blobs/sha256/`. They carry the same sixty-four characters, and a @@ -70,7 +70,7 @@ func TestTheArchivesOwnIdIsReadFromTheSavedFile(t *testing.T) { // The tag is read, and it is not decoration: it is the name the installer asks a runtime by, // because it is the one thing that survives `docker save` and `docker load` unchanged. The id // does not. -func TestTheSavedTagsAreRead(t *testing.T) { +func testTheSavedTagsAreRead(t *testing.T) { saved := savedImage(t, map[string]string{ "manifest.json": manifest(t, strings.Repeat("b", 64)+".json", "mesh-controller:v1"), }) @@ -85,7 +85,7 @@ func TestTheSavedTagsAreRead(t *testing.T) { // Nothing here reaches a bundle any more, but this is still the earliest moment somebody can be // told they embedded the wrong file — and the alternative is finding out at the load, from a // container runtime, in a sentence about a tar rather than about what was built. -func TestSomethingThatIsNotASavedImageIsRefused(t *testing.T) { +func testSomethingThatIsNotASavedImageIsRefused(t *testing.T) { notAnImage := savedImage(t, map[string]string{"hello": "world"}) if _, err := ArchiveID(notAnImage); err == nil { t.Error("a tar with no manifest.json was accepted as a saved image") @@ -100,7 +100,7 @@ func TestSomethingThatIsNotASavedImageIsRefused(t *testing.T) { // Exactly one image. A bootstrap that chose between several would be the thing that guesses which // one is the control plane, and it would guess right until the day somebody saved two. -func TestATarHoldingSeveralImagesIsRefused(t *testing.T) { +func testATarHoldingSeveralImagesIsRefused(t *testing.T) { entries, err := json.Marshal([]manifestEntry{ {Config: strings.Repeat("a", 64) + ".json"}, {Config: strings.Repeat("b", 64) + ".json"}, @@ -117,7 +117,7 @@ func TestATarHoldingSeveralImagesIsRefused(t *testing.T) { // An id is a digest or it is nothing. A truncated one names several images, and which one ran // would be whichever the runtime matched first — the same reasoning `internal/declaration` gives // for refusing a short image reference. -func TestAConfigThatIsNotADigestIsRefused(t *testing.T) { +func testAConfigThatIsNotADigestIsRefused(t *testing.T) { for _, config := range []string{"config.json", "abc.json", "blobs/sha256/" + strings.Repeat("a", 63)} { saved := savedImage(t, map[string]string{"manifest.json": manifest(t, config)}) if _, err := ArchiveID(saved); err == nil { @@ -129,7 +129,7 @@ func TestAConfigThatIsNotADigestIsRefused(t *testing.T) { // The committed placeholder must read as "carries nothing", so an installer built from a plain // checkout says so in preflight rather than getting a machine as far as a running store and // stopping. This is the same guarantee `internal/bundle` makes about a lock file of only comments. -func TestAnInstallerBuiltFromAPlainCheckoutCarriesNothing(t *testing.T) { +func testAnInstallerBuiltFromAPlainCheckoutCarriesNothing(t *testing.T) { if !IsEmpty() { // Not a failure of this checkout: `make bootstrap` embeds a real image and puts the // placeholder back, so a real image here means a build was interrupted. @@ -142,7 +142,7 @@ func TestAnInstallerBuiltFromAPlainCheckoutCarriesNothing(t *testing.T) { // And "empty" is decided by whether the bytes could be loaded, not by matching the placeholder's // text. A truncated or corrupted embed is equally unloadable and equally worth refusing early. -func TestEmptyMeansUnloadableRatherThanEqualToThePlaceholder(t *testing.T) { +func testEmptyMeansUnloadableRatherThanEqualToThePlaceholder(t *testing.T) { restore := saved defer func() { saved = restore }() @@ -158,3 +158,14 @@ func TestEmptyMeansUnloadableRatherThanEqualToThePlaceholder(t *testing.T) { t.Error("a real saved image was reported as no image at all") } } + +// TestImage runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestImage(t *testing.T) { + t.Run("TheArchivesOwnIdIsReadFromTheSavedFile", testTheArchivesOwnIdIsReadFromTheSavedFile) + t.Run("TheSavedTagsAreRead", testTheSavedTagsAreRead) + t.Run("SomethingThatIsNotASavedImageIsRefused", testSomethingThatIsNotASavedImageIsRefused) + t.Run("ATarHoldingSeveralImagesIsRefused", testATarHoldingSeveralImagesIsRefused) + t.Run("AConfigThatIsNotADigestIsRefused", testAConfigThatIsNotADigestIsRefused) + t.Run("AnInstallerBuiltFromAPlainCheckoutCarriesNothing", testAnInstallerBuiltFromAPlainCheckoutCarriesNothing) + t.Run("EmptyMeansUnloadableRatherThanEqualToThePlaceholder", testEmptyMeansUnloadableRatherThanEqualToThePlaceholder) +} diff --git a/internal/inventory/inventory_test.go b/internal/inventory/inventory_test.go index 60bc2b12..f511dc2e 100644 --- a/internal/inventory/inventory_test.go +++ b/internal/inventory/inventory_test.go @@ -11,7 +11,7 @@ import ( "github.com/novox/mesh-host/internal/profile" ) -func TestAnUnreadableFactIsRecordedNotFatal(t *testing.T) { +func testAnUnreadableFactIsRecordedNotFatal(t *testing.T) { // An inventory missing one field is useful; an inventory that refused to be taken is not. // And an absent fact and a fact that failed to read are different things — collapsing them // loses the one worth acting on. @@ -34,7 +34,7 @@ func TestAnUnreadableFactIsRecordedNotFatal(t *testing.T) { } } -func TestDistributionIsReadFromTheMachineNotAssumed(t *testing.T) { +func testDistributionIsReadFromTheMachineNotAssumed(t *testing.T) { cases := map[string]string{ "PRETTY_NAME=\"Arch Linux\"\nID=arch\n": "Arch Linux", "ID=arch\n": "arch", @@ -49,7 +49,7 @@ func TestDistributionIsReadFromTheMachineNotAssumed(t *testing.T) { } } -func TestMemoryIsReadOrReportedMissing(t *testing.T) { +func testMemoryIsReadOrReportedMissing(t *testing.T) { if kb, ok := memoryFrom("MemTotal: 32762868 kB\nMemFree: 1 kB\n"); !ok || kb != 32762868 { t.Errorf("memoryFrom returned %d, %v", kb, ok) } @@ -63,7 +63,7 @@ func TestMemoryIsReadOrReportedMissing(t *testing.T) { } } -func TestTheInventorySaysWhenItWasTaken(t *testing.T) { +func testTheInventorySaysWhenItWasTaken(t *testing.T) { // A node unreachable for a week is an ordinary situation (novox/hq ADR 0004), so an // inventory that cannot be told from a stale one is missing the fact that matters. before := time.Now().UTC() @@ -77,7 +77,7 @@ func TestTheInventorySaysWhenItWasTaken(t *testing.T) { } } -func TestTheHostDoesNotNameTheNode(t *testing.T) { +func testTheHostDoesNotNameTheNode(t *testing.T) { // A node's name is assigned by the mesh. A host that named itself would be deciding // something, which is precisely what novox/hq ADR 0005 forbids it to do. inv := Collect(context.Background(), nil, nil, time.Second) @@ -90,7 +90,7 @@ func TestTheHostDoesNotNameTheNode(t *testing.T) { // --- against this machine --------------------------------------------------------------- -func TestAgainstThisMachine_inventoryIsTrue(t *testing.T) { +func testAgainstThisMachine_inventoryIsTrue(t *testing.T) { // novox/hq ADR 0017: behaviour against a real system is tested alongside, not mocked. inv := Collect(context.Background(), nil, profile.Default(nil), 10*time.Second) @@ -116,3 +116,13 @@ func TestAgainstThisMachine_inventoryIsTrue(t *testing.T) { inv.Machine, inv.Distribution, inv.Kernel, inv.Architecture, inv.CPUs, inv.MemoryKB/1024, inv.Unreadable) } + +// TestInventory runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestInventory(t *testing.T) { + t.Run("AnUnreadableFactIsRecordedNotFatal", testAnUnreadableFactIsRecordedNotFatal) + t.Run("DistributionIsReadFromTheMachineNotAssumed", testDistributionIsReadFromTheMachineNotAssumed) + t.Run("MemoryIsReadOrReportedMissing", testMemoryIsReadOrReportedMissing) + t.Run("TheInventorySaysWhenItWasTaken", testTheInventorySaysWhenItWasTaken) + t.Run("TheHostDoesNotNameTheNode", testTheHostDoesNotNameTheNode) + t.Run("AgainstThisMachine_inventoryIsTrue", testAgainstThisMachine_inventoryIsTrue) +} diff --git a/internal/link/access_act_test.go b/internal/link/access_act_test.go index 32baa52c..d734678a 100644 --- a/internal/link/access_act_test.go +++ b/internal/link/access_act_test.go @@ -14,7 +14,7 @@ import ( // The take act's ask (novox/hq ADR 0325 §8): a hand-over's fields and the act's own in one signed object, under a // signing context of its own. The controller's side holds the same names and words. -func TestTheTakeActsAskKeepsItsFieldNamesAndContext(t *testing.T) { +func testTheTakeActsAskKeepsItsFieldNamesAndContext(t *testing.T) { body, _ := json.Marshal(AccessActAsk{Act: ActTake, Access: "radarr.movies", Warrant: "w"}) if got := keysOf(t, body); got != "access act warrant" { t.Fatalf("the act's fields are %q", got) @@ -40,7 +40,7 @@ func signedAct(t *testing.T, key ed25519.PrivateKey, ask HandOverAsk, act Access } // **Nothing is done without a warrant**, nor for any act but take, nor signed as a hand-over (ADR 0325 §8). -func TestTheTakeActRunsOnlyOnAWarrant(t *testing.T) { +func testTheTakeActRunsOnlyOnAWarrant(t *testing.T) { m, key := aMember(t) now := time.Now() var given []AccessAct @@ -182,7 +182,7 @@ func anEngine(t *testing.T) (*HandActs, *[]oc.Ask, *int) { // The controller names an access by its declared resource id exactly, which may hold a `/`: it reaches the act, // which matches it against what was declared. -func TestATakeActNamesItsAccessByItsDeclaredId(t *testing.T) { +func testATakeActNamesItsAccessByItsDeclaredId(t *testing.T) { m, key := aMember(t) var given []AccessAct handle := func(a AccessAct) (string, error) { given = append(given, a); return "started", nil } @@ -195,3 +195,10 @@ func TestATakeActNamesItsAccessByItsDeclaredId(t *testing.T) { t.Fatalf("an access id with a slash did not reach the act as declared: %+v %+v", a, given) } } + +// TestAccessAct runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestAccessAct(t *testing.T) { + t.Run("TheTakeActsAskKeepsItsFieldNamesAndContext", testTheTakeActsAskKeepsItsFieldNamesAndContext) + t.Run("TheTakeActRunsOnlyOnAWarrant", testTheTakeActRunsOnlyOnAWarrant) + t.Run("ATakeActNamesItsAccessByItsDeclaredId", testATakeActNamesItsAccessByItsDeclaredId) +} diff --git a/internal/link/handover_test.go b/internal/link/handover_test.go index 1ca0b771..44ad7c75 100644 --- a/internal/link/handover_test.go +++ b/internal/link/handover_test.go @@ -19,7 +19,7 @@ import ( // The hand-over's ask and answer hold these field names; the controller's side holds the same list // (mesh-controller internal/link, TestTheHandOverAskAndAnswerKeepTheirFieldNames). -func TestTheHandOverAskAndAnswerKeepTheirFieldNames(t *testing.T) { +func testTheHandOverAskAndAnswerKeepTheirFieldNames(t *testing.T) { body, _ := json.Marshal(HandOverAsk{Node: "laptop", Path: "/srv/notes", By: "jo", Expires: time.Now(), Nonce: "n"}) if got := keysOf(t, body); got != "by expires node nonce path" { t.Fatalf("the ask's fields are %q", got) @@ -79,7 +79,7 @@ func anAsk(now time.Time) HandOverAsk { // **An ask is believed only signed by the mesh, for this node, unexpired, once** (review of issue 356): a // responder can reach the subject through a reply, so the subject proves nothing. Each refusal below hands // the handler nothing; the good ask reaches it with its path and who asked, and the same ask again is refused. -func TestAHandOverAskIsBelievedOnlySignedForThisNodeUnexpiredAndOnce(t *testing.T) { +func testAHandOverAskIsBelievedOnlySignedForThisNodeUnexpiredAndOnce(t *testing.T) { m, key := aMember(t) _, stranger, _ := ed25519.GenerateKey(nil) now := time.Date(2026, 10, 9, 18, 0, 0, 0, time.UTC) @@ -170,7 +170,7 @@ func TestAHandOverAskIsBelievedOnlySignedForThisNodeUnexpiredAndOnce(t *testing. // **A request with no reply is nobody's question**: nothing is judged, recorded or said. One with a reply is // answered with the judgement. -func TestAHandOverIsAnsweredOnlyWhenItCarriesAReply(t *testing.T) { +func testAHandOverIsAnsweredOnlyWhenItCarriesAReply(t *testing.T) { m, key := aMember(t) now := time.Now() called := 0 @@ -213,7 +213,7 @@ func (l handingLink) HearHandOvers(h HandOverFunc) { l.given <- h } // **The link is given the queue's hand-over** when it is served: what the controller asks reaches the engine's // judgement, and nothing else. -func TestALinkThatHearsHandOversIsGivenTheQueues(t *testing.T) { +func testALinkThatHearsHandOversIsGivenTheQueues(t *testing.T) { m, _ := aMember(t) l := handingLink{quietLink: newQuietLink(), given: make(chan HandOverFunc, 1)} q := &Session{Membership: m, Timeout: time.Second} @@ -414,16 +414,16 @@ func (r fakeRequest) RespondJSON(any, ...micro.RespondOpt) error { return nil } func (r fakeRequest) Error(string, string, []byte, ...micro.RespondOpt) error { return nil } -func (r fakeRequest) Data() []byte { return []byte(`{}`) } +func (r fakeRequest) Data() []byte { return []byte(`{}`) } func (r fakeRequest) Headers() micro.Headers { return micro.Headers{stdio.AskHeader: []string{r.ask}} } -func (r fakeRequest) Subject() string { return r.subject } -func (r fakeRequest) Reply() string { return "_INBOX.x" } +func (r fakeRequest) Subject() string { return r.subject } +func (r fakeRequest) Reply() string { return "_INBOX.x" } // **Against a real server**: a signed request on the node's own subject is answered; one on another node's is // not heard; a message with no reply is answered by nobody. -func TestNatsAHandOverIsAskedOfTheNode(t *testing.T) { +func testNatsAHandOverIsAskedOfTheNode(t *testing.T) { conn, js := aBus(t) m, key := aMember(t) l := &natsLink{conn: conn, js: js, node: m.Node, signer: m.Signer} @@ -550,3 +550,12 @@ func TestNatsAHandOverIsAskedOfTheNode(t *testing.T) { } }) } + +// TestHandover runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestHandover(t *testing.T) { + t.Run("TheHandOverAskAndAnswerKeepTheirFieldNames", testTheHandOverAskAndAnswerKeepTheirFieldNames) + t.Run("AHandOverAskIsBelievedOnlySignedForThisNodeUnexpiredAndOnce", testAHandOverAskIsBelievedOnlySignedForThisNodeUnexpiredAndOnce) + t.Run("AHandOverIsAnsweredOnlyWhenItCarriesAReply", testAHandOverIsAnsweredOnlyWhenItCarriesAReply) + t.Run("ALinkThatHearsHandOversIsGivenTheQueues", testALinkThatHearsHandOversIsGivenTheQueues) + t.Run("NatsAHandOverIsAskedOfTheNode", testNatsAHandOverIsAskedOfTheNode) +} diff --git a/internal/link/have_test.go b/internal/link/have_test.go index 94231488..74507602 100644 --- a/internal/link/have_test.go +++ b/internal/link/have_test.go @@ -233,7 +233,7 @@ func aHaveQueue(l *haveLink) (*Session, *[]string) { // 1132/AC3, AC5: a module that applied is running with its build and a module that failed is failed with the detail; // the key does not exist yet, so it is created. -func TestAnAppliedModuleIsWrittenRunningAndAFailedOneFailed(t *testing.T) { +func testAnAppliedModuleIsWrittenRunningAndAFailedOneFailed(t *testing.T) { l := newHaveLink() q, _ := aHaveQueue(l) // Design 47 G A-197: each have as written is told to the node-engine's findings of itself, the failed one with its detail. @@ -258,7 +258,7 @@ func TestAnAppliedModuleIsWrittenRunningAndAFailedOneFailed(t *testing.T) { // 1132/AC5: a have equal to the bucket's value is not written; a different one is written over the last revision. Each // is written at the seat's form (H-A-388). -func TestAHaveIsWrittenOnlyWhenItDiffers(t *testing.T) { +func testAHaveIsWrittenOnlyWhenItDiffers(t *testing.T) { l := newHaveLink() l.put(t, "n1.a", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Form: nodeengine.Form, Build: "b-1", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) l.put(t, "n1.b", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Form: nodeengine.Form, Build: "b-0", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) @@ -278,7 +278,7 @@ func TestAHaveIsWrittenOnlyWhenItDiffers(t *testing.T) { } // 1132/AC4: a look's health reaches the module's have: ok, failed, waits or unknown, and only a change is written. -func TestAModulesHealthFollowsTheLook(t *testing.T) { +func testAModulesHealthFollowsTheLook(t *testing.T) { l := newHaveLink() q, _ := aHaveQueue(l) rep := Report{Modules: []ModuleFact{{Module: "a", Build: "b"}, {Module: "b", Build: "b"}, @@ -325,7 +325,7 @@ func TestAModulesHealthFollowsTheLook(t *testing.T) { } // 1132/AC6: the node's key holds its windows, busy, strays, filters and profile. -func TestTheNodeKeyCarriesTheNodesFacts(t *testing.T) { +func testTheNodeKeyCarriesTheNodesFacts(t *testing.T) { l := newHaveLink() q, journal := aHaveQueue(l) rep := appliedModules() @@ -527,7 +527,7 @@ func TestTheNodeKeyCarriesTheNodesFacts(t *testing.T) { } // 1132/AC7: a write the bucket refuses is said in the log, and the next apply writes again. -func TestAFailedHaveWriteIsSaidAndWrittenAgain(t *testing.T) { +func testAFailedHaveWriteIsSaidAndWrittenAgain(t *testing.T) { l := newHaveLink() l.failing = true q, said := aHaveQueue(l) @@ -547,7 +547,7 @@ func TestAFailedHaveWriteIsSaidAndWrittenAgain(t *testing.T) { } // A link without a bucket, and a report with no module facts (a refusal), write nothing and say nothing wrong. -func TestNoBucketAndNoFactsWriteNothing(t *testing.T) { +func testNoBucketAndNoFactsWriteNothing(t *testing.T) { plain := newQuietLink() q := &Session{Membership: Membership{Node: "n1"}, Timeout: time.Second} q.Attach(context.Background(), plain) @@ -564,7 +564,7 @@ func TestNoBucketAndNoFactsWriteNothing(t *testing.T) { // 1132/AC7: a bind that fails, or never answers, writes nothing and returns within the queue's timeout; a write that // fails ends the pass, and is said once. -func TestAFailedBindOrWriteEndsThePassAndReturnsInTime(t *testing.T) { +func testAFailedBindOrWriteEndsThePassAndReturnsInTime(t *testing.T) { for name, set := range map[string]func(*haveLink){ "a bind refused": func(l *haveLink) { l.bindFails = true }, "a bind that never answers": func(l *haveLink) { l.bindStuck = true }, @@ -618,7 +618,7 @@ func onlyA() Report { // 1369/AC1: after a declaration with a and b, one with a only writes n1.b with the phase removed, over the revision // read, and leaves a as it was; the key is not deleted. -func TestAModuleLeavingTheDeclarationIsWrittenRemoved(t *testing.T) { +func testAModuleLeavingTheDeclarationIsWrittenRemoved(t *testing.T) { l := newHaveLink() q, _ := aHaveQueue(l) var gone []string @@ -651,7 +651,7 @@ func TestAModuleLeavingTheDeclarationIsWrittenRemoved(t *testing.T) { } // 1369/AC2: a module removed and later added back is written with its new phase. -func TestARemovedModuleAddedBackIsWrittenWithItsNewPhase(t *testing.T) { +func testARemovedModuleAddedBackIsWrittenWithItsNewPhase(t *testing.T) { l := newHaveLink() q, _ := aHaveQueue(l) q.SayFacts(context.Background(), appliedModules()) @@ -668,7 +668,7 @@ func TestARemovedModuleAddedBackIsWrittenWithItsNewPhase(t *testing.T) { // 1369/AC3: a module this node-engine never wrote a have key for is not written, and a key that is gone from the // bucket is not created again. -func TestAModuleNeverWrittenIsNotWrittenRemoved(t *testing.T) { +func testAModuleNeverWrittenIsNotWrittenRemoved(t *testing.T) { l := newHaveLink() l.put(t, "n1.c", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Build: "b-9", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) q, _ := aHaveQueue(l) @@ -691,7 +691,7 @@ func TestAModuleNeverWrittenIsNotWrittenRemoved(t *testing.T) { } // A removal the bucket refused is written by the next pass. -func TestARefusedRemovalIsWrittenByTheNextPass(t *testing.T) { +func testARefusedRemovalIsWrittenByTheNextPass(t *testing.T) { l := newHaveLink() q, _ := aHaveQueue(l) q.SayFacts(context.Background(), appliedModules()) @@ -710,7 +710,7 @@ func TestARefusedRemovalIsWrittenByTheNextPass(t *testing.T) { // 1369/F1: a node-engine that started since wrote nothing, and the report names the modules the kept declaration held // before: one of them the new declaration lacks is written removed, one that is not in the bucket is not created. -func TestARestartedNodeEngineWritesTheRemovalFromTheReportsBefore(t *testing.T) { +func testARestartedNodeEngineWritesTheRemovalFromTheReportsBefore(t *testing.T) { l := newHaveLink() l.put(t, "n1.a", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Form: nodeengine.Form, Build: "b-1", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) l.put(t, "n1.b", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Form: nodeengine.Form, Build: "b-2", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}) @@ -731,7 +731,7 @@ func TestARestartedNodeEngineWritesTheRemovalFromTheReportsBefore(t *testing.T) // R6-A AC7: the first have this node-engine writes — or finds already saying what it would write — is told to the // proof, which proves a node-engine on trial to its launcher (novox/hq ADR 0539 §9); a write the bucket refuses is not. -func TestTheFirstHaveWrittenIsToldToTheProof(t *testing.T) { +func testTheFirstHaveWrittenIsToldToTheProof(t *testing.T) { l := newHaveLink() l.failing = true q, _ := aHaveQueue(l) @@ -764,7 +764,7 @@ func TestTheFirstHaveWrittenIsToldToTheProof(t *testing.T) { // R6-A AC6: an applied module's have names its fingerprint and the digest of the composition applied; a health check that // fails after the module's start window gives health failed, and the have keeps both. -func TestAnAppliedModulesHaveNamesTheFingerprintAndTheDigestAndFollowsItsHealth(t *testing.T) { +func testAnAppliedModulesHaveNamesTheFingerprintAndTheDigestAndFollowsItsHealth(t *testing.T) { l := newHaveLink() q, _ := aHaveQueue(l) fp := "src2:" + strings.Repeat("a", 64) @@ -870,7 +870,7 @@ func TestAnAppliedModulesHaveNamesTheFingerprintAndTheDigestAndFollowsItsHealth( // of it that could be down. Unknown kept it from ever being healthy, so the assigner's canary rule held every other node // of mesh-host back for good (issue 1945, live on 2026-10-25: ace's have of mesh-host said unknown, and novox and shanks // never got the new node-engine). A failed one stays failed, and before any look it is unknown. -func TestAModuleWithNothingToJudgeIsOkOnceLookedAt(t *testing.T) { +func testAModuleWithNothingToJudgeIsOkOnceLookedAt(t *testing.T) { l := newHaveLink() q, _ := aHaveQueue(l) q.SayFacts(context.Background(), Report{Modules: []ModuleFact{{Module: "mesh-host", Build: "b"}, {Module: "web", Build: "b"}, @@ -892,7 +892,7 @@ func TestAModuleWithNothingToJudgeIsOkOnceLookedAt(t *testing.T) { // A have an older engine left unknown is written over with this engine's health once the module is said again, as the // node agent says a module it finds running on its own have: a packages-only module (xorg, nothing long-running) is ok // after a look, so the assigner no longer holds back what requires its provision (2026-10-25, g14 and shanks). -func TestAModuleSaidAgainOverAnOlderEnginesUnknownIsWrittenWithThisEnginesHealth(t *testing.T) { +func testAModuleSaidAgainOverAnOlderEnginesUnknownIsWrittenWithThisEnginesHealth(t *testing.T) { l := newHaveLink() fp := "src2:" + strings.Repeat("a", 64) dig := "sha256:" + strings.Repeat("b", 64) @@ -914,7 +914,7 @@ func TestAModuleSaidAgainOverAnOlderEnginesUnknownIsWrittenWithThisEnginesHealth // A module's health is not yet judged (unknown) while its change is under way and until a look after it, never failed // from a look at what was being replaced: on 2026-10-25 15:27:36 the controller's canary on novox was held on a have // saying applying and failed, two seconds before its launch said healthy. -func TestAHealthIsNotJudgedWhileAModuleIsApplied(t *testing.T) { +func testAHealthIsNotJudgedWhileAModuleIsApplied(t *testing.T) { l := newHaveLink() q, _ := aHaveQueue(l) ctx := context.Background() @@ -946,7 +946,7 @@ func TestAHealthIsNotJudgedWhileAModuleIsApplied(t *testing.T) { } // A fact naming another composition than the one looked at, with no apply phase between, is not judged by the old look. -func TestAHealthIsNotCarriedOverToAnotherComposition(t *testing.T) { +func testAHealthIsNotCarriedOverToAnotherComposition(t *testing.T) { l := newHaveLink() q, _ := aHaveQueue(l) ctx := context.Background() @@ -960,7 +960,7 @@ func TestAHealthIsNotCarriedOverToAnotherComposition(t *testing.T) { // A declaration's report naming another composition of a module, with no health of its own, does not carry the old // look's health over; and a module removed leaves nothing marked unjudged behind. -func TestADeclarationReportMovesAHealthAndARemovalForgetsIt(t *testing.T) { +func testADeclarationReportMovesAHealthAndARemovalForgetsIt(t *testing.T) { l := newHaveLink() q, _ := aHaveQueue(l) ctx := context.Background() @@ -990,7 +990,7 @@ func TestADeclarationReportMovesAHealthAndARemovalForgetsIt(t *testing.T) { // ADR 0547 §8, 2026-10-26 on the bus node: the bus's user list of a module this engine says no have of (no want, and no // longer in the declaration) still reaches the module's key, merged into what the key says, every other field kept; a // key that does not exist is not made up and is said once; a writer that drops the list again is written over. -func TestAUserListReachesTheHaveOfAModuleNoApplyHereSays(t *testing.T) { +func testAUserListReachesTheHaveOfAModuleNoApplyHereSays(t *testing.T) { l := newHaveLink() older := nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Build: "build-1", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK} l.put(t, "n1.nats", older) @@ -1055,3 +1055,27 @@ func slicesIndex(rs []ResourceHealth, id string) int { func statedReads() []string { return slices.Sorted(slices.Values(append(catalogue.ManifestReads(), nodeengine.ManifestReadWordWantVersion))) } + +// TestHave runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestHave(t *testing.T) { + t.Run("AnAppliedModuleIsWrittenRunningAndAFailedOneFailed", testAnAppliedModuleIsWrittenRunningAndAFailedOneFailed) + t.Run("AHaveIsWrittenOnlyWhenItDiffers", testAHaveIsWrittenOnlyWhenItDiffers) + t.Run("AModulesHealthFollowsTheLook", testAModulesHealthFollowsTheLook) + t.Run("TheNodeKeyCarriesTheNodesFacts", testTheNodeKeyCarriesTheNodesFacts) + t.Run("AFailedHaveWriteIsSaidAndWrittenAgain", testAFailedHaveWriteIsSaidAndWrittenAgain) + t.Run("NoBucketAndNoFactsWriteNothing", testNoBucketAndNoFactsWriteNothing) + t.Run("AFailedBindOrWriteEndsThePassAndReturnsInTime", testAFailedBindOrWriteEndsThePassAndReturnsInTime) + t.Run("AModuleLeavingTheDeclarationIsWrittenRemoved", testAModuleLeavingTheDeclarationIsWrittenRemoved) + t.Run("ARemovedModuleAddedBackIsWrittenWithItsNewPhase", testARemovedModuleAddedBackIsWrittenWithItsNewPhase) + t.Run("AModuleNeverWrittenIsNotWrittenRemoved", testAModuleNeverWrittenIsNotWrittenRemoved) + t.Run("ARefusedRemovalIsWrittenByTheNextPass", testARefusedRemovalIsWrittenByTheNextPass) + t.Run("ARestartedNodeEngineWritesTheRemovalFromTheReportsBefore", testARestartedNodeEngineWritesTheRemovalFromTheReportsBefore) + t.Run("TheFirstHaveWrittenIsToldToTheProof", testTheFirstHaveWrittenIsToldToTheProof) + t.Run("AnAppliedModulesHaveNamesTheFingerprintAndTheDigestAndFollowsItsHealth", testAnAppliedModulesHaveNamesTheFingerprintAndTheDigestAndFollowsItsHealth) + t.Run("AModuleWithNothingToJudgeIsOkOnceLookedAt", testAModuleWithNothingToJudgeIsOkOnceLookedAt) + t.Run("AModuleSaidAgainOverAnOlderEnginesUnknownIsWrittenWithThisEnginesHealth", testAModuleSaidAgainOverAnOlderEnginesUnknownIsWrittenWithThisEnginesHealth) + t.Run("AHealthIsNotJudgedWhileAModuleIsApplied", testAHealthIsNotJudgedWhileAModuleIsApplied) + t.Run("AHealthIsNotCarriedOverToAnotherComposition", testAHealthIsNotCarriedOverToAnotherComposition) + t.Run("ADeclarationReportMovesAHealthAndARemovalForgetsIt", testADeclarationReportMovesAHealthAndARemovalForgetsIt) + t.Run("AUserListReachesTheHaveOfAModuleNoApplyHereSays", testAUserListReachesTheHaveOfAModuleNoApplyHereSays) +} diff --git a/internal/link/health_test.go b/internal/link/health_test.go index 8a87e3b1..2c442c22 100644 --- a/internal/link/health_test.go +++ b/internal/link/health_test.go @@ -24,7 +24,7 @@ func (l *sayingLink) Health(_ context.Context, node string, body []byte) error { return nil } -func TestAHealthStatementIsSaidOnTheLinkOpenNow(t *testing.T) { +func testAHealthStatementIsSaidOnTheLinkOpenNow(t *testing.T) { q := &Session{Membership: Membership{Node: "anchor"}} h := Health{Contract: LivenessContract, At: time.Now().UTC(), Resources: []ResourceHealth{{Module: "letta", Resource: "letta.server", State: StateUnhealthy, Reason: ReasonRestarting}}} @@ -151,7 +151,7 @@ func (m *memHealth) Put(_ context.Context, key string, value []byte) error { // A declared tool check reads the node tools' reply envelope: healthy only when the tool says so (novox/hq // ADR 0240, to-be 48 §2), and asked on this machine's own instance (to-be 48 §3). -func TestAToolsAnswerIsHealthyOnlyWhenItSaysSo(t *testing.T) { +func testAToolsAnswerIsHealthyOnlyWhenItSaysSo(t *testing.T) { for reply, want := range map[string]bool{ `{"result":{"healthy":true},"node":"anchor"}`: true, `{"result":{"healthy":false,"why":"the admin refused the secret"}}`: false, @@ -185,7 +185,7 @@ func TestAToolsAnswerIsHealthyOnlyWhenItSaysSo(t *testing.T) { // refused as if none were open (2026-10-08: every tool check read "no link to the bus is open" while // the link was up, because the NATS link could not Ask). With no link open, and with a link that cannot // ask, the check fails and says which. -func TestAToolCheckIsAskedOnTheLinkTheEngineHolds(t *testing.T) { +func testAToolCheckIsAskedOnTheLinkTheEngineHolds(t *testing.T) { q := &Session{Membership: Membership{Node: "anchor"}} if _, err := q.AskTool(t.Context(), "sensors", "sensors_health"); err == nil || err.Error() != "no link to the bus is open" { t.Fatalf("with no link open: %v", err) @@ -210,3 +210,10 @@ func TestAToolCheckIsAskedOnTheLinkTheEngineHolds(t *testing.T) { t.Fatalf("the NATS link was not asked: %v", err) } } + +// TestHealth runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestHealth(t *testing.T) { + t.Run("AHealthStatementIsSaidOnTheLinkOpenNow", testAHealthStatementIsSaidOnTheLinkOpenNow) + t.Run("AToolsAnswerIsHealthyOnlyWhenItSaysSo", testAToolsAnswerIsHealthyOnlyWhenItSaysSo) + t.Run("AToolCheckIsAskedOnTheLinkTheEngineHolds", testAToolCheckIsAskedOnTheLinkTheEngineHolds) +} diff --git a/internal/link/judge_directories_test.go b/internal/link/judge_directories_test.go index 6439266b..fd992fc1 100644 --- a/internal/link/judge_directories_test.go +++ b/internal/link/judge_directories_test.go @@ -7,7 +7,7 @@ import ( ) // The subject and the signing context the controller holds the same words for (mesh-controller internal/link). -func TestTheDirectoryJudgementAskKeepsItsSubjectAndContext(t *testing.T) { +func testTheDirectoryJudgementAskKeepsItsSubjectAndContext(t *testing.T) { if AskJudgeDirectoriesSubject("laptop") != "mesh.node.laptop.ask.judge-directories" { t.Fatalf("the subject is %q", AskJudgeDirectoriesSubject("laptop")) } @@ -19,7 +19,7 @@ func TestTheDirectoryJudgementAskKeepsItsSubjectAndContext(t *testing.T) { // A judgement ask is believed as a hand-over is: signed by the mesh under its own context, for this node, // unexpired, once, and naming no path. -func TestADirectoryJudgementAskIsBelievedOnlySignedForThisNodeAndOnce(t *testing.T) { +func testADirectoryJudgementAskIsBelievedOnlySignedForThisNodeAndOnce(t *testing.T) { m, key := aMember(t) now := time.Date(2026, 10, 12, 14, 0, 0, 0, time.UTC) var asked []string @@ -50,3 +50,9 @@ func TestADirectoryJudgementAskIsBelievedOnlySignedForThisNodeAndOnce(t *testing t.Fatal("a request with no reply subject was answered") } } + +// TestJudgeDirectories runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestJudgeDirectories(t *testing.T) { + t.Run("TheDirectoryJudgementAskKeepsItsSubjectAndContext", testTheDirectoryJudgementAskKeepsItsSubjectAndContext) + t.Run("ADirectoryJudgementAskIsBelievedOnlySignedForThisNodeAndOnce", testADirectoryJudgementAskIsBelievedOnlySignedForThisNodeAndOnce) +} diff --git a/internal/link/movesecret_test.go b/internal/link/movesecret_test.go index f5121f04..81458785 100644 --- a/internal/link/movesecret_test.go +++ b/internal/link/movesecret_test.go @@ -14,7 +14,7 @@ import ( // The move's ask (design 57's V3, issue 676): a hand-over's fields and the row's own in one signed object, under a // signing context of its own. The controller's side holds the same names and words. -func TestTheMovesAskKeepsItsFieldNamesAndContext(t *testing.T) { +func testTheMovesAskKeepsItsFieldNamesAndContext(t *testing.T) { body, _ := json.Marshal(MoveSecretAsk{Module: "m", Name: "n", Provider: "p", Provision: "q", Consumer: "c", ConsumerModule: "cm", Local: "l", Origin: "made", Generation: "g", MadeAt: time.Unix(1, 0).UTC(), Sealed: "s", SealedTo: "k"}) @@ -49,7 +49,7 @@ func signedMove(t *testing.T, key ed25519.PrivateKey, ask HandOverAsk, move Move // A move is believed as every signed ask is, then names one row this machine holds — its own secret, or a pair // credential with this machine at one end — with a value sealed to it and an origin the store has; only then is the // handler given it. A hand-over's signature is not a move's. -func TestAMoveIsTakenOnlyForARowThisMachineHolds(t *testing.T) { +func testAMoveIsTakenOnlyForARowThisMachineHolds(t *testing.T) { m, key := aMember(t) now := time.Now() var given []MoveSecret @@ -102,7 +102,7 @@ func TestAMoveIsTakenOnlyForARowThisMachineHolds(t *testing.T) { // **Against a real server**: the move's signed ask on the node's own subject is answered with what the handler // moved, and the engine asks the vault on the subject that names it, `node~` last. -func TestNatsAMoveIsAskedOfTheNodeAndTheVaultIsAskedInItsName(t *testing.T) { +func testNatsAMoveIsAskedOfTheNodeAndTheVaultIsAskedInItsName(t *testing.T) { conn, js := aBus(t) m, key := aMember(t) vault, err := conn.Subscribe("mesh.seat.mesh-vault.call.move-in.node~"+m.Node, func(msg *nats.Msg) { @@ -176,3 +176,10 @@ func TestNatsAMoveIsAskedOfTheNodeAndTheVaultIsAskedInItsName(t *testing.T) { t.Errorf("the grants part withheld twice is said %q, want once naming the seat asked", journal) } } + +// TestMovesecret runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestMovesecret(t *testing.T) { + t.Run("TheMovesAskKeepsItsFieldNamesAndContext", testTheMovesAskKeepsItsFieldNamesAndContext) + t.Run("AMoveIsTakenOnlyForARowThisMachineHolds", testAMoveIsTakenOnlyForARowThisMachineHolds) + t.Run("NatsAMoveIsAskedOfTheNodeAndTheVaultIsAskedInItsName", testNatsAMoveIsAskedOfTheNodeAndTheVaultIsAskedInItsName) +} diff --git a/internal/link/pinned_test.go b/internal/link/pinned_test.go index 19ef8c11..5826d5e6 100644 --- a/internal/link/pinned_test.go +++ b/internal/link/pinned_test.go @@ -63,7 +63,7 @@ func server(t *testing.T) (address string, fingerprint string) { // The right broker is accepted, a different one refused, and a malformed pin is caught before connecting, rather than at // the handshake, so a mistyped token fails while a person is looking at it (three tests merged). -func TestTheRightBrokerIsAcceptedAndAMalformedPinRefused(t *testing.T) { +func testTheRightBrokerIsAcceptedAndAMalformedPinRefused(t *testing.T) { address, pin := server(t) conn, err := dialPinned(address, pin, 5*time.Second) if err != nil { @@ -92,7 +92,7 @@ func TestTheRightBrokerIsAcceptedAndAMalformedPinRefused(t *testing.T) { } } -func TestNothingIsSentToTheWrongBroker(t *testing.T) { +func testNothingIsSentToTheWrongBroker(t *testing.T) { // ADR 0004 requires the check to happen *before* anything is sent. Asserted by counting what // the wrong server received: a handshake, and no application bytes. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) @@ -142,7 +142,7 @@ func TestNothingIsSentToTheWrongBroker(t *testing.T) { } } -func TestAnUnreachableBrokerIsAnOrdinaryFailure(t *testing.T) { +func testAnUnreachableBrokerIsAnOrdinaryFailure(t *testing.T) { // Must not read as a wrong certificate: one is a network problem worth retrying, the other // means the mesh was substituted. _, pin := server(t) @@ -161,3 +161,10 @@ func TestAnUnreachableBrokerIsAnOrdinaryFailure(t *testing.T) { t.Error("an unreachable broker was reported as presenting the wrong certificate") } } + +// TestPinned runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestPinned(t *testing.T) { + t.Run("TheRightBrokerIsAcceptedAndAMalformedPinRefused", testTheRightBrokerIsAcceptedAndAMalformedPinRefused) + t.Run("NothingIsSentToTheWrongBroker", testNothingIsSentToTheWrongBroker) + t.Run("AnUnreachableBrokerIsAnOrdinaryFailure", testAnUnreachableBrokerIsAnOrdinaryFailure) +} diff --git a/internal/link/rotate_test.go b/internal/link/rotate_test.go index ceb0191e..f994806c 100644 --- a/internal/link/rotate_test.go +++ b/internal/link/rotate_test.go @@ -60,7 +60,7 @@ func key(login, rotating, stage string) meshvault.NodeLoginsByNodeValue { // 774/S62/AC1 and AC2 (ADR 0583 §3): at ready the engine fetches the new value and test-dials it; one that does not // authenticate leaves it on the old login, saying why; one that does is switched to, confirmed over the new connection, and // the old value is kept. -func TestTheEngineSwitchesOnlyAfterATestDialAndConfirmsAsTheNewLogin(t *testing.T) { +func testTheEngineSwitchesOnlyAfterATestDialAndConfirmsAsTheNewLogin(t *testing.T) { g := newRotRig() ctx := context.Background() g.r.Heard(ctx, key("node.ace", "node.ace--b", meshvaultclient.RotationBegun)) @@ -95,7 +95,7 @@ func TestTheEngineSwitchesOnlyAfterATestDialAndConfirmsAsTheNewLogin(t *testing. // 774/S63/AC1-AC3 (ADR 0583 §4-§6): the old value is dropped at rotation-done and not before; an abandon after the switch, // before or after the confirmation, switches back before the new value is dropped; repeated failures with the new value before // rotation-done bring the old one back, said as node-account-fallback, and that rotation is not tried again. -func TestTheOldValueGoesAtRotationDoneAbandonSwitchesBackAndFailuresFallBack(t *testing.T) { +func testTheOldValueGoesAtRotationDoneAbandonSwitchesBackAndFailuresFallBack(t *testing.T) { ctx := context.Background() for _, stage := range []string{"before confirming", "after confirming"} { g := newRotRig() @@ -159,3 +159,9 @@ func TestTheOldValueGoesAtRotationDoneAbandonSwitchesBackAndFailuresFallBack(t * t.Error("the fall back is still said after the vault moved on") } } + +// TestRotate runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRotate(t *testing.T) { + t.Run("TheEngineSwitchesOnlyAfterATestDialAndConfirmsAsTheNewLogin", testTheEngineSwitchesOnlyAfterATestDialAndConfirmsAsTheNewLogin) + t.Run("TheOldValueGoesAtRotationDoneAbandonSwitchesBackAndFailuresFallBack", testTheOldValueGoesAtRotationDoneAbandonSwitchesBackAndFailuresFallBack) +} diff --git a/internal/link/roused_test.go b/internal/link/roused_test.go index 10715660..5be78f06 100644 --- a/internal/link/roused_test.go +++ b/internal/link/roused_test.go @@ -15,7 +15,7 @@ import ( // because nothing has tried to send anything. Heartbeats discover it twenty or thirty seconds // later, and for that time the node believes it is in a mesh it has left, which is the one state // this design says must never be indistinguishable from being connected. -func TestBeingRousedEndsTheCurrentAttemptRatherThanWaitingForATimeout(t *testing.T) { +func testBeingRousedEndsTheCurrentAttemptRatherThanWaitingForATimeout(t *testing.T) { // A link that never returns on its own, which is exactly what a suspended connection is. held := make(chan context.Context, 4) running := func(ctx context.Context) error { @@ -65,7 +65,7 @@ func TestBeingRousedEndsTheCurrentAttemptRatherThanWaitingForATimeout(t *testing } // A machine nothing ever rouses is every machine that does not suspend, and must behave as before. -func TestAMachineNothingRousesIsUnaffected(t *testing.T) { +func testAMachineNothingRousesIsUnaffected(t *testing.T) { attempts := make(chan struct{}, 4) running := func(context.Context) error { attempts <- struct{}{} @@ -101,3 +101,9 @@ func (s *saidSoFar) all() string { defer s.mu.Unlock() return strings.Join(s.said, "\n") } + +// TestRoused runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestRoused(t *testing.T) { + t.Run("BeingRousedEndsTheCurrentAttemptRatherThanWaitingForATimeout", testBeingRousedEndsTheCurrentAttemptRatherThanWaitingForATimeout) + t.Run("AMachineNothingRousesIsUnaffected", testAMachineNothingRousesIsUnaffected) +} diff --git a/internal/link/session_test.go b/internal/link/session_test.go index 21234b77..046f6288 100644 --- a/internal/link/session_test.go +++ b/internal/link/session_test.go @@ -67,7 +67,7 @@ func aMember(t *testing.T) (Membership, ed25519.PrivateKey) { } // Facts made with no link open are not kept, and nothing is said: the next link says them as they are then. -func TestFactsWithNoLinkOpenAreNotSaid(t *testing.T) { +func testFactsWithNoLinkOpenAreNotSaid(t *testing.T) { m, _ := aMember(t) l := newQuietLink() s := &Session{Membership: m, Timeout: time.Second} @@ -114,7 +114,7 @@ func TestFactsWithNoLinkOpenAreNotSaid(t *testing.T) { } // A link opening says the node's facts, off the link's own loop. -func TestALinkOpeningSaysTheFacts(t *testing.T) { +func testALinkOpeningSaysTheFacts(t *testing.T) { m, _ := aMember(t) l := newQuietLink() opened := make(chan struct{}, 1) @@ -171,7 +171,7 @@ func (l *refusingLink) Refused() <-chan string { return l.refused } // without them, and nats asks a refused subscription again only on a new connection; the seat answered nobody all // afternoon. A refused subscription is read from the server's words, said, and the link opened again after a pause // that grows while it is refused again; a refused publish is not one. -func TestASubscriptionTheBusRefusedIsAskedAgainOnANewLink(t *testing.T) { +func testASubscriptionTheBusRefusedIsAskedAgainOnANewLink(t *testing.T) { // The server's words, as the client hands them on (journal of nox-mesh-host on novox, 2026-10-30 12:10:44). for _, row := range []struct { err error @@ -233,3 +233,10 @@ func TestASubscriptionTheBusRefusedIsAskedAgainOnANewLink(t *testing.T) { t.Error("a link that held its subscriptions did not start from the first pause again") } } + +// TestSession runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSession(t *testing.T) { + t.Run("FactsWithNoLinkOpenAreNotSaid", testFactsWithNoLinkOpenAreNotSaid) + t.Run("ALinkOpeningSaysTheFacts", testALinkOpeningSaysTheFacts) + t.Run("ASubscriptionTheBusRefusedIsAskedAgainOnANewLink", testASubscriptionTheBusRefusedIsAskedAgainOnANewLink) +} diff --git a/internal/link/setuid_search_test.go b/internal/link/setuid_search_test.go index 8b333e74..1cb8b787 100644 --- a/internal/link/setuid_search_test.go +++ b/internal/link/setuid_search_test.go @@ -9,7 +9,7 @@ import ( ) // The subject and the signing context the controller holds the same words for (mesh-controller internal/link). -func TestTheSetuidSearchAskKeepsItsSubjectAndContext(t *testing.T) { +func testTheSetuidSearchAskKeepsItsSubjectAndContext(t *testing.T) { if AskSetuidSearchSubject("laptop") != "mesh.node.laptop.ask.setuid-search" { t.Fatalf("the subject is %q", AskSetuidSearchSubject("laptop")) } @@ -27,7 +27,7 @@ func signedSearch(t *testing.T, key ed25519.PrivateKey, context string, ask Hand // A search ask is believed as a hand-over is: signed by the mesh under its own context (a hand-over's signature // starts no search), for this node, unexpired, once, and naming no path. -func TestASetuidSearchAskIsBelievedOnlySignedForThisNodeAndOnce(t *testing.T) { +func testASetuidSearchAskIsBelievedOnlySignedForThisNodeAndOnce(t *testing.T) { m, key := aMember(t) now := time.Date(2026, 10, 10, 2, 0, 0, 0, time.UTC) var asked []string @@ -136,3 +136,9 @@ func TestASetuidSearchAskIsBelievedOnlySignedForThisNodeAndOnce(t *testing.T) { } }) } + +// TestSetuidSearch runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSetuidSearch(t *testing.T) { + t.Run("TheSetuidSearchAskKeepsItsSubjectAndContext", testTheSetuidSearchAskKeepsItsSubjectAndContext) + t.Run("ASetuidSearchAskIsBelievedOnlySignedForThisNodeAndOnce", testASetuidSearchAskIsBelievedOnlySignedForThisNodeAndOnce) +} diff --git a/internal/link/taken.go b/internal/link/taken.go index ec2e8975..293285d2 100644 --- a/internal/link/taken.go +++ b/internal/link/taken.go @@ -33,8 +33,12 @@ func takenKV(ctx context.Context, conn *nats.Conn) (jetstream.KeyValue, error) { return kv, nil } -func (l *natsLink) TakenKV(ctx context.Context) (jetstream.KeyValue, error) { return takenKV(ctx, l.conn) } -func (b OverNATS) TakenKV(ctx context.Context) (jetstream.KeyValue, error) { return takenKV(ctx, b.Conn) } +func (l *natsLink) TakenKV(ctx context.Context) (jetstream.KeyValue, error) { + return takenKV(ctx, l.conn) +} +func (b OverNATS) TakenKV(ctx context.Context) (jetstream.KeyValue, error) { + return takenKV(ctx, b.Conn) +} var ( _ TakenBus = (*natsLink)(nil) diff --git a/internal/liveness/liveness_test.go b/internal/liveness/liveness_test.go index 74b4764b..7bca6c00 100644 --- a/internal/liveness/liveness_test.go +++ b/internal/liveness/liveness_test.go @@ -78,7 +78,7 @@ func stateOf(t *testing.T, st Statement, id string) State { return State{} } -func TestARestartInsideGraceIsNotCountedAndTwoAfterItAreUnhealthy(t *testing.T) { +func testARestartInsideGraceIsNotCountedAndTwoAfterItAreUnhealthy(t *testing.T) { c := &clock{now: t0} rt := &fakeRuntime{containers: map[string]Observed{"letta-server": running("c1", 0, "a")}} j := aJudge(t, rt, c, filepath.Join(t.TempDir(), FileName)) @@ -130,7 +130,7 @@ func TestARestartInsideGraceIsNotCountedAndTwoAfterItAreUnhealthy(t *testing.T) } } -func TestARecreatedContainerKeepsItsCountedRestartsAndStartsAgain(t *testing.T) { +func testARecreatedContainerKeepsItsCountedRestartsAndStartsAgain(t *testing.T) { c := &clock{now: t0} rt := &fakeRuntime{containers: map[string]Observed{"letta-server": running("c1", 0, "a")}} j := aJudge(t, rt, c, filepath.Join(t.TempDir(), FileName)) @@ -157,7 +157,7 @@ func TestARecreatedContainerKeepsItsCountedRestartsAndStartsAgain(t *testing.T) } } -func TestTheEngineRestartedKeepsWhatItCounted(t *testing.T) { +func testTheEngineRestartedKeepsWhatItCounted(t *testing.T) { path := filepath.Join(t.TempDir(), FileName) c := &clock{now: t0} rt := &fakeRuntime{containers: map[string]Observed{"letta-server": running("c1", 0, "a")}} @@ -178,7 +178,7 @@ func TestTheEngineRestartedKeepsWhatItCounted(t *testing.T) { } } -func TestAContainerHeldByAWindowIsHeldAndJudgedAfreshAfter(t *testing.T) { +func testAContainerHeldByAWindowIsHeldAndJudgedAfreshAfter(t *testing.T) { c := &clock{now: t0} rt := &fakeRuntime{containers: map[string]Observed{"letta-server": running("c1", 0, "a")}} j := aJudge(t, rt, c, filepath.Join(t.TempDir(), FileName)) @@ -199,7 +199,7 @@ func TestAContainerHeldByAWindowIsHeldAndJudgedAfreshAfter(t *testing.T) { } } -func TestDownAfterGraceAndUnknownWhenNothingCouldBeRead(t *testing.T) { +func testDownAfterGraceAndUnknownWhenNothingCouldBeRead(t *testing.T) { c := &clock{now: t0} rt := &fakeRuntime{containers: map[string]Observed{}} j := aJudge(t, rt, c, filepath.Join(t.TempDir(), FileName)) @@ -219,7 +219,7 @@ func TestDownAfterGraceAndUnknownWhenNothingCouldBeRead(t *testing.T) { } } -func TestAUnitRestartedByItsManagerIsCountedAndOneStartedAgainIsNot(t *testing.T) { +func testAUnitRestartedByItsManagerIsCountedAndOneStartedAgainIsNot(t *testing.T) { unit := Resource{Module: "mqtt", ID: "mqtt.broker", Kind: KindService, Target: "mosquitto.service"} c := &clock{now: t0} rt := &fakeRuntime{units: map[string]Observed{"mosquitto.service": running("i1", 0, "")}} @@ -245,7 +245,7 @@ func TestAUnitRestartedByItsManagerIsCountedAndOneStartedAgainIsNot(t *testing.T // The long-running resources of a declaration: what stays up, by module; never a step, a schedule, a // service whose lifecycle is the machine's, the mesh's own resources, or what an adopted machine holds. -func TestWhatIsLongRunning(t *testing.T) { +func testWhatIsLongRunning(t *testing.T) { const image = "docker.io/library/postgres@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" d, err := declaration.ParseTrusted([]byte(`{"declaration":1,"resources":[ {"id":"store","type":"container","name":"mesh-store","image":"` + image + `"}, @@ -273,7 +273,7 @@ func TestWhatIsLongRunning(t *testing.T) { // **Nothing is restarted for being unhealthy** (ADR 0240 rule 6): a crash-looping container is judged // unhealthy, and everything the judge asked the runtime and the manager was a read. -func TestAnUnhealthyContainerIsNeitherRestartedRecreatedNorStopped(t *testing.T) { +func testAnUnhealthyContainerIsNeitherRestartedRecreatedNorStopped(t *testing.T) { var asked []string restarts := 0 run := func(_ context.Context, name string, args ...string) (string, error) { @@ -310,7 +310,7 @@ func TestAnUnhealthyContainerIsNeitherRestartedRecreatedNorStopped(t *testing.T) } // One read of every container per look, never one per container (ADR 0240: the engine stays cheap). -func TestOneLookIsOneReadOfEveryContainer(t *testing.T) { +func testOneLookIsOneReadOfEveryContainer(t *testing.T) { inspects := 0 run := func(_ context.Context, name string, args ...string) (string, error) { if args[0] == "container" { @@ -334,7 +334,7 @@ func TestOneLookIsOneReadOfEveryContainer(t *testing.T) { // **A look starts no account's manager** (novox/hq issue 764, ADR 0177): a user-scoped unit's manager is // asked of the machine's first; one not running is not read, nothing is started, and its unit is said // unknown with why — away, never down; one running is read as before. -func TestAUserUnitsManagerNotRunningIsNotReadAndNotDown(t *testing.T) { +func testAUserUnitsManagerNotRunningIsNotReadAndNotDown(t *testing.T) { var asked []string manager := "inactive" run := func(_ context.Context, name string, args ...string) (string, error) { @@ -386,7 +386,7 @@ func TestAUserUnitsManagerNotRunningIsNotReadAndNotDown(t *testing.T) { // A resource the runtime does not have at all after its grace is said missing, beside down: what the node agent applies // again (issue 1945). One that is there and stopped is down and not missing, and one that cannot be read is neither. -func TestAResourceNotThereIsMissingAndOneStoppedIsNot(t *testing.T) { +func testAResourceNotThereIsMissingAndOneStoppedIsNot(t *testing.T) { c := &clock{now: t0} rt := &fakeRuntime{containers: map[string]Observed{}} j := aJudge(t, rt, c, filepath.Join(t.TempDir(), FileName)) @@ -408,3 +408,18 @@ func TestAResourceNotThereIsMissingAndOneStoppedIsNot(t *testing.T) { t.Fatalf("a runtime that does not answer says nothing is missing: %+v", s) } } + +// TestLiveness runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestLiveness(t *testing.T) { + t.Run("ARestartInsideGraceIsNotCountedAndTwoAfterItAreUnhealthy", testARestartInsideGraceIsNotCountedAndTwoAfterItAreUnhealthy) + t.Run("ARecreatedContainerKeepsItsCountedRestartsAndStartsAgain", testARecreatedContainerKeepsItsCountedRestartsAndStartsAgain) + t.Run("TheEngineRestartedKeepsWhatItCounted", testTheEngineRestartedKeepsWhatItCounted) + t.Run("AContainerHeldByAWindowIsHeldAndJudgedAfreshAfter", testAContainerHeldByAWindowIsHeldAndJudgedAfreshAfter) + t.Run("DownAfterGraceAndUnknownWhenNothingCouldBeRead", testDownAfterGraceAndUnknownWhenNothingCouldBeRead) + t.Run("AUnitRestartedByItsManagerIsCountedAndOneStartedAgainIsNot", testAUnitRestartedByItsManagerIsCountedAndOneStartedAgainIsNot) + t.Run("WhatIsLongRunning", testWhatIsLongRunning) + t.Run("AnUnhealthyContainerIsNeitherRestartedRecreatedNorStopped", testAnUnhealthyContainerIsNeitherRestartedRecreatedNorStopped) + t.Run("OneLookIsOneReadOfEveryContainer", testOneLookIsOneReadOfEveryContainer) + t.Run("AUserUnitsManagerNotRunningIsNotReadAndNotDown", testAUserUnitsManagerNotRunningIsNotReadAndNotDown) + t.Run("AResourceNotThereIsMissingAndOneStoppedIsNot", testAResourceNotThereIsMissingAndOneStoppedIsNot) +} diff --git a/internal/liveness/readiness_test.go b/internal/liveness/readiness_test.go index d36361bd..31bb2edd 100644 --- a/internal/liveness/readiness_test.go +++ b/internal/liveness/readiness_test.go @@ -46,7 +46,7 @@ func lookOnce(t *testing.T, j *Judge) { } } -func TestAnHTTPCheckIsStartingUntilItPassesAndUnhealthyAfterItsLooksFail(t *testing.T) { +func testAnHTTPCheckIsStartingUntilItPassesAndUnhealthyAfterItsLooksFail(t *testing.T) { answering := true srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !answering || r.URL.Path != "/healthz" { @@ -98,7 +98,7 @@ func TestAnHTTPCheckIsStartingUntilItPassesAndUnhealthyAfterItsLooksFail(t *test } } -func TestAnHTTPCheckDialsTheEndpointsCurrentPortAfterAPortChange(t *testing.T) { +func testAnHTTPCheckDialsTheEndpointsCurrentPortAfterAPortChange(t *testing.T) { hit := map[string]int{} handler := func(name string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hit[name]++ }) @@ -122,7 +122,7 @@ func TestAnHTTPCheckDialsTheEndpointsCurrentPortAfterAPortChange(t *testing.T) { } } -func TestTheRuntimesCheckIsReadAndAnImageWithoutOneIsSaid(t *testing.T) { +func testTheRuntimesCheckIsReadAndAnImageWithoutOneIsSaid(t *testing.T) { c := &clock{now: t0} o := running("c1", 0, t0.Format(time.RFC3339Nano)) rt := &fakeRuntime{containers: map[string]Observed{"db": o}} @@ -151,7 +151,7 @@ func TestTheRuntimesCheckIsReadAndAnImageWithoutOneIsSaid(t *testing.T) { } } -func TestAUnitIsReadyWhenItsManagerSaysItIsActive(t *testing.T) { +func testAUnitIsReadyWhenItsManagerSaysItIsActive(t *testing.T) { c := &clock{now: t0} rt := &fakeRuntime{units: map[string]Observed{"d.service": {Found: true, Identity: "i1", Running: true}}} j := aJudge(t, rt, c, "") @@ -163,7 +163,7 @@ func TestAUnitIsReadyWhenItsManagerSaysItIsActive(t *testing.T) { } } -func TestNeverMoreLooksThanTheBudget(t *testing.T) { +func testNeverMoreLooksThanTheBudget(t *testing.T) { j := aJudge(t, &fakeRuntime{}, &clock{now: t0}, "") var rs []Resource for i := 0; i < 30; i++ { @@ -181,7 +181,7 @@ func TestNeverMoreLooksThanTheBudget(t *testing.T) { } } -func TestAToolCheckIsAskedOfTheNodeTools(t *testing.T) { +func testAToolCheckIsAskedOfTheNodeTools(t *testing.T) { asked := "" p := &Probes{AskTool: func(_ context.Context, module, tool string) (health.Answer, error) { asked = module + "." + tool @@ -196,7 +196,7 @@ func TestAToolCheckIsAskedOfTheNodeTools(t *testing.T) { // A tool that does not answer in time is said as the time it was given, once, and an error from the link is // said as it is, without a second "asking" in front of what the link already says. -func TestAToolCheckThatGetsNoAnswerSaysHowLongItWaited(t *testing.T) { +func testAToolCheckThatGetsNoAnswerSaysHowLongItWaited(t *testing.T) { check := &declaration.Health{Kind: declaration.HealthTool, Tool: "sensors_health", Interval: "30s", Timeout: "5s", Looks: 2, Grace: "0s"} p := &Probes{AskTool: func(context.Context, string, string) (health.Answer, error) { @@ -215,7 +215,7 @@ func TestAToolCheckThatGetsNoAnswerSaysHowLongItWaited(t *testing.T) { // The runtime's state of a container's own check is read out of its whole state: a container that carries // none has no Health in it, and that is not an error (a template naming it would refuse every container). -func TestTheRuntimesCheckIsReadOutOfTheContainersState(t *testing.T) { +func testTheRuntimesCheckIsReadOutOfTheContainersState(t *testing.T) { status, said := runtimeHealth(`{"Status":"running","Health":{"Status":"unhealthy","FailingStreak":3,"Log":[` + `{"ExitCode":1,"Output":"curl: (7) Failed to connect\n"}]}}`) if status != Unhealthy || said != "curl: (7) Failed to connect" { @@ -230,7 +230,7 @@ func TestTheRuntimesCheckIsReadOutOfTheContainersState(t *testing.T) { } // The engine's own looks run on their own clock, beside the looks of liveness, and are folded in. -func TestProbeLooksOnItsOwnAndTheNextLookFoldsItIn(t *testing.T) { +func testProbeLooksOnItsOwnAndTheNextLookFoldsItIn(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) defer srv.Close() rt := &fakeRuntime{containers: map[string]Observed{"web": running("c1", 0, time.Now().Format(time.RFC3339Nano))}} @@ -251,3 +251,16 @@ func TestProbeLooksOnItsOwnAndTheNextLookFoldsItIn(t *testing.T) { } t.Fatal("the engine's own look was never folded in") } + +// TestReadiness runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestReadiness(t *testing.T) { + t.Run("AnHTTPCheckIsStartingUntilItPassesAndUnhealthyAfterItsLooksFail", testAnHTTPCheckIsStartingUntilItPassesAndUnhealthyAfterItsLooksFail) + t.Run("AnHTTPCheckDialsTheEndpointsCurrentPortAfterAPortChange", testAnHTTPCheckDialsTheEndpointsCurrentPortAfterAPortChange) + t.Run("TheRuntimesCheckIsReadAndAnImageWithoutOneIsSaid", testTheRuntimesCheckIsReadAndAnImageWithoutOneIsSaid) + t.Run("AUnitIsReadyWhenItsManagerSaysItIsActive", testAUnitIsReadyWhenItsManagerSaysItIsActive) + t.Run("NeverMoreLooksThanTheBudget", testNeverMoreLooksThanTheBudget) + t.Run("AToolCheckIsAskedOfTheNodeTools", testAToolCheckIsAskedOfTheNodeTools) + t.Run("AToolCheckThatGetsNoAnswerSaysHowLongItWaited", testAToolCheckThatGetsNoAnswerSaysHowLongItWaited) + t.Run("TheRuntimesCheckIsReadOutOfTheContainersState", testTheRuntimesCheckIsReadOutOfTheContainersState) + t.Run("ProbeLooksOnItsOwnAndTheNextLookFoldsItIn", testProbeLooksOnItsOwnAndTheNextLookFoldsItIn) +} diff --git a/internal/liveness/replay_test.go b/internal/liveness/replay_test.go index 77c1eca2..9d57b8d1 100644 --- a/internal/liveness/replay_test.go +++ b/internal/liveness/replay_test.go @@ -29,7 +29,7 @@ import ( // MESH_REPLAY_CONTAINER; or by hand with MESH_REPLAY_RUNTIME=1, starting its own. Skipped otherwise: the // suite raises no container unasked. The grace is shortened to seconds, which changes the clock and not // the rule. -func TestReplayCrashLoopIsSaidUnhealthy(t *testing.T) { +func testReplayCrashLoopIsSaidUnhealthy(t *testing.T) { name := os.Getenv("MESH_REPLAY_CONTAINER") if name == "" && os.Getenv("MESH_REPLAY_RUNTIME") != "1" { t.Skip("no MESH_REPLAY_CONTAINER, and MESH_REPLAY_RUNTIME is not 1: this replay raises a container") @@ -111,7 +111,7 @@ const ( // of two looks and a TCP check beside it. MESH_REPLAY_STATEMENT, when set, is where the statement is written // for the controller's half (mesh-controller TestReplaySilentWebAppIsRaisedWithinTwoLooks). The container is // removed after, whatever happened. -func TestReplaySilentWebAppIsSaidUnhealthy(t *testing.T) { +func testReplaySilentWebAppIsSaidUnhealthy(t *testing.T) { if os.Getenv("MESH_REPLAY_RUNTIME") != "1" && os.Getenv("MESH_REPLAY_CONTAINER") == "" { t.Skip("no MESH_REPLAY_CONTAINER, and MESH_REPLAY_RUNTIME is not 1: this replay raises a container") } @@ -202,3 +202,9 @@ func TestReplaySilentWebAppIsSaidUnhealthy(t *testing.T) { } } } + +// TestReplay runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestReplay(t *testing.T) { + t.Run("ReplayCrashLoopIsSaidUnhealthy", testReplayCrashLoopIsSaidUnhealthy) + t.Run("ReplaySilentWebAppIsSaidUnhealthy", testReplaySilentWebAppIsSaidUnhealthy) +} diff --git a/internal/liveness/waiting_test.go b/internal/liveness/waiting_test.go index 29a5378b..db3646c4 100644 --- a/internal/liveness/waiting_test.go +++ b/internal/liveness/waiting_test.go @@ -58,7 +58,7 @@ func next(t *testing.T, j *Judge, c *clock, by time.Duration) State { return stateOf(t, st, "mounts.watch") } -func TestAToolThatWaitsIsStatedWaitingWithItsWaitsInsideTheGrace(t *testing.T) { +func testAToolThatWaitsIsStatedWaitingWithItsWaitsInsideTheGrace(t *testing.T) { answer := answerOf(t, health.Waiting("the source games waits for its password", password)) j, c := toolJudge(t, &answer) s := next(t, j, c, 0) @@ -71,7 +71,7 @@ func TestAToolThatWaitsIsStatedWaitingWithItsWaitsInsideTheGrace(t *testing.T) { } } -func TestAToolThatWaitsStaysWaitingAfterTheGraceAndIsNoFailingLook(t *testing.T) { +func testAToolThatWaitsStaysWaitingAfterTheGraceAndIsNoFailingLook(t *testing.T) { answer := answerOf(t, health.Waiting("waits", password)) j, c := toolJudge(t, &answer) for i := 0; i < 5; i++ { @@ -81,7 +81,7 @@ func TestAToolThatWaitsStaysWaitingAfterTheGraceAndIsNoFailingLook(t *testing.T) } } -func TestTheNextHealthyAnswerAfterAWaitIsHealthy(t *testing.T) { +func testTheNextHealthyAnswerAfterAWaitIsHealthy(t *testing.T) { answer := answerOf(t, health.Waiting("waits", password)) j, c := toolJudge(t, &answer) next(t, j, c, 2*time.Minute) @@ -91,7 +91,7 @@ func TestTheNextHealthyAnswerAfterAWaitIsHealthy(t *testing.T) { } } -func TestAnUnhealthyAnswerAfterAWaitFollowsTheFailingLooks(t *testing.T) { +func testAnUnhealthyAnswerAfterAWaitFollowsTheFailingLooks(t *testing.T) { answer := answerOf(t, health.Waiting("waits", password)) j, c := toolJudge(t, &answer) next(t, j, c, 2*time.Minute) @@ -105,7 +105,7 @@ func TestAnUnhealthyAnswerAfterAWaitFollowsTheFailingLooks(t *testing.T) { } } -func TestAnAnswerWithoutStateIsJudgedAsBefore(t *testing.T) { +func testAnAnswerWithoutStateIsJudgedAsBefore(t *testing.T) { answer := []byte(`{"healthy":false,"why":"down"}`) j, c := toolJudge(t, &answer) next(t, j, c, 2*time.Minute) @@ -118,7 +118,7 @@ func TestAnAnswerWithoutStateIsJudgedAsBefore(t *testing.T) { } } -func TestAMalformedWaitIsUnhealthyAndExcusesNothing(t *testing.T) { +func testAMalformedWaitIsUnhealthyAndExcusesNothing(t *testing.T) { answer := []byte(`{"state":"waits","healthy":false,"why":"it waits","waits":[{"part":"p","what":"the password"}]}`) j, c := toolJudge(t, &answer) next(t, j, c, 2*time.Minute) @@ -130,7 +130,7 @@ func TestAMalformedWaitIsUnhealthyAndExcusesNothing(t *testing.T) { // A pass from before a wait is not kept through it: passed, waited, then one failing look after the grace is // not healthy. -func TestAPassBeforeAWaitIsNotKeptThroughIt(t *testing.T) { +func testAPassBeforeAWaitIsNotKeptThroughIt(t *testing.T) { answer := answerOf(t, health.Healthy("ok")) j, c := toolJudge(t, &answer) if s := next(t, j, c, 0); s.State != Healthy { @@ -145,7 +145,7 @@ func TestAPassBeforeAWaitIsNotKeptThroughIt(t *testing.T) { } // A resource that is down is down, whatever its last look said it waits for. -func TestDownBeatsAWait(t *testing.T) { +func testDownBeatsAWait(t *testing.T) { answer := answerOf(t, health.Waiting("waits", password)) j, c, rt, _ := toolJudgeAt(t, &answer, filepath.Join(t.TempDir(), FileName)) next(t, j, c, 2*time.Minute) @@ -158,7 +158,7 @@ func TestDownBeatsAWait(t *testing.T) { } // A changed check says nothing of what the old one found waiting. -func TestAChangedCheckClearsTheWaits(t *testing.T) { +func testAChangedCheckClearsTheWaits(t *testing.T) { answer := answerOf(t, health.Waiting("waits", password)) j, c := toolJudge(t, &answer) next(t, j, c, 2*time.Minute) @@ -172,7 +172,7 @@ func TestAChangedCheckClearsTheWaits(t *testing.T) { } // The engine restarted keeps what a resource waits for, as it keeps everything else it judged. -func TestWaitsAreKeptAcrossTheEnginesRestart(t *testing.T) { +func testWaitsAreKeptAcrossTheEnginesRestart(t *testing.T) { answer := answerOf(t, health.Waiting("waits", password)) path := filepath.Join(t.TempDir(), FileName) j, c, rt, _ := toolJudgeAt(t, &answer, path) @@ -186,7 +186,7 @@ func TestWaitsAreKeptAcrossTheEnginesRestart(t *testing.T) { } // Waiting and healthy each way is a change, and so is a change of what it waits for alone. -func TestAChangeOfWaitingOrOfItsWaitsIsAChange(t *testing.T) { +func testAChangeOfWaitingOrOfItsWaitsIsAChange(t *testing.T) { answer := answerOf(t, health.Healthy("ok")) j, c := toolJudge(t, &answer) look := func(by time.Duration) bool { @@ -213,3 +213,18 @@ func TestAChangeOfWaitingOrOfItsWaitsIsAChange(t *testing.T) { t.Fatal("waiting to healthy was no change") } } + +// TestWaiting runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestWaiting(t *testing.T) { + t.Run("AToolThatWaitsIsStatedWaitingWithItsWaitsInsideTheGrace", testAToolThatWaitsIsStatedWaitingWithItsWaitsInsideTheGrace) + t.Run("AToolThatWaitsStaysWaitingAfterTheGraceAndIsNoFailingLook", testAToolThatWaitsStaysWaitingAfterTheGraceAndIsNoFailingLook) + t.Run("TheNextHealthyAnswerAfterAWaitIsHealthy", testTheNextHealthyAnswerAfterAWaitIsHealthy) + t.Run("AnUnhealthyAnswerAfterAWaitFollowsTheFailingLooks", testAnUnhealthyAnswerAfterAWaitFollowsTheFailingLooks) + t.Run("AnAnswerWithoutStateIsJudgedAsBefore", testAnAnswerWithoutStateIsJudgedAsBefore) + t.Run("AMalformedWaitIsUnhealthyAndExcusesNothing", testAMalformedWaitIsUnhealthyAndExcusesNothing) + t.Run("APassBeforeAWaitIsNotKeptThroughIt", testAPassBeforeAWaitIsNotKeptThroughIt) + t.Run("DownBeatsAWait", testDownBeatsAWait) + t.Run("AChangedCheckClearsTheWaits", testAChangedCheckClearsTheWaits) + t.Run("WaitsAreKeptAcrossTheEnginesRestart", testWaitsAreKeptAcrossTheEnginesRestart) + t.Run("AChangeOfWaitingOrOfItsWaitsIsAChange", testAChangeOfWaitingOrOfItsWaitsIsAChange) +} diff --git a/internal/network/network_test.go b/internal/network/network_test.go index 67155e70..0dd5c147 100644 --- a/internal/network/network_test.go +++ b/internal/network/network_test.go @@ -143,7 +143,7 @@ func partOf(st Statement, name string) (Part, bool) { return Part{}, false } -func TestAHealthyMachineIsSaidHealthyOnItsFirstLook(t *testing.T) { +func testAHealthyMachineIsSaidHealthyOnItsFirstLook(t *testing.T) { f := newFake(t) j := f.judge(t) st := f.look(t, j) @@ -155,7 +155,7 @@ func TestAHealthyMachineIsSaidHealthyOnItsFirstLook(t *testing.T) { } } -func TestAFileRewrittenByAVPNClientIsSaidOnTheSecondLookNamingItAndClearedWhenWrittenBack(t *testing.T) { +func testAFileRewrittenByAVPNClientIsSaidOnTheSecondLookNamingItAndClearedWhenWrittenBack(t *testing.T) { f := newFake(t) j := f.judge(t) f.look(t, j) @@ -193,7 +193,7 @@ func TestAFileRewrittenByAVPNClientIsSaidOnTheSecondLookNamingItAndClearedWhenWr } } -func TestAWriterIsNamedByWhatRunsWhenTheFileSaysNothing(t *testing.T) { +func testAWriterIsNamedByWhatRunsWhenTheFileSaysNothing(t *testing.T) { f := newFake(t) f.running = []string{"systemd", "openvpn"} j := f.judge(t) @@ -206,7 +206,7 @@ func TestAWriterIsNamedByWhatRunsWhenTheFileSaysNothing(t *testing.T) { } } -func TestALinkInPlaceOfTheFileNamesWhatItPointsAt(t *testing.T) { +func testALinkInPlaceOfTheFileNamesWhatItPointsAt(t *testing.T) { f := newFake(t) j := f.judge(t) target := filepath.Join(f.dir, "stub-resolv.conf") @@ -232,7 +232,7 @@ func TestALinkInPlaceOfTheFileNamesWhatItPointsAt(t *testing.T) { } } -func TestNothingDeclaredIsNotJudged(t *testing.T) { +func testNothingDeclaredIsNotJudged(t *testing.T) { f := newFake(t) j := f.judge(t) j.Declare("", "", false) @@ -244,7 +244,7 @@ func TestNothingDeclaredIsNotJudged(t *testing.T) { } } -func TestNXDomainForAMeshNamesIPv6AddressIsAFinding(t *testing.T) { +func testNXDomainForAMeshNamesIPv6AddressIsAFinding(t *testing.T) { f := newFake(t) f.answers["10.10.0.1|novox.internal|(IPv6)"] = Answer{Rcode: RcodeNXDomain} j := f.judge(t) @@ -257,7 +257,7 @@ func TestNXDomainForAMeshNamesIPv6AddressIsAFinding(t *testing.T) { } } -func TestAResolverThatDoesNotAnswerIsNamedAndOneLookIsNotAFinding(t *testing.T) { +func testAResolverThatDoesNotAnswerIsNamedAndOneLookIsNotAFinding(t *testing.T) { f := newFake(t) j := f.judge(t) f.wrong["10.10.0.2|novox.internal|(IPv4)"] = errors.New("no answer within 1s") @@ -278,7 +278,7 @@ func TestAResolverThatDoesNotAnswerIsNamedAndOneLookIsNotAFinding(t *testing.T) } } -func TestTheTunnelTheBusAndTheRouteAreEachSaid(t *testing.T) { +func testTheTunnelTheBusAndTheRouteAreEachSaid(t *testing.T) { f := newFake(t) j := f.judge(t) f.hub(f.now.Add(-10 * time.Minute)) @@ -297,7 +297,7 @@ func TestTheTunnelTheBusAndTheRouteAreEachSaid(t *testing.T) { } } -func TestOnTheHubAnyFreshPeerIsAHealthyTunnel(t *testing.T) { +func testOnTheHubAnyFreshPeerIsAHealthyTunnel(t *testing.T) { f := newFake(t) f.hs = "A=\t" + itoa(f.now.Add(-time.Hour).Unix()) + "\nB=\t" + itoa(f.now.Unix()) + "\nC=\t0\n" f.ips = "A=\t10.10.0.2/32\nB=\t10.10.0.3/32\nC=\t10.10.0.4/32\n" @@ -325,7 +325,7 @@ func TestOnTheHubAnyFreshPeerIsAHealthyTunnel(t *testing.T) { } } -func TestAnUnreadableTunnelIsSaidAndAMissingToolSkipsIt(t *testing.T) { +func testAnUnreadableTunnelIsSaidAndAMissingToolSkipsIt(t *testing.T) { f := newFake(t) f.wgErr = errors.New(`exec: "wg": executable file not found in $PATH`) j := f.judge(t) @@ -335,7 +335,7 @@ func TestAnUnreadableTunnelIsSaidAndAMissingToolSkipsIt(t *testing.T) { } } -func TestBetweenLooksTheLastStatementIsAnswered(t *testing.T) { +func testBetweenLooksTheLastStatementIsAnswered(t *testing.T) { f := newFake(t) var calls atomic.Int64 j := f.judge(t) @@ -352,7 +352,7 @@ func TestBetweenLooksTheLastStatementIsAnswered(t *testing.T) { } } -func TestTheWaitIsTheFilesOwn(t *testing.T) { +func testTheWaitIsTheFilesOwn(t *testing.T) { if w := waitOf(meshFile); w != time.Second { t.Fatalf("timeout:1 is %s", w) } @@ -363,7 +363,7 @@ func TestTheWaitIsTheFilesOwn(t *testing.T) { // TestAskReadsARealAnswer asks a resolver this test raises: an address for one name, none for its IPv6 // address, and no such name for another. -func TestAskReadsARealAnswer(t *testing.T) { +func testAskReadsARealAnswer(t *testing.T) { pc, err := net.ListenPacket("udp", "127.0.0.1:0") if err != nil { t.Skip("no UDP here:", err) @@ -406,7 +406,7 @@ func TestAskReadsARealAnswer(t *testing.T) { } } -func TestABackupNamedForItsWriterNamesItWhateverTheFileSays(t *testing.T) { +func testABackupNamedForItsWriterNamesItWhateverTheFileSays(t *testing.T) { f := newFake(t) j := f.judge(t) // The client renames the mesh's file aside: the backup keeps the old file's time. @@ -422,3 +422,21 @@ func TestABackupNamedForItsWriterNamesItWhateverTheFileSays(t *testing.T) { t.Fatalf("the backup did not name its writer: %+v", p) } } + +// TestNetwork runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestNetwork(t *testing.T) { + t.Run("AHealthyMachineIsSaidHealthyOnItsFirstLook", testAHealthyMachineIsSaidHealthyOnItsFirstLook) + t.Run("AFileRewrittenByAVPNClientIsSaidOnTheSecondLookNamingItAndClearedWhenWrittenBack", testAFileRewrittenByAVPNClientIsSaidOnTheSecondLookNamingItAndClearedWhenWrittenBack) + t.Run("AWriterIsNamedByWhatRunsWhenTheFileSaysNothing", testAWriterIsNamedByWhatRunsWhenTheFileSaysNothing) + t.Run("ALinkInPlaceOfTheFileNamesWhatItPointsAt", testALinkInPlaceOfTheFileNamesWhatItPointsAt) + t.Run("NothingDeclaredIsNotJudged", testNothingDeclaredIsNotJudged) + t.Run("NXDomainForAMeshNamesIPv6AddressIsAFinding", testNXDomainForAMeshNamesIPv6AddressIsAFinding) + t.Run("AResolverThatDoesNotAnswerIsNamedAndOneLookIsNotAFinding", testAResolverThatDoesNotAnswerIsNamedAndOneLookIsNotAFinding) + t.Run("TheTunnelTheBusAndTheRouteAreEachSaid", testTheTunnelTheBusAndTheRouteAreEachSaid) + t.Run("OnTheHubAnyFreshPeerIsAHealthyTunnel", testOnTheHubAnyFreshPeerIsAHealthyTunnel) + t.Run("AnUnreadableTunnelIsSaidAndAMissingToolSkipsIt", testAnUnreadableTunnelIsSaidAndAMissingToolSkipsIt) + t.Run("BetweenLooksTheLastStatementIsAnswered", testBetweenLooksTheLastStatementIsAnswered) + t.Run("TheWaitIsTheFilesOwn", testTheWaitIsTheFilesOwn) + t.Run("AskReadsARealAnswer", testAskReadsARealAnswer) + t.Run("ABackupNamedForItsWriterNamesItWhateverTheFileSays", testABackupNamedForItsWriterNamesItWhateverTheFileSays) +} diff --git a/internal/outward/links_test.go b/internal/outward/links_test.go index 893a45a2..654574c8 100644 --- a/internal/outward/links_test.go +++ b/internal/outward/links_test.go @@ -27,7 +27,7 @@ func write(t *testing.T, dir, name, body string) { } } -func TestLinksAreTheOnesCarryingADefaultRoute(t *testing.T) { +func testLinksAreTheOnesCarryingADefaultRoute(t *testing.T) { dir := t.TempDir() write(t, dir, "route", routeV4) write(t, dir, "ipv6_route", routeV6) @@ -47,7 +47,7 @@ func TestLinksAreTheOnesCarryingADefaultRoute(t *testing.T) { // A route to the zero address with a real mask is not a default route. Trusting the destination // alone would name every link with such a route as facing outside, and a filter that treats an // internal bridge as outward constrains this machine's own guests — the fault ADR 0140 removes. -func TestAZeroDestinationWithAMaskIsNotADefaultRoute(t *testing.T) { +func testAZeroDestinationWithAMaskIsNotADefaultRoute(t *testing.T) { dir := t.TempDir() write(t, dir, "route", `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT br-abc 00000000 00000000 0001 0 0 0 00FFFFFF 0 0 0 @@ -64,7 +64,7 @@ br-abc 00000000 00000000 0001 0 0 0 00FFFFFF 0 0 0 // A machine with no route off itself says so, rather than guessing. The mesh refuses to compose a // filter for it; a rule written around a link with no name does not load, and a rule set that does // not load is a machine filtering nothing while its unit reports success. -func TestNoDefaultRouteIsNoLinks(t *testing.T) { +func testNoDefaultRouteIsNoLinks(t *testing.T) { dir := t.TempDir() write(t, dir, "route", "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n") got, err := Links(dir, t.TempDir()) @@ -78,7 +78,7 @@ func TestNoDefaultRouteIsNoLinks(t *testing.T) { // A machine without the second address family has no file for it. That is not a machine that cannot // be filtered, so a missing table is read as no routes rather than as a failure. -func TestAMissingTableIsNotAFailure(t *testing.T) { +func testAMissingTableIsNotAFailure(t *testing.T) { dir := t.TempDir() write(t, dir, "route", routeV4) got, err := Links(dir, t.TempDir()) @@ -91,7 +91,7 @@ func TestAMissingTableIsNotAFailure(t *testing.T) { } // The same link carrying a default route in both families is reported once. -func TestALinkIsReportedOnce(t *testing.T) { +func testALinkIsReportedOnce(t *testing.T) { dir := t.TempDir() write(t, dir, "route", routeV4) write(t, dir, "ipv6_route", @@ -108,7 +108,7 @@ func TestALinkIsReportedOnce(t *testing.T) { // Against this machine's own routing table, so the parse is held to what the kernel actually writes // and not only to a fixture written to agree with it. -func TestAgainstThisMachinesOwnTable(t *testing.T) { +func testAgainstThisMachinesOwnTable(t *testing.T) { got, err := Links("", "") if err != nil { t.Fatal(err) @@ -140,7 +140,7 @@ func sysNet(t *testing.T, physical []string, virtual []string) string { // 197). A machine on its radio with its cable unplugged reported only the radio, and the filter then // accepted everything arriving on the cable the moment it was plugged in. Bridges, veths, the tunnel // and the loopback have no device behind them and stay this machine's own. -func TestEveryPhysicalLinkFacesOutsideUpOrDown(t *testing.T) { +func testEveryPhysicalLinkFacesOutsideUpOrDown(t *testing.T) { proc := t.TempDir() write(t, proc, "route", `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT wlp5s0 00000000 01FEA8C0 0003 0 0 600 00000000 0 0 0 @@ -154,3 +154,14 @@ wlp5s0 00000000 01FEA8C0 0003 0 0 600 00000000 0 0 0 t.Fatalf("outward links are %v, want %v", got, want) } } + +// TestLinks runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestLinks(t *testing.T) { + t.Run("LinksAreTheOnesCarryingADefaultRoute", testLinksAreTheOnesCarryingADefaultRoute) + t.Run("AZeroDestinationWithAMaskIsNotADefaultRoute", testAZeroDestinationWithAMaskIsNotADefaultRoute) + t.Run("NoDefaultRouteIsNoLinks", testNoDefaultRouteIsNoLinks) + t.Run("AMissingTableIsNotAFailure", testAMissingTableIsNotAFailure) + t.Run("ALinkIsReportedOnce", testALinkIsReportedOnce) + t.Run("AgainstThisMachinesOwnTable", testAgainstThisMachinesOwnTable) + t.Run("EveryPhysicalLinkFacesOutsideUpOrDown", testEveryPhysicalLinkFacesOutsideUpOrDown) +} diff --git a/internal/outward/networks_test.go b/internal/outward/networks_test.go index 182d3a39..bdb0cf11 100644 --- a/internal/outward/networks_test.go +++ b/internal/outward/networks_test.go @@ -18,7 +18,7 @@ func prefixes(s ...string) []netip.Prefix { // **Each link facing outside says the networks it is attached to** (novox/hq ADR 0340 §7), as the // network's address and prefix, never the machine's own address on it — and every one, public and // link-local included, because which count is the controller's judgement and said with why. -func TestEachOutwardLinkSaysTheNetworksItIsOn(t *testing.T) { +func testEachOutwardLinkSaysTheNetworksItIsOn(t *testing.T) { addrs := map[string][]netip.Prefix{ "eth0": prefixes("192.168.1.10/24", "fe80::1/64", "fd12:3456:789a::5/64"), "eth1": prefixes("203.0.113.7/24"), @@ -42,7 +42,7 @@ func TestEachOutwardLinkSaysTheNetworksItIsOn(t *testing.T) { // A link whose addresses cannot be read fails the whole, so the machine says the fact is unknown rather // than reporting part of its networks as all of them. -func TestAnUnreadableLinkIsNotAPartialAccount(t *testing.T) { +func testAnUnreadableLinkIsNotAPartialAccount(t *testing.T) { _, err := Networks([]string{"eth0"}, func(string) ([]netip.Prefix, error) { return nil, errors.New("denied") }) if err == nil { t.Fatal("an unreadable link was reported as having no networks") @@ -51,9 +51,16 @@ func TestAnUnreadableLinkIsNotAPartialAccount(t *testing.T) { // A link gone between reading the routing table and reading its addresses has no networks, and the // rest are still said. -func TestALinkGoneSinceItWasListedHasNoNetworks(t *testing.T) { +func testALinkGoneSinceItWasListedHasNoNetworks(t *testing.T) { got, err := Networks([]string{"gone0"}, RealAddresses) if err != nil || len(got) != 0 { t.Fatalf("got %v, %v", got, err) } } + +// TestNetworks runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestNetworks(t *testing.T) { + t.Run("EachOutwardLinkSaysTheNetworksItIsOn", testEachOutwardLinkSaysTheNetworksItIsOn) + t.Run("AnUnreadableLinkIsNotAPartialAccount", testAnUnreadableLinkIsNotAPartialAccount) + t.Run("ALinkGoneSinceItWasListedHasNoNetworks", testALinkGoneSinceItWasListedHasNoNetworks) +} diff --git a/internal/profile/machine_test.go b/internal/profile/machine_test.go index 64c7093b..a864fd51 100644 --- a/internal/profile/machine_test.go +++ b/internal/profile/machine_test.go @@ -48,7 +48,7 @@ func given(read map[string]string) Sources { } } -func TestMachine_saysEveryFactItCanRead(t *testing.T) { +func testMachine_saysEveryFactItCanRead(t *testing.T) { m := DescribeMachine(context.Background(), given(files)) if m.KernelRelease != "7.2.8-arch1-2" || m.Distribution != "Arch Linux" || m.Version != "rolling" { @@ -93,7 +93,7 @@ func TestMachine_saysEveryFactItCanRead(t *testing.T) { } // The acceptance of issue 160: a machine that cannot determine a fact says so rather than reporting a zero. -func TestMachine_aFactItCannotReadIsSaidUnknownNeverZero(t *testing.T) { +func testMachine_aFactItCannotReadIsSaidUnknownNeverZero(t *testing.T) { src := given(map[string]string{}) src.Readlink = func(string) (string, error) { return "", os.ErrNotExist } src.Run = func(context.Context, string, ...string) (string, error) { return "", errors.New("not found") } @@ -116,7 +116,7 @@ func TestMachine_aFactItCannotReadIsSaidUnknownNeverZero(t *testing.T) { } } -func TestMachine_aHungFilesystemCannotHangTheReport(t *testing.T) { +func testMachine_aHungFilesystemCannotHangTheReport(t *testing.T) { src := given(files) block := make(chan struct{}) var asked atomic.Int32 @@ -152,7 +152,7 @@ func TestMachine_aHungFilesystemCannotHangTheReport(t *testing.T) { } } -func TestMachine_coresUnsaidAreUnknownNotGuessed(t *testing.T) { +func testMachine_coresUnsaidAreUnknownNotGuessed(t *testing.T) { p := processorOf("processor\t: 0\nModel\t: Raspberry Pi 4\nprocessor\t: 1\n") if p.model != "Raspberry Pi 4" || p.threads != 2 || p.cores != 0 || p.unknown[FactCores] == "" { t.Errorf("%+v", p) @@ -160,7 +160,7 @@ func TestMachine_coresUnsaidAreUnknownNotGuessed(t *testing.T) { } // Against the real machine (ADR 0017): what it says agrees with what this process sees. -func TestAgainstThisMachine_machineSaysWhatItIs(t *testing.T) { +func testAgainstThisMachine_machineSaysWhatItIs(t *testing.T) { if runtime.GOOS != "linux" { t.Skip("the facts are read from Linux's own files") } @@ -193,7 +193,7 @@ func TestAgainstThisMachine_machineSaysWhatItIs(t *testing.T) { // **The networks it is attached to are among its facts** (novox/hq ADR 0340 §7), every one — the public // one too, which the controller judges and never counts — and a machine with none on a link facing // outside says why rather than reporting an empty list. -func TestMachine_saysTheNetworksItIsAttachedTo(t *testing.T) { +func testMachine_saysTheNetworksItIsAttachedTo(t *testing.T) { m := DescribeMachine(context.Background(), given(files)) raw, _ := json.Marshal(m) var said struct { @@ -212,3 +212,13 @@ func TestMachine_saysTheNetworksItIsAttachedTo(t *testing.T) { t.Fatalf("a machine with no network said %v, unknown %q", m.Networks, m.Unknown[FactNetworks]) } } + +// TestMachine runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestMachine(t *testing.T) { + t.Run("Machine_saysEveryFactItCanRead", testMachine_saysEveryFactItCanRead) + t.Run("Machine_aFactItCannotReadIsSaidUnknownNeverZero", testMachine_aFactItCannotReadIsSaidUnknownNeverZero) + t.Run("Machine_aHungFilesystemCannotHangTheReport", testMachine_aHungFilesystemCannotHangTheReport) + t.Run("Machine_coresUnsaidAreUnknownNotGuessed", testMachine_coresUnsaidAreUnknownNotGuessed) + t.Run("AgainstThisMachine_machineSaysWhatItIs", testAgainstThisMachine_machineSaysWhatItIs) + t.Run("Machine_saysTheNetworksItIsAttachedTo", testMachine_saysTheNetworksItIsAttachedTo) +} diff --git a/internal/profile/power_test.go b/internal/profile/power_test.go index aebea242..7f94726c 100644 --- a/internal/profile/power_test.go +++ b/internal/profile/power_test.go @@ -35,7 +35,7 @@ func sysfs(t *testing.T) string { return dir } -func TestALaptopHasABatteryAndAMeter(t *testing.T) { +func testALaptopHasABatteryAndAMeter(t *testing.T) { dir := sysfs(t) write(t, dir+"/power_supply/ACAD/type", "Mains") write(t, dir+"/power_supply/BAT1/type", "Battery") @@ -54,7 +54,7 @@ func TestALaptopHasABatteryAndAMeter(t *testing.T) { } } -func TestADevicesBatteryIsNotTheMachines(t *testing.T) { +func testADevicesBatteryIsNotTheMachines(t *testing.T) { // The case worth a test: a desktop with a wireless mouse reports a Battery, and a battery block // composed for it would show the mouse's charge as the machine's. dir := sysfs(t) @@ -71,7 +71,7 @@ func TestADevicesBatteryIsNotTheMachines(t *testing.T) { } } -func TestADesktopMeasuresItsProcessorAndItsGraphics(t *testing.T) { +func testADesktopMeasuresItsProcessorAndItsGraphics(t *testing.T) { dir := sysfs(t) write(t, dir+"/powercap/intel-rapl:0/name", "package-0") write(t, dir+"/powercap/intel-rapl:0/energy_uj", "1") @@ -91,7 +91,7 @@ func TestADesktopMeasuresItsProcessorAndItsGraphics(t *testing.T) { } } -func TestAMachineWithNothingToReadHasNeither(t *testing.T) { +func testAMachineWithNothingToReadHasNeither(t *testing.T) { sysfs(t) b, m := battery{}.Detect(context.Background()), powerMeter{}.Detect(context.Background()) if b.Present || m.Present || b.How == "" || m.How == "" || !strings.Contains(m.Detail, "nothing") { @@ -99,7 +99,7 @@ func TestAMachineWithNothingToReadHasNeither(t *testing.T) { } } -func TestAPackageShownTwiceIsOneMeterAndIntegratedGraphicsAreNone(t *testing.T) { +func testAPackageShownTwiceIsOneMeterAndIntegratedGraphicsAreNone(t *testing.T) { dir := sysfs(t) write(t, dir+"/powercap/intel-rapl:0/name", "package-0") write(t, dir+"/powercap/intel-rapl:0/energy_uj", "1") @@ -113,7 +113,7 @@ func TestAPackageShownTwiceIsOneMeterAndIntegratedGraphicsAreNone(t *testing.T) } } -func TestOnlyIntegratedGraphicsMeasureNothing(t *testing.T) { +func testOnlyIntegratedGraphicsMeasureNothing(t *testing.T) { dir := sysfs(t) write(t, dir+"/drm/card0/device/hwmon/hwmon1/power1_input", "5000000") if m := (powerMeter{}).Detect(context.Background()); m.Present { @@ -121,7 +121,7 @@ func TestOnlyIntegratedGraphicsMeasureNothing(t *testing.T) { } } -func TestABatteryOfUnknownScopeIsTheMachines(t *testing.T) { +func testABatteryOfUnknownScopeIsTheMachines(t *testing.T) { // Many laptops' firmware says nothing of scope; the kernel reports Unknown. Only Device is a // peripheral's. dir := sysfs(t) @@ -131,3 +131,14 @@ func TestABatteryOfUnknownScopeIsTheMachines(t *testing.T) { t.Fatalf("battery: %+v", b) } } + +// TestPower runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestPower(t *testing.T) { + t.Run("ALaptopHasABatteryAndAMeter", testALaptopHasABatteryAndAMeter) + t.Run("ADevicesBatteryIsNotTheMachines", testADevicesBatteryIsNotTheMachines) + t.Run("ADesktopMeasuresItsProcessorAndItsGraphics", testADesktopMeasuresItsProcessorAndItsGraphics) + t.Run("AMachineWithNothingToReadHasNeither", testAMachineWithNothingToReadHasNeither) + t.Run("APackageShownTwiceIsOneMeterAndIntegratedGraphicsAreNone", testAPackageShownTwiceIsOneMeterAndIntegratedGraphicsAreNone) + t.Run("OnlyIntegratedGraphicsMeasureNothing", testOnlyIntegratedGraphicsMeasureNothing) + t.Run("ABatteryOfUnknownScopeIsTheMachines", testABatteryOfUnknownScopeIsTheMachines) +} diff --git a/internal/profile/profile_system_test.go b/internal/profile/profile_system_test.go index 882f1dd3..a81ba019 100644 --- a/internal/profile/profile_system_test.go +++ b/internal/profile/profile_system_test.go @@ -15,7 +15,7 @@ import ( // These do not assert WHICH capabilities this machine has; that varies per machine and is the // point of detecting. They assert that detection tells the truth about whatever is here. -func TestAgainstThisMachine_detectionAgreesWithReality(t *testing.T) { +func testAgainstThisMachine_detectionAgreesWithReality(t *testing.T) { got := Detect(context.Background(), Default(nil), 10*time.Second) if got.Architecture == "" || got.Kernel == "" { @@ -50,7 +50,7 @@ func TestAgainstThisMachine_detectionAgreesWithReality(t *testing.T) { } } -func TestAgainstThisMachine_privilegeIsReportedHonestly(t *testing.T) { +func testAgainstThisMachine_privilegeIsReportedHonestly(t *testing.T) { // The host changes machines, so whether it can is the capability that decides what the // rest of it may attempt. Reporting it wrongly in either direction is worse than not // reporting it: claimed-and-absent means work is accepted and fails, and absent-when-held @@ -75,7 +75,7 @@ func TestAgainstThisMachine_privilegeIsReportedHonestly(t *testing.T) { } } -func TestAgainstThisMachine_detectionIsBounded(t *testing.T) { +func testAgainstThisMachine_detectionIsBounded(t *testing.T) { // Every probe runs a command on a real machine. If any of them can block, the host has a // startup that sometimes never finishes — the least debuggable failure there is. start := time.Now() @@ -88,3 +88,10 @@ func TestAgainstThisMachine_detectionIsBounded(t *testing.T) { } t.Logf("detected %d capabilities in %s", len(Default(nil)), elapsed) } + +// TestProfileSystem runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestProfileSystem(t *testing.T) { + t.Run("AgainstThisMachine_detectionAgreesWithReality", testAgainstThisMachine_detectionAgreesWithReality) + t.Run("AgainstThisMachine_privilegeIsReportedHonestly", testAgainstThisMachine_privilegeIsReportedHonestly) + t.Run("AgainstThisMachine_detectionIsBounded", testAgainstThisMachine_detectionIsBounded) +} diff --git a/internal/profile/profile_test.go b/internal/profile/profile_test.go index 9c844ed7..24c3d232 100644 --- a/internal/profile/profile_test.go +++ b/internal/profile/profile_test.go @@ -13,7 +13,7 @@ import ( // machine, because a test that fakes the system under detection asserts only that the fake // behaves as expected. -func TestIssue007_installedIsNotUsable(t *testing.T) { +func testIssue007_installedIsNotUsable(t *testing.T) { // 04-ISSUES/007 — an installed package is not a capability. The client was present and the // daemon was down, and the node took work it could not do. A detector whose command fails // must report ABSENT, however installed the thing looks. @@ -38,7 +38,7 @@ func TestIssue007_installedIsNotUsable(t *testing.T) { } } -func TestEveryVerdictSaysHowItKnows(t *testing.T) { +func testEveryVerdictSaysHowItKnows(t *testing.T) { // A capability reported absent with no reason is the fault in a new place: something // nobody can act on. Both outcomes must carry a method. for _, runner := range []Runner{ @@ -56,7 +56,7 @@ func TestEveryVerdictSaysHowItKnows(t *testing.T) { } } -func TestDetectionSurvivesAFailingProbe(t *testing.T) { +func testDetectionSurvivesAFailingProbe(t *testing.T) { // Deliberately NOT ADR 0010. That rule governs APPLYING state, where a failed step means // the machine is not what was asked for. A failed probe is a finding, and aborting would // replace one legible absence with total ignorance of the rest. @@ -77,7 +77,7 @@ func TestDetectionSurvivesAFailingProbe(t *testing.T) { } } -func TestAProbeCannotHangTheHost(t *testing.T) { +func testAProbeCannotHangTheHost(t *testing.T) { // A host that blocks forever on a wedged command reports nothing at all, which is worse // than reporting the capability absent. blocking := func(ctx context.Context, name string, args ...string) (string, error) { @@ -97,7 +97,7 @@ func TestAProbeCannotHangTheHost(t *testing.T) { } } -func TestUnknownCapabilityIsAbsentNotAnError(t *testing.T) { +func testUnknownCapabilityIsAbsentNotAnError(t *testing.T) { // Asking about a capability nothing detects is a question with a true answer. p := Detect(context.Background(), nil, time.Second) if p.Has("something-nothing-detects") { @@ -105,7 +105,7 @@ func TestUnknownCapabilityIsAbsentNotAnError(t *testing.T) { } } -func TestMissingListsWhatCannotBeAskedOf(t *testing.T) { +func testMissingListsWhatCannotBeAskedOf(t *testing.T) { // What a node CANNOT do is the half that decides whether work may be placed on it. none := func(context.Context, string, ...string) (string, error) { return "", errors.New("no") } missing := Detect(context.Background(), Default(none), time.Second).Missing() @@ -120,7 +120,7 @@ func TestMissingListsWhatCannotBeAskedOf(t *testing.T) { } } -func TestTheProfileIsOrdered(t *testing.T) { +func testTheProfileIsOrdered(t *testing.T) { // Two runs on an unchanged machine produce the same profile. Without this, comparing what // a node was against what it is would report differences that are only ordering. ok := func(context.Context, string, ...string) (string, error) { return "fine", nil } @@ -138,7 +138,7 @@ func TestTheProfileIsOrdered(t *testing.T) { } } -func TestADegradedInitIsStillAnInit(t *testing.T) { +func testADegradedInitIsStillAnInit(t *testing.T) { // Found by running against a real machine, not by reasoning. `systemctl is-system-running` // exits non-zero for every state except `running` — including `degraded`, which means some // units failed and the init is emphatically present. Reading the exit code declared no @@ -164,7 +164,7 @@ func TestADegradedInitIsStillAnInit(t *testing.T) { } } -func TestAnInitThatIsNotManagingThisMachineIsAbsent(t *testing.T) { +func testAnInitThatIsNotManagingThisMachineIsAbsent(t *testing.T) { // The other side of the same rule. `offline` means it is installed and not in charge — // which must not be read as present just because a state came back. for _, state := range []string{"offline", "unknown"} { @@ -180,7 +180,7 @@ func TestAnInitThatIsNotManagingThisMachineIsAbsent(t *testing.T) { } } -func TestAFailureWithNoMessageStillCarriesAReason(t *testing.T) { +func testAFailureWithNoMessageStillCarriesAReason(t *testing.T) { // systemctl fails with empty stderr, which produced a verdict reading "exited 1:" — absent, // with nothing anyone could act on. silent := func(context.Context, string, ...string) (string, error) { return "", errors.New("") } @@ -193,3 +193,17 @@ func TestAFailureWithNoMessageStillCarriesAReason(t *testing.T) { } } } + +// TestProfile runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestProfile(t *testing.T) { + t.Run("Issue007_installedIsNotUsable", testIssue007_installedIsNotUsable) + t.Run("EveryVerdictSaysHowItKnows", testEveryVerdictSaysHowItKnows) + t.Run("DetectionSurvivesAFailingProbe", testDetectionSurvivesAFailingProbe) + t.Run("AProbeCannotHangTheHost", testAProbeCannotHangTheHost) + t.Run("UnknownCapabilityIsAbsentNotAnError", testUnknownCapabilityIsAbsentNotAnError) + t.Run("MissingListsWhatCannotBeAskedOf", testMissingListsWhatCannotBeAskedOf) + t.Run("TheProfileIsOrdered", testTheProfileIsOrdered) + t.Run("ADegradedInitIsStillAnInit", testADegradedInitIsStillAnInit) + t.Run("AnInitThatIsNotManagingThisMachineIsAbsent", testAnInitThatIsNotManagingThisMachineIsAbsent) + t.Run("AFailureWithNoMessageStillCarriesAReason", testAFailureWithNoMessageStillCarriesAReason) +} diff --git a/internal/profile/seat_test.go b/internal/profile/seat_test.go index d4034405..348b7af2 100644 --- a/internal/profile/seat_test.go +++ b/internal/profile/seat_test.go @@ -31,7 +31,7 @@ func drm(t *testing.T, connectors map[string]string) { t.Cleanup(func() { SeatSource = old }) } -func TestAMachineWithAMonitorHasASeat(t *testing.T) { +func testAMachineWithAMonitorHasASeat(t *testing.T) { drm(t, map[string]string{"card0-DP-1": "connected", "card0-HDMI-A-1": "disconnected"}) got := seat{}.Detect(context.Background()) @@ -46,7 +46,7 @@ func TestAMachineWithAMonitorHasASeat(t *testing.T) { } } -func TestAServerWithAGraphicsCardAndNoMonitorHasNoSeat(t *testing.T) { +func testAServerWithAGraphicsCardAndNoMonitorHasNoSeat(t *testing.T) { // The case this capability exists for. A display server assigned here would install, start, // and have nowhere to draw — and the mesh would have thought it succeeded. drm(t, map[string]string{"card0-HDMI-A-1": "disconnected", "card0-DP-1": "disconnected"}) @@ -62,7 +62,7 @@ func TestAServerWithAGraphicsCardAndNoMonitorHasNoSeat(t *testing.T) { } } -func TestAMachineWithNoGraphicsAtAllHasNoSeat(t *testing.T) { +func testAMachineWithNoGraphicsAtAllHasNoSeat(t *testing.T) { // A container, or a phone, where the DRM subsystem is not there to read. The ordinary answer // on most nodes and a fault on none of them, so it is a plain "no" rather than an error. old := SeatSource @@ -78,7 +78,7 @@ func TestAMachineWithNoGraphicsAtAllHasNoSeat(t *testing.T) { } } -func TestAnUnknownConnectorIsNotASeat(t *testing.T) { +func testAnUnknownConnectorIsNotASeat(t *testing.T) { // Writeback connectors and some virtual devices report "unknown". Counting those would give // a seat to machines that have none — and this workstation has one, so it is not theoretical. drm(t, map[string]string{"card0-Writeback-1": "unknown"}) @@ -88,7 +88,7 @@ func TestAnUnknownConnectorIsNotASeat(t *testing.T) { } } -func TestTheAnswerSaysHowItKnows(t *testing.T) { +func testTheAnswerSaysHowItKnows(t *testing.T) { // Every detector says how, so a wrong answer can be found rather than argued about. drm(t, map[string]string{"card0-DP-1": "connected"}) if !strings.Contains((seat{}).Detect(context.Background()).How, "status") { @@ -96,7 +96,7 @@ func TestTheAnswerSaysHowItKnows(t *testing.T) { } } -func TestASeatIsNotAGraphicalSession(t *testing.T) { +func testASeatIsNotAGraphicalSession(t *testing.T) { // The two are different questions and the whole point of adding one was that they had been // answered by the same thing. A machine can have a seat and no session — that is every // workstation before anything is installed on it, and exactly where a display server should @@ -112,3 +112,13 @@ func TestASeatIsNotAGraphicalSession(t *testing.T) { t.Fatal("a machine with no session reported one") } } + +// TestSeat runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSeat(t *testing.T) { + t.Run("AMachineWithAMonitorHasASeat", testAMachineWithAMonitorHasASeat) + t.Run("AServerWithAGraphicsCardAndNoMonitorHasNoSeat", testAServerWithAGraphicsCardAndNoMonitorHasNoSeat) + t.Run("AMachineWithNoGraphicsAtAllHasNoSeat", testAMachineWithNoGraphicsAtAllHasNoSeat) + t.Run("AnUnknownConnectorIsNotASeat", testAnUnknownConnectorIsNotASeat) + t.Run("TheAnswerSaysHowItKnows", testTheAnswerSaysHowItKnows) + t.Run("ASeatIsNotAGraphicalSession", testASeatIsNotAGraphicalSession) +} diff --git a/internal/profile/userns_test.go b/internal/profile/userns_test.go index 67a27d25..5762abf3 100644 --- a/internal/profile/userns_test.go +++ b/internal/profile/userns_test.go @@ -58,7 +58,7 @@ func verdictOf(t *testing.T, p Profile, name string) Verdict { // ExecRunner wraps stderr as " exited : ". const unshareRefused = "unshare exited 1: unshare: unshare failed: Operation not permitted" -func TestUserNamespacesAsRootDropsToAnUnprivilegedUIDFirst(t *testing.T) { +func testUserNamespacesAsRootDropsToAnUnprivilegedUIDFirst(t *testing.T) { // 1308/AC1. Root can always make a user namespace, so a probe run as root proves nothing: the // command must drop to an unprivileged uid before unshare runs. asUID(t, 0, nil) @@ -75,7 +75,7 @@ func TestUserNamespacesAsRootDropsToAnUnprivilegedUIDFirst(t *testing.T) { } } -func TestUserNamespacesAbsentCarriesTheCommandsWords(t *testing.T) { +func testUserNamespacesAbsentCarriesTheCommandsWords(t *testing.T) { // 1308/AC2. The failing probe gives absent, and the detail is what unshare said. asUID(t, 0, nil) r := &recorded{err: errors.New(unshareRefused)} @@ -93,7 +93,7 @@ func TestUserNamespacesAbsentCarriesTheCommandsWords(t *testing.T) { } } -func TestUserNamespacesAbsentSaysWhyFromTheKernelSettings(t *testing.T) { +func testUserNamespacesAbsentSaysWhyFromTheKernelSettings(t *testing.T) { // 1308/AC2, the reasons: the two kernel settings that switch user namespaces off are read // through a replaceable function and named in the detail. asUID(t, 0, map[string]string{ @@ -112,7 +112,7 @@ func TestUserNamespacesAbsentSaysWhyFromTheKernelSettings(t *testing.T) { } } -func TestUserNamespacesNotAsRootUnsharesDirectly(t *testing.T) { +func testUserNamespacesNotAsRootUnsharesDirectly(t *testing.T) { // 1308/AC3. An unprivileged node-engine is already the unprivileged user: no setpriv. asUID(t, 1000, nil) r := &recorded{} @@ -129,7 +129,7 @@ func TestUserNamespacesNotAsRootUnsharesDirectly(t *testing.T) { } } -func TestUserNamespacesProbeThatHangsIsCutAndTheRestStillReport(t *testing.T) { +func testUserNamespacesProbeThatHangsIsCutAndTheRestStillReport(t *testing.T) { // 1308/AC4. A wedged unshare is cut by Detect's timeout; the other detectors still answer. asUID(t, 0, nil) blocking := func(ctx context.Context, name string, args ...string) (string, error) { @@ -153,3 +153,12 @@ func TestUserNamespacesProbeThatHangsIsCutAndTheRestStillReport(t *testing.T) { t.Fatal("detection did not return") } } + +// TestUserns runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestUserns(t *testing.T) { + t.Run("UserNamespacesAsRootDropsToAnUnprivilegedUIDFirst", testUserNamespacesAsRootDropsToAnUnprivilegedUIDFirst) + t.Run("UserNamespacesAbsentCarriesTheCommandsWords", testUserNamespacesAbsentCarriesTheCommandsWords) + t.Run("UserNamespacesAbsentSaysWhyFromTheKernelSettings", testUserNamespacesAbsentSaysWhyFromTheKernelSettings) + t.Run("UserNamespacesNotAsRootUnsharesDirectly", testUserNamespacesNotAsRootUnsharesDirectly) + t.Run("UserNamespacesProbeThatHangsIsCutAndTheRestStillReport", testUserNamespacesProbeThatHangsIsCutAndTheRestStillReport) +} diff --git a/internal/reachable/collect_test.go b/internal/reachable/collect_test.go index 1045631e..0b92cbd6 100644 --- a/internal/reachable/collect_test.go +++ b/internal/reachable/collect_test.go @@ -28,7 +28,7 @@ func find(rs []Reach, protocol, address string, port int) (Reach, bool) { return Reach{}, false } -func TestSocketsAreReadWithWhatHoldsThem(t *testing.T) { +func testSocketsAreReadWithWhatHoldsThem(t *testing.T) { got := Sockets(fixture(t, "ss.txt")) if r, ok := find(got, "tcp", "0.0.0.0", 22); !ok || r.By != "sshd" { t.Errorf("ssh not read: %+v", r) @@ -44,7 +44,7 @@ func TestSocketsAreReadWithWhatHoldsThem(t *testing.T) { } } -func TestPublishedPortsNameTheirContainerAndItsPort(t *testing.T) { +func testPublishedPortsNameTheirContainerAndItsPort(t *testing.T) { got := Published(fixture(t, "docker-ps.txt")) if r, ok := find(got, "tcp", "0.0.0.0", 8770); !ok || r.By != "whisper" || r.ContainerPort != 8000 || !r.Published { t.Errorf("a published port: %+v", r) @@ -62,7 +62,7 @@ func TestPublishedPortsNameTheirContainerAndItsPort(t *testing.T) { } } -func TestAPublishedPortIsReportedOnceAsPublished(t *testing.T) { +func testAPublishedPortIsReportedOnceAsPublished(t *testing.T) { merged := Merge(Sockets(fixture(t, "ss.txt")), Published(fixture(t, "docker-ps.txt"))) n := 0 for _, r := range merged { @@ -81,7 +81,7 @@ func TestAPublishedPortIsReportedOnceAsPublished(t *testing.T) { } } -func TestCollectAsksSsAndTheRuntime(t *testing.T) { +func testCollectAsksSsAndTheRuntime(t *testing.T) { var asked []string run := func(_ context.Context, name string, args ...string) (string, error) { asked = append(asked, name+" "+strings.Join(args, " ")) @@ -98,3 +98,11 @@ func TestCollectAsksSsAndTheRuntime(t *testing.T) { t.Errorf("asked %v", asked) } } + +// TestCollect runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestCollect(t *testing.T) { + t.Run("SocketsAreReadWithWhatHoldsThem", testSocketsAreReadWithWhatHoldsThem) + t.Run("PublishedPortsNameTheirContainerAndItsPort", testPublishedPortsNameTheirContainerAndItsPort) + t.Run("APublishedPortIsReportedOnceAsPublished", testAPublishedPortIsReportedOnceAsPublished) + t.Run("CollectAsksSsAndTheRuntime", testCollectAsksSsAndTheRuntime) +} diff --git a/internal/selfcompose/candidate_test.go b/internal/selfcompose/candidate_test.go index ba0d54eb..791a10ed 100644 --- a/internal/selfcompose/candidate_test.go +++ b/internal/selfcompose/candidate_test.go @@ -203,7 +203,9 @@ func TestTheNodeComposesACandidateOnAsk(t *testing.T) { } return nodeengine.ComposeCandidateAnswer{Verdict: nec.Composed} } - ended := func() nodeengine.ComposeCandidateAnswer { return nodeengine.ComposeCandidateAnswer{Verdict: nec.Unready} } + ended := func() nodeengine.ComposeCandidateAnswer { + return nodeengine.ComposeCandidateAnswer{Verdict: nec.Unready} + } first := make(chan bool, 1) go func() { _, joined := runs.once(ctx, "a", compose, ended); first <- joined }() <-started diff --git a/internal/selfcompose/entries_test.go b/internal/selfcompose/entries_test.go index b0d7b36f..b50bed2b 100644 --- a/internal/selfcompose/entries_test.go +++ b/internal/selfcompose/entries_test.go @@ -360,7 +360,7 @@ func runningModuleWithoutEntryStandsAsTheNewestBuild(t *testing.T) { // The node judges a move's data forms from the entry it kept of the build it runs, though the catalog half dropped that entry and no // running event names it; and an answered entry has the composition handed again, which the agent waits on (novox, mesh-hand-acts). -func TestRunningBuildEntryKeptAndHandedAgain(t *testing.T) { +func testRunningBuildEntryKeptAndHandedAgain(t *testing.T) { old := meshcatalogclient.SourcePrefix2 + strings.Repeat("1", 64) next := meshcatalogclient.SourcePrefix2 + strings.Repeat("2", 64) env := newFakeBus().env() @@ -633,7 +633,7 @@ func TestRunningBuildEntryKeptAndHandedAgain(t *testing.T) { // A-461, A-461e: a node asks the trunk build only of what it needs of another node's placement (the store's holder, the provider // it is bound to), never of every module placed there, and beside the pass. -func TestOnlyWhatTheNodeNeedsOfAnotherNodesPlacementIsAsked(t *testing.T) { +func testOnlyWhatTheNodeNeedsOfAnotherNodesPlacementIsAsked(t *testing.T) { t.Run("a trunk build the catalog gave none of waits its backoff or a catalog-revision (A-487a)", trunkAskBackoffAndCatalogRevision) t.Run("an entry whose ask failed is asked again on each catalog-revision, at most entry-asks times, then unanswered (H-A-60, H-A-110)", entryAskedAgainThenUnanswered) env := newFakeBus().env() @@ -868,3 +868,9 @@ func entryAskedAgainThenUnanswered(t *testing.T) { t.Errorf("told %s after the answer, want the finding cleared", gotTold) } } + +// TestEntries runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestEntries(t *testing.T) { + t.Run("RunningBuildEntryKeptAndHandedAgain", testRunningBuildEntryKeptAndHandedAgain) + t.Run("OnlyWhatTheNodeNeedsOfAnotherNodesPlacementIsAsked", testOnlyWhatTheNodeNeedsOfAnotherNodesPlacementIsAsked) +} diff --git a/internal/selfcompose/selfcompose_test.go b/internal/selfcompose/selfcompose_test.go index ed6c9be8..69d67094 100644 --- a/internal/selfcompose/selfcompose_test.go +++ b/internal/selfcompose/selfcompose_test.go @@ -209,7 +209,7 @@ func quiet(t *testing.T, out <-chan agent.Update) { // Issue 1126 (ADR 0547 §2): the node composes its wanted modules and its own composition from its inputs on the bus once // every input was read, hands each, then Caught; an input that changes nothing composed hands nothing; a module no want // names any more is taken back; a node that cannot compose says so once and hands nothing. -func TestTheNodeComposesItsWantsFromTheBus(t *testing.T) { +func testTheNodeComposesItsWantsFromTheBus(t *testing.T) { t.Run("it reads the catalog half by the fingerprints its wants name", composeFromEntries) t.Run("a running module without an entry stands as the newest build", runningModuleWithoutEntryStandsAsTheNewestBuild) t.Run("a want naming its version is resolved through the registry seats", aWantNamingItsVersionIsResolvedThroughTheRegistrySeats) @@ -1836,7 +1836,7 @@ func (r fixedReader) Served(context.Context, string, string, []string) (map[stri // counts the module as run inside its own composition (issue 1126, review round 2): a failed have that names nothing // it runs (NotComposed before the module ever ran) is not, so the next composition does not take the module from its // manifest past its build. -func TestAHaveSaysWhetherItsModuleRunsInsideTheNodesOwn(t *testing.T) { +func testAHaveSaysWhetherItsModuleRunsInsideTheNodesOwn(t *testing.T) { for _, row := range []struct { name string have nodeengine.HaveByNodeModuleValue @@ -1918,7 +1918,7 @@ func (g *namedGate) Status() seatlist.Status { // ADR 0636 §1: a node that has not read the seat list composes nothing new of a module whose seats are not bootstrapped, // says it holds the module (so its have says why) and hands it at the read, which the reader says as an event; what // already runs with the same composition is not held. -func TestAnUnreadSeatListHoldsWhatIsNewAndHandsItAtTheRead(t *testing.T) { +func testAnUnreadSeatListHoldsWhatIsNewAndHandsItAtTheRead(t *testing.T) { b := newFakeBus() fp := meshcatalogclient.SourcePrefix2 + strings.Repeat("a", 64) digest := meshcatalogclient.ManifestDigest([]byte(lemurs)) @@ -2062,7 +2062,7 @@ func TestAnUnreadSeatListHoldsWhatIsNewAndHandsItAtTheRead(t *testing.T) { } } -func TestAHeldOwnCompositionThatWasHandedIsNotDropped(t *testing.T) { +func testAHeldOwnCompositionThatWasHandedIsNotDropped(t *testing.T) { b := newFakeBus() fp := meshcatalogclient.SourcePrefix2 + strings.Repeat("a", 64) digest := meshcatalogclient.ManifestDigest([]byte(lemurs)) @@ -2129,7 +2129,7 @@ func TestAHeldOwnCompositionThatWasHandedIsNotDropped(t *testing.T) { // a node whose new own composition must start the holder of the seat mesh-catalog composes of it, whatever the list says, // the holder's resources and its account and nothing else, over what the node's own composition ran before; and the rest // of the new one is handed once the list was read. -func TestAnUnreadSeatListLetsThroughOfTheOwnCompositionOnlyWhatTheHolderOfTheCatalogNeeds(t *testing.T) { +func testAnUnreadSeatListLetsThroughOfTheOwnCompositionOnlyWhatTheHolderOfTheCatalogNeeds(t *testing.T) { catalog := `{"module":"catalog","version":"1","claims":[{"name":"` + meshcatalog.Seat + `"}]}` other := `{"module":"other","version":"1","claims":[{"name":"node-files"}]}` c := New(newFakeBus().env()) @@ -2177,7 +2177,7 @@ func TestAnUnreadSeatListLetsThroughOfTheOwnCompositionOnlyWhatTheHolderOfTheCat // ADR 0636 §1, the whole case: a node that runs two modules inside its own composition (a build of the old form each), // one of them the holder of the seat mesh-catalog, and reads no seat list. Its own composition, handed before the read, // carries the holder; the read, said as an event, hands the rest, the other module's resources, with no timer. -func TestTheHolderOfTheCatalogIsStartedFromTheOwnCompositionBeforeTheListIsReadAndTheRestAfter(t *testing.T) { +func testTheHolderOfTheCatalogIsStartedFromTheOwnCompositionBeforeTheListIsReadAndTheRestAfter(t *testing.T) { catalog := `{"module":"catalog","version":"1","claims":[{"name":"` + meshcatalog.Seat + `"}],"capabilities":["systemd"],` + `"resources":[{"id":"service","type":"service","unit":"catalog.service","state":"running","boot":"enabled"}]}` other := `{"module":"other","version":"1","capabilities":["systemd"],` + @@ -2260,7 +2260,7 @@ func TestTheHolderOfTheCatalogIsStartedFromTheOwnCompositionBeforeTheListIsReadA } // ADR 0636 §1: a reader the node could not start is no reader that gates nothing: the node holds like one that waits. -func TestACompositionHoldsWhenTheSeatListReaderCouldNotStart(t *testing.T) { +func testACompositionHoldsWhenTheSeatListReaderCouldNotStart(t *testing.T) { gate := Unread{} c := New(newFakeBus().env()) comps := map[string]compositions.Composed{"n1.node": {Node: "n1"}} @@ -2295,3 +2295,14 @@ func (b *patternBus) putAssigned(vals map[string][]byte, rev uint64) { b.put(buckets.Assignments, k, vals[k], rev) } } + +// TestSelfcompose runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSelfcompose(t *testing.T) { + t.Run("TheNodeComposesItsWantsFromTheBus", testTheNodeComposesItsWantsFromTheBus) + t.Run("AHaveSaysWhetherItsModuleRunsInsideTheNodesOwn", testAHaveSaysWhetherItsModuleRunsInsideTheNodesOwn) + t.Run("AnUnreadSeatListHoldsWhatIsNewAndHandsItAtTheRead", testAnUnreadSeatListHoldsWhatIsNewAndHandsItAtTheRead) + t.Run("AHeldOwnCompositionThatWasHandedIsNotDropped", testAHeldOwnCompositionThatWasHandedIsNotDropped) + t.Run("AnUnreadSeatListLetsThroughOfTheOwnCompositionOnlyWhatTheHolderOfTheCatalogNeeds", testAnUnreadSeatListLetsThroughOfTheOwnCompositionOnlyWhatTheHolderOfTheCatalogNeeds) + t.Run("TheHolderOfTheCatalogIsStartedFromTheOwnCompositionBeforeTheListIsReadAndTheRestAfter", testTheHolderOfTheCatalogIsStartedFromTheOwnCompositionBeforeTheListIsReadAndTheRestAfter) + t.Run("ACompositionHoldsWhenTheSeatListReaderCouldNotStart", testACompositionHoldsWhenTheSeatListReaderCouldNotStart) +} diff --git a/internal/store/declared_test.go b/internal/store/declared_test.go index 4d36a0f6..863fadea 100644 --- a/internal/store/declared_test.go +++ b/internal/store/declared_test.go @@ -22,7 +22,7 @@ func signedBy(t *testing.T, body string) (ed25519.PublicKey, Declared) { } } -func TestNothingDeclaredIsNotAFault(t *testing.T) { +func testNothingDeclaredIsNotAFault(t *testing.T) { // A node that has enrolled and not yet been assigned anything has nothing to hold its machine // to, and that is an ordinary state — different from having lost what it was told. public, _ := signedBy(t, "{}") @@ -32,7 +32,7 @@ func TestNothingDeclaredIsNotAFault(t *testing.T) { } } -func TestWhatWasKeptIsWhatComesBack(t *testing.T) { +func testWhatWasKeptIsWhatComesBack(t *testing.T) { path := DeclaredPath(filepath.Join(t.TempDir(), "state.json")) public, d := signedBy(t, `{"declaration":1,"resources":[]}`) if err := SaveDeclared(path, d); err != nil { @@ -48,7 +48,7 @@ func TestWhatWasKeptIsWhatComesBack(t *testing.T) { } } -func TestWhatWasKeptIsVerifiedAgainOnLoad(t *testing.T) { +func testWhatWasKeptIsVerifiedAgainOnLoad(t *testing.T) { // This file is on a machine, and a node reading it back unverified would apply whatever is in // it. Anyone able to write it already has root — but the check costs nothing, and it means // the file is trusted for the same reason the message was rather than for being local. @@ -75,7 +75,7 @@ func TestWhatWasKeptIsVerifiedAgainOnLoad(t *testing.T) { } } -func TestAnotherMeshsDeclarationIsRefused(t *testing.T) { +func testAnotherMeshsDeclarationIsRefused(t *testing.T) { // The same check answers a second question: this node now believes a different signing key, // so what it kept is not this mesh's. Applying it would be applying something nobody in this // mesh said. @@ -95,7 +95,7 @@ func TestAnotherMeshsDeclarationIsRefused(t *testing.T) { } } -func TestWhatWasKeptIsNotWorldReadable(t *testing.T) { +func testWhatWasKeptIsNotWorldReadable(t *testing.T) { path := DeclaredPath(filepath.Join(t.TempDir(), "state.json")) _, d := signedBy(t, `{"declaration":1}`) if err := SaveDeclared(path, d); err != nil { @@ -110,7 +110,7 @@ func TestWhatWasKeptIsNotWorldReadable(t *testing.T) { } } -func TestKeepingLeavesNoHalfWrittenFile(t *testing.T) { +func testKeepingLeavesNoHalfWrittenFile(t *testing.T) { dir := t.TempDir() path := DeclaredPath(filepath.Join(dir, "state.json")) _, d := signedBy(t, `{"declaration":1}`) @@ -130,7 +130,7 @@ func TestKeepingLeavesNoHalfWrittenFile(t *testing.T) { } } -func TestAnEmptyDeclarationIsNotKept(t *testing.T) { +func testAnEmptyDeclarationIsNotKept(t *testing.T) { // It would read back as an instruction to own nothing, and a node that acted on it would // remove everything the mesh had given it. path := DeclaredPath(filepath.Join(t.TempDir(), "state.json")) @@ -138,3 +138,14 @@ func TestAnEmptyDeclarationIsNotKept(t *testing.T) { t.Fatal("an empty declaration was kept") } } + +// TestDeclared runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestDeclared(t *testing.T) { + t.Run("NothingDeclaredIsNotAFault", testNothingDeclaredIsNotAFault) + t.Run("WhatWasKeptIsWhatComesBack", testWhatWasKeptIsWhatComesBack) + t.Run("WhatWasKeptIsVerifiedAgainOnLoad", testWhatWasKeptIsVerifiedAgainOnLoad) + t.Run("AnotherMeshsDeclarationIsRefused", testAnotherMeshsDeclarationIsRefused) + t.Run("WhatWasKeptIsNotWorldReadable", testWhatWasKeptIsNotWorldReadable) + t.Run("KeepingLeavesNoHalfWrittenFile", testKeepingLeavesNoHalfWrittenFile) + t.Run("AnEmptyDeclarationIsNotKept", testAnEmptyDeclarationIsNotKept) +} diff --git a/internal/store/store_test.go b/internal/store/store_test.go index d6501710..86b44f3a 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -8,7 +8,7 @@ import ( "time" ) -func TestAFreshMachineHasAnEmptyStateNotAnError(t *testing.T) { +func testAFreshMachineHasAnEmptyStateNotAnError(t *testing.T) { // The first apply on a machine that has never been touched is the ordinary case, not a // failure. A host that errored here could never bootstrap anything. s, err := Load(filepath.Join(t.TempDir(), "nothing-here.json")) @@ -20,7 +20,7 @@ func TestAFreshMachineHasAnEmptyStateNotAnError(t *testing.T) { } } -func TestAnUnreadableStateIsRefusedNotIgnored(t *testing.T) { +func testAnUnreadableStateIsRefusedNotIgnored(t *testing.T) { // The dangerous one. Starting empty would make the host believe it owns nothing, so it // would remove nothing it should and re-apply everything it need not — silently. path := filepath.Join(t.TempDir(), "state.json") @@ -36,7 +36,7 @@ func TestAnUnreadableStateIsRefusedNotIgnored(t *testing.T) { } } -func TestWhatIsSavedIsWhatIsLoaded(t *testing.T) { +func testWhatIsSavedIsWhatIsLoaded(t *testing.T) { path := filepath.Join(t.TempDir(), "state.json") want := State{Resources: []Applied{ {ID: "etc", Type: "directory", Target: "/etc/mesh", AppliedAt: time.Now().UTC().Truncate(time.Second)}, @@ -57,7 +57,7 @@ func TestWhatIsSavedIsWhatIsLoaded(t *testing.T) { } } -func TestTheStateIsNotWorldReadable(t *testing.T) { +func testTheStateIsNotWorldReadable(t *testing.T) { // It records what is on the machine and where. Not secret, and not everyone's business. path := filepath.Join(t.TempDir(), "state.json") if err := Save(path, State{Resources: []Applied{{ID: "a", Type: "file", Target: "/a"}}}); err != nil { @@ -72,7 +72,7 @@ func TestTheStateIsNotWorldReadable(t *testing.T) { } } -func TestSavingLeavesNoDebrisBehind(t *testing.T) { +func testSavingLeavesNoDebrisBehind(t *testing.T) { // The write is atomic through a temporary file. A run that left those behind would fill a // directory with near-copies of the truth, and the next reader would have to guess. dir := t.TempDir() @@ -155,7 +155,7 @@ func TestSavingLeavesNoDebrisBehind(t *testing.T) { }) } -func TestRecordReplacesRatherThanDuplicating(t *testing.T) { +func testRecordReplacesRatherThanDuplicating(t *testing.T) { s := State{} s.Record(Applied{ID: "a", Type: "file", Target: "/old"}) s.Record(Applied{ID: "a", Type: "file", Target: "/new"}) @@ -168,7 +168,7 @@ func TestRecordReplacesRatherThanDuplicating(t *testing.T) { } } -func TestOrphansAreWhatWasAppliedAndIsNoLongerDeclared(t *testing.T) { +func testOrphansAreWhatWasAppliedAndIsNoLongerDeclared(t *testing.T) { // The whole reason the store arrives at stage 2 rather than stage 3: removal is impossible // without knowing what was applied. s := State{Resources: []Applied{ @@ -188,14 +188,14 @@ func TestOrphansAreWhatWasAppliedAndIsNoLongerDeclared(t *testing.T) { } } -func TestNothingIsAnOrphanWhenEverythingIsDeclared(t *testing.T) { +func testNothingIsAnOrphanWhenEverythingIsDeclared(t *testing.T) { s := State{Resources: []Applied{{ID: "a", Type: "file", Target: "/a"}}} if got := s.Orphans(map[string]bool{"a": true}, OriginCarried); len(got) != 0 { t.Errorf("a declared resource was treated as an orphan: %+v", got) } } -func TestADeclarationDoesNotOrphanWhatTheBundleRaised(t *testing.T) { +func testADeclarationDoesNotOrphanWhatTheBundleRaised(t *testing.T) { // 04-ISSUES/010. A first node raises its foundation from the bundle it carries, then enrols // and is sent a declaration naming two resources. Before origins, that removed the store, the // broker and the control plane that had sent it — the mesh deleting itself over the link the @@ -218,7 +218,7 @@ func TestADeclarationDoesNotOrphanWhatTheBundleRaised(t *testing.T) { } } -func TestTheBundleDoesNotOrphanWhatTheMeshDeclared(t *testing.T) { +func testTheBundleDoesNotOrphanWhatTheMeshDeclared(t *testing.T) { // The same rule the other way. A host reconciling its carried bundle must not remove what the // mesh assigned to this node, or every restart would undo the node's actual work. s := State{Resources: []Applied{ @@ -232,7 +232,7 @@ func TestTheBundleDoesNotOrphanWhatTheMeshDeclared(t *testing.T) { } } -func TestStateWrittenBeforeOriginsExistedIsTreatedAsCarried(t *testing.T) { +func testStateWrittenBeforeOriginsExistedIsTreatedAsCarried(t *testing.T) { // Every resource a host had applied before this field existed came from its bundle, because // there was no other way to tell it anything. Guessing the other way would have the first // declaration remove the foundation — which is the fault this exists to prevent, arriving @@ -246,3 +246,18 @@ func TestStateWrittenBeforeOriginsExistedIsTreatedAsCarried(t *testing.T) { t.Error("the bundle cannot remove its own resource, so nothing could ever remove it") } } + +// TestStore runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestStore(t *testing.T) { + t.Run("AFreshMachineHasAnEmptyStateNotAnError", testAFreshMachineHasAnEmptyStateNotAnError) + t.Run("AnUnreadableStateIsRefusedNotIgnored", testAnUnreadableStateIsRefusedNotIgnored) + t.Run("WhatIsSavedIsWhatIsLoaded", testWhatIsSavedIsWhatIsLoaded) + t.Run("TheStateIsNotWorldReadable", testTheStateIsNotWorldReadable) + t.Run("SavingLeavesNoDebrisBehind", testSavingLeavesNoDebrisBehind) + t.Run("RecordReplacesRatherThanDuplicating", testRecordReplacesRatherThanDuplicating) + t.Run("OrphansAreWhatWasAppliedAndIsNoLongerDeclared", testOrphansAreWhatWasAppliedAndIsNoLongerDeclared) + t.Run("NothingIsAnOrphanWhenEverythingIsDeclared", testNothingIsAnOrphanWhenEverythingIsDeclared) + t.Run("ADeclarationDoesNotOrphanWhatTheBundleRaised", testADeclarationDoesNotOrphanWhatTheBundleRaised) + t.Run("TheBundleDoesNotOrphanWhatTheMeshDeclared", testTheBundleDoesNotOrphanWhatTheMeshDeclared) + t.Run("StateWrittenBeforeOriginsExistedIsTreatedAsCarried", testStateWrittenBeforeOriginsExistedIsTreatedAsCarried) +} diff --git a/internal/system/arch_install_test.go b/internal/system/arch_install_test.go index 66678794..e2f7e98a 100644 --- a/internal/system/arch_install_test.go +++ b/internal/system/arch_install_test.go @@ -38,7 +38,7 @@ func pacmanFailing(stdout, stderr string) Runner { } } -func TestAStaleDatabaseIsSaidAsOneWithItsAgeAndTheRemedy(t *testing.T) { +func testAStaleDatabaseIsSaidAsOneWithItsAgeAndTheRemedy(t *testing.T) { was := syncDatabaseAge defer func() { syncDatabaseAge = was }() syncDatabaseAge = func() string { @@ -66,7 +66,7 @@ func TestAStaleDatabaseIsSaidAsOneWithItsAgeAndTheRemedy(t *testing.T) { } // The same 404s read from stderr alone — the half this classifier used to be blind to. -func TestTheClassifierReadsWhatPacmanWroteToStderr(t *testing.T) { +func testTheClassifierReadsWhatPacmanWroteToStderr(t *testing.T) { if classifyInstallFailure(staleStderr) != installStale { t.Fatal("every mirror 404ing the named file is a stale database") } @@ -78,7 +78,7 @@ func TestTheClassifierReadsWhatPacmanWroteToStderr(t *testing.T) { } } -func TestAnUnreachableMirrorWithAFreshDatabaseIsAMirrorProblem(t *testing.T) { +func testAnUnreachableMirrorWithAFreshDatabaseIsAMirrorProblem(t *testing.T) { was := syncDatabaseAge defer func() { syncDatabaseAge = was }() syncDatabaseAge = func() string { return "from 2026-10-02, less than a day old" } @@ -94,14 +94,14 @@ error: failed to synchronize all databases (failed to retrieve some files)` } } -func TestAFailureThatIsNeitherKeepsPacmansWords(t *testing.T) { +func testAFailureThatIsNeitherKeepsPacmansWords(t *testing.T) { err := arch{}.InstallPackage(context.Background(), pacmanFailing("", "error: target not found: nodejsx"), "nodejsx") if err == nil || !strings.Contains(err.Error(), "target not found") || strings.Contains(err.Error(), "package database on this machine") { t.Errorf("an unknown package is pacman's own error, not a stale database:\n%v", err) } } -func TestDescribeAge(t *testing.T) { +func testDescribeAge(t *testing.T) { now := time.Date(2026, 10, 3, 0, 0, 0, 0, time.UTC) for when, want := range map[time.Time]string{ now.Add(-2 * time.Hour): "less than a day old", @@ -113,3 +113,12 @@ func TestDescribeAge(t *testing.T) { } } } + +// TestArchInstall runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestArchInstall(t *testing.T) { + t.Run("AStaleDatabaseIsSaidAsOneWithItsAgeAndTheRemedy", testAStaleDatabaseIsSaidAsOneWithItsAgeAndTheRemedy) + t.Run("TheClassifierReadsWhatPacmanWroteToStderr", testTheClassifierReadsWhatPacmanWroteToStderr) + t.Run("AnUnreachableMirrorWithAFreshDatabaseIsAMirrorProblem", testAnUnreachableMirrorWithAFreshDatabaseIsAMirrorProblem) + t.Run("AFailureThatIsNeitherKeepsPacmansWords", testAFailureThatIsNeitherKeepsPacmansWords) + t.Run("DescribeAge", testDescribeAge) +} diff --git a/internal/system/identities_test.go b/internal/system/identities_test.go index 49fbcb8d..b5258d3a 100644 --- a/internal/system/identities_test.go +++ b/internal/system/identities_test.go @@ -9,7 +9,7 @@ import ( // busybox has no usermod (novox/hq ADR 0328 §4): an account the mesh made is given its added groups with addgroup // and delgroup, and a change of its primary group is refused, saying why. -func TestBusyboxGivesAnAccountItsAddedGroupsAndRefusesAnotherPrimary(t *testing.T) { +func testBusyboxGivesAnAccountItsAddedGroupsAndRefusesAnotherPrimary(t *testing.T) { var ran []string run := func(_ context.Context, name string, args ...string) (string, error) { ran = append(ran, name+" "+strings.Join(args, " ")) @@ -39,7 +39,7 @@ func TestBusyboxGivesAnAccountItsAddedGroupsAndRefusesAnotherPrimary(t *testing. // An account is made with no home, and a change of its groups moves an old home of `/` away first: `usermod --gid` // regroups every file under the home the account owns, and under `/` that is the whole machine. -func TestAnAccountsGroupsChangeOnlyWithNoHome(t *testing.T) { +func testAnAccountsGroupsChangeOnlyWithNoHome(t *testing.T) { var ran []string home := "/" run := func(_ context.Context, name string, args ...string) (string, error) { @@ -73,7 +73,7 @@ func TestAnAccountsGroupsChangeOnlyWithNoHome(t *testing.T) { } // busybox removes what the mesh made of an identity with deluser and delgroup. -func TestBusyboxRemovesAnAccountAndAGroup(t *testing.T) { +func testBusyboxRemovesAnAccountAndAGroup(t *testing.T) { var ran []string run := func(_ context.Context, name string, args ...string) (string, error) { ran = append(ran, name+" "+strings.Join(args, " ")) @@ -89,3 +89,10 @@ func TestBusyboxRemovesAnAccountAndAGroup(t *testing.T) { t.Fatalf("removed with: %v", ran) } } + +// TestIdentities runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestIdentities(t *testing.T) { + t.Run("BusyboxGivesAnAccountItsAddedGroupsAndRefusesAnotherPrimary", testBusyboxGivesAnAccountItsAddedGroupsAndRefusesAnotherPrimary) + t.Run("AnAccountsGroupsChangeOnlyWithNoHome", testAnAccountsGroupsChangeOnlyWithNoHome) + t.Run("BusyboxRemovesAnAccountAndAGroup", testBusyboxRemovesAnAccountAndAGroup) +} diff --git a/internal/system/lookup_exit_test.go b/internal/system/lookup_exit_test.go index 7311f06e..9978067e 100644 --- a/internal/system/lookup_exit_test.go +++ b/internal/system/lookup_exit_test.go @@ -10,7 +10,7 @@ import ( // A user that does not exist yet is "absent", in the words the host's own runner uses // ("getent exited 2"), not only Go's ("exit status 2"). Matched as text, the runner's wording read as // a user database that did not answer, and the controller's account was never created. -func TestAMissingUserIsAbsentInTheRunnersWords(t *testing.T) { +func testAMissingUserIsAbsentInTheRunnersWords(t *testing.T) { for _, words := range []string{"getent exited 2: ", "exit status 2"} { run := func(context.Context, string, ...string) (string, error) { return "", errors.New(words) } _, found, err := LookUpUser(context.Background(), run, "nobody-here") @@ -25,7 +25,7 @@ func TestAMissingUserIsAbsentInTheRunnersWords(t *testing.T) { } // The real command, through a real exit: getent's code for a key not found. -func TestAMissingUserIsAbsentFromTheRealGetent(t *testing.T) { +func testAMissingUserIsAbsentFromTheRealGetent(t *testing.T) { if _, err := exec.LookPath("getent"); err != nil { t.Skip("no getent here") } @@ -38,3 +38,9 @@ func TestAMissingUserIsAbsentFromTheRealGetent(t *testing.T) { t.Errorf("found %v, err %v; want absent", found, err) } } + +// TestLookupExit runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestLookupExit(t *testing.T) { + t.Run("AMissingUserIsAbsentInTheRunnersWords", testAMissingUserIsAbsentInTheRunnersWords) + t.Run("AMissingUserIsAbsentFromTheRealGetent", testAMissingUserIsAbsentFromTheRealGetent) +} diff --git a/internal/system/system_test.go b/internal/system/system_test.go index 3d8ccdad..b32d9e9e 100644 --- a/internal/system/system_test.go +++ b/internal/system/system_test.go @@ -49,7 +49,7 @@ func sys(t *testing.T, name string) System { return s } -func TestEverySystemIsNamedAndReachable(t *testing.T) { +func testEverySystemIsNamedAndReachable(t *testing.T) { for _, want := range []string{"arch", "alpine", "android"} { if _, err := For(want); err != nil { t.Errorf("the %s host cannot be built: %v", want, err) @@ -68,7 +68,7 @@ func TestEverySystemIsNamedAndReachable(t *testing.T) { // --- what each system can do ----------------------------------------------------------------- -func TestAndroidRefusesTheShapesItCannotDo(t *testing.T) { +func testAndroidRefusesTheShapesItCannotDo(t *testing.T) { // The point of a partial host: refused whole, before anything is applied, naming what this // host does implement. Not attempted-and-failed half way through. d, err := declaration.ParseTrusted([]byte(`{"declaration":1,"resources":[ @@ -90,7 +90,7 @@ func TestAndroidRefusesTheShapesItCannotDo(t *testing.T) { } } -func TestAndroidAcceptsThePortableShapes(t *testing.T) { +func testAndroidAcceptsThePortableShapes(t *testing.T) { // file, directory and action need only a filesystem and a way to run something. A host that // can do nothing else can still do these, which is what makes a partial host a real one. d, err := declaration.ParseTrusted([]byte(`{"declaration":1,"resources":[ @@ -106,7 +106,7 @@ func TestAndroidAcceptsThePortableShapes(t *testing.T) { } } -func TestArchAndAlpineDoEveryShape(t *testing.T) { +func testArchAndAlpineDoEveryShape(t *testing.T) { for _, name := range []string{"arch", "alpine"} { s := sys(t, name) for _, shape := range everyShape() { @@ -119,7 +119,7 @@ func TestArchAndAlpineDoEveryShape(t *testing.T) { // --- confirming the machine is the one the host was built for -------------------------------- -func TestAHostOnTheWrongMachineSaysSo(t *testing.T) { +func testAHostOnTheWrongMachineSaysSo(t *testing.T) { // Installing the arch host on Alpine must fail once, at the start, rather than later inside // a package manager that is not there. alpineMachine := &recorder{answers: map[string]string{"apk info": "apk-tools-2.14.0\n"}} @@ -137,7 +137,7 @@ func TestAHostOnTheWrongMachineSaysSo(t *testing.T) { // --- packages --------------------------------------------------------------------------------- -func TestApkReportsAbsenceByEmptyOutputNotByExitCode(t *testing.T) { +func testApkReportsAbsenceByEmptyOutputNotByExitCode(t *testing.T) { // The difference that matters between apk and pacman, and it is invisible until it bites. // // pacman -Q missing -> exits NON-ZERO @@ -155,7 +155,7 @@ func TestApkReportsAbsenceByEmptyOutputNotByExitCode(t *testing.T) { } } -func TestApkFindsAnInstalledPackage(t *testing.T) { +func testApkFindsAnInstalledPackage(t *testing.T) { r := &recorder{answers: map[string]string{"apk info": "docker-24.0.7-r0\n"}} installed, err := sys(t, "alpine").PackageInstalled(context.Background(), r.run, "docker") if err != nil { @@ -166,7 +166,7 @@ func TestApkFindsAnInstalledPackage(t *testing.T) { } } -func TestABrokenPackageDatabaseIsNotReadAsNotInstalled(t *testing.T) { +func testABrokenPackageDatabaseIsNotReadAsNotInstalled(t *testing.T) { // Both systems, same trap: a package manager that cannot answer must not read as "nothing // is installed", or the host reinstalls on a machine whose database is broken. for _, name := range []string{"arch", "alpine"} { @@ -179,7 +179,7 @@ func TestABrokenPackageDatabaseIsNotReadAsNotInstalled(t *testing.T) { // --- services ---------------------------------------------------------------------------------- -func TestAServiceThatDoesNotExistIsNeverReportedStopped(t *testing.T) { +func testAServiceThatDoesNotExistIsNeverReportedStopped(t *testing.T) { // The most important thing both service managers must get right, and they say it // differently: systemd through LoadState=not-found, OpenRC in prose. for _, tc := range []struct{ name, key, out string }{ @@ -201,7 +201,7 @@ func TestAServiceThatDoesNotExistIsNeverReportedStopped(t *testing.T) { } } -func TestOpenRCStateIsReadFromItsOwnWords(t *testing.T) { +func testOpenRCStateIsReadFromItsOwnWords(t *testing.T) { for _, tc := range []struct{ out, want string }{ {" * status: started\n", "running"}, {" * status: stopped\n", "stopped"}, @@ -219,7 +219,7 @@ func TestOpenRCStateIsReadFromItsOwnWords(t *testing.T) { } } -func TestOpenRCBootStateComesFromTheRunlevel(t *testing.T) { +func testOpenRCBootStateComesFromTheRunlevel(t *testing.T) { // OpenRC has no `is-enabled`. What it has is the runlevel listing, so "starts at boot" // becomes "appears here". r := &recorder{answers: map[string]string{ @@ -237,7 +237,7 @@ func TestOpenRCBootStateComesFromTheRunlevel(t *testing.T) { } } -func TestEachSystemUsesItsOwnCommands(t *testing.T) { +func testEachSystemUsesItsOwnCommands(t *testing.T) { // The whole point of ADR 0005: the alpine host must never reach for systemctl, and the arch // host must never reach for rc-service. for _, tc := range []struct{ name, forbidden string }{ @@ -267,7 +267,7 @@ func TestEachSystemUsesItsOwnCommands(t *testing.T) { } } -func TestAndroidsUnreachableAppliersFailLoudly(t *testing.T) { +func testAndroidsUnreachableAppliersFailLoudly(t *testing.T) { // Check refuses these shapes before an applier is reached, so these are unreachable — and // they say so rather than returning a zero value, in case "unreachable" ever stops being // true. @@ -281,7 +281,7 @@ func TestAndroidsUnreachableAppliersFailLoudly(t *testing.T) { } } -func TestALoginThatIsNotThereIsAnAnswerAndABrokenDatabaseIsNot(t *testing.T) { +func testALoginThatIsNotThereIsAnAnswerAndABrokenDatabaseIsNot(t *testing.T) { // The distinction this package takes trouble over everywhere else, applied to users. A user // database that cannot be read must not be reported as "no such user" — absence read as // fact is the fault the whole host exists to prevent. @@ -304,7 +304,7 @@ func TestALoginThatIsNotThereIsAnAnswerAndABrokenDatabaseIsNot(t *testing.T) { } } -func TestALoginIsReadFromThePasswdEntry(t *testing.T) { +func testALoginIsReadFromThePasswdEntry(t *testing.T) { answering := func(context.Context, string, ...string) (string, error) { return "worker:x:1001:1001:,,,:/home/worker:/usr/bin/zsh\n", nil } @@ -317,7 +317,7 @@ func TestALoginIsReadFromThePasswdEntry(t *testing.T) { } } -func TestSomethingThatIsNotAPasswdEntryIsRefused(t *testing.T) { +func testSomethingThatIsNotAPasswdEntryIsRefused(t *testing.T) { // Rather than read as a login with empty fields, which would have the host decide the shell // differs and set it on every apply for ever. nonsense := func(context.Context, string, ...string) (string, error) { @@ -328,7 +328,7 @@ func TestSomethingThatIsNotAPasswdEntryIsRefused(t *testing.T) { } } -func TestAPartialHostRefusesUsersAndAllowsArchives(t *testing.T) { +func testAPartialHostRefusesUsersAndAllowsArchives(t *testing.T) { // An archive needs a filesystem and a way to fetch; a user needs a user database this host is // allowed to write, which Android does not have. speaks := map[declaration.Type]bool{} @@ -352,7 +352,7 @@ func TestAPartialHostRefusesUsersAndAllowsArchives(t *testing.T) { // novox/hq 04-ISSUES/002: the package exists, the declaration is correct, and the machine is // asking the mirrors for a version they have already replaced. Reported as a generic install // failure it sends somebody to check the manifest, which is the one thing that is right. -func TestAStaleIndexIsNamedRatherThanReportedAsAFailedInstall(t *testing.T) { +func testAStaleIndexIsNamedRatherThanReportedAsAFailedInstall(t *testing.T) { said := "error: failed retrieving file 'dnsmasq-2.90-1-x86_64.pkg.tar.zst' from mirror.one : " + "The requested URL returned error: 404\n" + "error: failed retrieving file 'dnsmasq-2.90-1-x86_64.pkg.tar.zst' from mirror.two : " + @@ -378,7 +378,7 @@ func TestAStaleIndexIsNamedRatherThanReportedAsAFailedInstall(t *testing.T) { // An ordinary failure is not dressed up as a stale index: saying "upgrade the machine" about a // package that does not exist sends somebody to do something large and useless. -func TestAnOrdinaryInstallFailureIsNotCalledAStaleIndex(t *testing.T) { +func testAnOrdinaryInstallFailureIsNotCalledAStaleIndex(t *testing.T) { run := func(context.Context, string, ...string) (string, error) { return "error: target not found: nosuchpackage", errors.New("exit status 1") } @@ -396,7 +396,7 @@ func TestAnOrdinaryInstallFailureIsNotCalledAStaleIndex(t *testing.T) { // One mirror failing is transient and retrying is the answer. Every mirror saying the file is gone // is the index being old. -func TestOneMirrorFailingIsNotAStaleIndex(t *testing.T) { +func testOneMirrorFailingIsNotAStaleIndex(t *testing.T) { run := func(context.Context, string, ...string) (string, error) { return "warning: failed retrieving file 'x.pkg.tar.zst' from mirror.one : timeout", errors.New("exit status 1") @@ -408,9 +408,34 @@ func TestOneMirrorFailingIsNotAStaleIndex(t *testing.T) { } // And an install that works still works. -func TestAnInstallThatSucceedsSaysNothing(t *testing.T) { +func testAnInstallThatSucceedsSaysNothing(t *testing.T) { run := func(context.Context, string, ...string) (string, error) { return "installed", nil } if err := (arch{}).InstallPackage(context.Background(), run, "dnsmasq"); err != nil { t.Fatalf("a successful install reported a failure: %v", err) } } + +// TestSystem runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSystem(t *testing.T) { + t.Run("EverySystemIsNamedAndReachable", testEverySystemIsNamedAndReachable) + t.Run("AndroidRefusesTheShapesItCannotDo", testAndroidRefusesTheShapesItCannotDo) + t.Run("AndroidAcceptsThePortableShapes", testAndroidAcceptsThePortableShapes) + t.Run("ArchAndAlpineDoEveryShape", testArchAndAlpineDoEveryShape) + t.Run("AHostOnTheWrongMachineSaysSo", testAHostOnTheWrongMachineSaysSo) + t.Run("ApkReportsAbsenceByEmptyOutputNotByExitCode", testApkReportsAbsenceByEmptyOutputNotByExitCode) + t.Run("ApkFindsAnInstalledPackage", testApkFindsAnInstalledPackage) + t.Run("ABrokenPackageDatabaseIsNotReadAsNotInstalled", testABrokenPackageDatabaseIsNotReadAsNotInstalled) + t.Run("AServiceThatDoesNotExistIsNeverReportedStopped", testAServiceThatDoesNotExistIsNeverReportedStopped) + t.Run("OpenRCStateIsReadFromItsOwnWords", testOpenRCStateIsReadFromItsOwnWords) + t.Run("OpenRCBootStateComesFromTheRunlevel", testOpenRCBootStateComesFromTheRunlevel) + t.Run("EachSystemUsesItsOwnCommands", testEachSystemUsesItsOwnCommands) + t.Run("AndroidsUnreachableAppliersFailLoudly", testAndroidsUnreachableAppliersFailLoudly) + t.Run("ALoginThatIsNotThereIsAnAnswerAndABrokenDatabaseIsNot", testALoginThatIsNotThereIsAnAnswerAndABrokenDatabaseIsNot) + t.Run("ALoginIsReadFromThePasswdEntry", testALoginIsReadFromThePasswdEntry) + t.Run("SomethingThatIsNotAPasswdEntryIsRefused", testSomethingThatIsNotAPasswdEntryIsRefused) + t.Run("APartialHostRefusesUsersAndAllowsArchives", testAPartialHostRefusesUsersAndAllowsArchives) + t.Run("AStaleIndexIsNamedRatherThanReportedAsAFailedInstall", testAStaleIndexIsNamedRatherThanReportedAsAFailedInstall) + t.Run("AnOrdinaryInstallFailureIsNotCalledAStaleIndex", testAnOrdinaryInstallFailureIsNotCalledAStaleIndex) + t.Run("OneMirrorFailingIsNotAStaleIndex", testOneMirrorFailingIsNotAStaleIndex) + t.Run("AnInstallThatSucceedsSaysNothing", testAnInstallThatSucceedsSaysNothing) +} diff --git a/internal/system/usermanager_test.go b/internal/system/usermanager_test.go index 0eeb29fd..12319c05 100644 --- a/internal/system/usermanager_test.go +++ b/internal/system/usermanager_test.go @@ -11,7 +11,7 @@ import ( // novox/hq ADR 0177: whether an account's own manager runs is asked of the machine's manager, by // the account's number — never of the account's, which the question would start. -func TestAnAccountsManagerIsAskedOfTheMachinesManager(t *testing.T) { +func testAnAccountsManagerIsAskedOfTheMachinesManager(t *testing.T) { var asked []string up := false run := func(_ context.Context, name string, args ...string) (string, error) { @@ -49,7 +49,7 @@ func TestAnAccountsManagerIsAskedOfTheMachinesManager(t *testing.T) { } } -func TestLingeringIsReadFromLogindsRecordAndSetThroughLoginctl(t *testing.T) { +func testLingeringIsReadFromLogindsRecordAndSetThroughLoginctl(t *testing.T) { dir := t.TempDir() defer LingerIn(dir)() a := arch{} @@ -73,3 +73,9 @@ func TestLingeringIsReadFromLogindsRecordAndSetThroughLoginctl(t *testing.T) { t.Fatalf("%v", asked) } } + +// TestUsermanager runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestUsermanager(t *testing.T) { + t.Run("AnAccountsManagerIsAskedOfTheMachinesManager", testAnAccountsManagerIsAskedOfTheMachinesManager) + t.Run("LingeringIsReadFromLogindsRecordAndSetThroughLoginctl", testLingeringIsReadFromLogindsRecordAndSetThroughLoginctl) +} diff --git a/internal/tunnel/tunnel_test.go b/internal/tunnel/tunnel_test.go index c35ca4bd..ba92c11d 100644 --- a/internal/tunnel/tunnel_test.go +++ b/internal/tunnel/tunnel_test.go @@ -37,7 +37,7 @@ func aConfig(private string, peers ...string) string { return b.String() } -func TestTheConfigurationIsReadWhole(t *testing.T) { +func testTheConfigurationIsReadWhole(t *testing.T) { private, public := aKey(t) _, peerA := aKey(t) _, peerB := aKey(t) @@ -60,7 +60,7 @@ func TestTheConfigurationIsReadWhole(t *testing.T) { } } -func TestThePrivateKeyNeverPrintsAndNeverTravels(t *testing.T) { +func testThePrivateKeyNeverPrintsAndNeverTravels(t *testing.T) { private, _ := aKey(t) found, err := Parse([]byte(aConfig(private))) if err != nil { @@ -86,7 +86,7 @@ func TestThePrivateKeyNeverPrintsAndNeverTravels(t *testing.T) { } } -func TestATunnelWithoutWhatTheMeshNeedsIsRefused(t *testing.T) { +func testATunnelWithoutWhatTheMeshNeedsIsRefused(t *testing.T) { private, _ := aKey(t) _, peer := aKey(t) for name, conf := range map[string]string{ @@ -126,7 +126,7 @@ func (m *aMachine) read(path string) ([]byte, error) { return nil, errors.New("no such file: " + path) } -func TestTheOneTunnelUpBesidesTheMeshsIsFound(t *testing.T) { +func testTheOneTunnelUpBesidesTheMeshsIsFound(t *testing.T) { private, public := aKey(t) m := &aMachine{up: "mesh0 wg0\n", files: map[string]string{ConfigDir + "/wg0.conf": aConfig(private)}} ReadFile = m.read @@ -147,7 +147,7 @@ func TestTheOneTunnelUpBesidesTheMeshsIsFound(t *testing.T) { } } -func TestNoneUpIsAnOrdinaryAnswerAndSeveralIsAQuestion(t *testing.T) { +func testNoneUpIsAnOrdinaryAnswerAndSeveralIsAQuestion(t *testing.T) { private, _ := aKey(t) m := &aMachine{up: "mesh0\n", files: map[string]string{ ConfigDir + "/wg0.conf": aConfig(private), ConfigDir + "/wg1.conf": aConfig(private)}} @@ -171,7 +171,7 @@ func TestNoneUpIsAnOrdinaryAnswerAndSeveralIsAQuestion(t *testing.T) { } } -func TestAFoundTunnelReadsItsMTU(t *testing.T) { +func testAFoundTunnelReadsItsMTU(t *testing.T) { // A tuned path sets MTU in [Interface]; the mesh must carry it or the tunnel regresses to the // default silently (novox/hq: a taken tunnel carries its MTU). private, public := aKey(t) @@ -197,7 +197,7 @@ func TestAFoundTunnelReadsItsMTU(t *testing.T) { // novox/hq ADR 0119: a take is proven by a handshake on the mesh's interface, read from `wg show // latest-handshakes` — as wg prints it, a key and a Unix time per peer, zero for never. -func TestAHandshakeIsAPeerWithATime(t *testing.T) { +func testAHandshakeIsAPeerWithATime(t *testing.T) { cases := map[string]struct { out string want int @@ -222,7 +222,7 @@ func TestAHandshakeIsAPeerWithATime(t *testing.T) { } } -func TestHandshakesThatCannotBeAskedAreAnErrorNotAZero(t *testing.T) { +func testHandshakesThatCannotBeAskedAreAnErrorNotAZero(t *testing.T) { var asked string ok := func(_ context.Context, name string, args ...string) (string, error) { asked = name + " " + strings.Join(args, " ") @@ -240,3 +240,15 @@ func TestHandshakesThatCannotBeAskedAreAnErrorNotAZero(t *testing.T) { t.Fatalf("a machine with no wg was read as one with no handshake: %v", err) } } + +// TestTunnel runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestTunnel(t *testing.T) { + t.Run("TheConfigurationIsReadWhole", testTheConfigurationIsReadWhole) + t.Run("ThePrivateKeyNeverPrintsAndNeverTravels", testThePrivateKeyNeverPrintsAndNeverTravels) + t.Run("ATunnelWithoutWhatTheMeshNeedsIsRefused", testATunnelWithoutWhatTheMeshNeedsIsRefused) + t.Run("TheOneTunnelUpBesidesTheMeshsIsFound", testTheOneTunnelUpBesidesTheMeshsIsFound) + t.Run("NoneUpIsAnOrdinaryAnswerAndSeveralIsAQuestion", testNoneUpIsAnOrdinaryAnswerAndSeveralIsAQuestion) + t.Run("AFoundTunnelReadsItsMTU", testAFoundTunnelReadsItsMTU) + t.Run("AHandshakeIsAPeerWithATime", testAHandshakeIsAPeerWithATime) + t.Run("HandshakesThatCannotBeAskedAreAnErrorNotAZero", testHandshakesThatCannotBeAskedAreAnErrorNotAZero) +} diff --git a/internal/units/units_test.go b/internal/units/units_test.go index fa308d04..b31b01a1 100644 --- a/internal/units/units_test.go +++ b/internal/units/units_test.go @@ -114,7 +114,7 @@ func lookTwice(t *testing.T, j *Judge) Statement { return st } -func TestTheModulesAndTheMachinesFailures(t *testing.T) { +func testTheModulesAndTheMachinesFailures(t *testing.T) { r := shanks() j := New(r) j.Set(OwnedBy(declared(), nil)) @@ -140,7 +140,7 @@ func TestTheModulesAndTheMachinesFailures(t *testing.T) { } } -func TestADeclaredUnitAndAWrittenFileAreTheirModules(t *testing.T) { +func testADeclaredUnitAndAWrittenFileAreTheirModules(t *testing.T) { r := &fakeReader{ failed: map[string][]Listed{ "system": {{Unit: "mesh-power-after-boot.service", Load: "loaded"}, {Unit: "sshd.service", Load: "loaded"}}, @@ -171,7 +171,7 @@ func TestADeclaredUnitAndAWrittenFileAreTheirModules(t *testing.T) { } } -func TestTwoLooksEachWay(t *testing.T) { +func testTwoLooksEachWay(t *testing.T) { r := shanks() j := New(r) j.Set(OwnedBy(declared(), nil)) @@ -204,7 +204,7 @@ func TestTwoLooksEachWay(t *testing.T) { } } -func TestAManagerThatCannotBeReadIsUnread(t *testing.T) { +func testAManagerThatCannotBeReadIsUnread(t *testing.T) { r := shanks() j := New(r) j.Set(OwnedBy(declared(), nil)) @@ -226,7 +226,7 @@ func TestAManagerThatCannotBeReadIsUnread(t *testing.T) { t.Fatalf("a manager read again says what it held, from when it was first found: %+v", st.Failed) } -func TestNoManagerReadIsUnknown(t *testing.T) { +func testNoManagerReadIsUnknown(t *testing.T) { r := &fakeReader{unread: map[string]error{"system": errors.New("systemctl: not found"), "user:operator": errors.New("systemctl: not found")}} j := New(r) @@ -236,7 +236,7 @@ func TestNoManagerReadIsUnknown(t *testing.T) { } } -func TestAnAdoptedMachinesHoldingIsTheMachines(t *testing.T) { +func testAnAdoptedMachinesHoldingIsTheMachines(t *testing.T) { d := &declaration.Declaration{Resources: []declaration.Resource{ &declaration.Service{ID: "found.cups", Type: declaration.TypeService, Unit: "cups.service"}, }} @@ -246,7 +246,7 @@ func TestAnAdoptedMachinesHoldingIsTheMachines(t *testing.T) { } } -func TestTheReaderOnlyReads(t *testing.T) { +func testTheReaderOnlyReads(t *testing.T) { var asked []string run := func(_ context.Context, name string, args ...string) (string, error) { asked = append(asked, name+" "+strings.Join(args, " ")) @@ -294,7 +294,7 @@ func contains(args []string, s string) bool { return false } -func TestNothingIsReadBeforeADeclaration(t *testing.T) { +func testNothingIsReadBeforeADeclaration(t *testing.T) { r := shanks() j := New(r) if st, changed := j.Look(context.Background()); st.State != "" || changed { @@ -305,7 +305,7 @@ func TestNothingIsReadBeforeADeclaration(t *testing.T) { // Issue 764: a look starts no account's manager. Only an account the declaration places a user-scoped // unit for is read at all, and its manager only while the machine's says it runs. -func TestAnAccountWithNoUserUnitsIsNeverRead(t *testing.T) { +func testAnAccountWithNoUserUnitsIsNeverRead(t *testing.T) { o := OwnedBy(declared(), nil) if strings.Join(o.Accounts, " ") != "operator" { t.Fatalf("only an account with a user-scoped unit is read: %v", o.Accounts) @@ -321,7 +321,7 @@ func TestAnAccountWithNoUserUnitsIsNeverRead(t *testing.T) { } } -func TestAManagerNotRunningIsAwayAndNotRead(t *testing.T) { +func testAManagerNotRunningIsAwayAndNotRead(t *testing.T) { r := shanks() j := New(r) j.Set(OwnedBy(declared(), nil)) @@ -359,7 +359,7 @@ func TestAManagerNotRunningIsAwayAndNotRead(t *testing.T) { } } -func TestAnAccountTheMachineLacksIsUnread(t *testing.T) { +func testAnAccountTheMachineLacksIsUnread(t *testing.T) { r := shanks() r.noAccount = map[string]bool{"operator": true} j := New(r) @@ -370,7 +370,7 @@ func TestAnAccountTheMachineLacksIsUnread(t *testing.T) { } } -func TestWhetherAManagerRunsIsAskedOfTheMachines(t *testing.T) { +func testWhetherAManagerRunsIsAskedOfTheMachines(t *testing.T) { var asked []string state := "inactive" run := func(_ context.Context, name string, args ...string) (string, error) { @@ -400,3 +400,19 @@ func TestWhetherAManagerRunsIsAskedOfTheMachines(t *testing.T) { } } } + +// TestUnits runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestUnits(t *testing.T) { + t.Run("TheModulesAndTheMachinesFailures", testTheModulesAndTheMachinesFailures) + t.Run("ADeclaredUnitAndAWrittenFileAreTheirModules", testADeclaredUnitAndAWrittenFileAreTheirModules) + t.Run("TwoLooksEachWay", testTwoLooksEachWay) + t.Run("AManagerThatCannotBeReadIsUnread", testAManagerThatCannotBeReadIsUnread) + t.Run("NoManagerReadIsUnknown", testNoManagerReadIsUnknown) + t.Run("AnAdoptedMachinesHoldingIsTheMachines", testAnAdoptedMachinesHoldingIsTheMachines) + t.Run("TheReaderOnlyReads", testTheReaderOnlyReads) + t.Run("NothingIsReadBeforeADeclaration", testNothingIsReadBeforeADeclaration) + t.Run("AnAccountWithNoUserUnitsIsNeverRead", testAnAccountWithNoUserUnitsIsNeverRead) + t.Run("AManagerNotRunningIsAwayAndNotRead", testAManagerNotRunningIsAwayAndNotRead) + t.Run("AnAccountTheMachineLacksIsUnread", testAnAccountTheMachineLacksIsUnread) + t.Run("WhetherAManagerRunsIsAskedOfTheMachines", testWhetherAManagerRunsIsAskedOfTheMachines) +} diff --git a/internal/upgrade/fallback_test.go b/internal/upgrade/fallback_test.go index a738b477..fad8ece0 100644 --- a/internal/upgrade/fallback_test.go +++ b/internal/upgrade/fallback_test.go @@ -9,7 +9,7 @@ import ( // The engine placed by hand becomes a copy of the proved one when the two differ (novox/hq issue 356): the // command on PATH is the build that runs the machine. -func TestTheFallbackBecomesACopyOfTheProvedEngine(t *testing.T) { +func testTheFallbackBecomesACopyOfTheProvedEngine(t *testing.T) { dir := t.TempDir() self := filepath.Join(dir, VersionsDirName, "v2", BinaryName) if err := os.MkdirAll(filepath.Dir(self), 0o755); err != nil { @@ -59,7 +59,7 @@ func TestTheFallbackBecomesACopyOfTheProvedEngine(t *testing.T) { // An engine running from the fallback itself — nothing delivered yet — renews nothing: it would copy a file // over itself. -func TestAnEngineRunningFromTheFallbackRenewsNothing(t *testing.T) { +func testAnEngineRunningFromTheFallbackRenewsNothing(t *testing.T) { dir := t.TempDir() fallback := filepath.Join(dir, BinaryName) if err := os.WriteFile(fallback, []byte("placed by hand and running"), 0o755); err != nil { @@ -72,7 +72,7 @@ func TestAnEngineRunningFromTheFallbackRenewsNothing(t *testing.T) { } // Nothing placed by hand: the proved engine is placed, so the launcher has a fallback and the machine a command. -func TestAMissingFallbackIsPlaced(t *testing.T) { +func testAMissingFallbackIsPlaced(t *testing.T) { dir := t.TempDir() self := filepath.Join(dir, "v1", BinaryName) if err := os.MkdirAll(filepath.Dir(self), 0o755); err != nil { @@ -93,7 +93,7 @@ func TestAMissingFallbackIsPlaced(t *testing.T) { // A link at the fallback's path is refused and left as it is: the mesh creates no link and writes through none // (novox/hq ADR 0012). The link's target is untouched too. -func TestALinkAtTheFallbackIsRefusedAndLeft(t *testing.T) { +func testALinkAtTheFallbackIsRefusedAndLeft(t *testing.T) { dir := t.TempDir() self := filepath.Join(dir, "v1", BinaryName) if err := os.MkdirAll(filepath.Dir(self), 0o755); err != nil { @@ -123,7 +123,7 @@ func TestALinkAtTheFallbackIsRefusedAndLeft(t *testing.T) { } // A running engine that cannot be read is said, not copied as nothing. -func TestAnUnreadableRunningEngineIsSaid(t *testing.T) { +func testAnUnreadableRunningEngineIsSaid(t *testing.T) { dir := t.TempDir() fallback := filepath.Join(dir, BinaryName) if err := os.WriteFile(fallback, []byte("placed"), 0o755); err != nil { @@ -142,7 +142,7 @@ func TestAnUnreadableRunningEngineIsSaid(t *testing.T) { } // The fallback's path is the launcher's: its environment variable, or the default. -func TestTheFallbackPathIsTheLaunchers(t *testing.T) { +func testTheFallbackPathIsTheLaunchers(t *testing.T) { t.Setenv(FallbackVar, "") if FallbackPath() != DefaultFallback { t.Fatalf("the default is %q", FallbackPath()) @@ -155,7 +155,7 @@ func TestTheFallbackPathIsTheLaunchers(t *testing.T) { // A fallback that is not a regular file — a directory where the engine should be — is refused and left: the mesh // replaces a file, never something else at its name. -func TestAFallbackThatIsNotARegularFileIsRefused(t *testing.T) { +func testAFallbackThatIsNotARegularFileIsRefused(t *testing.T) { dir := t.TempDir() self := filepath.Join(dir, "v1", BinaryName) if err := os.MkdirAll(filepath.Dir(self), 0o755); err != nil { @@ -184,3 +184,14 @@ func TestAFallbackThatIsNotARegularFileIsRefused(t *testing.T) { t.Fatal("something was placed from a directory") } } + +// TestFallback runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestFallback(t *testing.T) { + t.Run("TheFallbackBecomesACopyOfTheProvedEngine", testTheFallbackBecomesACopyOfTheProvedEngine) + t.Run("AnEngineRunningFromTheFallbackRenewsNothing", testAnEngineRunningFromTheFallbackRenewsNothing) + t.Run("AMissingFallbackIsPlaced", testAMissingFallbackIsPlaced) + t.Run("ALinkAtTheFallbackIsRefusedAndLeft", testALinkAtTheFallbackIsRefusedAndLeft) + t.Run("AnUnreadableRunningEngineIsSaid", testAnUnreadableRunningEngineIsSaid) + t.Run("TheFallbackPathIsTheLaunchers", testTheFallbackPathIsTheLaunchers) + t.Run("AFallbackThatIsNotARegularFileIsRefused", testAFallbackThatIsNotARegularFileIsRefused) +} diff --git a/internal/upgrade/upgrade_test.go b/internal/upgrade/upgrade_test.go index ecf3e630..ac303832 100644 --- a/internal/upgrade/upgrade_test.go +++ b/internal/upgrade/upgrade_test.go @@ -25,7 +25,7 @@ func started(t *testing.T) (Self, string) { return self, binary } -func TestAnUntouchedBinaryIsNotReplaced(t *testing.T) { +func testAnUntouchedBinaryIsNotReplaced(t *testing.T) { // The case that runs every ten minutes forever. A false positive here is a node that exits // and restarts on every reconcile — a restart loop dressed as an upgrade. self, _ := started(t) @@ -39,7 +39,7 @@ func TestAnUntouchedBinaryIsNotReplaced(t *testing.T) { } } -func TestRewritingTheSameFileIsNotAReplacement(t *testing.T) { +func testRewritingTheSameFileIsNotAReplacement(t *testing.T) { // Touching content in place keeps the inode, and a package manager does not install this // way — but something else on the machine might. The claim is about identity, not content. self, binary := started(t) @@ -62,7 +62,7 @@ func TestRewritingTheSameFileIsNotAReplacement(t *testing.T) { } } -func TestInstallingOverTheBinaryIsAReplacement(t *testing.T) { +func testInstallingOverTheBinaryIsAReplacement(t *testing.T) { // What a package manager actually does: write a new file and rename it over the old one. // The running process keeps the old inode; the path now holds a different file. self, binary := started(t) @@ -85,7 +85,7 @@ func TestInstallingOverTheBinaryIsAReplacement(t *testing.T) { } } -func TestRemovingTheBinaryIsAReplacement(t *testing.T) { +func testRemovingTheBinaryIsAReplacement(t *testing.T) { // A package removed rather than upgraded. Nothing is at the path, and the honest answer is // still "not what I am running" — reporting unchanged would leave the host claiming a // version that is no longer installed. @@ -103,7 +103,7 @@ func TestRemovingTheBinaryIsAReplacement(t *testing.T) { } } -func TestNotBeingAbleToTellIsAnError(t *testing.T) { +func testNotBeingAbleToTellIsAnError(t *testing.T) { // Never a silent false. A host that cannot read its own image must say so rather than // assume it is current, which is the shape of every fault this repository catalogues. if _, err := Current(filepath.Join(t.TempDir(), "no-such-binary")); err == nil { @@ -115,7 +115,7 @@ func TestNotBeingAbleToTellIsAnError(t *testing.T) { } } -func TestKnownGoodRoundTrips(t *testing.T) { +func testKnownGoodRoundTrips(t *testing.T) { path := KnownGoodPath(filepath.Join(t.TempDir(), "state.json")) if err := RecordKnownGood(path, "1.4.2"); err != nil { @@ -130,7 +130,7 @@ func TestKnownGoodRoundTrips(t *testing.T) { } } -func TestKnownGoodIsOneBareLine(t *testing.T) { +func testKnownGoodIsOneBareLine(t *testing.T) { // The reader is a shell script on a machine where the host is failing to start. It must not // need a JSON parser, and it must not need to strip anything but a newline. path := KnownGoodPath(filepath.Join(t.TempDir(), "state.json")) @@ -151,7 +151,7 @@ func TestKnownGoodIsOneBareLine(t *testing.T) { } } -func TestNeverHavingBeenGoodIsNotAnError(t *testing.T) { +func testNeverHavingBeenGoodIsNotAnError(t *testing.T) { // A machine whose host has never completed a reconcile has nothing to go back to. That is a // real state — the node was never working — and a rollback must be able to tell it apart // from a read failure, because guessing a version is how recovery becomes a second fault. @@ -166,7 +166,7 @@ func TestNeverHavingBeenGoodIsNotAnError(t *testing.T) { } } -func TestAnEmptyVersionIsRefused(t *testing.T) { +func testAnEmptyVersionIsRefused(t *testing.T) { // An empty known-good would make the rollback script install nothing and report success — // the exact failure the rollback exists to prevent, relocated into the rollback. path := KnownGoodPath(filepath.Join(t.TempDir(), "state.json")) @@ -175,7 +175,7 @@ func TestAnEmptyVersionIsRefused(t *testing.T) { } } -func TestRecordingAgainReplacesRatherThanAppends(t *testing.T) { +func testRecordingAgainReplacesRatherThanAppends(t *testing.T) { path := KnownGoodPath(filepath.Join(t.TempDir(), "state.json")) for _, v := range []string{"1.4.2", "1.4.3", "1.5.0"} { if err := RecordKnownGood(path, v); err != nil { @@ -191,3 +191,17 @@ func TestRecordingAgainReplacesRatherThanAppends(t *testing.T) { t.Errorf("after three recordings the file says %q; it holds the last one, not a history", got) } } + +// TestUpgrade runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestUpgrade(t *testing.T) { + t.Run("AnUntouchedBinaryIsNotReplaced", testAnUntouchedBinaryIsNotReplaced) + t.Run("RewritingTheSameFileIsNotAReplacement", testRewritingTheSameFileIsNotAReplacement) + t.Run("InstallingOverTheBinaryIsAReplacement", testInstallingOverTheBinaryIsAReplacement) + t.Run("RemovingTheBinaryIsAReplacement", testRemovingTheBinaryIsAReplacement) + t.Run("NotBeingAbleToTellIsAnError", testNotBeingAbleToTellIsAnError) + t.Run("KnownGoodRoundTrips", testKnownGoodRoundTrips) + t.Run("KnownGoodIsOneBareLine", testKnownGoodIsOneBareLine) + t.Run("NeverHavingBeenGoodIsNotAnError", testNeverHavingBeenGoodIsNotAnError) + t.Run("AnEmptyVersionIsRefused", testAnEmptyVersionIsRefused) + t.Run("RecordingAgainReplacesRatherThanAppends", testRecordingAgainReplacesRatherThanAppends) +} diff --git a/internal/upgrade/versions_test.go b/internal/upgrade/versions_test.go index 03ebc628..a8629bbe 100644 --- a/internal/upgrade/versions_test.go +++ b/internal/upgrade/versions_test.go @@ -35,7 +35,7 @@ func deliver(t *testing.T, dir, version string, at time.Time) string { // A version string is whatever the source was tagged or described as, and those do not sort: "1.10" // orders before "1.9", and a commit hash orders before either. Ordering by name would start an older // host and call that an upgrade. -func TestNewestIsWhenItArrivedAndNotHowItSorts(t *testing.T) { +func testNewestIsWhenItArrivedAndNotHowItSorts(t *testing.T) { dir := t.TempDir() base := time.Now().Add(-time.Hour) deliver(t, dir, "1.10", base) // sorts LAST by name, arrived first @@ -52,7 +52,7 @@ func TestNewestIsWhenItArrivedAndNotHowItSorts(t *testing.T) { // A delivery that was interrupted leaves a directory with no executable in it. Running "the newest" // would then mean running nothing, so it is not a version. -func TestADirectoryWithNoBinaryIsNotAVersion(t *testing.T) { +func testADirectoryWithNoBinaryIsNotAVersion(t *testing.T) { dir := t.TempDir() if err := os.MkdirAll(filepath.Join(dir, "half-delivered"), 0o755); err != nil { t.Fatal(err) @@ -71,7 +71,7 @@ func TestADirectoryWithNoBinaryIsNotAVersion(t *testing.T) { // Nothing delivered is not a fault. A machine whose host was placed by hand has no versions // directory at all, and that must read as "no successor" rather than as an error that stops a // reconcile. -func TestNoVersionsDirectoryIsNotAnError(t *testing.T) { +func testNoVersionsDirectoryIsNotAnError(t *testing.T) { got, err := Versions(filepath.Join(t.TempDir(), "absent")) if err != nil { t.Fatalf("an absent versions directory should not be an error: %v", err) @@ -81,7 +81,7 @@ func TestNoVersionsDirectoryIsNotAnError(t *testing.T) { } } -func TestTheNewestVersionIsTheSuccessorAndTheRunningOneIsNot(t *testing.T) { +func testTheNewestVersionIsTheSuccessorAndTheRunningOneIsNot(t *testing.T) { dir := t.TempDir() base := time.Now().Add(-time.Hour) deliver(t, dir, "one", base) @@ -103,7 +103,7 @@ func TestTheNewestVersionIsTheSuccessorAndTheRunningOneIsNot(t *testing.T) { // A host put there by hand, before any of this existed, is not among the delivered versions. What the // mesh delivered is what it asked for, so that is a successor — otherwise the first delivery to such a // machine would be ignored for ever, which is every machine in this mesh today. -func TestAHostThatWasNeverDeliveredHasASuccessor(t *testing.T) { +func testAHostThatWasNeverDeliveredHasASuccessor(t *testing.T) { dir := t.TempDir() deliver(t, dir, "delivered", time.Now().Add(-time.Hour)) @@ -118,7 +118,7 @@ func TestAHostThatWasNeverDeliveredHasASuccessor(t *testing.T) { // The running version and its predecessor are kept, and nothing else. The predecessor is exactly what // a rollback starts; everything older has no reader. -func TestRetireKeepsTheRunningVersionAndItsPredecessor(t *testing.T) { +func testRetireKeepsTheRunningVersionAndItsPredecessor(t *testing.T) { dir := t.TempDir() base := time.Now().Add(-4 * time.Hour) for i, v := range []string{"one", "two", "three", "four"} { @@ -143,7 +143,7 @@ func TestRetireKeepsTheRunningVersionAndItsPredecessor(t *testing.T) { // **Never the running version, whatever it is asked.** A host that deleted its own image would run // until it stopped and then be unstartable, and the launcher's rollback reads a version rather than a // process. -func TestRetireNeverRemovesTheRunningVersion(t *testing.T) { +func testRetireNeverRemovesTheRunningVersion(t *testing.T) { dir := t.TempDir() base := time.Now().Add(-2 * time.Hour) deliver(t, dir, "older", base) @@ -161,7 +161,7 @@ func TestRetireNeverRemovesTheRunningVersion(t *testing.T) { // A machine running a hand-placed host keeps the newest delivered version, because that is what a // rollback would reach for. Retiring it would leave the machine with no way back at all. -func TestRetireKeepsTheNewestWhenTheRunningVersionWasNeverDelivered(t *testing.T) { +func testRetireKeepsTheNewestWhenTheRunningVersionWasNeverDelivered(t *testing.T) { dir := t.TempDir() base := time.Now().Add(-3 * time.Hour) deliver(t, dir, "old", base) @@ -178,3 +178,15 @@ func TestRetireKeepsTheNewestWhenTheRunningVersionWasNeverDelivered(t *testing.T t.Fatalf("the only delivered version was retired: %v", err) } } + +// TestVersions runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestVersions(t *testing.T) { + t.Run("NewestIsWhenItArrivedAndNotHowItSorts", testNewestIsWhenItArrivedAndNotHowItSorts) + t.Run("ADirectoryWithNoBinaryIsNotAVersion", testADirectoryWithNoBinaryIsNotAVersion) + t.Run("NoVersionsDirectoryIsNotAnError", testNoVersionsDirectoryIsNotAnError) + t.Run("TheNewestVersionIsTheSuccessorAndTheRunningOneIsNot", testTheNewestVersionIsTheSuccessorAndTheRunningOneIsNot) + t.Run("AHostThatWasNeverDeliveredHasASuccessor", testAHostThatWasNeverDeliveredHasASuccessor) + t.Run("RetireKeepsTheRunningVersionAndItsPredecessor", testRetireKeepsTheRunningVersionAndItsPredecessor) + t.Run("RetireNeverRemovesTheRunningVersion", testRetireNeverRemovesTheRunningVersion) + t.Run("RetireKeepsTheNewestWhenTheRunningVersionWasNeverDelivered", testRetireKeepsTheNewestWhenTheRunningVersionWasNeverDelivered) +} diff --git a/internal/upgrade/witnessed_test.go b/internal/upgrade/witnessed_test.go index 30d488cc..5b29c46f 100644 --- a/internal/upgrade/witnessed_test.go +++ b/internal/upgrade/witnessed_test.go @@ -12,7 +12,7 @@ import ( // The launcher's record, read as the launcher writes it: the launcher itself writes it here, so the // two cannot drift (novox/hq to-be 45 §8). -func TestTheLaunchersRecordIsReadAsTheLauncherWritesIt(t *testing.T) { +func testTheLaunchersRecordIsReadAsTheLauncherWritesIt(t *testing.T) { state := t.TempDir() libexec := t.TempDir() versions := filepath.Join(libexec, VersionsDirName) @@ -50,7 +50,7 @@ func TestTheLaunchersRecordIsReadAsTheLauncherWritesIt(t *testing.T) { // A version the launcher rolled back is never what this host stands aside for: it would be refused, // and the host would stand aside after every apply for ever. -func TestTheHostNeverStandsAsideForARolledBackVersion(t *testing.T) { +func testTheHostNeverStandsAsideForARolledBackVersion(t *testing.T) { dir := t.TempDir() base := time.Now().Add(-2 * time.Hour) deliver(t, dir, "1.0", base) @@ -66,7 +66,7 @@ func TestTheHostNeverStandsAsideForARolledBackVersion(t *testing.T) { // Nothing newer than the running version is retired: a successor waiting, or one rolled back that the // mesh still declares — either would only be delivered again. -func TestRetireNeverRemovesANewerVersion(t *testing.T) { +func testRetireNeverRemovesANewerVersion(t *testing.T) { dir := t.TempDir() base := time.Now().Add(-4 * time.Hour) for i, v := range []string{"one", "two", "three", "four"} { @@ -83,7 +83,7 @@ func TestRetireNeverRemovesANewerVersion(t *testing.T) { // Proved: known-good, the counter cleared, older versions retired, and the launcher's verdicts ended — // unless this is the version a rollback went back to, about which they still stand. -func TestProvingAHostEndsTheLaunchersVerdictsOnlyWhenItIsNewer(t *testing.T) { +func testProvingAHostEndsTheLaunchersVerdictsOnlyWhenItIsNewer(t *testing.T) { state := filepath.Join(t.TempDir(), "state.json") dir := t.TempDir() base := time.Now().Add(-4 * time.Hour) @@ -126,7 +126,7 @@ func TestProvingAHostEndsTheLaunchersVerdictsOnlyWhenItIsNewer(t *testing.T) { } // A line the launcher's record cannot be read by is named, never guessed at. -func TestAnUnreadableRecordLineIsNamed(t *testing.T) { +func testAnUnreadableRecordLineIsNamed(t *testing.T) { path := filepath.Join(t.TempDir(), RolledBackName) if err := os.WriteFile(path, []byte("2.0\t1.0\t1759744800\trolled-back\twhy\ngarbage\n"), 0o644); err != nil { t.Fatal(err) @@ -136,3 +136,12 @@ func TestAnUnreadableRecordLineIsNamed(t *testing.T) { t.Fatalf("read %+v, %v", verdicts, err) } } + +// TestWitnessed runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestWitnessed(t *testing.T) { + t.Run("TheLaunchersRecordIsReadAsTheLauncherWritesIt", testTheLaunchersRecordIsReadAsTheLauncherWritesIt) + t.Run("TheHostNeverStandsAsideForARolledBackVersion", testTheHostNeverStandsAsideForARolledBackVersion) + t.Run("RetireNeverRemovesANewerVersion", testRetireNeverRemovesANewerVersion) + t.Run("ProvingAHostEndsTheLaunchersVerdictsOnlyWhenItIsNewer", testProvingAHostEndsTheLaunchersVerdictsOnlyWhenItIsNewer) + t.Run("AnUnreadableRecordLineIsNamed", testAnUnreadableRecordLineIsNamed) +} diff --git a/internal/validate/sdk_test.go b/internal/validate/sdk_test.go index d946fff5..96518380 100644 --- a/internal/validate/sdk_test.go +++ b/internal/validate/sdk_test.go @@ -9,7 +9,7 @@ import ( ) // The SDK's validator speaks the copied parser's vocabulary version (issue 1353 AC3). -func TestVersionIsTheParsersVersion(t *testing.T) { +func testVersionIsTheParsersVersion(t *testing.T) { if Version != declaration.Version { t.Fatalf("validate.Version = %d, declaration.Version = %d", Version, declaration.Version) } @@ -17,7 +17,7 @@ func TestVersionIsTheParsersVersion(t *testing.T) { // A body of another declaration version is refused whole, by both the validator and the parser (AC3). The body is // the shape mesh-host's validate_test.go uses for its good declaration, with the version changed. -func TestAnotherVersionIsRefusedWhole(t *testing.T) { +func testAnotherVersionIsRefusedWhole(t *testing.T) { body := `{"declaration": 99, "resources": [{"id": "d", "type": "directory", "path": "/var/lib/x", "mode": "0755"}]}` problems := Declaration([]byte(body)) if len(problems) == 0 { @@ -29,3 +29,9 @@ func TestAnotherVersionIsRefusedWhole(t *testing.T) { t.Fatalf("the parser and the validator disagree: %v / %v", err, problems) } } + +// TestSdk runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestSdk(t *testing.T) { + t.Run("VersionIsTheParsersVersion", testVersionIsTheParsersVersion) + t.Run("AnotherVersionIsRefusedWhole", testAnotherVersionIsRefusedWhole) +} diff --git a/internal/witness/contract_test.go b/internal/witness/contract_test.go index 6677fe96..43b8c90e 100644 --- a/internal/witness/contract_test.go +++ b/internal/witness/contract_test.go @@ -12,7 +12,7 @@ import ( // The contract, held (novox/hq to-be 45 §8). // The runtime is asked by its own name and this machine's: only this machine's runtime can answer. -func TestTheRuntimeIsAskedByItsNameAndThisMachines(t *testing.T) { +func testTheRuntimeIsAskedByItsNameAndThisMachines(t *testing.T) { if got := link.PingSubject("runner-x", "anchor"); got != "$SRV.PING.runner-x.anchor" { t.Fatalf("the host asks %s; the runtime answers $SRV.PING.node-tools.", got) } @@ -20,7 +20,7 @@ func TestTheRuntimeIsAskedByItsNameAndThisMachines(t *testing.T) { // What is judged by default is the mesh's core process on every machine, by the name it is composed under, and // nothing else: the controller ended (issue 1126), so its name is judged as any other. -func TestOnlyTheCoreProcessIsJudgedByDefault(t *testing.T) { +func testOnlyTheCoreProcessIsJudgedByDefault(t *testing.T) { // The tool runner's process by its id and name, whatever its module is called (ADR 0601 §4); a process named so by // another id, or another process, is not. for id, want := range map[string]string{"runner-x.runtime": ByPing, "node-tools.runtime": ByNone, "runner-x.server": ByNone, @@ -35,9 +35,16 @@ func TestOnlyTheCoreProcessIsJudgedByDefault(t *testing.T) { } // A verdict on the wire names its component as the controller's condition does. -func TestAVerdictNamesItsComponent(t *testing.T) { +func testAVerdictNamesItsComponent(t *testing.T) { raw, _ := json.Marshal(link.Rollback{Component: Component(ByPing), Outcome: link.RolledBack}) if !strings.Contains(string(raw), `"component":"node-tools"`) { t.Fatalf("a verdict names its component as %s", raw) } } + +// TestContract runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestContract(t *testing.T) { + t.Run("TheRuntimeIsAskedByItsNameAndThisMachines", testTheRuntimeIsAskedByItsNameAndThisMachines) + t.Run("OnlyTheCoreProcessIsJudgedByDefault", testOnlyTheCoreProcessIsJudgedByDefault) + t.Run("AVerdictNamesItsComponent", testAVerdictNamesItsComponent) +} diff --git a/internal/witness/draining_test.go b/internal/witness/draining_test.go index 64298912..a4cb3a77 100644 --- a/internal/witness/draining_test.go +++ b/internal/witness/draining_test.go @@ -83,7 +83,7 @@ func retiredBuilds(t *testing.T, root, name string) []string { // **A build moved aside while its process runs stays reachable by that process's user, and is deleted // only once no process runs from it** (novox/hq issue 289). On 2026-10-07 the controller still serving // after its build was moved into a 0700 directory, and then deleted, could not run its own verbs. -func TestABuildIsKeptReachableAndUndeletedWhileAProcessRunsFromIt(t *testing.T) { +func testABuildIsKeptReachableAndUndeletedWhileAProcessRunsFromIt(t *testing.T) { root := t.TempDir() name := "node-tools" start := time.Date(2026, 10, 7, 2, 0, 0, 0, time.UTC) @@ -140,7 +140,7 @@ func TestABuildIsKeptReachableAndUndeletedWhileAProcessRunsFromIt(t *testing.T) } // A process whose image was deleted from under it still counts as running from where it was. -func TestAProcessRunsFromABuildDeletedUnderIt(t *testing.T) { +func testAProcessRunsFromABuildDeletedUnderIt(t *testing.T) { dir := filepath.Join(t.TempDir(), "build") proc := runFrom(t, dir) if err := os.Remove(filepath.Join(dir, "sleep")); err != nil { @@ -155,7 +155,7 @@ func TestAProcessRunsFromABuildDeletedUnderIt(t *testing.T) { } // A build on trial replaced by another is retired too: it runs until the restart stops it. -func TestABuildOnTrialReplacedIsRetiredNotDeletedUnderItsProcess(t *testing.T) { +func testABuildOnTrialReplacedIsRetiredNotDeletedUnderItsProcess(t *testing.T) { root := t.TempDir() name := "node-tools" start := time.Date(2026, 10, 7, 2, 0, 0, 0, time.UTC) @@ -182,3 +182,10 @@ func TestABuildOnTrialReplacedIsRetiredNotDeletedUnderItsProcess(t *testing.T) { t.Fatal("C should run with A kept to go back to") } } + +// TestDraining runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestDraining(t *testing.T) { + t.Run("ABuildIsKeptReachableAndUndeletedWhileAProcessRunsFromIt", testABuildIsKeptReachableAndUndeletedWhileAProcessRunsFromIt) + t.Run("AProcessRunsFromABuildDeletedUnderIt", testAProcessRunsFromABuildDeletedUnderIt) + t.Run("ABuildOnTrialReplacedIsRetiredNotDeletedUnderItsProcess", testABuildOnTrialReplacedIsRetiredNotDeletedUnderItsProcess) +} diff --git a/internal/witness/watch_test.go b/internal/witness/watch_test.go index 148b6a29..644e2bac 100644 --- a/internal/witness/watch_test.go +++ b/internal/witness/watch_test.go @@ -109,7 +109,7 @@ func look(w *Watcher, clock *time.Time, n int) { } // A runtime that starts and never answers PING: restored to the build before, once, said once. -func TestARuntimeThatNeverAnswersIsRolledBackOnce(t *testing.T) { +func testARuntimeThatNeverAnswersIsRolledBackOnce(t *testing.T) { root := t.TempDir() clock := time.Date(2026, 10, 6, 10, 0, 0, 0, time.UTC) place(t, root, "node-tools", ByPing, buildA, "", "", clock) @@ -173,7 +173,7 @@ func TestARuntimeThatNeverAnswersIsRolledBackOnce(t *testing.T) { } // A healthy update: nothing deleted before it is proved; the build before it deleted once it is. -func TestAHealthyUpdateDeletesNothingUntilItIsProved(t *testing.T) { +func testAHealthyUpdateDeletesNothingUntilItIsProved(t *testing.T) { root := t.TempDir() clock := time.Date(2026, 10, 6, 10, 0, 0, 0, time.UTC) // The runtime placed by a host from before any witness: a record, and no state. @@ -210,7 +210,7 @@ func TestAHealthyUpdateDeletesNothingUntilItIsProved(t *testing.T) { // A build declared not reversible is never rolled back: the build before never starts against what it // changed, and the verdict is urgent and stands. -func TestANotReversibleBuildIsNeverRolledBack(t *testing.T) { +func testANotReversibleBuildIsNeverRolledBack(t *testing.T) { root := t.TempDir() clock := time.Date(2026, 10, 6, 10, 0, 0, 0, time.UTC) place(t, root, "node-tools", ByPing, buildA, "", "", clock) @@ -238,7 +238,7 @@ func TestANotReversibleBuildIsNeverRolledBack(t *testing.T) { } // A witness that cannot ask counts nothing against the build, and says so at GiveUp. -func TestAWitnessThatCannotAskNeverRollsBack(t *testing.T) { +func testAWitnessThatCannotAskNeverRollsBack(t *testing.T) { root := t.TempDir() clock := time.Date(2026, 10, 6, 10, 0, 0, 0, time.UTC) place(t, root, "node-tools", ByPing, buildA, "", "", clock) @@ -275,7 +275,7 @@ func TestAWitnessThatCannotAskNeverRollsBack(t *testing.T) { } // A restoration whose build will not start is said as such — not as a rollback that worked. -func TestARestorationThatDoesNotStartIsSaid(t *testing.T) { +func testARestorationThatDoesNotStartIsSaid(t *testing.T) { root := t.TempDir() clock := time.Date(2026, 10, 6, 10, 0, 0, 0, time.UTC) place(t, root, "node-tools", ByPing, buildA, "", "", clock) @@ -290,7 +290,7 @@ func TestARestorationThatDoesNotStartIsSaid(t *testing.T) { } // What the engine keeps survives the engine: a host that stands aside mid-trial resumes it. -func TestATrialSurvivesTheHostRestarting(t *testing.T) { +func testATrialSurvivesTheHostRestarting(t *testing.T) { root := t.TempDir() clock := time.Date(2026, 10, 6, 10, 0, 0, 0, time.UTC) place(t, root, "node-tools", ByPing, buildA, "", "", clock) @@ -305,3 +305,13 @@ func TestATrialSurvivesTheHostRestarting(t *testing.T) { t.Fatalf("the bound was not carried across the host restarting: %+v", verdicts) } } + +// TestWatch runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestWatch(t *testing.T) { + t.Run("ARuntimeThatNeverAnswersIsRolledBackOnce", testARuntimeThatNeverAnswersIsRolledBackOnce) + t.Run("AHealthyUpdateDeletesNothingUntilItIsProved", testAHealthyUpdateDeletesNothingUntilItIsProved) + t.Run("ANotReversibleBuildIsNeverRolledBack", testANotReversibleBuildIsNeverRolledBack) + t.Run("AWitnessThatCannotAskNeverRollsBack", testAWitnessThatCannotAskNeverRollsBack) + t.Run("ARestorationThatDoesNotStartIsSaid", testARestorationThatDoesNotStartIsSaid) + t.Run("ATrialSurvivesTheHostRestarting", testATrialSurvivesTheHostRestarting) +} diff --git a/packaging/operator_keys_test.go b/packaging/operator_keys_test.go index 5987bbeb..27970245 100644 --- a/packaging/operator_keys_test.go +++ b/packaging/operator_keys_test.go @@ -15,7 +15,7 @@ import ( // The operator's public keys reach every node as a file beside the state file, fed by a setting of the node-engine // (novox/hq ADR 0539 clauses 3 and 11): the node agent reads it, and a composition made by hand is applied only when one // of these keys signed it. The setting may be empty, and then no operator key is trusted. -func TestTheManifestDeclaresTheOperatorKeysFileFedByASetting(t *testing.T) { +func testTheManifestDeclaresTheOperatorKeysFileFedByASetting(t *testing.T) { raw, err := os.ReadFile("../module.json") if err != nil { t.Fatal(err) @@ -57,7 +57,7 @@ func TestTheManifestDeclaresTheOperatorKeysFileFedByASetting(t *testing.T) { } // The node agent hears the end of a backup on the event of node-backup's holder, so the manifest consumes it. -func TestTheManifestConsumesTheBackupEvent(t *testing.T) { +func testTheManifestConsumesTheBackupEvent(t *testing.T) { raw, err := os.ReadFile("../module.json") if err != nil { t.Fatal(err) @@ -150,3 +150,9 @@ func TestTheManifestConsumesTheBackupEvent(t *testing.T) { t.Fatalf("the manifest declares the state %+v", parsed.State) } } + +// TestOperatorKeys runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). +func TestOperatorKeys(t *testing.T) { + t.Run("TheManifestDeclaresTheOperatorKeysFileFedByASetting", testTheManifestDeclaresTheOperatorKeysFileFedByASetting) + t.Run("TheManifestConsumesTheBackupEvent", testTheManifestConsumesTheBackupEvent) +} -- 2.54.0 From 0aff33d617e4b5b48f6e7a1f68256ea972674803 Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 00:36:33 +0100 Subject: [PATCH 15/23] Claim composition-diff among the node-engine seat's verbs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The group's node-engine seat defines composition-diff, and the engine has answered it since E5, but its claim did not name it, so the manifest validator refused the manifest: the seat's protocol promises a verb the claim does not serve. The claim serves it, and the manifest test holds the claim to every verb of the seat's contract. Builds: design 47 H2 §813 (3); H-A-349 DQ-12b, H-A-355 (2), H-A-392; mesh-contracts feat/47-H2 3fbe3361 (the seat's composition-diff) --- module.json | 1 + packaging/operator_keys_test.go | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/module.json b/module.json index 088d8463..c0ba5c01 100644 --- a/module.json +++ b/module.json @@ -29,6 +29,7 @@ "acts", "packages", "composition", + "composition-diff", "compose", "compose-candidate", "manifest-reads", diff --git a/packaging/operator_keys_test.go b/packaging/operator_keys_test.go index 27970245..6798db6c 100644 --- a/packaging/operator_keys_test.go +++ b/packaging/operator_keys_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" + "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" "git.novox.be/novox/mesh-sdk/go/catalogue" "git.novox.be/novox/mesh-sdk/go/declaration" ) @@ -126,6 +127,26 @@ func testTheManifestConsumesTheBackupEvent(t *testing.T) { } // Design 47 H2 §813 (12), H-A-388: it states the declaration Version it reads, the one its contract parses, so the // delivery plan orders the composer that writes that Version after it. + // The claim of node-engine serves every verb the seat's contract defines, composition-diff among them (the H2 K row of + // mesh-contracts, H-A-355 (2), H-A-392): a claim short of one is refused by the manifest validator. + if parsed, err := catalogue.Decode(raw); err == nil { + var serves []string + for _, c := range parsed.Claims { + if c.Name == nodeengine.Seat { + serves = c.Serves + } + } + for _, verb := range []string{nodeengine.VerbHandOver, nodeengine.VerbAccessAct, nodeengine.VerbJudgeDirectories, + nodeengine.VerbSetuidSearch, nodeengine.VerbRootFree, nodeengine.VerbActs, nodeengine.VerbPackages, + nodeengine.VerbComposition, nodeengine.VerbCompositionDiff, nodeengine.VerbCompose, nodeengine.VerbComposeCandidate, + nodeengine.VerbManifestReads, nodeengine.VerbApplyOrder, nodeengine.VerbSeatList, nodeengine.VerbSeatListAgain, + nodeengine.VerbFirstViews, nodeengine.VerbFirstViewAgain, nodeengine.VerbEntryAgain, nodeengine.VerbProcessBuilds, + nodeengine.VerbConverged} { + if !slices.Contains(serves, verb) { + t.Errorf("the claim of %s does not serve %s: %v", nodeengine.Seat, verb, serves) + } + } + } // H-A-394 (1): a module that claims a seat is core. if parsed, err := catalogue.Decode(raw); err != nil || parsed.Class != catalogue.ClassCore { t.Errorf("the manifest's class is %q, and the node-engine claims a seat (%v)", parsed.Class, err) -- 2.54.0 From 845de02631365764832565819bb610995216c870 Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 01:12:33 +0100 Subject: [PATCH 16/23] Read a module's version through the registry seats' list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit H2's registry seat definitions fold the version read into list, filtered by module, so the validator refused the engine's manifest for invoking versions. The engine reads a version as a tag in list: oci-artifact-registry by the module, every page while it says next, the blob a manifest keeps; container-image-registry, whose list takes no module, by the repository's name. The manifest invokes list, and the node grant the tests run under follows it. Builds: design 47 H2 §779, §813 (7); H-A-350 DMC-10, H-A-415 (2) --- internal/nodegrant/testdata/node.json | 4 +- internal/selfcompose/selfcompose_test.go | 10 +-- internal/selfcompose/versions.go | 92 ++++++++++++++++-------- internal/selfcompose/versions_test.go | 31 +++++--- module.json | 6 +- 5 files changed, 94 insertions(+), 49 deletions(-) diff --git a/internal/nodegrant/testdata/node.json b/internal/nodegrant/testdata/node.json index e31dcc1c..8ef3e900 100644 --- a/internal/nodegrant/testdata/node.json +++ b/internal/nodegrant/testdata/node.json @@ -117,14 +117,14 @@ "mesh.control.NODE.>", "mesh.seat.mesh-catalog.call.entry.node~NODE", "mesh.seat.mesh-catalog.call.module.node~NODE", - "mesh.seat.container-image-registry.call.versions.node~NODE", + "mesh.seat.container-image-registry.call.list.node~NODE", "mesh.seat.mesh-catalog.call.revision.node~NODE", "mesh.seat.mesh-grants.call.withheld.node~NODE", "mesh.seat.mesh-module-assigner.call.assignments.node~NODE", "mesh.seat.mesh-recovery.call.kept-points.node~NODE", "mesh.seat.mesh-recovery.call.restore-kept.node~NODE", "mesh.seat.mesh-recovery.call.snapshot-kept.node~NODE", - "mesh.seat.oci-artifact-registry.call.versions.node~NODE", + "mesh.seat.oci-artifact-registry.call.list.node~NODE", "mesh.seat.mesh-catalog.call.seat-definitions.node~NODE", "mesh.seat.node-backup.call.backed-up.NODE.node~NODE", "mesh.seat.node-backup.call.now.NODE.node~NODE", diff --git a/internal/selfcompose/selfcompose_test.go b/internal/selfcompose/selfcompose_test.go index 69d67094..4126f872 100644 --- a/internal/selfcompose/selfcompose_test.go +++ b/internal/selfcompose/selfcompose_test.go @@ -470,8 +470,8 @@ func testTheNodeComposesItsWantsFromTheBus(t *testing.T) { // resolves the digests). e.Registry = EntryCall(func(_ context.Context, seat, _ string, args any) (json.RawMessage, error) { if seat == "container-image-registry" && args.(map[string]string)["name"] == "de-spiegel/site" { - return json.RawMessage(`{"name":"de-spiegel/site","versions":[{"name":"de-spiegel/site","kind":"image","digest":"sha256:` + - strings.Repeat("6", 64) + `","version":"1"}]}`), nil + return json.RawMessage(`{"repositories":[{"name":"de-spiegel/site","manifests":[{"digest":"sha256:` + + strings.Repeat("6", 64) + `","tags":["1"]}]}]}`), nil } return nil, errors.New("not held") }) @@ -1119,9 +1119,9 @@ func testTheNodeComposesItsWantsFromTheBus(t *testing.T) { catalogEntries[artFp] = artEntry // art's files archive at version 1, which the candidate "art-with" names (the candidate's version, never a digest). senv.Registry = EntryCall(func(_ context.Context, seat, _ string, args any) (json.RawMessage, error) { - if seat == "oci-artifact-registry" && args.(map[string]string)["name"] == "art/files" { - return json.RawMessage(`{"name":"art/files","versions":[{"name":"art/files","kind":"archive","digest":"sha256:` + - strings.Repeat("9", 64) + `","version":"1"}]}`), nil + if seat == "oci-artifact-registry" && args.(map[string]string)["module"] == "art" { + return json.RawMessage(`{"repositories":[{"name":"art/files","manifests":[{"digest":"sha256:` + strings.Repeat("8", 64) + + `","artifact":"sha256:` + strings.Repeat("9", 64) + `","tags":["1"]}]}]}`), nil } return nil, errors.New("not held") }) diff --git a/internal/selfcompose/versions.go b/internal/selfcompose/versions.go index 0e4ddae3..610f6601 100644 --- a/internal/selfcompose/versions.go +++ b/internal/selfcompose/versions.go @@ -19,7 +19,7 @@ import ( // **A want names its version; the node-engine resolves the digests** (design 47 G A-430, A-430a, the lead's answer A-430b). // A want of a released build names the module's version and no parts: each artifact of the build's entry is looked up at that -// version through the verb `versions` of the registry seat of its kind (oci-artifact-registry for a bundle or an archive, +// version through the verb `list` of the registry seat of its kind (oci-artifact-registry for a bundle or an archive, // container-image-registry for an image), under the name the builder numbered it by: `/`, or the entry's // package name for a package. An upstream copy is not numbered (it is mirrored by its pinned digest): its digest is the one its // manifest's `from` pins. A want that names parts (a build no version is known of) is read by its parts as before. A lookup that @@ -37,8 +37,12 @@ func (c *Composer) resolveAgain() time.Duration { return DefaultResolveAgain } -// versionsVerb is the verb a lookup asks. -const versionsVerb = "versions" +// listVerb is the verb a lookup asks: the registry seats read a version through `list`, filtered by module on +// oci-artifact-registry (design 47 H2 §813 (7), DMC-10, H-A-415 (2)). +const listVerb = "list" + +// listPagesMost bounds the pages one lookup reads of a seat's list. +const listPagesMost = 64 // resolvedKey names one resolution: a module's build at a version. type resolvedKey struct{ module, fp, version string } @@ -53,13 +57,21 @@ type versionParts struct { forgotten bool } -// registryVersions is the answer of either seat's verb `versions`: the two seats answer the same shape. -type registryVersions struct { - Versions []struct { - Digest string `json:"digest"` - Tag string `json:"tag,omitempty"` - Version string `json:"version,omitempty"` - } `json:"versions"` +// registryList is the answer of either seat's verb `list` (form 2): each repository with the manifests it holds, each +// manifest's digest, the blob it keeps (a bundle's or an archive's) and the tags naming it; capped with next when the rest +// is on another page. +type registryList struct { + Repositories []struct { + Name string `json:"name"` + Manifests []struct { + Digest string `json:"digest"` + Artifact string `json:"artifact,omitempty"` + Tags []string `json:"tags,omitempty"` + } `json:"manifests"` + } `json:"repositories"` + Capped bool `json:"capped,omitempty"` + Total int64 `json:"total,omitempty"` + Next string `json:"next,omitempty"` } // seatOfKind is the registry seat an artifact of kind is numbered in, and whether one is (design 51 *The seats*). @@ -218,7 +230,7 @@ func (c *Composer) lookUp(module string, e meshcatalog.CatalogEntry, w meshwants fail("(none)", a.Ref, "no registry seat the node-engine reads numbers an artifact of kind "+a.Kind) continue } - digest, why := c.versionDigest(seat, registryName(module, a), w) + digest, why := c.versionDigest(seat, module, registryName(module, a), w) if why != "" { fail(seat, a.Ref, why) continue @@ -232,30 +244,52 @@ func (c *Composer) lookUp(module string, e meshcatalog.CatalogEntry, w meshwants return parts, "" } -// versionDigest is the digest the seat's verb versions answers for name at w's version (its version or its tag), the newest -// first: a version names one build (A-430a), so the version alone is matched. -func (c *Composer) versionDigest(seat, name string, w meshwants.WantsByWantNodeModuleValue) (string, string) { +// versionDigest is the digest the seat's verb list answers for the repository name at w's version, a tag naming it: a +// version names one build (A-430a). oci-artifact-registry is asked for the module's repositories (`list {module}`) and +// answers the blob a manifest keeps, the digest a bundle or an archive is fetched by; container-image-registry, whose list +// takes no module, is asked for the repository by its name and answers the image manifest's digest. Every page is read +// while the answer says next (design 47 H2 §779, §813 (7), H-A-415 (2)). +func (c *Composer) versionDigest(seat, module, name string, w meshwants.WantsByWantNodeModuleValue) (string, string) { if c.env.Registry == nil { return "", "this node-engine reads no registry seat" } - raw, err := c.env.Registry("seat:"+seat+"."+versionsVerb, map[string]string{"name": name}) - if err != nil { - return "", fmt.Sprintf("the call for %s failed: %v", name, err) + in := map[string]string{"name": name} + if seat == ociartifactregistry.Seat { + in = map[string]string{"module": module} } - answer, said, ok := buscalls.Unwrap(raw) - if !ok { - return "", fmt.Sprintf("the seat refused %s: %s", name, said) - } - var v registryVersions - if err := json.Unmarshal(answer, &v); err != nil { - return "", fmt.Sprintf("its answer for %s cannot be read: %v", name, err) - } - for _, a := range v.Versions { - if (a.Version == w.Version || a.Tag == w.Version) && a.Digest != "" { - return a.Digest, "" + for page := 0; page < listPagesMost; page++ { + raw, err := c.env.Registry("seat:"+seat+"."+listVerb, in) + if err != nil { + return "", fmt.Sprintf("the call for %s failed: %v", name, err) } + answer, said, ok := buscalls.Unwrap(raw) + if !ok { + return "", fmt.Sprintf("the seat refused %s: %s", name, said) + } + var l registryList + if err := json.Unmarshal(answer, &l); err != nil { + return "", fmt.Sprintf("its answer for %s cannot be read: %v", name, err) + } + for _, r := range l.Repositories { + if r.Name != name { + continue + } + for _, m := range r.Manifests { + if !slices.Contains(m.Tags, w.Version) || m.Digest == "" { + continue + } + if seat == ociartifactregistry.Seat && m.Artifact != "" { + return m.Artifact, "" + } + return m.Digest, "" + } + } + if l.Next == "" { + return "", fmt.Sprintf("it holds no version %s of %s", w.Version, name) + } + in["next"] = l.Next } - return "", fmt.Sprintf("it holds no version %s of %s", w.Version, name) + return "", fmt.Sprintf("its list of %s did not end within %d pages", module, listPagesMost) } // pinnedDigest is the digest the manifest's upstream artifact pins in its from (`@sha256:`); "" when none. diff --git a/internal/selfcompose/versions_test.go b/internal/selfcompose/versions_test.go index 9b2fa862..1c22e10a 100644 --- a/internal/selfcompose/versions_test.go +++ b/internal/selfcompose/versions_test.go @@ -36,11 +36,13 @@ func aWantNamingItsVersionIsResolvedThroughTheRegistrySeats(t *testing.T) { }}} entry := meshcatalog.CatalogEntry{Module: "mail", Fp: fp, Manifest: manifest, Artifacts: []meshcatalog.Artifact{ {Ref: "mail:server", Kind: "upstream"}, {Ref: "mail:files", Kind: "archive"}, {Ref: "mail:web", Kind: "image"}}} - // The seats hold mail/files and mail/web; versions newest first. + // The seats hold mail/files and mail/web, each version a tag of its manifest; an archive's blob is what it is fetched + // by (design 47 H2 §813 (7), H-A-415 (2): the version is read through list). held := map[string]string{ - "oci-artifact-registry.mail/files": `{"name":"mail/files","versions":[{"name":"mail/files","kind":"archive","digest":"` + d("2") + `","version":"1.3.0"},{"name":"mail/files","kind":"archive","digest":"` + d("1") + `","version":"1.2.3"}]}`, - "container-image-registry.mail/web": `{"name":"mail/web","versions":[{"name":"mail/web","kind":"image","digest":"` + d("3") + `","version":"1.2.3"}]}`, - "container-image-registry.mail/other": `{"name":"mail/other","versions":[]}`, + "oci-artifact-registry.mail/files": `{"name":"mail/files","manifests":[{"digest":"` + d("8") + `","artifact":"` + d("2") + + `","tags":["1.3.0"]},{"digest":"` + d("7") + `","artifact":"` + d("1") + `","tags":["1.2.3"]}]}`, + "container-image-registry.mail/web": `{"name":"mail/web","manifests":[{"digest":"` + d("3") + `","tags":["1.2.3"]}]}`, + "container-image-registry.mail/other": `{"name":"mail/other","manifests":[]}`, } for name, row := range map[string]struct { want meshwants.WantsByWantNodeModuleValue @@ -62,17 +64,25 @@ func aWantNamingItsVersionIsResolvedThroughTheRegistrySeats(t *testing.T) { calls := 0 env.Registry = EntryCall(func(_ context.Context, seat, verb string, args any) (json.RawMessage, error) { calls++ - if verb != "versions" { - t.Errorf("%s: asked %s.%s", name, seat, verb) + in := args.(map[string]string) + // oci-artifact-registry is asked by the module, container-image-registry by the repository's name. + if verb != "list" || (seat == "oci-artifact-registry") != (in["module"] == "mail" && in["name"] == "") { + t.Errorf("%s: asked %s.%s %v", name, seat, verb, in) } if seat == row.down { return nil, errors.New("no responders") } - answer, ok := held[seat+"."+args.(map[string]string)["name"]] - if !ok { + var repos []string + for key, repo := range held { + r, ok := strings.CutPrefix(key, seat+".") + if ok && (r == in["name"] || (in["module"] != "" && strings.HasPrefix(r, in["module"]+"/"))) { + repos = append(repos, repo) + } + } + if len(repos) == 0 { return nil, errors.New("not held") } - return json.RawMessage(answer), nil + return json.RawMessage(`{"repositories":[` + strings.Join(repos, ",") + `]}`), nil }) env.Entry = EntryCall(func(context.Context, string, string, any) (json.RawMessage, error) { return nil, errors.New("not asked") @@ -311,7 +321,8 @@ func aResolutionWhoseFetchFailedIsForgotten(t *testing.T) { calls := 0 env.Registry = EntryCall(func(context.Context, string, string, any) (json.RawMessage, error) { calls++ - return json.RawMessage(`{"versions":[{"digest":"` + row.answer + `","version":"1.2.3"}]}`), nil + return json.RawMessage(`{"repositories":[{"name":"mail/files","manifests":[{"digest":"sha256:` + strings.Repeat("e", 64) + + `","artifact":"` + row.answer + `","tags":["1.2.3"]}]}]}`), nil }) env.Fetch = func(context.Context, string) ([]byte, error) { return body, row.fetch } env.Entry = EntryCall(func(context.Context, string, string, any) (json.RawMessage, error) { diff --git a/module.json b/module.json index c0ba5c01..928d52f7 100644 --- a/module.json +++ b/module.json @@ -45,7 +45,7 @@ } ], "invokes": [ - "seat:container-image-registry.versions", + "seat:container-image-registry.list", "seat:mesh-catalog.entry", "seat:mesh-catalog.module", {"verb": "seat:mesh-catalog.revision", "fields": ["none-yet"]}, @@ -56,7 +56,7 @@ "seat:mesh-recovery.restore-kept", "seat:mesh-recovery.snapshot-kept", "seat:node-packet-filter.allowed", - "seat:oci-artifact-registry.versions" + "seat:oci-artifact-registry.list" ], "consumes": [ "mesh-catalog.catalog-revision", @@ -125,7 +125,7 @@ }, "resolve-again-minutes": { "type": "number", - "description": "How long the node-engine holds a module whose want's version it could not resolve to its artifacts' digests, or whose resolution it forgot after a failed fetch, before it asks the registry seats' verb versions again, in minutes (design 47 H, H-A-146).", + "description": "How long the node-engine holds a module whose want's version it could not resolve to its artifacts' digests, or whose resolution it forgot after a failed fetch, before it asks the registry seats' verb list again, in minutes (design 47 H, H-A-146).", "minimum": 1, "maximum": 60, "default": 1 -- 2.54.0 From 9d0ca8e954bc6c1769d18aaefd2528210af1fca1 Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 01:13:44 +0100 Subject: [PATCH 17/23] State the declaration Version the engine's composer writes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The composer is the node-engine's own build, its declarations written by mesh-sdk's composition inside it, so the manifest states the Version it writes beside the one it reads; the manifest test holds both to the engine's declaration Version. Builds: design 47 H2 §813 (12); H-A-416 (2) --- module.json | 1 + packaging/operator_keys_test.go | 8 +++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/module.json b/module.json index 928d52f7..ee50160c 100644 --- a/module.json +++ b/module.json @@ -4,6 +4,7 @@ "slug": "host", "class": "core", "declaration-reads": 2, + "declaration-writes": 2, "build": { "artifacts": [ { diff --git a/packaging/operator_keys_test.go b/packaging/operator_keys_test.go index 6798db6c..95628fa0 100644 --- a/packaging/operator_keys_test.go +++ b/packaging/operator_keys_test.go @@ -122,7 +122,7 @@ func testTheManifestConsumesTheBackupEvent(t *testing.T) { // delivery (H-A-388 and its addendum, H-A-394). if needs, err := catalogue.ManifestNeeds(raw); err != nil || len(needs) == 0 { t.Fatalf("the manifest's needs: %v, %v", needs, err) - } else if missing := catalogue.MissingManifestReads(needs, nil); !slices.Equal(missing, []string{"word:class", "word:declaration-reads"}) { + } else if missing := catalogue.MissingManifestReads(needs, nil); !slices.Equal(missing, []string{"word:class", "word:declaration-reads", "word:declaration-writes"}) { t.Errorf("the manifest needs %v, which an engine stating nothing does not read: its new build would be held", missing) } // Design 47 H2 §813 (12), H-A-388: it states the declaration Version it reads, the one its contract parses, so the @@ -151,8 +151,10 @@ func testTheManifestConsumesTheBackupEvent(t *testing.T) { if parsed, err := catalogue.Decode(raw); err != nil || parsed.Class != catalogue.ClassCore { t.Errorf("the manifest's class is %q, and the node-engine claims a seat (%v)", parsed.Class, err) } - if parsed, err := catalogue.Decode(raw); err != nil || parsed.DeclarationReads != declaration.Version { - t.Errorf("the manifest states it reads declaration Version %d, and the engine reads %d (%v)", parsed.DeclarationReads, declaration.Version, err) + // H-A-416 (2): and the Version its composer writes, since the composer is the engine's own build. + if parsed, err := catalogue.Decode(raw); err != nil || parsed.DeclarationReads != declaration.Version || parsed.DeclarationWrites != declaration.Version { + t.Errorf("the manifest states it reads declaration Version %d and writes %d, and the engine reads and writes %d (%v)", + parsed.DeclarationReads, parsed.DeclarationWrites, declaration.Version, err) } // 774 (the alert table): the state health, one key per node, the node's own health report, kept until // written again (no TTL: a node that stops writing keeps its last word, which the watchman reads with its time). -- 2.54.0 From b305a5f08cf045ff2340a5f3e1f6aaed7ee9614e Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 01:13:44 +0100 Subject: [PATCH 18/23] Revert: the registry seats still hold versions; the engine asks it again MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The resolved definitions of oci-artifact-registry and container-image-registry on mesh-delivery feat/47-H2 (42788501) both still hold versions, from the registry part they include; D4a (ac99946f) only gave list a module filter and a cursor. The validator's refusal came from a request that did not resolve the includes, so nothing the definitions hold is changed: this reverts 845de026. Builds: design 47 H2 §813 (7); H-A-415 (2) and its addendum --- internal/nodegrant/testdata/node.json | 4 +- internal/selfcompose/selfcompose_test.go | 10 +-- internal/selfcompose/versions.go | 94 ++++++++---------------- internal/selfcompose/versions_test.go | 31 +++----- module.json | 6 +- 5 files changed, 50 insertions(+), 95 deletions(-) diff --git a/internal/nodegrant/testdata/node.json b/internal/nodegrant/testdata/node.json index 8ef3e900..e31dcc1c 100644 --- a/internal/nodegrant/testdata/node.json +++ b/internal/nodegrant/testdata/node.json @@ -117,14 +117,14 @@ "mesh.control.NODE.>", "mesh.seat.mesh-catalog.call.entry.node~NODE", "mesh.seat.mesh-catalog.call.module.node~NODE", - "mesh.seat.container-image-registry.call.list.node~NODE", + "mesh.seat.container-image-registry.call.versions.node~NODE", "mesh.seat.mesh-catalog.call.revision.node~NODE", "mesh.seat.mesh-grants.call.withheld.node~NODE", "mesh.seat.mesh-module-assigner.call.assignments.node~NODE", "mesh.seat.mesh-recovery.call.kept-points.node~NODE", "mesh.seat.mesh-recovery.call.restore-kept.node~NODE", "mesh.seat.mesh-recovery.call.snapshot-kept.node~NODE", - "mesh.seat.oci-artifact-registry.call.list.node~NODE", + "mesh.seat.oci-artifact-registry.call.versions.node~NODE", "mesh.seat.mesh-catalog.call.seat-definitions.node~NODE", "mesh.seat.node-backup.call.backed-up.NODE.node~NODE", "mesh.seat.node-backup.call.now.NODE.node~NODE", diff --git a/internal/selfcompose/selfcompose_test.go b/internal/selfcompose/selfcompose_test.go index 4126f872..69d67094 100644 --- a/internal/selfcompose/selfcompose_test.go +++ b/internal/selfcompose/selfcompose_test.go @@ -470,8 +470,8 @@ func testTheNodeComposesItsWantsFromTheBus(t *testing.T) { // resolves the digests). e.Registry = EntryCall(func(_ context.Context, seat, _ string, args any) (json.RawMessage, error) { if seat == "container-image-registry" && args.(map[string]string)["name"] == "de-spiegel/site" { - return json.RawMessage(`{"repositories":[{"name":"de-spiegel/site","manifests":[{"digest":"sha256:` + - strings.Repeat("6", 64) + `","tags":["1"]}]}]}`), nil + return json.RawMessage(`{"name":"de-spiegel/site","versions":[{"name":"de-spiegel/site","kind":"image","digest":"sha256:` + + strings.Repeat("6", 64) + `","version":"1"}]}`), nil } return nil, errors.New("not held") }) @@ -1119,9 +1119,9 @@ func testTheNodeComposesItsWantsFromTheBus(t *testing.T) { catalogEntries[artFp] = artEntry // art's files archive at version 1, which the candidate "art-with" names (the candidate's version, never a digest). senv.Registry = EntryCall(func(_ context.Context, seat, _ string, args any) (json.RawMessage, error) { - if seat == "oci-artifact-registry" && args.(map[string]string)["module"] == "art" { - return json.RawMessage(`{"repositories":[{"name":"art/files","manifests":[{"digest":"sha256:` + strings.Repeat("8", 64) + - `","artifact":"sha256:` + strings.Repeat("9", 64) + `","tags":["1"]}]}]}`), nil + if seat == "oci-artifact-registry" && args.(map[string]string)["name"] == "art/files" { + return json.RawMessage(`{"name":"art/files","versions":[{"name":"art/files","kind":"archive","digest":"sha256:` + + strings.Repeat("9", 64) + `","version":"1"}]}`), nil } return nil, errors.New("not held") }) diff --git a/internal/selfcompose/versions.go b/internal/selfcompose/versions.go index 610f6601..0e4ddae3 100644 --- a/internal/selfcompose/versions.go +++ b/internal/selfcompose/versions.go @@ -19,7 +19,7 @@ import ( // **A want names its version; the node-engine resolves the digests** (design 47 G A-430, A-430a, the lead's answer A-430b). // A want of a released build names the module's version and no parts: each artifact of the build's entry is looked up at that -// version through the verb `list` of the registry seat of its kind (oci-artifact-registry for a bundle or an archive, +// version through the verb `versions` of the registry seat of its kind (oci-artifact-registry for a bundle or an archive, // container-image-registry for an image), under the name the builder numbered it by: `/`, or the entry's // package name for a package. An upstream copy is not numbered (it is mirrored by its pinned digest): its digest is the one its // manifest's `from` pins. A want that names parts (a build no version is known of) is read by its parts as before. A lookup that @@ -37,12 +37,8 @@ func (c *Composer) resolveAgain() time.Duration { return DefaultResolveAgain } -// listVerb is the verb a lookup asks: the registry seats read a version through `list`, filtered by module on -// oci-artifact-registry (design 47 H2 §813 (7), DMC-10, H-A-415 (2)). -const listVerb = "list" - -// listPagesMost bounds the pages one lookup reads of a seat's list. -const listPagesMost = 64 +// versionsVerb is the verb a lookup asks. +const versionsVerb = "versions" // resolvedKey names one resolution: a module's build at a version. type resolvedKey struct{ module, fp, version string } @@ -57,21 +53,13 @@ type versionParts struct { forgotten bool } -// registryList is the answer of either seat's verb `list` (form 2): each repository with the manifests it holds, each -// manifest's digest, the blob it keeps (a bundle's or an archive's) and the tags naming it; capped with next when the rest -// is on another page. -type registryList struct { - Repositories []struct { - Name string `json:"name"` - Manifests []struct { - Digest string `json:"digest"` - Artifact string `json:"artifact,omitempty"` - Tags []string `json:"tags,omitempty"` - } `json:"manifests"` - } `json:"repositories"` - Capped bool `json:"capped,omitempty"` - Total int64 `json:"total,omitempty"` - Next string `json:"next,omitempty"` +// registryVersions is the answer of either seat's verb `versions`: the two seats answer the same shape. +type registryVersions struct { + Versions []struct { + Digest string `json:"digest"` + Tag string `json:"tag,omitempty"` + Version string `json:"version,omitempty"` + } `json:"versions"` } // seatOfKind is the registry seat an artifact of kind is numbered in, and whether one is (design 51 *The seats*). @@ -230,7 +218,7 @@ func (c *Composer) lookUp(module string, e meshcatalog.CatalogEntry, w meshwants fail("(none)", a.Ref, "no registry seat the node-engine reads numbers an artifact of kind "+a.Kind) continue } - digest, why := c.versionDigest(seat, module, registryName(module, a), w) + digest, why := c.versionDigest(seat, registryName(module, a), w) if why != "" { fail(seat, a.Ref, why) continue @@ -244,52 +232,30 @@ func (c *Composer) lookUp(module string, e meshcatalog.CatalogEntry, w meshwants return parts, "" } -// versionDigest is the digest the seat's verb list answers for the repository name at w's version, a tag naming it: a -// version names one build (A-430a). oci-artifact-registry is asked for the module's repositories (`list {module}`) and -// answers the blob a manifest keeps, the digest a bundle or an archive is fetched by; container-image-registry, whose list -// takes no module, is asked for the repository by its name and answers the image manifest's digest. Every page is read -// while the answer says next (design 47 H2 §779, §813 (7), H-A-415 (2)). -func (c *Composer) versionDigest(seat, module, name string, w meshwants.WantsByWantNodeModuleValue) (string, string) { +// versionDigest is the digest the seat's verb versions answers for name at w's version (its version or its tag), the newest +// first: a version names one build (A-430a), so the version alone is matched. +func (c *Composer) versionDigest(seat, name string, w meshwants.WantsByWantNodeModuleValue) (string, string) { if c.env.Registry == nil { return "", "this node-engine reads no registry seat" } - in := map[string]string{"name": name} - if seat == ociartifactregistry.Seat { - in = map[string]string{"module": module} + raw, err := c.env.Registry("seat:"+seat+"."+versionsVerb, map[string]string{"name": name}) + if err != nil { + return "", fmt.Sprintf("the call for %s failed: %v", name, err) } - for page := 0; page < listPagesMost; page++ { - raw, err := c.env.Registry("seat:"+seat+"."+listVerb, in) - if err != nil { - return "", fmt.Sprintf("the call for %s failed: %v", name, err) - } - answer, said, ok := buscalls.Unwrap(raw) - if !ok { - return "", fmt.Sprintf("the seat refused %s: %s", name, said) - } - var l registryList - if err := json.Unmarshal(answer, &l); err != nil { - return "", fmt.Sprintf("its answer for %s cannot be read: %v", name, err) - } - for _, r := range l.Repositories { - if r.Name != name { - continue - } - for _, m := range r.Manifests { - if !slices.Contains(m.Tags, w.Version) || m.Digest == "" { - continue - } - if seat == ociartifactregistry.Seat && m.Artifact != "" { - return m.Artifact, "" - } - return m.Digest, "" - } - } - if l.Next == "" { - return "", fmt.Sprintf("it holds no version %s of %s", w.Version, name) - } - in["next"] = l.Next + answer, said, ok := buscalls.Unwrap(raw) + if !ok { + return "", fmt.Sprintf("the seat refused %s: %s", name, said) } - return "", fmt.Sprintf("its list of %s did not end within %d pages", module, listPagesMost) + var v registryVersions + if err := json.Unmarshal(answer, &v); err != nil { + return "", fmt.Sprintf("its answer for %s cannot be read: %v", name, err) + } + for _, a := range v.Versions { + if (a.Version == w.Version || a.Tag == w.Version) && a.Digest != "" { + return a.Digest, "" + } + } + return "", fmt.Sprintf("it holds no version %s of %s", w.Version, name) } // pinnedDigest is the digest the manifest's upstream artifact pins in its from (`@sha256:`); "" when none. diff --git a/internal/selfcompose/versions_test.go b/internal/selfcompose/versions_test.go index 1c22e10a..9b2fa862 100644 --- a/internal/selfcompose/versions_test.go +++ b/internal/selfcompose/versions_test.go @@ -36,13 +36,11 @@ func aWantNamingItsVersionIsResolvedThroughTheRegistrySeats(t *testing.T) { }}} entry := meshcatalog.CatalogEntry{Module: "mail", Fp: fp, Manifest: manifest, Artifacts: []meshcatalog.Artifact{ {Ref: "mail:server", Kind: "upstream"}, {Ref: "mail:files", Kind: "archive"}, {Ref: "mail:web", Kind: "image"}}} - // The seats hold mail/files and mail/web, each version a tag of its manifest; an archive's blob is what it is fetched - // by (design 47 H2 §813 (7), H-A-415 (2): the version is read through list). + // The seats hold mail/files and mail/web; versions newest first. held := map[string]string{ - "oci-artifact-registry.mail/files": `{"name":"mail/files","manifests":[{"digest":"` + d("8") + `","artifact":"` + d("2") + - `","tags":["1.3.0"]},{"digest":"` + d("7") + `","artifact":"` + d("1") + `","tags":["1.2.3"]}]}`, - "container-image-registry.mail/web": `{"name":"mail/web","manifests":[{"digest":"` + d("3") + `","tags":["1.2.3"]}]}`, - "container-image-registry.mail/other": `{"name":"mail/other","manifests":[]}`, + "oci-artifact-registry.mail/files": `{"name":"mail/files","versions":[{"name":"mail/files","kind":"archive","digest":"` + d("2") + `","version":"1.3.0"},{"name":"mail/files","kind":"archive","digest":"` + d("1") + `","version":"1.2.3"}]}`, + "container-image-registry.mail/web": `{"name":"mail/web","versions":[{"name":"mail/web","kind":"image","digest":"` + d("3") + `","version":"1.2.3"}]}`, + "container-image-registry.mail/other": `{"name":"mail/other","versions":[]}`, } for name, row := range map[string]struct { want meshwants.WantsByWantNodeModuleValue @@ -64,25 +62,17 @@ func aWantNamingItsVersionIsResolvedThroughTheRegistrySeats(t *testing.T) { calls := 0 env.Registry = EntryCall(func(_ context.Context, seat, verb string, args any) (json.RawMessage, error) { calls++ - in := args.(map[string]string) - // oci-artifact-registry is asked by the module, container-image-registry by the repository's name. - if verb != "list" || (seat == "oci-artifact-registry") != (in["module"] == "mail" && in["name"] == "") { - t.Errorf("%s: asked %s.%s %v", name, seat, verb, in) + if verb != "versions" { + t.Errorf("%s: asked %s.%s", name, seat, verb) } if seat == row.down { return nil, errors.New("no responders") } - var repos []string - for key, repo := range held { - r, ok := strings.CutPrefix(key, seat+".") - if ok && (r == in["name"] || (in["module"] != "" && strings.HasPrefix(r, in["module"]+"/"))) { - repos = append(repos, repo) - } - } - if len(repos) == 0 { + answer, ok := held[seat+"."+args.(map[string]string)["name"]] + if !ok { return nil, errors.New("not held") } - return json.RawMessage(`{"repositories":[` + strings.Join(repos, ",") + `]}`), nil + return json.RawMessage(answer), nil }) env.Entry = EntryCall(func(context.Context, string, string, any) (json.RawMessage, error) { return nil, errors.New("not asked") @@ -321,8 +311,7 @@ func aResolutionWhoseFetchFailedIsForgotten(t *testing.T) { calls := 0 env.Registry = EntryCall(func(context.Context, string, string, any) (json.RawMessage, error) { calls++ - return json.RawMessage(`{"repositories":[{"name":"mail/files","manifests":[{"digest":"sha256:` + strings.Repeat("e", 64) + - `","artifact":"` + row.answer + `","tags":["1.2.3"]}]}]}`), nil + return json.RawMessage(`{"versions":[{"digest":"` + row.answer + `","version":"1.2.3"}]}`), nil }) env.Fetch = func(context.Context, string) ([]byte, error) { return body, row.fetch } env.Entry = EntryCall(func(context.Context, string, string, any) (json.RawMessage, error) { diff --git a/module.json b/module.json index ee50160c..4db1dbac 100644 --- a/module.json +++ b/module.json @@ -46,7 +46,7 @@ } ], "invokes": [ - "seat:container-image-registry.list", + "seat:container-image-registry.versions", "seat:mesh-catalog.entry", "seat:mesh-catalog.module", {"verb": "seat:mesh-catalog.revision", "fields": ["none-yet"]}, @@ -57,7 +57,7 @@ "seat:mesh-recovery.restore-kept", "seat:mesh-recovery.snapshot-kept", "seat:node-packet-filter.allowed", - "seat:oci-artifact-registry.list" + "seat:oci-artifact-registry.versions" ], "consumes": [ "mesh-catalog.catalog-revision", @@ -126,7 +126,7 @@ }, "resolve-again-minutes": { "type": "number", - "description": "How long the node-engine holds a module whose want's version it could not resolve to its artifacts' digests, or whose resolution it forgot after a failed fetch, before it asks the registry seats' verb list again, in minutes (design 47 H, H-A-146).", + "description": "How long the node-engine holds a module whose want's version it could not resolve to its artifacts' digests, or whose resolution it forgot after a failed fetch, before it asks the registry seats' verb versions again, in minutes (design 47 H, H-A-146).", "minimum": 1, "maximum": 60, "default": 1 -- 2.54.0 From 86380b66c1ea5d46319db3dd71c67a6ab57bc0cc Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 01:17:49 +0100 Subject: [PATCH 19/23] Write each node's declaration at the Version its engine reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The composer is the node-engine's own build, so a newer composer could hand an older engine a field its strict decode refuses. The engine's record now states the declaration Version it reads, and the composer writes node X's declaration at the lower of its own Version and X's (1 when X states none), leaving out what that Version lacks: an engine reading 1 gets no drain-bound and runs on its own default. Builds: design 47 H2 §813 (12); H-A-416 (2), H-A-419; mesh-contracts feat/47-H2 e6ed560e (the record's declaration-reads) --- internal/compose/composed.go | 37 +++++++++++++++++++++++++++++ internal/compose/composed_test.go | 15 ++++++++++++ internal/compose/frombus/frombus.go | 1 + internal/compose/input.go | 3 +++ internal/link/have_test.go | 4 +++- internal/link/record.go | 3 +++ 6 files changed, 62 insertions(+), 1 deletion(-) diff --git a/internal/compose/composed.go b/internal/compose/composed.go index 9ba9dc16..b7a56b79 100644 --- a/internal/compose/composed.go +++ b/internal/compose/composed.go @@ -213,9 +213,11 @@ func compositions(in Input, node string, fps map[string]string, mode Mode, appli } // What the tool runner's process runs as, whose slice of each held module the composed process keeps (H-A-306). var runsRuntime map[string]string + reads := 0 for i := range reading.Nodes { if reading.Nodes[i].Name == node { runsRuntime = reading.Nodes[i].RunsRuntime + reads = reading.Nodes[i].DeclarationReads } } var kept []json.RawMessage @@ -223,6 +225,10 @@ func compositions(in Input, node string, fps map[string]string, mode Mode, appli foldedPaths := map[string]bool{} left := map[string]bool{} for _, raw := range envelope.Resources { + // Written at the lower of this composer's declaration Version and the one the node's engine reads (H-A-416 (2)). + if raw, err = AtDeclarationVersion(raw, reads); err != nil { + return nil, nil, nil, nil, err + } var head struct { ID string `json:"id"` Module string `json:"module"` @@ -836,3 +842,34 @@ func carry(kept []json.RawMessage, foldedPaths map[string]bool, runs *engcomp.Co } return out, foldedPaths, nil } + +// drainBoundVersion is the declaration Version a process's drain-bound came with (mesh-sdk declaration, H-A-388 (2)). +const drainBoundVersion = 2 + +// DeclarationVersionFor is the declaration Version a node's declaration is written at: the lower of this composer's +// own (declaration.Version) and the one its engine states it reads, 1 when it states none (design 47 H2 §813 (12), +// H-A-416 (2), H-A-419). +func DeclarationVersionFor(reads int) int { + if reads < 1 { + reads = 1 + } + return min(reads, declaration.Version) +} + +// AtDeclarationVersion is a resource as a node whose engine reads Version reads (DeclarationVersionFor): the fields that +// Version lacks left out, so an older engine never meets a field it refuses; a process's drain-bound then takes the +// engine's own default (H-A-416 (2)). +func AtDeclarationVersion(raw json.RawMessage, reads int) (json.RawMessage, error) { + if DeclarationVersionFor(reads) >= drainBoundVersion { + return raw, nil + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(raw, &fields); err != nil { + return nil, err + } + if _, has := fields["drain-bound"]; !has { + return raw, nil + } + delete(fields, "drain-bound") + return json.Marshal(fields) +} diff --git a/internal/compose/composed_test.go b/internal/compose/composed_test.go index 595d38f2..2179aa48 100644 --- a/internal/compose/composed_test.go +++ b/internal/compose/composed_test.go @@ -241,6 +241,21 @@ func TestCompositionsAreTheDeclarationSplitByModule(t *testing.T) { env[catalogue.RuntimeToolModules], env[catalogue.RuntimeToolEnv], wantServed, words) } } + // Design 47 H2 §813 (12), H-A-416 (2), H-A-419: a node's declaration is written at the lower of the composer's Version + // and the one its engine states it reads: one stating 1, or none, gets Version 1 and no drain-bound; one stating 2 + // gets Version 2 with it. + t.Run("a declaration is written at the Version the node's engine reads", func(t *testing.T) { + process := json.RawMessage(`{"id":"node-tools.runtime","type":"process","drain-bound":30}`) + for _, row := range []struct { + reads, version int + drain bool + }{{0, 1, false}, {1, 1, false}, {2, 2, true}, {3, 2, true}} { + got, err := AtDeclarationVersion(process, row.reads) + if err != nil || DeclarationVersionFor(row.reads) != row.version || strings.Contains(string(got), "drain-bound") != row.drain { + t.Errorf("an engine reading %d: Version %d, %s (%v)", row.reads, DeclarationVersionFor(row.reads), got, err) + } + } + }) } // lead-47 2026-11-16: a held tool runner keeps the program it runs (Carried, runningProgram) after what the runtime serves diff --git a/internal/compose/frombus/frombus.go b/internal/compose/frombus/frombus.go index e5a59254..8d1def99 100644 --- a/internal/compose/frombus/frombus.go +++ b/internal/compose/frombus/frombus.go @@ -1260,6 +1260,7 @@ func nodeOf(rec nodeengine.NodeRecord, p meshmoduleassigner.Assignments) compose SealingKey: rec.SealingKey, OutwardLinks: rec.OutwardLinks, Networks: attachedOf(rec.Networks), NetworksSaid: rec.NetworksSaid, ServingKey: rec.ServingKey, Certificate: rec.Certificate, Contract: int(rec.Contract), Stated: rec.Contract > 0, + DeclarationReads: int(rec.DeclarationReads), } placeNode(&n, p) if len(rec.Capabilities) > 0 { diff --git a/internal/compose/input.go b/internal/compose/input.go index 1eb57312..d3c0b713 100644 --- a/internal/compose/input.go +++ b/internal/compose/input.go @@ -247,6 +247,9 @@ type Node struct { // Contract is the contract of its node-engine's newest statement (inv.HealthOf); Stated is whether it ever stated one. Contract int Stated bool + // DeclarationReads is the declaration Version its node-engine states it reads (nodeengine.NodeRecord.DeclarationReads, + // design 47 H2 §813 (12), H-A-416 (2), H-A-419); 0 when it states none, read as 1. + DeclarationReads int // InOwn is the modules it runs inside its own composition (`.node`), not by a composition of their own, since // no fingerprint of the new form names them where it runs them (novox/hq issue 1126): Compositions folds their // resources into the node's own, as the controller's composed writer does, unless fps gives one of the new form. diff --git a/internal/link/have_test.go b/internal/link/have_test.go index 74507602..5cea7449 100644 --- a/internal/link/have_test.go +++ b/internal/link/have_test.go @@ -19,6 +19,7 @@ import ( "git.novox.be/novox/mesh-sdk/go/busretry" "git.novox.be/novox/mesh-sdk/go/catalogue" + "git.novox.be/novox/mesh-sdk/go/declaration" "github.com/nats-io/nats.go" ) @@ -372,7 +373,8 @@ func testTheNodeKeyCarriesTheNodesFacts(t *testing.T) { Certificate: "cert", Trusts: keys.Trusts, Capabilities: []string{"apt", "bus-state-calls", "ledger-calls", "systemd"}, OutwardLinks: []string{"eth0"}, NetworksSaid: true, Networks: []nodeengine.AttachedNetwork{{Link: "eth0", Network: "192.0.2.0/24"}}, Contract: NodeKeyContract, ManifestReads: statedReads(), // what it reads of a manifest: its contract's (ADR 0614 §4) and that it reads a want by version (H §772) - RunnerCapabilities: []string{"bus-state-calls", "ledger-calls"}, RunnerFingerprint: "sha256:runner"} + RunnerCapabilities: []string{"bus-state-calls", "ledger-calls"}, RunnerFingerprint: "sha256:runner", + DeclarationReads: declaration.Version} // H-A-416 (2), H-A-419: the declaration Version this engine reads if !nodeengineclient.SameNodeRecord(*got.Record, wantRecord) { t.Errorf("record = %+v, want %+v", *got.Record, wantRecord) } diff --git a/internal/link/record.go b/internal/link/record.go index e0e0ce46..1db4748c 100644 --- a/internal/link/record.go +++ b/internal/link/record.go @@ -11,6 +11,7 @@ import ( "time" "git.novox.be/novox/mesh-sdk/go/catalogue" + "git.novox.be/novox/mesh-sdk/go/declaration" ) // The node's record (novox/hq ADR 0555 §3, issue 1126): what the machine observes of itself, written in its own have key @@ -154,5 +155,7 @@ func recordOf(node string, r Report, keys RecordKeys) *nodeengine.NodeRecord { if r.Health != nil { rec.Contract = int64(r.Health.Contract) } + // The declaration Version this engine reads, by which a composer writes this node's declaration (H-A-416 (2), H-A-419). + rec.DeclarationReads = declaration.Version return rec } -- 2.54.0 From 7d87dde0a41c91445e14c37af4b9fa8de0a72ed0 Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 02:57:04 +0100 Subject: [PATCH 20/23] H-A-458 (1): compare a want's run with the have's only within its pipeline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A want of another pipeline is a placement the assigner made on purpose, so a lower run of it was refused against a run of another branch the engine had applied. The have now keeps the pipeline of the want it was applied from beside its run (the node-engine seat's form 4), settleOne compares the runs only when the pipelines are equal, and a want of another pipeline replaces whatever stands. Rows: a lower run of another pipeline is applied, a lower run of the same is refused and said; the have names both. Review round 1, finding: the applied run's branch. Builds: design 47 H2 §813 (1); H-A-429 (1), H-A-458 (1) --- cmd/mesh-host/nodeagent.go | 4 ++-- internal/agent/agent.go | 22 +++++++++++++++------- internal/agent/agent_test.go | 23 ++++++++++++++++++++++- internal/link/have.go | 4 ++-- internal/link/have_test.go | 6 ++++-- internal/link/messages.go | 3 +++ 6 files changed, 48 insertions(+), 14 deletions(-) diff --git a/cmd/mesh-host/nodeagent.go b/cmd/mesh-host/nodeagent.go index 7e6e8eb8..d28a669e 100644 --- a/cmd/mesh-host/nodeagent.go +++ b/cmd/mesh-host/nodeagent.go @@ -109,7 +109,7 @@ func (h sessionHaves) ReadErr(ctx context.Context, module string) (agent.Have, b return agent.Have{}, false, err } return agent.Have{Module: module, FP: got.Fp, Composed: got.Composed, Phase: string(got.Phase), Detail: got.Detail, - Sealed: got.SealedAt, Wait: got.Wait, Run: got.Run}, true, nil + Sealed: got.SealedAt, Wait: got.Wait, Run: got.Run, Pipeline: got.Pipeline}, true, nil } func (h sessionHaves) Write(ctx context.Context, x agent.Have) { @@ -126,7 +126,7 @@ func (h sessionHaves) Write(ctx context.Context, x agent.Have) { } h.session.NoteModule(ctx, link.ModuleFact{Module: x.Module, FP: x.FP, Composed: x.Composed, Phase: phase, Failed: phase == string(nodeengineclient.PhaseFailed), Detail: shorten(x.Detail), Judgement: x.Judgement, Waits: x.Waits, - BuildAlone: x.BuildAlone, Kept: x.Kept, Sealed: x.Sealed, PullWait: x.PullWait, Wait: x.Wait, Run: x.Run}) + BuildAlone: x.BuildAlone, Kept: x.Kept, Sealed: x.Sealed, PullWait: x.PullWait, Wait: x.Wait, Run: x.Run, Pipeline: x.Pipeline}) } func (h sessionHaves) Removed(ctx context.Context, module string) { diff --git a/internal/agent/agent.go b/internal/agent/agent.go index cf450d61..d78e0358 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -82,6 +82,10 @@ type Have struct { // H-A-384 (2), H-A-388; nodeengine.HaveByNodeModuleValue.Run): kept in the have, so a restarted engine applies no // older run again. A write that names none keeps the one the module's last have said (writeHave). Run string + // Pipeline is the pipeline of the want the module was applied from, its key ., kept beside Run + // (H-A-429 (1), H-A-458 (1); nodeengine.HaveByNodeModuleValue.Pipeline): a want's run is compared with Run only when + // the want names the same pipeline. Kept and replaced together with Run. + Pipeline string } // Haves is the node's have bucket as the agent uses it. @@ -753,9 +757,10 @@ func (a *Agent) writeHave(ctx context.Context, h Have) { h.Sealed = last.Sealed } } - // The run the module was applied from stays in its have until an apply from another run (H-A-384 (2)). + // The run the module was applied from stays in its have until an apply from another run (H-A-384 (2)), with + // the pipeline it was of (H-A-458 (1)). if h.Run == "" { - h.Run = last.Run + h.Run, h.Pipeline = last.Run, last.Pipeline } } } @@ -1530,7 +1535,9 @@ func (a *Agent) settleOne(ctx context.Context, module string) { a.mu.Unlock() } // Design 47 H2 §813 (1), H-A-384 (2): the run the module was applied from is its have's, never this engine's memory, so - // a restarted engine applies no older run again. Read only for a want that carries one. + // a restarted engine applies no older run again. Read only for a want that carries one, and compared only within the + // want's pipeline: a want of another pipeline is a placement the assigner made on purpose and replaces whatever stands + // (H-A-429 (1), H-A-458 (1)). appliedRun := "" if w.Want.Run != "" { h, found, unread := a.readHave(ctx, module) @@ -1541,7 +1548,7 @@ func (a *Agent) settleOne(ctx context.Context, module string) { a.mu.Unlock() return } - if found { + if found && h.Pipeline == w.Want.Pipeline { appliedRun = h.Run } } @@ -1872,7 +1879,7 @@ func (a *Agent) apply(ctx context.Context, module string, w wantNow, comp compNo delete(a.notComposed, module) // the apply says what it runs now a.running[module] = nodeengine.HaveByNodeModuleValue{Fp: fp, Composed: dig, Phase: nodeengineclient.PhaseRunning} a.applied[module] = comp - run := w.Want.Run + run, pipeline := w.Want.Run, w.Want.Pipeline a.mu.Unlock() if run != "" { a.env.Say(fmt.Sprintf("applied %s from run %s", what, run)) @@ -1881,7 +1888,7 @@ func (a *Agent) apply(ctx context.Context, module string, w wantNow, comp compNo if a.env.Settled != nil { a.env.Settled(module) } - a.writeHave(ctx, Have{Module: module, FP: fp, Composed: dig, Phase: string(nodeengineclient.PhaseRunning), Detail: res.Detail, Run: run}) + a.writeHave(ctx, Have{Module: module, FP: fp, Composed: dig, Phase: string(nodeengineclient.PhaseRunning), Detail: res.Detail, Run: run, Pipeline: pipeline}) a.catchUp(ctx, module, catchUps) } @@ -1892,7 +1899,8 @@ func (a *Agent) takenAtStart(module string, runs compositions.Composed) { } } -// runIsNewer says whether a want's run orders after the run a module was applied from (design 47 H2 §813 (1)): each is +// runIsNewer says whether a want's run orders after the run a module was applied from (design 47 H2 §813 (1)), both of one +// pipeline (settleOne compares no runs of two, H-A-458 (1)): each is // the composition run's pipeline sequence in decimal. A want or an apply without one is not ordered by run, nor is a run // that is no decimal number. func runIsNewer(want, applied string) bool { diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index d41804f6..d5a968b1 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -394,11 +394,32 @@ func testAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) { if got := len(b.appliedList()) - before; got != 0 { t.Errorf("a want of run 10 after a have of run 20: applied %d times, want none", got) } + // H-A-429 (1), H-A-458 (1): a want's run is compared with the have's only within one pipeline: a lower run of another + // pipeline replaces what stands, and the have keeps that pipeline beside its run; a lower run of the same is refused. + for _, row := range []struct { + fp, run, pipeline string + applied int + }{{"7", "10", "feat.mesh-host", 1}, {"8", "9", "feat.mesh-host", 0}} { + before := len(b.appliedList()) + fpr := fpOf(row.fp) + ckr, crawr, digr := composition(t, "web", fpr, false, archive("a", d2)) + b.comps.put(ckr, crawr) + wkr, _ := wantFor(t, "web", fpr, digr, "") + rawr, _ := bucketstest.Want(meshwants.WantsByWantNodeModuleValue{Fp: fpr, Run: row.run, Pipeline: row.pipeline}) + b.wants.put(wkr, rawr) + b.idle() + if got := len(b.appliedList()) - before; got != row.applied { + t.Errorf("a want of run %s of pipeline %s: applied %d times, want %d", row.run, row.pipeline, got, row.applied) + } + } + if h := b.haves.last("web"); h.Run != "10" || h.Pipeline != "feat.mesh-host" { + t.Errorf("the have names run %q of pipeline %q, want run 10 of feat.mesh-host", h.Run, h.Pipeline) + } b.mu.Lock() said := strings.Join(b.said, "\n") b.mu.Unlock() for _, want := range []string{"from run 7", "from run 8", "carries run 5, and the engine applied it from run 7", - "carries run 10, and the engine applied it from run 20"} { + "carries run 10, and the engine applied it from run 20", "carries run 9, and the engine applied it from run 10"} { if !strings.Contains(said, want) { t.Errorf("the journal does not say %q:\n%s", want, said) } diff --git a/internal/link/have.go b/internal/link/have.go index 63d28d87..c94c77a4 100644 --- a/internal/link/have.go +++ b/internal/link/have.go @@ -413,8 +413,8 @@ func (q *Session) writeHaves(ctx context.Context, bus Bus) { h.PullWait = f.PullWait } h.Wait = f.Wait - // The seat's form 2 carries the run the module was applied from (H-A-388). - h.Run, h.Form = f.Run, nodeengine.Form + // The seat's form 2 carries the run the module was applied from (H-A-388), form 4 the pipeline beside it (H-A-458 (1)). + h.Run, h.Pipeline, h.Form = f.Run, f.Pipeline, nodeengine.Form h.Health = s.healthOf(module, f) if h.Detail == "" { h.Detail = s.wordsOf(module, h.Health) diff --git a/internal/link/have_test.go b/internal/link/have_test.go index 5cea7449..d1fdc7c0 100644 --- a/internal/link/have_test.go +++ b/internal/link/have_test.go @@ -771,9 +771,11 @@ func testAnAppliedModulesHaveNamesTheFingerprintAndTheDigestAndFollowsItsHealth( q, _ := aHaveQueue(l) fp := "src2:" + strings.Repeat("a", 64) dig := "sha256:" + strings.Repeat("b", 64) - q.NoteModule(context.Background(), ModuleFact{Module: "web", FP: fp, Composed: dig}) + // H-A-458 (1): the run it was applied from is kept with the pipeline of its want. + q.NoteModule(context.Background(), ModuleFact{Module: "web", FP: fp, Composed: dig, Run: "12", Pipeline: "main.mesh-host"}) h := l.have(t, "n1.web") - if h.Fp != fp || h.Composed != dig || h.Phase != nodeengineclient.PhaseRunning || h.Health != nodeengineclient.HealthUnknown { + if h.Fp != fp || h.Composed != dig || h.Phase != nodeengineclient.PhaseRunning || h.Health != nodeengineclient.HealthUnknown || + h.Run != "12" || h.Pipeline != "main.mesh-host" { t.Fatalf("the have after the apply: %+v", h) } // Design 47, *What each step says*: running is said once, when the build is healthy and its manifest is known, on diff --git a/internal/link/messages.go b/internal/link/messages.go index 9c2490a9..5f21990e 100644 --- a/internal/link/messages.go +++ b/internal/link/messages.go @@ -651,4 +651,7 @@ type ModuleFact struct { Wait *nodeengine.Wait // Run is the composition run the module was applied from (nodeengine.HaveByNodeModuleValue.Run, design 47 H2 §813 (1), H-A-388). Run string + // Pipeline is the pipeline of the want it was applied from, kept beside Run (nodeengine.HaveByNodeModuleValue.Pipeline, + // H-A-458 (1)). + Pipeline string } -- 2.54.0 From 213542192c55dcdc77663799cbdf843d232fd5a8 Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 02:57:45 +0100 Subject: [PATCH 21/23] H-A-458 (3): bind the taken write by the compose call's own context MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The state taken's write was bound by a five-second bound of its own, whatever the ask's deadline, so an ask whose caller had gone could still be kept, and its repeat refused. takenWithin goes: Env.Taken carries the compose call's context, Session.TakeOnce binds the state with it and keeps nothing once it ended. Row: a take whose context ended is refused, and the same id is then taken the first time. Review round 1, finding: the taken bound. Builds: design 47 H2 §775; H-A-364 (a), H-A-458 (3) --- cmd/mesh-host/recovery_integration_test.go | 12 +++++++++++- internal/link/taken.go | 13 ++++++------- internal/selfcompose/candidate.go | 2 +- internal/selfcompose/candidate_test.go | 2 +- internal/selfcompose/selfcompose.go | 5 +++-- 5 files changed, 22 insertions(+), 12 deletions(-) diff --git a/cmd/mesh-host/recovery_integration_test.go b/cmd/mesh-host/recovery_integration_test.go index 70956784..4c8d2cdb 100644 --- a/cmd/mesh-host/recovery_integration_test.go +++ b/cmd/mesh-host/recovery_integration_test.go @@ -138,10 +138,20 @@ func TestNatsTheRecoveryStepAsksHearsBoundsAndCatchesUpOverTheBus(t *testing.T) // Design 47 H2 §775, H-A-364: over the same session, an ask of the seat is taken once in the state taken: the first time, // and never again within its bound. for i, want := range []bool{true, false} { - if took, err := session.TakeOnce(nodeengine.Seat, "ask-1", time.Minute); err != nil || took != want { + if took, err := session.TakeOnce(ctx, nodeengine.Seat, "ask-1", time.Minute); err != nil || took != want { t.Fatalf("take %d of ask-1: %v, %v; want %v", i+1, took, err, want) } } + // H-A-458 (3): the write is bound by the ask's own context: an ask whose context ended keeps nothing, so the same id is + // taken the first time once asked again within a live one. + gone, end := context.WithCancel(ctx) + end() + if took, err := session.TakeOnce(gone, nodeengine.Seat, "ask-2", time.Minute); err == nil || took { + t.Fatalf("a take of ask-2 whose context ended: %v, %v; want refused", took, err) + } + if took, err := session.TakeOnce(ctx, nodeengine.Seat, "ask-2", time.Minute); err != nil || !took { + t.Fatalf("ask-2 asked again within a live context: %v, %v; want taken the first time", took, err) + } events, stop, err := r.Hear(ctx, "restored", "db", "cache") if err != nil { diff --git a/internal/link/taken.go b/internal/link/taken.go index 293285d2..5861e6b8 100644 --- a/internal/link/taken.go +++ b/internal/link/taken.go @@ -45,12 +45,10 @@ var ( _ TakenBus = OverNATS{} ) -// takenWithin bounds binding the state taken. -const takenWithin = 5 * time.Second - // TakeOnce takes the ask ask of seat once, in the state taken for bound (process.State.TakeOnce): true the first time it -// is given, false when it was taken within its bound. ErrNoLink when no link is held. -func (q *Session) TakeOnce(seat, ask string, bound time.Duration) (bool, error) { +// is given, false when it was taken within its bound. ErrNoLink when no link is held. The write is bound by ctx, the ask's +// own deadline (H-A-458 (3), P11): no bound of its own, and an ask whose context ended keeps nothing. +func (q *Session) TakeOnce(ctx context.Context, seat, ask string, bound time.Duration) (bool, error) { q.init() q.mu.Lock() bus := q.bus @@ -59,11 +57,12 @@ func (q *Session) TakeOnce(seat, ask string, bound time.Duration) (bool, error) if bus == nil || !ok { return false, ErrNoLink } - ctx, cancel := context.WithTimeout(context.Background(), takenWithin) - defer cancel() kv, err := t.TakenKV(ctx) if err != nil { return false, err } + if err := ctx.Err(); err != nil { + return false, fmt.Errorf("the ask %s of %s is not kept in the state %s: its context ended: %w", ask, seat, TakenBucket, err) + } return process.StateOver("mesh-host", process.TakenState, kv).TakeOnce(seat, ask, bound) } diff --git a/internal/selfcompose/candidate.go b/internal/selfcompose/candidate.go index 0badb931..52fc655a 100644 --- a/internal/selfcompose/candidate.go +++ b/internal/selfcompose/candidate.go @@ -159,7 +159,7 @@ func (s *Shadow) ComposeCandidate(ctx context.Context, ask nodeengine.ComposeCan a, joined := s.asked.once(ctx, id, func() nodeengine.ComposeCandidateAnswer { took := "" if c.env.Taken != nil { - switch first, err := c.env.Taken(nodeengine.Seat, id, c.composeAskBound()); { + switch first, err := c.env.Taken(ctx, nodeengine.Seat, id, c.composeAskBound()); { case err != nil: took = fmt.Sprintf(", not kept in taken: %v", err) case !first: diff --git a/internal/selfcompose/candidate_test.go b/internal/selfcompose/candidate_test.go index 791a10ed..83433662 100644 --- a/internal/selfcompose/candidate_test.go +++ b/internal/selfcompose/candidate_test.go @@ -88,7 +88,7 @@ func TestTheNodeComposesACandidateOnAsk(t *testing.T) { // Design 47 H2 §775, H-A-364: an ask with an id is taken once in the state taken, for compose-ask-bound. var takes []string taken := map[string]bool{} - env.Taken = func(seat, ask string, bound time.Duration) (bool, error) { + env.Taken = func(_ context.Context, seat, ask string, bound time.Duration) (bool, error) { takes = append(takes, seat+"."+ask+" "+bound.String()) first := !taken[ask] taken[ask] = true diff --git a/internal/selfcompose/selfcompose.go b/internal/selfcompose/selfcompose.go index 0850f3a3..cf265bfd 100644 --- a/internal/selfcompose/selfcompose.go +++ b/internal/selfcompose/selfcompose.go @@ -154,8 +154,9 @@ type Env struct { // (design 08 control-verbs §1, H-A-314 (5)). ComposeAskBound time.Duration // Taken takes an ask of the seat seat once by its id (design 47 H2 §775, H-A-364 (a)): kept in the node-engine's state - // `taken` under `.` for bound; false when it was taken before. Nil keeps nothing. - Taken func(seat, ask string, bound time.Duration) (bool, error) + // `taken` under `.` for bound; false when it was taken before. Nil keeps nothing. Its write is bound by ctx, + // the compose call's own (H-A-458 (3)). + Taken func(ctx context.Context, seat, ask string, bound time.Duration) (bool, error) // Registry asks the registry seats' verb versions (oci-artifact-registry, container-image-registry) in the engine's own // name: a want naming its version is resolved to its artifacts' digests through it (design 47 G A-430a). Registry meshcatalogclient.Call -- 2.54.0 From 3b1f5a07d2cc606f8a5edb5d4c79044a9b1ad607 Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 02:58:22 +0100 Subject: [PATCH 22/23] H-A-458 (2): answer the composition's drift through the seat's contract MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The verb composition's drift, the directory entries the mesh made whose owner or mode on disk differ, was the engine's own DriftView, a field the node-engine seat's definition did not have. The definition now carries drift (id, path, drift) at form 4, and the engine answers it as the generated CompositionAnswerDriftItem; DriftView goes. Row: the answer read back through the contract's decoder names the drift. Review round 1, finding: drift in the composition answer. Builds: design 47 H2 §813; H-A-374, H-A-392 (b), H-A-458 (2) --- cmd/mesh-host/nodeagent.go | 6 +++--- internal/agent/agent.go | 2 +- internal/agent/agent_test.go | 10 ++++++++-- internal/agent/composition.go | 12 ++---------- 4 files changed, 14 insertions(+), 16 deletions(-) diff --git a/cmd/mesh-host/nodeagent.go b/cmd/mesh-host/nodeagent.go index d28a669e..fde0506a 100644 --- a/cmd/mesh-host/nodeagent.go +++ b/cmd/mesh-host/nodeagent.go @@ -558,7 +558,7 @@ func nodeAgent(ctx context.Context, opts options, signer ed25519.PublicKey, trus say(line) } }, - DirectoryDrift: func(runs compositions.Composed) []agent.DriftView { + DirectoryDrift: func(runs compositions.Composed) []nodeengine.CompositionAnswerDriftItem { d, err := declarationOf(runs) if err != nil { return nil @@ -567,9 +567,9 @@ func nodeAgent(ctx context.Context, opts options, signer ed25519.PublicKey, trus if err != nil { return nil } - var out []agent.DriftView + var out []nodeengine.CompositionAnswerDriftItem for _, x := range apply.DirectoryDrifts(d, known) { - out = append(out, agent.DriftView{ID: x.ID, Path: x.Path, Drift: x.Drift}) + out = append(out, nodeengine.CompositionAnswerDriftItem{ID: x.ID, Path: x.Path, Drift: x.Drift}) } return out }, diff --git a/internal/agent/agent.go b/internal/agent/agent.go index d78e0358..7753f658 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -195,7 +195,7 @@ type Env struct { TakenAtStart func(module string, runs compositions.Composed) // DirectoryDrift reads, for the verb composition's diff, each directory entry of runs the mesh made whose owner or // mode on disk differ (apply.DirectoryDrifts, H-A-392). Nil reads none. - DirectoryDrift func(runs compositions.Composed) []DriftView + DirectoryDrift func(runs compositions.Composed) []nodeengine.CompositionAnswerDriftItem // RunsChanged is told, outside the agent's lock, that what runs (Everything) changed other than by an apply or a // removal: once at the start, when the haves and the compositions they name are read, and each time a module is // taken as running from its have or the kept declaration. Like Settled, the filling then tells the provisioner's diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index d5a968b1..d1c96b92 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -2027,13 +2027,19 @@ func testTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes( keep(dk, draw) keep(dk, drawMoved) // H-A-392: and with diff, each directory the mesh made of what runs whose mode or owner on disk drifted. - b.ag.env.DirectoryDrift = func(runs compositions.Composed) []DriftView { - return []DriftView{{ID: runs.Module + ".data", Path: "/srv/db", Drift: "mode 0700, 0711 declared"}} + b.ag.env.DirectoryDrift = func(runs compositions.Composed) []nodeengine.CompositionAnswerDriftItem { + return []nodeengine.CompositionAnswerDriftItem{{ID: runs.Module + ".data", Path: "/srv/db", Drift: "mode 0700, 0711 declared"}} } view, err := b.ag.Composition(context.Background(), "db", "", true) if len(view.Drift) != 1 || view.Drift[0].ID != "db.data" { t.Errorf("the diff of db names the drift %+v", view.Drift) } + // H-A-458 (2): the answer is read as the seat's contract has it, drift among its fields. + if raw, merr := json.Marshal(view); merr != nil { + t.Error(merr) + } else if read, _, derr := nodeengine.DecodeCompositionAnswer(raw); derr != nil || len(read.Drift) != 1 || read.Drift[0] != view.Drift[0] { + t.Errorf("the composition answer read through the contract: drift %+v, %v", read.Drift, derr) + } if err != nil || view.Have == nil || view.Have.Phase != string(nodeengineclient.PhaseWaitingYes) || view.Composition.Digest != ddigMoved || view.Runs == nil || view.Runs.Composed != ddig || view.Judged.Judgement != string(nodeengineclient.JudgedRecreates) || !view.Judged.WaitsForYes || len(view.Diff) != 1 || view.Diff[0].ID != "db.server" || view.Diff[0].Change != "changed" || diff --git a/internal/agent/composition.go b/internal/agent/composition.go index c39bb8bd..4eae9994 100644 --- a/internal/agent/composition.go +++ b/internal/agent/composition.go @@ -51,8 +51,8 @@ type CompositionView struct { Diff []judge.ResourceChange `json:"diff,omitempty"` // Drift is, when the diff is asked, each directory entry of what runs that the mesh made, as its record holds, whose // owner or mode on disk differ from it (H-A-374, H-A-392): read-only; the engine sets it right at its next start or - // apply of the module. - Drift []DriftView `json:"drift,omitempty"` + // apply of the module. Its form is the node-engine seat's contract's (H-A-458 (2)). + Drift []nodeengine.CompositionAnswerDriftItem `json:"drift,omitempty"` // Own is, of the node's own composition (module node), its own fields beside what runs names (issue 774: ace's // own composition dropped the provisioner client's account, and nothing read could show it). Own *OwnView `json:"own,omitempty"` @@ -348,14 +348,6 @@ func (a *Agent) revisionsOf(ctx context.Context, key string) ([]compNow, error) return out, nil } -// DriftView is one directory entry the mesh made whose owner or mode on disk differ from it, as the verb composition's -// diff names it (H-A-392): its id, its path and how, in words. -type DriftView struct { - ID string `json:"id"` - Path string `json:"path"` - Drift string `json:"drift"` -} - // CompositionDiff answers the node-engine seat's read verb composition-diff (design 47 H2 §813 (3), H-A-349 DQ-12b): one // module's composition that runs beside another revision of its composition key, given by its revision or its digest, // as the entries that differ per resource; environment entries by name, a secret's value masked. It changes nothing. -- 2.54.0 From 876bf45223d9fbb4f3f54cb62c2b773cda9685e0 Mon Sep 17 00:00:00 2001 From: jochen Date: Sun, 22 Nov 2026 03:13:15 +0100 Subject: [PATCH 23/23] H-A-458 (1): compare a want's run with the have's only within its branch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A pipeline's key is ., so every pipeline of a branch has its own key, and comparing the whole key found no applied run for a stale want of an older pipeline of the same branch (main.175 after main.180): it was applied. settleOne now compares the branches, each key without its last part; a want of another branch still replaces whatever stands. Rows with real keys: feat.10 applied, feat.9 refused and said, main.5 applied, the have naming run 5 of main.5. Review round 2, finding: the whole pipeline key compared instead of its branch. Builds: design 47 H2 §813 (1); H-A-429 (1), H-A-458 (1) --- internal/agent/agent.go | 18 ++++++++++++++---- internal/agent/agent_test.go | 11 ++++++----- internal/link/have_test.go | 4 ++-- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 7753f658..159b5c69 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -84,7 +84,7 @@ type Have struct { Run string // Pipeline is the pipeline of the want the module was applied from, its key ., kept beside Run // (H-A-429 (1), H-A-458 (1); nodeengine.HaveByNodeModuleValue.Pipeline): a want's run is compared with Run only when - // the want names the same pipeline. Kept and replaced together with Run. + // the want's pipeline is of the same branch (pipelineBranch). Kept and replaced together with Run. Pipeline string } @@ -1536,8 +1536,9 @@ func (a *Agent) settleOne(ctx context.Context, module string) { } // Design 47 H2 §813 (1), H-A-384 (2): the run the module was applied from is its have's, never this engine's memory, so // a restarted engine applies no older run again. Read only for a want that carries one, and compared only within the - // want's pipeline: a want of another pipeline is a placement the assigner made on purpose and replaces whatever stands - // (H-A-429 (1), H-A-458 (1)). + // want's branch: a want of another branch is a placement the assigner made on purpose and replaces whatever stands + // (H-A-429 (1), H-A-458 (1)). A pipeline's key is ., so every pipeline of a branch has its own key and + // the branch is the key without its last part. appliedRun := "" if w.Want.Run != "" { h, found, unread := a.readHave(ctx, module) @@ -1548,7 +1549,7 @@ func (a *Agent) settleOne(ctx context.Context, module string) { a.mu.Unlock() return } - if found && h.Pipeline == w.Want.Pipeline { + if found && pipelineBranch(h.Pipeline) == pipelineBranch(w.Want.Pipeline) { appliedRun = h.Run } } @@ -1903,6 +1904,15 @@ func (a *Agent) takenAtStart(module string, runs compositions.Composed) { // pipeline (settleOne compares no runs of two, H-A-458 (1)): each is // the composition run's pipeline sequence in decimal. A want or an apply without one is not ordered by run, nor is a run // that is no decimal number. +// pipelineBranch is the branch of a pipeline's key . (design 47 H1, the runner's key; H-A-458 (1)): the +// key without its last part. A key with no source part is its own branch. +func pipelineBranch(key string) string { + if i := strings.LastIndexByte(key, '.'); i >= 0 { + return key[:i] + } + return key +} + func runIsNewer(want, applied string) bool { if want == "" || applied == "" { return true diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index d1c96b92..a8327a46 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -394,12 +394,13 @@ func testAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) { if got := len(b.appliedList()) - before; got != 0 { t.Errorf("a want of run 10 after a have of run 20: applied %d times, want none", got) } - // H-A-429 (1), H-A-458 (1): a want's run is compared with the have's only within one pipeline: a lower run of another - // pipeline replaces what stands, and the have keeps that pipeline beside its run; a lower run of the same is refused. + // H-A-429 (1), H-A-458 (1): a want's run is compared with the have's only within one branch, a pipeline's key being + // .: a lower run of another branch replaces what stands, and the have keeps its pipeline beside its + // run; a lower run of an older pipeline of the same branch is refused. for _, row := range []struct { fp, run, pipeline string applied int - }{{"7", "10", "feat.mesh-host", 1}, {"8", "9", "feat.mesh-host", 0}} { + }{{"7", "10", "feat.10", 1}, {"8", "9", "feat.9", 0}, {"b", "5", "main.5", 1}} { before := len(b.appliedList()) fpr := fpOf(row.fp) ckr, crawr, digr := composition(t, "web", fpr, false, archive("a", d2)) @@ -412,8 +413,8 @@ func testAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) { t.Errorf("a want of run %s of pipeline %s: applied %d times, want %d", row.run, row.pipeline, got, row.applied) } } - if h := b.haves.last("web"); h.Run != "10" || h.Pipeline != "feat.mesh-host" { - t.Errorf("the have names run %q of pipeline %q, want run 10 of feat.mesh-host", h.Run, h.Pipeline) + if h := b.haves.last("web"); h.Run != "5" || h.Pipeline != "main.5" { + t.Errorf("the have names run %q of pipeline %q, want run 5 of main.5", h.Run, h.Pipeline) } b.mu.Lock() said := strings.Join(b.said, "\n") diff --git a/internal/link/have_test.go b/internal/link/have_test.go index d1fdc7c0..4ed84058 100644 --- a/internal/link/have_test.go +++ b/internal/link/have_test.go @@ -772,10 +772,10 @@ func testAnAppliedModulesHaveNamesTheFingerprintAndTheDigestAndFollowsItsHealth( fp := "src2:" + strings.Repeat("a", 64) dig := "sha256:" + strings.Repeat("b", 64) // H-A-458 (1): the run it was applied from is kept with the pipeline of its want. - q.NoteModule(context.Background(), ModuleFact{Module: "web", FP: fp, Composed: dig, Run: "12", Pipeline: "main.mesh-host"}) + q.NoteModule(context.Background(), ModuleFact{Module: "web", FP: fp, Composed: dig, Run: "12", Pipeline: "main.12"}) h := l.have(t, "n1.web") if h.Fp != fp || h.Composed != dig || h.Phase != nodeengineclient.PhaseRunning || h.Health != nodeengineclient.HealthUnknown || - h.Run != "12" || h.Pipeline != "main.mesh-host" { + h.Run != "12" || h.Pipeline != "main.12" { t.Fatalf("the have after the apply: %+v", h) } // Design 47, *What each step says*: running is said once, when the build is healthy and its manifest is known, on -- 2.54.0