Created
December 19, 2014 11:02
-
-
Save jorge-lavin/d347650edc5fc97987ef to your computer and use it in GitHub Desktop.
Mock and monkey patching example
This file contains hidden or 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
Folder structure should be like | |
test_my_package.py | |
my_package/ | |
__init__.py | |
my_module.py | |
Requieres mock to be available | |
Usage: python test_my_package |
This file contains hidden or 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 os | |
import random | |
class MyClass(object): | |
def __init__(self): | |
self.cwd = None | |
self.random_generator = random.random | |
def get_current_work_dir(self): | |
cwd = os.getcwd() | |
self.cwd = cwd | |
def get_random(self, n): | |
return n*self.random_generator() |
This file contains hidden or 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 unittest | |
import mock | |
import my_package | |
class MethodTests(unittest.TestCase): | |
def test_get_current_work_dir(self): | |
# Mock to be used with a large set of code, as is the os package | |
self.mock_os = mock.patch('my_package.my_module.os').start() | |
test_work_dir = 'foo' | |
self.mock_os.getcwd.return_value = test_work_dir | |
my_instance = my_package.my_module.MyClass() | |
my_instance.get_current_work_dir() | |
expected_work_dir = my_instance.cwd | |
self.assertEquals(expected_work_dir, test_work_dir) | |
def test_get_random(self): | |
# Monkey patching to replace the external call to random.random in random_generator method at MyClass | |
my_instance = my_package.my_module.MyClass() | |
def return_random_number(): # This can be replaced with a lambda like function | |
return 1 | |
my_instance.random_generator = return_random_number | |
self.assertEquals(2, my_instance.get_random(2)) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment