Skip to content

Instantly share code, notes, and snippets.

@erikzaadi
Created July 3, 2012 13:47
Show Gist options
  • Save erikzaadi/3039780 to your computer and use it in GitHub Desktop.
Save erikzaadi/3039780 to your computer and use it in GitHub Desktop.
Mocking python imports
#everyone loves a __init__ file
from third_party_module import World
class MyModule(object):
"""
My shining class
"""
def __init__(self):
"""
Let's instanciate the World (muhaha)
"""
self.world = World()
def hello(self):
"""
My shining method
"""
self.world.say("hello")
from unittest import TestCase
from mock import MagicMock
from my_module import MyModule
class TestBadMyModule(TestCase):
"""
Let's test my module!
"""
def test_hello_should_say_waitforit_hello(self):
"""
We want to test that the hello method calls the say function with the string "hello:
"""
m = MyModule()
m.world = MagicMock()
m.hello()
m.world.say.assert_called_once_with("hello")
from unittest import TestCase
from mock import patch, MagicMock
class TestGoodMyModule(TestCase):
"""
Let's test my module properly
"""
def setUp(self):
"""
It's patching time
"""
#http://www.voidspace.org.uk/python/mock/examples.html#mocking-imports-with-patch-dict
self.internetz_mock = MagicMock()
self.internetz_mock.the.internetz.everything.log.return_value = True
modules = {
'the': self.internetz_mock,
'the.internetz': self.internetz_mock.internetz,
}
self.module_patcher = patch.dict('sys.modules', modules)
self.module_patcher.start()
from my_module import MyModule
self.my_module = MyModule
def tearDown(self):
"""
Let's clean up
"""
self.module_patcher.stop()
def test_hello_should_say_waitforit_hello(self):
"""
We want to test that the hello method calls the say function with the string "hello:
"""
m = self.my_module()
m.world = MagicMock()
m.hello()
m.world.say.assert_called_once_with("hello")
from the.internetz import everything
class World(object):
"""
what a grand class
"""
def say(self, msg):
"""
It speaks!
"""
everything.log(msg)
print msg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment