package ntfy import ( "fmt" "strings" "testing" "time" ) // The budget allows limit receipts in any window, not limit per refill: a // sixth receipt waits until the first is a whole window old. func TestBudget(t *testing.T) { t0 := time.Date(2026, 11, 30, 21, 0, 0, 0, time.UTC) b := budget{limit: 5, window: 10 * time.Minute} for i := range 5 { now := t0.Add(time.Duration(i) * time.Minute) if !b.room(now) { t.Fatalf("no room for receipt %d", i+1) } b.spend(now) } at := t0.Add(5 * time.Minute) if b.room(at) { t.Fatal("room for a sixth receipt within the window") } if next := b.next(at); !next.Equal(t0.Add(10 * time.Minute)) { t.Errorf("next = %s, want when the first receipt is 10 minutes old", next) } if !b.room(t0.Add(10 * time.Minute)) { t.Error("no room once the first receipt left the window") } // A receipt dated in the future, as after the clock went back, counts // as printed now rather than blocking for longer than a window. b = budget{limit: 1, window: time.Minute, prints: []time.Time{t0.Add(time.Hour)}} if b.room(t0) { t.Error("room with a receipt just counted") } if !b.room(t0.Add(time.Minute)) { t.Error("a receipt dated in the future blocked for more than a window") } } func TestRing(t *testing.T) { var items []string for i := range ringSize + 10 { items = append(items, fmt.Sprint(i)) } r := newRing(items) if r.has("9") || !r.has("10") || !r.has(fmt.Sprint(ringSize+9)) { t.Error("the ring kept the wrong items") } if got := r.list(); len(got) != ringSize || got[0] != "10" { t.Errorf("list has %d items from %q", len(got), got[0]) } // An item added twice stays until both copies are forgotten. r = newRing([]string{"a", "a"}) for i := range ringSize - 1 { r.add(fmt.Sprint(i)) } if !r.has("a") { t.Error("forgot a while one copy is left") } r.add("x") if r.has("a") { t.Error("remembers a after both copies left") } } func TestHeldRows(t *testing.T) { now := time.Date(2026, 11, 30, 21, 5, 0, 0, time.UTC) var h held h.add(Message{ID: "a", Time: now.Unix(), Title: strings.Repeat("é", 200), Tags: []string{"warning"}, RawPriority: 4}, false, false, now) h.add(Message{ID: "b", Message: "\n \nfirst line\nsecond"}, true, true, now.Add(time.Minute)) if h.Count != 2 || !h.Overnight || h.Since != now.Unix() { t.Errorf("held %+v", h) } if row := h.Rows[0]; len(row.Title) > maxRowText || !strings.HasPrefix(row.Title, "é") || row.FirstLine != "" || row.Priority != 4 { t.Errorf("row %+v", row) } if row := h.Rows[1]; row.FirstLine != "first line" || !row.Updated || row.Priority != 3 { t.Errorf("row %+v", row) } d := h.digest(now.Add(9 * time.Minute)) if d.Count != 2 || !d.Since.Equal(now) || !d.Until.Equal(now.Add(9*time.Minute)) || len(d.Rows) != 2 { t.Errorf("digest %+v", d) } }