Skip to content

Commit 53358fe

Browse files
TeoSlayerteovl
andauthored
test(daemon): isolate HOME for the package test binary (#252)
Many pkg/daemon tests construct New(Config{}) with an empty IdentityPath, so the daemon resolves managed-engine state (~/.pilot/managed_<netID>.json), the hostname cache, and the network snapshot under os.UserHomeDir() — the real home. Run in parallel (within the package and across the packages go test ./... runs concurrently on a shared CI runner) those tests race on the same ~/.pilot files, flaking on macOS (the snapshot / hostname-cache / managed-engine tests, which pass in isolation). Add a TestMain that points HOME (and USERPROFILE) at a throwaway dir before any test runs, making the package hermetic. Verified: tests no longer touch the real ~/.pilot; suite green; repeated concurrent ./pkg/... runs clean. Co-authored-by: Teodor Calin <teodor@vulturelabs.io>
1 parent d39c0ef commit 53358fe

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

pkg/daemon/zz_testmain_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package daemon
2+
3+
import (
4+
"os"
5+
"testing"
6+
)
7+
8+
// TestMain isolates HOME for the entire package test binary.
9+
//
10+
// Many tests here construct a daemon with New(Config{}) (empty
11+
// IdentityPath). Such a daemon resolves its on-disk state — managed-engine
12+
// files (~/.pilot/managed_<netID>.json), the hostname cache, the network
13+
// snapshot — under os.UserHomeDir(). Without isolation those tests read and
14+
// write the *real* home concurrently: both within this package's parallel
15+
// tests and across the packages that `go test ./...` runs in parallel on a
16+
// shared CI runner. That races on the same files and flakes (observed
17+
// reddening macOS CI on the snapshot / hostname-cache / managed-engine
18+
// tests, which pass in isolation).
19+
//
20+
// Pointing HOME (and USERPROFILE, for os.UserHomeDir on Windows) at a
21+
// throwaway directory before any test runs makes every test in this
22+
// package hermetic. Tests that set their own HOME via t.Setenv still work —
23+
// they override and restore relative to this base.
24+
func TestMain(m *testing.M) {
25+
tmp, err := os.MkdirTemp("", "pilot-daemon-test-home-")
26+
if err != nil {
27+
panic("daemon test: create temp HOME: " + err.Error())
28+
}
29+
_ = os.Setenv("HOME", tmp)
30+
_ = os.Setenv("USERPROFILE", tmp)
31+
32+
code := m.Run()
33+
34+
_ = os.RemoveAll(tmp)
35+
os.Exit(code)
36+
}

0 commit comments

Comments
 (0)