|
| 1 | +package tui |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + "strings" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/Gitlawb/zero/internal/config" |
| 11 | +) |
| 12 | + |
| 13 | +func underRoot(root, dir string) bool { |
| 14 | + rel, err := filepath.Rel(root, dir) |
| 15 | + return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) |
| 16 | +} |
| 17 | + |
| 18 | +// Guards TestMain: the per-user directories every newModel reads (and the ones |
| 19 | +// tests could write to) must resolve inside the isolated root on every OS. |
| 20 | +func TestUserDirsAreIsolatedFromTheDeveloperHome(t *testing.T) { |
| 21 | + if isolatedUserDirsRoot == "" { |
| 22 | + t.Fatal("TestMain did not isolate the user directories") |
| 23 | + } |
| 24 | + home, err := os.UserHomeDir() |
| 25 | + if err != nil { |
| 26 | + t.Fatal(err) |
| 27 | + } |
| 28 | + userConfig, err := config.UserConfigDir() |
| 29 | + if err != nil { |
| 30 | + t.Fatal(err) |
| 31 | + } |
| 32 | + cache, err := os.UserCacheDir() |
| 33 | + if err != nil { |
| 34 | + t.Fatal(err) |
| 35 | + } |
| 36 | + for name, dir := range map[string]string{"home": home, "config": userConfig, "cache": cache} { |
| 37 | + if !underRoot(isolatedUserDirsRoot, dir) { |
| 38 | + t.Errorf("%s dir %q is outside the isolated root %q", name, dir, isolatedUserDirsRoot) |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +// newModel loads slash commands from <user config>/zero/commands. A fresh model |
| 44 | +// must see none, and must see exactly what is planted in the isolated dir. |
| 45 | +func TestNewModelLoadsUserCommandsOnlyFromIsolatedConfig(t *testing.T) { |
| 46 | + if got := len(newModel(context.Background(), Options{Cwd: t.TempDir()}).userCommands); got != 0 { |
| 47 | + t.Fatalf("fresh model loaded %d user command(s) from outside the test sandbox", got) |
| 48 | + } |
| 49 | + |
| 50 | + userConfig, err := config.UserConfigDir() |
| 51 | + if err != nil { |
| 52 | + t.Fatal(err) |
| 53 | + } |
| 54 | + dir := filepath.Join(userConfig, "zero", "commands") |
| 55 | + if err := os.MkdirAll(dir, 0o755); err != nil { |
| 56 | + t.Fatal(err) |
| 57 | + } |
| 58 | + path := filepath.Join(dir, "hermetic-probe.md") |
| 59 | + if err := os.WriteFile(path, []byte("probe"), 0o644); err != nil { |
| 60 | + t.Fatal(err) |
| 61 | + } |
| 62 | + t.Cleanup(func() { _ = os.Remove(path) }) |
| 63 | + |
| 64 | + commands := newModel(context.Background(), Options{Cwd: t.TempDir()}).userCommands |
| 65 | + if len(commands) != 1 || commands[0].Name != "hermetic-probe" { |
| 66 | + t.Fatalf("user commands = %#v, want only the planted hermetic-probe", commands) |
| 67 | + } |
| 68 | +} |
0 commit comments