Skip to content

Instantly share code, notes, and snippets.

@romuald
Last active February 22, 2023 10:05
Show Gist options
  • Save romuald/f0592fc865768ac34d3881cd2f7fd408 to your computer and use it in GitHub Desktop.
Save romuald/f0592fc865768ac34d3881cd2f7fd408 to your computer and use it in GitHub Desktop.
Python "pass-through" patch recipe
"""
This is a simple "pass-through" patch recipe for python testing
Allows to check if a method was called during testing
For example:
```
with nosy_patch('package.inner_method') as mock:
package.outter_method()
mock.assert_called()
```
"""
import unittest.mock
def _nosy_patch(patch_method, *args, **kwargs):
if 'side_effect' in kwargs:
raise TypeError(
"'side_effect' is an invalid keyword argument for _nosy_patch()"
)
def side_effect(*sargs, **skwargs):
return mock.temp_original(*sargs, **skwargs)
mock = patch_method(*args, side_effect=side_effect, **kwargs)
return mock
def nosy_patch(*args, **kwargs):
"""
A "transparent" mock.patch that is a simple pass-through, but allows to
inspect / check if some calls where made, through the patch object
"""
return _nosy_patch(unittest.mock.patch, *args, **kwargs)
def nosy_patch_object(*args, **kwargs):
"""
A "transparent" mock.patch.object that is a simple pass-through, but allows
to inspect / check if some calls where made, through the patch object
"""
return _nosy_patch(unittest.mock.patch.object, *args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment