Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions test/tools/AutomationClient.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,23 @@ def close(self):
self.mcp_session = None


def remove_profile(path, attempts=20, delay=0.1, remove=shutil.rmtree):
"""Removes a browser profile that a helper of the browser may still write into after the application exited (#642).

The helper can create a file between the walk of the directory and its removal (ENOTEMPTY): the removal is repeated
until the helper is gone, and what it still holds at the end is left to the system's temporary directory."""
for _ in range(attempts):
# A FileNotFoundError may come from a file that the helper removed during the walk, not from the root: only
# the absence of the root ends the removal.
with contextlib.suppress(OSError):
remove(path)
if not os.path.exists(path):
return True
time.sleep(delay)
shutil.rmtree(path, ignore_errors=True)
return not os.path.exists(path)


@contextlib.contextmanager
def profile_directory():
"""A private directory in the system temporary directory, whose removal tolerates what the browser still removes.
Expand All @@ -138,7 +155,7 @@ def profile_directory():
try:
yield path
finally:
shutil.rmtree(path, ignore_errors=True)
remove_profile(path)


def raw_request(port, text):
Expand All @@ -157,15 +174,17 @@ class Host:
def __init__(self, args, project, root, name, log, extra=(), environment=None, integrity=None):
self.root, self.name, self.log = root, name, log
self.sessions = root / "sessions"
profile = root / f"{name}-profile"
# The profile is outside the scenario's directory, whose strict cleanup a late write of a browser helper must not
# fail (#642): it lives in the private directory of profile_directory(), removed by remove_profile().
self.profiles = profile_directory()
temporary = self.profiles.__enter__()
profile = pathlib.Path(temporary) / f"{name}-profile"
self.base = ["--project", str(project), "--environment", environment or args.environment,
"--integrity", integrity or json.loads(pathlib.Path(args.provision).read_text())["integrity"],
"--registry-dir", args.registry]
env = dict(os.environ, XDG_DATA_HOME=str(profile / "data"), XDG_CACHE_HOME=str(profile / "cache"),
WEBFRONT_TEST_CEF_PROFILE=str(profile / "cef"))
# Chromium puts its singleton Unix socket in TMPDIR: a short private directory keeps it below sockaddr_un's limit.
self.profiles = profile_directory()
temporary = self.profiles.__enter__()
env.update(TMPDIR=temporary, TEMP=temporary, TMP=temporary)
# Closing its standard input closes the application's window (stop()).
self.process = subprocess.Popen([args.host, *self.base, "--sessions", str(self.sessions), *extra],
Expand Down
89 changes: 89 additions & 0 deletions test/tools/ProfileCleanupTest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""A browser helper writing into the profile after the application exited must not fail the cleanup (#642)."""
import errno
import pathlib
import shutil
import sys
import tempfile
import types
import unittest
from unittest import mock

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import AutomationClient # noqa: E402


class ProfileCleanup(unittest.TestCase):
def test_late_write_is_retried(self):
path = pathlib.Path(tempfile.mkdtemp(prefix="wf-profile-test-"))
(path / "cache").mkdir()
calls = []

def remove(target):
calls.append(target)
if len(calls) == 1:
# The helper writes after the walk of the directory and before its removal.
(path / "cache" / "late").write_text("x")
raise OSError(errno.ENOTEMPTY, "Directory not empty", str(target))
shutil.rmtree(target)

try:
self.assertTrue(AutomationClient.remove_profile(path, delay=0, remove=remove))
self.assertGreater(len(calls), 1)
self.assertFalse(path.exists())
finally:
shutil.rmtree(path, ignore_errors=True)

def test_vanished_file_is_not_a_vanished_root(self):
path = pathlib.Path(tempfile.mkdtemp(prefix="wf-profile-test-"))
calls = []

def remove(target):
calls.append(target)
if len(calls) == 1:
# shutil.rmtree reports a file that a helper removed during its walk, while the root remains.
raise FileNotFoundError(errno.ENOENT, "No such file", str(target / "gone"))
shutil.rmtree(target)

try:
self.assertTrue(AutomationClient.remove_profile(path, delay=0, remove=remove))
self.assertGreater(len(calls), 1)
self.assertFalse(path.exists())
finally:
shutil.rmtree(path, ignore_errors=True)

def test_remaining_root_is_reported(self):
path = pathlib.Path(tempfile.mkdtemp(prefix="wf-profile-test-"))
try:
def remove(target):
raise FileNotFoundError(errno.ENOENT, "No such file", str(target / "gone"))

with mock.patch.object(AutomationClient.shutil, "rmtree"):
self.assertFalse(AutomationClient.remove_profile(path, attempts=2, delay=0, remove=remove))
finally:
shutil.rmtree(path, ignore_errors=True)

def test_host_profiles_are_outside_the_scenario_directory(self):
with tempfile.TemporaryDirectory() as scenario, tempfile.TemporaryFile("w+") as log:
root = pathlib.Path(scenario).resolve()
args = types.SimpleNamespace(host="automation_host", environment="environment.tgz", registry="registry")
with mock.patch.object(AutomationClient.subprocess, "Popen") as popen:
popen.return_value.poll.return_value = 0
host = AutomationClient.Host(args, root / "project", root, "blocked", log, integrity="sha512-x")
env = popen.call_args.kwargs["env"]
try:
profiles = [pathlib.Path(env[name]).resolve()
for name in ("XDG_DATA_HOME", "XDG_CACHE_HOME", "WEBFRONT_TEST_CEF_PROFILE")]
private = pathlib.Path(env["TMPDIR"]).resolve()
for profile in profiles:
self.assertFalse(profile.is_relative_to(root), profile)
self.assertTrue(profile.is_relative_to(private), profile)
finally:
host.close()
self.assertFalse(private.exists())

def test_missing_directory_is_removed(self):
self.assertTrue(AutomationClient.remove_profile(pathlib.Path(tempfile.gettempdir()) / "wf-profile-absent-642"))


if __name__ == "__main__":
unittest.main()
5 changes: 5 additions & 0 deletions test/web/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,11 @@ set(_fixtures "${CMAKE_CURRENT_BINARY_DIR}/developer-fixtures")
if(_browser_tests_available)
webfront_optional_window_test_runner(_window_test_prefix _automation_windows_available)
find_package(Python3 COMPONENTS Interpreter QUIET)
if(Python3_Interpreter_FOUND)
# The cleanup of a browser profile that a helper still writes into after the application exited (#642).
add_test(NAME AutomationProfileCleanup COMMAND "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/test/tools/ProfileCleanupTest.py")
set_tests_properties(AutomationProfileCleanup PROPERTIES LABELS fast TIMEOUT 30)
endif()
if(Python3_Interpreter_FOUND AND _automation_windows_available)
# An application that enabled automation, which serves MCP itself (ADR-025): the program every scenario drives
# through its URL. A test program, not a shipped executable.
Expand Down
Loading