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