You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
95 lines
2.4 KiB
95 lines
2.4 KiB
package config
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"testing"
|
|
)
|
|
|
|
func TestLoadUsesRootsFromEnvironment(t *testing.T) {
|
|
t.Setenv(rootsEnvVar, `[{"name":"Media","path":"/mnt/media"},{"name":"Archive","path":"/mnt/archive"}]`)
|
|
t.Setenv(rootsFileEnvVar, "")
|
|
|
|
config, err := Load()
|
|
if err != nil {
|
|
t.Fatalf("Load() error = %v", err)
|
|
}
|
|
|
|
want := []Root{
|
|
{Name: "Media", Path: "/mnt/media"},
|
|
{Name: "Archive", Path: "/mnt/archive"},
|
|
}
|
|
if !reflect.DeepEqual(config.Roots, want) {
|
|
t.Errorf("Load().Roots = %#v, want %#v", config.Roots, want)
|
|
}
|
|
}
|
|
|
|
func TestLoadUsesRootsFromFile(t *testing.T) {
|
|
configPath := filepath.Join(t.TempDir(), "roots.json")
|
|
contents := `{
|
|
"roots": [
|
|
{"name": "Documents", "path": "/mnt/documents"}
|
|
]
|
|
}`
|
|
if err := os.WriteFile(configPath, []byte(contents), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
t.Setenv(rootsEnvVar, "")
|
|
t.Setenv(rootsFileEnvVar, configPath)
|
|
|
|
config, err := Load()
|
|
if err != nil {
|
|
t.Fatalf("Load() error = %v", err)
|
|
}
|
|
|
|
want := []Root{{Name: "Documents", Path: "/mnt/documents"}}
|
|
if !reflect.DeepEqual(config.Roots, want) {
|
|
t.Errorf("Load().Roots = %#v, want %#v", config.Roots, want)
|
|
}
|
|
}
|
|
|
|
func TestLoadEnvironmentOverridesRootsFile(t *testing.T) {
|
|
configPath := filepath.Join(t.TempDir(), "roots.json")
|
|
if err := os.WriteFile(configPath, []byte(`{"roots":[{"name":"File root","path":"/mnt/from-file"}]}`), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
t.Setenv(rootsFileEnvVar, configPath)
|
|
t.Setenv(rootsEnvVar, `[{"name":"Environment root","path":"/mnt/from-environment"}]`)
|
|
|
|
config, err := Load()
|
|
if err != nil {
|
|
t.Fatalf("Load() error = %v", err)
|
|
}
|
|
|
|
want := []Root{{Name: "Environment root", Path: "/mnt/from-environment"}}
|
|
if !reflect.DeepEqual(config.Roots, want) {
|
|
t.Errorf("Load().Roots = %#v, want %#v", config.Roots, want)
|
|
}
|
|
}
|
|
|
|
func TestLoadRejectsInvalidRoots(t *testing.T) {
|
|
t.Setenv(rootsFileEnvVar, "")
|
|
|
|
tests := []struct {
|
|
name string
|
|
value string
|
|
}{
|
|
{name: "empty list", value: `[]`},
|
|
{name: "relative path", value: `[{"name":"Media","path":"relative/path"}]`},
|
|
{name: "blank name", value: `[{"name":" ","path":"/mnt/media"}]`},
|
|
{name: "duplicate names", value: `[{"name":"Media","path":"/mnt/media"},{"name":"Media","path":"/mnt/archive"}]`},
|
|
}
|
|
|
|
for _, test := range tests {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
t.Setenv(rootsEnvVar, test.value)
|
|
|
|
if _, err := Load(); err == nil {
|
|
t.Fatal("Load() error = nil, want an error")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|