blob: cef5405fe9568ac94170b6291ac73409c44afe9b [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
Serhiy Storchaka5665bc52013-11-17 00:12:21 +020055 self.assertNotIn('_items', mock.__dict__,
Michael Foord345266a2012-03-14 12:24:34 -070056 "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
Michael Foord28d591c2012-09-28 16:15:22 +0100466 def test_assert_called_once_with_message(self):
467 mock = Mock(name='geoffrey')
468 self.assertRaisesRegex(AssertionError,
469 r"Expected 'geoffrey' to be called once\.",
470 mock.assert_called_once_with)
471
472
Michael Foord345266a2012-03-14 12:24:34 -0700473 def test__name__(self):
474 mock = Mock()
475 self.assertRaises(AttributeError, lambda: mock.__name__)
476
477 mock.__name__ = 'foo'
478 self.assertEqual(mock.__name__, 'foo')
479
480
481 def test_spec_list_subclass(self):
482 class Sub(list):
483 pass
484 mock = Mock(spec=Sub(['foo']))
485
486 mock.append(3)
487 mock.append.assert_called_with(3)
488 self.assertRaises(AttributeError, getattr, mock, 'foo')
489
490
491 def test_spec_class(self):
492 class X(object):
493 pass
494
495 mock = Mock(spec=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200496 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700497
498 mock = Mock(spec=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200499 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700500
501 self.assertIs(mock.__class__, X)
502 self.assertEqual(Mock().__class__.__name__, 'Mock')
503
504 mock = Mock(spec_set=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200505 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700506
507 mock = Mock(spec_set=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200508 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700509
510
511 def test_setting_attribute_with_spec_set(self):
512 class X(object):
513 y = 3
514
515 mock = Mock(spec=X)
516 mock.x = 'foo'
517
518 mock = Mock(spec_set=X)
519 def set_attr():
520 mock.x = 'foo'
521
522 mock.y = 'foo'
523 self.assertRaises(AttributeError, set_attr)
524
525
526 def test_copy(self):
527 current = sys.getrecursionlimit()
528 self.addCleanup(sys.setrecursionlimit, current)
529
530 # can't use sys.maxint as this doesn't exist in Python 3
531 sys.setrecursionlimit(int(10e8))
532 # this segfaults without the fix in place
533 copy.copy(Mock())
534
535
536 def test_subclass_with_properties(self):
537 class SubClass(Mock):
538 def _get(self):
539 return 3
540 def _set(self, value):
541 raise NameError('strange error')
542 some_attribute = property(_get, _set)
543
544 s = SubClass(spec_set=SubClass)
545 self.assertEqual(s.some_attribute, 3)
546
547 def test():
548 s.some_attribute = 3
549 self.assertRaises(NameError, test)
550
551 def test():
552 s.foo = 'bar'
553 self.assertRaises(AttributeError, test)
554
555
556 def test_setting_call(self):
557 mock = Mock()
558 def __call__(self, a):
559 return self._mock_call(a)
560
561 type(mock).__call__ = __call__
562 mock('one')
563 mock.assert_called_with('one')
564
565 self.assertRaises(TypeError, mock, 'one', 'two')
566
567
568 def test_dir(self):
569 mock = Mock()
570 attrs = set(dir(mock))
571 type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
572
573 # all public attributes from the type are included
574 self.assertEqual(set(), type_attrs - attrs)
575
576 # creates these attributes
577 mock.a, mock.b
578 self.assertIn('a', dir(mock))
579 self.assertIn('b', dir(mock))
580
581 # instance attributes
582 mock.c = mock.d = None
583 self.assertIn('c', dir(mock))
584 self.assertIn('d', dir(mock))
585
586 # magic methods
587 mock.__iter__ = lambda s: iter([])
588 self.assertIn('__iter__', dir(mock))
589
590
591 def test_dir_from_spec(self):
592 mock = Mock(spec=unittest.TestCase)
593 testcase_attrs = set(dir(unittest.TestCase))
594 attrs = set(dir(mock))
595
596 # all attributes from the spec are included
597 self.assertEqual(set(), testcase_attrs - attrs)
598
599 # shadow a sys attribute
600 mock.version = 3
601 self.assertEqual(dir(mock).count('version'), 1)
602
603
604 def test_filter_dir(self):
605 patcher = patch.object(mock, 'FILTER_DIR', False)
606 patcher.start()
607 try:
608 attrs = set(dir(Mock()))
609 type_attrs = set(dir(Mock))
610
611 # ALL attributes from the type are included
612 self.assertEqual(set(), type_attrs - attrs)
613 finally:
614 patcher.stop()
615
616
617 def test_configure_mock(self):
618 mock = Mock(foo='bar')
619 self.assertEqual(mock.foo, 'bar')
620
621 mock = MagicMock(foo='bar')
622 self.assertEqual(mock.foo, 'bar')
623
624 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
625 'foo': MagicMock()}
626 mock = Mock(**kwargs)
627 self.assertRaises(KeyError, mock)
628 self.assertEqual(mock.foo.bar(), 33)
629 self.assertIsInstance(mock.foo, MagicMock)
630
631 mock = Mock()
632 mock.configure_mock(**kwargs)
633 self.assertRaises(KeyError, mock)
634 self.assertEqual(mock.foo.bar(), 33)
635 self.assertIsInstance(mock.foo, MagicMock)
636
637
638 def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
639 # needed because assertRaisesRegex doesn't work easily with newlines
640 try:
641 func(*args, **kwargs)
642 except:
643 instance = sys.exc_info()[1]
644 self.assertIsInstance(instance, exception)
645 else:
646 self.fail('Exception %r not raised' % (exception,))
647
648 msg = str(instance)
649 self.assertEqual(msg, message)
650
651
652 def test_assert_called_with_failure_message(self):
653 mock = NonCallableMock()
654
655 expected = "mock(1, '2', 3, bar='foo')"
656 message = 'Expected call: %s\nNot called'
657 self.assertRaisesWithMsg(
658 AssertionError, message % (expected,),
659 mock.assert_called_with, 1, '2', 3, bar='foo'
660 )
661
662 mock.foo(1, '2', 3, foo='foo')
663
664
665 asserters = [
666 mock.foo.assert_called_with, mock.foo.assert_called_once_with
667 ]
668 for meth in asserters:
669 actual = "foo(1, '2', 3, foo='foo')"
670 expected = "foo(1, '2', 3, bar='foo')"
671 message = 'Expected call: %s\nActual call: %s'
672 self.assertRaisesWithMsg(
673 AssertionError, message % (expected, actual),
674 meth, 1, '2', 3, bar='foo'
675 )
676
677 # just kwargs
678 for meth in asserters:
679 actual = "foo(1, '2', 3, foo='foo')"
680 expected = "foo(bar='foo')"
681 message = 'Expected call: %s\nActual call: %s'
682 self.assertRaisesWithMsg(
683 AssertionError, message % (expected, actual),
684 meth, bar='foo'
685 )
686
687 # just args
688 for meth in asserters:
689 actual = "foo(1, '2', 3, foo='foo')"
690 expected = "foo(1, 2, 3)"
691 message = 'Expected call: %s\nActual call: %s'
692 self.assertRaisesWithMsg(
693 AssertionError, message % (expected, actual),
694 meth, 1, 2, 3
695 )
696
697 # empty
698 for meth in asserters:
699 actual = "foo(1, '2', 3, foo='foo')"
700 expected = "foo()"
701 message = 'Expected call: %s\nActual call: %s'
702 self.assertRaisesWithMsg(
703 AssertionError, message % (expected, actual), meth
704 )
705
706
707 def test_mock_calls(self):
708 mock = MagicMock()
709
710 # need to do this because MagicMock.mock_calls used to just return
711 # a MagicMock which also returned a MagicMock when __eq__ was called
712 self.assertIs(mock.mock_calls == [], True)
713
714 mock = MagicMock()
715 mock()
716 expected = [('', (), {})]
717 self.assertEqual(mock.mock_calls, expected)
718
719 mock.foo()
720 expected.append(call.foo())
721 self.assertEqual(mock.mock_calls, expected)
722 # intermediate mock_calls work too
723 self.assertEqual(mock.foo.mock_calls, [('', (), {})])
724
725 mock = MagicMock()
726 mock().foo(1, 2, 3, a=4, b=5)
727 expected = [
728 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
729 ]
730 self.assertEqual(mock.mock_calls, expected)
731 self.assertEqual(mock.return_value.foo.mock_calls,
732 [('', (1, 2, 3), dict(a=4, b=5))])
733 self.assertEqual(mock.return_value.mock_calls,
734 [('foo', (1, 2, 3), dict(a=4, b=5))])
735
736 mock = MagicMock()
737 mock().foo.bar().baz()
738 expected = [
739 ('', (), {}), ('().foo.bar', (), {}),
740 ('().foo.bar().baz', (), {})
741 ]
742 self.assertEqual(mock.mock_calls, expected)
743 self.assertEqual(mock().mock_calls,
744 call.foo.bar().baz().call_list())
745
746 for kwargs in dict(), dict(name='bar'):
747 mock = MagicMock(**kwargs)
748 int(mock.foo)
749 expected = [('foo.__int__', (), {})]
750 self.assertEqual(mock.mock_calls, expected)
751
752 mock = MagicMock(**kwargs)
753 mock.a()()
754 expected = [('a', (), {}), ('a()', (), {})]
755 self.assertEqual(mock.mock_calls, expected)
756 self.assertEqual(mock.a().mock_calls, [call()])
757
758 mock = MagicMock(**kwargs)
759 mock(1)(2)(3)
760 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
761 self.assertEqual(mock().mock_calls, call(2)(3).call_list())
762 self.assertEqual(mock()().mock_calls, call(3).call_list())
763
764 mock = MagicMock(**kwargs)
765 mock(1)(2)(3).a.b.c(4)
766 self.assertEqual(mock.mock_calls,
767 call(1)(2)(3).a.b.c(4).call_list())
768 self.assertEqual(mock().mock_calls,
769 call(2)(3).a.b.c(4).call_list())
770 self.assertEqual(mock()().mock_calls,
771 call(3).a.b.c(4).call_list())
772
773 mock = MagicMock(**kwargs)
774 int(mock().foo.bar().baz())
775 last_call = ('().foo.bar().baz().__int__', (), {})
776 self.assertEqual(mock.mock_calls[-1], last_call)
777 self.assertEqual(mock().mock_calls,
778 call.foo.bar().baz().__int__().call_list())
779 self.assertEqual(mock().foo.bar().mock_calls,
780 call.baz().__int__().call_list())
781 self.assertEqual(mock().foo.bar().baz.mock_calls,
782 call().__int__().call_list())
783
784
785 def test_subclassing(self):
786 class Subclass(Mock):
787 pass
788
789 mock = Subclass()
790 self.assertIsInstance(mock.foo, Subclass)
791 self.assertIsInstance(mock(), Subclass)
792
793 class Subclass(Mock):
794 def _get_child_mock(self, **kwargs):
795 return Mock(**kwargs)
796
797 mock = Subclass()
798 self.assertNotIsInstance(mock.foo, Subclass)
799 self.assertNotIsInstance(mock(), Subclass)
800
801
802 def test_arg_lists(self):
803 mocks = [
804 Mock(),
805 MagicMock(),
806 NonCallableMock(),
807 NonCallableMagicMock()
808 ]
809
810 def assert_attrs(mock):
811 names = 'call_args_list', 'method_calls', 'mock_calls'
812 for name in names:
813 attr = getattr(mock, name)
814 self.assertIsInstance(attr, _CallList)
815 self.assertIsInstance(attr, list)
816 self.assertEqual(attr, [])
817
818 for mock in mocks:
819 assert_attrs(mock)
820
821 if callable(mock):
822 mock()
823 mock(1, 2)
824 mock(a=3)
825
826 mock.reset_mock()
827 assert_attrs(mock)
828
829 mock.foo()
830 mock.foo.bar(1, a=3)
831 mock.foo(1).bar().baz(3)
832
833 mock.reset_mock()
834 assert_attrs(mock)
835
836
837 def test_call_args_two_tuple(self):
838 mock = Mock()
839 mock(1, a=3)
840 mock(2, b=4)
841
842 self.assertEqual(len(mock.call_args), 2)
843 args, kwargs = mock.call_args
844 self.assertEqual(args, (2,))
845 self.assertEqual(kwargs, dict(b=4))
846
847 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
848 for expected, call_args in zip(expected_list, mock.call_args_list):
849 self.assertEqual(len(call_args), 2)
850 self.assertEqual(expected[0], call_args[0])
851 self.assertEqual(expected[1], call_args[1])
852
853
854 def test_side_effect_iterator(self):
855 mock = Mock(side_effect=iter([1, 2, 3]))
856 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
857 self.assertRaises(StopIteration, mock)
858
859 mock = MagicMock(side_effect=['a', 'b', 'c'])
860 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
861 self.assertRaises(StopIteration, mock)
862
863 mock = Mock(side_effect='ghi')
864 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
865 self.assertRaises(StopIteration, mock)
866
867 class Foo(object):
868 pass
869 mock = MagicMock(side_effect=Foo)
870 self.assertIsInstance(mock(), Foo)
871
872 mock = Mock(side_effect=Iter())
873 self.assertEqual([mock(), mock(), mock(), mock()],
874 ['this', 'is', 'an', 'iter'])
875 self.assertRaises(StopIteration, mock)
876
877
Michael Foord2cd48732012-04-21 15:52:11 +0100878 def test_side_effect_iterator_exceptions(self):
879 for Klass in Mock, MagicMock:
880 iterable = (ValueError, 3, KeyError, 6)
881 m = Klass(side_effect=iterable)
882 self.assertRaises(ValueError, m)
883 self.assertEqual(m(), 3)
884 self.assertRaises(KeyError, m)
885 self.assertEqual(m(), 6)
886
887
Michael Foord345266a2012-03-14 12:24:34 -0700888 def test_side_effect_setting_iterator(self):
889 mock = Mock()
890 mock.side_effect = iter([1, 2, 3])
891 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
892 self.assertRaises(StopIteration, mock)
893 side_effect = mock.side_effect
894 self.assertIsInstance(side_effect, type(iter([])))
895
896 mock.side_effect = ['a', 'b', 'c']
897 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
898 self.assertRaises(StopIteration, mock)
899 side_effect = mock.side_effect
900 self.assertIsInstance(side_effect, type(iter([])))
901
902 this_iter = Iter()
903 mock.side_effect = this_iter
904 self.assertEqual([mock(), mock(), mock(), mock()],
905 ['this', 'is', 'an', 'iter'])
906 self.assertRaises(StopIteration, mock)
907 self.assertIs(mock.side_effect, this_iter)
908
Andrew Svetlov8b2cd752013-04-07 16:42:24 +0300909 def test_side_effect_iterator_default(self):
910 mock = Mock(return_value=2)
911 mock.side_effect = iter([1, DEFAULT])
912 self.assertEqual([mock(), mock()], [1, 2])
Michael Foord345266a2012-03-14 12:24:34 -0700913
914 def test_assert_has_calls_any_order(self):
915 mock = Mock()
916 mock(1, 2)
917 mock(a=3)
918 mock(3, 4)
919 mock(b=6)
920 mock(b=6)
921
922 kalls = [
923 call(1, 2), ({'a': 3},),
924 ((3, 4),), ((), {'a': 3}),
925 ('', (1, 2)), ('', {'a': 3}),
926 ('', (1, 2), {}), ('', (), {'a': 3})
927 ]
928 for kall in kalls:
929 mock.assert_has_calls([kall], any_order=True)
930
931 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
932 self.assertRaises(
933 AssertionError, mock.assert_has_calls,
934 [kall], any_order=True
935 )
936
937 kall_lists = [
938 [call(1, 2), call(b=6)],
939 [call(3, 4), call(1, 2)],
940 [call(b=6), call(b=6)],
941 ]
942
943 for kall_list in kall_lists:
944 mock.assert_has_calls(kall_list, any_order=True)
945
946 kall_lists = [
947 [call(b=6), call(b=6), call(b=6)],
948 [call(1, 2), call(1, 2)],
949 [call(3, 4), call(1, 2), call(5, 7)],
950 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
951 ]
952 for kall_list in kall_lists:
953 self.assertRaises(
954 AssertionError, mock.assert_has_calls,
955 kall_list, any_order=True
956 )
957
958 def test_assert_has_calls(self):
959 kalls1 = [
960 call(1, 2), ({'a': 3},),
961 ((3, 4),), call(b=6),
962 ('', (1,), {'b': 6}),
963 ]
964 kalls2 = [call.foo(), call.bar(1)]
965 kalls2.extend(call.spam().baz(a=3).call_list())
966 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
967
968 mocks = []
969 for mock in Mock(), MagicMock():
970 mock(1, 2)
971 mock(a=3)
972 mock(3, 4)
973 mock(b=6)
974 mock(1, b=6)
975 mocks.append((mock, kalls1))
976
977 mock = Mock()
978 mock.foo()
979 mock.bar(1)
980 mock.spam().baz(a=3)
981 mock.bam(set(), foo={}).fish([1])
982 mocks.append((mock, kalls2))
983
984 for mock, kalls in mocks:
985 for i in range(len(kalls)):
986 for step in 1, 2, 3:
987 these = kalls[i:i+step]
988 mock.assert_has_calls(these)
989
990 if len(these) > 1:
991 self.assertRaises(
992 AssertionError,
993 mock.assert_has_calls,
994 list(reversed(these))
995 )
996
997
998 def test_assert_any_call(self):
999 mock = Mock()
1000 mock(1, 2)
1001 mock(a=3)
1002 mock(1, b=6)
1003
1004 mock.assert_any_call(1, 2)
1005 mock.assert_any_call(a=3)
1006 mock.assert_any_call(1, b=6)
1007
1008 self.assertRaises(
1009 AssertionError,
1010 mock.assert_any_call
1011 )
1012 self.assertRaises(
1013 AssertionError,
1014 mock.assert_any_call,
1015 1, 3
1016 )
1017 self.assertRaises(
1018 AssertionError,
1019 mock.assert_any_call,
1020 a=4
1021 )
1022
1023
1024 def test_mock_calls_create_autospec(self):
1025 def f(a, b):
1026 pass
1027 obj = Iter()
1028 obj.f = f
1029
1030 funcs = [
1031 create_autospec(f),
1032 create_autospec(obj).f
1033 ]
1034 for func in funcs:
1035 func(1, 2)
1036 func(3, 4)
1037
1038 self.assertEqual(
1039 func.mock_calls, [call(1, 2), call(3, 4)]
1040 )
1041
1042
1043 def test_mock_add_spec(self):
1044 class _One(object):
1045 one = 1
1046 class _Two(object):
1047 two = 2
1048 class Anything(object):
1049 one = two = three = 'four'
1050
1051 klasses = [
1052 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1053 ]
1054 for Klass in list(klasses):
1055 klasses.append(lambda K=Klass: K(spec=Anything))
1056 klasses.append(lambda K=Klass: K(spec_set=Anything))
1057
1058 for Klass in klasses:
1059 for kwargs in dict(), dict(spec_set=True):
1060 mock = Klass()
1061 #no error
1062 mock.one, mock.two, mock.three
1063
1064 for One, Two in [(_One, _Two), (['one'], ['two'])]:
1065 for kwargs in dict(), dict(spec_set=True):
1066 mock.mock_add_spec(One, **kwargs)
1067
1068 mock.one
1069 self.assertRaises(
1070 AttributeError, getattr, mock, 'two'
1071 )
1072 self.assertRaises(
1073 AttributeError, getattr, mock, 'three'
1074 )
1075 if 'spec_set' in kwargs:
1076 self.assertRaises(
1077 AttributeError, setattr, mock, 'three', None
1078 )
1079
1080 mock.mock_add_spec(Two, **kwargs)
1081 self.assertRaises(
1082 AttributeError, getattr, mock, 'one'
1083 )
1084 mock.two
1085 self.assertRaises(
1086 AttributeError, getattr, mock, 'three'
1087 )
1088 if 'spec_set' in kwargs:
1089 self.assertRaises(
1090 AttributeError, setattr, mock, 'three', None
1091 )
1092 # note that creating a mock, setting an instance attribute, and
1093 # *then* setting a spec doesn't work. Not the intended use case
1094
1095
1096 def test_mock_add_spec_magic_methods(self):
1097 for Klass in MagicMock, NonCallableMagicMock:
1098 mock = Klass()
1099 int(mock)
1100
1101 mock.mock_add_spec(object)
1102 self.assertRaises(TypeError, int, mock)
1103
1104 mock = Klass()
1105 mock['foo']
1106 mock.__int__.return_value =4
1107
1108 mock.mock_add_spec(int)
1109 self.assertEqual(int(mock), 4)
1110 self.assertRaises(TypeError, lambda: mock['foo'])
1111
1112
1113 def test_adding_child_mock(self):
1114 for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock:
1115 mock = Klass()
1116
1117 mock.foo = Mock()
1118 mock.foo()
1119
1120 self.assertEqual(mock.method_calls, [call.foo()])
1121 self.assertEqual(mock.mock_calls, [call.foo()])
1122
1123 mock = Klass()
1124 mock.bar = Mock(name='name')
1125 mock.bar()
1126 self.assertEqual(mock.method_calls, [])
1127 self.assertEqual(mock.mock_calls, [])
1128
1129 # mock with an existing _new_parent but no name
1130 mock = Klass()
1131 mock.baz = MagicMock()()
1132 mock.baz()
1133 self.assertEqual(mock.method_calls, [])
1134 self.assertEqual(mock.mock_calls, [])
1135
1136
1137 def test_adding_return_value_mock(self):
1138 for Klass in Mock, MagicMock:
1139 mock = Klass()
1140 mock.return_value = MagicMock()
1141
1142 mock()()
1143 self.assertEqual(mock.mock_calls, [call(), call()()])
1144
1145
1146 def test_manager_mock(self):
1147 class Foo(object):
1148 one = 'one'
1149 two = 'two'
1150 manager = Mock()
1151 p1 = patch.object(Foo, 'one')
1152 p2 = patch.object(Foo, 'two')
1153
1154 mock_one = p1.start()
1155 self.addCleanup(p1.stop)
1156 mock_two = p2.start()
1157 self.addCleanup(p2.stop)
1158
1159 manager.attach_mock(mock_one, 'one')
1160 manager.attach_mock(mock_two, 'two')
1161
1162 Foo.two()
1163 Foo.one()
1164
1165 self.assertEqual(manager.mock_calls, [call.two(), call.one()])
1166
1167
1168 def test_magic_methods_mock_calls(self):
1169 for Klass in Mock, MagicMock:
1170 m = Klass()
1171 m.__int__ = Mock(return_value=3)
1172 m.__float__ = MagicMock(return_value=3.0)
1173 int(m)
1174 float(m)
1175
1176 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
1177 self.assertEqual(m.method_calls, [])
1178
1179
1180 def test_attribute_deletion(self):
1181 # this behaviour isn't *useful*, but at least it's now tested...
1182 for Klass in Mock, MagicMock, NonCallableMagicMock, NonCallableMock:
1183 m = Klass()
1184 original = m.foo
1185 m.foo = 3
1186 del m.foo
1187 self.assertEqual(m.foo, original)
1188
1189 new = m.foo = Mock()
1190 del m.foo
1191 self.assertEqual(m.foo, new)
1192
1193
1194 def test_mock_parents(self):
1195 for Klass in Mock, MagicMock:
1196 m = Klass()
1197 original_repr = repr(m)
1198 m.return_value = m
1199 self.assertIs(m(), m)
1200 self.assertEqual(repr(m), original_repr)
1201
1202 m.reset_mock()
1203 self.assertIs(m(), m)
1204 self.assertEqual(repr(m), original_repr)
1205
1206 m = Klass()
1207 m.b = m.a
1208 self.assertIn("name='mock.a'", repr(m.b))
1209 self.assertIn("name='mock.a'", repr(m.a))
1210 m.reset_mock()
1211 self.assertIn("name='mock.a'", repr(m.b))
1212 self.assertIn("name='mock.a'", repr(m.a))
1213
1214 m = Klass()
1215 original_repr = repr(m)
1216 m.a = m()
1217 m.a.return_value = m
1218
1219 self.assertEqual(repr(m), original_repr)
1220 self.assertEqual(repr(m.a()), original_repr)
1221
1222
1223 def test_attach_mock(self):
1224 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1225 for Klass in classes:
1226 for Klass2 in classes:
1227 m = Klass()
1228
1229 m2 = Klass2(name='foo')
1230 m.attach_mock(m2, 'bar')
1231
1232 self.assertIs(m.bar, m2)
1233 self.assertIn("name='mock.bar'", repr(m2))
1234
1235 m.bar.baz(1)
1236 self.assertEqual(m.mock_calls, [call.bar.baz(1)])
1237 self.assertEqual(m.method_calls, [call.bar.baz(1)])
1238
1239
1240 def test_attach_mock_return_value(self):
1241 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1242 for Klass in Mock, MagicMock:
1243 for Klass2 in classes:
1244 m = Klass()
1245
1246 m2 = Klass2(name='foo')
1247 m.attach_mock(m2, 'return_value')
1248
1249 self.assertIs(m(), m2)
1250 self.assertIn("name='mock()'", repr(m2))
1251
1252 m2.foo()
1253 self.assertEqual(m.mock_calls, call().foo().call_list())
1254
1255
1256 def test_attribute_deletion(self):
1257 for mock in Mock(), MagicMock():
1258 self.assertTrue(hasattr(mock, 'm'))
1259
1260 del mock.m
1261 self.assertFalse(hasattr(mock, 'm'))
1262
1263 del mock.f
1264 self.assertFalse(hasattr(mock, 'f'))
1265 self.assertRaises(AttributeError, getattr, mock, 'f')
1266
1267
1268 def test_class_assignable(self):
1269 for mock in Mock(), MagicMock():
1270 self.assertNotIsInstance(mock, int)
1271
1272 mock.__class__ = int
1273 self.assertIsInstance(mock, int)
1274 mock.foo
1275
1276
1277
1278if __name__ == '__main__':
1279 unittest.main()