provider tests: the allowance tests end only once their own reading and renewal tell are done, and each sub2api key test reads its key under an id of its own (#1058)

TestKeyAllowanceStaleMidRead waits until its own OnRenewed hook has been
told, and puts back the hooks it found. TestAllowancesBeforeFirstReading's
cleanup waits for the reading it held before the reset. sub2apiKey takes the
test and names the key sub2api-<test>, so a renewal told late by one test
is not counted by the next, and TestKeyAllowanceRenewed counts only its own
key's renewals. Only test code changes.

Squashed from #1058 (waitingsnow, head 42fe2c7b). The reviewer changed one
thing: quota_asked_test.go's TestKeyReadsOnlyWhenAsked, added on main by
e9221e96 after the PR's last rebase, still called sub2apiKey(srv), so the
PR's head merged onto main didn't build. It now calls sub2apiKey(t, srv).

What was run (macOS arm64, Go 1.26.8, -tags nogui, sandbox HOME, private
GOCACHE), on the merge with origin/main 5b14ebf4:
- 100 ms before key_allowance.go's tellRenewed:
  -count=5 -run '^(TestKeyAllowanceStaleMidRead|TestKeyAllowanceRenewed)$'
  fails on main's tests ("its week's limit raised to $1,000: told
  [/sub2api#703eb1a04b /sub2api#703eb1a04b]") and passes with this change.
- With 250 ms before Allowances stores a reading, plus 500 ms before each
  codex Allowances ask, TestAllowancesBeforeFirstReading followed by
  TestResetRunsOutForRouting passes on current main as well as with this
  change. That failure reproduced 5/5 at 443f1cbc, but not on current main.
  The cleanup's wait is kept anyway: it is right regardless.
- -race -count=20 of TestKeyAllowance|TestSub2API|TestAllowancesBeforeFirstReading|
  TestResetRunsOutForRouting|TestKeyReadsOnlyWhenAsked|TestCachedCardsTellKeyReadings: ok
- go test ./internal/provider: ok (728s on a heavily loaded machine; a
  first run under the default 10m timeout timed out from the load)
- go vet on darwin, GOOS=linux -tags nogui and GOOS=windows for the
  package; gofmt -l clean.
Not run: go test ./... on an idle machine.
This commit is contained in:
wei
2026-10-13 09:09:37 +08:00
committed by yetone
parent c162a98a11
commit 043e0cfc7b
4 changed files with 64 additions and 23 deletions
+13 -1
View File
@@ -52,13 +52,22 @@ func TestAllowancesBeforeFirstReading(t *testing.T) {
"primary_window": map[string]any{"used_percent": used[r.Header.Get("chatgpt-account-id")], "limit_window_seconds": 18000}}})
}))
t.Cleanup(fake.Close)
t.Cleanup(func() { close(hold) })
old := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
t.Cleanup(func() { CodexBase = old })
oldWait := firstWait
firstWait = 50 * time.Millisecond
t.Cleanup(func() { firstWait = oldWait })
var reading chan struct{} // the read Allowances leaves out
t.Cleanup(func() {
close(hold)
// it lands while CodexBase, which it reads, is still the fake's,
// and before the reset: not in the next test that asks for codex's
// allowances, which would take it for its own
if reading != nil {
<-reading
}
})
// read once, as before the restart: kept on disk
if u := LoginUsage(context.Background(), "codex"); len(u) != 2 {
@@ -68,6 +77,9 @@ func TestAllowancesBeforeFirstReading(t *testing.T) {
reset()
slow.Store(true)
a := Allowances("codex")
usedCache.Lock()
reading = usedCache.loading["codex"]
usedCache.Unlock()
now := time.Now()
for user, want := range map[string]float64{"me@example.com": 12, "work@example.com": 97} {
if got, _ := a[user].For("gpt-5.5", now); got != want {
+3 -3
View File
@@ -170,15 +170,15 @@ func TestCachedCardsTellKeyReadings(t *testing.T) {
keyLimitsHome(t)
week := time.Now().Add(72 * time.Hour).Truncate(time.Second)
srv, asked := sub2apiServer(t, func() ([]byte, int) { return weekUsed(t, "720", week), 200 })
p := sub2apiKey(srv)
p := sub2apiKey(t, srv)
if err := Save(p); err != nil {
t.Fatal(err)
}
if q := cardOf(CachedCards(time.Now()), "sub2api", ""); q != nil {
if q := cardOf(CachedCards(time.Now()), p.ID, ""); q != nil {
t.Fatalf("a card before anything was read: %+v", q)
}
waitAllowance(t, p, func(Allowance) bool { return true })
q := cardOf(CachedCards(time.Now()), "sub2api", "")
q := cardOf(CachedCards(time.Now()), p.ID, "")
if q == nil || q.Kind != "balance" || len(q.Windows) != 2 || q.Windows[1].Name != "7 days" || q.Windows[1].Used != 90 || q.Name != "Sub2API" || q.ReadAt == nil {
t.Fatalf("after routing's read: %+v", q)
}
+1 -1
View File
@@ -191,7 +191,7 @@ func TestAllowancesReadByThemselvesByDefault(t *testing.T) {
func TestKeyReadsOnlyWhenAsked(t *testing.T) {
keyLimitsHome(t)
srv, asked := sub2apiServer(t, func() ([]byte, int) { return sub2apiUsage(t, true), 200 })
p := sub2apiKey(srv)
p := sub2apiKey(t, srv)
if err := Save(p); err != nil {
t.Fatal(err)
}
+47 -18
View File
@@ -161,8 +161,10 @@ func sub2apiServer(t *testing.T, body func() ([]byte, int)) (*httptest.Server, *
return srv, &asked
}
func sub2apiKey(srv *httptest.Server) Provider {
return Provider{ID: "sub2api", Name: "Sub2API", Chat: srv.URL + "/v1", Responses: srv.URL + "/v1",
// sub2apiKey is a key at srv, under an id of the test's own: a renewal a
// reading behind another test tells, after it ended, is not this one's.
func sub2apiKey(t *testing.T, srv *httptest.Server) Provider {
return Provider{ID: "sub2api-" + Slug(t.Name()), Name: "Sub2API", Chat: srv.URL + "/v1", Responses: srv.URL + "/v1",
Key: "sk-limited", BalanceURL: srv.URL + "/v1/usage"}
}
@@ -175,14 +177,14 @@ func TestSub2APIKeyLimitsOnItsCard(t *testing.T) {
b := sub2apiUsage(t, true)
body.Store(&b)
srv, _ := sub2apiServer(t, func() ([]byte, int) { return *body.Load(), 200 })
p := sub2apiKey(srv)
p := sub2apiKey(t, srv)
if err := Save(p); err != nil {
t.Fatal(err)
}
card := func() SubscriptionQuota {
ForgetBalances()
for _, q := range KeyBalances(context.Background()) {
if q.Provider == "sub2api" {
if q.Provider == p.ID {
return q
}
}
@@ -247,7 +249,7 @@ func TestKeyAllowanceNeverWaits(t *testing.T) {
<-release
return weekUsed(t, "720", week), 200
})
p := sub2apiKey(srv)
p := sub2apiKey(t, srv)
if err := Save(p); err != nil {
t.Fatal(err)
}
@@ -307,7 +309,7 @@ func TestKeyAllowanceFailedReadKeepsLast(t *testing.T) {
}
return weekUsed(t, "720", week), 200
})
p := sub2apiKey(srv)
p := sub2apiKey(t, srv)
if err := Save(p); err != nil {
t.Fatal(err)
}
@@ -348,7 +350,7 @@ func TestKeyAllowanceForgottenMidRead(t *testing.T) {
})
var once sync.Once
t.Cleanup(func() { once.Do(func() { close(release) }) })
p := sub2apiKey(srv)
p := sub2apiKey(t, srv)
KeyAllowance(p)
for asked.Load() < 1 {
time.Sleep(5 * time.Millisecond)
@@ -379,7 +381,22 @@ func TestKeyAllowanceStaleMidRead(t *testing.T) {
})
var once sync.Once
t.Cleanup(func() { once.Do(func() { close(release) }) })
p := sub2apiKey(srv)
p := sub2apiKey(t, srv)
renewedHooks.Lock()
hooks := renewedHooks.fs
renewedHooks.Unlock()
t.Cleanup(func() {
renewedHooks.Lock()
renewedHooks.fs = hooks
renewedHooks.Unlock()
})
renewed := make(chan struct{})
var told sync.Once
OnRenewed(func(agent, user string) {
if agent == "" && user == KeyAllowanceID(p) {
told.Do(func() { close(renewed) })
}
})
KeyAllowance(p)
for asked.Load() < 1 {
time.Sleep(5 * time.Millisecond)
@@ -390,6 +407,14 @@ func TestKeyAllowanceStaleMidRead(t *testing.T) {
if n := asked.Load(); n != 2 {
t.Fatalf("asked %d times", n)
}
// the reading after tells the week renewed only after it is kept, so
// waitAllowance can return first: waited for here, or a later test's
// hook is told it
select {
case <-renewed:
case <-time.After(5 * time.Second):
t.Fatal("the week renewed was never told")
}
}
// Until the key is first read (magpie just started), its windows are the
@@ -405,7 +430,7 @@ func TestKeyAllowanceSeededFromItsCard(t *testing.T) {
}
return weekUsed(t, "720", week), 200
})
p := sub2apiKey(srv)
p := sub2apiKey(t, srv)
if err := Save(p); err != nil {
t.Fatal(err)
}
@@ -455,7 +480,7 @@ func TestKeyAllowanceOnlyForSub2APIKeys(t *testing.T) {
func TestKeyAllowancePerKeyAndForgotten(t *testing.T) {
keyLimitsHome(t)
srv, asked := sub2apiServer(t, func() ([]byte, int) { return sub2apiUsage(t, true), 200 })
p := sub2apiKey(srv)
p := sub2apiKey(t, srv)
now := time.Now()
week := now.Add(72 * time.Hour)
noteKeyAllowance(p, []QuotaWindow{{Name: "7 days", Span: 7 * 24 * time.Hour, Used: 95, ResetsAt: &week}}, now)
@@ -512,7 +537,7 @@ func TestKeyAllowanceRenewed(t *testing.T) {
}
return []byte(`{"error":{"type":"api_error","message":"internal error"}}`), 502
})
p := sub2apiKey(srv)
p := sub2apiKey(t, srv)
if err := Save(p); err != nil {
t.Fatal(err)
}
@@ -524,17 +549,21 @@ func TestKeyAllowanceRenewed(t *testing.T) {
renewedHooks.fs = hooks
renewedHooks.Unlock()
})
var mu sync.Mutex
var told []string
OnRenewed(func(agent, user string) {
mu.Lock()
told = append(told, agent+"/"+user)
mu.Unlock()
})
id := KeyAllowanceID(p)
if id != keyAllowanceID(p) {
t.Fatalf("KeyAllowanceID = %q", id)
}
var mu sync.Mutex
var told []string
// only its own key's: another test's reading may still tell its own
OnRenewed(func(agent, user string) {
if user != id {
return
}
mu.Lock()
told = append(told, agent+"/"+user)
mu.Unlock()
})
reply := func(b []byte) { body.Store(&b) }
// read is a reading as routing's, done here rather than behind it
read := func(b []byte) {