blob: 127786c587783d3f809ce2bf4f87528ce63db928 [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001import copy
2import sys
3
4import unittest
5from unittest.test.testmock.support import is_instance
6from unittest import mock
7from unittest.mock import (
8 call, DEFAULT, patch, sentinel,
9 MagicMock, Mock, NonCallableMock,
10 NonCallableMagicMock, _CallList,
11 create_autospec
12)
13
14
15class Iter(object):
16 def __init__(self):
17 self.thing = iter(['this', 'is', 'an', 'iter'])
18
19 def __iter__(self):
20 return self
21
22 def next(self):
23 return next(self.thing)
24
25 __next__ = next
26
27
Antoine Pitrou5c64df72013-02-03 00:23:58 +010028class Something(object):
29 def meth(self, a, b, c, d=None):
30 pass
31
32 @classmethod
33 def cmeth(cls, a, b, c, d=None):
34 pass
35
36 @staticmethod
37 def smeth(a, b, c, d=None):
38 pass
39
Michael Foord345266a2012-03-14 12:24:34 -070040
41class MockTest(unittest.TestCase):
42
43 def test_all(self):
44 # if __all__ is badly defined then import * will raise an error
45 # We have to exec it because you can't import * inside a method
46 # in Python 3
Michael Foord83a16852012-03-14 12:58:46 -070047 exec("from unittest.mock import *")
Michael Foord345266a2012-03-14 12:24:34 -070048
49
50 def test_constructor(self):
51 mock = Mock()
52
53 self.assertFalse(mock.called, "called not initialised correctly")
54 self.assertEqual(mock.call_count, 0,
55 "call_count not initialised correctly")
56 self.assertTrue(is_instance(mock.return_value, Mock),
57 "return_value not initialised correctly")
58
59 self.assertEqual(mock.call_args, None,
60 "call_args not initialised correctly")
61 self.assertEqual(mock.call_args_list, [],
62 "call_args_list not initialised correctly")
63 self.assertEqual(mock.method_calls, [],
64 "method_calls not initialised correctly")
65
66 # Can't use hasattr for this test as it always returns True on a mock
67 self.assertFalse('_items' in mock.__dict__,
68 "default mock should not have '_items' attribute")
69
70 self.assertIsNone(mock._mock_parent,
71 "parent not initialised correctly")
72 self.assertIsNone(mock._mock_methods,
73 "methods not initialised correctly")
74 self.assertEqual(mock._mock_children, {},
75 "children not initialised incorrectly")
76
77
78 def test_return_value_in_constructor(self):
79 mock = Mock(return_value=None)
80 self.assertIsNone(mock.return_value,
81 "return value in constructor not honoured")
82
83
84 def test_repr(self):
85 mock = Mock(name='foo')
86 self.assertIn('foo', repr(mock))
87 self.assertIn("'%s'" % id(mock), repr(mock))
88
89 mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')]
90 for mock, name in mocks:
91 self.assertIn('%s.bar' % name, repr(mock.bar))
92 self.assertIn('%s.foo()' % name, repr(mock.foo()))
93 self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing))
94 self.assertIn('%s()' % name, repr(mock()))
95 self.assertIn('%s()()' % name, repr(mock()()))
96 self.assertIn('%s()().foo.bar.baz().bing' % name,
97 repr(mock()().foo.bar.baz().bing))
98
99
100 def test_repr_with_spec(self):
101 class X(object):
102 pass
103
104 mock = Mock(spec=X)
105 self.assertIn(" spec='X' ", repr(mock))
106
107 mock = Mock(spec=X())
108 self.assertIn(" spec='X' ", repr(mock))
109
110 mock = Mock(spec_set=X)
111 self.assertIn(" spec_set='X' ", repr(mock))
112
113 mock = Mock(spec_set=X())
114 self.assertIn(" spec_set='X' ", repr(mock))
115
116 mock = Mock(spec=X, name='foo')
117 self.assertIn(" spec='X' ", repr(mock))
118 self.assertIn(" name='foo' ", repr(mock))
119
120 mock = Mock(name='foo')
121 self.assertNotIn("spec", repr(mock))
122
123 mock = Mock()
124 self.assertNotIn("spec", repr(mock))
125
126 mock = Mock(spec=['foo'])
127 self.assertNotIn("spec", repr(mock))
128
129
130 def test_side_effect(self):
131 mock = Mock()
132
133 def effect(*args, **kwargs):
134 raise SystemError('kablooie')
135
136 mock.side_effect = effect
137 self.assertRaises(SystemError, mock, 1, 2, fish=3)
138 mock.assert_called_with(1, 2, fish=3)
139
140 results = [1, 2, 3]
141 def effect():
142 return results.pop()
143 mock.side_effect = effect
144
145 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
146 "side effect not used correctly")
147
148 mock = Mock(side_effect=sentinel.SideEffect)
149 self.assertEqual(mock.side_effect, sentinel.SideEffect,
150 "side effect in constructor not used")
151
152 def side_effect():
153 return DEFAULT
154 mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
155 self.assertEqual(mock(), sentinel.RETURN)
156
157
158 @unittest.skipUnless('java' in sys.platform,
159 'This test only applies to Jython')
160 def test_java_exception_side_effect(self):
161 import java
162 mock = Mock(side_effect=java.lang.RuntimeException("Boom!"))
163
164 # can't use assertRaises with java exceptions
165 try:
166 mock(1, 2, fish=3)
167 except java.lang.RuntimeException:
168 pass
169 else:
170 self.fail('java exception not raised')
171 mock.assert_called_with(1,2, fish=3)
172
173
174 def test_reset_mock(self):
175 parent = Mock()
176 spec = ["something"]
177 mock = Mock(name="child", parent=parent, spec=spec)
178 mock(sentinel.Something, something=sentinel.SomethingElse)
179 something = mock.something
180 mock.something()
181 mock.side_effect = sentinel.SideEffect
182 return_value = mock.return_value
183 return_value()
184
185 mock.reset_mock()
186
187 self.assertEqual(mock._mock_name, "child",
188 "name incorrectly reset")
189 self.assertEqual(mock._mock_parent, parent,
190 "parent incorrectly reset")
191 self.assertEqual(mock._mock_methods, spec,
192 "methods incorrectly reset")
193
194 self.assertFalse(mock.called, "called not reset")
195 self.assertEqual(mock.call_count, 0, "call_count not reset")
196 self.assertEqual(mock.call_args, None, "call_args not reset")
197 self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
198 self.assertEqual(mock.method_calls, [],
199 "method_calls not initialised correctly: %r != %r" %
200 (mock.method_calls, []))
201 self.assertEqual(mock.mock_calls, [])
202
203 self.assertEqual(mock.side_effect, sentinel.SideEffect,
204 "side_effect incorrectly reset")
205 self.assertEqual(mock.return_value, return_value,
206 "return_value incorrectly reset")
207 self.assertFalse(return_value.called, "return value mock not reset")
208 self.assertEqual(mock._mock_children, {'something': something},
209 "children reset incorrectly")
210 self.assertEqual(mock.something, something,
211 "children incorrectly cleared")
212 self.assertFalse(mock.something.called, "child not reset")
213
214
215 def test_reset_mock_recursion(self):
216 mock = Mock()
217 mock.return_value = mock
218
219 # used to cause recursion
220 mock.reset_mock()
221
222
223 def test_call(self):
224 mock = Mock()
225 self.assertTrue(is_instance(mock.return_value, Mock),
226 "Default return_value should be a Mock")
227
228 result = mock()
229 self.assertEqual(mock(), result,
230 "different result from consecutive calls")
231 mock.reset_mock()
232
233 ret_val = mock(sentinel.Arg)
234 self.assertTrue(mock.called, "called not set")
235 self.assertEqual(mock.call_count, 1, "call_count incoreect")
236 self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
237 "call_args not set")
238 self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
239 "call_args_list not initialised correctly")
240
241 mock.return_value = sentinel.ReturnValue
242 ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
243 self.assertEqual(ret_val, sentinel.ReturnValue,
244 "incorrect return value")
245
246 self.assertEqual(mock.call_count, 2, "call_count incorrect")
247 self.assertEqual(mock.call_args,
248 ((sentinel.Arg,), {'key': sentinel.KeyArg}),
249 "call_args not set")
250 self.assertEqual(mock.call_args_list, [
251 ((sentinel.Arg,), {}),
252 ((sentinel.Arg,), {'key': sentinel.KeyArg})
253 ],
254 "call_args_list not set")
255
256
257 def test_call_args_comparison(self):
258 mock = Mock()
259 mock()
260 mock(sentinel.Arg)
261 mock(kw=sentinel.Kwarg)
262 mock(sentinel.Arg, kw=sentinel.Kwarg)
263 self.assertEqual(mock.call_args_list, [
264 (),
265 ((sentinel.Arg,),),
266 ({"kw": sentinel.Kwarg},),
267 ((sentinel.Arg,), {"kw": sentinel.Kwarg})
268 ])
269 self.assertEqual(mock.call_args,
270 ((sentinel.Arg,), {"kw": sentinel.Kwarg}))
271
272
273 def test_assert_called_with(self):
274 mock = Mock()
275 mock()
276
277 # Will raise an exception if it fails
278 mock.assert_called_with()
279 self.assertRaises(AssertionError, mock.assert_called_with, 1)
280
281 mock.reset_mock()
282 self.assertRaises(AssertionError, mock.assert_called_with)
283
284 mock(1, 2, 3, a='fish', b='nothing')
285 mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
286
287
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100288 def test_assert_called_with_function_spec(self):
289 def f(a, b, c, d=None):
290 pass
291
292 mock = Mock(spec=f)
293
294 mock(1, b=2, c=3)
295 mock.assert_called_with(1, 2, 3)
296 mock.assert_called_with(a=1, b=2, c=3)
297 self.assertRaises(AssertionError, mock.assert_called_with,
298 1, b=3, c=2)
299 # Expected call doesn't match the spec's signature
300 with self.assertRaises(AssertionError) as cm:
301 mock.assert_called_with(e=8)
302 self.assertIsInstance(cm.exception.__cause__, TypeError)
303
304
305 def test_assert_called_with_method_spec(self):
306 def _check(mock):
307 mock(1, b=2, c=3)
308 mock.assert_called_with(1, 2, 3)
309 mock.assert_called_with(a=1, b=2, c=3)
310 self.assertRaises(AssertionError, mock.assert_called_with,
311 1, b=3, c=2)
312
313 mock = Mock(spec=Something().meth)
314 _check(mock)
315 mock = Mock(spec=Something.cmeth)
316 _check(mock)
317 mock = Mock(spec=Something().cmeth)
318 _check(mock)
319 mock = Mock(spec=Something.smeth)
320 _check(mock)
321 mock = Mock(spec=Something().smeth)
322 _check(mock)
323
324
Michael Foord345266a2012-03-14 12:24:34 -0700325 def test_assert_called_once_with(self):
326 mock = Mock()
327 mock()
328
329 # Will raise an exception if it fails
330 mock.assert_called_once_with()
331
332 mock()
333 self.assertRaises(AssertionError, mock.assert_called_once_with)
334
335 mock.reset_mock()
336 self.assertRaises(AssertionError, mock.assert_called_once_with)
337
338 mock('foo', 'bar', baz=2)
339 mock.assert_called_once_with('foo', 'bar', baz=2)
340
341 mock.reset_mock()
342 mock('foo', 'bar', baz=2)
343 self.assertRaises(
344 AssertionError,
345 lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
346 )
347
348
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100349 def test_assert_called_once_with_function_spec(self):
350 def f(a, b, c, d=None):
351 pass
352
353 mock = Mock(spec=f)
354
355 mock(1, b=2, c=3)
356 mock.assert_called_once_with(1, 2, 3)
357 mock.assert_called_once_with(a=1, b=2, c=3)
358 self.assertRaises(AssertionError, mock.assert_called_once_with,
359 1, b=3, c=2)
360 # Expected call doesn't match the spec's signature
361 with self.assertRaises(AssertionError) as cm:
362 mock.assert_called_once_with(e=8)
363 self.assertIsInstance(cm.exception.__cause__, TypeError)
364 # Mock called more than once => always fails
365 mock(4, 5, 6)
366 self.assertRaises(AssertionError, mock.assert_called_once_with,
367 1, 2, 3)
368 self.assertRaises(AssertionError, mock.assert_called_once_with,
369 4, 5, 6)
370
371
Michael Foord345266a2012-03-14 12:24:34 -0700372 def test_attribute_access_returns_mocks(self):
373 mock = Mock()
374 something = mock.something
375 self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
376 self.assertEqual(mock.something, something,
377 "different attributes returned for same name")
378
379 # Usage example
380 mock = Mock()
381 mock.something.return_value = 3
382
383 self.assertEqual(mock.something(), 3, "method returned wrong value")
384 self.assertTrue(mock.something.called,
385 "method didn't record being called")
386
387
388 def test_attributes_have_name_and_parent_set(self):
389 mock = Mock()
390 something = mock.something
391
392 self.assertEqual(something._mock_name, "something",
393 "attribute name not set correctly")
394 self.assertEqual(something._mock_parent, mock,
395 "attribute parent not set correctly")
396
397
398 def test_method_calls_recorded(self):
399 mock = Mock()
400 mock.something(3, fish=None)
401 mock.something_else.something(6, cake=sentinel.Cake)
402
403 self.assertEqual(mock.something_else.method_calls,
404 [("something", (6,), {'cake': sentinel.Cake})],
405 "method calls not recorded correctly")
406 self.assertEqual(mock.method_calls, [
407 ("something", (3,), {'fish': None}),
408 ("something_else.something", (6,), {'cake': sentinel.Cake})
409 ],
410 "method calls not recorded correctly")
411
412
413 def test_method_calls_compare_easily(self):
414 mock = Mock()
415 mock.something()
416 self.assertEqual(mock.method_calls, [('something',)])
417 self.assertEqual(mock.method_calls, [('something', (), {})])
418
419 mock = Mock()
420 mock.something('different')
421 self.assertEqual(mock.method_calls, [('something', ('different',))])
422 self.assertEqual(mock.method_calls,
423 [('something', ('different',), {})])
424
425 mock = Mock()
426 mock.something(x=1)
427 self.assertEqual(mock.method_calls, [('something', {'x': 1})])
428 self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
429
430 mock = Mock()
431 mock.something('different', some='more')
432 self.assertEqual(mock.method_calls, [
433 ('something', ('different',), {'some': 'more'})
434 ])
435
436
437 def test_only_allowed_methods_exist(self):
438 for spec in ['something'], ('something',):
439 for arg in 'spec', 'spec_set':
440 mock = Mock(**{arg: spec})
441
442 # this should be allowed
443 mock.something
444 self.assertRaisesRegex(
445 AttributeError,
446 "Mock object has no attribute 'something_else'",
447 getattr, mock, 'something_else'
448 )
449
450
451 def test_from_spec(self):
452 class Something(object):
453 x = 3
454 __something__ = None
455 def y(self):
456 pass
457
458 def test_attributes(mock):
459 # should work
460 mock.x
461 mock.y
462 mock.__something__
463 self.assertRaisesRegex(
464 AttributeError,
465 "Mock object has no attribute 'z'",
466 getattr, mock, 'z'
467 )
468 self.assertRaisesRegex(
469 AttributeError,
470 "Mock object has no attribute '__foobar__'",
471 getattr, mock, '__foobar__'
472 )
473
474 test_attributes(Mock(spec=Something))
475 test_attributes(Mock(spec=Something()))
476
477
478 def test_wraps_calls(self):
479 real = Mock()
480
481 mock = Mock(wraps=real)
482 self.assertEqual(mock(), real())
483
484 real.reset_mock()
485
486 mock(1, 2, fish=3)
487 real.assert_called_with(1, 2, fish=3)
488
489
490 def test_wraps_call_with_nondefault_return_value(self):
491 real = Mock()
492
493 mock = Mock(wraps=real)
494 mock.return_value = 3
495
496 self.assertEqual(mock(), 3)
497 self.assertFalse(real.called)
498
499
500 def test_wraps_attributes(self):
501 class Real(object):
502 attribute = Mock()
503
504 real = Real()
505
506 mock = Mock(wraps=real)
507 self.assertEqual(mock.attribute(), real.attribute())
508 self.assertRaises(AttributeError, lambda: mock.fish)
509
510 self.assertNotEqual(mock.attribute, real.attribute)
511 result = mock.attribute.frog(1, 2, fish=3)
512 Real.attribute.frog.assert_called_with(1, 2, fish=3)
513 self.assertEqual(result, Real.attribute.frog())
514
515
516 def test_exceptional_side_effect(self):
517 mock = Mock(side_effect=AttributeError)
518 self.assertRaises(AttributeError, mock)
519
520 mock = Mock(side_effect=AttributeError('foo'))
521 self.assertRaises(AttributeError, mock)
522
523
524 def test_baseexceptional_side_effect(self):
525 mock = Mock(side_effect=KeyboardInterrupt)
526 self.assertRaises(KeyboardInterrupt, mock)
527
528 mock = Mock(side_effect=KeyboardInterrupt('foo'))
529 self.assertRaises(KeyboardInterrupt, mock)
530
531
532 def test_assert_called_with_message(self):
533 mock = Mock()
534 self.assertRaisesRegex(AssertionError, 'Not called',
535 mock.assert_called_with)
536
537
Michael Foord28d591c2012-09-28 16:15:22 +0100538 def test_assert_called_once_with_message(self):
539 mock = Mock(name='geoffrey')
540 self.assertRaisesRegex(AssertionError,
541 r"Expected 'geoffrey' to be called once\.",
542 mock.assert_called_once_with)
543
544
Michael Foord345266a2012-03-14 12:24:34 -0700545 def test__name__(self):
546 mock = Mock()
547 self.assertRaises(AttributeError, lambda: mock.__name__)
548
549 mock.__name__ = 'foo'
550 self.assertEqual(mock.__name__, 'foo')
551
552
553 def test_spec_list_subclass(self):
554 class Sub(list):
555 pass
556 mock = Mock(spec=Sub(['foo']))
557
558 mock.append(3)
559 mock.append.assert_called_with(3)
560 self.assertRaises(AttributeError, getattr, mock, 'foo')
561
562
563 def test_spec_class(self):
564 class X(object):
565 pass
566
567 mock = Mock(spec=X)
568 self.assertTrue(isinstance(mock, X))
569
570 mock = Mock(spec=X())
571 self.assertTrue(isinstance(mock, X))
572
573 self.assertIs(mock.__class__, X)
574 self.assertEqual(Mock().__class__.__name__, 'Mock')
575
576 mock = Mock(spec_set=X)
577 self.assertTrue(isinstance(mock, X))
578
579 mock = Mock(spec_set=X())
580 self.assertTrue(isinstance(mock, X))
581
582
583 def test_setting_attribute_with_spec_set(self):
584 class X(object):
585 y = 3
586
587 mock = Mock(spec=X)
588 mock.x = 'foo'
589
590 mock = Mock(spec_set=X)
591 def set_attr():
592 mock.x = 'foo'
593
594 mock.y = 'foo'
595 self.assertRaises(AttributeError, set_attr)
596
597
598 def test_copy(self):
599 current = sys.getrecursionlimit()
600 self.addCleanup(sys.setrecursionlimit, current)
601
602 # can't use sys.maxint as this doesn't exist in Python 3
603 sys.setrecursionlimit(int(10e8))
604 # this segfaults without the fix in place
605 copy.copy(Mock())
606
607
608 def test_subclass_with_properties(self):
609 class SubClass(Mock):
610 def _get(self):
611 return 3
612 def _set(self, value):
613 raise NameError('strange error')
614 some_attribute = property(_get, _set)
615
616 s = SubClass(spec_set=SubClass)
617 self.assertEqual(s.some_attribute, 3)
618
619 def test():
620 s.some_attribute = 3
621 self.assertRaises(NameError, test)
622
623 def test():
624 s.foo = 'bar'
625 self.assertRaises(AttributeError, test)
626
627
628 def test_setting_call(self):
629 mock = Mock()
630 def __call__(self, a):
631 return self._mock_call(a)
632
633 type(mock).__call__ = __call__
634 mock('one')
635 mock.assert_called_with('one')
636
637 self.assertRaises(TypeError, mock, 'one', 'two')
638
639
640 def test_dir(self):
641 mock = Mock()
642 attrs = set(dir(mock))
643 type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
644
645 # all public attributes from the type are included
646 self.assertEqual(set(), type_attrs - attrs)
647
648 # creates these attributes
649 mock.a, mock.b
650 self.assertIn('a', dir(mock))
651 self.assertIn('b', dir(mock))
652
653 # instance attributes
654 mock.c = mock.d = None
655 self.assertIn('c', dir(mock))
656 self.assertIn('d', dir(mock))
657
658 # magic methods
659 mock.__iter__ = lambda s: iter([])
660 self.assertIn('__iter__', dir(mock))
661
662
663 def test_dir_from_spec(self):
664 mock = Mock(spec=unittest.TestCase)
665 testcase_attrs = set(dir(unittest.TestCase))
666 attrs = set(dir(mock))
667
668 # all attributes from the spec are included
669 self.assertEqual(set(), testcase_attrs - attrs)
670
671 # shadow a sys attribute
672 mock.version = 3
673 self.assertEqual(dir(mock).count('version'), 1)
674
675
676 def test_filter_dir(self):
677 patcher = patch.object(mock, 'FILTER_DIR', False)
678 patcher.start()
679 try:
680 attrs = set(dir(Mock()))
681 type_attrs = set(dir(Mock))
682
683 # ALL attributes from the type are included
684 self.assertEqual(set(), type_attrs - attrs)
685 finally:
686 patcher.stop()
687
688
689 def test_configure_mock(self):
690 mock = Mock(foo='bar')
691 self.assertEqual(mock.foo, 'bar')
692
693 mock = MagicMock(foo='bar')
694 self.assertEqual(mock.foo, 'bar')
695
696 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
697 'foo': MagicMock()}
698 mock = Mock(**kwargs)
699 self.assertRaises(KeyError, mock)
700 self.assertEqual(mock.foo.bar(), 33)
701 self.assertIsInstance(mock.foo, MagicMock)
702
703 mock = Mock()
704 mock.configure_mock(**kwargs)
705 self.assertRaises(KeyError, mock)
706 self.assertEqual(mock.foo.bar(), 33)
707 self.assertIsInstance(mock.foo, MagicMock)
708
709
710 def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
711 # needed because assertRaisesRegex doesn't work easily with newlines
712 try:
713 func(*args, **kwargs)
714 except:
715 instance = sys.exc_info()[1]
716 self.assertIsInstance(instance, exception)
717 else:
718 self.fail('Exception %r not raised' % (exception,))
719
720 msg = str(instance)
721 self.assertEqual(msg, message)
722
723
724 def test_assert_called_with_failure_message(self):
725 mock = NonCallableMock()
726
727 expected = "mock(1, '2', 3, bar='foo')"
728 message = 'Expected call: %s\nNot called'
729 self.assertRaisesWithMsg(
730 AssertionError, message % (expected,),
731 mock.assert_called_with, 1, '2', 3, bar='foo'
732 )
733
734 mock.foo(1, '2', 3, foo='foo')
735
736
737 asserters = [
738 mock.foo.assert_called_with, mock.foo.assert_called_once_with
739 ]
740 for meth in asserters:
741 actual = "foo(1, '2', 3, foo='foo')"
742 expected = "foo(1, '2', 3, bar='foo')"
743 message = 'Expected call: %s\nActual call: %s'
744 self.assertRaisesWithMsg(
745 AssertionError, message % (expected, actual),
746 meth, 1, '2', 3, bar='foo'
747 )
748
749 # just kwargs
750 for meth in asserters:
751 actual = "foo(1, '2', 3, foo='foo')"
752 expected = "foo(bar='foo')"
753 message = 'Expected call: %s\nActual call: %s'
754 self.assertRaisesWithMsg(
755 AssertionError, message % (expected, actual),
756 meth, bar='foo'
757 )
758
759 # just args
760 for meth in asserters:
761 actual = "foo(1, '2', 3, foo='foo')"
762 expected = "foo(1, 2, 3)"
763 message = 'Expected call: %s\nActual call: %s'
764 self.assertRaisesWithMsg(
765 AssertionError, message % (expected, actual),
766 meth, 1, 2, 3
767 )
768
769 # empty
770 for meth in asserters:
771 actual = "foo(1, '2', 3, foo='foo')"
772 expected = "foo()"
773 message = 'Expected call: %s\nActual call: %s'
774 self.assertRaisesWithMsg(
775 AssertionError, message % (expected, actual), meth
776 )
777
778
779 def test_mock_calls(self):
780 mock = MagicMock()
781
782 # need to do this because MagicMock.mock_calls used to just return
783 # a MagicMock which also returned a MagicMock when __eq__ was called
784 self.assertIs(mock.mock_calls == [], True)
785
786 mock = MagicMock()
787 mock()
788 expected = [('', (), {})]
789 self.assertEqual(mock.mock_calls, expected)
790
791 mock.foo()
792 expected.append(call.foo())
793 self.assertEqual(mock.mock_calls, expected)
794 # intermediate mock_calls work too
795 self.assertEqual(mock.foo.mock_calls, [('', (), {})])
796
797 mock = MagicMock()
798 mock().foo(1, 2, 3, a=4, b=5)
799 expected = [
800 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
801 ]
802 self.assertEqual(mock.mock_calls, expected)
803 self.assertEqual(mock.return_value.foo.mock_calls,
804 [('', (1, 2, 3), dict(a=4, b=5))])
805 self.assertEqual(mock.return_value.mock_calls,
806 [('foo', (1, 2, 3), dict(a=4, b=5))])
807
808 mock = MagicMock()
809 mock().foo.bar().baz()
810 expected = [
811 ('', (), {}), ('().foo.bar', (), {}),
812 ('().foo.bar().baz', (), {})
813 ]
814 self.assertEqual(mock.mock_calls, expected)
815 self.assertEqual(mock().mock_calls,
816 call.foo.bar().baz().call_list())
817
818 for kwargs in dict(), dict(name='bar'):
819 mock = MagicMock(**kwargs)
820 int(mock.foo)
821 expected = [('foo.__int__', (), {})]
822 self.assertEqual(mock.mock_calls, expected)
823
824 mock = MagicMock(**kwargs)
825 mock.a()()
826 expected = [('a', (), {}), ('a()', (), {})]
827 self.assertEqual(mock.mock_calls, expected)
828 self.assertEqual(mock.a().mock_calls, [call()])
829
830 mock = MagicMock(**kwargs)
831 mock(1)(2)(3)
832 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
833 self.assertEqual(mock().mock_calls, call(2)(3).call_list())
834 self.assertEqual(mock()().mock_calls, call(3).call_list())
835
836 mock = MagicMock(**kwargs)
837 mock(1)(2)(3).a.b.c(4)
838 self.assertEqual(mock.mock_calls,
839 call(1)(2)(3).a.b.c(4).call_list())
840 self.assertEqual(mock().mock_calls,
841 call(2)(3).a.b.c(4).call_list())
842 self.assertEqual(mock()().mock_calls,
843 call(3).a.b.c(4).call_list())
844
845 mock = MagicMock(**kwargs)
846 int(mock().foo.bar().baz())
847 last_call = ('().foo.bar().baz().__int__', (), {})
848 self.assertEqual(mock.mock_calls[-1], last_call)
849 self.assertEqual(mock().mock_calls,
850 call.foo.bar().baz().__int__().call_list())
851 self.assertEqual(mock().foo.bar().mock_calls,
852 call.baz().__int__().call_list())
853 self.assertEqual(mock().foo.bar().baz.mock_calls,
854 call().__int__().call_list())
855
856
857 def test_subclassing(self):
858 class Subclass(Mock):
859 pass
860
861 mock = Subclass()
862 self.assertIsInstance(mock.foo, Subclass)
863 self.assertIsInstance(mock(), Subclass)
864
865 class Subclass(Mock):
866 def _get_child_mock(self, **kwargs):
867 return Mock(**kwargs)
868
869 mock = Subclass()
870 self.assertNotIsInstance(mock.foo, Subclass)
871 self.assertNotIsInstance(mock(), Subclass)
872
873
874 def test_arg_lists(self):
875 mocks = [
876 Mock(),
877 MagicMock(),
878 NonCallableMock(),
879 NonCallableMagicMock()
880 ]
881
882 def assert_attrs(mock):
883 names = 'call_args_list', 'method_calls', 'mock_calls'
884 for name in names:
885 attr = getattr(mock, name)
886 self.assertIsInstance(attr, _CallList)
887 self.assertIsInstance(attr, list)
888 self.assertEqual(attr, [])
889
890 for mock in mocks:
891 assert_attrs(mock)
892
893 if callable(mock):
894 mock()
895 mock(1, 2)
896 mock(a=3)
897
898 mock.reset_mock()
899 assert_attrs(mock)
900
901 mock.foo()
902 mock.foo.bar(1, a=3)
903 mock.foo(1).bar().baz(3)
904
905 mock.reset_mock()
906 assert_attrs(mock)
907
908
909 def test_call_args_two_tuple(self):
910 mock = Mock()
911 mock(1, a=3)
912 mock(2, b=4)
913
914 self.assertEqual(len(mock.call_args), 2)
915 args, kwargs = mock.call_args
916 self.assertEqual(args, (2,))
917 self.assertEqual(kwargs, dict(b=4))
918
919 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
920 for expected, call_args in zip(expected_list, mock.call_args_list):
921 self.assertEqual(len(call_args), 2)
922 self.assertEqual(expected[0], call_args[0])
923 self.assertEqual(expected[1], call_args[1])
924
925
926 def test_side_effect_iterator(self):
927 mock = Mock(side_effect=iter([1, 2, 3]))
928 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
929 self.assertRaises(StopIteration, mock)
930
931 mock = MagicMock(side_effect=['a', 'b', 'c'])
932 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
933 self.assertRaises(StopIteration, mock)
934
935 mock = Mock(side_effect='ghi')
936 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
937 self.assertRaises(StopIteration, mock)
938
939 class Foo(object):
940 pass
941 mock = MagicMock(side_effect=Foo)
942 self.assertIsInstance(mock(), Foo)
943
944 mock = Mock(side_effect=Iter())
945 self.assertEqual([mock(), mock(), mock(), mock()],
946 ['this', 'is', 'an', 'iter'])
947 self.assertRaises(StopIteration, mock)
948
949
Michael Foord2cd48732012-04-21 15:52:11 +0100950 def test_side_effect_iterator_exceptions(self):
951 for Klass in Mock, MagicMock:
952 iterable = (ValueError, 3, KeyError, 6)
953 m = Klass(side_effect=iterable)
954 self.assertRaises(ValueError, m)
955 self.assertEqual(m(), 3)
956 self.assertRaises(KeyError, m)
957 self.assertEqual(m(), 6)
958
959
Michael Foord345266a2012-03-14 12:24:34 -0700960 def test_side_effect_setting_iterator(self):
961 mock = Mock()
962 mock.side_effect = iter([1, 2, 3])
963 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
964 self.assertRaises(StopIteration, mock)
965 side_effect = mock.side_effect
966 self.assertIsInstance(side_effect, type(iter([])))
967
968 mock.side_effect = ['a', 'b', 'c']
969 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
970 self.assertRaises(StopIteration, mock)
971 side_effect = mock.side_effect
972 self.assertIsInstance(side_effect, type(iter([])))
973
974 this_iter = Iter()
975 mock.side_effect = this_iter
976 self.assertEqual([mock(), mock(), mock(), mock()],
977 ['this', 'is', 'an', 'iter'])
978 self.assertRaises(StopIteration, mock)
979 self.assertIs(mock.side_effect, this_iter)
980
Andrew Svetlov8b2cd752013-04-07 16:42:24 +0300981 def test_side_effect_iterator_default(self):
982 mock = Mock(return_value=2)
983 mock.side_effect = iter([1, DEFAULT])
984 self.assertEqual([mock(), mock()], [1, 2])
Michael Foord345266a2012-03-14 12:24:34 -0700985
986 def test_assert_has_calls_any_order(self):
987 mock = Mock()
988 mock(1, 2)
989 mock(a=3)
990 mock(3, 4)
991 mock(b=6)
992 mock(b=6)
993
994 kalls = [
995 call(1, 2), ({'a': 3},),
996 ((3, 4),), ((), {'a': 3}),
997 ('', (1, 2)), ('', {'a': 3}),
998 ('', (1, 2), {}), ('', (), {'a': 3})
999 ]
1000 for kall in kalls:
1001 mock.assert_has_calls([kall], any_order=True)
1002
1003 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
1004 self.assertRaises(
1005 AssertionError, mock.assert_has_calls,
1006 [kall], any_order=True
1007 )
1008
1009 kall_lists = [
1010 [call(1, 2), call(b=6)],
1011 [call(3, 4), call(1, 2)],
1012 [call(b=6), call(b=6)],
1013 ]
1014
1015 for kall_list in kall_lists:
1016 mock.assert_has_calls(kall_list, any_order=True)
1017
1018 kall_lists = [
1019 [call(b=6), call(b=6), call(b=6)],
1020 [call(1, 2), call(1, 2)],
1021 [call(3, 4), call(1, 2), call(5, 7)],
1022 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
1023 ]
1024 for kall_list in kall_lists:
1025 self.assertRaises(
1026 AssertionError, mock.assert_has_calls,
1027 kall_list, any_order=True
1028 )
1029
1030 def test_assert_has_calls(self):
1031 kalls1 = [
1032 call(1, 2), ({'a': 3},),
1033 ((3, 4),), call(b=6),
1034 ('', (1,), {'b': 6}),
1035 ]
1036 kalls2 = [call.foo(), call.bar(1)]
1037 kalls2.extend(call.spam().baz(a=3).call_list())
1038 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
1039
1040 mocks = []
1041 for mock in Mock(), MagicMock():
1042 mock(1, 2)
1043 mock(a=3)
1044 mock(3, 4)
1045 mock(b=6)
1046 mock(1, b=6)
1047 mocks.append((mock, kalls1))
1048
1049 mock = Mock()
1050 mock.foo()
1051 mock.bar(1)
1052 mock.spam().baz(a=3)
1053 mock.bam(set(), foo={}).fish([1])
1054 mocks.append((mock, kalls2))
1055
1056 for mock, kalls in mocks:
1057 for i in range(len(kalls)):
1058 for step in 1, 2, 3:
1059 these = kalls[i:i+step]
1060 mock.assert_has_calls(these)
1061
1062 if len(these) > 1:
1063 self.assertRaises(
1064 AssertionError,
1065 mock.assert_has_calls,
1066 list(reversed(these))
1067 )
1068
1069
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001070 def test_assert_has_calls_with_function_spec(self):
1071 def f(a, b, c, d=None):
1072 pass
1073
1074 mock = Mock(spec=f)
1075
1076 mock(1, b=2, c=3)
1077 mock(4, 5, c=6, d=7)
1078 mock(10, 11, c=12)
1079 calls = [
1080 ('', (1, 2, 3), {}),
1081 ('', (4, 5, 6), {'d': 7}),
1082 ((10, 11, 12), {}),
1083 ]
1084 mock.assert_has_calls(calls)
1085 mock.assert_has_calls(calls, any_order=True)
1086 mock.assert_has_calls(calls[1:])
1087 mock.assert_has_calls(calls[1:], any_order=True)
1088 mock.assert_has_calls(calls[:-1])
1089 mock.assert_has_calls(calls[:-1], any_order=True)
1090 # Reversed order
1091 calls = list(reversed(calls))
1092 with self.assertRaises(AssertionError):
1093 mock.assert_has_calls(calls)
1094 mock.assert_has_calls(calls, any_order=True)
1095 with self.assertRaises(AssertionError):
1096 mock.assert_has_calls(calls[1:])
1097 mock.assert_has_calls(calls[1:], any_order=True)
1098 with self.assertRaises(AssertionError):
1099 mock.assert_has_calls(calls[:-1])
1100 mock.assert_has_calls(calls[:-1], any_order=True)
1101
1102
Michael Foord345266a2012-03-14 12:24:34 -07001103 def test_assert_any_call(self):
1104 mock = Mock()
1105 mock(1, 2)
1106 mock(a=3)
1107 mock(1, b=6)
1108
1109 mock.assert_any_call(1, 2)
1110 mock.assert_any_call(a=3)
1111 mock.assert_any_call(1, b=6)
1112
1113 self.assertRaises(
1114 AssertionError,
1115 mock.assert_any_call
1116 )
1117 self.assertRaises(
1118 AssertionError,
1119 mock.assert_any_call,
1120 1, 3
1121 )
1122 self.assertRaises(
1123 AssertionError,
1124 mock.assert_any_call,
1125 a=4
1126 )
1127
1128
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001129 def test_assert_any_call_with_function_spec(self):
1130 def f(a, b, c, d=None):
1131 pass
1132
1133 mock = Mock(spec=f)
1134
1135 mock(1, b=2, c=3)
1136 mock(4, 5, c=6, d=7)
1137 mock.assert_any_call(1, 2, 3)
1138 mock.assert_any_call(a=1, b=2, c=3)
1139 mock.assert_any_call(4, 5, 6, 7)
1140 mock.assert_any_call(a=4, b=5, c=6, d=7)
1141 self.assertRaises(AssertionError, mock.assert_any_call,
1142 1, b=3, c=2)
1143 # Expected call doesn't match the spec's signature
1144 with self.assertRaises(AssertionError) as cm:
1145 mock.assert_any_call(e=8)
1146 self.assertIsInstance(cm.exception.__cause__, TypeError)
1147
1148
Michael Foord345266a2012-03-14 12:24:34 -07001149 def test_mock_calls_create_autospec(self):
1150 def f(a, b):
1151 pass
1152 obj = Iter()
1153 obj.f = f
1154
1155 funcs = [
1156 create_autospec(f),
1157 create_autospec(obj).f
1158 ]
1159 for func in funcs:
1160 func(1, 2)
1161 func(3, 4)
1162
1163 self.assertEqual(
1164 func.mock_calls, [call(1, 2), call(3, 4)]
1165 )
1166
1167
1168 def test_mock_add_spec(self):
1169 class _One(object):
1170 one = 1
1171 class _Two(object):
1172 two = 2
1173 class Anything(object):
1174 one = two = three = 'four'
1175
1176 klasses = [
1177 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1178 ]
1179 for Klass in list(klasses):
1180 klasses.append(lambda K=Klass: K(spec=Anything))
1181 klasses.append(lambda K=Klass: K(spec_set=Anything))
1182
1183 for Klass in klasses:
1184 for kwargs in dict(), dict(spec_set=True):
1185 mock = Klass()
1186 #no error
1187 mock.one, mock.two, mock.three
1188
1189 for One, Two in [(_One, _Two), (['one'], ['two'])]:
1190 for kwargs in dict(), dict(spec_set=True):
1191 mock.mock_add_spec(One, **kwargs)
1192
1193 mock.one
1194 self.assertRaises(
1195 AttributeError, getattr, mock, 'two'
1196 )
1197 self.assertRaises(
1198 AttributeError, getattr, mock, 'three'
1199 )
1200 if 'spec_set' in kwargs:
1201 self.assertRaises(
1202 AttributeError, setattr, mock, 'three', None
1203 )
1204
1205 mock.mock_add_spec(Two, **kwargs)
1206 self.assertRaises(
1207 AttributeError, getattr, mock, 'one'
1208 )
1209 mock.two
1210 self.assertRaises(
1211 AttributeError, getattr, mock, 'three'
1212 )
1213 if 'spec_set' in kwargs:
1214 self.assertRaises(
1215 AttributeError, setattr, mock, 'three', None
1216 )
1217 # note that creating a mock, setting an instance attribute, and
1218 # *then* setting a spec doesn't work. Not the intended use case
1219
1220
1221 def test_mock_add_spec_magic_methods(self):
1222 for Klass in MagicMock, NonCallableMagicMock:
1223 mock = Klass()
1224 int(mock)
1225
1226 mock.mock_add_spec(object)
1227 self.assertRaises(TypeError, int, mock)
1228
1229 mock = Klass()
1230 mock['foo']
1231 mock.__int__.return_value =4
1232
1233 mock.mock_add_spec(int)
1234 self.assertEqual(int(mock), 4)
1235 self.assertRaises(TypeError, lambda: mock['foo'])
1236
1237
1238 def test_adding_child_mock(self):
1239 for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock:
1240 mock = Klass()
1241
1242 mock.foo = Mock()
1243 mock.foo()
1244
1245 self.assertEqual(mock.method_calls, [call.foo()])
1246 self.assertEqual(mock.mock_calls, [call.foo()])
1247
1248 mock = Klass()
1249 mock.bar = Mock(name='name')
1250 mock.bar()
1251 self.assertEqual(mock.method_calls, [])
1252 self.assertEqual(mock.mock_calls, [])
1253
1254 # mock with an existing _new_parent but no name
1255 mock = Klass()
1256 mock.baz = MagicMock()()
1257 mock.baz()
1258 self.assertEqual(mock.method_calls, [])
1259 self.assertEqual(mock.mock_calls, [])
1260
1261
1262 def test_adding_return_value_mock(self):
1263 for Klass in Mock, MagicMock:
1264 mock = Klass()
1265 mock.return_value = MagicMock()
1266
1267 mock()()
1268 self.assertEqual(mock.mock_calls, [call(), call()()])
1269
1270
1271 def test_manager_mock(self):
1272 class Foo(object):
1273 one = 'one'
1274 two = 'two'
1275 manager = Mock()
1276 p1 = patch.object(Foo, 'one')
1277 p2 = patch.object(Foo, 'two')
1278
1279 mock_one = p1.start()
1280 self.addCleanup(p1.stop)
1281 mock_two = p2.start()
1282 self.addCleanup(p2.stop)
1283
1284 manager.attach_mock(mock_one, 'one')
1285 manager.attach_mock(mock_two, 'two')
1286
1287 Foo.two()
1288 Foo.one()
1289
1290 self.assertEqual(manager.mock_calls, [call.two(), call.one()])
1291
1292
1293 def test_magic_methods_mock_calls(self):
1294 for Klass in Mock, MagicMock:
1295 m = Klass()
1296 m.__int__ = Mock(return_value=3)
1297 m.__float__ = MagicMock(return_value=3.0)
1298 int(m)
1299 float(m)
1300
1301 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
1302 self.assertEqual(m.method_calls, [])
1303
1304
1305 def test_attribute_deletion(self):
1306 # this behaviour isn't *useful*, but at least it's now tested...
1307 for Klass in Mock, MagicMock, NonCallableMagicMock, NonCallableMock:
1308 m = Klass()
1309 original = m.foo
1310 m.foo = 3
1311 del m.foo
1312 self.assertEqual(m.foo, original)
1313
1314 new = m.foo = Mock()
1315 del m.foo
1316 self.assertEqual(m.foo, new)
1317
1318
1319 def test_mock_parents(self):
1320 for Klass in Mock, MagicMock:
1321 m = Klass()
1322 original_repr = repr(m)
1323 m.return_value = m
1324 self.assertIs(m(), m)
1325 self.assertEqual(repr(m), original_repr)
1326
1327 m.reset_mock()
1328 self.assertIs(m(), m)
1329 self.assertEqual(repr(m), original_repr)
1330
1331 m = Klass()
1332 m.b = m.a
1333 self.assertIn("name='mock.a'", repr(m.b))
1334 self.assertIn("name='mock.a'", repr(m.a))
1335 m.reset_mock()
1336 self.assertIn("name='mock.a'", repr(m.b))
1337 self.assertIn("name='mock.a'", repr(m.a))
1338
1339 m = Klass()
1340 original_repr = repr(m)
1341 m.a = m()
1342 m.a.return_value = m
1343
1344 self.assertEqual(repr(m), original_repr)
1345 self.assertEqual(repr(m.a()), original_repr)
1346
1347
1348 def test_attach_mock(self):
1349 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1350 for Klass in classes:
1351 for Klass2 in classes:
1352 m = Klass()
1353
1354 m2 = Klass2(name='foo')
1355 m.attach_mock(m2, 'bar')
1356
1357 self.assertIs(m.bar, m2)
1358 self.assertIn("name='mock.bar'", repr(m2))
1359
1360 m.bar.baz(1)
1361 self.assertEqual(m.mock_calls, [call.bar.baz(1)])
1362 self.assertEqual(m.method_calls, [call.bar.baz(1)])
1363
1364
1365 def test_attach_mock_return_value(self):
1366 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1367 for Klass in Mock, MagicMock:
1368 for Klass2 in classes:
1369 m = Klass()
1370
1371 m2 = Klass2(name='foo')
1372 m.attach_mock(m2, 'return_value')
1373
1374 self.assertIs(m(), m2)
1375 self.assertIn("name='mock()'", repr(m2))
1376
1377 m2.foo()
1378 self.assertEqual(m.mock_calls, call().foo().call_list())
1379
1380
1381 def test_attribute_deletion(self):
1382 for mock in Mock(), MagicMock():
1383 self.assertTrue(hasattr(mock, 'm'))
1384
1385 del mock.m
1386 self.assertFalse(hasattr(mock, 'm'))
1387
1388 del mock.f
1389 self.assertFalse(hasattr(mock, 'f'))
1390 self.assertRaises(AttributeError, getattr, mock, 'f')
1391
1392
1393 def test_class_assignable(self):
1394 for mock in Mock(), MagicMock():
1395 self.assertNotIsInstance(mock, int)
1396
1397 mock.__class__ = int
1398 self.assertIsInstance(mock, int)
1399 mock.foo
1400
1401
1402
1403if __name__ == '__main__':
1404 unittest.main()