package link import ( "errors" "testing" "time" "github.com/nats-io/nats.go" ) // An ask a machine holds but does not start gets no heartbeat, and the bus hands it to another machine after the ack // wait, so two machines run one check (issue 1649). type fakeHeld struct{ msgs []*nats.Msg } func (f *fakeHeld) NextMsg(time.Duration) (*nats.Msg, error) { if len(f.msgs) == 0 { return nil, nats.ErrTimeout } m := f.msgs[0] f.msgs = f.msgs[1:] return m, nil } type brokenHeld struct{} func (brokenHeld) NextMsg(time.Duration) (*nats.Msg, error) { return nil, errors.New("closed") } func TestEveryMessageAPullHoldsIsHandedBackBeforeABuildStarts(t *testing.T) { a := &fakeHeld{msgs: []*nats.Msg{{Subject: "a1"}, {Subject: "a2"}}} b := &fakeHeld{msgs: []*nats.Msg{{Subject: "b1"}}} var back []string n := handBackHeld([]heldSource{a, brokenHeld{}, b}, func(m *nats.Msg) { back = append(back, m.Subject) }) if n != 3 || len(back) != 3 || back[0] != "a1" || back[2] != "b1" { t.Fatalf("handed back %d %v; want a1 a2 b1", n, back) } if n := handBackHeld([]heldSource{a, b}, func(*nats.Msg) { t.Fatal("handed back what was not held") }); n != 0 { t.Fatalf("a second pass handed back %d", n) } } func TestAnAskAnotherBuilderIsRunningIsADuplicateAndYoursIsNot(t *testing.T) { r := aPullCheck("build-1", 423, "head-4771ee53aa", "trunk-0123456789", false) run := CheckRunning{Head: r.Ref, Trunk: "trunk-0123456789", Builder: "shanks", Build: "build-1", Started: time.Now()} for name, c := range map[string]struct { running CheckRunning found bool me string dup bool }{ "another builder runs this very ask": {run, true, "ace", true}, "this builder runs it itself": {run, true, "shanks", false}, "nobody runs it": {CheckRunning{}, false, "ace", false}, "another ask of the same head": {CheckRunning{Head: r.Ref, Trunk: "trunk-0123456789", Builder: "shanks", Build: "build-0"}, true, "ace", false}, "the same ask at another head": {CheckRunning{Head: "head-other-0000", Trunk: "trunk-0123456789", Builder: "shanks", Build: "build-1"}, true, "ace", false}, } { if got := duplicateOf(c.running, c.found, r, c.me) != ""; got != c.dup { t.Errorf("%s: duplicate = %v; want %v", name, got, c.dup) } } }