返回 DeepSeek-Reasonix
usage_test.go
根目录 / internal / agent / usage_test.go
1 package agent
2
3 import (
4 "strings"
5 "testing"
6
7 "reasonix/internal/event"
8 "reasonix/internal/provider"
9 )
10
11 // renderUsage drives a Usage event through a fresh TextSink (no renderer) and
12 // returns what it wrote — the usage line, exercised through the event path.
13 func renderUsage(u *provider.Usage, p *provider.Pricing, d ...*event.CacheDiagnostics) string {
14 var b strings.Builder
15 var diag *event.CacheDiagnostics
16 if len(d) > 0 {
17 diag = d[0]
18 }
19 e := event.Event{Kind: event.Usage, Usage: u, Pricing: p, CacheDiagnostics: diag}
20 e.CostQuote = event.EnsureCostQuote(e, nil)
21 NewTextSink(&b, nil, 80).Emit(e)
22 return b.String()
23 }
24
25 func TestUsageLine(t *testing.T) {
26 u := &provider.Usage{
27 PromptTokens: 1000,
28 CompletionTokens: 200,
29 TotalTokens: 1200,
30 CacheHitTokens: 900,
31 CacheMissTokens: 100,
32 }
33
34 if out := renderUsage(u, nil); !strings.Contains(out, "1200 tok") || !strings.Contains(out, "900 cached / 100 new") {
35 t.Errorf("usage line = %q (want 1200 tok and 900 cached / 100 new)", out)
36 }
37
38 // With pricing: 900*0.02 + 100*1 + 200*2 = 518 per 1M = 0.000518 -> "¥0.0005".
39 if out := renderUsage(u, &provider.Pricing{CacheHit: 0.02, Input: 1, Output: 2, Currency: "¥"}); !strings.Contains(out, "¥0.0005") {
40 t.Errorf("cost line = %q (want ¥0.0005...)", out)
41 }
42
43 // nil or zero usage prints nothing.
44 if out := renderUsage(nil, nil) + renderUsage(&provider.Usage{}, nil); out != "" {
45 t.Errorf("nil/zero usage should print nothing, got %q", out)
46 }
47 }
48
49 // TestUsageLineDerivesMissFromHit covers the OpenAI/MiMo shape where only the
50 // cached count is reported; the displayed "new" value comes from
51 // PromptTokens - CacheHitTokens. Verifies the absolute split doesn't show 0.
52 func TestUsageLineDerivesMissFromHit(t *testing.T) {
53 u := &provider.Usage{
54 PromptTokens: 3540,
55 CompletionTokens: 378,
56 TotalTokens: 3918,
57 CacheHitTokens: 1133,
58 // CacheMissTokens deliberately 0 — provider only reported the hit
59 }
60 if out := renderUsage(u, nil); !strings.Contains(out, "1133 cached / 2407 new") {
61 t.Errorf("usage line = %q (want 1133 cached / 2407 new)", out)
62 }
63 }
64
65 func TestUsageLineReportsPrefixChurn(t *testing.T) {
66 u := &provider.Usage{PromptTokens: 100, CompletionTokens: 10, TotalTokens: 110}
67 d := &event.CacheDiagnostics{
68 PrefixChanged: true,
69 PrefixChangeReasons: []string{"tools", "log_rewrite"},
70 }
71 if out := renderUsage(u, nil, d); !strings.Contains(out, "cache prefix changed: tools+log_rewrite") {
72 t.Errorf("usage line = %q (want cache prefix change reason)", out)
73 }
74 }
75
75 lines GO