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