| 1 | package cage |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | func TestConfigChangeRequiresStop(t *testing.T) { |
| 11 | dir := t.TempDir() |
| 12 | os.MkdirAll(filepath.Join(dir, "lima", "test"), 0700) |
| 13 | c := DefaultConfig() |
| 14 | if err := c.RecordRunning(dir, "test"); err != nil { |
| 15 | t.Fatal(err) |
| 16 | } |
| 17 | if err := c.CheckRunning(dir); err != nil { |
| 18 | t.Fatal(err) |
| 19 | } |
| 20 | c.Timezone = "Asia/Tokyo" |
| 21 | if c.CheckRunning(dir) == nil { |
| 22 | t.Fatal("running profile silently changed") |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | func TestRunningRecordRejectsReusedPID(t *testing.T) { |
| 27 | dir := t.TempDir() |
| 28 | instance := filepath.Join(dir, "lima", "test") |
| 29 | os.MkdirAll(instance, 0700) |
| 30 | c := DefaultConfig() |
| 31 | if err := c.RecordRunning(dir, "test"); err != nil { |
| 32 | t.Fatal(err) |
| 33 | } |
| 34 | b, err := os.ReadFile(filepath.Join(instance, "cage-running.json")) |
| 35 | if err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | var record runningProfile |
| 39 | if err := json.Unmarshal(b, &record); err != nil { |
| 40 | t.Fatal(err) |
| 41 | } |
| 42 | if record.Started == "" { |
| 43 | t.Skip("process start time is unavailable on this platform") |
| 44 | } |
| 45 | if !record.alive() { |
| 46 | t.Fatal("current owner was not recognized") |
| 47 | } |
| 48 | legacy := runningProfile{PID: record.PID} |
| 49 | if !legacy.alive() { |
| 50 | t.Fatal("legacy PID-only record was rejected") |
| 51 | } |
| 52 | reused := runningProfile{PID: record.PID, Started: record.Started + "0", Fingerprint: record.Fingerprint} |
| 53 | if reused.alive() { |
| 54 | t.Fatal("record from an earlier process with the same PID was treated as running") |
| 55 | } |
| 56 | b, _ = json.Marshal(reused) |
| 57 | if err := os.WriteFile(filepath.Join(instance, "cage-running.json"), b, 0600); err != nil { |
| 58 | t.Fatal(err) |
| 59 | } |
| 60 | c.Timezone = "Asia/Tokyo" |
| 61 | if err := c.CheckRunning(dir); err != nil { |
| 62 | t.Fatalf("stale record blocked a configuration change: %v", err) |
| 63 | } |
| 64 | } |