package agent import ( "net/http" "testing" "time" "github.com/x-grk/longpolling-remote-access/internal/proto" ) // updates counts what an agent was made to update with. type updates struct{ n int } func (u *updates) do() proto.TaskResult { u.n++; return proto.TaskResult{OK: true} } // The agent is told, by headers or by the WebSocket's message, how often to // compare versions; nothing told, nothing done. func TestAutoUpdateIsTold(t *testing.T) { a := New(Config{}) if a.autoUpdateOn() { t.Fatal("on with nothing told") } h := http.Header{} h.Set(proto.AutoUpdateHeader, "90") h.Set(proto.ServerVersionHeader, "9.9.9") a.applyUpdateHeaders(h) if m, v := a.updateInfo(); m != 90 || v != "9.9.9" { t.Fatalf("by headers: %d %q", m, v) } a.applyUpdateInfo(0, "9.9.9") if a.autoUpdateOn() { t.Fatal("still on after being told 0") } a.applyUpdateInfo(30, "9.9.9") if m, _ := a.updateInfo(); m != 30 { t.Fatalf("by the message: %d", m) } // Rubbish is not taken for a number. h.Set(proto.AutoUpdateHeader, "soon") a.applyUpdateHeaders(h) if m, _ := a.updateInfo(); m != 0 { t.Fatalf("rubbish: %d", m) } } // When the interval is out the agent looks; it updates only to a newer // version of the server's, and tries again the next time if it did not work. func TestAutoUpdateTick(t *testing.T) { a := New(Config{}) u := &updates{} now := time.Now() a.applyUpdateInfo(60, "9.9.9") if !a.autoUpdateTick(now, u.do) || u.n != 1 { t.Fatalf("a newer server: %d updates", u.n) } if a.autoUpdateTick(now.Add(30*time.Minute), u.do) || u.n != 1 { t.Fatalf("before the interval is out: %d updates", u.n) } if !a.autoUpdateTick(now.Add(61*time.Minute), u.do) || u.n != 2 { t.Fatalf("at the next time: %d updates", u.n) } // The same, an older one, a build that is not a version: nothing. for _, v := range []string{Version, "0.0.1", "dev", ""} { b := New(Config{}) b.applyUpdateInfo(60, v) if b.autoUpdateTick(now, u.do) { t.Fatalf("updated to %q", v) } } // Off: nothing, whatever the server has. c := New(Config{}) c.applyUpdateInfo(0, "9.9.9") if c.autoUpdateTick(now, u.do) || u.n != 2 { t.Fatalf("off, yet updated: %d", u.n) } }