Files
magpie/internal/gateway/codex_models_wait_test.go
T
wei 920d96af55 tests: provider, plugin, gateway, codexcat, gui and tui tests pass in any order and on any -count (#1146)
Squashed from wei's #1146, onto main. Each test now starts from state of
its own instead of what an earlier test (or an earlier -count run) left:

- plugin: changed() counts the OnChange hooks still running; Told waits
  for them, and Settle ends with Told and UseCached(nil), so a change one
  test made isn't told in the next and the next test's plugin list isn't
  read as changed. Only tests call Settle/Told; in production changed()
  only counts. New TestSettleWaitsForTheHooksItTold and
  TestSettleForgetsTheFoldersPlugins.
- provider: isolate forgets Copilot's state, the plans' quota cards and
  balances; the warm-up, Cursor sign-in, hold and moved-plugin tests wait
  for what they started.
- gateway: fresh() forgets refused seals, and TestRouting,
  TestSmartRouting and TestQuotaRestsUntilItsReset start from
  forgetRouting; codexSignedIn and TestForeignReasoningIsLeftOut start
  from fresh.
- codexcat: XDG_CONFIG_HOME under the test's home. tui: costAt reset.
  gui: the fake Cursor account no longer outlives its test. cli: Settle.

Left out as already on main: the cli_identity keepIdentities switch
(9c3772311 keeps the asks in a sandbox via testenv's marker) and the
omarchy reset (main's TestCurrent already resets cached/seen/asked).

Run (darwin, loaded machine):
- On main 043e0cfc7, -count=3: TestRouting, TestSmartRouting,
  TestQuotaRestsUntilItsReset, TestForeignReasoningIsLeftOut,
  TestStandaloneNativeFallback fail; codexcat and tui fail; provider
  -shuffle=1791359851244745000 fails TestCopilotAuto and
  TestCopilotSignAndModels, and -count=2 -shuffle=1791856220860256000
  -run 'Copilot|TestPlanQuotas|TestCachedCardsAskNobody' fails
  TestPlanQuotas and TestCachedCardsAskNobody. With this change, that
  provider run (-shuffle=on, -count=2), the same gateway tests,
  ./internal/codexcat, ./internal/tui and the Settle/Hold/warm-up tests
  in plugin and provider pass -count=3.
- Breaking Settle by hand: without Told(),
  TestSettleWaitsForTheHooksItTold fails; without UseCached(nil),
  TestSettleForgetsTheFoldersPlugins fails.
- gofmt -l; go vet ./... on darwin, GOOS=linux -tags nogui, GOOS=windows.
Not run: the whole ./... suite at once (the machine's load times it out)
and Windows/Linux test runs.
2026-10-13 09:52:14 +08:00

90 lines
3.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package gateway
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
)
// A ChatGPT backend slow to hand over its model list doesn't hold magpie's
// answer past the 5 s Codex waits for it: Codex then kept the list it was
// built with, none of magpie's models in it (#539). The answer comes in
// time, with magpie's models and Codex's own from its last list.
func TestCodexModelListBackendSlow(t *testing.T) {
setup(t, provider.Chat, &fake{t: t})
release := make(chan struct{})
up := chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
select {
case <-release:
case <-r.Context().Done():
}
})
t.Cleanup(func() { close(release); up.CloseClientConnections() })
home, _ := os.UserHomeDir()
os.MkdirAll(filepath.Join(home, ".codex"), 0o755)
os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"),
[]byte(`{"etag":"\"v1\"","models":[{"slug":"gpt-5.5","priority":1,"base_instructions":"x"}]}`), 0o644)
was := codexModelsWait
codexModelsWait = 200 * time.Millisecond
t.Cleanup(func() { codexModelsWait = was })
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", CodexPath+"/models?client_version=0.159.2", nil)
req.Header.Set("Authorization", "Bearer chatgpt-token")
done := make(chan struct{})
go func() { New().Handler().ServeHTTP(rec, req); close(done) }()
select {
case <-done:
case <-time.After(3 * time.Second):
t.Fatal("magpie's model list waited on the backend past the time Codex gives it")
}
var list struct {
Models []map[string]any `json:"models"`
}
json.Unmarshal(rec.Body.Bytes(), &list)
has := map[string]bool{}
for _, m := range list.Models {
s, _ := m["slug"].(string)
has[s] = true
}
if rec.Code != 200 || !has["fake/m1"] || !has["gpt-5.5"] {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
}
// One /models request from Codex builds magpie's providers once (#746,
// sperwe: seven builds, each reading every agent's sign-in, some 200
// keychain reads, took 5.3–5.6 s, past the 5 s Codex waits, and Codex kept
// its own list): the catalog, the codex provider's picks and windows and
// the list's tag all read the one build.
func TestCodexModelListBuildsProvidersOnce(t *testing.T) {
// not from the plugins' list an earlier test's folder had: seen last,
// it reads as changed in setup's folder, and the change, told in the
// background, has the providers built again for the list
plugin.UseCached(nil)
setup(t, provider.Chat, &fake{t: t})
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"models":[{"slug":"gpt-5.5","priority":1}]}`))
})
h := New().Handler()
n := provider.AllBuilt.Load()
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", CodexPath+"/models?client_version=0.159.2", nil)
req.Header.Set("Authorization", "Bearer chatgpt-token")
h.ServeHTTP(rec, req)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"fake/m1"`) || !strings.Contains(rec.Body.String(), `"gpt-5.5"`) {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
if got := provider.AllBuilt.Load() - n; got != 1 {
t.Fatalf("the providers were built %d times for one list, want 1", got)
}
}