Files
mesh-delivery/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/main_test.go
T
jschoubben 058b2458fb §626 (teller, bridge, runner, watchman): the own-module guards are folded into an existing test each
The four TestNoCode...OwnModule functions became helpers called by TestTheNamesAreTheManifests, TestMergeCallsTheToolOnceAndWritesTheMergedMessage, TestTools and TestNoTickerTimerOrSleep, so no module ends with more tests than its merge base for them.

Builds: design 47 G §626, §428, A-296

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
2026-11-12 22:58:54 +01:00

358 lines
16 KiB
Go

package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log"
"slices"
"strings"
"sync"
"testing"
"time"
condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
git "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
"git.novox.be/novox/mesh-sdk/go/process"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg"
"mesh-delivery-forge-bridge/internal/bridge"
"mesh-delivery-forge-bridge/internal/gitfixture"
)
const head = "0123456789abcdef0123456789abcdef01234567"
type fakeMsg struct {
subject string
data []byte
acked, termd int
nak []time.Duration
}
func (f *fakeMsg) Subject() string { return f.subject }
func (f *fakeMsg) Data() []byte { return f.data }
func (f *fakeMsg) Headers() nats.Header { return nats.Header{"X-Event-Id": {"ev-1"}} }
func (f *fakeMsg) Ack() error { f.acked++; return nil }
func (f *fakeMsg) NakWithDelay(d time.Duration) error { f.nak = append(f.nak, d); return nil }
func (f *fakeMsg) Term() error { f.termd++; return nil }
type fakePub struct {
subjects []string
data [][]byte
err error
}
func (p *fakePub) Publish(_ context.Context, subject string, payload []byte, _ ...jetstream.PublishOpt) (*jetstream.PubAck, error) {
if p.err != nil {
return nil, p.err
}
p.subjects, p.data = append(p.subjects, subject), append(p.data, payload)
return &jetstream.PubAck{}, nil
}
// body is the seat git's pull.updated (modules/mesh-delivery-contracts/seats/git), the head head_sha laid over it when given.
func body(m map[string]any) []byte {
e := map[string]any{"repository": "novox/mesh-delivery", "number": 12, "branch": "feat/x", "head": head, "base": "main",
"change": map[string]any{"paths": []string{"modules/a/x.go"}, "module-dirs": []string{"modules/a"}}}
if h, ok := m["head_sha"]; ok {
e["head"] = h
}
b, _ := json.Marshal(e)
return b
}
func TestReadableEventIsWrittenOnForgeAndAcked(t *testing.T) { // 1235/AC2 (unit part; the bus is the integration test)
t.Run("1945: a refused bucket is said, or stops the start naming its grant", func(t *testing.T) {
refusal := errors.New("nats: permissions violation for publish to $JS.API.STREAM.INFO.KV_x")
var said []string
if kv := process.OptionalBucket(context.Background(), refusingBus{refusal}, "x", "x is not heard", func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) }); kv != nil || len(said) != 1 || !strings.Contains(said[0], "permissions violation") {
t.Errorf("an optional bucket refused: %v, said %v", kv, said)
}
if _, err := process.EssentialBucket(context.Background(), refusingBus{refusal}, "bridge", "x", "work"); err == nil || !strings.Contains(err.Error(), "grant of x") {
t.Errorf("an essential bucket refused: %v, want its grant named", err)
}
})
var logs bytes.Buffer
m, pub := &fakeMsg{subject: git.SubjectPullUpdated, data: body(nil)}, &fakePub{}
handle(context.Background(), m, pub, someFiles, watchesMain(), log.New(&logs, "", 0))
if len(pub.subjects) != 1 || pub.subjects[0] != "mesh.stream.mesh-delivery-forge-bridge.event.forge.novox.mesh-delivery.pull" {
t.Fatalf("published on %v", pub.subjects)
}
f, err := forgemsg.DecodeForge(pub.data[0])
if err != nil || f.Number != 12 || f.Branch != "feat/x" || f.Head != head || f.Action != "updated" || !f.DirsKnown {
t.Errorf("message %+v err %v", f, err)
}
if m.acked != 1 || m.termd != 0 {
t.Errorf("acked %d terminated %d", m.acked, m.termd)
}
}
func TestUnreadableEventIsTerminatedAndLogged(t *testing.T) { // 1235/AC5
var logs bytes.Buffer
m, pub := &fakeMsg{subject: git.SubjectPullUpdated, data: body(map[string]any{"head_sha": "short"})}, &fakePub{}
handle(context.Background(), m, pub, someFiles, watchesMain(), log.New(&logs, "", 0))
if len(pub.subjects) != 0 {
t.Errorf("a message was written: %v", pub.subjects)
}
if m.termd != 1 || m.acked != 0 {
t.Errorf("terminated %d acked %d, want terminated once", m.termd, m.acked)
}
if !strings.Contains(logs.String(), git.SubjectPullUpdated) || !strings.Contains(logs.String(), "head") {
t.Errorf("log %q names neither the subject nor why", logs.String())
}
// 1235: an unwritten message is not acked (a failed write is redelivered by the server, not retried here); merged here
// from a test of its own, for the test budget.
logs.Reset()
m, pub = &fakeMsg{subject: git.SubjectPullUpdated, data: body(nil)}, &fakePub{err: errors.New("no stream")}
handle(context.Background(), m, pub, someFiles, watchesMain(), log.New(&logs, "", 0))
if m.acked != 0 || m.termd != 0 {
t.Errorf("acked %d terminated %d, want neither", m.acked, m.termd)
}
if !strings.Contains(logs.String(), "no stream") {
t.Errorf("log %q", logs.String())
}
}
// watchesMain watches main of every repository, as the gate's source names it before the first registration.
func watchesMain() *bridge.Watched {
w := &bridge.Watched{}
w.Set(nil, []string{"main"})
return w
}
// movedEvent is the seat git's branch-moved of main of novox/mesh-delivery, naming a head the bridge never takes.
func movedEvent(branch string) []byte {
b, _ := json.Marshal(map[string]any{"repository": "novox/mesh-delivery", "branch": branch, "head": strings.Repeat("f", 40)})
return b
}
const landed = "89abcdef0123456789abcdef0123456789abcdef"
// moveCall answers the seat git as a forge whose main of novox/mesh-delivery is protected at landed, merged there by #12;
// trees answers trees, every other verb answers err.
func moveCall(trees json.RawMessage, err error, keys *[]string, args *[]any, mu *sync.Mutex) caller {
return func(_ context.Context, key string, body any) (json.RawMessage, error) {
mu.Lock()
*keys, *args = append(*keys, key), append(*args, body)
mu.Unlock()
switch key {
case "seat:git.branch":
return json.RawMessage(`{"repository":"novox/mesh-delivery","branch":"main","head":"` + landed + `","protected":true}`), nil
case "seat:git.pull":
return json.RawMessage(`{"pull":{"repository":"novox/mesh-delivery","number":12,"branch":"feat/x","head":"` + head + `","base":"main","state":"merged","merge-commit":"` + landed + `"}}`), nil
case "seat:git.trees":
if trees != nil {
return trees, nil
}
}
return nil, err
}
}
func newMover(call caller, pub publisher, heads headStore, logs *bytes.Buffer) *mover {
return &mover{call: call, pub: pub, heads: heads, watched: watchesMain(), turn: &sync.Mutex{}, logger: log.New(logs, "", 0)}
}
func TestTreesRefusedLeavesTheEventForTenSecondsAndLogs(t *testing.T) { // 1236/AC3
var logs bytes.Buffer
var keys []string
var args []any
var mu sync.Mutex
m, pub, heads := &fakeMsg{subject: bridge.BranchMovedSubject, data: movedEvent("main")}, &fakePub{}, newHeads()
newMover(moveCall(nil, errors.New("the tree listing of novox/mesh-delivery was cut"), &keys, &args, &mu), pub, heads, &logs).hear(context.Background(), m)
if len(pub.subjects) != 0 || heads.get("branch.novox.mesh-delivery.main") != "" {
t.Errorf("a message was written: %v", pub.subjects)
}
if m.acked != 0 || m.termd != 0 || len(m.nak) != 1 || m.nak[0] < 10*time.Second {
t.Errorf("acked %d terminated %d naks %v, want one nak of at least 10 s", m.acked, m.termd, m.nak)
}
for _, w := range []string{"novox/mesh-delivery", landed, "the tree listing of novox/mesh-delivery was cut"} {
if !strings.Contains(logs.String(), w) {
t.Errorf("log %q does not name %q", logs.String(), w)
}
}
}
// 1236/AC1; design 47 *The seat git* (verbs trees, file); design 47 G §11, §20, §509 (FB1, FB10): a move of a watched branch
// is taken by the seat's verb branch, never the event's head, written once as merged with its pull request and base, and
// its head kept, so the same move heard again writes nothing; a move of a branch not watched writes nothing.
func TestMergeCallsTheToolOnceAndWritesTheMergedMessage(t *testing.T) {
noCodeNamesTheBridgesOwnModule(t)
var logs bytes.Buffer
var keys []string
var args []any
var mu sync.Mutex // the files are asked for concurrently (issue 1458)
trees := gitfixture.Given(t, "trees answers", "verb:trees.answer") // root ddd…, "" ddd…, contracts eee…
call := moveCall(trees, nil, &keys, &args, &mu)
file := gitfixture.Given(t, "file answers", "verb:file.answer")
files := func(ctx context.Context, key string, body any) (json.RawMessage, error) {
if key == "seat:git.file" { // the manifests, 1448; the trees are what this test is about
mu.Lock()
keys = append(keys, key)
mu.Unlock()
return file, nil
}
return call(ctx, key, body)
}
m, pub, heads := &fakeMsg{subject: bridge.BranchMovedSubject, data: movedEvent("main")}, &fakePub{}, newHeads()
mv := newMover(files, pub, heads, &logs)
mv.hear(context.Background(), m)
if len(keys) < 3 || keys[0] != "seat:git.branch" || keys[1] != "seat:git.pull" || keys[2] != "seat:git.trees" || slices.Index(keys[3:], "seat:git.trees") >= 0 {
t.Fatalf("calls %v, want the branch, its pull, then the trees once", keys)
}
if got, _ := json.Marshal(args[2]); !sameJSON(got, []byte(`{"repository":"novox/mesh-delivery","commit":"`+landed+`"}`)) {
t.Errorf("arguments %s", got)
}
if len(pub.subjects) != 1 || pub.subjects[0] != "mesh.stream.mesh-delivery-forge-bridge.event.forge.novox.mesh-delivery.merged" {
t.Fatalf("published on %v", pub.subjects)
}
f, err := forgemsg.DecodeForge(pub.data[0])
d, e := strings.Repeat("d", 40), strings.Repeat("e", 40)
if err != nil || f.Root != d || f.Trees[""] != d || f.Trees["contracts"] != e || f.Merge != landed || f.Base != "main" || f.Number != 12 || f.Branch != "feat/x" {
t.Errorf("message %+v err %v", f, err)
}
if m.acked != 1 || heads.get("branch.novox.mesh-delivery.main") != landed {
t.Errorf("acked %d, head kept %q", m.acked, heads.get("branch.novox.mesh-delivery.main"))
}
again, other := &fakeMsg{subject: bridge.BranchMovedSubject, data: movedEvent("main")}, &fakeMsg{subject: bridge.BranchMovedSubject, data: movedEvent("feat/x")}
mv.hear(context.Background(), again)
mv.hear(context.Background(), other)
if len(pub.subjects) != 1 || again.acked != 1 || other.acked != 1 {
t.Errorf("the same move again and a move of a branch not watched wrote %d messages (acked %d, %d), want none", len(pub.subjects)-1, again.acked, other.acked)
}
}
func TestAnAnswerWithoutARootIsNotUsed(t *testing.T) { // 1236 (a shape the seat does not answer); design 47 *A failed read answers an error*
for _, raw := range []json.RawMessage{json.RawMessage(`{"trees":{"a":"t"}}`), json.RawMessage(`[1]`),
gitfixture.Given(t, "trees answers an error, never none", "verb:trees.answer")} {
call := func(context.Context, string, any) (json.RawMessage, error) { return raw, nil }
if _, _, err := treesVia(context.Background(), call)("o", "r", "s"); err == nil {
t.Errorf("the answer %s was taken", raw)
}
}
}
func TestFilesViaAsksByOwnerRepoPathRefAndTakesTheContent(t *testing.T) { // 1448/AC4; design 47 *The seat git* (verb file)
var keys []string
var args []any
call := func(_ context.Context, key string, body any) (json.RawMessage, error) {
keys, args = append(keys, key), append(args, body)
return gitfixture.Given(t, "file answers", "verb:file.answer"), nil
}
got, err := filesVia(context.Background(), call)("novox", "mesh-contracts", "seats/index.json", strings.Repeat("a", 40))
if err != nil || string(got) != `{"format":1,"seats":["mesh-broker"]}` {
t.Fatalf("got %q err %v", got, err)
}
if len(keys) != 1 || keys[0] != "seat:git.file" {
t.Fatalf("calls %v", keys)
}
want := gitfixture.Given(t, "file asks", "verb:file.input")
if b, _ := json.Marshal(args[0]); !sameJSON(b, want) {
t.Errorf("arguments %s, want the seat's %s", b, want)
}
}
func TestFilesViaTellsNotFoundFromOtherErrorsAndOtherShapes(t *testing.T) { // 1448/AC3; design 47 *A failed read answers an error*
call := func(err error, raw json.RawMessage) caller {
return func(context.Context, string, any) (json.RawMessage, error) { return raw, err }
}
absent := gitfixture.All(t, "file answers", "verb:file.answer")[1]
if _, err := filesVia(context.Background(), call(nil, absent))("o", "r", "p", "s"); !errors.Is(err, bridge.ErrNotFound) {
t.Errorf("an absent file is %v, want ErrNotFound", err)
}
if _, err := filesVia(context.Background(), call(errors.New("nats: timeout"), nil))("o", "r", "p", "s"); err == nil || errors.Is(err, bridge.ErrNotFound) {
t.Errorf("a seat that does not answer is %v, want an error that is not ErrNotFound", err)
}
for _, raw := range []json.RawMessage{gitfixture.Given(t, "file answers an error, never none", "verb:file.answer"), json.RawMessage(`{}`), json.RawMessage(`[1]`), json.RawMessage(`{"path":"p"}`)} {
if _, err := filesVia(context.Background(), call(nil, raw))("o", "r", "p", "s"); err == nil || errors.Is(err, bridge.ErrNotFound) {
t.Errorf("the answer %s gave %v, want an error", raw, err)
}
}
}
// sameJSON is whether two JSON texts say the same value.
func sameJSON(a, b []byte) bool {
var x, y any
if json.Unmarshal(a, &x) != nil || json.Unmarshal(b, &y) != nil {
return false
}
ax, _ := json.Marshal(x)
by, _ := json.Marshal(y)
return bytes.Equal(ax, by)
}
// someFiles is a forge that has a module.json at every path and no other file, for the tests that are not about the files.
func someFiles(_, _, path, _ string) ([]byte, error) {
if strings.HasSuffix(path, "module.json") {
return []byte("{}"), nil
}
return nil, bridge.ErrNotFound
}
// refusingBus refuses every bucket with err (issue 1945).
type refusingBus struct{ err error }
func (r refusingBus) KeyValue(context.Context, string) (jetstream.KeyValue, error) { return nil, r.err }
// fakeFindings is a finding writer that holds what it is given.
type fakeFindings struct {
held []condseat.Finding
cleared []string
}
func (f *fakeFindings) Write(_ context.Context, w condseat.Finding) error {
f.held = append(f.held, w)
return nil
}
func (f *fakeFindings) Clear(_ context.Context, scope, id, kind, _ string) error {
f.cleared = append(f.cleared, scope+"."+id+"."+kind)
f.held = nil
return nil
}
func (f *fakeFindings) Held() []condseat.Finding { return f.held }
// Design 47 G §17, A-251 (FB2): a move of a watched branch whose protection was removed writes nothing and says the finding
// branch-unprotected, scope merge, its id the owner, repository and branch escaped as a key; a move that finds the protection
// back clears it, and a protected branch with no finding held says nothing.
func TestAnUnprotectedBranchIsSaidAsAFindingAndClearedWhenItIsBack(t *testing.T) {
var logs bytes.Buffer
protected := false
call := func(_ context.Context, key string, _ any) (json.RawMessage, error) {
if key == "seat:git.branch" {
return json.RawMessage(fmt.Sprintf(`{"repository":"novox/mesh-delivery","branch":"beta","head":"%s","protected":%t}`, landed, protected)), nil
}
return nil, errors.New("not asked: " + key)
}
pub, heads, findings := &fakePub{}, newHeads(), &fakeFindings{}
mv := newMover(call, pub, heads, &logs)
mv.findings, mv.now = findings, func() time.Time { return time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC) }
mv.watched = &bridge.Watched{}
mv.watched.Set(nil, []string{"beta"})
mv.hear(context.Background(), &fakeMsg{subject: bridge.BranchMovedSubject, data: movedEvent("beta")})
if len(pub.subjects) != 0 || len(findings.held) != 1 {
t.Fatalf("written %v, findings %+v: want nothing written and one finding", pub.subjects, findings.held)
}
f := findings.held[0]
if f.Scope != "merge" || f.ID != "novox/mesh-delivery/beta" || f.Kind != "branch-unprotected" || f.Severity != "warning" || f.Observer != "mesh-delivery-forge-bridge" ||
f.Subject.Scope != "merge" || f.Subject.ID != "novox/mesh-delivery/beta" || !strings.Contains(f.Summary, "beta") {
t.Errorf("the finding = %+v", f)
}
// The protection is back at a move whose head the bridge wrote already: the finding is cleared.
protected = true
heads.vals["branch.novox.mesh-delivery.beta"] = landed
mv.hear(context.Background(), &fakeMsg{subject: bridge.BranchMovedSubject, data: movedEvent("beta")})
if len(findings.cleared) != 1 || findings.cleared[0] != "merge.novox/mesh-delivery/beta.branch-unprotected" || len(findings.held) != 0 {
t.Errorf("cleared %v held %+v, want the finding cleared", findings.cleared, findings.held)
}
mv.hear(context.Background(), &fakeMsg{subject: bridge.BranchMovedSubject, data: movedEvent("beta")})
if len(findings.cleared) != 1 {
t.Errorf("cleared %v: a protected branch with no finding held clears nothing", findings.cleared)
}
}