package anthropic import ( "os" "testing" ) // The test runs against the real shape captured from the endpoint, not an // invented JSON: it is the only way to notice if the contract changes. func loadFixture(t *testing.T) []byte { t.Helper() raw, err := os.ReadFile("testdata/usage.json") if err != nil { t.Fatal(err) } return raw } func TestParseUsageRealShape(t *testing.T) { u, err := ParseUsage(loadFixture(t)) if err != nil { t.Fatal(err) } if len(u.Windows) != 3 { t.Fatalf("windows = %d, want 3", len(u.Windows)) } session := u.Find(KindSession) if session == nil || session.Percent != 12 || session.Severity != "normal" { t.Errorf("session = %+v", session) } if session.ResetsAt == nil { t.Error("session has no resets_at") } weekly := u.Find(KindWeeklyAll) if weekly == nil || weekly.Percent != 30 || !weekly.IsActive { t.Errorf("weekly_all = %+v", weekly) } // What the spike uncovered: the per-model breakdown is not in // seven_day_opus/sonnet (null) but here, with the name the server picks. scoped := u.Find(KindWeeklyScoped) if scoped == nil || scoped.Model != "Fable" || scoped.Percent != 9 { t.Errorf("weekly_scoped = %+v, want model=Fable percent=9", scoped) } if u.ExtraUsageEnabled { t.Error("extra_usage reads as enabled, the fixture says false") } } // Code-named fields (tangelo, iguana_necktie, nimbus_quill...) must neither // break parsing nor end up among the windows. func TestParseUsageIgnoresUnknownFields(t *testing.T) { u, err := ParseUsage([]byte(`{ "limits": [{"kind":"session","group":"session","percent":5,"severity":"normal","is_active":true}], "wildcard_feature": {"utilization": 99.0}, "qualcosa_di_nuovo": [1,2,3] }`)) if err != nil { t.Fatal(err) } if len(u.Windows) != 1 || u.Windows[0].Percent != 5 { t.Errorf("windows = %+v", u.Windows) } } // If limits[] disappears we fall back to the top-level fields, where // utilization is a float that needs rounding. func TestParseUsageFallsBackToTopLevel(t *testing.T) { u, err := ParseUsage([]byte(`{ "limits": [], "five_hour": {"utilization": 12.4, "resets_at": "2026-08-27T14:59:59Z"}, "seven_day": {"utilization": 30.6, "resets_at": "2026-08-28T00:59:59Z"} }`)) if err != nil { t.Fatal(err) } if w := u.Find(KindSession); w == nil || w.Percent != 12 { t.Errorf("session = %+v, want percent=12", w) } if w := u.Find(KindWeeklyAll); w == nil || w.Percent != 31 { t.Errorf("weekly = %+v, want percent=31 (rounded)", w) } } func TestParseUsageRejectsEmpty(t *testing.T) { if _, err := ParseUsage([]byte(`{"limits": []}`)); err == nil { t.Error("a response with no windows must be an error, not a zeroed state") } } func TestClampPercent(t *testing.T) { for _, tc := range []struct { in float64 want int }{{-5, 0}, {0, 0}, {12.4, 12}, {30.6, 31}, {100, 100}, {140, 100}} { if got := clampPercent(tc.in); got != tc.want { t.Errorf("clampPercent(%v) = %d, want %d", tc.in, got, tc.want) } } }