Repository navigation
test(cli): run the whole package against a throwaway user state #1250
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Vasanthdev2004
wants to merge
4
commits into
main
Choose a base branch
from
test/cli-package-isolation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
2407d9a
test(cli): run the whole package against a throwaway user state
Vasanthdev2004 ebdd97a
test(cli): clear the overrides instead of setting them, and keep cred…
Vasanthdev2004 d5a19ff
Merge remote-tracking branch 'origin/main' into test/cli-package-isol…
Vasanthdev2004 a36d047
test(cli): ignore an isolation marker the package setup did not write
Vasanthdev2004 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,397 @@ | ||
| package cli | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "os" | ||
| "os/exec" | ||
| "path/filepath" | ||
| "strings" | ||
| "testing" | ||
| ) | ||
|
|
||
| // userStateIsolatedEnv marks a process whose per-user directories have already | ||
| // been replaced. Its value is the package root the setup created. A test that | ||
| // starts this test binary again as a child inherits it and keeps the parent's | ||
| // root. A test that hands a child its own environment passes it on too, so the | ||
| // child keeps the directories it was given. | ||
| // | ||
| // The marker only counts while it names a root that still holds | ||
| // packageRootStamp. Any other value, such as "1" exported in a shell or the | ||
| // path of a root that has been removed, is ignored and the process isolates | ||
| // itself as usual. Skipping the setup on a value nobody checked would run the | ||
| // whole package against the developer's own directories. | ||
| const userStateIsolatedEnv = "ZERO_TEST_CLI_USER_STATE_ISOLATED" | ||
|
|
||
| // packageRootStamp is the file the setup writes into each root it creates. | ||
| const packageRootStamp = "zero-cli-test-package-root" | ||
|
|
||
| // packageHomeEnvNames are the directories every platform derives the per-user | ||
| // paths from when nothing overrides them. They are pointed at the package root. | ||
| var packageHomeEnvNames = []string{"HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA"} | ||
|
|
||
| // packageClearedEnvNames outrank the directories above, so an inherited value | ||
| // would send a path straight back to the developer's own. They are removed, | ||
| // not pointed at the root: a machine with none of them set is what the tests | ||
| // were written against, and several redirect only the directory their platform | ||
| // starts from. Setting XDG_CONFIG_HOME for everyone would outrank a test that | ||
| // moves HOME on macOS, where the config directory honours it first. | ||
| var packageClearedEnvNames = []string{ | ||
| "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME", | ||
| "ZERO_SANDBOX_GRANTS_PATH", "ZERO_WINDOWS_SANDBOX_HOME", | ||
| } | ||
|
|
||
| // packageUserStateRoot is the throwaway root TestMain put behind every | ||
| // per-user base directory. In a child that was already isolated it is the root | ||
| // of the run that started it. | ||
| var packageUserStateRoot string | ||
|
|
||
| // TestMain runs every test in this package against a throwaway per-user root. | ||
| // | ||
| // THE DEFAULT HAS TO BE ISOLATED, NOT THE EXCEPTION. Tests here drive the root | ||
| // command, and the root command fills whatever a test leaves out with the | ||
| // production wiring: it loads user config, user hooks, plugins and stores from | ||
| // the per-user directories, and saves credentials to the keychain. A test that | ||
| // redirects none of them runs against the developer's own. With a user-level | ||
| // hooks.json in place, one run of this package executed those hooks more than | ||
| // two thousand times, and a hooks file that merely says enabled:false is enough | ||
| // to fail a test that never mentions it. isolateCLIUserState fixes that for the | ||
| // tests that call it, and there are several hundred that do not. | ||
| // | ||
| // So the process starts out looking like a machine with an empty home and none | ||
| // of the directory overrides above. Zero's overrides for single files and | ||
| // stores, such as ZERO_OAUTH_TOKENS_PATH or ZERO_MODELS_CACHE_PATH, are not | ||
| // touched here. A test that needs its own root still calls isolateCLIUserState | ||
| // or t.Setenv, which override this for that test and restore it afterwards. | ||
| func TestMain(m *testing.M) { | ||
| os.Exit(runPackageTests(m.Run)) | ||
| } | ||
|
|
||
| func runPackageTests(run func() int) int { | ||
| root, cleanup, err := isolatePackageUserState() | ||
| if err != nil { | ||
| fmt.Fprintf(os.Stderr, "isolate the package from the user's own state: %v\n", err) | ||
| return 1 | ||
| } | ||
| defer cleanup() | ||
| packageUserStateRoot = root | ||
| return run() | ||
| } | ||
|
|
||
| // isolatePackageUserState points the home directories of this process at one | ||
| // new throwaway root, removes the variables that outrank them, and keeps | ||
| // credentials in a file under that root. It returns the root and a function | ||
| // that removes it. In a child of an isolated run it changes nothing and returns | ||
| // the parent's root with a function that leaves it in place. | ||
| func isolatePackageUserState() (string, func(), error) { | ||
| if marker := os.Getenv(userStateIsolatedEnv); isLivePackageRoot(marker) { | ||
| return marker, func() {}, nil | ||
| } | ||
| root, err := os.MkdirTemp("", "zero-cli-user-state-") | ||
| if err != nil { | ||
| return "", nil, fmt.Errorf("create the root: %w", err) | ||
| } | ||
| // The physical spelling, so a path derived from it compares equal to one | ||
| // the system reports: the temporary directory is reached through a link on | ||
| // macOS and through a short name on some Windows machines. | ||
| if resolved, err := filepath.EvalSymlinks(root); err == nil { | ||
| root = resolved | ||
| } | ||
| cleanup := func() { _ = os.RemoveAll(root) } | ||
| fail := func(err error) (string, func(), error) { | ||
| cleanup() | ||
| return "", nil, err | ||
| } | ||
| for _, name := range packageHomeEnvNames { | ||
| if err := os.Setenv(name, root); err != nil { | ||
| return fail(fmt.Errorf("redirect %s: %w", name, err)) | ||
| } | ||
| } | ||
| for _, name := range packageClearedEnvNames { | ||
| if err := os.Unsetenv(name); err != nil { | ||
| return fail(fmt.Errorf("clear %s: %w", name, err)) | ||
| } | ||
| } | ||
| // Credentials resolve keychain-first. A redirected home has no keychain, and | ||
| // a test key has no business in the real one. | ||
| if err := os.Setenv("ZERO_CRED_STORAGE", "encrypted-file"); err != nil { | ||
| return fail(fmt.Errorf("keep credentials in a file: %w", err)) | ||
| } | ||
| if err := os.WriteFile(filepath.Join(root, packageRootStamp), nil, 0o600); err != nil { | ||
| return fail(fmt.Errorf("stamp the root: %w", err)) | ||
| } | ||
| if err := os.Setenv(userStateIsolatedEnv, root); err != nil { | ||
| return fail(fmt.Errorf("mark the process as isolated: %w", err)) | ||
| } | ||
| return root, cleanup, nil | ||
| } | ||
|
|
||
| // isLivePackageRoot reports whether path is a root the setup created and has | ||
| // not removed yet. The setup exports an absolute path. A relative one would | ||
| // depend on the directory a child happens to start in, so it never counts. | ||
| func isLivePackageRoot(path string) bool { | ||
| if !filepath.IsAbs(path) { | ||
| return false | ||
| } | ||
| _, err := os.Lstat(filepath.Join(path, packageRootStamp)) | ||
| return err == nil | ||
| } | ||
|
|
||
| // The names are written out again here on purpose. Reusing the lists the setup | ||
| // walks would let a name dropped from them go unnoticed. | ||
| var ( | ||
| everyPackageHomeEnvName = []string{"HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA"} | ||
| everyPackageClearedEnvName = []string{ | ||
| "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME", | ||
| "ZERO_SANDBOX_GRANTS_PATH", "ZERO_WINDOWS_SANDBOX_HOME", | ||
| } | ||
| ) | ||
|
|
||
| func pathIsUnder(t *testing.T, root, path string) bool { | ||
| t.Helper() | ||
| resolvedRoot, err := filepath.EvalSymlinks(root) | ||
| if err != nil { | ||
| t.Fatalf("resolve %s: %v", root, err) | ||
| } | ||
| resolved, err := filepath.EvalSymlinks(path) | ||
| if err != nil { | ||
| // The path does not exist yet. The root is exported in its physical | ||
| // spelling, so a path built from it already has the right prefix. | ||
| resolved = filepath.Clean(path) | ||
| } | ||
| rel, err := filepath.Rel(resolvedRoot, resolved) | ||
| return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) | ||
| } | ||
|
|
||
| // THE PACKAGE DEFAULT IS PINNED HERE, so removing TestMain fails a test | ||
| // instead of quietly sending several hundred tests back to the developer's own | ||
| // directories. | ||
| // | ||
| // It reads the environment a test starts with, before any t.Setenv. It also | ||
| // asks Go for the three directories it derives from that environment, because | ||
| // those are what the production code resolves on each platform, and on a new | ||
| // root they do not exist yet. | ||
| func TestPackageRunsAgainstAThrowawayUserState(t *testing.T) { | ||
| if packageUserStateRoot == "" { | ||
| t.Fatal("TestMain did not replace the per-user directories for this package") | ||
| } | ||
| if resolved, err := filepath.EvalSymlinks(packageUserStateRoot); err != nil || resolved != packageUserStateRoot { | ||
| t.Fatalf("the package root is %q and resolves to %q, %v; it must be exported in its physical spelling", packageUserStateRoot, resolved, err) | ||
| } | ||
| if got := os.Getenv(userStateIsolatedEnv); got != packageUserStateRoot || !isLivePackageRoot(got) { | ||
| t.Errorf("%s = %q, want the live package root %q so a child keeps it", userStateIsolatedEnv, got, packageUserStateRoot) | ||
| } | ||
| for _, name := range everyPackageHomeEnvName { | ||
| if value := os.Getenv(name); value != packageUserStateRoot { | ||
| t.Errorf("%s = %q, want the package root %q", name, value, packageUserStateRoot) | ||
| } | ||
| } | ||
| for _, name := range everyPackageClearedEnvName { | ||
| if value, set := os.LookupEnv(name); set { | ||
| t.Errorf("%s = %q is still set; it outranks the home directories", name, value) | ||
| } | ||
| } | ||
| if got := os.Getenv("ZERO_CRED_STORAGE"); got != "encrypted-file" { | ||
| t.Errorf("ZERO_CRED_STORAGE = %q, want credentials kept in a file", got) | ||
| } | ||
| for name, resolve := range map[string]func() (string, error){ | ||
| "os.UserHomeDir": os.UserHomeDir, | ||
| "os.UserConfigDir": os.UserConfigDir, | ||
| "os.UserCacheDir": os.UserCacheDir, | ||
| } { | ||
| if path, err := resolve(); err != nil || !pathIsUnder(t, packageUserStateRoot, path) { | ||
| t.Errorf("%s() = %q, %v; want a path under %q", name, path, err, packageUserStateRoot) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // THE SETUP ITSELF, AGAINST AN ENVIRONMENT THAT POINTS SOMEWHERE ELSE. | ||
| // | ||
| // A decoy directory stands in for the developer's own behind every home | ||
| // directory and every override, and credential storage is set to the keychain, | ||
| // which the machines that run this suite never have all at once. After the | ||
| // setup nothing may still name the decoy, the overrides must be gone, and the | ||
| // process must be marked so that a child does not do it all again. The removal | ||
| // function must take the root away. | ||
| func TestIsolatePackageUserStateReplacesTheHomeAndClearsTheOverrides(t *testing.T) { | ||
| decoy := t.TempDir() | ||
| for _, name := range everyPackageHomeEnvName { | ||
| t.Setenv(name, decoy) | ||
| } | ||
| for _, name := range everyPackageClearedEnvName { | ||
| t.Setenv(name, filepath.Join(decoy, "override")) | ||
| } | ||
| t.Setenv("ZERO_CRED_STORAGE", "keyring") | ||
| t.Setenv(userStateIsolatedEnv, "") | ||
|
|
||
| root, cleanup, err := isolatePackageUserState() | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if root == "" || pathIsUnder(t, decoy, root) { | ||
| t.Fatalf("root = %q, want a new directory outside %q", root, decoy) | ||
| } | ||
| if resolved, err := filepath.EvalSymlinks(root); err != nil || resolved != root { | ||
| t.Errorf("root = %q resolves to %q, %v; want the physical spelling", root, resolved, err) | ||
| } | ||
| for _, name := range everyPackageHomeEnvName { | ||
| if value := os.Getenv(name); value != root { | ||
| t.Errorf("%s = %q, want the new root %q", name, value, root) | ||
| } | ||
| } | ||
| for _, name := range everyPackageClearedEnvName { | ||
| if value, set := os.LookupEnv(name); set { | ||
| t.Errorf("%s = %q is still set", name, value) | ||
| } | ||
| } | ||
| if got := os.Getenv("ZERO_CRED_STORAGE"); got != "encrypted-file" { | ||
| t.Errorf("ZERO_CRED_STORAGE = %q, want credentials kept in a file", got) | ||
| } | ||
| if got := os.Getenv(userStateIsolatedEnv); got != root || !isLivePackageRoot(got) { | ||
| t.Errorf("%s = %q, want the live root %q; a child started by a test would isolate itself again", userStateIsolatedEnv, got, root) | ||
| } | ||
| cleanup() | ||
| if _, err := os.Stat(root); !os.IsNotExist(err) { | ||
| t.Errorf("the root %q is still there after cleanup: %v", root, err) | ||
| } | ||
| if isLivePackageRoot(root) { | ||
| t.Errorf("the removed root %q still counts as live", root) | ||
| } | ||
| } | ||
|
|
||
| // pointUserStateAt sets every home directory to home and every override to a | ||
| // path under it, the way a developer's own environment might. | ||
| func pointUserStateAt(t *testing.T, home string) { | ||
| t.Helper() | ||
| for _, name := range everyPackageHomeEnvName { | ||
| t.Setenv(name, home) | ||
| } | ||
| for _, name := range everyPackageClearedEnvName { | ||
| t.Setenv(name, filepath.Join(home, "override")) | ||
| } | ||
| } | ||
|
|
||
| // A CHILD OF AN ISOLATED RUN IS LEFT ALONE. | ||
| // | ||
| // Some tests start this test binary again as a child and hand it its own | ||
| // directories, and two such children have to share them. Replacing the | ||
| // directories again in the child would give each its own empty root. The | ||
| // child must not remove the parent's root either. | ||
| func TestIsolatePackageUserStateLeavesAChildOfAnIsolatedRunAlone(t *testing.T) { | ||
| pointUserStateAt(t, t.TempDir()) | ||
| t.Setenv(userStateIsolatedEnv, "") | ||
| parentRoot, parentCleanup, err := isolatePackageUserState() | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| defer parentCleanup() | ||
|
|
||
| given := t.TempDir() | ||
| for _, name := range append(append([]string{}, everyPackageHomeEnvName...), everyPackageClearedEnvName...) { | ||
| t.Setenv(name, given) | ||
| } | ||
| t.Setenv(userStateIsolatedEnv, parentRoot) | ||
|
|
||
| root, cleanup, err := isolatePackageUserState() | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if root != parentRoot { | ||
| t.Fatalf("root = %q, want the parent's root %q: the process was already isolated", root, parentRoot) | ||
| } | ||
| for _, name := range append(append([]string{}, everyPackageHomeEnvName...), everyPackageClearedEnvName...) { | ||
| if value := os.Getenv(name); value != given { | ||
| t.Errorf("%s = %q, want the directory it was given, %q", name, value, given) | ||
| } | ||
| } | ||
| cleanup() | ||
| if !isLivePackageRoot(parentRoot) { | ||
| t.Errorf("the child removed the parent's root %q", parentRoot) | ||
| } | ||
| } | ||
|
|
||
| // A MARKER THE SETUP DID NOT WRITE IS IGNORED. | ||
| // | ||
| // The marker skips the whole setup, so a value that merely looks set, exported | ||
| // in a shell or copied from a log, must not be enough. With any of these the | ||
| // process has to be isolated exactly as if the marker were absent. | ||
| func TestIsolatePackageUserStateIgnoresAMarkerItDidNotWrite(t *testing.T) { | ||
| removedRoot := func(t *testing.T) string { | ||
| t.Setenv(userStateIsolatedEnv, "") | ||
| root, cleanup, err := isolatePackageUserState() | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| cleanup() | ||
| return root | ||
| } | ||
| for name, marker := range map[string]func(t *testing.T) string{ | ||
| "a flag value": func(*testing.T) string { return "1" }, | ||
| "a relative path to a stamped root": func(t *testing.T) string { | ||
| t.Chdir(t.TempDir()) | ||
| if err := os.Mkdir("root", 0o700); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if err := os.WriteFile(filepath.Join("root", packageRootStamp), nil, 0o600); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| return "root" | ||
| }, | ||
| "a directory the setup never made": func(t *testing.T) string { return t.TempDir() }, | ||
| "the root of a run that has finished": removedRoot, | ||
| } { | ||
| t.Run(name, func(t *testing.T) { | ||
| decoy := t.TempDir() | ||
| pointUserStateAt(t, decoy) | ||
| value := marker(t) | ||
| pointUserStateAt(t, decoy) | ||
| t.Setenv(userStateIsolatedEnv, value) | ||
|
|
||
| root, cleanup, err := isolatePackageUserState() | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| defer cleanup() | ||
| if root == "" || root == value || pathIsUnder(t, decoy, root) { | ||
| t.Fatalf("root = %q with the marker %q, want a new root outside %q", root, value, decoy) | ||
| } | ||
| for _, name := range everyPackageHomeEnvName { | ||
| if got := os.Getenv(name); got != root { | ||
| t.Errorf("%s = %q, want the new root %q", name, got, root) | ||
| } | ||
| } | ||
| for _, name := range everyPackageClearedEnvName { | ||
| if got, set := os.LookupEnv(name); set { | ||
| t.Errorf("%s = %q is still set", name, got) | ||
| } | ||
| } | ||
| if got := os.Getenv(userStateIsolatedEnv); got != root { | ||
| t.Errorf("%s = %q, want the new root %q", userStateIsolatedEnv, got, root) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| // THE SAME THROUGH TestMain, the way a developer would hit it: the package run | ||
| // starts with the marker already exported and every directory pointing at a | ||
| // decoy. The child runs the test that pins the package default, which fails | ||
| // if the setup was skipped. | ||
| func TestPackageRunIgnoresAMarkerFromTheOutsideEnvironment(t *testing.T) { | ||
| decoy := t.TempDir() | ||
| cmd := exec.Command(os.Args[0], "-test.run=^TestPackageRunsAgainstAThrowawayUserState$", "-test.v") | ||
| // The parent's own setup already put ZERO_CRED_STORAGE in os.Environ, so | ||
| // set it back to the keychain: the child has to get the file from its setup. | ||
| cmd.Env = append(os.Environ(), userStateIsolatedEnv+"=1", "ZERO_CRED_STORAGE=keyring") | ||
| for _, name := range everyPackageHomeEnvName { | ||
| cmd.Env = append(cmd.Env, name+"="+decoy) | ||
| } | ||
| for _, name := range everyPackageClearedEnvName { | ||
| cmd.Env = append(cmd.Env, name+"="+filepath.Join(decoy, "override")) | ||
| } | ||
| output, err := cmd.CombinedOutput() | ||
| if err != nil { | ||
| t.Fatalf("the package run with %s=1 in its environment failed: %v\n%s", userStateIsolatedEnv, err, output) | ||
| } | ||
| if !strings.Contains(string(output), "--- PASS: TestPackageRunsAgainstAThrowawayUserState") { | ||
| t.Fatalf("the child did not run the package check:\n%s", output) | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Clear
ZERO_MODELS_CACHE_PATHin the package setup.TestRunExecReasoningEffortNoticeForNonReasoningModeldoes not setZERO_MODELS_CACHE_PATHorZERO_DISABLE_MODELS_FETCH. It runsrunExecthroughrunWithDeps. An inherited absoluteZERO_MODELS_CACHE_PATHcan make this test read the developer's models cache and, when the cache is stale and the fetch succeeds, overwrite it. The repository rule requires tests to leave the developer's cache untouched.Clear the variable in
packageClearedEnvNames. The default cache path then falls under the throwawayHOME. Add the same guard toTestPackageRunsAgainstAThrowawayUserStateso the package setup keeps this variable cleared.Suggested fix
Committable suggestion
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Right, it leaks, and
ZERO_MODELS_CACHE_PATHis not the only one. The package setup also leavesZERO_OAUTH_TOKENS_PATH,ZERO_OAUTH_STORAGE,ZERO_MCP_PERMISSIONS_PATH,ZERO_MCP_OAUTH_TOKENS_PATH,ZERO_SKILLS_DIR,XDG_RUNTIME_DIRand a few more alone. I reproduced it and filed it as #1253 with the measurements.It stays out of this PR on purpose. The review above put clearing
ZERO_MODELS_CACHE_PATHout of scope here, as outside the directory redirection #1249 asks for. The fix for #1253 clears all of them in the same setup and adds them to the guard tests' own list. I'll open it once this merges, since it changes the lists this PR adds.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@Vasanthdev2004 Understood.
#1253tracks the follow-up. I’m not marking this finding as addressed.Learnings added
Learnings used
You are interacting with an AI system.