Skip to content

Instantly share code, notes, and snippets.

@durden
Created November 14, 2017 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save durden/ce188f45142edbff030c0bc158d3b342 to your computer and use it in GitHub Desktop.
Save durden/ce188f45142edbff030c0bc158d3b342 to your computer and use it in GitHub Desktop.
Simple mocking in Python
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