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