Vellum/internal/library/library_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

111 lines
3 KiB
Go

package library
import (
"context"
"database/sql"
"errors"
"io"
"log/slog"
"os"
"path/filepath"
"testing"
"github.com/mithral/vellum/internal/core"
"github.com/mithral/vellum/migrations"
)
func testDB(t *testing.T) *sql.DB {
t.Helper()
db, err := core.OpenDB(filepath.Join(t.TempDir(), "lib.db"))
if err != nil {
t.Fatalf("OpenDB: %v", err)
}
t.Cleanup(func() { _ = db.Close() })
log := slog.New(slog.NewTextHandler(io.Discard, nil))
if err := core.Migrate(context.Background(), db, migrations.FS, log); err != nil {
t.Fatalf("Migrate: %v", err)
}
return db
}
func testLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
func writeFile(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
func TestRegistryBasics(t *testing.T) {
if err := ValidateKind("ebooks"); err != nil {
t.Errorf("ebooks should be valid: %v", err)
}
if err := ValidateKind("nonsense"); !errors.Is(err, ErrUnknownKind) {
t.Errorf("nonsense kind error = %v, want ErrUnknownKind", err)
}
if k, ok := KindForExtension(".epub"); !ok || k != "ebooks" {
t.Errorf("KindForExtension(.epub) = %q,%v", k, ok)
}
if k, ok := KindForExtension("CBZ"); !ok || k != "comics" {
t.Errorf("KindForExtension(CBZ) = %q,%v (should be case-insensitive)", k, ok)
}
if len(SupportedTypes()) == 0 {
t.Error("no media types registered")
}
}
func TestCleanTitle(t *testing.T) {
cases := map[string]string{
"Project Hail Mary.epub": "Project Hail Mary",
"the_hobbit.mobi": "the hobbit",
"Book.Title.2020.epub": "Book Title 2020",
"/deep/path/Saga 001.cbz": "Saga 001",
}
for in, want := range cases {
if got := CleanTitle(in); got != want {
t.Errorf("CleanTitle(%q) = %q, want %q", in, got, want)
}
}
}
func TestCreateLibraryValidation(t *testing.T) {
db := testDB(t)
ctx := context.Background()
root := t.TempDir()
if _, err := Create(ctx, db, "Good", "ebooks", root); err != nil {
t.Fatalf("valid create failed: %v", err)
}
if _, err := Create(ctx, db, "Good", "ebooks", root); !errors.Is(err, ErrNameExists) {
t.Errorf("duplicate name error = %v, want ErrNameExists", err)
}
if _, err := Create(ctx, db, "Bad", "nonsense", root); !errors.Is(err, ErrUnknownKind) {
t.Errorf("bad kind error = %v, want ErrUnknownKind", err)
}
if _, err := Create(ctx, db, "Bad", "ebooks", "/nope/not/here"); !errors.Is(err, ErrInvalidRoot) {
t.Errorf("bad root error = %v, want ErrInvalidRoot", err)
}
}
func TestListVisibleNeverMeansAll(t *testing.T) {
db := testDB(t)
ctx := context.Background()
root := t.TempDir()
if _, err := Create(ctx, db, "Ebooks", "ebooks", root); err != nil {
t.Fatal(err)
}
libs, err := ListVisible(ctx, db, nil)
if err != nil {
t.Fatal(err)
}
if len(libs) != 0 {
t.Errorf("ListVisible(nil) returned %d libraries; empty set must mean none", len(libs))
}
}