From 33f5390a6284824ebadd351facfb33a8f1ec6922 Mon Sep 17 00:00:00 2001 From: Kurt McKee Date: Wed, 18 Dec 2024 08:31:31 -0600 Subject: [PATCH] Stop patches in the reverse order they were started Because some functions are patched twice (like `os.rename()`), stopping the patches in the same order they were started can result in restoration of one of the patches. For example: ``` fn = os.rename # Patch nesting order: 1 then 2 os.rename = patch_1(fn) os.rename = patch_2(patch_1(fn)) # Unpatch 1 then 2: A still-patched function is restored os.rename = fn os.rename = patch_1(fn) # Unpatch 2 then 1: The original function is restored os.rename = patch_1(fn) os.rename = fn ``` Fixes #365 --- tests/conftest.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/conftest.py b/tests/conftest.py index 162781b..040dea9 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -217,7 +217,9 @@ def root(standardize_tmp): try: yield current_root finally: - [patch.stop() for patch in patches] + # Patches must be stopped in reverse order because some patches are nested. + # Stopping in the reverse order restores the original function. + [patch.stop() for patch in reversed(patches)] os.chdir(current_working_directory) if sys.version_info >= (3, 12): rmtree(current_root, onexc=rmtree_error_handler)