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