68 lines
2.1 KiB
Go
68 lines
2.1 KiB
Go
package facts
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func TestLoadDirReadsSnapshots(t *testing.T) {
|
|
dir := t.TempDir()
|
|
snap := `{"hostname":"n1","kernel":"k","containerd":"c","package_sample":{"a":"1"},"usb_scratch":{"mountpoint":"/mnt/scratch","label":"titan-16-scratch","mount_healthy":true,"bind_targets":[{"path":"/var/lib/rancher","healthy":true}],"bind_healthy":true}}`
|
|
if err := os.WriteFile(filepath.Join(dir, "snap.json"), []byte(snap), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, err := LoadDir(dir)
|
|
if err != nil {
|
|
t.Fatalf("LoadDir: %v", err)
|
|
}
|
|
if len(got) != 1 || got[0].Hostname != "n1" || got[0].PackageSample["a"] != "1" {
|
|
t.Fatalf("unexpected snapshot: %+v", got)
|
|
}
|
|
if got[0].USBScratch == nil || got[0].USBScratch.Label != "titan-16-scratch" || len(got[0].USBScratch.BindTargets) != 1 {
|
|
t.Fatalf("unexpected usb scratch snapshot: %+v", got[0].USBScratch)
|
|
}
|
|
}
|
|
|
|
func TestLoadDirRejectsInvalidJSON(t *testing.T) {
|
|
dir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(dir, "broken.json"), []byte(`{"hostname":`), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := LoadDir(dir); err == nil {
|
|
t.Fatal("expected JSON parse error")
|
|
}
|
|
}
|
|
|
|
func TestLoadDirReadsNestedDirectoriesAndMissingDir(t *testing.T) {
|
|
dir := t.TempDir()
|
|
nested := filepath.Join(dir, "nested")
|
|
if err := os.MkdirAll(nested, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(nested, "snap.json"), []byte(`{"hostname":"n2"}`), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, err := LoadDir(dir)
|
|
if err != nil {
|
|
t.Fatalf("LoadDir nested: %v", err)
|
|
}
|
|
if len(got) != 1 || got[0].Hostname != "n2" {
|
|
t.Fatalf("unexpected nested snapshots: %+v", got)
|
|
}
|
|
if _, err := LoadDir(filepath.Join(dir, "missing")); err == nil {
|
|
t.Fatal("expected missing dir error")
|
|
}
|
|
}
|
|
|
|
func TestLoadDirReportsReadFailures(t *testing.T) {
|
|
dir := t.TempDir()
|
|
if err := os.Symlink(filepath.Join(dir, "missing-target"), filepath.Join(dir, "broken.json")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
if _, err := LoadDir(dir); err == nil {
|
|
t.Fatal("expected broken json symlink to fail during read")
|
|
}
|
|
}
|