Vellum/internal/providers/igdb_test.go
mithral 35442e4aff Phase 2: split the fat packages along real boundaries
Four extractions, each chosen because the two halves have different callers,
different failure modes or different testing needs. Not a line-count exercise.

internal/home out of internal/media
- media serves item RESOURCES (detail, file, cover, progress); home computes
  AGGREGATES (the five shelves). The 2328-line package was doing both.
- media keeps POST /items/{id}/view because it is item-scoped and must stay in
  the package that authorizes the item; it imports home.RecordView for that one
  thing. home does not import media.
- Verified live: all five shelves non-empty, and two consecutive /home calls
  return different explore ids, which is the non-determinism the Explore rewrite
  exists for.

internal/scanner out of internal/library
- The scanner walks the filesystem and reconciles; library CRUD is an admin HTTP
  surface. Different callers (a job vs a request), different failure modes.
- The registry deliberately STAYED in internal/library: three of its four callers
  are not the scanner (modules register types, handlers serve the list, metadata
  reads the group mode, subsonic calls CleanTitle). It is a property of the kind,
  not of the scan. The one genuinely scanner-owned helper became
  library.ExtensionsFor.
- Two tests moved with the code rather than being rewritten; they now exercise
  the boundary by calling library.ListMissing across it.
- Verified live: first scan updates, rescan reports unchanged=N, so change
  detection still short-circuits.

internal/providers out of internal/metadata
- Providers talk to third-party APIs; the enrich job owns the matching policy and
  the database writes. The split's whole point is that a provider is testable
  WITHOUT a database, so a DB-free test was added and OpenLibrary gained a
  BaseURL override to make it possible.
- providers imports zero internal packages — a true leaf.
- The matching policy (searchTitle, artistHint, pickBest) is untouched. It exists
  because real false matches were found.

dto packages out of internal/jellyfin and internal/subsonic
- The wire types and their mapping are now separate from the handler logic, so
  the contract with clients we do not control is reviewable on its own.
- Both dto packages are PURE: zero references to sql.DB or net/http, verified by
  grep. That is what makes them reviewable.
- No field name, tag or error code changed.

internal/arch did its job: it failed the build twice during this phase, once for
each new package that was not yet placed in a layer. That is the rule working,
not an obstacle.

Verified: gofmt clean, build exit 0, vet exit 0, 23 packages pass, svelte-check
0/0, and end to end against a running server — home shelves, a queued scan
reporting unchanged, Jellyfin /Items, and Subsonic ping.

Process note: one agent (dto) stopped mid-task and left the tree red — the dto
packages unlayered and its test still referencing constants that had moved. The
arch test caught it immediately. I finished it by hand: exported constant
references in the test, and both dto packages placed at layer 3.

Still open from Phase 1: internal/jellyfin has no test files, catalog is
item-centric while Subsonic is file-first, and subsonic loadAlbum now scopes to
the item's own library.
2026-10-11 16:03:10 -04:00

95 lines
2.7 KiB
Go

package providers
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
)
func TestIGDBSearch(t *testing.T) {
var tokenHits int32
tokenSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&tokenHits, 1)
if r.URL.Query().Get("grant_type") != "client_credentials" {
t.Errorf("grant_type = %q", r.URL.Query().Get("grant_type"))
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"access_token":"tok-123","expires_in":5184000}`))
}))
defer tokenSrv.Close()
var gotBody, gotClientID, gotAuth string
apiSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
gotClientID = r.Header.Get("Client-ID")
gotAuth = r.Header.Get("Authorization")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[
{
"id": 1029,
"name": "Sonic the Hedgehog",
"summary": "A fast blue hedgehog.",
"first_release_date": 677635200,
"cover": {"url": "//images.igdb.com/igdb/image/upload/t_thumb/co1234.jpg"}
}
]`))
}))
defer apiSrv.Close()
p := NewIGDB("client-id", "client-secret")
p.TokenURL = tokenSrv.URL
p.BaseURL = apiSrv.URL
cands, err := p.Search(context.Background(), Query{Title: "Sonic"})
if err != nil {
t.Fatalf("Search: %v", err)
}
if len(cands) != 1 {
t.Fatalf("got %d candidates, want 1", len(cands))
}
c := cands[0]
if c.Title != "Sonic the Hedgehog" {
t.Errorf("Title = %q", c.Title)
}
if c.ExternalID != "1029" {
t.Errorf("ExternalID = %q", c.ExternalID)
}
if c.Year != 1991 {
t.Errorf("Year = %d, want 1991", c.Year)
}
if c.CoverURL != "https://images.igdb.com/igdb/image/upload/t_cover_big/co1234.jpg" {
t.Errorf("CoverURL = %q (want https and t_cover_big)", c.CoverURL)
}
if !strings.Contains(gotBody, `search "Sonic"`) {
t.Errorf("query body = %q", gotBody)
}
if gotClientID != "client-id" || gotAuth != "Bearer tok-123" {
t.Errorf("headers: Client-ID=%q Authorization=%q", gotClientID, gotAuth)
}
// A second search must reuse the cached token, not re-authenticate.
if _, err := p.Search(context.Background(), Query{Title: "Sonic 2"}); err != nil {
t.Fatal(err)
}
if n := atomic.LoadInt32(&tokenHits); n != 1 {
t.Errorf("token endpoint hit %d times, want 1 (token should be cached)", n)
}
}
func TestIGDBWithoutCredentialsDoesNothing(t *testing.T) {
p := NewIGDB("", "")
cands, err := p.Search(context.Background(), Query{Title: "Sonic"})
if err != nil {
t.Fatalf("Search: %v", err)
}
if len(cands) != 0 {
t.Errorf("got %d candidates with no credentials, want 0", len(cands))
}
}