Created
November 14, 2017 08:55
-
-
Save durden/ce188f45142edbff030c0bc158d3b342 to your computer and use it in GitHub Desktop.
Simple mocking in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import contextlib | |
@contextlib.contextmanager | |
def mock_attr(object_, orig_attr_name, mock_attr): | |
""" | |
Temporarily mock object attribute for testing | |
This is similiar to the unittest.patch.object in Python 3.3 just much | |
simpler for our limited needs and use in Python 2.7. | |
:param object_: Object holding reference to attribute to mock | |
:param orig_attr_name: Name of original attribute to mock | |
:param mock_attr: Object to mock attribute with | |
""" | |
orig_attr = getattr(object_, orig_attr_name) | |
setattr(object_, orig_attr_name, mock_attr) | |
try: | |
yield object_ | |
finally: | |
setattr(object_, orig_attr_name, orig_attr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment