85 lines
2.6 KiB
Go
85 lines
2.6 KiB
Go
package budget
|
|
|
|
import (
|
|
"encoding/json"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"testing"
|
|
)
|
|
|
|
func TestWriteFiles(t *testing.T) {
|
|
p := homePaths(t.TempDir())
|
|
old := "old.scope.d/50-budget.conf"
|
|
put(t, filepath.Join(p.units, old), "old")
|
|
put(t, filepath.Join(p.units, "user.conf"), "keep")
|
|
put(t, filepath.Join(p.state, "files.json"), `["old.scope.d/50-budget.conf"]`)
|
|
files := map[string]string{"app-.scope.d/50-budget.conf": "[Scope]\nMemoryMax=8G\n", "search.slice": "[Slice]\n"}
|
|
if err := writeFiles(p, files); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(p.units, old)); !os.IsNotExist(err) {
|
|
t.Fatalf("stale owned file remains: %v", err)
|
|
}
|
|
data, err := os.ReadFile(filepath.Join(p.units, "user.conf"))
|
|
if err != nil || string(data) != "keep" {
|
|
t.Fatal("unmanaged configuration changed")
|
|
}
|
|
data, err = os.ReadFile(filepath.Join(p.state, "files.json"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var manifest []string
|
|
if err := json.Unmarshal(data, &manifest); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !reflect.DeepEqual(manifest, keys(files)) {
|
|
t.Fatal(manifest)
|
|
}
|
|
for name, want := range files {
|
|
data, err := os.ReadFile(filepath.Join(p.units, name))
|
|
if err != nil || string(data) != want {
|
|
t.Fatalf("%s: %q, %v", name, data, err)
|
|
}
|
|
}
|
|
if err := writeFiles(p, files); err != nil {
|
|
t.Fatal("second apply failed:", err)
|
|
}
|
|
}
|
|
|
|
func TestFilesRetry(t *testing.T) {
|
|
p := homePaths(t.TempDir())
|
|
old := "old-a.scope.d/50-budget.conf"
|
|
put(t, filepath.Join(p.units, old), "old")
|
|
put(t, filepath.Join(p.state, "files.json"), `["old-a.scope.d/50-budget.conf", "old-b.scope.d/50-budget.conf"]`)
|
|
blocker := filepath.Join(p.units, "new.scope.d")
|
|
put(t, blocker, "blocked")
|
|
files := map[string]string{"new.scope.d/50-budget.conf": "[Scope]\nMemoryMax=8G\n"}
|
|
if err := writeFiles(p, files); err == nil {
|
|
t.Fatal("write failure ignored")
|
|
}
|
|
if _, err := os.Stat(filepath.Join(p.units, old)); !os.IsNotExist(err) {
|
|
t.Fatalf("cleanup did not finish before the write failure: %v", err)
|
|
}
|
|
if err := os.Remove(blocker); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := writeFiles(p, files); err != nil {
|
|
t.Fatal("retry failed:", err)
|
|
}
|
|
data, err := os.ReadFile(filepath.Join(p.units, "new.scope.d/50-budget.conf"))
|
|
if err != nil || string(data) != files["new.scope.d/50-budget.conf"] {
|
|
t.Fatalf("replacement file: %q, %v", data, err)
|
|
}
|
|
data, err = os.ReadFile(filepath.Join(p.state, "files.json"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var manifest []string
|
|
if err := json.Unmarshal(data, &manifest); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !reflect.DeepEqual(manifest, keys(files)) {
|
|
t.Fatal("manifest was not updated:", manifest)
|
|
}
|
|
}
|