// Package websearchtest is a fake search backend for tests: no network. package websearchtest import ( "context" "sync" "amadan.net/oficina/equipo/internal/websearch" ) // Fake answers each query from Results, or fails it with Fail, and // records the queries it was asked, in order. Backend is its name // (fake when empty). type Fake struct { Backend string Results map[string][]websearch.Result Fail map[string]*websearch.Error // Hook, when set, runs first with the query; an error it returns is // the answer (as a refusal at the final check would be). Hook func(ctx context.Context, q string) error mu sync.Mutex Calls []string } func (f *Fake) Name() string { if f.Backend == "" { return "fake" } return f.Backend } func (f *Fake) Search(ctx context.Context, q string, _ int) ([]websearch.Result, error) { if f.Hook != nil { if err := f.Hook(ctx, q); err != nil { return nil, err } } f.mu.Lock() f.Calls = append(f.Calls, q) f.mu.Unlock() if e := f.Fail[q]; e != nil { return nil, &websearch.Error{Backend: f.Name(), Class: e.Class} } return f.Results[q], nil } // Asked is how many queries it was asked. func (f *Fake) Asked() int { f.mu.Lock() defer f.mu.Unlock() return len(f.Calls) } // MemUsage is an in-memory Usage: caps by backend, counts by backend and // month, the month set by the test. type MemUsage struct { mu sync.Mutex Caps map[string]int Month string Used map[websearch.Reservation]int Taken int } func (u *MemUsage) Take(_ context.Context, backend string) (websearch.Reservation, bool, error) { u.mu.Lock() defer u.mu.Unlock() if u.Used == nil { u.Used = map[websearch.Reservation]int{} } r := websearch.Reservation{Backend: backend, Month: u.Month} if u.Used[r] >= u.Caps[backend] { return r, false, nil } u.Used[r]++ u.Taken++ return r, true, nil } func (u *MemUsage) Return(_ context.Context, r websearch.Reservation) error { u.mu.Lock() defer u.mu.Unlock() if u.Used[r] > 0 { u.Used[r]-- } return nil }