From 2d23cd9e55f5bfabffd1735878e4f4b2d7cf4c98 Mon Sep 17 00:00:00 2001 From: Vito Sansevero Date: Sun, 15 Nov 2026 05:59:36 -0800 Subject: [PATCH] fix(tests): two more Windows machine failures: killed test servers, nearby ComfyUI (#636) On a Windows machine with a virtual environment, the tests that start tests/browser/server.py failed their cleanup with WinError 32 on the server's log file, 3 of 3 runs. The venv's python.exe is a launcher that runs the real interpreter as a child; killing the launcher returns while Windows is still ending that child. The temp folder is now removed by remove_when_released, which waits until the files are released, up to 30 s. CI never saw it: its Windows job runs a plain interpreter. The diagnostics tests that expect no output folder ran in the temp root, so the fallback's ../../ComfyUI/output could reach a real ComfyUI next to it. They now run two folders deep inside the temp folder. --- tests/process_cleanup.py | 29 ++++++++++++ tests/test_browser_server_lifetime.py | 15 ++++--- tests/test_browser_slow_reset_watch.py | 17 ++++--- tests/test_process_cleanup.py | 62 ++++++++++++++++++++++++++ tests/test_utils_diagnostics.py | 17 +++++-- 5 files changed, 124 insertions(+), 16 deletions(-) create mode 100644 tests/process_cleanup.py create mode 100644 tests/test_process_cleanup.py diff --git a/tests/process_cleanup.py b/tests/process_cleanup.py new file mode 100644 index 00000000..3322ceb3 --- /dev/null +++ b/tests/process_cleanup.py @@ -0,0 +1,29 @@ +"""Remove a folder that a killed test server may still hold for a moment (#636). + +On Windows a virtual environment's ``python.exe`` is a launcher: it starts +the real interpreter as a child process and ends it with itself. Killing the +launcher returns at once, while Windows is still ending that child, which +still has its log file open, so removing the folder at that moment fails with +WinError 32. ``remove_when_released`` waits until the folder can be removed, +up to a bound, and raises the last error after it. +""" + +import shutil +import time + +RELEASE_TIMEOUT_S = 30 +POLL_S = 0.05 + + +def remove_when_released(path: str, timeout: float = RELEASE_TIMEOUT_S) -> None: + deadline = time.monotonic() + timeout + while True: + try: + shutil.rmtree(path) + return + except FileNotFoundError: + return + except PermissionError: + if time.monotonic() >= deadline: + raise + time.sleep(POLL_S) diff --git a/tests/test_browser_server_lifetime.py b/tests/test_browser_server_lifetime.py index e2ce9dd8..1bf2adbb 100644 --- a/tests/test_browser_server_lifetime.py +++ b/tests/test_browser_server_lifetime.py @@ -17,6 +17,11 @@ import urllib.error import urllib.request from pathlib import Path +try: + from tests.process_cleanup import remove_when_released +except ImportError: # discovered with tests/ as the top-level directory + from process_cleanup import remove_when_released + REPO_ROOT = Path(__file__).resolve().parent.parent SERVER_TIMEOUT_S = 60 @@ -25,12 +30,12 @@ class BrowserServerCase(unittest.TestCase): """Starts the test server in a temp folder of its own; holds no tests.""" def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) + self.tmp = tempfile.mkdtemp() + self.addCleanup(remove_when_released, self.tmp) def start(self, *extra): - env = {**os.environ, "TMPDIR": self.tmp.name} - env.update(TEMP=self.tmp.name, TMP=self.tmp.name) + env = {**os.environ, "TMPDIR": self.tmp} + env.update(TEMP=self.tmp, TMP=self.tmp) process = subprocess.Popen( [sys.executable, "-m", "tests.browser.server", "--port", "0", *extra], cwd=REPO_ROOT, @@ -65,7 +70,7 @@ class BrowserServerCase(unittest.TestCase): time.sleep(0.1) def roots(self): - return sorted(path.name for path in Path(self.tmp.name).glob("pm-browser-*")) + return sorted(path.name for path in Path(self.tmp).glob("pm-browser-*")) class TestBrowserServerLifetime(BrowserServerCase): diff --git a/tests/test_browser_slow_reset_watch.py b/tests/test_browser_slow_reset_watch.py index 3d211c65..d35d0f07 100644 --- a/tests/test_browser_slow_reset_watch.py +++ b/tests/test_browser_slow_reset_watch.py @@ -22,6 +22,11 @@ from pathlib import Path from tests.browser import slow_reset_watch from tests.browser.slow_reset_watch import REPORT_PREFIX, ResetWatch, is_reset_path +try: + from tests.process_cleanup import remove_when_released +except ImportError: # discovered with tests/ as the top-level directory + from process_cleanup import remove_when_released + REPO_ROOT = Path(__file__).resolve().parent.parent SERVER_TIMEOUT_S = 60 HOLD_SECONDS = slow_reset_watch.SLOW_RESET_SECONDS + 4 @@ -108,10 +113,10 @@ class TestSlowResetOnTheServer(unittest.TestCase): """A reset behind another process's write lock, on tests/browser/server.py.""" def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - env = {**os.environ, "TMPDIR": self.tmp.name} - env.update(TEMP=self.tmp.name, TMP=self.tmp.name) + self.tmp = tempfile.mkdtemp() + self.addCleanup(remove_when_released, self.tmp) + env = {**os.environ, "TMPDIR": self.tmp} + env.update(TEMP=self.tmp, TMP=self.tmp) self.stderr = tempfile.TemporaryFile() self.addCleanup(self.stderr.close) process = subprocess.Popen( @@ -145,9 +150,7 @@ class TestSlowResetOnTheServer(unittest.TestCase): self.assertIsNone(process.poll(), "the server exited early") self.assertLess(time.monotonic(), deadline, "never ready") time.sleep(0.1) - [self.db_path] = glob.glob( - os.path.join(self.tmp.name, "pm-browser-*", "browser.db") - ) + [self.db_path] = glob.glob(os.path.join(self.tmp, "pm-browser-*", "browser.db")) def reset(self) -> tuple[int, float]: request = urllib.request.Request( diff --git a/tests/test_process_cleanup.py b/tests/test_process_cleanup.py new file mode 100644 index 00000000..716688f4 --- /dev/null +++ b/tests/test_process_cleanup.py @@ -0,0 +1,62 @@ +"""remove_when_released waits for a dying process's files, within a bound (#636).""" + +import os +import tempfile +import unittest +from unittest import mock + +try: + from tests import process_cleanup +except ImportError: # discovered with tests/ as the top-level directory + import process_cleanup + + +class TestRemoveWhenReleased(unittest.TestCase): + def test_removes_the_folder(self): + folder = tempfile.mkdtemp() + with open(os.path.join(folder, "server.log"), "w") as handle: + handle.write("x") + process_cleanup.remove_when_released(folder) + self.assertFalse(os.path.exists(folder)) + + def test_a_missing_folder_is_already_removed(self): + folder = tempfile.mkdtemp() + os.rmdir(folder) + process_cleanup.remove_when_released(folder) + + def test_retries_while_another_process_still_holds_a_file(self): + held = PermissionError(32, "being used by another process") + with ( + mock.patch.object( + process_cleanup.shutil, "rmtree", side_effect=[held, held, None] + ) as rmtree, + mock.patch.object(process_cleanup.time, "sleep") as sleep, + ): + process_cleanup.remove_when_released("folder") + self.assertEqual(rmtree.call_count, 3) + self.assertEqual(sleep.call_count, 2) + + def test_raises_the_last_error_after_the_bound(self): + held = PermissionError(32, "being used by another process") + clock = iter([0.0, 0.0, 5.0, 11.0]) + with ( + mock.patch.object(process_cleanup.shutil, "rmtree", side_effect=held), + mock.patch.object(process_cleanup.time, "sleep"), + mock.patch.object( + process_cleanup.time, "monotonic", side_effect=lambda: next(clock) + ), + ): + with self.assertRaises(PermissionError): + process_cleanup.remove_when_released("folder", timeout=10) + + def test_other_errors_are_not_retried(self): + with mock.patch.object( + process_cleanup.shutil, "rmtree", side_effect=OSError("disk gone") + ) as rmtree: + with self.assertRaises(OSError): + process_cleanup.remove_when_released("folder") + self.assertEqual(rmtree.call_count, 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_utils_diagnostics.py b/tests/test_utils_diagnostics.py index c001233f..10db5898 100644 --- a/tests/test_utils_diagnostics.py +++ b/tests/test_utils_diagnostics.py @@ -50,6 +50,17 @@ class DiagnosticsTestCase(unittest.TestCase): os.chdir(path) self.addCleanup(os.chdir, previous) + def _chdir_without_comfyui(self): + """Work two levels inside the temp folder (#636). + + The fallback looks up to two levels above the working folder for + ``output`` and ``ComfyUI/output``; from here that never leaves the + temp folder, wherever the machine keeps it or installs ComfyUI. + """ + folder = os.path.join(self.tmp.name, "a", "b") + os.makedirs(folder) + self._chdir(folder) + class TestDatabaseChecks(DiagnosticsTestCase): def test_missing_database_is_an_error(self): @@ -159,9 +170,7 @@ class TestComfyUIOutputCheck(DiagnosticsTestCase): ) def test_nothing_found_is_a_warning(self): - empty = os.path.join(self.tmp.name, "empty") - os.makedirs(empty) - self._chdir(empty) + self._chdir_without_comfyui() with mock.patch.dict(sys.modules, {"folder_paths": None, "py.config": None}): result = self.diag.check_comfyui_output() self.assertEqual(result["status"], "warning") @@ -203,7 +212,7 @@ class TestDependenciesAndFullRun(DiagnosticsTestCase): def test_full_diagnostic_reports_every_category(self): self._populate() - self._chdir(self.tmp.name) + self._chdir_without_comfyui() with mock.patch.dict(sys.modules, {"folder_paths": None, "py.config": None}): results = self.diag.run_full_diagnostic() self.assertEqual(