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