1import inspect
2import time
3import types
4import unittest
5
6from unittest.mock import (
7    call, _Call, create_autospec, MagicMock,
8    Mock, ANY, _CallList, patch, PropertyMock, _callable
9)
10
11from datetime import datetime
12from functools import partial
13
14class SomeClass(object):
15    def one(self, a, b):
16        pass
17    def two(self):
18        pass
19    def three(self, a=None):
20        pass
21
22
23
24class AnyTest(unittest.TestCase):
25
26    def test_any(self):
27        self.assertEqual(ANY, object())
28
29        mock = Mock()
30        mock(ANY)
31        mock.assert_called_with(ANY)
32
33        mock = Mock()
34        mock(foo=ANY)
35        mock.assert_called_with(foo=ANY)
36
37    def test_repr(self):
38        self.assertEqual(repr(ANY), '<ANY>')
39        self.assertEqual(str(ANY), '<ANY>')
40
41
42    def test_any_and_datetime(self):
43        mock = Mock()
44        mock(datetime.now(), foo=datetime.now())
45
46        mock.assert_called_with(ANY, foo=ANY)
47
48
49    def test_any_mock_calls_comparison_order(self):
50        mock = Mock()
51        d = datetime.now()
52        class Foo(object):
53            def __eq__(self, other):
54                return False
55            def __ne__(self, other):
56                return True
57
58        for d in datetime.now(), Foo():
59            mock.reset_mock()
60
61            mock(d, foo=d, bar=d)
62            mock.method(d, zinga=d, alpha=d)
63            mock().method(a1=d, z99=d)
64
65            expected = [
66                call(ANY, foo=ANY, bar=ANY),
67                call.method(ANY, zinga=ANY, alpha=ANY),
68                call(), call().method(a1=ANY, z99=ANY)
69            ]
70            self.assertEqual(expected, mock.mock_calls)
71            self.assertEqual(mock.mock_calls, expected)
72
73
74
75class CallTest(unittest.TestCase):
76
77    def test_call_with_call(self):
78        kall = _Call()
79        self.assertEqual(kall, _Call())
80        self.assertEqual(kall, _Call(('',)))
81        self.assertEqual(kall, _Call(((),)))
82        self.assertEqual(kall, _Call(({},)))
83        self.assertEqual(kall, _Call(('', ())))
84        self.assertEqual(kall, _Call(('', {})))
85        self.assertEqual(kall, _Call(('', (), {})))
86        self.assertEqual(kall, _Call(('foo',)))
87        self.assertEqual(kall, _Call(('bar', ())))
88        self.assertEqual(kall, _Call(('baz', {})))
89        self.assertEqual(kall, _Call(('spam', (), {})))
90
91        kall = _Call(((1, 2, 3),))
92        self.assertEqual(kall, _Call(((1, 2, 3),)))
93        self.assertEqual(kall, _Call(('', (1, 2, 3))))
94        self.assertEqual(kall, _Call(((1, 2, 3), {})))
95        self.assertEqual(kall, _Call(('', (1, 2, 3), {})))
96
97        kall = _Call(((1, 2, 4),))
98        self.assertNotEqual(kall, _Call(('', (1, 2, 3))))
99        self.assertNotEqual(kall, _Call(('', (1, 2, 3), {})))
100
101        kall = _Call(('foo', (1, 2, 4),))
102        self.assertNotEqual(kall, _Call(('', (1, 2, 4))))
103        self.assertNotEqual(kall, _Call(('', (1, 2, 4), {})))
104        self.assertNotEqual(kall, _Call(('bar', (1, 2, 4))))
105        self.assertNotEqual(kall, _Call(('bar', (1, 2, 4), {})))
106
107        kall = _Call(({'a': 3},))
108        self.assertEqual(kall, _Call(('', (), {'a': 3})))
109        self.assertEqual(kall, _Call(('', {'a': 3})))
110        self.assertEqual(kall, _Call(((), {'a': 3})))
111        self.assertEqual(kall, _Call(({'a': 3},)))
112
113
114    def test_empty__Call(self):
115        args = _Call()
116
117        self.assertEqual(args, ())
118        self.assertEqual(args, ('foo',))
119        self.assertEqual(args, ((),))
120        self.assertEqual(args, ('foo', ()))
121        self.assertEqual(args, ('foo',(), {}))
122        self.assertEqual(args, ('foo', {}))
123        self.assertEqual(args, ({},))
124
125
126    def test_named_empty_call(self):
127        args = _Call(('foo', (), {}))
128
129        self.assertEqual(args, ('foo',))
130        self.assertEqual(args, ('foo', ()))
131        self.assertEqual(args, ('foo',(), {}))
132        self.assertEqual(args, ('foo', {}))
133
134        self.assertNotEqual(args, ((),))
135        self.assertNotEqual(args, ())
136        self.assertNotEqual(args, ({},))
137        self.assertNotEqual(args, ('bar',))
138        self.assertNotEqual(args, ('bar', ()))
139        self.assertNotEqual(args, ('bar', {}))
140
141
142    def test_call_with_args(self):
143        args = _Call(((1, 2, 3), {}))
144
145        self.assertEqual(args, ((1, 2, 3),))
146        self.assertEqual(args, ('foo', (1, 2, 3)))
147        self.assertEqual(args, ('foo', (1, 2, 3), {}))
148        self.assertEqual(args, ((1, 2, 3), {}))
149
150
151    def test_named_call_with_args(self):
152        args = _Call(('foo', (1, 2, 3), {}))
153
154        self.assertEqual(args, ('foo', (1, 2, 3)))
155        self.assertEqual(args, ('foo', (1, 2, 3), {}))
156
157        self.assertNotEqual(args, ((1, 2, 3),))
158        self.assertNotEqual(args, ((1, 2, 3), {}))
159
160
161    def test_call_with_kwargs(self):
162        args = _Call(((), dict(a=3, b=4)))
163
164        self.assertEqual(args, (dict(a=3, b=4),))
165        self.assertEqual(args, ('foo', dict(a=3, b=4)))
166        self.assertEqual(args, ('foo', (), dict(a=3, b=4)))
167        self.assertEqual(args, ((), dict(a=3, b=4)))
168
169
170    def test_named_call_with_kwargs(self):
171        args = _Call(('foo', (), dict(a=3, b=4)))
172
173        self.assertEqual(args, ('foo', dict(a=3, b=4)))
174        self.assertEqual(args, ('foo', (), dict(a=3, b=4)))
175
176        self.assertNotEqual(args, (dict(a=3, b=4),))
177        self.assertNotEqual(args, ((), dict(a=3, b=4)))
178
179
180    def test_call_with_args_call_empty_name(self):
181        args = _Call(((1, 2, 3), {}))
182        self.assertEqual(args, call(1, 2, 3))
183        self.assertEqual(call(1, 2, 3), args)
184        self.assertIn(call(1, 2, 3), [args])
185
186
187    def test_call_ne(self):
188        self.assertNotEqual(_Call(((1, 2, 3),)), call(1, 2))
189        self.assertFalse(_Call(((1, 2, 3),)) != call(1, 2, 3))
190        self.assertTrue(_Call(((1, 2), {})) != call(1, 2, 3))
191
192
193    def test_call_non_tuples(self):
194        kall = _Call(((1, 2, 3),))
195        for value in 1, None, self, int:
196            self.assertNotEqual(kall, value)
197            self.assertFalse(kall == value)
198
199
200    def test_repr(self):
201        self.assertEqual(repr(_Call()), 'call()')
202        self.assertEqual(repr(_Call(('foo',))), 'call.foo()')
203
204        self.assertEqual(repr(_Call(((1, 2, 3), {'a': 'b'}))),
205                         "call(1, 2, 3, a='b')")
206        self.assertEqual(repr(_Call(('bar', (1, 2, 3), {'a': 'b'}))),
207                         "call.bar(1, 2, 3, a='b')")
208
209        self.assertEqual(repr(call), 'call')
210        self.assertEqual(str(call), 'call')
211
212        self.assertEqual(repr(call()), 'call()')
213        self.assertEqual(repr(call(1)), 'call(1)')
214        self.assertEqual(repr(call(zz='thing')), "call(zz='thing')")
215
216        self.assertEqual(repr(call().foo), 'call().foo')
217        self.assertEqual(repr(call(1).foo.bar(a=3).bing),
218                         'call().foo.bar().bing')
219        self.assertEqual(
220            repr(call().foo(1, 2, a=3)),
221            "call().foo(1, 2, a=3)"
222        )
223        self.assertEqual(repr(call()()), "call()()")
224        self.assertEqual(repr(call(1)(2)), "call()(2)")
225        self.assertEqual(
226            repr(call()().bar().baz.beep(1)),
227            "call()().bar().baz.beep(1)"
228        )
229
230
231    def test_call(self):
232        self.assertEqual(call(), ('', (), {}))
233        self.assertEqual(call('foo', 'bar', one=3, two=4),
234                         ('', ('foo', 'bar'), {'one': 3, 'two': 4}))
235
236        mock = Mock()
237        mock(1, 2, 3)
238        mock(a=3, b=6)
239        self.assertEqual(mock.call_args_list,
240                         [call(1, 2, 3), call(a=3, b=6)])
241
242    def test_attribute_call(self):
243        self.assertEqual(call.foo(1), ('foo', (1,), {}))
244        self.assertEqual(call.bar.baz(fish='eggs'),
245                         ('bar.baz', (), {'fish': 'eggs'}))
246
247        mock = Mock()
248        mock.foo(1, 2 ,3)
249        mock.bar.baz(a=3, b=6)
250        self.assertEqual(mock.method_calls,
251                         [call.foo(1, 2, 3), call.bar.baz(a=3, b=6)])
252
253
254    def test_extended_call(self):
255        result = call(1).foo(2).bar(3, a=4)
256        self.assertEqual(result, ('().foo().bar', (3,), dict(a=4)))
257
258        mock = MagicMock()
259        mock(1, 2, a=3, b=4)
260        self.assertEqual(mock.call_args, call(1, 2, a=3, b=4))
261        self.assertNotEqual(mock.call_args, call(1, 2, 3))
262
263        self.assertEqual(mock.call_args_list, [call(1, 2, a=3, b=4)])
264        self.assertEqual(mock.mock_calls, [call(1, 2, a=3, b=4)])
265
266        mock = MagicMock()
267        mock.foo(1).bar()().baz.beep(a=6)
268
269        last_call = call.foo(1).bar()().baz.beep(a=6)
270        self.assertEqual(mock.mock_calls[-1], last_call)
271        self.assertEqual(mock.mock_calls, last_call.call_list())
272
273
274    def test_extended_not_equal(self):
275        a = call(x=1).foo
276        b = call(x=2).foo
277        self.assertEqual(a, a)
278        self.assertEqual(b, b)
279        self.assertNotEqual(a, b)
280
281
282    def test_nested_calls_not_equal(self):
283        a = call(x=1).foo().bar
284        b = call(x=2).foo().bar
285        self.assertEqual(a, a)
286        self.assertEqual(b, b)
287        self.assertNotEqual(a, b)
288
289
290    def test_call_list(self):
291        mock = MagicMock()
292        mock(1)
293        self.assertEqual(call(1).call_list(), mock.mock_calls)
294
295        mock = MagicMock()
296        mock(1).method(2)
297        self.assertEqual(call(1).method(2).call_list(),
298                         mock.mock_calls)
299
300        mock = MagicMock()
301        mock(1).method(2)(3)
302        self.assertEqual(call(1).method(2)(3).call_list(),
303                         mock.mock_calls)
304
305        mock = MagicMock()
306        int(mock(1).method(2)(3).foo.bar.baz(4)(5))
307        kall = call(1).method(2)(3).foo.bar.baz(4)(5).__int__()
308        self.assertEqual(kall.call_list(), mock.mock_calls)
309
310
311    def test_call_any(self):
312        self.assertEqual(call, ANY)
313
314        m = MagicMock()
315        int(m)
316        self.assertEqual(m.mock_calls, [ANY])
317        self.assertEqual([ANY], m.mock_calls)
318
319
320    def test_two_args_call(self):
321        args = _Call(((1, 2), {'a': 3}), two=True)
322        self.assertEqual(len(args), 2)
323        self.assertEqual(args[0], (1, 2))
324        self.assertEqual(args[1], {'a': 3})
325
326        other_args = _Call(((1, 2), {'a': 3}))
327        self.assertEqual(args, other_args)
328
329    def test_call_with_name(self):
330        self.assertEqual(_Call((), 'foo')[0], 'foo')
331        self.assertEqual(_Call((('bar', 'barz'),),)[0], '')
332        self.assertEqual(_Call((('bar', 'barz'), {'hello': 'world'}),)[0], '')
333
334
335class SpecSignatureTest(unittest.TestCase):
336
337    def _check_someclass_mock(self, mock):
338        self.assertRaises(AttributeError, getattr, mock, 'foo')
339        mock.one(1, 2)
340        mock.one.assert_called_with(1, 2)
341        self.assertRaises(AssertionError,
342                          mock.one.assert_called_with, 3, 4)
343        self.assertRaises(TypeError, mock.one, 1)
344
345        mock.two()
346        mock.two.assert_called_with()
347        self.assertRaises(AssertionError,
348                          mock.two.assert_called_with, 3)
349        self.assertRaises(TypeError, mock.two, 1)
350
351        mock.three()
352        mock.three.assert_called_with()
353        self.assertRaises(AssertionError,
354                          mock.three.assert_called_with, 3)
355        self.assertRaises(TypeError, mock.three, 3, 2)
356
357        mock.three(1)
358        mock.three.assert_called_with(1)
359
360        mock.three(a=1)
361        mock.three.assert_called_with(a=1)
362
363
364    def test_basic(self):
365        mock = create_autospec(SomeClass)
366        self._check_someclass_mock(mock)
367        mock = create_autospec(SomeClass())
368        self._check_someclass_mock(mock)
369
370
371    def test_create_autospec_return_value(self):
372        def f():
373            pass
374        mock = create_autospec(f, return_value='foo')
375        self.assertEqual(mock(), 'foo')
376
377        class Foo(object):
378            pass
379
380        mock = create_autospec(Foo, return_value='foo')
381        self.assertEqual(mock(), 'foo')
382
383
384    def test_autospec_reset_mock(self):
385        m = create_autospec(int)
386        int(m)
387        m.reset_mock()
388        self.assertEqual(m.__int__.call_count, 0)
389
390
391    def test_mocking_unbound_methods(self):
392        class Foo(object):
393            def foo(self, foo):
394                pass
395        p = patch.object(Foo, 'foo')
396        mock_foo = p.start()
397        Foo().foo(1)
398
399        mock_foo.assert_called_with(1)
400
401
402    def test_create_autospec_unbound_methods(self):
403        # see mock issue 128
404        # this is expected to fail until the issue is fixed
405        return
406        class Foo(object):
407            def foo(self):
408                pass
409
410        klass = create_autospec(Foo)
411        instance = klass()
412        self.assertRaises(TypeError, instance.foo, 1)
413
414        # Note: no type checking on the "self" parameter
415        klass.foo(1)
416        klass.foo.assert_called_with(1)
417        self.assertRaises(TypeError, klass.foo)
418
419
420    def test_create_autospec_keyword_arguments(self):
421        class Foo(object):
422            a = 3
423        m = create_autospec(Foo, a='3')
424        self.assertEqual(m.a, '3')
425
426
427    def test_create_autospec_keyword_only_arguments(self):
428        def foo(a, *, b=None):
429            pass
430
431        m = create_autospec(foo)
432        m(1)
433        m.assert_called_with(1)
434        self.assertRaises(TypeError, m, 1, 2)
435
436        m(2, b=3)
437        m.assert_called_with(2, b=3)
438
439
440    def test_function_as_instance_attribute(self):
441        obj = SomeClass()
442        def f(a):
443            pass
444        obj.f = f
445
446        mock = create_autospec(obj)
447        mock.f('bing')
448        mock.f.assert_called_with('bing')
449
450
451    def test_spec_as_list(self):
452        # because spec as a list of strings in the mock constructor means
453        # something very different we treat a list instance as the type.
454        mock = create_autospec([])
455        mock.append('foo')
456        mock.append.assert_called_with('foo')
457
458        self.assertRaises(AttributeError, getattr, mock, 'foo')
459
460        class Foo(object):
461            foo = []
462
463        mock = create_autospec(Foo)
464        mock.foo.append(3)
465        mock.foo.append.assert_called_with(3)
466        self.assertRaises(AttributeError, getattr, mock.foo, 'foo')
467
468
469    def test_attributes(self):
470        class Sub(SomeClass):
471            attr = SomeClass()
472
473        sub_mock = create_autospec(Sub)
474
475        for mock in (sub_mock, sub_mock.attr):
476            self._check_someclass_mock(mock)
477
478
479    def test_builtin_functions_types(self):
480        # we could replace builtin functions / methods with a function
481        # with *args / **kwargs signature. Using the builtin method type
482        # as a spec seems to work fairly well though.
483        class BuiltinSubclass(list):
484            def bar(self, arg):
485                pass
486            sorted = sorted
487            attr = {}
488
489        mock = create_autospec(BuiltinSubclass)
490        mock.append(3)
491        mock.append.assert_called_with(3)
492        self.assertRaises(AttributeError, getattr, mock.append, 'foo')
493
494        mock.bar('foo')
495        mock.bar.assert_called_with('foo')
496        self.assertRaises(TypeError, mock.bar, 'foo', 'bar')
497        self.assertRaises(AttributeError, getattr, mock.bar, 'foo')
498
499        mock.sorted([1, 2])
500        mock.sorted.assert_called_with([1, 2])
501        self.assertRaises(AttributeError, getattr, mock.sorted, 'foo')
502
503        mock.attr.pop(3)
504        mock.attr.pop.assert_called_with(3)
505        self.assertRaises(AttributeError, getattr, mock.attr, 'foo')
506
507
508    def test_method_calls(self):
509        class Sub(SomeClass):
510            attr = SomeClass()
511
512        mock = create_autospec(Sub)
513        mock.one(1, 2)
514        mock.two()
515        mock.three(3)
516
517        expected = [call.one(1, 2), call.two(), call.three(3)]
518        self.assertEqual(mock.method_calls, expected)
519
520        mock.attr.one(1, 2)
521        mock.attr.two()
522        mock.attr.three(3)
523
524        expected.extend(
525            [call.attr.one(1, 2), call.attr.two(), call.attr.three(3)]
526        )
527        self.assertEqual(mock.method_calls, expected)
528
529
530    def test_magic_methods(self):
531        class BuiltinSubclass(list):
532            attr = {}
533
534        mock = create_autospec(BuiltinSubclass)
535        self.assertEqual(list(mock), [])
536        self.assertRaises(TypeError, int, mock)
537        self.assertRaises(TypeError, int, mock.attr)
538        self.assertEqual(list(mock), [])
539
540        self.assertIsInstance(mock['foo'], MagicMock)
541        self.assertIsInstance(mock.attr['foo'], MagicMock)
542
543
544    def test_spec_set(self):
545        class Sub(SomeClass):
546            attr = SomeClass()
547
548        for spec in (Sub, Sub()):
549            mock = create_autospec(spec, spec_set=True)
550            self._check_someclass_mock(mock)
551
552            self.assertRaises(AttributeError, setattr, mock, 'foo', 'bar')
553            self.assertRaises(AttributeError, setattr, mock.attr, 'foo', 'bar')
554
555
556    def test_descriptors(self):
557        class Foo(object):
558            @classmethod
559            def f(cls, a, b):
560                pass
561            @staticmethod
562            def g(a, b):
563                pass
564
565        class Bar(Foo):
566            pass
567
568        class Baz(SomeClass, Bar):
569            pass
570
571        for spec in (Foo, Foo(), Bar, Bar(), Baz, Baz()):
572            mock = create_autospec(spec)
573            mock.f(1, 2)
574            mock.f.assert_called_once_with(1, 2)
575
576            mock.g(3, 4)
577            mock.g.assert_called_once_with(3, 4)
578
579
580    def test_recursive(self):
581        class A(object):
582            def a(self):
583                pass
584            foo = 'foo bar baz'
585            bar = foo
586
587        A.B = A
588        mock = create_autospec(A)
589
590        mock()
591        self.assertFalse(mock.B.called)
592
593        mock.a()
594        mock.B.a()
595        self.assertEqual(mock.method_calls, [call.a(), call.B.a()])
596
597        self.assertIs(A.foo, A.bar)
598        self.assertIsNot(mock.foo, mock.bar)
599        mock.foo.lower()
600        self.assertRaises(AssertionError, mock.bar.lower.assert_called_with)
601
602
603    def test_spec_inheritance_for_classes(self):
604        class Foo(object):
605            def a(self, x):
606                pass
607            class Bar(object):
608                def f(self, y):
609                    pass
610
611        class_mock = create_autospec(Foo)
612
613        self.assertIsNot(class_mock, class_mock())
614
615        for this_mock in class_mock, class_mock():
616            this_mock.a(x=5)
617            this_mock.a.assert_called_with(x=5)
618            this_mock.a.assert_called_with(5)
619            self.assertRaises(TypeError, this_mock.a, 'foo', 'bar')
620            self.assertRaises(AttributeError, getattr, this_mock, 'b')
621
622        instance_mock = create_autospec(Foo())
623        instance_mock.a(5)
624        instance_mock.a.assert_called_with(5)
625        instance_mock.a.assert_called_with(x=5)
626        self.assertRaises(TypeError, instance_mock.a, 'foo', 'bar')
627        self.assertRaises(AttributeError, getattr, instance_mock, 'b')
628
629        # The return value isn't isn't callable
630        self.assertRaises(TypeError, instance_mock)
631
632        instance_mock.Bar.f(6)
633        instance_mock.Bar.f.assert_called_with(6)
634        instance_mock.Bar.f.assert_called_with(y=6)
635        self.assertRaises(AttributeError, getattr, instance_mock.Bar, 'g')
636
637        instance_mock.Bar().f(6)
638        instance_mock.Bar().f.assert_called_with(6)
639        instance_mock.Bar().f.assert_called_with(y=6)
640        self.assertRaises(AttributeError, getattr, instance_mock.Bar(), 'g')
641
642
643    def test_inherit(self):
644        class Foo(object):
645            a = 3
646
647        Foo.Foo = Foo
648
649        # class
650        mock = create_autospec(Foo)
651        instance = mock()
652        self.assertRaises(AttributeError, getattr, instance, 'b')
653
654        attr_instance = mock.Foo()
655        self.assertRaises(AttributeError, getattr, attr_instance, 'b')
656
657        # instance
658        mock = create_autospec(Foo())
659        self.assertRaises(AttributeError, getattr, mock, 'b')
660        self.assertRaises(TypeError, mock)
661
662        # attribute instance
663        call_result = mock.Foo()
664        self.assertRaises(AttributeError, getattr, call_result, 'b')
665
666
667    def test_builtins(self):
668        # used to fail with infinite recursion
669        create_autospec(1)
670
671        create_autospec(int)
672        create_autospec('foo')
673        create_autospec(str)
674        create_autospec({})
675        create_autospec(dict)
676        create_autospec([])
677        create_autospec(list)
678        create_autospec(set())
679        create_autospec(set)
680        create_autospec(1.0)
681        create_autospec(float)
682        create_autospec(1j)
683        create_autospec(complex)
684        create_autospec(False)
685        create_autospec(True)
686
687
688    def test_function(self):
689        def f(a, b):
690            pass
691
692        mock = create_autospec(f)
693        self.assertRaises(TypeError, mock)
694        mock(1, 2)
695        mock.assert_called_with(1, 2)
696        mock.assert_called_with(1, b=2)
697        mock.assert_called_with(a=1, b=2)
698
699        f.f = f
700        mock = create_autospec(f)
701        self.assertRaises(TypeError, mock.f)
702        mock.f(3, 4)
703        mock.f.assert_called_with(3, 4)
704        mock.f.assert_called_with(a=3, b=4)
705
706
707    def test_skip_attributeerrors(self):
708        class Raiser(object):
709            def __get__(self, obj, type=None):
710                if obj is None:
711                    raise AttributeError('Can only be accessed via an instance')
712
713        class RaiserClass(object):
714            raiser = Raiser()
715
716            @staticmethod
717            def existing(a, b):
718                return a + b
719
720        s = create_autospec(RaiserClass)
721        self.assertRaises(TypeError, lambda x: s.existing(1, 2, 3))
722        s.existing(1, 2)
723        self.assertRaises(AttributeError, lambda: s.nonexisting)
724
725        # check we can fetch the raiser attribute and it has no spec
726        obj = s.raiser
727        obj.foo, obj.bar
728
729
730    def test_signature_class(self):
731        class Foo(object):
732            def __init__(self, a, b=3):
733                pass
734
735        mock = create_autospec(Foo)
736
737        self.assertRaises(TypeError, mock)
738        mock(1)
739        mock.assert_called_once_with(1)
740        mock.assert_called_once_with(a=1)
741        self.assertRaises(AssertionError, mock.assert_called_once_with, 2)
742
743        mock(4, 5)
744        mock.assert_called_with(4, 5)
745        mock.assert_called_with(a=4, b=5)
746        self.assertRaises(AssertionError, mock.assert_called_with, a=5, b=4)
747
748
749    def test_class_with_no_init(self):
750        # this used to raise an exception
751        # due to trying to get a signature from object.__init__
752        class Foo(object):
753            pass
754        create_autospec(Foo)
755
756
757    def test_signature_callable(self):
758        class Callable(object):
759            def __init__(self, x, y):
760                pass
761            def __call__(self, a):
762                pass
763
764        mock = create_autospec(Callable)
765        mock(1, 2)
766        mock.assert_called_once_with(1, 2)
767        mock.assert_called_once_with(x=1, y=2)
768        self.assertRaises(TypeError, mock, 'a')
769
770        instance = mock(1, 2)
771        self.assertRaises(TypeError, instance)
772        instance(a='a')
773        instance.assert_called_once_with('a')
774        instance.assert_called_once_with(a='a')
775        instance('a')
776        instance.assert_called_with('a')
777        instance.assert_called_with(a='a')
778
779        mock = create_autospec(Callable(1, 2))
780        mock(a='a')
781        mock.assert_called_once_with(a='a')
782        self.assertRaises(TypeError, mock)
783        mock('a')
784        mock.assert_called_with('a')
785
786
787    def test_signature_noncallable(self):
788        class NonCallable(object):
789            def __init__(self):
790                pass
791
792        mock = create_autospec(NonCallable)
793        instance = mock()
794        mock.assert_called_once_with()
795        self.assertRaises(TypeError, mock, 'a')
796        self.assertRaises(TypeError, instance)
797        self.assertRaises(TypeError, instance, 'a')
798
799        mock = create_autospec(NonCallable())
800        self.assertRaises(TypeError, mock)
801        self.assertRaises(TypeError, mock, 'a')
802
803
804    def test_create_autospec_none(self):
805        class Foo(object):
806            bar = None
807
808        mock = create_autospec(Foo)
809        none = mock.bar
810        self.assertNotIsInstance(none, type(None))
811
812        none.foo()
813        none.foo.assert_called_once_with()
814
815
816    def test_autospec_functions_with_self_in_odd_place(self):
817        class Foo(object):
818            def f(a, self):
819                pass
820
821        a = create_autospec(Foo)
822        a.f(10)
823        a.f.assert_called_with(10)
824        a.f.assert_called_with(self=10)
825        a.f(self=10)
826        a.f.assert_called_with(10)
827        a.f.assert_called_with(self=10)
828
829
830    def test_autospec_data_descriptor(self):
831        class Descriptor(object):
832            def __init__(self, value):
833                self.value = value
834
835            def __get__(self, obj, cls=None):
836                if obj is None:
837                    return self
838                return self.value
839
840            def __set__(self, obj, value):
841                pass
842
843        class MyProperty(property):
844            pass
845
846        class Foo(object):
847            __slots__ = ['slot']
848
849            @property
850            def prop(self):
851                return 3
852
853            @MyProperty
854            def subprop(self):
855                return 4
856
857            desc = Descriptor(42)
858
859        foo = create_autospec(Foo)
860
861        def check_data_descriptor(mock_attr):
862            # Data descriptors don't have a spec.
863            self.assertIsInstance(mock_attr, MagicMock)
864            mock_attr(1, 2, 3)
865            mock_attr.abc(4, 5, 6)
866            mock_attr.assert_called_once_with(1, 2, 3)
867            mock_attr.abc.assert_called_once_with(4, 5, 6)
868
869        # property
870        check_data_descriptor(foo.prop)
871        # property subclass
872        check_data_descriptor(foo.subprop)
873        # class __slot__
874        check_data_descriptor(foo.slot)
875        # plain data descriptor
876        check_data_descriptor(foo.desc)
877
878
879    def test_autospec_on_bound_builtin_function(self):
880        meth = types.MethodType(time.ctime, time.time())
881        self.assertIsInstance(meth(), str)
882        mocked = create_autospec(meth)
883
884        # no signature, so no spec to check against
885        mocked()
886        mocked.assert_called_once_with()
887        mocked.reset_mock()
888        mocked(4, 5, 6)
889        mocked.assert_called_once_with(4, 5, 6)
890
891
892    def test_autospec_getattr_partial_function(self):
893        # bpo-32153 : getattr returning partial functions without
894        # __name__ should not create AttributeError in create_autospec
895        class Foo:
896
897            def __getattr__(self, attribute):
898                return partial(lambda name: name, attribute)
899
900        proxy = Foo()
901        autospec = create_autospec(proxy)
902        self.assertFalse(hasattr(autospec, '__name__'))
903
904
905    def test_spec_inspect_signature(self):
906
907        def myfunc(x, y):
908            pass
909
910        mock = create_autospec(myfunc)
911        mock(1, 2)
912        mock(x=1, y=2)
913
914        self.assertEqual(inspect.getfullargspec(mock), inspect.getfullargspec(myfunc))
915        self.assertEqual(mock.mock_calls, [call(1, 2), call(x=1, y=2)])
916        self.assertRaises(TypeError, mock, 1)
917
918
919    def test_spec_inspect_signature_annotations(self):
920
921        def foo(a: int, b: int=10, *, c:int) -> int:
922            return a + b + c
923
924        mock = create_autospec(foo)
925        mock(1, 2, c=3)
926        mock(1, c=3)
927
928        self.assertEqual(inspect.getfullargspec(mock), inspect.getfullargspec(foo))
929        self.assertEqual(mock.mock_calls, [call(1, 2, c=3), call(1, c=3)])
930        self.assertRaises(TypeError, mock, 1)
931        self.assertRaises(TypeError, mock, 1, 2, 3, c=4)
932
933
934class TestCallList(unittest.TestCase):
935
936    def test_args_list_contains_call_list(self):
937        mock = Mock()
938        self.assertIsInstance(mock.call_args_list, _CallList)
939
940        mock(1, 2)
941        mock(a=3)
942        mock(3, 4)
943        mock(b=6)
944
945        for kall in call(1, 2), call(a=3), call(3, 4), call(b=6):
946            self.assertIn(kall, mock.call_args_list)
947
948        calls = [call(a=3), call(3, 4)]
949        self.assertIn(calls, mock.call_args_list)
950        calls = [call(1, 2), call(a=3)]
951        self.assertIn(calls, mock.call_args_list)
952        calls = [call(3, 4), call(b=6)]
953        self.assertIn(calls, mock.call_args_list)
954        calls = [call(3, 4)]
955        self.assertIn(calls, mock.call_args_list)
956
957        self.assertNotIn(call('fish'), mock.call_args_list)
958        self.assertNotIn([call('fish')], mock.call_args_list)
959
960
961    def test_call_list_str(self):
962        mock = Mock()
963        mock(1, 2)
964        mock.foo(a=3)
965        mock.foo.bar().baz('fish', cat='dog')
966
967        expected = (
968            "[call(1, 2),\n"
969            " call.foo(a=3),\n"
970            " call.foo.bar(),\n"
971            " call.foo.bar().baz('fish', cat='dog')]"
972        )
973        self.assertEqual(str(mock.mock_calls), expected)
974
975
976    def test_propertymock(self):
977        p = patch('%s.SomeClass.one' % __name__, new_callable=PropertyMock)
978        mock = p.start()
979        try:
980            SomeClass.one
981            mock.assert_called_once_with()
982
983            s = SomeClass()
984            s.one
985            mock.assert_called_with()
986            self.assertEqual(mock.mock_calls, [call(), call()])
987
988            s.one = 3
989            self.assertEqual(mock.mock_calls, [call(), call(), call(3)])
990        finally:
991            p.stop()
992
993
994    def test_propertymock_returnvalue(self):
995        m = MagicMock()
996        p = PropertyMock()
997        type(m).foo = p
998
999        returned = m.foo
1000        p.assert_called_once_with()
1001        self.assertIsInstance(returned, MagicMock)
1002        self.assertNotIsInstance(returned, PropertyMock)
1003
1004
1005class TestCallablePredicate(unittest.TestCase):
1006
1007    def test_type(self):
1008        for obj in [str, bytes, int, list, tuple, SomeClass]:
1009            self.assertTrue(_callable(obj))
1010
1011    def test_call_magic_method(self):
1012        class Callable:
1013            def __call__(self):
1014                pass
1015        instance = Callable()
1016        self.assertTrue(_callable(instance))
1017
1018    def test_staticmethod(self):
1019        class WithStaticMethod:
1020            @staticmethod
1021            def staticfunc():
1022                pass
1023        self.assertTrue(_callable(WithStaticMethod.staticfunc))
1024
1025    def test_non_callable_staticmethod(self):
1026        class BadStaticMethod:
1027            not_callable = staticmethod(None)
1028        self.assertFalse(_callable(BadStaticMethod.not_callable))
1029
1030    def test_classmethod(self):
1031        class WithClassMethod:
1032            @classmethod
1033            def classfunc(cls):
1034                pass
1035        self.assertTrue(_callable(WithClassMethod.classfunc))
1036
1037    def test_non_callable_classmethod(self):
1038        class BadClassMethod:
1039            not_callable = classmethod(None)
1040        self.assertFalse(_callable(BadClassMethod.not_callable))
1041
1042
1043if __name__ == '__main__':
1044    unittest.main()
1045