Skip to content

Instantly share code, notes, and snippets.

@cdunklau
Created November 20, 2014 10:15
Show Gist options
  • Save cdunklau/5cfb951969c89bf023a7 to your computer and use it in GitHub Desktop.
Save cdunklau/5cfb951969c89bf023a7 to your computer and use it in GitHub Desktop.
One reason to import modules instead of names directly
import unittest
import mock # or `from unittest import mock` in py3.3+
import undertest1
import undertest2
class MockDemoTestCase(unittest.TestCase):
# we can directly patch givestring's module namespace.
@mock.patch('othermodule.givestring', return_value='expected result')
def test_undertest1_use_othermodule_function(self, mocked_func):
self.assertEqual(undertest1.use_othermodule_function(), ['expected', 'result'])
mocked_func.assert_called_with('somearg')
# We must patch undertest2's namespace because `givestring` has been
# imported directly.
@mock.patch('undertest2.givestring', return_value='expected result')
def test_undertest2_use_othermodule_function(self, mocked_func):
self.assertEqual(undertest2.use_othermodule_function(), ['expected', 'result'])
mocked_func.assert_called_with('somearg')
import othermodule
def use_othermodule_function():
result = othermodule.givestring('somearg')
return result.split()
from othermodule import givestring
def use_othermodule_function():
result = givestring('somearg')
return result.split()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment