blob: 444c20897eea6e95facf7b3b49f0ef4810830d08 [file] [log] [blame]
Michael Foorda9e6fb22012-03-28 14:36:02 +01001:mod:`unittest.mock` --- getting started
2========================================
Michael Foord944e02d2012-03-25 23:12:55 +01003
Michael Foord944e02d2012-03-25 23:12:55 +01004.. moduleauthor:: Michael Foord <michael@python.org>
5.. currentmodule:: unittest.mock
6
7.. versionadded:: 3.3
8
9
Michael Foorda9e6fb22012-03-28 14:36:02 +010010.. _getting-started:
11
12Using Mock
13----------
14
15Mock Patching Methods
16~~~~~~~~~~~~~~~~~~~~~
17
18Common uses for :class:`Mock` objects include:
19
20* Patching methods
21* Recording method calls on objects
22
23You might want to replace a method on an object to check that
24it is called with the correct arguments by another part of the system:
25
26 >>> real = SomeClass()
27 >>> real.method = MagicMock(name='method')
28 >>> real.method(3, 4, 5, key='value')
29 <MagicMock name='method()' id='...'>
30
31Once our mock has been used (`real.method` in this example) it has methods
32and attributes that allow you to make assertions about how it has been used.
33
34.. note::
35
36 In most of these examples the :class:`Mock` and :class:`MagicMock` classes
37 are interchangeable. As the `MagicMock` is the more capable class it makes
38 a sensible one to use by default.
39
40Once the mock has been called its :attr:`~Mock.called` attribute is set to
41`True`. More importantly we can use the :meth:`~Mock.assert_called_with` or
Georg Brandl24891672012-04-01 13:48:26 +020042:meth:`~Mock.assert_called_once_with` method to check that it was called with
Michael Foorda9e6fb22012-03-28 14:36:02 +010043the correct arguments.
44
45This example tests that calling `ProductionClass().method` results in a call to
46the `something` method:
47
Ezio Melottic9cfcf12013-03-11 09:42:40 +020048 >>> class ProductionClass:
Michael Foorda9e6fb22012-03-28 14:36:02 +010049 ... def method(self):
50 ... self.something(1, 2, 3)
51 ... def something(self, a, b, c):
52 ... pass
53 ...
54 >>> real = ProductionClass()
55 >>> real.something = MagicMock()
56 >>> real.method()
57 >>> real.something.assert_called_once_with(1, 2, 3)
58
59
60
61Mock for Method Calls on an Object
62~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
63
64In the last example we patched a method directly on an object to check that it
65was called correctly. Another common use case is to pass an object into a
66method (or some part of the system under test) and then check that it is used
67in the correct way.
68
69The simple `ProductionClass` below has a `closer` method. If it is called with
70an object then it calls `close` on it.
71
Ezio Melottic9cfcf12013-03-11 09:42:40 +020072 >>> class ProductionClass:
Michael Foorda9e6fb22012-03-28 14:36:02 +010073 ... def closer(self, something):
74 ... something.close()
75 ...
76
77So to test it we need to pass in an object with a `close` method and check
78that it was called correctly.
79
80 >>> real = ProductionClass()
81 >>> mock = Mock()
82 >>> real.closer(mock)
83 >>> mock.close.assert_called_with()
84
85We don't have to do any work to provide the 'close' method on our mock.
86Accessing close creates it. So, if 'close' hasn't already been called then
87accessing it in the test will create it, but :meth:`~Mock.assert_called_with`
88will raise a failure exception.
89
90
91Mocking Classes
92~~~~~~~~~~~~~~~
93
94A common use case is to mock out classes instantiated by your code under test.
95When you patch a class, then that class is replaced with a mock. Instances
96are created by *calling the class*. This means you access the "mock instance"
97by looking at the return value of the mocked class.
98
99In the example below we have a function `some_function` that instantiates `Foo`
100and calls a method on it. The call to `patch` replaces the class `Foo` with a
101mock. The `Foo` instance is the result of calling the mock, so it is configured
Michael Foord0682a0c2012-04-13 20:51:20 +0100102by modifying the mock :attr:`~Mock.return_value`.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100103
104 >>> def some_function():
105 ... instance = module.Foo()
106 ... return instance.method()
107 ...
108 >>> with patch('module.Foo') as mock:
109 ... instance = mock.return_value
110 ... instance.method.return_value = 'the result'
111 ... result = some_function()
112 ... assert result == 'the result'
113
114
115Naming your mocks
116~~~~~~~~~~~~~~~~~
117
118It can be useful to give your mocks a name. The name is shown in the repr of
119the mock and can be helpful when the mock appears in test failure messages. The
120name is also propagated to attributes or methods of the mock:
121
122 >>> mock = MagicMock(name='foo')
123 >>> mock
124 <MagicMock name='foo' id='...'>
125 >>> mock.method
126 <MagicMock name='foo.method' id='...'>
127
128
129Tracking all Calls
130~~~~~~~~~~~~~~~~~~
131
132Often you want to track more than a single call to a method. The
133:attr:`~Mock.mock_calls` attribute records all calls
134to child attributes of the mock - and also to their children.
135
136 >>> mock = MagicMock()
137 >>> mock.method()
138 <MagicMock name='mock.method()' id='...'>
139 >>> mock.attribute.method(10, x=53)
140 <MagicMock name='mock.attribute.method()' id='...'>
141 >>> mock.mock_calls
142 [call.method(), call.attribute.method(10, x=53)]
143
144If you make an assertion about `mock_calls` and any unexpected methods
145have been called, then the assertion will fail. This is useful because as well
146as asserting that the calls you expected have been made, you are also checking
147that they were made in the right order and with no additional calls:
148
149You use the :data:`call` object to construct lists for comparing with
150`mock_calls`:
151
152 >>> expected = [call.method(), call.attribute.method(10, x=53)]
153 >>> mock.mock_calls == expected
154 True
155
156
157Setting Return Values and Attributes
158~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
159
160Setting the return values on a mock object is trivially easy:
161
162 >>> mock = Mock()
163 >>> mock.return_value = 3
164 >>> mock()
165 3
166
167Of course you can do the same for methods on the mock:
168
169 >>> mock = Mock()
170 >>> mock.method.return_value = 3
171 >>> mock.method()
172 3
173
174The return value can also be set in the constructor:
175
176 >>> mock = Mock(return_value=3)
177 >>> mock()
178 3
179
180If you need an attribute setting on your mock, just do it:
181
182 >>> mock = Mock()
183 >>> mock.x = 3
184 >>> mock.x
185 3
186
187Sometimes you want to mock up a more complex situation, like for example
188`mock.connection.cursor().execute("SELECT 1")`. If we wanted this call to
189return a list, then we have to configure the result of the nested call.
190
191We can use :data:`call` to construct the set of calls in a "chained call" like
192this for easy assertion afterwards:
193
194 >>> mock = Mock()
195 >>> cursor = mock.connection.cursor.return_value
196 >>> cursor.execute.return_value = ['foo']
197 >>> mock.connection.cursor().execute("SELECT 1")
198 ['foo']
199 >>> expected = call.connection.cursor().execute("SELECT 1").call_list()
200 >>> mock.mock_calls
201 [call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]
202 >>> mock.mock_calls == expected
203 True
204
205It is the call to `.call_list()` that turns our call object into a list of
206calls representing the chained calls.
207
208
209Raising exceptions with mocks
210~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
211
212A useful attribute is :attr:`~Mock.side_effect`. If you set this to an
213exception class or instance then the exception will be raised when the mock
214is called.
215
216 >>> mock = Mock(side_effect=Exception('Boom!'))
217 >>> mock()
218 Traceback (most recent call last):
219 ...
220 Exception: Boom!
221
222
223Side effect functions and iterables
224~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
225
226`side_effect` can also be set to a function or an iterable. The use case for
227`side_effect` as an iterable is where your mock is going to be called several
228times, and you want each call to return a different value. When you set
229`side_effect` to an iterable every call to the mock returns the next value
230from the iterable:
231
232 >>> mock = MagicMock(side_effect=[4, 5, 6])
233 >>> mock()
234 4
235 >>> mock()
236 5
237 >>> mock()
238 6
239
240
241For more advanced use cases, like dynamically varying the return values
242depending on what the mock is called with, `side_effect` can be a function.
243The function will be called with the same arguments as the mock. Whatever the
244function returns is what the call returns:
245
246 >>> vals = {(1, 2): 1, (2, 3): 2}
247 >>> def side_effect(*args):
248 ... return vals[args]
249 ...
250 >>> mock = MagicMock(side_effect=side_effect)
251 >>> mock(1, 2)
252 1
253 >>> mock(2, 3)
254 2
255
256
257Creating a Mock from an Existing Object
258~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
259
260One problem with over use of mocking is that it couples your tests to the
261implementation of your mocks rather than your real code. Suppose you have a
262class that implements `some_method`. In a test for another class, you
263provide a mock of this object that *also* provides `some_method`. If later
264you refactor the first class, so that it no longer has `some_method` - then
265your tests will continue to pass even though your code is now broken!
266
267`Mock` allows you to provide an object as a specification for the mock,
268using the `spec` keyword argument. Accessing methods / attributes on the
269mock that don't exist on your specification object will immediately raise an
270attribute error. If you change the implementation of your specification, then
271tests that use that class will start failing immediately without you having to
272instantiate the class in those tests.
273
274 >>> mock = Mock(spec=SomeClass)
275 >>> mock.old_method()
276 Traceback (most recent call last):
277 ...
278 AttributeError: object has no attribute 'old_method'
279
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100280Using a specification also enables a smarter matching of calls made to the
281mock, regardless of whether some parameters were passed as positional or
282named arguments::
283
284 >>> def f(a, b, c): pass
285 ...
286 >>> mock = Mock(spec=f)
287 >>> mock(1, 2, 3)
288 <Mock name='mock()' id='140161580456576'>
289 >>> mock.assert_called_with(a=1, b=2, c=3)
290
291If you want this smarter matching to also work with method calls on the mock,
292you can use :ref:`auto-speccing <auto-speccing>`.
293
Michael Foorda9e6fb22012-03-28 14:36:02 +0100294If you want a stronger form of specification that prevents the setting
295of arbitrary attributes as well as the getting of them then you can use
296`spec_set` instead of `spec`.
297
298
299
300Patch Decorators
301----------------
302
303.. note::
304
305 With `patch` it matters that you patch objects in the namespace where they
306 are looked up. This is normally straightforward, but for a quick guide
307 read :ref:`where to patch <where-to-patch>`.
308
309
310A common need in tests is to patch a class attribute or a module attribute,
311for example patching a builtin or patching a class in a module to test that it
312is instantiated. Modules and classes are effectively global, so patching on
313them has to be undone after the test or the patch will persist into other
314tests and cause hard to diagnose problems.
315
316mock provides three convenient decorators for this: `patch`, `patch.object` and
317`patch.dict`. `patch` takes a single string, of the form
318`package.module.Class.attribute` to specify the attribute you are patching. It
319also optionally takes a value that you want the attribute (or class or
320whatever) to be replaced with. 'patch.object' takes an object and the name of
321the attribute you would like patched, plus optionally the value to patch it
322with.
323
324`patch.object`:
325
326 >>> original = SomeClass.attribute
327 >>> @patch.object(SomeClass, 'attribute', sentinel.attribute)
328 ... def test():
329 ... assert SomeClass.attribute == sentinel.attribute
330 ...
331 >>> test()
332 >>> assert SomeClass.attribute == original
333
334 >>> @patch('package.module.attribute', sentinel.attribute)
335 ... def test():
336 ... from package.module import attribute
337 ... assert attribute is sentinel.attribute
338 ...
339 >>> test()
340
Ezio Melottib40a2202013-03-30 05:55:52 +0200341If you are patching a module (including :mod:`builtins`) then use `patch`
Michael Foorda9e6fb22012-03-28 14:36:02 +0100342instead of `patch.object`:
343
Ezio Melottib40a2202013-03-30 05:55:52 +0200344 >>> mock = MagicMock(return_value=sentinel.file_handle)
345 >>> with patch('builtins.open', mock):
Michael Foorda9e6fb22012-03-28 14:36:02 +0100346 ... handle = open('filename', 'r')
347 ...
348 >>> mock.assert_called_with('filename', 'r')
349 >>> assert handle == sentinel.file_handle, "incorrect file handle returned"
350
351The module name can be 'dotted', in the form `package.module` if needed:
352
353 >>> @patch('package.module.ClassName.attribute', sentinel.attribute)
354 ... def test():
355 ... from package.module import ClassName
356 ... assert ClassName.attribute == sentinel.attribute
357 ...
358 >>> test()
359
360A nice pattern is to actually decorate test methods themselves:
361
362 >>> class MyTest(unittest2.TestCase):
363 ... @patch.object(SomeClass, 'attribute', sentinel.attribute)
364 ... def test_something(self):
365 ... self.assertEqual(SomeClass.attribute, sentinel.attribute)
366 ...
367 >>> original = SomeClass.attribute
368 >>> MyTest('test_something').test_something()
369 >>> assert SomeClass.attribute == original
370
371If you want to patch with a Mock, you can use `patch` with only one argument
372(or `patch.object` with two arguments). The mock will be created for you and
373passed into the test function / method:
374
375 >>> class MyTest(unittest2.TestCase):
376 ... @patch.object(SomeClass, 'static_method')
377 ... def test_something(self, mock_method):
378 ... SomeClass.static_method()
379 ... mock_method.assert_called_with()
380 ...
381 >>> MyTest('test_something').test_something()
382
383You can stack up multiple patch decorators using this pattern:
384
385 >>> class MyTest(unittest2.TestCase):
386 ... @patch('package.module.ClassName1')
387 ... @patch('package.module.ClassName2')
388 ... def test_something(self, MockClass2, MockClass1):
Ezio Melottie2123702013-01-10 03:43:33 +0200389 ... self.assertIs(package.module.ClassName1, MockClass1)
390 ... self.assertIs(package.module.ClassName2, MockClass2)
Michael Foorda9e6fb22012-03-28 14:36:02 +0100391 ...
392 >>> MyTest('test_something').test_something()
393
394When you nest patch decorators the mocks are passed in to the decorated
395function in the same order they applied (the normal *python* order that
396decorators are applied). This means from the bottom up, so in the example
397above the mock for `test_module.ClassName2` is passed in first.
398
399There is also :func:`patch.dict` for setting values in a dictionary just
400during a scope and restoring the dictionary to its original state when the test
401ends:
402
403 >>> foo = {'key': 'value'}
404 >>> original = foo.copy()
405 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
406 ... assert foo == {'newkey': 'newvalue'}
407 ...
408 >>> assert foo == original
409
410`patch`, `patch.object` and `patch.dict` can all be used as context managers.
411
412Where you use `patch` to create a mock for you, you can get a reference to the
413mock using the "as" form of the with statement:
414
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200415 >>> class ProductionClass:
Michael Foorda9e6fb22012-03-28 14:36:02 +0100416 ... def method(self):
417 ... pass
418 ...
419 >>> with patch.object(ProductionClass, 'method') as mock_method:
420 ... mock_method.return_value = None
421 ... real = ProductionClass()
422 ... real.method(1, 2, 3)
423 ...
424 >>> mock_method.assert_called_with(1, 2, 3)
425
426
427As an alternative `patch`, `patch.object` and `patch.dict` can be used as
428class decorators. When used in this way it is the same as applying the
429decorator indvidually to every method whose name starts with "test".
430
431
432.. _further-examples:
433
434Further Examples
Georg Brandl7fc972a2013-02-03 14:00:04 +0100435----------------
Michael Foorda9e6fb22012-03-28 14:36:02 +0100436
437
438Here are some more examples for some slightly more advanced scenarios.
Michael Foord944e02d2012-03-25 23:12:55 +0100439
440
441Mocking chained calls
Georg Brandl7fc972a2013-02-03 14:00:04 +0100442~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100443
444Mocking chained calls is actually straightforward with mock once you
445understand the :attr:`~Mock.return_value` attribute. When a mock is called for
446the first time, or you fetch its `return_value` before it has been called, a
447new `Mock` is created.
448
449This means that you can see how the object returned from a call to a mocked
450object has been used by interrogating the `return_value` mock:
451
452 >>> mock = Mock()
453 >>> mock().foo(a=2, b=3)
454 <Mock name='mock().foo()' id='...'>
455 >>> mock.return_value.foo.assert_called_with(a=2, b=3)
456
457From here it is a simple step to configure and then make assertions about
458chained calls. Of course another alternative is writing your code in a more
459testable way in the first place...
460
461So, suppose we have some code that looks a little bit like this:
462
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200463 >>> class Something:
Michael Foord944e02d2012-03-25 23:12:55 +0100464 ... def __init__(self):
465 ... self.backend = BackendProvider()
466 ... def method(self):
467 ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
468 ... # more code
469
470Assuming that `BackendProvider` is already well tested, how do we test
471`method()`? Specifically, we want to test that the code section `# more
472code` uses the response object in the correct way.
473
474As this chain of calls is made from an instance attribute we can monkey patch
475the `backend` attribute on a `Something` instance. In this particular case
476we are only interested in the return value from the final call to
477`start_call` so we don't have much configuration to do. Let's assume the
478object it returns is 'file-like', so we'll ensure that our response object
479uses the builtin `file` as its `spec`.
480
481To do this we create a mock instance as our mock backend and create a mock
482response object for it. To set the response as the return value for that final
483`start_call` we could do this:
484
485 `mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response`.
486
487We can do that in a slightly nicer way using the :meth:`~Mock.configure_mock`
488method to directly set the return value for us:
489
490 >>> something = Something()
491 >>> mock_response = Mock(spec=file)
492 >>> mock_backend = Mock()
493 >>> config = {'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response}
494 >>> mock_backend.configure_mock(**config)
495
496With these we monkey patch the "mock backend" in place and can make the real
497call:
498
499 >>> something.backend = mock_backend
500 >>> something.method()
501
502Using :attr:`~Mock.mock_calls` we can check the chained call with a single
503assert. A chained call is several calls in one line of code, so there will be
504several entries in `mock_calls`. We can use :meth:`call.call_list` to create
505this list of calls for us:
506
507 >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
508 >>> call_list = chained.call_list()
509 >>> assert mock_backend.mock_calls == call_list
510
511
512Partial mocking
Georg Brandl7fc972a2013-02-03 14:00:04 +0100513~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100514
515In some tests I wanted to mock out a call to `datetime.date.today()
516<http://docs.python.org/library/datetime.html#datetime.date.today>`_ to return
517a known date, but I didn't want to prevent the code under test from
518creating new date objects. Unfortunately `datetime.date` is written in C, and
519so I couldn't just monkey-patch out the static `date.today` method.
520
521I found a simple way of doing this that involved effectively wrapping the date
522class with a mock, but passing through calls to the constructor to the real
523class (and returning real instances).
524
525The :func:`patch decorator <patch>` is used here to
526mock out the `date` class in the module under test. The :attr:`side_effect`
527attribute on the mock date class is then set to a lambda function that returns
528a real date. When the mock date class is called a real date will be
529constructed and returned by `side_effect`.
530
531 >>> from datetime import date
532 >>> with patch('mymodule.date') as mock_date:
533 ... mock_date.today.return_value = date(2010, 10, 8)
534 ... mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
535 ...
536 ... assert mymodule.date.today() == date(2010, 10, 8)
537 ... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
538 ...
539
540Note that we don't patch `datetime.date` globally, we patch `date` in the
541module that *uses* it. See :ref:`where to patch <where-to-patch>`.
542
543When `date.today()` is called a known date is returned, but calls to the
544`date(...)` constructor still return normal dates. Without this you can find
545yourself having to calculate an expected result using exactly the same
546algorithm as the code under test, which is a classic testing anti-pattern.
547
548Calls to the date constructor are recorded in the `mock_date` attributes
549(`call_count` and friends) which may also be useful for your tests.
550
551An alternative way of dealing with mocking dates, or other builtin classes,
552is discussed in `this blog entry
553<http://williamjohnbert.com/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/>`_.
554
555
556Mocking a Generator Method
Georg Brandl7fc972a2013-02-03 14:00:04 +0100557~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100558
559A Python generator is a function or method that uses the `yield statement
560<http://docs.python.org/reference/simple_stmts.html#the-yield-statement>`_ to
561return a series of values when iterated over [#]_.
562
563A generator method / function is called to return the generator object. It is
564the generator object that is then iterated over. The protocol method for
565iteration is `__iter__
566<http://docs.python.org/library/stdtypes.html#container.__iter__>`_, so we can
567mock this using a `MagicMock`.
568
569Here's an example class with an "iter" method implemented as a generator:
570
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200571 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100572 ... def iter(self):
573 ... for i in [1, 2, 3]:
574 ... yield i
575 ...
576 >>> foo = Foo()
577 >>> list(foo.iter())
578 [1, 2, 3]
579
580
581How would we mock this class, and in particular its "iter" method?
582
583To configure the values returned from the iteration (implicit in the call to
584`list`), we need to configure the object returned by the call to `foo.iter()`.
585
586 >>> mock_foo = MagicMock()
587 >>> mock_foo.iter.return_value = iter([1, 2, 3])
588 >>> list(mock_foo.iter())
589 [1, 2, 3]
590
591.. [#] There are also generator expressions and more `advanced uses
592 <http://www.dabeaz.com/coroutines/index.html>`_ of generators, but we aren't
593 concerned about them here. A very good introduction to generators and how
594 powerful they are is: `Generator Tricks for Systems Programmers
595 <http://www.dabeaz.com/generators/>`_.
596
597
598Applying the same patch to every test method
Georg Brandl7fc972a2013-02-03 14:00:04 +0100599~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100600
601If you want several patches in place for multiple test methods the obvious way
602is to apply the patch decorators to every method. This can feel like unnecessary
603repetition. For Python 2.6 or more recent you can use `patch` (in all its
604various forms) as a class decorator. This applies the patches to all test
605methods on the class. A test method is identified by methods whose names start
606with `test`:
607
608 >>> @patch('mymodule.SomeClass')
609 ... class MyTest(TestCase):
610 ...
611 ... def test_one(self, MockSomeClass):
Ezio Melottie2123702013-01-10 03:43:33 +0200612 ... self.assertIs(mymodule.SomeClass, MockSomeClass)
Michael Foord944e02d2012-03-25 23:12:55 +0100613 ...
614 ... def test_two(self, MockSomeClass):
Ezio Melottie2123702013-01-10 03:43:33 +0200615 ... self.assertIs(mymodule.SomeClass, MockSomeClass)
Michael Foord944e02d2012-03-25 23:12:55 +0100616 ...
617 ... def not_a_test(self):
618 ... return 'something'
619 ...
620 >>> MyTest('test_one').test_one()
621 >>> MyTest('test_two').test_two()
622 >>> MyTest('test_two').not_a_test()
623 'something'
624
625An alternative way of managing patches is to use the :ref:`start-and-stop`.
626These allow you to move the patching into your `setUp` and `tearDown` methods.
627
628 >>> class MyTest(TestCase):
629 ... def setUp(self):
630 ... self.patcher = patch('mymodule.foo')
631 ... self.mock_foo = self.patcher.start()
632 ...
633 ... def test_foo(self):
Ezio Melottie2123702013-01-10 03:43:33 +0200634 ... self.assertIs(mymodule.foo, self.mock_foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100635 ...
636 ... def tearDown(self):
637 ... self.patcher.stop()
638 ...
639 >>> MyTest('test_foo').run()
640
641If you use this technique you must ensure that the patching is "undone" by
642calling `stop`. This can be fiddlier than you might think, because if an
643exception is raised in the setUp then tearDown is not called.
644:meth:`unittest.TestCase.addCleanup` makes this easier:
645
646 >>> class MyTest(TestCase):
647 ... def setUp(self):
648 ... patcher = patch('mymodule.foo')
649 ... self.addCleanup(patcher.stop)
650 ... self.mock_foo = patcher.start()
651 ...
652 ... def test_foo(self):
Ezio Melottie2123702013-01-10 03:43:33 +0200653 ... self.assertIs(mymodule.foo, self.mock_foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100654 ...
655 >>> MyTest('test_foo').run()
656
657
658Mocking Unbound Methods
Georg Brandl7fc972a2013-02-03 14:00:04 +0100659~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100660
661Whilst writing tests today I needed to patch an *unbound method* (patching the
662method on the class rather than on the instance). I needed self to be passed
663in as the first argument because I want to make asserts about which objects
664were calling this particular method. The issue is that you can't patch with a
665mock for this, because if you replace an unbound method with a mock it doesn't
666become a bound method when fetched from the instance, and so it doesn't get
667self passed in. The workaround is to patch the unbound method with a real
668function instead. The :func:`patch` decorator makes it so simple to
669patch out methods with a mock that having to create a real function becomes a
670nuisance.
671
672If you pass `autospec=True` to patch then it does the patching with a
673*real* function object. This function object has the same signature as the one
674it is replacing, but delegates to a mock under the hood. You still get your
675mock auto-created in exactly the same way as before. What it means though, is
676that if you use it to patch out an unbound method on a class the mocked
677function will be turned into a bound method if it is fetched from an instance.
678It will have `self` passed in as the first argument, which is exactly what I
679wanted:
680
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200681 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100682 ... def foo(self):
683 ... pass
684 ...
685 >>> with patch.object(Foo, 'foo', autospec=True) as mock_foo:
686 ... mock_foo.return_value = 'foo'
687 ... foo = Foo()
688 ... foo.foo()
689 ...
690 'foo'
691 >>> mock_foo.assert_called_once_with(foo)
692
693If we don't use `autospec=True` then the unbound method is patched out
694with a Mock instance instead, and isn't called with `self`.
695
696
697Checking multiple calls with mock
Georg Brandl7fc972a2013-02-03 14:00:04 +0100698~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100699
700mock has a nice API for making assertions about how your mock objects are used.
701
702 >>> mock = Mock()
703 >>> mock.foo_bar.return_value = None
704 >>> mock.foo_bar('baz', spam='eggs')
705 >>> mock.foo_bar.assert_called_with('baz', spam='eggs')
706
707If your mock is only being called once you can use the
708:meth:`assert_called_once_with` method that also asserts that the
709:attr:`call_count` is one.
710
711 >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
712 >>> mock.foo_bar()
713 >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
714 Traceback (most recent call last):
715 ...
716 AssertionError: Expected to be called once. Called 2 times.
717
718Both `assert_called_with` and `assert_called_once_with` make assertions about
719the *most recent* call. If your mock is going to be called several times, and
720you want to make assertions about *all* those calls you can use
721:attr:`~Mock.call_args_list`:
722
723 >>> mock = Mock(return_value=None)
724 >>> mock(1, 2, 3)
725 >>> mock(4, 5, 6)
726 >>> mock()
727 >>> mock.call_args_list
728 [call(1, 2, 3), call(4, 5, 6), call()]
729
730The :data:`call` helper makes it easy to make assertions about these calls. You
731can build up a list of expected calls and compare it to `call_args_list`. This
732looks remarkably similar to the repr of the `call_args_list`:
733
734 >>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
735 >>> mock.call_args_list == expected
736 True
737
738
739Coping with mutable arguments
Georg Brandl7fc972a2013-02-03 14:00:04 +0100740~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100741
742Another situation is rare, but can bite you, is when your mock is called with
743mutable arguments. `call_args` and `call_args_list` store *references* to the
744arguments. If the arguments are mutated by the code under test then you can no
745longer make assertions about what the values were when the mock was called.
746
747Here's some example code that shows the problem. Imagine the following functions
748defined in 'mymodule'::
749
750 def frob(val):
751 pass
752
753 def grob(val):
754 "First frob and then clear val"
755 frob(val)
756 val.clear()
757
758When we try to test that `grob` calls `frob` with the correct argument look
759what happens:
760
761 >>> with patch('mymodule.frob') as mock_frob:
762 ... val = set([6])
763 ... mymodule.grob(val)
764 ...
765 >>> val
766 set([])
767 >>> mock_frob.assert_called_with(set([6]))
768 Traceback (most recent call last):
769 ...
770 AssertionError: Expected: ((set([6]),), {})
771 Called with: ((set([]),), {})
772
773One possibility would be for mock to copy the arguments you pass in. This
774could then cause problems if you do assertions that rely on object identity
775for equality.
776
777Here's one solution that uses the :attr:`side_effect`
778functionality. If you provide a `side_effect` function for a mock then
779`side_effect` will be called with the same args as the mock. This gives us an
780opportunity to copy the arguments and store them for later assertions. In this
781example I'm using *another* mock to store the arguments so that I can use the
782mock methods for doing the assertion. Again a helper function sets this up for
783me.
784
785 >>> from copy import deepcopy
786 >>> from unittest.mock import Mock, patch, DEFAULT
787 >>> def copy_call_args(mock):
788 ... new_mock = Mock()
789 ... def side_effect(*args, **kwargs):
790 ... args = deepcopy(args)
791 ... kwargs = deepcopy(kwargs)
792 ... new_mock(*args, **kwargs)
793 ... return DEFAULT
794 ... mock.side_effect = side_effect
795 ... return new_mock
796 ...
797 >>> with patch('mymodule.frob') as mock_frob:
798 ... new_mock = copy_call_args(mock_frob)
799 ... val = set([6])
800 ... mymodule.grob(val)
801 ...
802 >>> new_mock.assert_called_with(set([6]))
803 >>> new_mock.call_args
804 call(set([6]))
805
806`copy_call_args` is called with the mock that will be called. It returns a new
807mock that we do the assertion on. The `side_effect` function makes a copy of
808the args and calls our `new_mock` with the copy.
809
810.. note::
811
812 If your mock is only going to be used once there is an easier way of
813 checking arguments at the point they are called. You can simply do the
814 checking inside a `side_effect` function.
815
816 >>> def side_effect(arg):
817 ... assert arg == set([6])
818 ...
819 >>> mock = Mock(side_effect=side_effect)
820 >>> mock(set([6]))
821 >>> mock(set())
822 Traceback (most recent call last):
823 ...
824 AssertionError
825
826An alternative approach is to create a subclass of `Mock` or `MagicMock` that
827copies (using :func:`copy.deepcopy`) the arguments.
828Here's an example implementation:
829
830 >>> from copy import deepcopy
831 >>> class CopyingMock(MagicMock):
832 ... def __call__(self, *args, **kwargs):
833 ... args = deepcopy(args)
834 ... kwargs = deepcopy(kwargs)
835 ... return super(CopyingMock, self).__call__(*args, **kwargs)
836 ...
837 >>> c = CopyingMock(return_value=None)
838 >>> arg = set()
839 >>> c(arg)
840 >>> arg.add(1)
841 >>> c.assert_called_with(set())
842 >>> c.assert_called_with(arg)
843 Traceback (most recent call last):
844 ...
845 AssertionError: Expected call: mock(set([1]))
846 Actual call: mock(set([]))
847 >>> c.foo
848 <CopyingMock name='mock.foo' id='...'>
849
850When you subclass `Mock` or `MagicMock` all dynamically created attributes,
851and the `return_value` will use your subclass automatically. That means all
852children of a `CopyingMock` will also have the type `CopyingMock`.
853
854
Michael Foord944e02d2012-03-25 23:12:55 +0100855Nesting Patches
Georg Brandl7fc972a2013-02-03 14:00:04 +0100856~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100857
858Using patch as a context manager is nice, but if you do multiple patches you
859can end up with nested with statements indenting further and further to the
860right:
861
862 >>> class MyTest(TestCase):
863 ...
864 ... def test_foo(self):
865 ... with patch('mymodule.Foo') as mock_foo:
866 ... with patch('mymodule.Bar') as mock_bar:
867 ... with patch('mymodule.Spam') as mock_spam:
868 ... assert mymodule.Foo is mock_foo
869 ... assert mymodule.Bar is mock_bar
870 ... assert mymodule.Spam is mock_spam
871 ...
872 >>> original = mymodule.Foo
873 >>> MyTest('test_foo').test_foo()
874 >>> assert mymodule.Foo is original
875
876With unittest `cleanup` functions and the :ref:`start-and-stop` we can
877achieve the same effect without the nested indentation. A simple helper
878method, `create_patch`, puts the patch in place and returns the created mock
879for us:
880
881 >>> class MyTest(TestCase):
882 ...
883 ... def create_patch(self, name):
884 ... patcher = patch(name)
885 ... thing = patcher.start()
886 ... self.addCleanup(patcher.stop)
887 ... return thing
888 ...
889 ... def test_foo(self):
890 ... mock_foo = self.create_patch('mymodule.Foo')
891 ... mock_bar = self.create_patch('mymodule.Bar')
892 ... mock_spam = self.create_patch('mymodule.Spam')
893 ...
894 ... assert mymodule.Foo is mock_foo
895 ... assert mymodule.Bar is mock_bar
896 ... assert mymodule.Spam is mock_spam
897 ...
898 >>> original = mymodule.Foo
899 >>> MyTest('test_foo').run()
900 >>> assert mymodule.Foo is original
901
902
903Mocking a dictionary with MagicMock
Georg Brandl7fc972a2013-02-03 14:00:04 +0100904~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100905
906You may want to mock a dictionary, or other container object, recording all
907access to it whilst having it still behave like a dictionary.
908
909We can do this with :class:`MagicMock`, which will behave like a dictionary,
910and using :data:`~Mock.side_effect` to delegate dictionary access to a real
911underlying dictionary that is under our control.
912
913When the `__getitem__` and `__setitem__` methods of our `MagicMock` are called
914(normal dictionary access) then `side_effect` is called with the key (and in
915the case of `__setitem__` the value too). We can also control what is returned.
916
917After the `MagicMock` has been used we can use attributes like
918:data:`~Mock.call_args_list` to assert about how the dictionary was used:
919
920 >>> my_dict = {'a': 1, 'b': 2, 'c': 3}
921 >>> def getitem(name):
922 ... return my_dict[name]
923 ...
924 >>> def setitem(name, val):
925 ... my_dict[name] = val
926 ...
927 >>> mock = MagicMock()
928 >>> mock.__getitem__.side_effect = getitem
929 >>> mock.__setitem__.side_effect = setitem
930
931.. note::
932
933 An alternative to using `MagicMock` is to use `Mock` and *only* provide
934 the magic methods you specifically want:
935
936 >>> mock = Mock()
937 >>> mock.__setitem__ = Mock(side_effect=getitem)
938 >>> mock.__getitem__ = Mock(side_effect=setitem)
939
940 A *third* option is to use `MagicMock` but passing in `dict` as the `spec`
941 (or `spec_set`) argument so that the `MagicMock` created only has
942 dictionary magic methods available:
943
944 >>> mock = MagicMock(spec_set=dict)
945 >>> mock.__getitem__.side_effect = getitem
946 >>> mock.__setitem__.side_effect = setitem
947
948With these side effect functions in place, the `mock` will behave like a normal
949dictionary but recording the access. It even raises a `KeyError` if you try
950to access a key that doesn't exist.
951
952 >>> mock['a']
953 1
954 >>> mock['c']
955 3
956 >>> mock['d']
957 Traceback (most recent call last):
958 ...
959 KeyError: 'd'
960 >>> mock['b'] = 'fish'
961 >>> mock['d'] = 'eggs'
962 >>> mock['b']
963 'fish'
964 >>> mock['d']
965 'eggs'
966
967After it has been used you can make assertions about the access using the normal
968mock methods and attributes:
969
970 >>> mock.__getitem__.call_args_list
971 [call('a'), call('c'), call('d'), call('b'), call('d')]
972 >>> mock.__setitem__.call_args_list
973 [call('b', 'fish'), call('d', 'eggs')]
974 >>> my_dict
975 {'a': 1, 'c': 3, 'b': 'fish', 'd': 'eggs'}
976
977
978Mock subclasses and their attributes
Georg Brandl7fc972a2013-02-03 14:00:04 +0100979~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +0100980
981There are various reasons why you might want to subclass `Mock`. One reason
982might be to add helper methods. Here's a silly example:
983
984 >>> class MyMock(MagicMock):
985 ... def has_been_called(self):
986 ... return self.called
987 ...
988 >>> mymock = MyMock(return_value=None)
989 >>> mymock
990 <MyMock id='...'>
991 >>> mymock.has_been_called()
992 False
993 >>> mymock()
994 >>> mymock.has_been_called()
995 True
996
997The standard behaviour for `Mock` instances is that attributes and the return
998value mocks are of the same type as the mock they are accessed on. This ensures
999that `Mock` attributes are `Mocks` and `MagicMock` attributes are `MagicMocks`
1000[#]_. So if you're subclassing to add helper methods then they'll also be
1001available on the attributes and return value mock of instances of your
1002subclass.
1003
1004 >>> mymock.foo
1005 <MyMock name='mock.foo' id='...'>
1006 >>> mymock.foo.has_been_called()
1007 False
1008 >>> mymock.foo()
1009 <MyMock name='mock.foo()' id='...'>
1010 >>> mymock.foo.has_been_called()
1011 True
1012
1013Sometimes this is inconvenient. For example, `one user
1014<https://code.google.com/p/mock/issues/detail?id=105>`_ is subclassing mock to
1015created a `Twisted adaptor
1016<http://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html>`_.
1017Having this applied to attributes too actually causes errors.
1018
1019`Mock` (in all its flavours) uses a method called `_get_child_mock` to create
1020these "sub-mocks" for attributes and return values. You can prevent your
1021subclass being used for attributes by overriding this method. The signature is
1022that it takes arbitrary keyword arguments (`**kwargs`) which are then passed
1023onto the mock constructor:
1024
1025 >>> class Subclass(MagicMock):
1026 ... def _get_child_mock(self, **kwargs):
1027 ... return MagicMock(**kwargs)
1028 ...
1029 >>> mymock = Subclass()
1030 >>> mymock.foo
1031 <MagicMock name='mock.foo' id='...'>
1032 >>> assert isinstance(mymock, Subclass)
1033 >>> assert not isinstance(mymock.foo, Subclass)
1034 >>> assert not isinstance(mymock(), Subclass)
1035
1036.. [#] An exception to this rule are the non-callable mocks. Attributes use the
1037 callable variant because otherwise non-callable mocks couldn't have callable
1038 methods.
1039
1040
1041Mocking imports with patch.dict
Georg Brandl7fc972a2013-02-03 14:00:04 +01001042~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001043
1044One situation where mocking can be hard is where you have a local import inside
1045a function. These are harder to mock because they aren't using an object from
1046the module namespace that we can patch out.
1047
1048Generally local imports are to be avoided. They are sometimes done to prevent
1049circular dependencies, for which there is *usually* a much better way to solve
1050the problem (refactor the code) or to prevent "up front costs" by delaying the
1051import. This can also be solved in better ways than an unconditional local
1052import (store the module as a class or module attribute and only do the import
1053on first use).
1054
1055That aside there is a way to use `mock` to affect the results of an import.
1056Importing fetches an *object* from the `sys.modules` dictionary. Note that it
1057fetches an *object*, which need not be a module. Importing a module for the
1058first time results in a module object being put in `sys.modules`, so usually
1059when you import something you get a module back. This need not be the case
1060however.
1061
1062This means you can use :func:`patch.dict` to *temporarily* put a mock in place
1063in `sys.modules`. Any imports whilst this patch is active will fetch the mock.
1064When the patch is complete (the decorated function exits, the with statement
1065body is complete or `patcher.stop()` is called) then whatever was there
1066previously will be restored safely.
1067
1068Here's an example that mocks out the 'fooble' module.
1069
1070 >>> mock = Mock()
1071 >>> with patch.dict('sys.modules', {'fooble': mock}):
1072 ... import fooble
1073 ... fooble.blob()
1074 ...
1075 <Mock name='mock.blob()' id='...'>
1076 >>> assert 'fooble' not in sys.modules
1077 >>> mock.blob.assert_called_once_with()
1078
1079As you can see the `import fooble` succeeds, but on exit there is no 'fooble'
1080left in `sys.modules`.
1081
1082This also works for the `from module import name` form:
1083
1084 >>> mock = Mock()
1085 >>> with patch.dict('sys.modules', {'fooble': mock}):
1086 ... from fooble import blob
1087 ... blob.blip()
1088 ...
1089 <Mock name='mock.blob.blip()' id='...'>
1090 >>> mock.blob.blip.assert_called_once_with()
1091
1092With slightly more work you can also mock package imports:
1093
1094 >>> mock = Mock()
1095 >>> modules = {'package': mock, 'package.module': mock.module}
1096 >>> with patch.dict('sys.modules', modules):
1097 ... from package.module import fooble
1098 ... fooble()
1099 ...
1100 <Mock name='mock.module.fooble()' id='...'>
1101 >>> mock.module.fooble.assert_called_once_with()
1102
1103
1104Tracking order of calls and less verbose call assertions
Georg Brandl7fc972a2013-02-03 14:00:04 +01001105~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001106
1107The :class:`Mock` class allows you to track the *order* of method calls on
1108your mock objects through the :attr:`~Mock.method_calls` attribute. This
1109doesn't allow you to track the order of calls between separate mock objects,
1110however we can use :attr:`~Mock.mock_calls` to achieve the same effect.
1111
1112Because mocks track calls to child mocks in `mock_calls`, and accessing an
1113arbitrary attribute of a mock creates a child mock, we can create our separate
1114mocks from a parent one. Calls to those child mock will then all be recorded,
1115in order, in the `mock_calls` of the parent:
1116
1117 >>> manager = Mock()
1118 >>> mock_foo = manager.foo
1119 >>> mock_bar = manager.bar
1120
1121 >>> mock_foo.something()
1122 <Mock name='mock.foo.something()' id='...'>
1123 >>> mock_bar.other.thing()
1124 <Mock name='mock.bar.other.thing()' id='...'>
1125
1126 >>> manager.mock_calls
1127 [call.foo.something(), call.bar.other.thing()]
1128
1129We can then assert about the calls, including the order, by comparing with
1130the `mock_calls` attribute on the manager mock:
1131
1132 >>> expected_calls = [call.foo.something(), call.bar.other.thing()]
1133 >>> manager.mock_calls == expected_calls
1134 True
1135
1136If `patch` is creating, and putting in place, your mocks then you can attach
1137them to a manager mock using the :meth:`~Mock.attach_mock` method. After
1138attaching calls will be recorded in `mock_calls` of the manager.
1139
1140 >>> manager = MagicMock()
1141 >>> with patch('mymodule.Class1') as MockClass1:
1142 ... with patch('mymodule.Class2') as MockClass2:
1143 ... manager.attach_mock(MockClass1, 'MockClass1')
1144 ... manager.attach_mock(MockClass2, 'MockClass2')
1145 ... MockClass1().foo()
1146 ... MockClass2().bar()
1147 ...
1148 <MagicMock name='mock.MockClass1().foo()' id='...'>
1149 <MagicMock name='mock.MockClass2().bar()' id='...'>
1150 >>> manager.mock_calls
1151 [call.MockClass1(),
1152 call.MockClass1().foo(),
1153 call.MockClass2(),
1154 call.MockClass2().bar()]
1155
1156If many calls have been made, but you're only interested in a particular
1157sequence of them then an alternative is to use the
1158:meth:`~Mock.assert_has_calls` method. This takes a list of calls (constructed
1159with the :data:`call` object). If that sequence of calls are in
1160:attr:`~Mock.mock_calls` then the assert succeeds.
1161
1162 >>> m = MagicMock()
1163 >>> m().foo().bar().baz()
1164 <MagicMock name='mock().foo().bar().baz()' id='...'>
1165 >>> m.one().two().three()
1166 <MagicMock name='mock.one().two().three()' id='...'>
1167 >>> calls = call.one().two().three().call_list()
1168 >>> m.assert_has_calls(calls)
1169
1170Even though the chained call `m.one().two().three()` aren't the only calls that
1171have been made to the mock, the assert still succeeds.
1172
1173Sometimes a mock may have several calls made to it, and you are only interested
1174in asserting about *some* of those calls. You may not even care about the
1175order. In this case you can pass `any_order=True` to `assert_has_calls`:
1176
1177 >>> m = MagicMock()
1178 >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
1179 (...)
1180 >>> calls = [call.fifty('50'), call(1), call.seven(7)]
1181 >>> m.assert_has_calls(calls, any_order=True)
1182
1183
1184More complex argument matching
Georg Brandl7fc972a2013-02-03 14:00:04 +01001185~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foord944e02d2012-03-25 23:12:55 +01001186
1187Using the same basic concept as :data:`ANY` we can implement matchers to do more
1188complex assertions on objects used as arguments to mocks.
1189
1190Suppose we expect some object to be passed to a mock that by default
1191compares equal based on object identity (which is the Python default for user
1192defined classes). To use :meth:`~Mock.assert_called_with` we would need to pass
1193in the exact same object. If we are only interested in some of the attributes
1194of this object then we can create a matcher that will check these attributes
1195for us.
1196
1197You can see in this example how a 'standard' call to `assert_called_with` isn't
1198sufficient:
1199
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001200 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +01001201 ... def __init__(self, a, b):
1202 ... self.a, self.b = a, b
1203 ...
1204 >>> mock = Mock(return_value=None)
1205 >>> mock(Foo(1, 2))
1206 >>> mock.assert_called_with(Foo(1, 2))
1207 Traceback (most recent call last):
1208 ...
1209 AssertionError: Expected: call(<__main__.Foo object at 0x...>)
1210 Actual call: call(<__main__.Foo object at 0x...>)
1211
1212A comparison function for our `Foo` class might look something like this:
1213
1214 >>> def compare(self, other):
1215 ... if not type(self) == type(other):
1216 ... return False
1217 ... if self.a != other.a:
1218 ... return False
1219 ... if self.b != other.b:
1220 ... return False
1221 ... return True
1222 ...
1223
1224And a matcher object that can use comparison functions like this for its
1225equality operation would look something like this:
1226
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001227 >>> class Matcher:
Michael Foord944e02d2012-03-25 23:12:55 +01001228 ... def __init__(self, compare, some_obj):
1229 ... self.compare = compare
1230 ... self.some_obj = some_obj
1231 ... def __eq__(self, other):
1232 ... return self.compare(self.some_obj, other)
1233 ...
1234
1235Putting all this together:
1236
1237 >>> match_foo = Matcher(compare, Foo(1, 2))
1238 >>> mock.assert_called_with(match_foo)
1239
1240The `Matcher` is instantiated with our compare function and the `Foo` object
1241we want to compare against. In `assert_called_with` the `Matcher` equality
1242method will be called, which compares the object the mock was called with
1243against the one we created our matcher with. If they match then
1244`assert_called_with` passes, and if they don't an `AssertionError` is raised:
1245
1246 >>> match_wrong = Matcher(compare, Foo(3, 4))
1247 >>> mock.assert_called_with(match_wrong)
1248 Traceback (most recent call last):
1249 ...
1250 AssertionError: Expected: ((<Matcher object at 0x...>,), {})
1251 Called with: ((<Foo object at 0x...>,), {})
1252
1253With a bit of tweaking you could have the comparison function raise the
1254`AssertionError` directly and provide a more useful failure message.
1255
1256As of version 1.5, the Python testing library `PyHamcrest
1257<http://pypi.python.org/pypi/PyHamcrest>`_ provides similar functionality,
1258that may be useful here, in the form of its equality matcher
1259(`hamcrest.library.integration.match_equality
1260<http://packages.python.org/PyHamcrest/integration.html#hamcrest.library.integration.match_equality>`_).