80 lines
2.6 KiB
Go
80 lines
2.6 KiB
Go
package config
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func TestLoadNamedNetBoxes(t *testing.T) {
|
|
dir := t.TempDir()
|
|
t.Setenv("XDG_CONFIG_HOME", dir)
|
|
t.Setenv("NETSSH_NETBOX_URL", "https://legacy-env.example")
|
|
t.Setenv("NETSSH_NETBOX_TOKEN", "legacy-env-token")
|
|
data := `netboxes:
|
|
- name: Office
|
|
url: https://office.example/netbox
|
|
token: nbt_office
|
|
- name: lab
|
|
url: https://lab.example
|
|
token: legacy-token
|
|
cache:
|
|
path: /tmp/netssh-tests/hosts.json
|
|
`
|
|
if err := os.WriteFile(filepath.Join(dir, "netssh.yaml"), []byte(data), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cfg, err := Load()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !cfg.HasNetBox() || len(cfg.NetBoxes) != 2 || cfg.NetBoxes[0].Name != "office" || cfg.NetBoxes[0].TokenVersion != 2 || cfg.NetBoxes[1].TokenVersion != 1 {
|
|
t.Fatalf("bad instances: %+v", cfg.NetBoxes)
|
|
}
|
|
if cfg.NetBox.URL != "" {
|
|
t.Fatal("legacy environment variables added an unnamed instance")
|
|
}
|
|
first := cfg.CachePath()
|
|
if first == cfg.Cache.Path {
|
|
t.Fatal("named sources reuse legacy cache")
|
|
}
|
|
cfg.NetBoxes[0], cfg.NetBoxes[1] = cfg.NetBoxes[1], cfg.NetBoxes[0]
|
|
cfg.NetBoxes[0].Token = "rotated"
|
|
if cfg.CachePath() != first {
|
|
t.Fatal("reordering/rotating credentials discarded cache")
|
|
}
|
|
cfg.NetBoxes[0].URL = "https://other.example"
|
|
if cfg.CachePath() == first {
|
|
t.Fatal("changed endpoint reuses old hosts")
|
|
}
|
|
}
|
|
|
|
func TestValidateNetBoxes(t *testing.T) {
|
|
good := NetBoxConfig{Name: "office", URL: "https://office.example"}
|
|
for _, tc := range []struct {
|
|
name string
|
|
cfg Config
|
|
}{
|
|
{"duplicate", Config{NetBoxes: []NetBoxConfig{good, {Name: "OFFICE", URL: "https://other.example"}}}},
|
|
{"empty name", Config{NetBoxes: []NetBoxConfig{{URL: "https://office.example"}}}},
|
|
{"invalid name", Config{NetBoxes: []NetBoxConfig{{Name: "a/b", URL: "https://office.example"}}}},
|
|
{"missing URL", Config{NetBoxes: []NetBoxConfig{{Name: "office"}}}},
|
|
{"invalid URL", Config{NetBoxes: []NetBoxConfig{{Name: "office", URL: "file:///tmp/netbox"}}}},
|
|
{"conflicting config", Config{NetBox: good, NetBoxes: []NetBoxConfig{good}}},
|
|
{"invalid token version", Config{NetBoxes: []NetBoxConfig{{Name: "office", URL: good.URL, TokenVersion: 3}}}},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
if err := tc.cfg.ValidateNetBoxes(); err == nil {
|
|
t.Fatal("invalid configuration accepted")
|
|
}
|
|
})
|
|
}
|
|
legacy := Config{NetBox: good, Cache: CacheConfig{Path: "hosts.json"}}
|
|
if err := legacy.ValidateNetBoxes(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !legacy.HasNetBox() || legacy.CachePath() != "hosts.json" {
|
|
t.Fatal("legacy behavior changed")
|
|
}
|
|
}
|