Last active
August 29, 2015 13:57
-
-
Save harmon/9607783 to your computer and use it in GitHub Desktop.
This wraps the python "Mock" library "patch" function into something that is less verbose.
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
# This helper module provides Mock library "patch" abilities | |
# while integrating with the unittest test classes in a way | |
# to reduce the verbosity of their API. | |
# | |
# Use like so: | |
# | |
# from sync.mocking_helper import patch_me | |
# | |
# class MyClassTest(object): | |
# def setUp(self): | |
# self.new_mock = patch_me(self, 'my.target.class.to.patch', 'name_of_mock_object') | |
# | |
# def test_fun(self): | |
# self.new_mock.return_value = 5 | |
# self.class_that_uses_my_target_class_to_patch() | |
# self.new_mock.assert_called_with('some_value') | |
# | |
# | |
# This will reduce your code from: | |
# class APIHelperTest(TestCase): | |
# def setUp(self): | |
# self.build_patch = patch('fileupload.api_helper.build') | |
# build = self.build_patch.start() | |
# | |
# self.mock = Mock(name='build') | |
# | |
# build.return_value = mock | |
# | |
# def tearDown(self): | |
# self.build_patch.stop() | |
# To: | |
# class APIHelperTest(TestCase): | |
# def setUp(self): | |
# build_mock = patch_me(self, 'fileupload.api_helper.build', 'build') | |
# | |
# | |
from mock import patch, MagicMock | |
__all__ = ('patch_me',) | |
def patch_me(test_class, module_to_patch, patch_name): | |
original_teardown = test_class.tearDown | |
new_patch = patch(module_to_patch, new=MagicMock(name=patch_name)) | |
new_mock = new_patch.start() | |
test_class.tearDown = _new_teardown(original_teardown, new_patch) | |
return new_mock | |
def _new_teardown(old_teardown, new_patch): | |
def teardown_wrapper(): | |
new_patch.stop() | |
old_teardown() | |
return teardown_wrapper | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment