package alive import ( "encoding/json" "errors" "sync" "testing" "time" ) type said struct { mu sync.Mutex subs []string body [][]byte fail error // tried is told every Say, said or not, so a test waits on the heartbeat itself and never on the clock. tried chan struct{} } func newSaid(fail error) *said { return &said{fail: fail, tried: make(chan struct{}, 16)} } func (s *said) Say(subject string, body []byte) error { s.mu.Lock() defer func() { s.mu.Unlock(); s.tried <- struct{}{} }() if s.fail != nil { return s.fail } s.subs, s.body = append(s.subs, subject), append(s.body, body) return nil } func (s *said) count() int { s.mu.Lock() defer s.mu.Unlock() return len(s.subs) } // **The runtime says it is there at once and every interval, as its machine, with the interval**: the // controller's bound is three of them (to-be 45 S11). The ticks are the test's own, so a loaded machine // cannot make it miss one (principle 11; design 47 H ยง774); stopped, it says nothing more. func TestTheRuntimeSaysItIsThereEveryInterval(t *testing.T) { s := newSaid(nil) ticks := make(chan time.Time) stop := keep(s, "anchor", 20*time.Millisecond, ticks, t.Logf) <-s.tried for i := 0; i < 2; i++ { ticks <- time.Time{} <-s.tried } stop() stop() if n := s.count(); n != 3 { t.Fatalf("said %d times at once and on two ticks", n) } var beat Beat if err := json.Unmarshal(s.body[0], &beat); err != nil || beat.Node != "anchor" || beat.IntervalSeconds != 0 || s.subs[0] != "mesh.control.anchor.tools-alive" { t.Fatalf("%s on %s: %v", s.body[0], s.subs[0], err) } select { case ticks <- time.Time{}: t.Fatal("a tick was taken after it was stopped") default: } if s.count() != 3 { t.Fatal("said after it was stopped") } // Keep itself keeps the interval on a ticker of its own. kept := newSaid(nil) stopKept := Keep(kept, "anchor", time.Hour, t.Logf) <-kept.tried stopKept() if kept.count() != 1 { t.Fatalf("Keep said %d times before its first interval", kept.count()) } } // **A heartbeat the bus will not take is said once, and again when it is taken**: not a line a minute. func TestAHeartbeatThatCannotBeSaidIsLoggedOnce(t *testing.T) { s := newSaid(errors.New("permissions violation")) var mu sync.Mutex var lines []string ticks := make(chan time.Time) stop := keep(s, "anchor", 10*time.Millisecond, ticks, func(f string, a ...any) { mu.Lock() lines = append(lines, f) mu.Unlock() }) <-s.tried for i := 0; i < 4; i++ { ticks <- time.Time{} <-s.tried } stop() mu.Lock() defer mu.Unlock() if len(lines) != 1 { t.Fatalf("logged %d lines for one failure", len(lines)) } }