From fb97b62fcff0fa3df6540c23b3e613f2e39b7c32 Mon Sep 17 00:00:00 2001 From: mrbean-bremen Date: Wed, 10 Jan 2024 21:37:55 +0100 Subject: [PATCH] Reload modules loaded dynamically during test - modules loaded dynamically are now reloaded instead of deleted; deleting them caused some unexpected behavior in django - if reloading failed delete the module as last ressort --- CHANGES.md | 2 ++ pyfakefs/fake_filesystem_unittest.py | 12 +++++++----- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 3aa409eb..08fa02a8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -5,6 +5,8 @@ The released versions correspond to PyPI releases. ### Fixes * fixes handling of unhashable modules which cannot be cached (see [#923](../../issues/923)) +* reload modules loaded by the dynamic patcher instead of removing them - sometimes they may + not be reloaded automatically (see [#932](../../issues/932)) ## [Version 5.3.2](https://pypi.python.org/pypi/pyfakefs/5.3.2) (2023-11-30) Bugfix release. diff --git a/pyfakefs/fake_filesystem_unittest.py b/pyfakefs/fake_filesystem_unittest.py index 271791d5..b0bd238d 100644 --- a/pyfakefs/fake_filesystem_unittest.py +++ b/pyfakefs/fake_filesystem_unittest.py @@ -104,7 +104,7 @@ def patchfs( use_known_patches: bool = True, patch_open_code: PatchMode = PatchMode.OFF, patch_default_args: bool = False, - use_cache: bool = True + use_cache: bool = True, ) -> Callable: """Convenience decorator to use patcher with additional parameters in a test function. @@ -1091,12 +1091,14 @@ def cleanup(self) -> None: reloaded_module_names = [ module.__name__ for module in self._patcher.modules_to_reload ] - # Dereference all modules loaded during the test so they will reload on - # the next use, ensuring that no faked modules are referenced after the - # test. + # Reload all modules loaded during the test, ensuring that + # no faked modules are referenced after the test. for name in self._loaded_module_names: if name in sys.modules and name not in reloaded_module_names: - del sys.modules[name] + try: + reload(sys.modules[name]) + except Exception: + del sys.modules[name] def needs_patch(self, name: str) -> bool: """Check if the module with the given name shall be replaced."""