sonda/internal/config/config_test.go
tgiachi 46463846b3 feat(library): named media libraries managed through the API
- feat(storage): libraries table (name, path); audio_files points at a library
  by id instead of repeating the root path; migration 0005 for both drivers
  turns every existing root into a library and keeps file ids, tracks and the
  missing flag
- feat(library): Libraries service validates names and paths: absolute, an
  existing directory, never the filesystem root, never inside or around
  another library (checked on real paths, so symlinks cannot hide an overlap)
- feat(api): admin-only GET/POST /libraries, PATCH/DELETE /libraries/{id} and
  POST /libraries/{id}/scan; deleting a library drops its index entries and
  keeps tracks and listening history
- feat(library): the scanner and the scan manager work on libraries; scanning
  with no libraries answers 409 no_libraries
- feat(streaming): the library directory comes from the database instead of
  a configured list of roots
- breaking(config): library.roots is removed; an old config fails with a hint
  to use POST /api/v1/libraries
- test: CRUD and duplicates on both databases, path change keeps files,
  upgrade of a database written before libraries existed
2026-11-11 13:30:25 +01:00

171 lines
4.9 KiB
Go

package config
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func writeFile(t *testing.T, dir, content string) string {
t.Helper()
p := filepath.Join(dir, "sonda.toml")
if err := os.WriteFile(p, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
return p
}
func TestLoadEmptyPathReturnsDefaults(t *testing.T) {
cfg, err := Load("")
if err != nil {
t.Fatal(err)
}
if cfg.Server.Listen != "127.0.0.1:8080" {
t.Errorf("listen = %q", cfg.Server.Listen)
}
if cfg.Database.Path != "sonda.db" {
t.Errorf("db path = %q", cfg.Database.Path)
}
if cfg.Database.Driver != "sqlite" {
t.Errorf("db driver = %q", cfg.Database.Driver)
}
if cfg.Log.Env != "production" {
t.Errorf("env = %q", cfg.Log.Env)
}
if cfg.Library.ScanWorkers != 4 {
t.Errorf("scan workers = %d", cfg.Library.ScanWorkers)
}
if cfg.Auth.AccessTTL() != 15*time.Minute {
t.Errorf("access ttl = %v", cfg.Auth.AccessTTL())
}
if cfg.Auth.RefreshTTL() != 720*time.Hour {
t.Errorf("refresh ttl = %v", cfg.Auth.RefreshTTL())
}
}
func TestLoadFileOverridesDefaults(t *testing.T) {
dir := t.TempDir()
p := writeFile(t, dir, `
[server]
listen = "0.0.0.0:9000"
[library]
scan_workers = 9
[providers.lastfm]
api_key = "k"
`)
cfg, err := Load(p)
if err != nil {
t.Fatal(err)
}
if cfg.Server.Listen != "0.0.0.0:9000" {
t.Errorf("listen = %q", cfg.Server.Listen)
}
if cfg.Library.ScanWorkers != 9 {
t.Errorf("scan workers = %d", cfg.Library.ScanWorkers)
}
if cfg.Providers.LastFM.APIKey != "k" {
t.Errorf("api key = %q", cfg.Providers.LastFM.APIKey)
}
// untouched keys keep their defaults
if cfg.Database.Path != "sonda.db" {
t.Errorf("db path = %q", cfg.Database.Path)
}
}
func TestLoadEnvOverridesFile(t *testing.T) {
dir := t.TempDir()
p := writeFile(t, dir, "[log]\nenv = \"production\"\n")
t.Setenv("SONDA_ENV", "dev")
t.Setenv("SONDA_LISTEN", "127.0.0.1:1")
t.Setenv("SONDA_DB_PATH", "x.db")
t.Setenv("SONDA_DB_DRIVER", "postgres")
t.Setenv("SONDA_DB_DSN", "postgres://u:p@h/db")
t.Setenv("SONDA_LASTFM_API_KEY", "envkey")
t.Setenv("SONDA_JWT_SECRET", "envsecret")
cfg, err := Load(p)
if err != nil {
t.Fatal(err)
}
if cfg.Log.Env != "dev" || cfg.Server.Listen != "127.0.0.1:1" ||
cfg.Database.Path != "x.db" || cfg.Providers.LastFM.APIKey != "envkey" ||
cfg.Auth.JWTSecret != "envsecret" ||
cfg.Database.Driver != "postgres" || cfg.Database.DSN != "postgres://u:p@h/db" {
t.Errorf("env not applied: %+v", cfg)
}
}
func TestLoadRejectsUnknownField(t *testing.T) {
dir := t.TempDir()
p := writeFile(t, dir, "[server]\nlisten_addr = \"x\"\n")
if _, err := Load(p); err == nil {
t.Fatal("expected error for unknown field")
}
}
func TestLoadMissingFile(t *testing.T) {
if _, err := Load(filepath.Join(t.TempDir(), "nope.toml")); err == nil {
t.Fatal("expected error for missing file")
}
}
func TestValidate(t *testing.T) {
tests := []struct {
name string
mutate func(*Config)
wantErr string
}{
{"ok", func(c *Config) {}, ""},
{"bad env", func(c *Config) { c.Log.Env = "staging" }, "log.env"},
{"empty listen", func(c *Config) { c.Server.Listen = "" }, "server.listen"},
{"empty db", func(c *Config) { c.Database.Path = "" }, "database.path"},
{"bad driver", func(c *Config) { c.Database.Driver = "mysql" }, "database.driver"},
{"postgres without dsn", func(c *Config) { c.Database.Driver = "postgres" }, "database.dsn"},
{"postgres ok", func(c *Config) {
c.Database.Driver = "postgres"
c.Database.Path = ""
c.Database.DSN = "postgres://u:p@localhost/db"
}, ""},
{"no secret", func(c *Config) { c.Auth.JWTSecret = "" }, "auth.jwt_secret"},
{"short secret", func(c *Config) { c.Auth.JWTSecret = "short" }, "auth.jwt_secret"},
{"bad workers", func(c *Config) { c.Library.ScanWorkers = 0 }, "library.scan_workers"},
{"bad access ttl", func(c *Config) { c.Auth.AccessTTLMinutes = 0 }, "auth.access_ttl_minutes"},
{"bad refresh ttl", func(c *Config) { c.Auth.RefreshTTLHours = 0 }, "auth.refresh_ttl_hours"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg, err := Load("")
if err != nil {
t.Fatal(err)
}
cfg.Auth.JWTSecret = strings.Repeat("s", 32)
tt.mutate(&cfg)
err = cfg.Validate()
if tt.wantErr == "" {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
return
}
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("err = %v, want containing %q", err, tt.wantErr)
}
})
}
}
// library.roots moved into the database; an old config must fail with a hint,
// not with a bare "unknown key".
func TestLoadExplainsRemovedLibraryRoots(t *testing.T) {
p := writeFile(t, t.TempDir(), "[library]\nroots = [\"/music\"]\n")
_, err := Load(p)
if err == nil {
t.Fatal("expected an error for library.roots")
}
if !strings.Contains(err.Error(), "library.roots") || !strings.Contains(err.Error(), "/api/v1/libraries") {
t.Errorf("error = %v, want a pointer to the libraries API", err)
}
}