Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

tests: a plugin fake's vendor counts only its own test's requests (#3357)

yetone3dc25a61681f
diff --git a/internal/gateway/credit_scope_test.go b/internal/gateway/credit_scope_test.go
index fd147c40e..bced8ce98 100644
--- a/internal/gateway/credit_scope_test.go
+++ b/internal/gateway/credit_scope_test.go
@@ -60,7 +60,7 @@ func TestOutOfCreditLeavesFreeModels(t *testing.T) {
var mu sync.Mutex
var keys []string // the key each request for fake-1 came with
- up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var q struct {
Model string `json:"model"`
}
@@ -80,7 +80,6 @@ func TestOutOfCreditLeavesFreeModels(t *testing.T) {
io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")
}))
defer up.Close()
- t.Setenv("FAKE_BASE", up.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
diff --git a/internal/gateway/plugin_cline_pin_test.go b/internal/gateway/plugin_cline_pin_test.go
index c2cf1e31c..e464df37c 100644
--- a/internal/gateway/plugin_cline_pin_test.go
+++ b/internal/gateway/plugin_cline_pin_test.go
@@ -49,6 +49,7 @@ func TestClinePluginPinsDeepSeekAndGLM(t *testing.T) {
mu.Lock()
sent = nil
mu.Unlock()
+ tries, last := 0, []int{}
for _, req := range []struct{ path, body string }{
{"/v1/chat/completions", `{"model":"` + pid + `/deepseek-v4-pro","messages":[{"role":"user","content":"hi"}]}`},
{"/v1/messages", `{"model":"` + pid + `/deepseek-v4-pro","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`},
@@ -57,14 +58,36 @@ func TestClinePluginPinsDeepSeekAndGLM(t *testing.T) {
{"/v1/chat/completions", `{"model":"` + pid + `/fake-1","messages":[{"role":"user","content":"hi"}]}`},
{"/v1/chat/completions", `{"model":"` + pid + `/glm-5.3-flash","messages":[{"role":"user","content":"hi"}]}`},
} {
- postProto(t, New(), req.path, req.body)
+ // each ask is one request, unless magpie tried it again: then
+ // it says why, and a try the vendor answered is never sent twice
+ rt := postProto(t, New(), req.path, req.body)
+ tries += len(rt.Tries)
+ mu.Lock()
+ last = append(last, len(sent)-1)
+ mu.Unlock()
+ for i, try := range rt.Tries {
+ if i > 0 {
+ t.Logf("%s %s: tried again after %d %q", req.path, req.body, rt.Tries[i-1].Status, rt.Tries[i-1].Error)
+ }
+ if try.Status == 200 && i < len(rt.Tries)-1 {
+ t.Fatalf("%s %s: a try the vendor answered 200 was sent again: %+v", req.path, req.body, rt.Tries)
+ }
+ }
}
mu.Lock()
defer mu.Unlock()
- if len(sent) != 6 {
- t.Fatalf("the plugin sent %d requests", len(sent))
+ if len(sent) != tries {
+ t.Fatalf("the plugin sent %d requests for 6 asks tried %d times", len(sent), tries)
}
- return append([]map[string]any(nil), sent...)
+ // each ask's request as it last went
+ var got []map[string]any
+ for n, i := range last {
+ if i < 0 || (n > 0 && i == last[n-1]) {
+ t.Fatalf("ask %d reached the plugin's vendor with no request", n)
+ }
+ got = append(got, sent[i])
+ }
+ return got
}
for i, q := range ask() {
if q["providerOptions"] != nil {
diff --git a/internal/gateway/plugin_extra_queue_test.go b/internal/gateway/plugin_extra_queue_test.go
index 5cea39860..0f9b515c1 100644
--- a/internal/gateway/plugin_extra_queue_test.go
+++ b/internal/gateway/plugin_extra_queue_test.go
@@ -31,7 +31,7 @@ func TestPluginSecondAccountKeepsTheQueue(t *testing.T) {
var seen []string
gate := make(chan struct{})
let := sync.OnceFunc(func() { close(gate) })
- up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
mu.Lock()
seen = append(seen, r.Header.Get("Authorization"))
@@ -46,7 +46,6 @@ func TestPluginSecondAccountKeepsTheQueue(t *testing.T) {
}))
t.Cleanup(up.Close)
t.Cleanup(let) // runs before up.Close, which waits for the held request
- t.Setenv("FAKE_BASE", up.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
diff --git a/internal/gateway/plugin_failover_test.go b/internal/gateway/plugin_failover_test.go
index e45bc71a8..65aa6d4ae 100644
--- a/internal/gateway/plugin_failover_test.go
+++ b/internal/gateway/plugin_failover_test.go
@@ -36,7 +36,7 @@ func TestPluginFailover(t *testing.T) {
var mu sync.Mutex
var tried []string // each request's account, as its token names it
fail := map[string]string{} // account → how it fails
- up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
who := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer fresh-r-")
mu.Lock()
@@ -78,7 +78,6 @@ func TestPluginFailover(t *testing.T) {
fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")
}))
defer up.Close()
- t.Setenv("FAKE_BASE", up.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
@@ -259,7 +258,7 @@ func TestPluginSaysSignIn(t *testing.T) {
var mu sync.Mutex
status, said := 200, ""
- up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
mu.Lock()
st, sa := status, said
@@ -277,7 +276,6 @@ func TestPluginSaysSignIn(t *testing.T) {
fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")
}))
defer up.Close()
- t.Setenv("FAKE_BASE", up.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
diff --git a/internal/gateway/plugin_grok_parity_test.go b/internal/gateway/plugin_grok_parity_test.go
index 5abd0f1c5..d2ebe7fd1 100644
--- a/internal/gateway/plugin_grok_parity_test.go
+++ b/internal/gateway/plugin_grok_parity_test.go
@@ -30,9 +30,7 @@ func besideFake(t *testing.T, id string, up http.Handler) string {
t.Setenv("FAKE_ID", id)
t.Setenv("FAKE_RESPONSES", "1")
t.Cleanup(plugin.Settle)
- srv := httptest.NewServer(up)
- t.Cleanup(srv.Close)
- t.Setenv("FAKE_BASE", srv.URL+"/v1")
+ testenv.FakeVendor(t, up)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
diff --git a/internal/gateway/plugin_parity_test.go b/internal/gateway/plugin_parity_test.go
index 877c23475..3853d007d 100644
--- a/internal/gateway/plugin_parity_test.go
+++ b/internal/gateway/plugin_parity_test.go
@@ -26,9 +26,7 @@ func movedFake(t *testing.T, id string, up http.Handler) {
t.Setenv("MAGPIE_BUN", bun)
t.Setenv("FAKE_ID", id)
t.Cleanup(plugin.Settle)
- srv := httptest.NewServer(up)
- t.Cleanup(srv.Close)
- t.Setenv("FAKE_BASE", srv.URL+"/v1")
+ testenv.FakeVendor(t, up)
dir := filepath.Dir(provider.Path())
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
diff --git a/internal/gateway/plugin_plan_lacks_test.go b/internal/gateway/plugin_plan_lacks_test.go
index be950e889..81bbfce7e 100644
--- a/internal/gateway/plugin_plan_lacks_test.go
+++ b/internal/gateway/plugin_plan_lacks_test.go
@@ -27,7 +27,7 @@ func TestPluginAccountLackingTheModelGoesLast(t *testing.T) {
t.Cleanup(plugin.Settle)
var mu sync.Mutex
var keys []string
- up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
keys = append(keys, r.Header.Get("Authorization"))
@@ -42,7 +42,6 @@ func TestPluginAccountLackingTheModelGoesLast(t *testing.T) {
io.WriteString(w, sse(`event: response.completed`+"\n"+`data: {"type":"response.completed","response":`+done+`}`))
}))
defer up.Close()
- t.Setenv("FAKE_BASE", up.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
diff --git a/internal/gateway/plugin_test.go b/internal/gateway/plugin_test.go
index a02c19742..ca6f41591 100644
--- a/internal/gateway/plugin_test.go
+++ b/internal/gateway/plugin_test.go
@@ -5,7 +5,6 @@ import (
"fmt"
"io"
"net/http"
- "net/http/httptest"
"path/filepath"
"slices"
"strings"
@@ -35,7 +34,7 @@ func TestPluginProvider(t *testing.T) {
var got []seen
limited := "" // the Authorization answered 429
refused := "" // and 401
- up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
got = append(got, seen{r.URL.RequestURI(), r.Header.Get("Authorization"), r.Header.Get("X-Plugin-Model"), string(b)})
@@ -77,7 +76,6 @@ func TestPluginProvider(t *testing.T) {
}
}))
defer up.Close()
- t.Setenv("FAKE_BASE", up.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
diff --git a/internal/gateway/workbuddy_restricted_test.go b/internal/gateway/workbuddy_restricted_test.go
index 8e7f6ecc7..c29a8db7e 100644
--- a/internal/gateway/workbuddy_restricted_test.go
+++ b/internal/gateway/workbuddy_restricted_test.go
@@ -5,7 +5,6 @@ import (
"fmt"
"io"
"net/http"
- "net/http/httptest"
"path/filepath"
"strings"
"sync"
@@ -139,7 +138,7 @@ func TestPluginRestrictedAccountSkipped(t *testing.T) {
t.Cleanup(plugin.Settle)
var mu sync.Mutex
var tried []string
- up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
who := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer fresh-r-")
mu.Lock()
@@ -156,7 +155,6 @@ func TestPluginRestrictedAccountSkipped(t *testing.T) {
fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")
}))
defer up.Close()
- t.Setenv("FAKE_BASE", up.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
diff --git a/internal/gateway/written_reset_test.go b/internal/gateway/written_reset_test.go
index 1bbd669d6..be649489b 100644
--- a/internal/gateway/written_reset_test.go
+++ b/internal/gateway/written_reset_test.go
@@ -308,14 +308,13 @@ func TestPluginWrittenResetRests(t *testing.T) {
back := 4 * time.Hour
refusal := wbAt("zh", time.Now().Add(back))
- up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(429)
fmt.Fprintf(w, `{"error":{"message":%q,"code":"6004"}}`, refusal)
}))
defer up.Close()
- t.Setenv("FAKE_BASE", up.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
diff --git a/internal/plugin/info_once_test.go b/internal/plugin/info_once_test.go
index e3ceb50b2..cf19caa98 100644
--- a/internal/plugin/info_once_test.go
+++ b/internal/plugin/info_once_test.go
@@ -4,13 +4,14 @@ import (
"context"
"io"
"net/http"
- "net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
+
+ "github.com/yetone/magpie/internal/testenv"
)
// A request is told the provider as info builds it once for its account,
@@ -21,14 +22,13 @@ func TestFetchBuildsInfoOnce(t *testing.T) {
sandbox(t)
var mu sync.Mutex
var told []string // x-plugin-model, as chat.headers set it, and x-models, as the loader was told them
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ srv := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
told = append(told, r.Header.Get("x-plugin-model")+" "+r.Header.Get("x-models"))
mu.Unlock()
io.WriteString(w, "ok")
}))
defer srv.Close()
- t.Setenv("FAKE_BASE", srv.URL+"/v1")
log := filepath.Join(t.TempDir(), "models.log")
t.Setenv("FAKE_MODELS_LOG", log)
asked := func() int {
diff --git a/internal/plugin/plugin_renew_race_test.go b/internal/plugin/plugin_renew_race_test.go
index a8f0c8187..bf09249ec 100644
--- a/internal/plugin/plugin_renew_race_test.go
+++ b/internal/plugin/plugin_renew_race_test.go
@@ -17,6 +17,8 @@ import (
"sync"
"testing"
"time"
+
+ "github.com/yetone/magpie/internal/testenv"
)
// raceVendor is a vendor that spends a refresh token once (plugins
@@ -67,7 +69,7 @@ func newRaceVendor(t *testing.T) *raceVendor {
fmt.Fprintf(w, `{"access":"a-%s","refresh":%q}`, next, next)
}))
t.Cleanup(tokens.Close)
- api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ api := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v.mu.Lock()
v.auths = append(v.auths, r.Header.Get("Authorization"))
v.mu.Unlock()
@@ -75,7 +77,6 @@ func newRaceVendor(t *testing.T) *raceVendor {
}))
t.Cleanup(api.Close)
t.Setenv("RACE_TOKEN_URL", tokens.URL)
- t.Setenv("FAKE_BASE", api.URL+"/v1")
return v
}
diff --git a/internal/plugin/plugin_renew_test.go b/internal/plugin/plugin_renew_test.go
index 25c1256f3..22e3a25ec 100644
--- a/internal/plugin/plugin_renew_test.go
+++ b/internal/plugin/plugin_renew_test.go
@@ -5,13 +5,14 @@ import (
"encoding/json"
"io"
"net/http"
- "net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
+
+ "github.com/yetone/magpie/internal/testenv"
)
// A plugin with auth.refresh leaves renewing its sign-ins to magpie: a
@@ -24,14 +25,13 @@ func TestPluginRenewsSignIns(t *testing.T) {
sandbox(t)
var mu sync.Mutex
var seen []string
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ srv := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
seen = append(seen, r.Header.Get("Authorization"))
mu.Unlock()
io.WriteString(w, "ok")
}))
defer srv.Close()
- t.Setenv("FAKE_BASE", srv.URL+"/v1")
logf := filepath.Join(t.TempDir(), "renewals")
t.Setenv("RENEW_LOG", logf)
said := make(chan string, 16)
diff --git a/internal/plugin/plugin_test.go b/internal/plugin/plugin_test.go
index d9b21ed5a..42247362c 100644
--- a/internal/plugin/plugin_test.go
+++ b/internal/plugin/plugin_test.go
@@ -39,7 +39,7 @@ func sandbox(t *testing.T) {
func TestFakePlugin(t *testing.T) {
sandbox(t)
var seen []http.Header
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ srv := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen = append(seen, r.Header.Clone())
b, _ := io.ReadAll(r.Body)
w.Header().Set("Content-Type", "text/event-stream")
@@ -50,7 +50,6 @@ func TestFakePlugin(t *testing.T) {
fmt.Fprint(w, "data: [DONE]\n\n")
}))
defer srv.Close()
- t.Setenv("FAKE_BASE", srv.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
@@ -197,12 +196,11 @@ func TestFakePlugin(t *testing.T) {
func TestPluginAccounts(t *testing.T) {
sandbox(t)
var auths []string
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ srv := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auths = append(auths, r.Header.Get("Authorization"))
fmt.Fprint(w, "{}")
}))
defer srv.Close()
- t.Setenv("FAKE_BASE", srv.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
abs, _ := filepath.Abs("testdata/fake/index.js")
diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js
index 9e2092e09..69b3c0da3 100644
--- a/internal/plugin/testdata/fake/index.js
+++ b/internal/plugin/testdata/fake/index.js
@@ -176,6 +176,10 @@ export const FakePlugin = async ({ client }) => ({
h.set("authorization", "Bearer " + (a.type === "oauth" ? a.access : a.key))
h.set("x-models", Object.keys(provider.models).sort().join(","))
h.set("x-body-type", typeof init.body)
+ // $FAKE_RUN: the test this host runs for, so its vendor tells its
+ // own requests from a stray that reached a port the kernel handed
+ // on (testenv.FakeVendor)
+ if (process.env.FAKE_RUN) h.set("x-fake-run", process.env.FAKE_RUN)
// where magpie said the agent works, as the plugin read it; its own
// headers go on too, as a plugin that sends on what it got sends
// them, for the host to take off
diff --git a/internal/plugin/testdata/renew/index.js b/internal/plugin/testdata/renew/index.js
index 96896365c..e14560951 100644
--- a/internal/plugin/testdata/renew/index.js
+++ b/internal/plugin/testdata/renew/index.js
@@ -35,6 +35,8 @@ export const RenewPlugin = async () => ({
const a = await getAuth()
const h = new Headers(init.headers)
h.set("authorization", "Bearer " + a.access)
+ // the test this host runs for (testenv.FakeVendor)
+ if (process.env.FAKE_RUN) h.set("x-fake-run", process.env.FAKE_RUN)
return fetch(url, { ...init, headers: h })
},
}),
diff --git a/internal/plugin/testdata/renewrace/index.js b/internal/plugin/testdata/renewrace/index.js
index 317b5fac8..62f91a8f1 100644
--- a/internal/plugin/testdata/renewrace/index.js
+++ b/internal/plugin/testdata/renewrace/index.js
@@ -28,6 +28,8 @@ export const RacePlugin = async () => ({
const a = await getAuth()
const h = new Headers(init.headers)
h.set("authorization", "Bearer " + a.access)
+ // the test this host runs for (testenv.FakeVendor)
+ if (process.env.FAKE_RUN) h.set("x-fake-run", process.env.FAKE_RUN)
return fetch(url, { ...init, headers: h })
},
}),
diff --git a/internal/plugin/updates_test.go b/internal/plugin/updates_test.go
index 814459e70..dacc7270e 100644
--- a/internal/plugin/updates_test.go
+++ b/internal/plugin/updates_test.go
@@ -5,13 +5,14 @@ import (
"encoding/json"
"io"
"net/http"
- "net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
+
+ "github.com/yetone/magpie/internal/testenv"
)
// installedAt fakes the package installed at version v.
@@ -119,7 +120,7 @@ func TestPinned(t *testing.T) {
func TestRestartFinishesTheReply(t *testing.T) {
sandbox(t)
release := make(chan struct{})
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ srv := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "data: first\n\n")
w.(http.Flusher).Flush()
@@ -133,7 +134,6 @@ func TestRestartFinishesTheReply(t *testing.T) {
// slow reply's handler, which a failed check would leave held (#1808)
let := sync.OnceFunc(func() { close(release) })
defer let()
- t.Setenv("FAKE_BASE", srv.URL+"/v1")
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
abs, _ := filepath.Abs("testdata/fake/index.js")
diff --git a/internal/testenv/vendor.go b/internal/testenv/vendor.go
new file mode 100644
index 000000000..a5ee4ad87
--- /dev/null
+++ b/internal/testenv/vendor.go
@@ -0,0 +1,47 @@
+package testenv
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+// FakeVendor serves h as the vendor of the fake plugin
+// (internal/plugin/testdata/fake), at $FAKE_BASE, for as long as the test
+// runs. Only this test's requests reach h: the fake plugin's fetch sends
+// $FAKE_RUN, a value made for this test, as X-Fake-Run, and anything
+// without it is answered 421 and logged, with what it was and where it
+// came from, never counted as the test's.
+//
+// The kernel hands a port a test freed to the next listener that asks,
+// in this process or another shard's, and a request still on its way to
+// the old one lands here (#3357): TestClinePluginPinsDeepSeekAndGLM's
+// vendor got a seventh request while magpie had sent six, and
+// TestPluginToldWhereTheAgentWorks's a second (#3347). A test that holds
+// its plugin to exactly one request per ask keeps that guarantee for its
+// own requests, and a stranger's is no longer one of them.
+func FakeVendor(t testing.TB, h http.Handler) *httptest.Server {
+ t.Helper()
+ var b [12]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ t.Fatal(err)
+ }
+ run := hex.EncodeToString(b[:])
+ t.Setenv("FAKE_RUN", run)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if got := r.Header.Get("X-Fake-Run"); got != run {
+ n, _ := io.Copy(io.Discard, r.Body)
+ t.Logf("the vendor got a request that isn't this test's (X-Fake-Run %q): %s %s from %s, User-Agent %q, Authorization %q, %d bytes; answered 421", got, r.Method, r.RequestURI, r.RemoteAddr, r.UserAgent(), r.Header.Get("Authorization"), n)
+ w.WriteHeader(http.StatusMisdirectedRequest)
+ return
+ }
+ r.Header.Del("X-Fake-Run")
+ h.ServeHTTP(w, r)
+ }))
+ t.Cleanup(srv.Close)
+ t.Setenv("FAKE_BASE", srv.URL+"/v1")
+ return srv
+}