| 1 | // Package websearchtest is a fake search backend for tests: no network. |
| 2 | package websearchtest |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "sync" |
| 7 | |
| 8 | "amadan.net/oficina/equipo/internal/websearch" |
| 9 | ) |
| 10 | |
| 11 | // Fake answers each query from Results, or fails it with Fail, and |
| 12 | // records the queries it was asked, in order. Backend is its name |
| 13 | // (fake when empty). |
| 14 | type Fake struct { |
| 15 | Backend string |
| 16 | Results map[string][]websearch.Result |
| 17 | Fail map[string]*websearch.Error |
| 18 | // Hook, when set, runs first with the query; an error it returns is |
| 19 | // the answer (as a refusal at the final check would be). |
| 20 | Hook func(ctx context.Context, q string) error |
| 21 | |
| 22 | mu sync.Mutex |
| 23 | Calls []string |
| 24 | } |
| 25 | |
| 26 | func (f *Fake) Name() string { |
| 27 | if f.Backend == "" { |
| 28 | return "fake" |
| 29 | } |
| 30 | return f.Backend |
| 31 | } |
| 32 | |
| 33 | func (f *Fake) Search(ctx context.Context, q string, _ int) ([]websearch.Result, error) { |
| 34 | if f.Hook != nil { |
| 35 | if err := f.Hook(ctx, q); err != nil { |
| 36 | return nil, err |
| 37 | } |
| 38 | } |
| 39 | f.mu.Lock() |
| 40 | f.Calls = append(f.Calls, q) |
| 41 | f.mu.Unlock() |
| 42 | if e := f.Fail[q]; e != nil { |
| 43 | return nil, &websearch.Error{Backend: f.Name(), Class: e.Class} |
| 44 | } |
| 45 | return f.Results[q], nil |
| 46 | } |
| 47 | |
| 48 | // Asked is how many queries it was asked. |
| 49 | func (f *Fake) Asked() int { |
| 50 | f.mu.Lock() |
| 51 | defer f.mu.Unlock() |
| 52 | return len(f.Calls) |
| 53 | } |
| 54 | |
| 55 | // MemUsage is an in-memory Usage: caps by backend, counts by backend and |
| 56 | // month, the month set by the test. |
| 57 | type MemUsage struct { |
| 58 | mu sync.Mutex |
| 59 | Caps map[string]int |
| 60 | Month string |
| 61 | Used map[websearch.Reservation]int |
| 62 | Taken int |
| 63 | } |
| 64 | |
| 65 | func (u *MemUsage) Take(_ context.Context, backend string) (websearch.Reservation, bool, error) { |
| 66 | u.mu.Lock() |
| 67 | defer u.mu.Unlock() |
| 68 | if u.Used == nil { |
| 69 | u.Used = map[websearch.Reservation]int{} |
| 70 | } |
| 71 | r := websearch.Reservation{Backend: backend, Month: u.Month} |
| 72 | if u.Used[r] >= u.Caps[backend] { |
| 73 | return r, false, nil |
| 74 | } |
| 75 | u.Used[r]++ |
| 76 | u.Taken++ |
| 77 | return r, true, nil |
| 78 | } |
| 79 | |
| 80 | func (u *MemUsage) Return(_ context.Context, r websearch.Reservation) error { |
| 81 | u.mu.Lock() |
| 82 | defer u.mu.Unlock() |
| 83 | if u.Used[r] > 0 { |
| 84 | u.Used[r]-- |
| 85 | } |
| 86 | return nil |
| 87 | } |
| 88 | |