@@ -113,7 +113,7 @@ class TestCase(unittest.TestCase):
113
113
def __init__ (self , methodName = 'runTest' , additional_skip_names = None ,
114
114
patch_path = True , special_names = None ,
115
115
modules_to_reload = None ,
116
- use_dynamic_patch = False ):
116
+ use_dynamic_patch = True ):
117
117
"""Creates the test class instance and the stubber used to stub out
118
118
file system related modules.
119
119
@@ -140,11 +140,10 @@ def __init__(self, methodName='runTest', additional_skip_names=None,
140
140
Note: this is done independently of `use_dynamic_patch`
141
141
Caution: this may not work with some Python versions
142
142
or have unwanted side effects.
143
- use_dynamic_patch (experimental) : If `True`, dynamic patching
143
+ use_dynamic_patch: If `True`, dynamic patching
144
144
after setup is used (for example for modules loaded locally
145
145
inside of functions).
146
- Caution: this may not work with some Python versions
147
- or have unwanted side effects.
146
+ Can be switched off if it causes unwanted side effects.
148
147
149
148
If you specify arguments `additional_skip_names` or `patch_path` here
150
149
and you have DocTests, consider also specifying the same arguments to
@@ -232,6 +231,7 @@ def setUpPyfakefs(self):
232
231
dyn_patcher = DynamicPatcher (self ._stubber )
233
232
sys .meta_path .insert (0 , dyn_patcher )
234
233
self .addCleanup (lambda : sys .meta_path .pop (0 ))
234
+ self .addCleanup (dyn_patcher .cleanup )
235
235
236
236
@DeprecationWarning
237
237
def tearDownPyfakefs (self ):
@@ -436,6 +436,7 @@ class DynamicPatcher(object):
436
436
def __init__ (self , patcher ):
437
437
self ._patcher = patcher
438
438
self ._patching = False
439
+ self .sysmodules = {}
439
440
self .modules = self ._patcher ._fake_modules
440
441
if 'path' in self .modules :
441
442
self .modules ['os.path' ] = self .modules ['path' ]
@@ -445,8 +446,13 @@ def __init__(self, patcher):
445
446
# otherwise the find_... methods will not be called
446
447
for module in self .modules :
447
448
if self .needs_patch (module ) and module in sys .modules :
449
+ self .sysmodules [module ] = sys .modules [module ]
448
450
del sys .modules [module ]
449
451
452
+ def cleanup (self ):
453
+ for module in self .sysmodules :
454
+ sys .modules [module ] = self .sysmodules [module ]
455
+
450
456
def needs_patch (self , name ):
451
457
"""Check if the module with the given name shall be replaced."""
452
458
if self ._patching or name not in self .modules :
0 commit comments