Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: Chrome-backed tests pass their user-data-dir to t.TempDir, so Chrome's post-test writes race the cleanup and red an arbitrary card's gate with 'directory not empty' (PIN-222)

Luigi Agostia01b7d2f3921
diff --git a/internal/bridge/action_form_aria_test.go b/internal/bridge/action_form_aria_test.go
index 5aefa9b4..02e95bdd 100644
--- a/internal/bridge/action_form_aria_test.go
+++ b/internal/bridge/action_form_aria_test.go
@@ -15,10 +15,7 @@ import (
func TestCheckUncheckARIACheckboxAndVerifyState(t *testing.T) {
chromePath := testbrowser.Path(t)
- profile, err := os.MkdirTemp("", "pinchtab-aria-checkbox-")
- if err != nil {
- t.Fatal(err)
- }
+ profile := testbrowser.ProfileDir(t)
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
diff --git a/internal/bridge/action_pointer_drag_test.go b/internal/bridge/action_pointer_drag_test.go
index fcb9a46f..5dea8735 100644
--- a/internal/bridge/action_pointer_drag_test.go
+++ b/internal/bridge/action_pointer_drag_test.go
@@ -44,10 +44,7 @@ func newDragFixture(t *testing.T) *dragFixture {
t.Helper()
chromePath := testbrowser.Path(t)
- profile, err := os.MkdirTemp("", "pinchtab-drag-")
- if err != nil {
- t.Fatal(err)
- }
+ profile := testbrowser.ProfileDir(t)
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
diff --git a/internal/bridge/action_resolve_modal_test.go b/internal/bridge/action_resolve_modal_test.go
index 9a747a6f..3789179a 100644
--- a/internal/bridge/action_resolve_modal_test.go
+++ b/internal/bridge/action_resolve_modal_test.go
@@ -16,10 +16,7 @@ import (
func TestDialogScopeReproducesGlobalEscapeAndContainsActionsAndReads(t *testing.T) {
chromePath := testbrowser.Path(t)
- profile, err := os.MkdirTemp("", "pinchtab-modal-scope-")
- if err != nil {
- t.Fatal(err)
- }
+ profile := testbrowser.ProfileDir(t)
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
@@ -168,10 +165,7 @@ func TestDialogScopeReproducesGlobalEscapeAndContainsActionsAndReads(t *testing.
func TestTopmostModalUsesBrowserPaintOrderAndRejectsFalseOwners(t *testing.T) {
chromePath := testbrowser.Path(t)
- profile, err := os.MkdirTemp("", "pinchtab-modal-order-")
- if err != nil {
- t.Fatal(err)
- }
+ profile := testbrowser.ProfileDir(t)
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
@@ -255,10 +249,7 @@ func TestTopmostModalUsesBrowserPaintOrderAndRejectsFalseOwners(t *testing.T) {
func TestDialogScopeContainmentIncludesOpenShadowDescendants(t *testing.T) {
chromePath := testbrowser.Path(t)
- profile, err := os.MkdirTemp("", "pinchtab-modal-shadow-containment-")
- if err != nil {
- t.Fatal(err)
- }
+ profile := testbrowser.ProfileDir(t)
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
diff --git a/internal/bridge/action_resolve_scope_test.go b/internal/bridge/action_resolve_scope_test.go
index 470ea5ab..7317ddb5 100644
--- a/internal/bridge/action_resolve_scope_test.go
+++ b/internal/bridge/action_resolve_scope_test.go
@@ -394,7 +394,7 @@ func newScopedWrapperFixture(t *testing.T) context.Context {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/bridge/action_resolve_unified_test.go b/internal/bridge/action_resolve_unified_test.go
index e77b24e2..43f0f9aa 100644
--- a/internal/bridge/action_resolve_unified_test.go
+++ b/internal/bridge/action_resolve_unified_test.go
@@ -42,7 +42,7 @@ func newSelectorFixture(t *testing.T) context.Context {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/bridge/attach_indicator_test.go b/internal/bridge/attach_indicator_test.go
index 9dabb0e0..78633f0f 100644
--- a/internal/bridge/attach_indicator_test.go
+++ b/internal/bridge/attach_indicator_test.go
@@ -17,10 +17,7 @@ import (
func TestAttachIndicatorNamesPortPersistsAndClears(t *testing.T) {
chromePath := testbrowser.Path(t)
- profile, err := os.MkdirTemp("", "pinchtab-attach-indicator-")
- if err != nil {
- t.Fatal(err)
- }
+ profile := testbrowser.ProfileDir(t)
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
diff --git a/internal/bridge/capture_background_tab_test.go b/internal/bridge/capture_background_tab_test.go
index a1852d4c..ce0a58bf 100644
--- a/internal/bridge/capture_background_tab_test.go
+++ b/internal/bridge/capture_background_tab_test.go
@@ -3,7 +3,6 @@ package bridge
import (
"context"
"encoding/base64"
- "os"
"testing"
"time"
@@ -23,11 +22,7 @@ import (
// of whether a real tab is actually painting.
func TestCaptureScreenshotOfBackgroundTabCompletesQuickly(t *testing.T) {
chromePath := testbrowser.Path(t)
- profile, err := os.MkdirTemp("", "pinchtab-bg-capture-")
- if err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { _ = os.RemoveAll(profile) })
+ profile := testbrowser.ProfileDir(t)
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
diff --git a/internal/bridge/capture_clip_bounds_test.go b/internal/bridge/capture_clip_bounds_test.go
index 7d90e5d6..23f6f19a 100644
--- a/internal/bridge/capture_clip_bounds_test.go
+++ b/internal/bridge/capture_clip_bounds_test.go
@@ -27,7 +27,7 @@ func newClipScrollFixture(t *testing.T) (context.Context, int64) {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/bridge/fingerprint_hints_test.go b/internal/bridge/fingerprint_hints_test.go
index c84e96f6..35f51cda 100644
--- a/internal/bridge/fingerprint_hints_test.go
+++ b/internal/bridge/fingerprint_hints_test.go
@@ -35,10 +35,7 @@ func TestRotatedIdentitySendsClientHintsThatAgreeWithTheUserAgent(t *testing.T)
}))
t.Cleanup(server.Close)
- profile, err := os.MkdirTemp("", "pinchtab-ua-hints-")
- if err != nil {
- t.Fatal(err)
- }
+ profile := testbrowser.ProfileDir(t)
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
diff --git a/internal/bridge/isolated_world_batch_test.go b/internal/bridge/isolated_world_batch_test.go
index 5e21da35..35af7e70 100644
--- a/internal/bridge/isolated_world_batch_test.go
+++ b/internal/bridge/isolated_world_batch_test.go
@@ -87,7 +87,7 @@ func newCountedContainmentFixture(t *testing.T) (context.Context, *cdpCounter) {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(testbrowser.Path(t)),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/bridge/isolated_world_test.go b/internal/bridge/isolated_world_test.go
index 3e87f61c..06be471c 100644
--- a/internal/bridge/isolated_world_test.go
+++ b/internal/bridge/isolated_world_test.go
@@ -43,7 +43,7 @@ func newHijackFixture(t *testing.T) context.Context {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(testbrowser.Path(t)),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/bridge/observe/bounds_test.go b/internal/bridge/observe/bounds_test.go
index 7d7e58a2..8148f548 100644
--- a/internal/bridge/observe/bounds_test.go
+++ b/internal/bridge/observe/bounds_test.go
@@ -55,7 +55,7 @@ func newScrollFixtureFrom(t *testing.T, html string, scrollX, scrollY int) scrol
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/bridge/observe/snapshot_checked_test.go b/internal/bridge/observe/snapshot_checked_test.go
index c02aab9d..a7777632 100644
--- a/internal/bridge/observe/snapshot_checked_test.go
+++ b/internal/bridge/observe/snapshot_checked_test.go
@@ -37,7 +37,7 @@ func newCheckedFixture(t *testing.T) context.Context {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/bridge/pointer_isolated_test.go b/internal/bridge/pointer_isolated_test.go
index 4a0617aa..a113f6aa 100644
--- a/internal/bridge/pointer_isolated_test.go
+++ b/internal/bridge/pointer_isolated_test.go
@@ -17,7 +17,7 @@ func newPointerFixture(t *testing.T, html string) context.Context {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(testbrowser.Path(t)),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/bridge/screenshot_clip_test.go b/internal/bridge/screenshot_clip_test.go
index a74a1144..730701b3 100644
--- a/internal/bridge/screenshot_clip_test.go
+++ b/internal/bridge/screenshot_clip_test.go
@@ -32,7 +32,7 @@ func newClipFixture(t *testing.T) context.Context {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/bridge/upload_filename_test.go b/internal/bridge/upload_filename_test.go
index d14c3167..4281edc7 100644
--- a/internal/bridge/upload_filename_test.go
+++ b/internal/bridge/upload_filename_test.go
@@ -23,11 +23,7 @@ func newUploadFixture(t *testing.T) context.Context {
// Chrome that is still flushing its cache directory as the test returns makes
// that removal error — a green assertion then reports red for a reason that
// has nothing to do with what was asserted. Best-effort removal instead.
- userDataDir, err := os.MkdirTemp("", "pinchtab-upload-fixture-*")
- if err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { _ = os.RemoveAll(userDataDir) })
+ userDataDir := testbrowser.ProfileDir(t)
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
diff --git a/internal/browsers/chrome/instance_clip_test.go b/internal/browsers/chrome/instance_clip_test.go
index a97309b9..33aa1cbf 100644
--- a/internal/browsers/chrome/instance_clip_test.go
+++ b/internal/browsers/chrome/instance_clip_test.go
@@ -28,7 +28,7 @@ func newClipFixture(t *testing.T) (*chrome.Instance, context.Context) {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/cdptk/screenshot_test.go b/internal/cdptk/screenshot_test.go
index 490a8843..d88adb06 100644
--- a/internal/cdptk/screenshot_test.go
+++ b/internal/cdptk/screenshot_test.go
@@ -41,7 +41,7 @@ func newHijackFixture(t *testing.T) context.Context {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(testbrowser.Path(t)),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
@@ -164,7 +164,7 @@ func newFramedFixture(t *testing.T) context.Context {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(testbrowser.Path(t)),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/handlers/action_selector_modal_test.go b/internal/handlers/action_selector_modal_test.go
index 90472cb9..3f3399b1 100644
--- a/internal/handlers/action_selector_modal_test.go
+++ b/internal/handlers/action_selector_modal_test.go
@@ -19,10 +19,7 @@ import (
func TestActionSelectorResolutionDefaultsToTopmostDialog(t *testing.T) {
chromePath := testbrowser.Path(t)
- profile, err := os.MkdirTemp("", "pinchtab-handler-modal-")
- if err != nil {
- t.Fatal(err)
- }
+ profile := testbrowser.ProfileDir(t)
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
diff --git a/internal/handlers/box_frame_test.go b/internal/handlers/box_frame_test.go
index 255f1f97..e1a6e0e6 100644
--- a/internal/handlers/box_frame_test.go
+++ b/internal/handlers/box_frame_test.go
@@ -60,7 +60,7 @@ func newFrameFixture(t *testing.T) frameFixture {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/handlers/capture_test.go b/internal/handlers/capture_test.go
index c81d2edd..df92b5e9 100644
--- a/internal/handlers/capture_test.go
+++ b/internal/handlers/capture_test.go
@@ -156,7 +156,7 @@ func newCaptureFixture(t *testing.T) captureFixture {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/handlers/interstitial_dismiss_test.go b/internal/handlers/interstitial_dismiss_test.go
index d5b75dd4..beba4564 100644
--- a/internal/handlers/interstitial_dismiss_test.go
+++ b/internal/handlers/interstitial_dismiss_test.go
@@ -35,10 +35,7 @@ func TestKnownInterstitialDismissalIsCatalogAndModalScoped(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- profile, err := os.MkdirTemp("", "pinchtab-interstitial-")
- if err != nil {
- t.Fatal(err)
- }
+ profile := testbrowser.ProfileDir(t)
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
diff --git a/internal/handlers/screenshot_selector_test.go b/internal/handlers/screenshot_selector_test.go
index c552aa88..9d600632 100644
--- a/internal/handlers/screenshot_selector_test.go
+++ b/internal/handlers/screenshot_selector_test.go
@@ -44,7 +44,7 @@ func newScreenshotFixture(t *testing.T) screenshotFixture {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/handlers/semantic_wrapper_index_test.go b/internal/handlers/semantic_wrapper_index_test.go
index fe3aa205..6023825f 100644
--- a/internal/handlers/semantic_wrapper_index_test.go
+++ b/internal/handlers/semantic_wrapper_index_test.go
@@ -124,7 +124,7 @@ func TestTheSameNthSelectsTheSameOrdinalOnBothPaths(t *testing.T) {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/handlers/visible_test.go b/internal/handlers/visible_test.go
index d56368aa..2b4d273e 100644
--- a/internal/handlers/visible_test.go
+++ b/internal/handlers/visible_test.go
@@ -217,7 +217,7 @@ func TestTheVisibleEndpointReadsThePositionCSSComputed(t *testing.T) {
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(chromePath),
- chromedp.UserDataDir(t.TempDir()),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true),
)...)
diff --git a/internal/testbrowser/profile.go b/internal/testbrowser/profile.go
new file mode 100644
index 00000000..2ff4f52a
--- /dev/null
+++ b/internal/testbrowser/profile.go
@@ -0,0 +1,55 @@
+package testbrowser
+
+import (
+ "os"
+ "testing"
+ "time"
+)
+
+// removalAttempts and removalBackoff bound the retry: Chrome's flush finishes in
+// milliseconds, so a couple of retries clear the common case without lengthening a
+// suite that is not racing.
+const (
+ removalAttempts = 3
+ removalBackoff = 50 * time.Millisecond
+)
+
+// ProfileDir returns a fresh Chrome user-data-dir for a browser-backed test and
+// removes it, best effort, when the test ends.
+//
+// It exists because t.TempDir CANNOT hold a browser profile. Chrome's shutdown is
+// asynchronous: when the test body returns the process is often still flushing
+// Default/Cache/Cache_Data, so files appear under the tree while t.TempDir's
+// RemoveAll is walking it, RemoveAll fails on a directory that was empty when it
+// was read, and t.TempDir turns that into a TEST FAILURE. The failure names a
+// directory that is "not empty", says nothing about the behaviour under test, and
+// lands on whichever browser test lost the race that run — so every reader spends a
+// turn proving the red is not theirs.
+//
+// Removal failure here is logged, never asserted: a leaked temp profile is the
+// lesser evil. This tolerance is scoped to browser profiles on purpose — tests that
+// launch no browser keep strict t.TempDir cleanup, which is what catches their own
+// cleanup bugs.
+func ProfileDir(t testing.TB) string {
+ t.Helper()
+ dir, err := os.MkdirTemp("", "pinchtab-test-profile-")
+ if err != nil {
+ t.Fatalf("create browser profile dir: %v", err)
+ }
+ t.Cleanup(func() { removeProfileDir(t, dir) })
+ return dir
+}
+
+func removeProfileDir(t testing.TB, dir string) {
+ t.Helper()
+ var err error
+ for attempt := 0; attempt < removalAttempts; attempt++ {
+ if attempt > 0 {
+ time.Sleep(removalBackoff)
+ }
+ if err = os.RemoveAll(dir); err == nil {
+ return
+ }
+ }
+ t.Logf("browser profile dir %s left behind (the browser is probably still flushing it): %v", dir, err)
+}
diff --git a/internal/testbrowser/profile_test.go b/internal/testbrowser/profile_test.go
new file mode 100644
index 00000000..cfb8765f
--- /dev/null
+++ b/internal/testbrowser/profile_test.go
@@ -0,0 +1,154 @@
+package testbrowser
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// The property the fix delivers, proven deterministically rather than sampled by
+// re-running a suite: a browser profile whose removal FAILS must not fail the test.
+// The subtest's own recorder stands in for a real Chrome still flushing its cache —
+// on this platform a directory is unremovable while it is a mount point or read-only
+// parent, so the honest simulation is to fail the removal by making the PARENT
+// unwritable, which is exactly the class of error RemoveAll reports mid-flush.
+func TestProfileDirCleanupToleratesAFailedRemoval(t *testing.T) {
+ parent := t.TempDir()
+ dir := filepath.Join(parent, "profile")
+ if err := os.MkdirAll(filepath.Join(dir, "Default", "Cache", "Cache_Data"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "Default", "Cache", "Cache_Data", "index"), []byte("x"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(parent, 0o500); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.Chmod(parent, 0o700) })
+
+ recorder := &cleanupRecorder{TB: t}
+ removeProfileDir(recorder, dir)
+
+ if recorder.failed {
+ t.Fatalf("a failed profile removal failed the test; that is the flake this helper exists to remove")
+ }
+ if !recorder.logged {
+ t.Error("a failed profile removal was silent; the leak must be visible in the test log")
+ }
+ if _, err := os.Stat(dir); err != nil {
+ t.Fatalf("the unremovable dir vanished, so this test did not exercise a failed removal: %v", err)
+ }
+}
+
+func TestProfileDirRemovesTheDirectoryOnTheHappyPath(t *testing.T) {
+ var dir string
+ t.Run("inner", func(inner *testing.T) {
+ dir = ProfileDir(inner)
+ if err := os.WriteFile(filepath.Join(dir, "SingletonLock"), []byte("x"), 0o644); err != nil {
+ inner.Fatal(err)
+ }
+ })
+ if _, err := os.Stat(dir); !os.IsNotExist(err) {
+ t.Errorf("profile dir %s survived the test that created it (%v); the tolerance is for a racing browser, not a licence to leak", dir, err)
+ }
+}
+
+// cleanupRecorder captures what removeProfileDir did to the test instead of doing it,
+// so "does not fail" is an assertion rather than the absence of one.
+type cleanupRecorder struct {
+ testing.TB
+ failed bool
+ logged bool
+}
+
+func (r *cleanupRecorder) Helper() {}
+func (r *cleanupRecorder) Logf(string, ...any) { r.logged = true }
+func (r *cleanupRecorder) Errorf(string, ...any) { r.failed = true }
+func (r *cleanupRecorder) Fatalf(string, ...any) { r.failed = true }
+func (r *cleanupRecorder) Error(...any) { r.failed = true }
+func (r *cleanupRecorder) Fatal(...any) { r.failed = true }
+func (r *cleanupRecorder) Cleanup(f func()) { f() }
+
+// A Chrome profile handed to t.TempDir is the defect itself: t.TempDir asserts its
+// own RemoveAll succeeded, and a browser still flushing its cache makes that fail on
+// an unrelated card's gate. The rule is checked over the whole module, because the
+// next browser test is as likely to be written in a package that has none today.
+func TestNoBrowserProfileIsPointedAtATestTempDir(t *testing.T) {
+ root := moduleRoot(t)
+ sites := 0
+
+ err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() {
+ if name := d.Name(); name == ".git" || name == "node_modules" || name == "dist" {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if !strings.HasSuffix(path, "_test.go") {
+ return nil
+ }
+
+ file, parseErr := parser.ParseFile(token.NewFileSet(), path, nil, 0)
+ if parseErr != nil {
+ return nil
+ }
+ rel, _ := filepath.Rel(root, path)
+ ast.Inspect(file, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok || !isSelectorCall(call.Fun, "chromedp", "UserDataDir") || len(call.Args) != 1 {
+ return true
+ }
+ sites++
+ if inner, ok := call.Args[0].(*ast.CallExpr); ok && isMethodCall(inner.Fun, "TempDir") {
+ t.Errorf("%s hands a Chrome profile to t.TempDir; use testbrowser.ProfileDir(t) — t.TempDir fails the test when the browser is still flushing its cache", rel)
+ }
+ return true
+ })
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("walk %s: %v", root, err)
+ }
+ if sites < 20 {
+ t.Fatalf("found only %d chromedp.UserDataDir call sites; the census matched almost nothing and would pass vacuously", sites)
+ }
+}
+
+func isSelectorCall(fun ast.Expr, pkg, name string) bool {
+ sel, ok := fun.(*ast.SelectorExpr)
+ if !ok || sel.Sel.Name != name {
+ return false
+ }
+ ident, ok := sel.X.(*ast.Ident)
+ return ok && ident.Name == pkg
+}
+
+func isMethodCall(fun ast.Expr, name string) bool {
+ sel, ok := fun.(*ast.SelectorExpr)
+ return ok && sel.Sel.Name == name
+}
+
+func moduleRoot(t *testing.T) string {
+ t.Helper()
+ dir, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for {
+ if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
+ return dir
+ }
+ parent := filepath.Dir(dir)
+ if parent == dir {
+ t.Fatal("no go.mod above the test's working directory; the census cannot find the module root")
+ }
+ dir = parent
+ }
+}