Skip to content

Instantly share code, notes, and snippets.

@Geekfish
Last active July 27, 2023 08:44
Show Gist options
  • Save Geekfish/aa43368ceade131b8ed9c822d2163373 to your computer and use it in GitHub Desktop.
Save Geekfish/aa43368ceade131b8ed9c822d2163373 to your computer and use it in GitHub Desktop.
Same as patch, but allows you to pass a module object which will be reloaded when entering/leaving the context.
import imp
from functools import partial
from mock.mock import _patch, _get_target, DEFAULT
class PatchWithReload(_patch):
def __init__(self, module_to_reload, *args, **kwargs):
self.module_to_reload = module_to_reload
super(PatchWithReload, self).__init__(*args, **kwargs)
def __enter__(self):
super(PatchWithReload, self).__enter__()
imp.reload(self.module_to_reload)
def __exit__(self, *exc_info):
super(PatchWithReload, self).__exit__(*exc_info)
imp.reload(self.module_to_reload)
def patch_with_reload(
target, module_to_reload, new=DEFAULT, spec=None, create=False,
spec_set=None, autospec=None, new_callable=None, **kwargs
):
"""
Same as patch, but allows you to pass a module object which will be reloaded
when entering/leaving the context
"""
getter, attribute = _get_target(target)
return PatchWithReload(
module_to_reload,
getter, attribute, new, spec, create,
spec_set, autospec, new_callable, kwargs
)
# Example - patching a decorator:
ignore_decorator = partial(
patch_with_reload,
'decorators.some_decorator',
side_effect=lambda x: x
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment