mock Gerard Meszaros's, "xUnit Test Patterns", 2007.
"System under test" (SUT)
Scope: class or module
unittest: test framework included in Python standard library
unittest exampleimport unittest
import our_module
class TestOurModule(unittest.TestCase):
def test_our_add(self):
"""Our addition function should work on 2 and 3."""
# arrange
x = 2
y = 3
expected_result = 5
# act; assert
self.assertEqual(our_module.add(x, y), expected_result)
# Another test in same test case.
def test_our_multiply(self):
"""Our multiply function should work on 3 and 4."""
self.assertEqual(our_module.multiply(3, 4), 12)
(Assume Python 2.7 or higher, for nice test discovery features.)
$ python -m unittest discover
Oops, where is our_module?
E
======================================================================
ERROR: test_our_module (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_our_module
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.3/lib/python2.7/unittest/loader.py", line 252, in _find_tests
module = self._get_module_from_name(name)
File "/usr/local/Cellar/python/2.7.3/lib/python2.7/unittest/loader.py", line 230, in _get_module_from_name
__import__(name)
File "/Users/chen/Dropbox/pghpython/2012-10-24/talk-on-python-mock/test_our_module.py", line 2, in <module>
import our_module
ImportError: No module named our_module
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
Our test case test_our_module failed because we had not yet written our_module.py at all!
This is on purpose.
Creating our_module.py:
# Note: this is deliberately buggy!
def add(x, y):
"""Return sum of x and y using clever algorithm."""
return x + y + 1
$ python -m unittest discover
FE
======================================================================
ERROR: test_our_multiply (test_our_module.TestOurModule)
Our multiply function should work on 3 and 4.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/chen/Dropbox/pghpython/2012-10-24/talk-on-python-mock/test_our_module.py", line 20, in test_our_multiply
self.assertEqual(our_module.multiply(3, 4), 12)
AttributeError: 'module' object has no attribute 'multiply'
======================================================================
FAIL: test_our_add (test_our_module.TestOurModule)
Our addition function should work on 2 and 3.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/chen/Dropbox/pghpython/2012-10-24/talk-on-python-mock/test_our_module.py", line 14, in test_our_add
self.assertEqual(our_module.add(x, y), expected_result)
AssertionError: 6 != 5
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=1, errors=1)
We want to focus only on test_our_add for now, so mark test_our_multiply as skipped for now:
@unittest.skip("Not working on multiply till add works")
def test_our_multiply(self):
"""Our multiply function should work on 3 and 4."""
self.assertEqual(our_module.multiply(3, 4), 12)
Rerun:
$ python -m unittest discover
Fs
======================================================================
FAIL: test_our_add (test_our_module.TestOurModule)
Our addition function should work on 2 and 3.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/chen/Dropbox/pghpython/2012-10-24/talk-on-python-mock/test_our_module.py", line 14, in test_our_add
self.assertEqual(our_module.add(x, y), expected_result)
AssertionError: 6 != 5
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=1, skipped=1)
def add(x, y):
"""Return sum of x and y using clever algorithm."""
return x + y
Rerun:
$ python -m unittest discover
.s
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK (skipped=1)
multiply@unittest.skip decorator from test_our_multiplyour_module.multiplySuccess!
$ python -m unittest discover
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
A test double is anything that stands in for a real thing: terminology by Meszaros, used by Fowler
mockunittest.mockeasy_install or pipTechnically, the mock library provides a test spy rather than a mock!
Michael Foord, creator of mock, on terminology:
mock.Mock()is capable of being used in most of the different roles described by Fowler, except (annoyingly / frustratingly / ironically) a Mock itself!
mockCreate a mock; author says it makes sense to use MagicMock in place of original Mock since MagicMock is more capable:
>>> from mock import MagicMock
>>> m = MagicMock()
Use the mock; actions are recorded internally:
>>> result = m(42, "everything")
Make an assertion that fails:
>>> m.assert_called_once_with("something", "else")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/2.7.3/lib/python2.7/site-packages/mock.py", line 835, in assert_called_once_with
return self.assert_called_with(*args, **kwargs)
File "/usr/local/Cellar/python/2.7.3/lib/python2.7/site-packages/mock.py", line 824, in assert_called_with
raise AssertionError(msg)
AssertionError: Expected call: mock('something', 'else')
Actual call: mock(42, 'everything')
Make an assertion that succeeds (silently):
>>> m.assert_called_once_with(42, "everything")
>>> from mock import MagicMock
>>> m = MagicMock()
>>> # Not called yet
... m.called
False
>>> # Make three calls
... m(2, 3)
<MagicMock name='mock()' id='4300782544'>
>>> m(True)
<MagicMock name='mock()' id='4300782544'>
>>> m("hello", "world")
<MagicMock name='mock()' id='4300782544'>
>>> # Number of calls made
... m.call_count
3
>>> # Assert whether ever called with (2, 3)?
... m.assert_any_call(2, 3)
>>> # the exact sequence of all calls
... m.mock_calls
[call(2, 3), call(True), call('hello', 'world')]
>>> # Set return value for the next call
... m.return_value = "yes"
>>> m(52)
'yes'
mock provides many ways to patch out a real object by a fake one.
Especially useful: context managers and decorators
Assume: we have double in our_module:
def double(x):
"""Return double x."""
return multiply(2, x)
Without a mocking framework, tricky.
multiply_count, initialized to 0our_module.multiply to increment multiply_count on each calldouble and then assert on the state multiply_count being 0Terrible: temporary change to source code in order to test
Must do a lot of refactoring just to be able to test!
our_module into a class OurMathClass(Note: this is Python 2.7 code)
class OurMathClass(object):
def add(self, x, y):
"""Return sum of x and y using clever algorithm."""
return x + y
def multiply(self, x, y):
"""Return product of x and y using clever algorithm."""
return x * y
def double(self, x):
"""Return double x."""
return self.multiply(2, x)
import unittest
import our_math_class
class TestOurMathClass(unittest.TestCase):
def setUp(self):
self.our_module = our_math_class.OurMathClass()
def test_our_add(self):
"""Our addition function should work on 2 and 3."""
# arrange
x = 2
y = 3
expected_result = 5
# act; assert
self.assertEqual(self.our_module.add(x, y), expected_result)
# Another test in same test case.
def test_our_multiply(self):
"""Our multiply function should work on 3 and 4."""
self.assertEqual(self.our_module.multiply(3, 4), 12)
OurMathClass to spyUse overriding:
(Note: this is Python 2.7 code)
from our_math_class import OurMathClass
class OurSpyingMathClass(OurMathClass):
def __init__(self):
self.multiply_call_count = 0
# Override
def multiply(self, x, y):
"""Return product of x and y while spying."""
self.multiply_call_count += 1
# Python 2.7 classes
return super(OurSpyingMathClass, self).multiply(x, y)
OurMathClass with spy class def setUp(self):
self.our_module = our_spying_math_class.OurSpyingMathClass()
def test_our_double_with_multiply(self):
"""Our double function should not work by multiplying."""
result = self.our_module.double(5)
self.assertEqual(self.our_module.multiply_call_count, 0)
Test finally runs!
$ python -m unittest test_our_spying_math_class
.F.
======================================================================
FAIL: test_our_double_with_multiply (test_our_spying_math_class.TestOurSpyingMathClass)
Our double function should not work by multiplying.
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_our_spying_math_class.py", line 29, in test_our_double_with_multiply
self.assertEqual(self.our_module.multiply_call_count, 0)
AssertionError: 1 != 0
----------------------------------------------------------------------
Ran 3 tests in 0.000s
FAILED (failures=1)
I actually like this principled approach.
Use patch decorator: patch existing function in dynamic context.
@mock.patch('our_module.multiply')
def test_our_double_with_multiply(self, fake_multiply):
"""Our double function should not work by multiplying."""
result = our_module.double(5)
self.assertEqual(fake_multiply.call_count, 0)
It fails because fake_multiply.call_count is in fact 1.
The redesigned doubling algorithm:
def double(x):
"""Return double x using clever algorithm."""
return add(x, x)
This passes the test.
Lessons:
Drawbacks:
mock does scary monkey patching behind the scenes; be warned, in complex and corner casesWant to add to OurMathClass: a function divide such that dividing N by 0 results in sending email to zerowatcherN@foo.com
test_our_math_class.pydef test_our_divide(self):
"""Dividing by zero should result in email being sent."""
with mock.patch.object(our_math_class.OurMathClass, 'mail') as mail:
result = self.our_module.divide(5, 0)
mail.assert_called_once_with('zerowatcher5@foo.com')
mail: avoid sending real email!Note that our test passes without having yet implemented the mailer.
def divide(self, x, y):
"""Return division of x and y, sending email if y is 0."""
if y == 0:
self.mail('zerowatcher' + str(x) + '@foo.com')
else:
return x / y
# TODO implement
def mail(self):
"""Email a message."""
pass
Used the mock for isolation.
Other functionality one might want to patch out:
mock provides flexible test spiesFranklin Chen
This slideshow: http://franklinchen.com/talk-on-python-mock
| Table of Contents | t |
|---|---|
| Exposé | ESC |
| Full screen slides | e |
| Presenter View | p |
| Source Files | s |
| Slide Numbers | n |
| Toggle screen blanking | b |
| Show/hide slide context | c |
| Notes | 2 |
| Help | h |