Skip to content

Instantly share code, notes, and snippets.

@igorsobreira
Created February 18, 2013 19:56
Show Gist options
  • Save igorsobreira/4980152 to your computer and use it in GitHub Desktop.
Save igorsobreira/4980152 to your computer and use it in GitHub Desktop.
def patch_func_globals(func, **vars):
'''
Monkeypatches global variables used by a function or method
It's useful if you need to mock a global function or variable
your function uses
Usage:
with patch_func_globals(your_func, used_func=mocked_func):
your_func()
where `used_func` is called inside `your_func()`
If your function is actually a generator you must call it before
patching it, like:
my_generator = my_func_with_yield()
with patch_func_globals(my_generator, foo=foo_mock):
result = list(my_generator) # consume the generator
'''
# if it's a generator get the function object from the frame
if hasattr(func, 'gi_frame'):
return mock.patch.dict(func.gi_frame.f_globals, vars)
# methods have the function object on __func__ attribute
if hasattr(func, '__func__'):
func = func.__func__
return mock.patch.dict(func.__globals__, vars)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment