package metrics import ( "testing" ) func TestRecordAndSnapshot(t *testing.T) { c := NewCollector() c.Record(200) c.Record(200) c.Record(500) c.Record(404) reqs, rates, hours, totalReq, totalErr := c.Snapshot24h() if len(reqs) != 24 || len(rates) != 24 || len(hours) != 24 { t.Fatalf("snapshot 长度应为 24: req=%d rates=%d hours=%d", len(reqs), len(rates), len(hours)) } if totalReq != 4 || totalErr != 2 { t.Fatalf("窗口统计错误: totalReq=%d totalErr=%d", totalReq, totalErr) } // 当前小时桶应有 4 请求 if reqs[23] != 4 { t.Fatalf("当前小时请求量 = %d, 期望 4", reqs[23]) } if rates[23] < 49 || rates[23] > 51 { t.Fatalf("当前小时错误率 = %v, 期望约 50", rates[23]) } tr, te, t5, _ := c.Totals() if tr != 4 || te != 2 || t5 != 1 { t.Fatalf("累计统计错误: req=%d err=%d 5xx=%d", tr, te, t5) } }