Files
magpie/internal/gateway/search_api_keys_test.go
T
yetone 067a0b7552 gateway: a search API takes several keys, and one out of credit hands the search to the next (#1477, bluesky4485)
Tavily's free credit runs out, and changing the key by hand each time was
the reporter's chore. A search API's key can now be several, split by
commas (or spaces, semicolons, lines): Settings › Search's key field says
so, and `magpie search add tavily k1,k2` takes them. Each search starts
from the key that answered last (kept per vendor in memory) and goes on to
the next only when the answer is about the key: 401/403 turned away,
402/432/433 out of credit (Tavily's plan and pay-as-you-go limits), 429
rate limited. Anything else, such as a 500 or no answer in time, isn't the
key's, and the other keys aren't spent on it. Keys are stored as one
comma-joined string in the same field, so nothing is migrated; the list,
CLI and Settings show each key masked.

Run: TestSearchAPIKeysTakeTurns (httptest Tavily answering 432 with
Tavily's own body, 401 and 500) passes and goes red with the hand-off
removed; go test -tags nogui -run Search ./internal/gateway
./internal/provider ./internal/gui . passes; search-api, searcher-pick,
gui-ja, gui-de, gui-zh-tw .test.cjs pass in Chromium and WebKit. Not tried
against the real Tavily with a spent key.
2026-10-10 18:31:32 +08:00

90 lines
3.1 KiB
Go

package gateway
import (
"context"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A search API given several keys (#1477) goes on to the next when one is
// out of credit (Tavily's 432), and starts the next search from the one
// that answered. A failure that isn't about the key (a 500) doesn't spend
// the other keys.
func TestSearchAPIKeysTakeTurns(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
var mu sync.Mutex
var asked []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
mu.Lock()
asked = append(asked, key)
mu.Unlock()
switch key {
case "tvly-spent":
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(432)
io.WriteString(w, `{"detail":{"error":"This request exceeds your plan's set usage limit. Please upgrade your plan or contact support@tavily.com"}}`)
case "tvly-down":
http.Error(w, `{"detail":{"error":"down"}}`, 500)
case "tvly-good":
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"query":"x","results":[{"title":"Go downloads","url":"https://go.dev/dl/","content":"go1.27.1","score":0.9}]}`)
default:
http.Error(w, `{"detail":{"error":"Unauthorized: missing or invalid API key."}}`, 401)
}
}))
defer srv.Close()
s := New()
search := func(keys string) (string, error) {
t.Helper()
if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "tavily", Key: keys, URL: srv.URL}); err != nil {
t.Fatal(err)
}
mu.Lock()
asked = nil
mu.Unlock()
said, _, err := s.apiSearch(context.Background(), "latest go")
return said, err
}
took := func() []string { mu.Lock(); defer mu.Unlock(); return slices.Clone(asked) }
searchKeyAt.Delete("tavily")
if said, err := search("tvly-spent, tvly-bad\ntvly-good"); err != nil || !strings.Contains(said, "go1.27.1") {
t.Fatalf("spent, bad, good: %q, %v", said, err)
}
if got := took(); !slices.Equal(got, []string{"tvly-spent", "tvly-bad", "tvly-good"}) {
t.Errorf("asked with %v, want each key in turn", got)
}
if _, err := search("tvly-spent,tvly-bad,tvly-good"); err != nil {
t.Fatal(err)
}
if got := took(); !slices.Equal(got, []string{"tvly-good"}) {
t.Errorf("the next search asked with %v, want the key that answered first", got)
}
searchKeyAt.Delete("tavily")
if _, err := search("tvly-down,tvly-good"); err == nil {
t.Error("a 500 on the first key went on to the next")
}
if got := took(); !slices.Equal(got, []string{"tvly-down"}) {
t.Errorf("asked with %v after a 500, want the first key alone", got)
}
searchKeyAt.Delete("tavily")
_, err := search("tvly-spent,tvly-bad")
if err == nil || !strings.Contains(err.Error(), "key 1:") || !strings.Contains(err.Error(), "usage limit") || !strings.Contains(err.Error(), "key 2:") {
t.Errorf("every key refused: %v", err)
}
if as := provider.StoredSearchAPIs(); len(as) != 1 || as[0].Key != "tvly-spent,tvly-bad" || as[0].MaskedKey() != "tvly…pent, ••••••••" {
t.Errorf("stored %+v, shown %q", as, as[0].MaskedKey())
}
}