sonda/internal/config/config_test.go
tgiachi 3a739dc3ae feat: add sondad server with config, storage, auth and listening API
- feat(config): TOML config with env overrides, strict parsing and validation
- feat(storage): SQLite (modernc) and PostgreSQL (pgx) backends through bun,
  embedded per-driver SQL migrations with a transactional runner
- feat(schema): catalog tables (artists, albums, tracks, audio_files with
  per-root paths), users and listening events with idempotency keys
- feat(auth): Argon2id password hashing, HS256 JWT tokens, first-user-only
  registration and login
- feat(api): gin REST API under /api/v1 (health, register, login, listens)
  with a consistent error envelope, body limit and request logging
- feat(sondad): zap logger, graceful shutdown, composition root in main
- chore: example config, .gitignore for secrets, DB files, IDE and agent files
2026-11-11 12:06:15 +01:00

160 lines
4.4 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.Auth.TokenTTL() != 168*time.Hour {
t.Errorf("token ttl = %v", cfg.Auth.TokenTTL())
}
}
func TestLoadFileOverridesDefaults(t *testing.T) {
dir := t.TempDir()
p := writeFile(t, dir, `
[server]
listen = "0.0.0.0:9000"
[library]
roots = ["/a", "/b"]
[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 len(cfg.Library.Roots) != 2 {
t.Errorf("roots = %v", cfg.Library.Roots)
}
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) {
good := t.TempDir()
file := filepath.Join(good, "f")
if err := os.WriteFile(file, nil, 0o600); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
mutate func(*Config)
wantErr string
}{
{"ok", func(c *Config) {}, ""},
{"no roots", func(c *Config) { c.Library.Roots = nil }, "library.roots"},
{"root missing", func(c *Config) { c.Library.Roots = []string{filepath.Join(good, "nope")} }, "library.roots"},
{"root is file", func(c *Config) { c.Library.Roots = []string{file} }, "not a directory"},
{"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 ttl", func(c *Config) { c.Auth.TokenTTLHours = 0 }, "auth.token_ttl_hours"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg, err := Load("")
if err != nil {
t.Fatal(err)
}
cfg.Library.Roots = []string{good}
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)
}
})
}
}