Debian Codegraph @

lib-python/3/unittest/test/testmock/testmock.py

raw symbols SCIP
1 import copy
2 import re
3 import sys
4 import tempfile
5
6 from test.support import ALWAYS_EQ
7 import unittest
8 from unittest.test.testmock.support import is_instance
9 from unittest import mock
10 from unittest.mock import (
11 call, DEFAULT, patch, sentinel,
12 MagicMock, Mock, NonCallableMock,
13 NonCallableMagicMock, AsyncMock, _Call, _CallList,
14 create_autospec, InvalidSpecError
15 )
16
17
18 class Iter(object):
19 def __init__(self):
20 self.thing = iter(['this', 'is', 'an', 'iter'])
21
22 def __iter__(self):
23 return self
24
25 def next(self):
26 return next(self.thing)
27
28 __next__ = next
29
30
31 class Something(object):
32 def meth(self, a, b, c, d=None): pass
33
34 @classmethod
35 def cmeth(cls, a, b, c, d=None): pass
36
37 @staticmethod
38 def smeth(a, b, c, d=None): pass
39
40
41 class Typos():
42 autospect = None
43 auto_spec = None
44 set_spec = None
45
46
47 def something(a): pass
48
49
50 class MockTest(unittest.TestCase):
51
52 def test_all(self):
53 # if __all__ is badly defined then import * will raise an error
54 # We have to exec it because you can't import * inside a method
55 # in Python 3
56 exec("from unittest.mock import *")
57
58
59 def test_constructor(self):
60 mock = Mock()
61
62 self.assertFalse(mock.called, "called not initialised correctly")
63 self.assertEqual(mock.call_count, 0,
64 "call_count not initialised correctly")
65 self.assertTrue(is_instance(mock.return_value, Mock),
66 "return_value not initialised correctly")
67
68 self.assertEqual(mock.call_args, None,
69 "call_args not initialised correctly")
70 self.assertEqual(mock.call_args_list, [],
71 "call_args_list not initialised correctly")
72 self.assertEqual(mock.method_calls, [],
73 "method_calls not initialised correctly")
74
75 # Can't use hasattr for this test as it always returns True on a mock
76 self.assertNotIn('_items', mock.__dict__,
77 "default mock should not have '_items' attribute")
78
79 self.assertIsNone(mock._mock_parent,
80 "parent not initialised correctly")
81 self.assertIsNone(mock._mock_methods,
82 "methods not initialised correctly")
83 self.assertEqual(mock._mock_children, {},
84 "children not initialised incorrectly")
85
86
87 def test_return_value_in_constructor(self):
88 mock = Mock(return_value=None)
89 self.assertIsNone(mock.return_value,
90 "return value in constructor not honoured")
91
92
93 def test_change_return_value_via_delegate(self):
94 def f(): pass
95 mock = create_autospec(f)
96 mock.mock.return_value = 1
97 self.assertEqual(mock(), 1)
98
99
100 def test_change_side_effect_via_delegate(self):
101 def f(): pass
102 mock = create_autospec(f)
103 mock.mock.side_effect = TypeError()
104 with self.assertRaises(TypeError):
105 mock()
106
107
108 def test_repr(self):
109 mock = Mock(name='foo')
110 self.assertIn('foo', repr(mock))
111 self.assertIn("'%s'" % id(mock), repr(mock))
112
113 mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')]
114 for mock, name in mocks:
115 self.assertIn('%s.bar' % name, repr(mock.bar))
116 self.assertIn('%s.foo()' % name, repr(mock.foo()))
117 self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing))
118 self.assertIn('%s()' % name, repr(mock()))
119 self.assertIn('%s()()' % name, repr(mock()()))
120 self.assertIn('%s()().foo.bar.baz().bing' % name,
121 repr(mock()().foo.bar.baz().bing))
122
123
124 def test_repr_with_spec(self):
125 class X(object):
126 pass
127
128 mock = Mock(spec=X)
129 self.assertIn(" spec='X' ", repr(mock))
130
131 mock = Mock(spec=X())
132 self.assertIn(" spec='X' ", repr(mock))
133
134 mock = Mock(spec_set=X)
135 self.assertIn(" spec_set='X' ", repr(mock))
136
137 mock = Mock(spec_set=X())
138 self.assertIn(" spec_set='X' ", repr(mock))
139
140 mock = Mock(spec=X, name='foo')
141 self.assertIn(" spec='X' ", repr(mock))
142 self.assertIn(" name='foo' ", repr(mock))
143
144 mock = Mock(name='foo')
145 self.assertNotIn("spec", repr(mock))
146
147 mock = Mock()
148 self.assertNotIn("spec", repr(mock))
149
150 mock = Mock(spec=['foo'])
151 self.assertNotIn("spec", repr(mock))
152
153
154 def test_side_effect(self):
155 mock = Mock()
156
157 def effect(*args, **kwargs):
158 raise SystemError('kablooie')
159
160 mock.side_effect = effect
161 self.assertRaises(SystemError, mock, 1, 2, fish=3)
162 mock.assert_called_with(1, 2, fish=3)
163
164 results = [1, 2, 3]
165 def effect():
166 return results.pop()
167 mock.side_effect = effect
168
169 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
170 "side effect not used correctly")
171
172 mock = Mock(side_effect=sentinel.SideEffect)
173 self.assertEqual(mock.side_effect, sentinel.SideEffect,
174 "side effect in constructor not used")
175
176 def side_effect():
177 return DEFAULT
178 mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
179 self.assertEqual(mock(), sentinel.RETURN)
180
181 def test_autospec_side_effect(self):
182 # Test for issue17826
183 results = [1, 2, 3]
184 def effect():
185 return results.pop()
186 def f(): pass
187
188 mock = create_autospec(f)
189 mock.side_effect = [1, 2, 3]
190 self.assertEqual([mock(), mock(), mock()], [1, 2, 3],
191 "side effect not used correctly in create_autospec")
192 # Test where side effect is a callable
193 results = [1, 2, 3]
194 mock = create_autospec(f)
195 mock.side_effect = effect
196 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
197 "callable side effect not used correctly")
198
199 def test_autospec_side_effect_exception(self):
200 # Test for issue 23661
201 def f(): pass
202
203 mock = create_autospec(f)
204 mock.side_effect = ValueError('Bazinga!')
205 self.assertRaisesRegex(ValueError, 'Bazinga!', mock)
206
207
208 def test_autospec_mock(self):
209 class A(object):
210 class B(object):
211 C = None
212
213 with mock.patch.object(A, 'B'):
214 with self.assertRaisesRegex(InvalidSpecError,
215 "Cannot autospec attr 'B' from target <MagicMock spec='A'"):
216 create_autospec(A).B
217 with self.assertRaisesRegex(InvalidSpecError,
218 "Cannot autospec attr 'B' from target 'A'"):
219 mock.patch.object(A, 'B', autospec=True).start()
220 with self.assertRaisesRegex(InvalidSpecError,
221 "Cannot autospec attr 'C' as the patch target "):
222 mock.patch.object(A.B, 'C', autospec=True).start()
223 with self.assertRaisesRegex(InvalidSpecError,
224 "Cannot spec attr 'B' as the spec "):
225 mock.patch.object(A, 'B', spec=A.B).start()
226 with self.assertRaisesRegex(InvalidSpecError,
227 "Cannot spec attr 'B' as the spec_set "):
228 mock.patch.object(A, 'B', spec_set=A.B).start()
229 with self.assertRaisesRegex(InvalidSpecError,
230 "Cannot spec attr 'B' as the spec_set "):
231 mock.patch.object(A, 'B', spec_set=A.B).start()
232 with self.assertRaisesRegex(InvalidSpecError, "Cannot spec a Mock object."):
233 mock.Mock(A.B)
234 with mock.patch('builtins.open', mock.mock_open()):
235 mock.mock_open() # should still be valid with open() mocked
236
237 def test_create_autospec_wraps_class(self):
238 """Autospec a class with wraps & test if the call is passed to the
239 wrapped object."""
240 result = "real result"
241
242 class Result:
243 def get_result(self):
244 return result
245 class_mock = create_autospec(spec=Result, wraps=Result)
246 # Have to reassign the return_value to DEFAULT to return the real
247 # result (actual instance of "Result") when the mock is called.
248 class_mock.return_value = mock.DEFAULT
249 self.assertEqual(class_mock().get_result(), result)
250 # Autospec should also wrap child attributes of parent.
251 self.assertEqual(class_mock.get_result._mock_wraps, Result.get_result)
252
253 def test_create_autospec_instance_wraps_class(self):
254 """Autospec a class instance with wraps & test if the call is passed
255 to the wrapped object."""
256 result = "real result"
257
258 class Result:
259 @staticmethod
260 def get_result():
261 """This is a static method because when the mocked instance of
262 'Result' will call this method, it won't be able to consume
263 'self' argument."""
264 return result
265 instance_mock = create_autospec(spec=Result, instance=True, wraps=Result)
266 # Have to reassign the return_value to DEFAULT to return the real
267 # result from "Result.get_result" when the mocked instance of "Result"
268 # calls "get_result".
269 instance_mock.get_result.return_value = mock.DEFAULT
270 self.assertEqual(instance_mock.get_result(), result)
271 # Autospec should also wrap child attributes of the instance.
272 self.assertEqual(instance_mock.get_result._mock_wraps, Result.get_result)
273
274 def test_create_autospec_wraps_function_type(self):
275 """Autospec a function or a method with wraps & test if the call is
276 passed to the wrapped object."""
277 result = "real result"
278
279 class Result:
280 def get_result(self):
281 return result
282 func_mock = create_autospec(spec=Result.get_result, wraps=Result.get_result)
283 self.assertEqual(func_mock(Result()), result)
284
285 def test_explicit_return_value_even_if_mock_wraps_object(self):
286 """If the mock has an explicit return_value set then calls are not
287 passed to the wrapped object and the return_value is returned instead.
288 """
289 def my_func():
290 return None
291 func_mock = create_autospec(spec=my_func, wraps=my_func)
292 return_value = "explicit return value"
293 func_mock.return_value = return_value
294 self.assertEqual(func_mock(), return_value)
295
296 def test_reset_mock(self):
297 parent = Mock()
298 spec = ["something"]
299 mock = Mock(name="child", parent=parent, spec=spec)
300 mock(sentinel.Something, something=sentinel.SomethingElse)
301 something = mock.something
302 mock.something()
303 mock.side_effect = sentinel.SideEffect
304 return_value = mock.return_value
305 return_value()
306
307 mock.reset_mock()
308
309 self.assertEqual(mock._mock_name, "child",
310 "name incorrectly reset")
311 self.assertEqual(mock._mock_parent, parent,
312 "parent incorrectly reset")
313 self.assertEqual(mock._mock_methods, spec,
314 "methods incorrectly reset")
315
316 self.assertFalse(mock.called, "called not reset")
317 self.assertEqual(mock.call_count, 0, "call_count not reset")
318 self.assertEqual(mock.call_args, None, "call_args not reset")
319 self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
320 self.assertEqual(mock.method_calls, [],
321 "method_calls not initialised correctly: %r != %r" %
322 (mock.method_calls, []))
323 self.assertEqual(mock.mock_calls, [])
324
325 self.assertEqual(mock.side_effect, sentinel.SideEffect,
326 "side_effect incorrectly reset")
327 self.assertEqual(mock.return_value, return_value,
328 "return_value incorrectly reset")
329 self.assertFalse(return_value.called, "return value mock not reset")
330 self.assertEqual(mock._mock_children, {'something': something},
331 "children reset incorrectly")
332 self.assertEqual(mock.something, something,
333 "children incorrectly cleared")
334 self.assertFalse(mock.something.called, "child not reset")
335
336
337 def test_reset_mock_recursion(self):
338 mock = Mock()
339 mock.return_value = mock
340
341 # used to cause recursion
342 mock.reset_mock()
343
344 def test_reset_mock_on_mock_open_issue_18622(self):
345 a = mock.mock_open()
346 a.reset_mock()
347
348 def test_call(self):
349 mock = Mock()
350 self.assertTrue(is_instance(mock.return_value, Mock),
351 "Default return_value should be a Mock")
352
353 result = mock()
354 self.assertEqual(mock(), result,
355 "different result from consecutive calls")
356 mock.reset_mock()
357
358 ret_val = mock(sentinel.Arg)
359 self.assertTrue(mock.called, "called not set")
360 self.assertEqual(mock.call_count, 1, "call_count incorrect")
361 self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
362 "call_args not set")
363 self.assertEqual(mock.call_args.args, (sentinel.Arg,),
364 "call_args not set")
365 self.assertEqual(mock.call_args.kwargs, {},
366 "call_args not set")
367 self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
368 "call_args_list not initialised correctly")
369
370 mock.return_value = sentinel.ReturnValue
371 ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
372 self.assertEqual(ret_val, sentinel.ReturnValue,
373 "incorrect return value")
374
375 self.assertEqual(mock.call_count, 2, "call_count incorrect")
376 self.assertEqual(mock.call_args,
377 ((sentinel.Arg,), {'key': sentinel.KeyArg}),
378 "call_args not set")
379 self.assertEqual(mock.call_args_list, [
380 ((sentinel.Arg,), {}),
381 ((sentinel.Arg,), {'key': sentinel.KeyArg})
382 ],
383 "call_args_list not set")
384
385
386 def test_call_args_comparison(self):
387 mock = Mock()
388 mock()
389 mock(sentinel.Arg)
390 mock(kw=sentinel.Kwarg)
391 mock(sentinel.Arg, kw=sentinel.Kwarg)
392 self.assertEqual(mock.call_args_list, [
393 (),
394 ((sentinel.Arg,),),
395 ({"kw": sentinel.Kwarg},),
396 ((sentinel.Arg,), {"kw": sentinel.Kwarg})
397 ])
398 self.assertEqual(mock.call_args,
399 ((sentinel.Arg,), {"kw": sentinel.Kwarg}))
400 self.assertEqual(mock.call_args.args, (sentinel.Arg,))
401 self.assertEqual(mock.call_args.kwargs, {"kw": sentinel.Kwarg})
402
403 # Comparing call_args to a long sequence should not raise
404 # an exception. See issue 24857.
405 self.assertFalse(mock.call_args == "a long sequence")
406
407
408 def test_calls_equal_with_any(self):
409 # Check that equality and non-equality is consistent even when
410 # comparing with mock.ANY
411 mm = mock.MagicMock()
412 self.assertTrue(mm == mm)
413 self.assertFalse(mm != mm)
414 self.assertFalse(mm == mock.MagicMock())
415 self.assertTrue(mm != mock.MagicMock())
416 self.assertTrue(mm == mock.ANY)
417 self.assertFalse(mm != mock.ANY)
418 self.assertTrue(mock.ANY == mm)
419 self.assertFalse(mock.ANY != mm)
420 self.assertTrue(mm == ALWAYS_EQ)
421 self.assertFalse(mm != ALWAYS_EQ)
422
423 call1 = mock.call(mock.MagicMock())
424 call2 = mock.call(mock.ANY)
425 self.assertTrue(call1 == call2)
426 self.assertFalse(call1 != call2)
427 self.assertTrue(call2 == call1)
428 self.assertFalse(call2 != call1)
429
430 self.assertTrue(call1 == ALWAYS_EQ)
431 self.assertFalse(call1 != ALWAYS_EQ)
432 self.assertFalse(call1 == 1)
433 self.assertTrue(call1 != 1)
434
435
436 def test_assert_called_with(self):
437 mock = Mock()
438 mock()
439
440 # Will raise an exception if it fails
441 mock.assert_called_with()
442 self.assertRaises(AssertionError, mock.assert_called_with, 1)
443
444 mock.reset_mock()
445 self.assertRaises(AssertionError, mock.assert_called_with)
446
447 mock(1, 2, 3, a='fish', b='nothing')
448 mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
449
450
451 def test_assert_called_with_any(self):
452 m = MagicMock()
453 m(MagicMock())
454 m.assert_called_with(mock.ANY)
455
456
457 def test_assert_called_with_function_spec(self):
458 def f(a, b, c, d=None): pass
459
460 mock = Mock(spec=f)
461
462 mock(1, b=2, c=3)
463 mock.assert_called_with(1, 2, 3)
464 mock.assert_called_with(a=1, b=2, c=3)
465 self.assertRaises(AssertionError, mock.assert_called_with,
466 1, b=3, c=2)
467 # Expected call doesn't match the spec's signature
468 with self.assertRaises(AssertionError) as cm:
469 mock.assert_called_with(e=8)
470 self.assertIsInstance(cm.exception.__cause__, TypeError)
471
472
473 def test_assert_called_with_method_spec(self):
474 def _check(mock):
475 mock(1, b=2, c=3)
476 mock.assert_called_with(1, 2, 3)
477 mock.assert_called_with(a=1, b=2, c=3)
478 self.assertRaises(AssertionError, mock.assert_called_with,
479 1, b=3, c=2)
480
481 mock = Mock(spec=Something().meth)
482 _check(mock)
483 mock = Mock(spec=Something.cmeth)
484 _check(mock)
485 mock = Mock(spec=Something().cmeth)
486 _check(mock)
487 mock = Mock(spec=Something.smeth)
488 _check(mock)
489 mock = Mock(spec=Something().smeth)
490 _check(mock)
491
492
493 def test_assert_called_exception_message(self):
494 msg = "Expected '{0}' to have been called"
495 with self.assertRaisesRegex(AssertionError, msg.format('mock')):
496 Mock().assert_called()
497 with self.assertRaisesRegex(AssertionError, msg.format('test_name')):
498 Mock(name="test_name").assert_called()
499
500
501 def test_assert_called_once_with(self):
502 mock = Mock()
503 mock()
504
505 # Will raise an exception if it fails
506 mock.assert_called_once_with()
507
508 mock()
509 self.assertRaises(AssertionError, mock.assert_called_once_with)
510
511 mock.reset_mock()
512 self.assertRaises(AssertionError, mock.assert_called_once_with)
513
514 mock('foo', 'bar', baz=2)
515 mock.assert_called_once_with('foo', 'bar', baz=2)
516
517 mock.reset_mock()
518 mock('foo', 'bar', baz=2)
519 self.assertRaises(
520 AssertionError,
521 lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
522 )
523
524 def test_assert_called_once_with_call_list(self):
525 m = Mock()
526 m(1)
527 m(2)
528 self.assertRaisesRegex(AssertionError,
529 re.escape("Calls: [call(1), call(2)]"),
530 lambda: m.assert_called_once_with(2))
531
532
533 def test_assert_called_once_with_function_spec(self):
534 def f(a, b, c, d=None): pass
535
536 mock = Mock(spec=f)
537
538 mock(1, b=2, c=3)
539 mock.assert_called_once_with(1, 2, 3)
540 mock.assert_called_once_with(a=1, b=2, c=3)
541 self.assertRaises(AssertionError, mock.assert_called_once_with,
542 1, b=3, c=2)
543 # Expected call doesn't match the spec's signature
544 with self.assertRaises(AssertionError) as cm:
545 mock.assert_called_once_with(e=8)
546 self.assertIsInstance(cm.exception.__cause__, TypeError)
547 # Mock called more than once => always fails
548 mock(4, 5, 6)
549 self.assertRaises(AssertionError, mock.assert_called_once_with,
550 1, 2, 3)
551 self.assertRaises(AssertionError, mock.assert_called_once_with,
552 4, 5, 6)
553
554
555 def test_attribute_access_returns_mocks(self):
556 mock = Mock()
557 something = mock.something
558 self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
559 self.assertEqual(mock.something, something,
560 "different attributes returned for same name")
561
562 # Usage example
563 mock = Mock()
564 mock.something.return_value = 3
565
566 self.assertEqual(mock.something(), 3, "method returned wrong value")
567 self.assertTrue(mock.something.called,
568 "method didn't record being called")
569
570
571 def test_attributes_have_name_and_parent_set(self):
572 mock = Mock()
573 something = mock.something
574
575 self.assertEqual(something._mock_name, "something",
576 "attribute name not set correctly")
577 self.assertEqual(something._mock_parent, mock,
578 "attribute parent not set correctly")
579
580
581 def test_method_calls_recorded(self):
582 mock = Mock()
583 mock.something(3, fish=None)
584 mock.something_else.something(6, cake=sentinel.Cake)
585
586 self.assertEqual(mock.something_else.method_calls,
587 [("something", (6,), {'cake': sentinel.Cake})],
588 "method calls not recorded correctly")
589 self.assertEqual(mock.method_calls, [
590 ("something", (3,), {'fish': None}),
591 ("something_else.something", (6,), {'cake': sentinel.Cake})
592 ],
593 "method calls not recorded correctly")
594
595
596 def test_method_calls_compare_easily(self):
597 mock = Mock()
598 mock.something()
599 self.assertEqual(mock.method_calls, [('something',)])
600 self.assertEqual(mock.method_calls, [('something', (), {})])
601
602 mock = Mock()
603 mock.something('different')
604 self.assertEqual(mock.method_calls, [('something', ('different',))])
605 self.assertEqual(mock.method_calls,
606 [('something', ('different',), {})])
607
608 mock = Mock()
609 mock.something(x=1)
610 self.assertEqual(mock.method_calls, [('something', {'x': 1})])
611 self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
612
613 mock = Mock()
614 mock.something('different', some='more')
615 self.assertEqual(mock.method_calls, [
616 ('something', ('different',), {'some': 'more'})
617 ])
618
619
620 def test_only_allowed_methods_exist(self):
621 for spec in ['something'], ('something',):
622 for arg in 'spec', 'spec_set':
623 mock = Mock(**{arg: spec})
624
625 # this should be allowed
626 mock.something
627 self.assertRaisesRegex(
628 AttributeError,
629 "Mock object has no attribute 'something_else'",
630 getattr, mock, 'something_else'
631 )
632
633
634 def test_from_spec(self):
635 class Something(object):
636 x = 3
637 __something__ = None
638 def y(self): pass
639
640 def test_attributes(mock):
641 # should work
642 mock.x
643 mock.y
644 mock.__something__
645 self.assertRaisesRegex(
646 AttributeError,
647 "Mock object has no attribute 'z'",
648 getattr, mock, 'z'
649 )
650 self.assertRaisesRegex(
651 AttributeError,
652 "Mock object has no attribute '__foobar__'",
653 getattr, mock, '__foobar__'
654 )
655
656 test_attributes(Mock(spec=Something))
657 test_attributes(Mock(spec=Something()))
658
659
660 def test_wraps_calls(self):
661 real = Mock()
662
663 mock = Mock(wraps=real)
664 # If "Mock" wraps an object, just accessing its
665 # "return_value" ("NonCallableMock.__get_return_value") should not
666 # trigger its descriptor ("NonCallableMock.__set_return_value") so
667 # the default "return_value" should always be "sentinel.DEFAULT".
668 self.assertEqual(mock.return_value, DEFAULT)
669 # It will not be "sentinel.DEFAULT" if the mock is not wrapping any
670 # object.
671 self.assertNotEqual(real.return_value, DEFAULT)
672 self.assertEqual(mock(), real())
673
674 real.reset_mock()
675
676 mock(1, 2, fish=3)
677 real.assert_called_with(1, 2, fish=3)
678
679
680 def test_wraps_prevents_automatic_creation_of_mocks(self):
681 class Real(object):
682 pass
683
684 real = Real()
685 mock = Mock(wraps=real)
686
687 self.assertRaises(AttributeError, lambda: mock.new_attr())
688
689
690 def test_wraps_call_with_nondefault_return_value(self):
691 real = Mock()
692
693 mock = Mock(wraps=real)
694 mock.return_value = 3
695
696 self.assertEqual(mock(), 3)
697 self.assertFalse(real.called)
698
699
700 def test_wraps_attributes(self):
701 class Real(object):
702 attribute = Mock()
703
704 real = Real()
705
706 mock = Mock(wraps=real)
707 self.assertEqual(mock.attribute(), real.attribute())
708 self.assertRaises(AttributeError, lambda: mock.fish)
709
710 self.assertNotEqual(mock.attribute, real.attribute)
711 result = mock.attribute.frog(1, 2, fish=3)
712 Real.attribute.frog.assert_called_with(1, 2, fish=3)
713 self.assertEqual(result, Real.attribute.frog())
714
715
716 def test_customize_wrapped_object_with_side_effect_iterable_with_default(self):
717 class Real(object):
718 def method(self):
719 return sentinel.ORIGINAL_VALUE
720
721 real = Real()
722 mock = Mock(wraps=real)
723 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
724
725 self.assertEqual(mock.method(), sentinel.VALUE1)
726 self.assertEqual(mock.method(), sentinel.ORIGINAL_VALUE)
727 self.assertRaises(StopIteration, mock.method)
728
729
730 def test_customize_wrapped_object_with_side_effect_iterable(self):
731 class Real(object):
732 def method(self): pass
733
734 real = Real()
735 mock = Mock(wraps=real)
736 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
737
738 self.assertEqual(mock.method(), sentinel.VALUE1)
739 self.assertEqual(mock.method(), sentinel.VALUE2)
740 self.assertRaises(StopIteration, mock.method)
741
742
743 def test_customize_wrapped_object_with_side_effect_exception(self):
744 class Real(object):
745 def method(self): pass
746
747 real = Real()
748 mock = Mock(wraps=real)
749 mock.method.side_effect = RuntimeError
750
751 self.assertRaises(RuntimeError, mock.method)
752
753
754 def test_customize_wrapped_object_with_side_effect_function(self):
755 class Real(object):
756 def method(self): pass
757 def side_effect():
758 return sentinel.VALUE
759
760 real = Real()
761 mock = Mock(wraps=real)
762 mock.method.side_effect = side_effect
763
764 self.assertEqual(mock.method(), sentinel.VALUE)
765
766
767 def test_customize_wrapped_object_with_return_value(self):
768 class Real(object):
769 def method(self): pass
770
771 real = Real()
772 mock = Mock(wraps=real)
773 mock.method.return_value = sentinel.VALUE
774
775 self.assertEqual(mock.method(), sentinel.VALUE)
776
777
778 def test_customize_wrapped_object_with_return_value_and_side_effect(self):
779 # side_effect should always take precedence over return_value.
780 class Real(object):
781 def method(self): pass
782
783 real = Real()
784 mock = Mock(wraps=real)
785 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
786 mock.method.return_value = sentinel.WRONG_VALUE
787
788 self.assertEqual(mock.method(), sentinel.VALUE1)
789 self.assertEqual(mock.method(), sentinel.VALUE2)
790 self.assertRaises(StopIteration, mock.method)
791
792
793 def test_customize_wrapped_object_with_return_value_and_side_effect2(self):
794 # side_effect can return DEFAULT to default to return_value
795 class Real(object):
796 def method(self): pass
797
798 real = Real()
799 mock = Mock(wraps=real)
800 mock.method.side_effect = lambda: DEFAULT
801 mock.method.return_value = sentinel.VALUE
802
803 self.assertEqual(mock.method(), sentinel.VALUE)
804
805
806 def test_customize_wrapped_object_with_return_value_and_side_effect_default(self):
807 class Real(object):
808 def method(self): pass
809
810 real = Real()
811 mock = Mock(wraps=real)
812 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
813 mock.method.return_value = sentinel.RETURN
814
815 self.assertEqual(mock.method(), sentinel.VALUE1)
816 self.assertEqual(mock.method(), sentinel.RETURN)
817 self.assertRaises(StopIteration, mock.method)
818
819
820 def test_magic_method_wraps_dict(self):
821 # bpo-25597: MagicMock with wrap doesn't call wrapped object's
822 # method for magic methods with default values.
823 data = {'foo': 'bar'}
824
825 wrapped_dict = MagicMock(wraps=data)
826 self.assertEqual(wrapped_dict.get('foo'), 'bar')
827 # Accessing key gives a MagicMock
828 self.assertIsInstance(wrapped_dict['foo'], MagicMock)
829 # __contains__ method has a default value of False
830 self.assertFalse('foo' in wrapped_dict)
831
832 # return_value is non-sentinel and takes precedence over wrapped value.
833 wrapped_dict.get.return_value = 'return_value'
834 self.assertEqual(wrapped_dict.get('foo'), 'return_value')
835
836 # return_value is sentinel and hence wrapped value is returned.
837 wrapped_dict.get.return_value = sentinel.DEFAULT
838 self.assertEqual(wrapped_dict.get('foo'), 'bar')
839
840 self.assertEqual(wrapped_dict.get('baz'), None)
841 self.assertIsInstance(wrapped_dict['baz'], MagicMock)
842 self.assertFalse('bar' in wrapped_dict)
843
844 data['baz'] = 'spam'
845 self.assertEqual(wrapped_dict.get('baz'), 'spam')
846 self.assertIsInstance(wrapped_dict['baz'], MagicMock)
847 self.assertFalse('bar' in wrapped_dict)
848
849 del data['baz']
850 self.assertEqual(wrapped_dict.get('baz'), None)
851
852
853 def test_magic_method_wraps_class(self):
854
855 class Foo:
856
857 def __getitem__(self, index):
858 return index
859
860 def __custom_method__(self):
861 return "foo"
862
863
864 klass = MagicMock(wraps=Foo)
865 obj = klass()
866 self.assertEqual(obj.__getitem__(2), 2)
867 self.assertEqual(obj[2], 2)
868 self.assertEqual(obj.__custom_method__(), "foo")
869
870
871 def test_exceptional_side_effect(self):
872 mock = Mock(side_effect=AttributeError)
873 self.assertRaises(AttributeError, mock)
874
875 mock = Mock(side_effect=AttributeError('foo'))
876 self.assertRaises(AttributeError, mock)
877
878
879 def test_baseexceptional_side_effect(self):
880 mock = Mock(side_effect=KeyboardInterrupt)
881 self.assertRaises(KeyboardInterrupt, mock)
882
883 mock = Mock(side_effect=KeyboardInterrupt('foo'))
884 self.assertRaises(KeyboardInterrupt, mock)
885
886
887 def test_assert_called_with_message(self):
888 mock = Mock()
889 self.assertRaisesRegex(AssertionError, 'not called',
890 mock.assert_called_with)
891
892
893 def test_assert_called_once_with_message(self):
894 mock = Mock(name='geoffrey')
895 self.assertRaisesRegex(AssertionError,
896 r"Expected 'geoffrey' to be called once\.",
897 mock.assert_called_once_with)
898
899
900 def test__name__(self):
901 mock = Mock()
902 self.assertRaises(AttributeError, lambda: mock.__name__)
903
904 mock.__name__ = 'foo'
905 self.assertEqual(mock.__name__, 'foo')
906
907
908 def test_spec_list_subclass(self):
909 class Sub(list):
910 pass
911 mock = Mock(spec=Sub(['foo']))
912
913 mock.append(3)
914 mock.append.assert_called_with(3)
915 self.assertRaises(AttributeError, getattr, mock, 'foo')
916
917
918 def test_spec_class(self):
919 class X(object):
920 pass
921
922 mock = Mock(spec=X)
923 self.assertIsInstance(mock, X)
924
925 mock = Mock(spec=X())
926 self.assertIsInstance(mock, X)
927
928 self.assertIs(mock.__class__, X)
929 self.assertEqual(Mock().__class__.__name__, 'Mock')
930
931 mock = Mock(spec_set=X)
932 self.assertIsInstance(mock, X)
933
934 mock = Mock(spec_set=X())
935 self.assertIsInstance(mock, X)
936
937
938 def test_spec_class_no_object_base(self):
939 class X:
940 pass
941
942 mock = Mock(spec=X)
943 self.assertIsInstance(mock, X)
944
945 mock = Mock(spec=X())
946 self.assertIsInstance(mock, X)
947
948 self.assertIs(mock.__class__, X)
949 self.assertEqual(Mock().__class__.__name__, 'Mock')
950
951 mock = Mock(spec_set=X)
952 self.assertIsInstance(mock, X)
953
954 mock = Mock(spec_set=X())
955 self.assertIsInstance(mock, X)
956
957
958 def test_setting_attribute_with_spec_set(self):
959 class X(object):
960 y = 3
961
962 mock = Mock(spec=X)
963 mock.x = 'foo'
964
965 mock = Mock(spec_set=X)
966 def set_attr():
967 mock.x = 'foo'
968
969 mock.y = 'foo'
970 self.assertRaises(AttributeError, set_attr)
971
972
973 def test_copy(self):
974 current = sys.getrecursionlimit()
975 self.addCleanup(sys.setrecursionlimit, current)
976
977 # can't use sys.maxint as this doesn't exist in Python 3
978 sys.setrecursionlimit(int(10e8))
979 # this segfaults without the fix in place
980 copy.copy(Mock())
981
982
983 def test_subclass_with_properties(self):
984 class SubClass(Mock):
985 def _get(self):
986 return 3
987 def _set(self, value):
988 raise NameError('strange error')
989 some_attribute = property(_get, _set)
990
991 s = SubClass(spec_set=SubClass)
992 self.assertEqual(s.some_attribute, 3)
993
994 def test():
995 s.some_attribute = 3
996 self.assertRaises(NameError, test)
997
998 def test():
999 s.foo = 'bar'
1000 self.assertRaises(AttributeError, test)
1001
1002
1003 def test_setting_call(self):
1004 mock = Mock()
1005 def __call__(self, a):
1006 self._increment_mock_call(a)
1007 return self._mock_call(a)
1008
1009 type(mock).__call__ = __call__
1010 mock('one')
1011 mock.assert_called_with('one')
1012
1013 self.assertRaises(TypeError, mock, 'one', 'two')
1014
1015
1016 def test_dir(self):
1017 mock = Mock()
1018 attrs = set(dir(mock))
1019 type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
1020
1021 # all public attributes from the type are included
1022 self.assertEqual(set(), type_attrs - attrs)
1023
1024 # creates these attributes
1025 mock.a, mock.b
1026 self.assertIn('a', dir(mock))
1027 self.assertIn('b', dir(mock))
1028
1029 # instance attributes
1030 mock.c = mock.d = None
1031 self.assertIn('c', dir(mock))
1032 self.assertIn('d', dir(mock))
1033
1034 # magic methods
1035 mock.__iter__ = lambda s: iter([])
1036 self.assertIn('__iter__', dir(mock))
1037
1038
1039 def test_dir_from_spec(self):
1040 mock = Mock(spec=unittest.TestCase)
1041 testcase_attrs = set(dir(unittest.TestCase))
1042 attrs = set(dir(mock))
1043
1044 # all attributes from the spec are included
1045 self.assertEqual(set(), testcase_attrs - attrs)
1046
1047 # shadow a sys attribute
1048 mock.version = 3
1049 self.assertEqual(dir(mock).count('version'), 1)
1050
1051
1052 def test_filter_dir(self):
1053 patcher = patch.object(mock, 'FILTER_DIR', False)
1054 patcher.start()
1055 try:
1056 attrs = set(dir(Mock()))
1057 type_attrs = set(dir(Mock))
1058
1059 # ALL attributes from the type are included
1060 self.assertEqual(set(), type_attrs - attrs)
1061 finally:
1062 patcher.stop()
1063
1064
1065 def test_dir_does_not_include_deleted_attributes(self):
1066 mock = Mock()
1067 mock.child.return_value = 1
1068
1069 self.assertIn('child', dir(mock))
1070 del mock.child
1071 self.assertNotIn('child', dir(mock))
1072
1073
1074 def test_configure_mock(self):
1075 mock = Mock(foo='bar')
1076 self.assertEqual(mock.foo, 'bar')
1077
1078 mock = MagicMock(foo='bar')
1079 self.assertEqual(mock.foo, 'bar')
1080
1081 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
1082 'foo': MagicMock()}
1083 mock = Mock(**kwargs)
1084 self.assertRaises(KeyError, mock)
1085 self.assertEqual(mock.foo.bar(), 33)
1086 self.assertIsInstance(mock.foo, MagicMock)
1087
1088 mock = Mock()
1089 mock.configure_mock(**kwargs)
1090 self.assertRaises(KeyError, mock)
1091 self.assertEqual(mock.foo.bar(), 33)
1092 self.assertIsInstance(mock.foo, MagicMock)
1093
1094
1095 def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
1096 # needed because assertRaisesRegex doesn't work easily with newlines
1097 with self.assertRaises(exception) as context:
1098 func(*args, **kwargs)
1099 msg = str(context.exception)
1100 self.assertEqual(msg, message)
1101
1102
1103 def test_assert_called_with_failure_message(self):
1104 mock = NonCallableMock()
1105
1106 actual = 'not called.'
1107 expected = "mock(1, '2', 3, bar='foo')"
1108 message = 'expected call not found.\nExpected: %s\n Actual: %s'
1109 self.assertRaisesWithMsg(
1110 AssertionError, message % (expected, actual),
1111 mock.assert_called_with, 1, '2', 3, bar='foo'
1112 )
1113
1114 mock.foo(1, '2', 3, foo='foo')
1115
1116
1117 asserters = [
1118 mock.foo.assert_called_with, mock.foo.assert_called_once_with
1119 ]
1120 for meth in asserters:
1121 actual = "foo(1, '2', 3, foo='foo')"
1122 expected = "foo(1, '2', 3, bar='foo')"
1123 message = 'expected call not found.\nExpected: %s\n Actual: %s'
1124 self.assertRaisesWithMsg(
1125 AssertionError, message % (expected, actual),
1126 meth, 1, '2', 3, bar='foo'
1127 )
1128
1129 # just kwargs
1130 for meth in asserters:
1131 actual = "foo(1, '2', 3, foo='foo')"
1132 expected = "foo(bar='foo')"
1133 message = 'expected call not found.\nExpected: %s\n Actual: %s'
1134 self.assertRaisesWithMsg(
1135 AssertionError, message % (expected, actual),
1136 meth, bar='foo'
1137 )
1138
1139 # just args
1140 for meth in asserters:
1141 actual = "foo(1, '2', 3, foo='foo')"
1142 expected = "foo(1, 2, 3)"
1143 message = 'expected call not found.\nExpected: %s\n Actual: %s'
1144 self.assertRaisesWithMsg(
1145 AssertionError, message % (expected, actual),
1146 meth, 1, 2, 3
1147 )
1148
1149 # empty
1150 for meth in asserters:
1151 actual = "foo(1, '2', 3, foo='foo')"
1152 expected = "foo()"
1153 message = 'expected call not found.\nExpected: %s\n Actual: %s'
1154 self.assertRaisesWithMsg(
1155 AssertionError, message % (expected, actual), meth
1156 )
1157
1158
1159 def test_mock_calls(self):
1160 mock = MagicMock()
1161
1162 # need to do this because MagicMock.mock_calls used to just return
1163 # a MagicMock which also returned a MagicMock when __eq__ was called
1164 self.assertIs(mock.mock_calls == [], True)
1165
1166 mock = MagicMock()
1167 mock()
1168 expected = [('', (), {})]
1169 self.assertEqual(mock.mock_calls, expected)
1170
1171 mock.foo()
1172 expected.append(call.foo())
1173 self.assertEqual(mock.mock_calls, expected)
1174 # intermediate mock_calls work too
1175 self.assertEqual(mock.foo.mock_calls, [('', (), {})])
1176
1177 mock = MagicMock()
1178 mock().foo(1, 2, 3, a=4, b=5)
1179 expected = [
1180 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
1181 ]
1182 self.assertEqual(mock.mock_calls, expected)
1183 self.assertEqual(mock.return_value.foo.mock_calls,
1184 [('', (1, 2, 3), dict(a=4, b=5))])
1185 self.assertEqual(mock.return_value.mock_calls,
1186 [('foo', (1, 2, 3), dict(a=4, b=5))])
1187
1188 mock = MagicMock()
1189 mock().foo.bar().baz()
1190 expected = [
1191 ('', (), {}), ('().foo.bar', (), {}),
1192 ('().foo.bar().baz', (), {})
1193 ]
1194 self.assertEqual(mock.mock_calls, expected)
1195 self.assertEqual(mock().mock_calls,
1196 call.foo.bar().baz().call_list())
1197
1198 for kwargs in dict(), dict(name='bar'):
1199 mock = MagicMock(**kwargs)
1200 int(mock.foo)
1201 expected = [('foo.__int__', (), {})]
1202 self.assertEqual(mock.mock_calls, expected)
1203
1204 mock = MagicMock(**kwargs)
1205 mock.a()()
1206 expected = [('a', (), {}), ('a()', (), {})]
1207 self.assertEqual(mock.mock_calls, expected)
1208 self.assertEqual(mock.a().mock_calls, [call()])
1209
1210 mock = MagicMock(**kwargs)
1211 mock(1)(2)(3)
1212 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
1213 self.assertEqual(mock().mock_calls, call(2)(3).call_list())
1214 self.assertEqual(mock()().mock_calls, call(3).call_list())
1215
1216 mock = MagicMock(**kwargs)
1217 mock(1)(2)(3).a.b.c(4)
1218 self.assertEqual(mock.mock_calls,
1219 call(1)(2)(3).a.b.c(4).call_list())
1220 self.assertEqual(mock().mock_calls,
1221 call(2)(3).a.b.c(4).call_list())
1222 self.assertEqual(mock()().mock_calls,
1223 call(3).a.b.c(4).call_list())
1224
1225 mock = MagicMock(**kwargs)
1226 int(mock().foo.bar().baz())
1227 last_call = ('().foo.bar().baz().__int__', (), {})
1228 self.assertEqual(mock.mock_calls[-1], last_call)
1229 self.assertEqual(mock().mock_calls,
1230 call.foo.bar().baz().__int__().call_list())
1231 self.assertEqual(mock().foo.bar().mock_calls,
1232 call.baz().__int__().call_list())
1233 self.assertEqual(mock().foo.bar().baz.mock_calls,
1234 call().__int__().call_list())
1235
1236
1237 def test_child_mock_call_equal(self):
1238 m = Mock()
1239 result = m()
1240 result.wibble()
1241 # parent looks like this:
1242 self.assertEqual(m.mock_calls, [call(), call().wibble()])
1243 # but child should look like this:
1244 self.assertEqual(result.mock_calls, [call.wibble()])
1245
1246
1247 def test_mock_call_not_equal_leaf(self):
1248 m = Mock()
1249 m.foo().something()
1250 self.assertNotEqual(m.mock_calls[1], call.foo().different())
1251 self.assertEqual(m.mock_calls[0], call.foo())
1252
1253
1254 def test_mock_call_not_equal_non_leaf(self):
1255 m = Mock()
1256 m.foo().bar()
1257 self.assertNotEqual(m.mock_calls[1], call.baz().bar())
1258 self.assertNotEqual(m.mock_calls[0], call.baz())
1259
1260
1261 def test_mock_call_not_equal_non_leaf_params_different(self):
1262 m = Mock()
1263 m.foo(x=1).bar()
1264 # This isn't ideal, but there's no way to fix it without breaking backwards compatibility:
1265 self.assertEqual(m.mock_calls[1], call.foo(x=2).bar())
1266
1267
1268 def test_mock_call_not_equal_non_leaf_attr(self):
1269 m = Mock()
1270 m.foo.bar()
1271 self.assertNotEqual(m.mock_calls[0], call.baz.bar())
1272
1273
1274 def test_mock_call_not_equal_non_leaf_call_versus_attr(self):
1275 m = Mock()
1276 m.foo.bar()
1277 self.assertNotEqual(m.mock_calls[0], call.foo().bar())
1278
1279
1280 def test_mock_call_repr(self):
1281 m = Mock()
1282 m.foo().bar().baz.bob()
1283 self.assertEqual(repr(m.mock_calls[0]), 'call.foo()')
1284 self.assertEqual(repr(m.mock_calls[1]), 'call.foo().bar()')
1285 self.assertEqual(repr(m.mock_calls[2]), 'call.foo().bar().baz.bob()')
1286
1287
1288 def test_mock_call_repr_loop(self):
1289 m = Mock()
1290 m.foo = m
1291 repr(m.foo())
1292 self.assertRegex(repr(m.foo()), r"<Mock name='mock\(\)' id='\d+'>")
1293
1294
1295 def test_mock_calls_contains(self):
1296 m = Mock()
1297 self.assertFalse([call()] in m.mock_calls)
1298
1299
1300 def test_subclassing(self):
1301 class Subclass(Mock):
1302 pass
1303
1304 mock = Subclass()
1305 self.assertIsInstance(mock.foo, Subclass)
1306 self.assertIsInstance(mock(), Subclass)
1307
1308 class Subclass(Mock):
1309 def _get_child_mock(self, **kwargs):
1310 return Mock(**kwargs)
1311
1312 mock = Subclass()
1313 self.assertNotIsInstance(mock.foo, Subclass)
1314 self.assertNotIsInstance(mock(), Subclass)
1315
1316
1317 def test_arg_lists(self):
1318 mocks = [
1319 Mock(),
1320 MagicMock(),
1321 NonCallableMock(),
1322 NonCallableMagicMock()
1323 ]
1324
1325 def assert_attrs(mock):
1326 names = 'call_args_list', 'method_calls', 'mock_calls'
1327 for name in names:
1328 attr = getattr(mock, name)
1329 self.assertIsInstance(attr, _CallList)
1330 self.assertIsInstance(attr, list)
1331 self.assertEqual(attr, [])
1332
1333 for mock in mocks:
1334 assert_attrs(mock)
1335
1336 if callable(mock):
1337 mock()
1338 mock(1, 2)
1339 mock(a=3)
1340
1341 mock.reset_mock()
1342 assert_attrs(mock)
1343
1344 mock.foo()
1345 mock.foo.bar(1, a=3)
1346 mock.foo(1).bar().baz(3)
1347
1348 mock.reset_mock()
1349 assert_attrs(mock)
1350
1351
1352 def test_call_args_two_tuple(self):
1353 mock = Mock()
1354 mock(1, a=3)
1355 mock(2, b=4)
1356
1357 self.assertEqual(len(mock.call_args), 2)
1358 self.assertEqual(mock.call_args.args, (2,))
1359 self.assertEqual(mock.call_args.kwargs, dict(b=4))
1360
1361 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
1362 for expected, call_args in zip(expected_list, mock.call_args_list):
1363 self.assertEqual(len(call_args), 2)
1364 self.assertEqual(expected[0], call_args[0])
1365 self.assertEqual(expected[1], call_args[1])
1366
1367
1368 def test_side_effect_iterator(self):
1369 mock = Mock(side_effect=iter([1, 2, 3]))
1370 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1371 self.assertRaises(StopIteration, mock)
1372
1373 mock = MagicMock(side_effect=['a', 'b', 'c'])
1374 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1375 self.assertRaises(StopIteration, mock)
1376
1377 mock = Mock(side_effect='ghi')
1378 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
1379 self.assertRaises(StopIteration, mock)
1380
1381 class Foo(object):
1382 pass
1383 mock = MagicMock(side_effect=Foo)
1384 self.assertIsInstance(mock(), Foo)
1385
1386 mock = Mock(side_effect=Iter())
1387 self.assertEqual([mock(), mock(), mock(), mock()],
1388 ['this', 'is', 'an', 'iter'])
1389 self.assertRaises(StopIteration, mock)
1390
1391
1392 def test_side_effect_iterator_exceptions(self):
1393 for Klass in Mock, MagicMock:
1394 iterable = (ValueError, 3, KeyError, 6)
1395 m = Klass(side_effect=iterable)
1396 self.assertRaises(ValueError, m)
1397 self.assertEqual(m(), 3)
1398 self.assertRaises(KeyError, m)
1399 self.assertEqual(m(), 6)
1400
1401
1402 def test_side_effect_setting_iterator(self):
1403 mock = Mock()
1404 mock.side_effect = iter([1, 2, 3])
1405 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1406 self.assertRaises(StopIteration, mock)
1407 side_effect = mock.side_effect
1408 self.assertIsInstance(side_effect, type(iter([])))
1409
1410 mock.side_effect = ['a', 'b', 'c']
1411 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1412 self.assertRaises(StopIteration, mock)
1413 side_effect = mock.side_effect
1414 self.assertIsInstance(side_effect, type(iter([])))
1415
1416 this_iter = Iter()
1417 mock.side_effect = this_iter
1418 self.assertEqual([mock(), mock(), mock(), mock()],
1419 ['this', 'is', 'an', 'iter'])
1420 self.assertRaises(StopIteration, mock)
1421 self.assertIs(mock.side_effect, this_iter)
1422
1423 def test_side_effect_iterator_default(self):
1424 mock = Mock(return_value=2)
1425 mock.side_effect = iter([1, DEFAULT])
1426 self.assertEqual([mock(), mock()], [1, 2])
1427
1428 def test_assert_has_calls_any_order(self):
1429 mock = Mock()
1430 mock(1, 2)
1431 mock(a=3)
1432 mock(3, 4)
1433 mock(b=6)
1434 mock(b=6)
1435
1436 kalls = [
1437 call(1, 2), ({'a': 3},),
1438 ((3, 4),), ((), {'a': 3}),
1439 ('', (1, 2)), ('', {'a': 3}),
1440 ('', (1, 2), {}), ('', (), {'a': 3})
1441 ]
1442 for kall in kalls:
1443 mock.assert_has_calls([kall], any_order=True)
1444
1445 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
1446 self.assertRaises(
1447 AssertionError, mock.assert_has_calls,
1448 [kall], any_order=True
1449 )
1450
1451 kall_lists = [
1452 [call(1, 2), call(b=6)],
1453 [call(3, 4), call(1, 2)],
1454 [call(b=6), call(b=6)],
1455 ]
1456
1457 for kall_list in kall_lists:
1458 mock.assert_has_calls(kall_list, any_order=True)
1459
1460 kall_lists = [
1461 [call(b=6), call(b=6), call(b=6)],
1462 [call(1, 2), call(1, 2)],
1463 [call(3, 4), call(1, 2), call(5, 7)],
1464 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
1465 ]
1466 for kall_list in kall_lists:
1467 self.assertRaises(
1468 AssertionError, mock.assert_has_calls,
1469 kall_list, any_order=True
1470 )
1471
1472 def test_assert_has_calls(self):
1473 kalls1 = [
1474 call(1, 2), ({'a': 3},),
1475 ((3, 4),), call(b=6),
1476 ('', (1,), {'b': 6}),
1477 ]
1478 kalls2 = [call.foo(), call.bar(1)]
1479 kalls2.extend(call.spam().baz(a=3).call_list())
1480 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
1481
1482 mocks = []
1483 for mock in Mock(), MagicMock():
1484 mock(1, 2)
1485 mock(a=3)
1486 mock(3, 4)
1487 mock(b=6)
1488 mock(1, b=6)
1489 mocks.append((mock, kalls1))
1490
1491 mock = Mock()
1492 mock.foo()
1493 mock.bar(1)
1494 mock.spam().baz(a=3)
1495 mock.bam(set(), foo={}).fish([1])
1496 mocks.append((mock, kalls2))
1497
1498 for mock, kalls in mocks:
1499 for i in range(len(kalls)):
1500 for step in 1, 2, 3:
1501 these = kalls[i:i+step]
1502 mock.assert_has_calls(these)
1503
1504 if len(these) > 1:
1505 self.assertRaises(
1506 AssertionError,
1507 mock.assert_has_calls,
1508 list(reversed(these))
1509 )
1510
1511
1512 def test_assert_has_calls_nested_spec(self):
1513 class Something:
1514
1515 def __init__(self): pass
1516 def meth(self, a, b, c, d=None): pass
1517
1518 class Foo:
1519
1520 def __init__(self, a): pass
1521 def meth1(self, a, b): pass
1522
1523 mock_class = create_autospec(Something)
1524
1525 for m in [mock_class, mock_class()]:
1526 m.meth(1, 2, 3, d=1)
1527 m.assert_has_calls([call.meth(1, 2, 3, d=1)])
1528 m.assert_has_calls([call.meth(1, 2, 3, 1)])
1529
1530 mock_class.reset_mock()
1531
1532 for m in [mock_class, mock_class()]:
1533 self.assertRaises(AssertionError, m.assert_has_calls, [call.Foo()])
1534 m.Foo(1).meth1(1, 2)
1535 m.assert_has_calls([call.Foo(1), call.Foo(1).meth1(1, 2)])
1536 m.Foo.assert_has_calls([call(1), call().meth1(1, 2)])
1537
1538 mock_class.reset_mock()
1539
1540 invalid_calls = [call.meth(1),
1541 call.non_existent(1),
1542 call.Foo().non_existent(1),
1543 call.Foo().meth(1, 2, 3, 4)]
1544
1545 for kall in invalid_calls:
1546 self.assertRaises(AssertionError,
1547 mock_class.assert_has_calls,
1548 [kall]
1549 )
1550
1551
1552 def test_assert_has_calls_nested_without_spec(self):
1553 m = MagicMock()
1554 m().foo().bar().baz()
1555 m.one().two().three()
1556 calls = call.one().two().three().call_list()
1557 m.assert_has_calls(calls)
1558
1559
1560 def test_assert_has_calls_with_function_spec(self):
1561 def f(a, b, c, d=None): pass
1562
1563 mock = Mock(spec=f)
1564
1565 mock(1, b=2, c=3)
1566 mock(4, 5, c=6, d=7)
1567 mock(10, 11, c=12)
1568 calls = [
1569 ('', (1, 2, 3), {}),
1570 ('', (4, 5, 6), {'d': 7}),
1571 ((10, 11, 12), {}),
1572 ]
1573 mock.assert_has_calls(calls)
1574 mock.assert_has_calls(calls, any_order=True)
1575 mock.assert_has_calls(calls[1:])
1576 mock.assert_has_calls(calls[1:], any_order=True)
1577 mock.assert_has_calls(calls[:-1])
1578 mock.assert_has_calls(calls[:-1], any_order=True)
1579 # Reversed order
1580 calls = list(reversed(calls))
1581 with self.assertRaises(AssertionError):
1582 mock.assert_has_calls(calls)
1583 mock.assert_has_calls(calls, any_order=True)
1584 with self.assertRaises(AssertionError):
1585 mock.assert_has_calls(calls[1:])
1586 mock.assert_has_calls(calls[1:], any_order=True)
1587 with self.assertRaises(AssertionError):
1588 mock.assert_has_calls(calls[:-1])
1589 mock.assert_has_calls(calls[:-1], any_order=True)
1590
1591 def test_assert_has_calls_not_matching_spec_error(self):
1592 def f(x=None): pass
1593
1594 mock = Mock(spec=f)
1595 mock(1)
1596
1597 with self.assertRaisesRegex(
1598 AssertionError,
1599 '^{}$'.format(
1600 re.escape('Calls not found.\n'
1601 'Expected: [call()]\n'
1602 ' Actual: [call(1)]'))) as cm:
1603 mock.assert_has_calls([call()])
1604 self.assertIsNone(cm.exception.__cause__)
1605
1606
1607 with self.assertRaisesRegex(
1608 AssertionError,
1609 '^{}$'.format(
1610 re.escape(
1611 'Error processing expected calls.\n'
1612 "Errors: [None, TypeError('too many positional arguments')]\n"
1613 "Expected: [call(), call(1, 2)]\n"
1614 ' Actual: [call(1)]'))) as cm:
1615 mock.assert_has_calls([call(), call(1, 2)])
1616 self.assertIsInstance(cm.exception.__cause__, TypeError)
1617
1618 def test_assert_any_call(self):
1619 mock = Mock()
1620 mock(1, 2)
1621 mock(a=3)
1622 mock(1, b=6)
1623
1624 mock.assert_any_call(1, 2)
1625 mock.assert_any_call(a=3)
1626 mock.assert_any_call(1, b=6)
1627
1628 self.assertRaises(
1629 AssertionError,
1630 mock.assert_any_call
1631 )
1632 self.assertRaises(
1633 AssertionError,
1634 mock.assert_any_call,
1635 1, 3
1636 )
1637 self.assertRaises(
1638 AssertionError,
1639 mock.assert_any_call,
1640 a=4
1641 )
1642
1643
1644 def test_assert_any_call_with_function_spec(self):
1645 def f(a, b, c, d=None): pass
1646
1647 mock = Mock(spec=f)
1648
1649 mock(1, b=2, c=3)
1650 mock(4, 5, c=6, d=7)
1651 mock.assert_any_call(1, 2, 3)
1652 mock.assert_any_call(a=1, b=2, c=3)
1653 mock.assert_any_call(4, 5, 6, 7)
1654 mock.assert_any_call(a=4, b=5, c=6, d=7)
1655 self.assertRaises(AssertionError, mock.assert_any_call,
1656 1, b=3, c=2)
1657 # Expected call doesn't match the spec's signature
1658 with self.assertRaises(AssertionError) as cm:
1659 mock.assert_any_call(e=8)
1660 self.assertIsInstance(cm.exception.__cause__, TypeError)
1661
1662
1663 def test_mock_calls_create_autospec(self):
1664 def f(a, b): pass
1665 obj = Iter()
1666 obj.f = f
1667
1668 funcs = [
1669 create_autospec(f),
1670 create_autospec(obj).f
1671 ]
1672 for func in funcs:
1673 func(1, 2)
1674 func(3, 4)
1675
1676 self.assertEqual(
1677 func.mock_calls, [call(1, 2), call(3, 4)]
1678 )
1679
1680 #Issue21222
1681 def test_create_autospec_with_name(self):
1682 m = mock.create_autospec(object(), name='sweet_func')
1683 self.assertIn('sweet_func', repr(m))
1684
1685 #Issue23078
1686 def test_create_autospec_classmethod_and_staticmethod(self):
1687 class TestClass:
1688 @classmethod
1689 def class_method(cls): pass
1690
1691 @staticmethod
1692 def static_method(): pass
1693 for method in ('class_method', 'static_method'):
1694 with self.subTest(method=method):
1695 mock_method = mock.create_autospec(getattr(TestClass, method))
1696 mock_method()
1697 mock_method.assert_called_once_with()
1698 self.assertRaises(TypeError, mock_method, 'extra_arg')
1699
1700 #Issue21238
1701 def test_mock_unsafe(self):
1702 m = Mock()
1703 msg = "is not a valid assertion. Use a spec for the mock"
1704 with self.assertRaisesRegex(AttributeError, msg):
1705 m.assert_foo_call()
1706 with self.assertRaisesRegex(AttributeError, msg):
1707 m.assret_foo_call()
1708 with self.assertRaisesRegex(AttributeError, msg):
1709 m.asert_foo_call()
1710 with self.assertRaisesRegex(AttributeError, msg):
1711 m.aseert_foo_call()
1712 with self.assertRaisesRegex(AttributeError, msg):
1713 m.assrt_foo_call()
1714 m = Mock(unsafe=True)
1715 m.assert_foo_call()
1716 m.assret_foo_call()
1717 m.asert_foo_call()
1718 m.aseert_foo_call()
1719 m.assrt_foo_call()
1720
1721 # gh-100739
1722 def test_mock_safe_with_spec(self):
1723 class Foo(object):
1724 def assert_bar(self):
1725 pass
1726
1727 def assertSome(self):
1728 pass
1729
1730 m = Mock(spec=Foo)
1731 m.assert_bar()
1732 m.assertSome()
1733
1734 m.assert_bar.assert_called_once()
1735 m.assertSome.assert_called_once()
1736
1737 #Issue21262
1738 def test_assert_not_called(self):
1739 m = Mock()
1740 m.hello.assert_not_called()
1741 m.hello()
1742 with self.assertRaises(AssertionError):
1743 m.hello.assert_not_called()
1744
1745 def test_assert_not_called_message(self):
1746 m = Mock()
1747 m(1, 2)
1748 self.assertRaisesRegex(AssertionError,
1749 re.escape("Calls: [call(1, 2)]"),
1750 m.assert_not_called)
1751
1752 def test_assert_called(self):
1753 m = Mock()
1754 with self.assertRaises(AssertionError):
1755 m.hello.assert_called()
1756 m.hello()
1757 m.hello.assert_called()
1758
1759 m.hello()
1760 m.hello.assert_called()
1761
1762 def test_assert_called_once(self):
1763 m = Mock()
1764 with self.assertRaises(AssertionError):
1765 m.hello.assert_called_once()
1766 m.hello()
1767 m.hello.assert_called_once()
1768
1769 m.hello()
1770 with self.assertRaises(AssertionError):
1771 m.hello.assert_called_once()
1772
1773 def test_assert_called_once_message(self):
1774 m = Mock()
1775 m(1, 2)
1776 m(3)
1777 self.assertRaisesRegex(AssertionError,
1778 re.escape("Calls: [call(1, 2), call(3)]"),
1779 m.assert_called_once)
1780
1781 def test_assert_called_once_message_not_called(self):
1782 m = Mock()
1783 with self.assertRaises(AssertionError) as e:
1784 m.assert_called_once()
1785 self.assertNotIn("Calls:", str(e.exception))
1786
1787 #Issue37212 printout of keyword args now preserves the original order
1788 def test_ordered_call_signature(self):
1789 m = Mock()
1790 m.hello(name='hello', daddy='hero')
1791 text = "call(name='hello', daddy='hero')"
1792 self.assertEqual(repr(m.hello.call_args), text)
1793
1794 #Issue21270 overrides tuple methods for mock.call objects
1795 def test_override_tuple_methods(self):
1796 c = call.count()
1797 i = call.index(132,'hello')
1798 m = Mock()
1799 m.count()
1800 m.index(132,"hello")
1801 self.assertEqual(m.method_calls[0], c)
1802 self.assertEqual(m.method_calls[1], i)
1803
1804 def test_reset_return_sideeffect(self):
1805 m = Mock(return_value=10, side_effect=[2,3])
1806 m.reset_mock(return_value=True, side_effect=True)
1807 self.assertIsInstance(m.return_value, Mock)
1808 self.assertEqual(m.side_effect, None)
1809
1810 def test_reset_return(self):
1811 m = Mock(return_value=10, side_effect=[2,3])
1812 m.reset_mock(return_value=True)
1813 self.assertIsInstance(m.return_value, Mock)
1814 self.assertNotEqual(m.side_effect, None)
1815
1816 def test_reset_sideeffect(self):
1817 m = Mock(return_value=10, side_effect=[2, 3])
1818 m.reset_mock(side_effect=True)
1819 self.assertEqual(m.return_value, 10)
1820 self.assertEqual(m.side_effect, None)
1821
1822 def test_reset_return_with_children(self):
1823 m = MagicMock(f=MagicMock(return_value=1))
1824 self.assertEqual(m.f(), 1)
1825 m.reset_mock(return_value=True)
1826 self.assertNotEqual(m.f(), 1)
1827
1828 def test_reset_return_with_children_side_effect(self):
1829 m = MagicMock(f=MagicMock(side_effect=[2, 3]))
1830 self.assertNotEqual(m.f.side_effect, None)
1831 m.reset_mock(side_effect=True)
1832 self.assertEqual(m.f.side_effect, None)
1833
1834 def test_mock_add_spec(self):
1835 class _One(object):
1836 one = 1
1837 class _Two(object):
1838 two = 2
1839 class Anything(object):
1840 one = two = three = 'four'
1841
1842 klasses = [
1843 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1844 ]
1845 for Klass in list(klasses):
1846 klasses.append(lambda K=Klass: K(spec=Anything))
1847 klasses.append(lambda K=Klass: K(spec_set=Anything))
1848
1849 for Klass in klasses:
1850 for kwargs in dict(), dict(spec_set=True):
1851 mock = Klass()
1852 #no error
1853 mock.one, mock.two, mock.three
1854
1855 for One, Two in [(_One, _Two), (['one'], ['two'])]:
1856 for kwargs in dict(), dict(spec_set=True):
1857 mock.mock_add_spec(One, **kwargs)
1858
1859 mock.one
1860 self.assertRaises(
1861 AttributeError, getattr, mock, 'two'
1862 )
1863 self.assertRaises(
1864 AttributeError, getattr, mock, 'three'
1865 )
1866 if 'spec_set' in kwargs:
1867 self.assertRaises(
1868 AttributeError, setattr, mock, 'three', None
1869 )
1870
1871 mock.mock_add_spec(Two, **kwargs)
1872 self.assertRaises(
1873 AttributeError, getattr, mock, 'one'
1874 )
1875 mock.two
1876 self.assertRaises(
1877 AttributeError, getattr, mock, 'three'
1878 )
1879 if 'spec_set' in kwargs:
1880 self.assertRaises(
1881 AttributeError, setattr, mock, 'three', None
1882 )
1883 # note that creating a mock, setting an instance attribute, and
1884 # *then* setting a spec doesn't work. Not the intended use case
1885
1886
1887 def test_mock_add_spec_magic_methods(self):
1888 for Klass in MagicMock, NonCallableMagicMock:
1889 mock = Klass()
1890 int(mock)
1891
1892 mock.mock_add_spec(object)
1893 self.assertRaises(TypeError, int, mock)
1894
1895 mock = Klass()
1896 mock['foo']
1897 mock.__int__.return_value =4
1898
1899 mock.mock_add_spec(int)
1900 self.assertEqual(int(mock), 4)
1901 self.assertRaises(TypeError, lambda: mock['foo'])
1902
1903
1904 def test_adding_child_mock(self):
1905 for Klass in (NonCallableMock, Mock, MagicMock, NonCallableMagicMock,
1906 AsyncMock):
1907 mock = Klass()
1908
1909 mock.foo = Mock()
1910 mock.foo()
1911
1912 self.assertEqual(mock.method_calls, [call.foo()])
1913 self.assertEqual(mock.mock_calls, [call.foo()])
1914
1915 mock = Klass()
1916 mock.bar = Mock(name='name')
1917 mock.bar()
1918 self.assertEqual(mock.method_calls, [])
1919 self.assertEqual(mock.mock_calls, [])
1920
1921 # mock with an existing _new_parent but no name
1922 mock = Klass()
1923 mock.baz = MagicMock()()
1924 mock.baz()
1925 self.assertEqual(mock.method_calls, [])
1926 self.assertEqual(mock.mock_calls, [])
1927
1928
1929 def test_adding_return_value_mock(self):
1930 for Klass in Mock, MagicMock:
1931 mock = Klass()
1932 mock.return_value = MagicMock()
1933
1934 mock()()
1935 self.assertEqual(mock.mock_calls, [call(), call()()])
1936
1937
1938 def test_manager_mock(self):
1939 class Foo(object):
1940 one = 'one'
1941 two = 'two'
1942 manager = Mock()
1943 p1 = patch.object(Foo, 'one')
1944 p2 = patch.object(Foo, 'two')
1945
1946 mock_one = p1.start()
1947 self.addCleanup(p1.stop)
1948 mock_two = p2.start()
1949 self.addCleanup(p2.stop)
1950
1951 manager.attach_mock(mock_one, 'one')
1952 manager.attach_mock(mock_two, 'two')
1953
1954 Foo.two()
1955 Foo.one()
1956
1957 self.assertEqual(manager.mock_calls, [call.two(), call.one()])
1958
1959
1960 def test_magic_methods_mock_calls(self):
1961 for Klass in Mock, MagicMock:
1962 m = Klass()
1963 m.__int__ = Mock(return_value=3)
1964 m.__float__ = MagicMock(return_value=3.0)
1965 int(m)
1966 float(m)
1967
1968 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
1969 self.assertEqual(m.method_calls, [])
1970
1971 def test_mock_open_reuse_issue_21750(self):
1972 mocked_open = mock.mock_open(read_data='data')
1973 f1 = mocked_open('a-name')
1974 f1_data = f1.read()
1975 f2 = mocked_open('another-name')
1976 f2_data = f2.read()
1977 self.assertEqual(f1_data, f2_data)
1978
1979 def test_mock_open_dunder_iter_issue(self):
1980 # Test dunder_iter method generates the expected result and
1981 # consumes the iterator.
1982 mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue')
1983 f1 = mocked_open('a-name')
1984 lines = [line for line in f1]
1985 self.assertEqual(lines[0], 'Remarkable\n')
1986 self.assertEqual(lines[1], 'Norwegian Blue')
1987 self.assertEqual(list(f1), [])
1988
1989 def test_mock_open_using_next(self):
1990 mocked_open = mock.mock_open(read_data='1st line\n2nd line\n3rd line')
1991 f1 = mocked_open('a-name')
1992 line1 = next(f1)
1993 line2 = f1.__next__()
1994 lines = [line for line in f1]
1995 self.assertEqual(line1, '1st line\n')
1996 self.assertEqual(line2, '2nd line\n')
1997 self.assertEqual(lines[0], '3rd line')
1998 self.assertEqual(list(f1), [])
1999 with self.assertRaises(StopIteration):
2000 next(f1)
2001
2002 def test_mock_open_next_with_readline_with_return_value(self):
2003 mopen = mock.mock_open(read_data='foo\nbarn')
2004 mopen.return_value.readline.return_value = 'abc'
2005 self.assertEqual('abc', next(mopen()))
2006
2007 def test_mock_open_write(self):
2008 # Test exception in file writing write()
2009 mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
2010 with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
2011 mock_filehandle = mock_namedtemp.return_value
2012 mock_write = mock_filehandle.write
2013 mock_write.side_effect = OSError('Test 2 Error')
2014 def attempt():
2015 tempfile.NamedTemporaryFile().write('asd')
2016 self.assertRaises(OSError, attempt)
2017
2018 def test_mock_open_alter_readline(self):
2019 mopen = mock.mock_open(read_data='foo\nbarn')
2020 mopen.return_value.readline.side_effect = lambda *args:'abc'
2021 first = mopen().readline()
2022 second = mopen().readline()
2023 self.assertEqual('abc', first)
2024 self.assertEqual('abc', second)
2025
2026 def test_mock_open_after_eof(self):
2027 # read, readline and readlines should work after end of file.
2028 _open = mock.mock_open(read_data='foo')
2029 h = _open('bar')
2030 h.read()
2031 self.assertEqual('', h.read())
2032 self.assertEqual('', h.read())
2033 self.assertEqual('', h.readline())
2034 self.assertEqual('', h.readline())
2035 self.assertEqual([], h.readlines())
2036 self.assertEqual([], h.readlines())
2037
2038 def test_mock_parents(self):
2039 for Klass in Mock, MagicMock:
2040 m = Klass()
2041 original_repr = repr(m)
2042 m.return_value = m
2043 self.assertIs(m(), m)
2044 self.assertEqual(repr(m), original_repr)
2045
2046 m.reset_mock()
2047 self.assertIs(m(), m)
2048 self.assertEqual(repr(m), original_repr)
2049
2050 m = Klass()
2051 m.b = m.a
2052 self.assertIn("name='mock.a'", repr(m.b))
2053 self.assertIn("name='mock.a'", repr(m.a))
2054 m.reset_mock()
2055 self.assertIn("name='mock.a'", repr(m.b))
2056 self.assertIn("name='mock.a'", repr(m.a))
2057
2058 m = Klass()
2059 original_repr = repr(m)
2060 m.a = m()
2061 m.a.return_value = m
2062
2063 self.assertEqual(repr(m), original_repr)
2064 self.assertEqual(repr(m.a()), original_repr)
2065
2066
2067 def test_attach_mock(self):
2068 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
2069 for Klass in classes:
2070 for Klass2 in classes:
2071 m = Klass()
2072
2073 m2 = Klass2(name='foo')
2074 m.attach_mock(m2, 'bar')
2075
2076 self.assertIs(m.bar, m2)
2077 self.assertIn("name='mock.bar'", repr(m2))
2078
2079 m.bar.baz(1)
2080 self.assertEqual(m.mock_calls, [call.bar.baz(1)])
2081 self.assertEqual(m.method_calls, [call.bar.baz(1)])
2082
2083
2084 def test_attach_mock_return_value(self):
2085 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
2086 for Klass in Mock, MagicMock:
2087 for Klass2 in classes:
2088 m = Klass()
2089
2090 m2 = Klass2(name='foo')
2091 m.attach_mock(m2, 'return_value')
2092
2093 self.assertIs(m(), m2)
2094 self.assertIn("name='mock()'", repr(m2))
2095
2096 m2.foo()
2097 self.assertEqual(m.mock_calls, call().foo().call_list())
2098
2099
2100 def test_attach_mock_patch_autospec(self):
2101 parent = Mock()
2102
2103 with mock.patch(f'{__name__}.something', autospec=True) as mock_func:
2104 self.assertEqual(mock_func.mock._extract_mock_name(), 'something')
2105 parent.attach_mock(mock_func, 'child')
2106 parent.child(1)
2107 something(2)
2108 mock_func(3)
2109
2110 parent_calls = [call.child(1), call.child(2), call.child(3)]
2111 child_calls = [call(1), call(2), call(3)]
2112 self.assertEqual(parent.mock_calls, parent_calls)
2113 self.assertEqual(parent.child.mock_calls, child_calls)
2114 self.assertEqual(something.mock_calls, child_calls)
2115 self.assertEqual(mock_func.mock_calls, child_calls)
2116 self.assertIn('mock.child', repr(parent.child.mock))
2117 self.assertEqual(mock_func.mock._extract_mock_name(), 'mock.child')
2118
2119
2120 def test_attach_mock_patch_autospec_signature(self):
2121 with mock.patch(f'{__name__}.Something.meth', autospec=True) as mocked:
2122 manager = Mock()
2123 manager.attach_mock(mocked, 'attach_meth')
2124 obj = Something()
2125 obj.meth(1, 2, 3, d=4)
2126 manager.assert_has_calls([call.attach_meth(mock.ANY, 1, 2, 3, d=4)])
2127 obj.meth.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)])
2128 mocked.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)])
2129
2130 with mock.patch(f'{__name__}.something', autospec=True) as mocked:
2131 manager = Mock()
2132 manager.attach_mock(mocked, 'attach_func')
2133 something(1)
2134 manager.assert_has_calls([call.attach_func(1)])
2135 something.assert_has_calls([call(1)])
2136 mocked.assert_has_calls([call(1)])
2137
2138 with mock.patch(f'{__name__}.Something', autospec=True) as mocked:
2139 manager = Mock()
2140 manager.attach_mock(mocked, 'attach_obj')
2141 obj = Something()
2142 obj.meth(1, 2, 3, d=4)
2143 manager.assert_has_calls([call.attach_obj(),
2144 call.attach_obj().meth(1, 2, 3, d=4)])
2145 obj.meth.assert_has_calls([call(1, 2, 3, d=4)])
2146 mocked.assert_has_calls([call(), call().meth(1, 2, 3, d=4)])
2147
2148
2149 def test_attribute_deletion(self):
2150 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
2151 NonCallableMock()):
2152 self.assertTrue(hasattr(mock, 'm'))
2153
2154 del mock.m
2155 self.assertFalse(hasattr(mock, 'm'))
2156
2157 del mock.f
2158 self.assertFalse(hasattr(mock, 'f'))
2159 self.assertRaises(AttributeError, getattr, mock, 'f')
2160
2161
2162 def test_mock_does_not_raise_on_repeated_attribute_deletion(self):
2163 # bpo-20239: Assigning and deleting twice an attribute raises.
2164 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
2165 NonCallableMock()):
2166 mock.foo = 3
2167 self.assertTrue(hasattr(mock, 'foo'))
2168 self.assertEqual(mock.foo, 3)
2169
2170 del mock.foo
2171 self.assertFalse(hasattr(mock, 'foo'))
2172
2173 mock.foo = 4
2174 self.assertTrue(hasattr(mock, 'foo'))
2175 self.assertEqual(mock.foo, 4)
2176
2177 del mock.foo
2178 self.assertFalse(hasattr(mock, 'foo'))
2179
2180
2181 def test_mock_raises_when_deleting_nonexistent_attribute(self):
2182 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
2183 NonCallableMock()):
2184 del mock.foo
2185 with self.assertRaises(AttributeError):
2186 del mock.foo
2187
2188
2189 def test_reset_mock_does_not_raise_on_attr_deletion(self):
2190 # bpo-31177: reset_mock should not raise AttributeError when attributes
2191 # were deleted in a mock instance
2192 mock = Mock()
2193 mock.child = True
2194 del mock.child
2195 mock.reset_mock()
2196 self.assertFalse(hasattr(mock, 'child'))
2197
2198
2199 def test_class_assignable(self):
2200 for mock in Mock(), MagicMock():
2201 self.assertNotIsInstance(mock, int)
2202
2203 mock.__class__ = int
2204 self.assertIsInstance(mock, int)
2205 mock.foo
2206
2207 def test_name_attribute_of_call(self):
2208 # bpo-35357: _Call should not disclose any attributes whose names
2209 # may clash with popular ones (such as ".name")
2210 self.assertIsNotNone(call.name)
2211 self.assertEqual(type(call.name), _Call)
2212 self.assertEqual(type(call.name().name), _Call)
2213
2214 def test_parent_attribute_of_call(self):
2215 # bpo-35357: _Call should not disclose any attributes whose names
2216 # may clash with popular ones (such as ".parent")
2217 self.assertIsNotNone(call.parent)
2218 self.assertEqual(type(call.parent), _Call)
2219 self.assertEqual(type(call.parent().parent), _Call)
2220
2221
2222 def test_parent_propagation_with_create_autospec(self):
2223
2224 def foo(a, b): pass
2225
2226 mock = Mock()
2227 mock.child = create_autospec(foo)
2228 mock.child(1, 2)
2229
2230 self.assertRaises(TypeError, mock.child, 1)
2231 self.assertEqual(mock.mock_calls, [call.child(1, 2)])
2232 self.assertIn('mock.child', repr(mock.child.mock))
2233
2234 def test_parent_propagation_with_autospec_attach_mock(self):
2235
2236 def foo(a, b): pass
2237
2238 parent = Mock()
2239 parent.attach_mock(create_autospec(foo, name='bar'), 'child')
2240 parent.child(1, 2)
2241
2242 self.assertRaises(TypeError, parent.child, 1)
2243 self.assertEqual(parent.child.mock_calls, [call.child(1, 2)])
2244 self.assertIn('mock.child', repr(parent.child.mock))
2245
2246
2247 def test_isinstance_under_settrace(self):
2248 # bpo-36593 : __class__ is not set for a class that has __class__
2249 # property defined when it's used with sys.settrace(trace) set.
2250 # Delete the module to force reimport with tracing function set
2251 # restore the old reference later since there are other tests that are
2252 # dependent on unittest.mock.patch. In testpatch.PatchTest
2253 # test_patch_dict_test_prefix and test_patch_test_prefix not restoring
2254 # causes the objects patched to go out of sync
2255
2256 old_patch = unittest.mock.patch
2257
2258 # Directly using __setattr__ on unittest.mock causes current imported
2259 # reference to be updated. Use a lambda so that during cleanup the
2260 # re-imported new reference is updated.
2261 self.addCleanup(lambda patch: setattr(unittest.mock, 'patch', patch),
2262 old_patch)
2263
2264 with patch.dict('sys.modules'):
2265 del sys.modules['unittest.mock']
2266
2267 # This trace will stop coverage being measured ;-)
2268 def trace(frame, event, arg): # pragma: no cover
2269 return trace
2270
2271 self.addCleanup(sys.settrace, sys.gettrace())
2272 sys.settrace(trace)
2273
2274 from unittest.mock import (
2275 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
2276 )
2277
2278 mocks = [
2279 Mock, MagicMock, NonCallableMock, NonCallableMagicMock, AsyncMock
2280 ]
2281
2282 for mock in mocks:
2283 obj = mock(spec=Something)
2284 self.assertIsInstance(obj, Something)
2285
2286 def test_bool_not_called_when_passing_spec_arg(self):
2287 class Something:
2288 def __init__(self):
2289 self.obj_with_bool_func = unittest.mock.MagicMock()
2290
2291 obj = Something()
2292 with unittest.mock.patch.object(obj, 'obj_with_bool_func', spec=object): pass
2293
2294 self.assertEqual(obj.obj_with_bool_func.__bool__.call_count, 0)
2295
2296 def test_misspelled_arguments(self):
2297 class Foo():
2298 one = 'one'
2299 # patch, patch.object and create_autospec need to check for misspelled
2300 # arguments explicitly and throw a RuntimError if found.
2301 with self.assertRaises(RuntimeError):
2302 with patch(f'{__name__}.Something.meth', autospect=True): pass
2303 with self.assertRaises(RuntimeError):
2304 with patch.object(Foo, 'one', autospect=True): pass
2305 with self.assertRaises(RuntimeError):
2306 with patch(f'{__name__}.Something.meth', auto_spec=True): pass
2307 with self.assertRaises(RuntimeError):
2308 with patch.object(Foo, 'one', auto_spec=True): pass
2309 with self.assertRaises(RuntimeError):
2310 with patch(f'{__name__}.Something.meth', set_spec=True): pass
2311 with self.assertRaises(RuntimeError):
2312 with patch.object(Foo, 'one', set_spec=True): pass
2313 with self.assertRaises(RuntimeError):
2314 m = create_autospec(Foo, set_spec=True)
2315 # patch.multiple, on the other hand, should flag misspelled arguments
2316 # through an AttributeError, when trying to find the keys from kwargs
2317 # as attributes on the target.
2318 with self.assertRaises(AttributeError):
2319 with patch.multiple(
2320 f'{__name__}.Something', meth=DEFAULT, autospect=True): pass
2321 with self.assertRaises(AttributeError):
2322 with patch.multiple(
2323 f'{__name__}.Something', meth=DEFAULT, auto_spec=True): pass
2324 with self.assertRaises(AttributeError):
2325 with patch.multiple(
2326 f'{__name__}.Something', meth=DEFAULT, set_spec=True): pass
2327
2328 with patch(f'{__name__}.Something.meth', unsafe=True, autospect=True):
2329 pass
2330 with patch.object(Foo, 'one', unsafe=True, autospect=True): pass
2331 with patch(f'{__name__}.Something.meth', unsafe=True, auto_spec=True):
2332 pass
2333 with patch.object(Foo, 'one', unsafe=True, auto_spec=True): pass
2334 with patch(f'{__name__}.Something.meth', unsafe=True, set_spec=True):
2335 pass
2336 with patch.object(Foo, 'one', unsafe=True, set_spec=True): pass
2337 m = create_autospec(Foo, set_spec=True, unsafe=True)
2338 with patch.multiple(
2339 f'{__name__}.Typos', autospect=True, set_spec=True, auto_spec=True):
2340 pass
2341
2342
2343 if __name__ == '__main__':
2344 unittest.main()