blob: 8b2e96d1fc1c41ce79cac7e18335068015af417c [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001import unittest
2
3from unittest.mock import (
4 call, _Call, create_autospec, MagicMock,
5 Mock, ANY, _CallList, patch, PropertyMock
6)
7
8from datetime import datetime
9
10class SomeClass(object):
11 def one(self, a, b):
12 pass
13 def two(self):
14 pass
15 def three(self, a=None):
16 pass
17
18
19
20class AnyTest(unittest.TestCase):
21
22 def test_any(self):
23 self.assertEqual(ANY, object())
24
25 mock = Mock()
26 mock(ANY)
27 mock.assert_called_with(ANY)
28
29 mock = Mock()
30 mock(foo=ANY)
31 mock.assert_called_with(foo=ANY)
32
33 def test_repr(self):
34 self.assertEqual(repr(ANY), '<ANY>')
35 self.assertEqual(str(ANY), '<ANY>')
36
37
38 def test_any_and_datetime(self):
39 mock = Mock()
40 mock(datetime.now(), foo=datetime.now())
41
42 mock.assert_called_with(ANY, foo=ANY)
43
44
45 def test_any_mock_calls_comparison_order(self):
46 mock = Mock()
47 d = datetime.now()
48 class Foo(object):
49 def __eq__(self, other):
50 return False
51 def __ne__(self, other):
52 return True
53
54 for d in datetime.now(), Foo():
55 mock.reset_mock()
56
57 mock(d, foo=d, bar=d)
58 mock.method(d, zinga=d, alpha=d)
59 mock().method(a1=d, z99=d)
60
61 expected = [
62 call(ANY, foo=ANY, bar=ANY),
63 call.method(ANY, zinga=ANY, alpha=ANY),
64 call(), call().method(a1=ANY, z99=ANY)
65 ]
66 self.assertEqual(expected, mock.mock_calls)
67 self.assertEqual(mock.mock_calls, expected)
68
69
70
71class CallTest(unittest.TestCase):
72
73 def test_call_with_call(self):
74 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(('', {})))
81 self.assertEqual(kall, _Call(('', (), {})))
82 self.assertEqual(kall, _Call(('foo',)))
83 self.assertEqual(kall, _Call(('bar', ())))
84 self.assertEqual(kall, _Call(('baz', {})))
85 self.assertEqual(kall, _Call(('spam', (), {})))
86
87 kall = _Call(((1, 2, 3),))
88 self.assertEqual(kall, _Call(((1, 2, 3),)))
89 self.assertEqual(kall, _Call(('', (1, 2, 3))))
90 self.assertEqual(kall, _Call(((1, 2, 3), {})))
91 self.assertEqual(kall, _Call(('', (1, 2, 3), {})))
92
93 kall = _Call(((1, 2, 4),))
94 self.assertNotEqual(kall, _Call(('', (1, 2, 3))))
95 self.assertNotEqual(kall, _Call(('', (1, 2, 3), {})))
96
97 kall = _Call(('foo', (1, 2, 4),))
98 self.assertNotEqual(kall, _Call(('', (1, 2, 4))))
99 self.assertNotEqual(kall, _Call(('', (1, 2, 4), {})))
100 self.assertNotEqual(kall, _Call(('bar', (1, 2, 4))))
101 self.assertNotEqual(kall, _Call(('bar', (1, 2, 4), {})))
102
103 kall = _Call(({'a': 3},))
104 self.assertEqual(kall, _Call(('', (), {'a': 3})))
105 self.assertEqual(kall, _Call(('', {'a': 3})))
106 self.assertEqual(kall, _Call(((), {'a': 3})))
107 self.assertEqual(kall, _Call(({'a': 3},)))
108
109
110 def test_empty__Call(self):
111 args = _Call()
112
113 self.assertEqual(args, ())
114 self.assertEqual(args, ('foo',))
115 self.assertEqual(args, ((),))
116 self.assertEqual(args, ('foo', ()))
117 self.assertEqual(args, ('foo',(), {}))
118 self.assertEqual(args, ('foo', {}))
119 self.assertEqual(args, ({},))
120
121
122 def test_named_empty_call(self):
123 args = _Call(('foo', (), {}))
124
125 self.assertEqual(args, ('foo',))
126 self.assertEqual(args, ('foo', ()))
127 self.assertEqual(args, ('foo',(), {}))
128 self.assertEqual(args, ('foo', {}))
129
130 self.assertNotEqual(args, ((),))
131 self.assertNotEqual(args, ())
132 self.assertNotEqual(args, ({},))
133 self.assertNotEqual(args, ('bar',))
134 self.assertNotEqual(args, ('bar', ()))
135 self.assertNotEqual(args, ('bar', {}))
136
137
138 def test_call_with_args(self):
139 args = _Call(((1, 2, 3), {}))
140
141 self.assertEqual(args, ((1, 2, 3),))
142 self.assertEqual(args, ('foo', (1, 2, 3)))
143 self.assertEqual(args, ('foo', (1, 2, 3), {}))
144 self.assertEqual(args, ((1, 2, 3), {}))
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
153 self.assertNotEqual(args, ((1, 2, 3),))
154 self.assertNotEqual(args, ((1, 2, 3), {}))
155
156
157 def test_call_with_kwargs(self):
158 args = _Call(((), dict(a=3, b=4)))
159
160 self.assertEqual(args, (dict(a=3, b=4),))
161 self.assertEqual(args, ('foo', dict(a=3, b=4)))
162 self.assertEqual(args, ('foo', (), dict(a=3, b=4)))
163 self.assertEqual(args, ((), dict(a=3, b=4)))
164
165
166 def test_named_call_with_kwargs(self):
167 args = _Call(('foo', (), dict(a=3, b=4)))
168
169 self.assertEqual(args, ('foo', dict(a=3, b=4)))
170 self.assertEqual(args, ('foo', (), dict(a=3, b=4)))
171
172 self.assertNotEqual(args, (dict(a=3, b=4),))
173 self.assertNotEqual(args, ((), dict(a=3, b=4)))
174
175
176 def test_call_with_args_call_empty_name(self):
177 args = _Call(((1, 2, 3), {}))
178 self.assertEqual(args, call(1, 2, 3))
179 self.assertEqual(call(1, 2, 3), args)
180 self.assertTrue(call(1, 2, 3) in [args])
181
182
183 def test_call_ne(self):
184 self.assertNotEqual(_Call(((1, 2, 3),)), call(1, 2))
185 self.assertFalse(_Call(((1, 2, 3),)) != call(1, 2, 3))
186 self.assertTrue(_Call(((1, 2), {})) != call(1, 2, 3))
187
188
189 def test_call_non_tuples(self):
190 kall = _Call(((1, 2, 3),))
191 for value in 1, None, self, int:
192 self.assertNotEqual(kall, value)
193 self.assertFalse(kall == value)
194
195
196 def test_repr(self):
197 self.assertEqual(repr(_Call()), 'call()')
198 self.assertEqual(repr(_Call(('foo',))), 'call.foo()')
199
200 self.assertEqual(repr(_Call(((1, 2, 3), {'a': 'b'}))),
201 "call(1, 2, 3, a='b')")
202 self.assertEqual(repr(_Call(('bar', (1, 2, 3), {'a': 'b'}))),
203 "call.bar(1, 2, 3, a='b')")
204
205 self.assertEqual(repr(call), 'call')
206 self.assertEqual(str(call), 'call')
207
208 self.assertEqual(repr(call()), 'call()')
209 self.assertEqual(repr(call(1)), 'call(1)')
210 self.assertEqual(repr(call(zz='thing')), "call(zz='thing')")
211
212 self.assertEqual(repr(call().foo), 'call().foo')
213 self.assertEqual(repr(call(1).foo.bar(a=3).bing),
214 'call().foo.bar().bing')
215 self.assertEqual(
216 repr(call().foo(1, 2, a=3)),
217 "call().foo(1, 2, a=3)"
218 )
219 self.assertEqual(repr(call()()), "call()()")
220 self.assertEqual(repr(call(1)(2)), "call()(2)")
221 self.assertEqual(
222 repr(call()().bar().baz.beep(1)),
223 "call()().bar().baz.beep(1)"
224 )
225
226
227 def test_call(self):
228 self.assertEqual(call(), ('', (), {}))
229 self.assertEqual(call('foo', 'bar', one=3, two=4),
230 ('', ('foo', 'bar'), {'one': 3, 'two': 4}))
231
232 mock = Mock()
233 mock(1, 2, 3)
234 mock(a=3, b=6)
235 self.assertEqual(mock.call_args_list,
236 [call(1, 2, 3), call(a=3, b=6)])
237
238 def test_attribute_call(self):
239 self.assertEqual(call.foo(1), ('foo', (1,), {}))
240 self.assertEqual(call.bar.baz(fish='eggs'),
241 ('bar.baz', (), {'fish': 'eggs'}))
242
243 mock = Mock()
244 mock.foo(1, 2 ,3)
245 mock.bar.baz(a=3, b=6)
246 self.assertEqual(mock.method_calls,
247 [call.foo(1, 2, 3), call.bar.baz(a=3, b=6)])
248
249
250 def test_extended_call(self):
251 result = call(1).foo(2).bar(3, a=4)
252 self.assertEqual(result, ('().foo().bar', (3,), dict(a=4)))
253
254 mock = MagicMock()
255 mock(1, 2, a=3, b=4)
256 self.assertEqual(mock.call_args, call(1, 2, a=3, b=4))
257 self.assertNotEqual(mock.call_args, call(1, 2, 3))
258
259 self.assertEqual(mock.call_args_list, [call(1, 2, a=3, b=4)])
260 self.assertEqual(mock.mock_calls, [call(1, 2, a=3, b=4)])
261
262 mock = MagicMock()
263 mock.foo(1).bar()().baz.beep(a=6)
264
265 last_call = call.foo(1).bar()().baz.beep(a=6)
266 self.assertEqual(mock.mock_calls[-1], last_call)
267 self.assertEqual(mock.mock_calls, last_call.call_list())
268
269
270 def test_call_list(self):
271 mock = MagicMock()
272 mock(1)
273 self.assertEqual(call(1).call_list(), mock.mock_calls)
274
275 mock = MagicMock()
276 mock(1).method(2)
277 self.assertEqual(call(1).method(2).call_list(),
278 mock.mock_calls)
279
280 mock = MagicMock()
281 mock(1).method(2)(3)
282 self.assertEqual(call(1).method(2)(3).call_list(),
283 mock.mock_calls)
284
285 mock = MagicMock()
286 int(mock(1).method(2)(3).foo.bar.baz(4)(5))
287 kall = call(1).method(2)(3).foo.bar.baz(4)(5).__int__()
288 self.assertEqual(kall.call_list(), mock.mock_calls)
289
290
291 def test_call_any(self):
292 self.assertEqual(call, ANY)
293
294 m = MagicMock()
295 int(m)
296 self.assertEqual(m.mock_calls, [ANY])
297 self.assertEqual([ANY], m.mock_calls)
298
299
300 def test_two_args_call(self):
301 args = _Call(((1, 2), {'a': 3}), two=True)
302 self.assertEqual(len(args), 2)
303 self.assertEqual(args[0], (1, 2))
304 self.assertEqual(args[1], {'a': 3})
305
306 other_args = _Call(((1, 2), {'a': 3}))
307 self.assertEqual(args, other_args)
308
309
310class SpecSignatureTest(unittest.TestCase):
311
312 def _check_someclass_mock(self, mock):
313 self.assertRaises(AttributeError, getattr, mock, 'foo')
314 mock.one(1, 2)
315 mock.one.assert_called_with(1, 2)
316 self.assertRaises(AssertionError,
317 mock.one.assert_called_with, 3, 4)
318 self.assertRaises(TypeError, mock.one, 1)
319
320 mock.two()
321 mock.two.assert_called_with()
322 self.assertRaises(AssertionError,
323 mock.two.assert_called_with, 3)
324 self.assertRaises(TypeError, mock.two, 1)
325
326 mock.three()
327 mock.three.assert_called_with()
328 self.assertRaises(AssertionError,
329 mock.three.assert_called_with, 3)
330 self.assertRaises(TypeError, mock.three, 3, 2)
331
332 mock.three(1)
333 mock.three.assert_called_with(1)
334
335 mock.three(a=1)
336 mock.three.assert_called_with(a=1)
337
338
339 def test_basic(self):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100340 mock = create_autospec(SomeClass)
341 self._check_someclass_mock(mock)
342 mock = create_autospec(SomeClass())
343 self._check_someclass_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -0700344
345
346 def test_create_autospec_return_value(self):
347 def f():
348 pass
349 mock = create_autospec(f, return_value='foo')
350 self.assertEqual(mock(), 'foo')
351
352 class Foo(object):
353 pass
354
355 mock = create_autospec(Foo, return_value='foo')
356 self.assertEqual(mock(), 'foo')
357
358
Michael Foord75963642012-06-09 17:31:59 +0100359 def test_autospec_reset_mock(self):
360 m = create_autospec(int)
361 int(m)
362 m.reset_mock()
363 self.assertEqual(m.__int__.call_count, 0)
364
365
Michael Foord345266a2012-03-14 12:24:34 -0700366 def test_mocking_unbound_methods(self):
367 class Foo(object):
368 def foo(self, foo):
369 pass
370 p = patch.object(Foo, 'foo')
371 mock_foo = p.start()
372 Foo().foo(1)
373
374 mock_foo.assert_called_with(1)
375
376
377 def test_create_autospec_unbound_methods(self):
Michael Foord3af125a2012-04-21 18:22:28 +0100378 # see mock issue 128
Michael Foord345266a2012-03-14 12:24:34 -0700379 # this is expected to fail until the issue is fixed
380 return
381 class Foo(object):
382 def foo(self):
383 pass
384
385 klass = create_autospec(Foo)
386 instance = klass()
387 self.assertRaises(TypeError, instance.foo, 1)
388
389 # Note: no type checking on the "self" parameter
390 klass.foo(1)
391 klass.foo.assert_called_with(1)
392 self.assertRaises(TypeError, klass.foo)
393
394
395 def test_create_autospec_keyword_arguments(self):
396 class Foo(object):
397 a = 3
398 m = create_autospec(Foo, a='3')
399 self.assertEqual(m.a, '3')
400
401
Michael Foord3af125a2012-04-21 18:22:28 +0100402 def test_create_autospec_keyword_only_arguments(self):
403 def foo(a, *, b=None):
404 pass
405
406 m = create_autospec(foo)
407 m(1)
408 m.assert_called_with(1)
409 self.assertRaises(TypeError, m, 1, 2)
410
411 m(2, b=3)
412 m.assert_called_with(2, b=3)
413
414
Michael Foord345266a2012-03-14 12:24:34 -0700415 def test_function_as_instance_attribute(self):
416 obj = SomeClass()
417 def f(a):
418 pass
419 obj.f = f
420
421 mock = create_autospec(obj)
422 mock.f('bing')
423 mock.f.assert_called_with('bing')
424
425
426 def test_spec_as_list(self):
427 # because spec as a list of strings in the mock constructor means
428 # something very different we treat a list instance as the type.
429 mock = create_autospec([])
430 mock.append('foo')
431 mock.append.assert_called_with('foo')
432
433 self.assertRaises(AttributeError, getattr, mock, 'foo')
434
435 class Foo(object):
436 foo = []
437
438 mock = create_autospec(Foo)
439 mock.foo.append(3)
440 mock.foo.append.assert_called_with(3)
441 self.assertRaises(AttributeError, getattr, mock.foo, 'foo')
442
443
444 def test_attributes(self):
445 class Sub(SomeClass):
446 attr = SomeClass()
447
448 sub_mock = create_autospec(Sub)
449
450 for mock in (sub_mock, sub_mock.attr):
451 self._check_someclass_mock(mock)
452
453
454 def test_builtin_functions_types(self):
455 # we could replace builtin functions / methods with a function
456 # with *args / **kwargs signature. Using the builtin method type
457 # as a spec seems to work fairly well though.
458 class BuiltinSubclass(list):
459 def bar(self, arg):
460 pass
461 sorted = sorted
462 attr = {}
463
464 mock = create_autospec(BuiltinSubclass)
465 mock.append(3)
466 mock.append.assert_called_with(3)
467 self.assertRaises(AttributeError, getattr, mock.append, 'foo')
468
469 mock.bar('foo')
470 mock.bar.assert_called_with('foo')
471 self.assertRaises(TypeError, mock.bar, 'foo', 'bar')
472 self.assertRaises(AttributeError, getattr, mock.bar, 'foo')
473
474 mock.sorted([1, 2])
475 mock.sorted.assert_called_with([1, 2])
476 self.assertRaises(AttributeError, getattr, mock.sorted, 'foo')
477
478 mock.attr.pop(3)
479 mock.attr.pop.assert_called_with(3)
480 self.assertRaises(AttributeError, getattr, mock.attr, 'foo')
481
482
483 def test_method_calls(self):
484 class Sub(SomeClass):
485 attr = SomeClass()
486
487 mock = create_autospec(Sub)
488 mock.one(1, 2)
489 mock.two()
490 mock.three(3)
491
492 expected = [call.one(1, 2), call.two(), call.three(3)]
493 self.assertEqual(mock.method_calls, expected)
494
495 mock.attr.one(1, 2)
496 mock.attr.two()
497 mock.attr.three(3)
498
499 expected.extend(
500 [call.attr.one(1, 2), call.attr.two(), call.attr.three(3)]
501 )
502 self.assertEqual(mock.method_calls, expected)
503
504
505 def test_magic_methods(self):
506 class BuiltinSubclass(list):
507 attr = {}
508
509 mock = create_autospec(BuiltinSubclass)
510 self.assertEqual(list(mock), [])
511 self.assertRaises(TypeError, int, mock)
512 self.assertRaises(TypeError, int, mock.attr)
513 self.assertEqual(list(mock), [])
514
515 self.assertIsInstance(mock['foo'], MagicMock)
516 self.assertIsInstance(mock.attr['foo'], MagicMock)
517
518
519 def test_spec_set(self):
520 class Sub(SomeClass):
521 attr = SomeClass()
522
523 for spec in (Sub, Sub()):
524 mock = create_autospec(spec, spec_set=True)
525 self._check_someclass_mock(mock)
526
527 self.assertRaises(AttributeError, setattr, mock, 'foo', 'bar')
528 self.assertRaises(AttributeError, setattr, mock.attr, 'foo', 'bar')
529
530
531 def test_descriptors(self):
532 class Foo(object):
533 @classmethod
534 def f(cls, a, b):
535 pass
536 @staticmethod
537 def g(a, b):
538 pass
539
540 class Bar(Foo):
541 pass
542
543 class Baz(SomeClass, Bar):
544 pass
545
546 for spec in (Foo, Foo(), Bar, Bar(), Baz, Baz()):
547 mock = create_autospec(spec)
548 mock.f(1, 2)
549 mock.f.assert_called_once_with(1, 2)
550
551 mock.g(3, 4)
552 mock.g.assert_called_once_with(3, 4)
553
554
555 def test_recursive(self):
556 class A(object):
557 def a(self):
558 pass
559 foo = 'foo bar baz'
560 bar = foo
561
562 A.B = A
563 mock = create_autospec(A)
564
565 mock()
566 self.assertFalse(mock.B.called)
567
568 mock.a()
569 mock.B.a()
570 self.assertEqual(mock.method_calls, [call.a(), call.B.a()])
571
572 self.assertIs(A.foo, A.bar)
573 self.assertIsNot(mock.foo, mock.bar)
574 mock.foo.lower()
575 self.assertRaises(AssertionError, mock.bar.lower.assert_called_with)
576
577
578 def test_spec_inheritance_for_classes(self):
579 class Foo(object):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100580 def a(self, x):
Michael Foord345266a2012-03-14 12:24:34 -0700581 pass
582 class Bar(object):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100583 def f(self, y):
Michael Foord345266a2012-03-14 12:24:34 -0700584 pass
585
586 class_mock = create_autospec(Foo)
587
588 self.assertIsNot(class_mock, class_mock())
589
590 for this_mock in class_mock, class_mock():
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100591 this_mock.a(x=5)
592 this_mock.a.assert_called_with(x=5)
593 this_mock.a.assert_called_with(5)
594 self.assertRaises(TypeError, this_mock.a, 'foo', 'bar')
Michael Foord345266a2012-03-14 12:24:34 -0700595 self.assertRaises(AttributeError, getattr, this_mock, 'b')
596
597 instance_mock = create_autospec(Foo())
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100598 instance_mock.a(5)
599 instance_mock.a.assert_called_with(5)
600 instance_mock.a.assert_called_with(x=5)
601 self.assertRaises(TypeError, instance_mock.a, 'foo', 'bar')
Michael Foord345266a2012-03-14 12:24:34 -0700602 self.assertRaises(AttributeError, getattr, instance_mock, 'b')
603
604 # The return value isn't isn't callable
605 self.assertRaises(TypeError, instance_mock)
606
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100607 instance_mock.Bar.f(6)
608 instance_mock.Bar.f.assert_called_with(6)
609 instance_mock.Bar.f.assert_called_with(y=6)
Michael Foord345266a2012-03-14 12:24:34 -0700610 self.assertRaises(AttributeError, getattr, instance_mock.Bar, 'g')
611
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100612 instance_mock.Bar().f(6)
613 instance_mock.Bar().f.assert_called_with(6)
614 instance_mock.Bar().f.assert_called_with(y=6)
Michael Foord345266a2012-03-14 12:24:34 -0700615 self.assertRaises(AttributeError, getattr, instance_mock.Bar(), 'g')
616
617
618 def test_inherit(self):
619 class Foo(object):
620 a = 3
621
622 Foo.Foo = Foo
623
624 # class
625 mock = create_autospec(Foo)
626 instance = mock()
627 self.assertRaises(AttributeError, getattr, instance, 'b')
628
629 attr_instance = mock.Foo()
630 self.assertRaises(AttributeError, getattr, attr_instance, 'b')
631
632 # instance
633 mock = create_autospec(Foo())
634 self.assertRaises(AttributeError, getattr, mock, 'b')
635 self.assertRaises(TypeError, mock)
636
637 # attribute instance
638 call_result = mock.Foo()
639 self.assertRaises(AttributeError, getattr, call_result, 'b')
640
641
642 def test_builtins(self):
643 # used to fail with infinite recursion
644 create_autospec(1)
645
646 create_autospec(int)
647 create_autospec('foo')
648 create_autospec(str)
649 create_autospec({})
650 create_autospec(dict)
651 create_autospec([])
652 create_autospec(list)
653 create_autospec(set())
654 create_autospec(set)
655 create_autospec(1.0)
656 create_autospec(float)
657 create_autospec(1j)
658 create_autospec(complex)
659 create_autospec(False)
660 create_autospec(True)
661
662
663 def test_function(self):
664 def f(a, b):
665 pass
666
667 mock = create_autospec(f)
668 self.assertRaises(TypeError, mock)
669 mock(1, 2)
670 mock.assert_called_with(1, 2)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100671 mock.assert_called_with(1, b=2)
672 mock.assert_called_with(a=1, b=2)
Michael Foord345266a2012-03-14 12:24:34 -0700673
674 f.f = f
675 mock = create_autospec(f)
676 self.assertRaises(TypeError, mock.f)
677 mock.f(3, 4)
678 mock.f.assert_called_with(3, 4)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100679 mock.f.assert_called_with(a=3, b=4)
Michael Foord345266a2012-03-14 12:24:34 -0700680
681
Michael Foord656319e2012-04-13 17:39:16 +0100682 def test_skip_attributeerrors(self):
683 class Raiser(object):
684 def __get__(self, obj, type=None):
685 if obj is None:
686 raise AttributeError('Can only be accessed via an instance')
687
688 class RaiserClass(object):
689 raiser = Raiser()
690
691 @staticmethod
692 def existing(a, b):
693 return a + b
694
695 s = create_autospec(RaiserClass)
696 self.assertRaises(TypeError, lambda x: s.existing(1, 2, 3))
697 s.existing(1, 2)
698 self.assertRaises(AttributeError, lambda: s.nonexisting)
699
700 # check we can fetch the raiser attribute and it has no spec
701 obj = s.raiser
702 obj.foo, obj.bar
703
704
Michael Foord345266a2012-03-14 12:24:34 -0700705 def test_signature_class(self):
706 class Foo(object):
707 def __init__(self, a, b=3):
708 pass
709
710 mock = create_autospec(Foo)
711
712 self.assertRaises(TypeError, mock)
713 mock(1)
714 mock.assert_called_once_with(1)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100715 mock.assert_called_once_with(a=1)
716 self.assertRaises(AssertionError, mock.assert_called_once_with, 2)
Michael Foord345266a2012-03-14 12:24:34 -0700717
718 mock(4, 5)
719 mock.assert_called_with(4, 5)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100720 mock.assert_called_with(a=4, b=5)
721 self.assertRaises(AssertionError, mock.assert_called_with, a=5, b=4)
Michael Foord345266a2012-03-14 12:24:34 -0700722
723
724 def test_class_with_no_init(self):
725 # this used to raise an exception
726 # due to trying to get a signature from object.__init__
727 class Foo(object):
728 pass
729 create_autospec(Foo)
730
731
732 def test_signature_callable(self):
733 class Callable(object):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100734 def __init__(self, x, y):
Michael Foord345266a2012-03-14 12:24:34 -0700735 pass
736 def __call__(self, a):
737 pass
738
739 mock = create_autospec(Callable)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100740 mock(1, 2)
741 mock.assert_called_once_with(1, 2)
742 mock.assert_called_once_with(x=1, y=2)
Michael Foord345266a2012-03-14 12:24:34 -0700743 self.assertRaises(TypeError, mock, 'a')
744
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100745 instance = mock(1, 2)
Michael Foord345266a2012-03-14 12:24:34 -0700746 self.assertRaises(TypeError, instance)
747 instance(a='a')
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100748 instance.assert_called_once_with('a')
Michael Foord345266a2012-03-14 12:24:34 -0700749 instance.assert_called_once_with(a='a')
750 instance('a')
751 instance.assert_called_with('a')
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100752 instance.assert_called_with(a='a')
Michael Foord345266a2012-03-14 12:24:34 -0700753
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100754 mock = create_autospec(Callable(1, 2))
Michael Foord345266a2012-03-14 12:24:34 -0700755 mock(a='a')
756 mock.assert_called_once_with(a='a')
757 self.assertRaises(TypeError, mock)
758 mock('a')
759 mock.assert_called_with('a')
760
761
762 def test_signature_noncallable(self):
763 class NonCallable(object):
764 def __init__(self):
765 pass
766
767 mock = create_autospec(NonCallable)
768 instance = mock()
769 mock.assert_called_once_with()
770 self.assertRaises(TypeError, mock, 'a')
771 self.assertRaises(TypeError, instance)
772 self.assertRaises(TypeError, instance, 'a')
773
774 mock = create_autospec(NonCallable())
775 self.assertRaises(TypeError, mock)
776 self.assertRaises(TypeError, mock, 'a')
777
778
779 def test_create_autospec_none(self):
780 class Foo(object):
781 bar = None
782
783 mock = create_autospec(Foo)
784 none = mock.bar
785 self.assertNotIsInstance(none, type(None))
786
787 none.foo()
788 none.foo.assert_called_once_with()
789
790
791 def test_autospec_functions_with_self_in_odd_place(self):
792 class Foo(object):
793 def f(a, self):
794 pass
795
796 a = create_autospec(Foo)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100797 a.f(10)
798 a.f.assert_called_with(10)
799 a.f.assert_called_with(self=10)
Michael Foord345266a2012-03-14 12:24:34 -0700800 a.f(self=10)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100801 a.f.assert_called_with(10)
Michael Foord345266a2012-03-14 12:24:34 -0700802 a.f.assert_called_with(self=10)
803
804
805 def test_autospec_property(self):
806 class Foo(object):
807 @property
808 def foo(self):
809 return 3
810
811 foo = create_autospec(Foo)
812 mock_property = foo.foo
813
814 # no spec on properties
815 self.assertTrue(isinstance(mock_property, MagicMock))
816 mock_property(1, 2, 3)
817 mock_property.abc(4, 5, 6)
818 mock_property.assert_called_once_with(1, 2, 3)
819 mock_property.abc.assert_called_once_with(4, 5, 6)
820
821
822 def test_autospec_slots(self):
823 class Foo(object):
824 __slots__ = ['a']
825
826 foo = create_autospec(Foo)
827 mock_slot = foo.a
828
829 # no spec on slots
830 mock_slot(1, 2, 3)
831 mock_slot.abc(4, 5, 6)
832 mock_slot.assert_called_once_with(1, 2, 3)
833 mock_slot.abc.assert_called_once_with(4, 5, 6)
834
835
836class TestCallList(unittest.TestCase):
837
838 def test_args_list_contains_call_list(self):
839 mock = Mock()
840 self.assertIsInstance(mock.call_args_list, _CallList)
841
842 mock(1, 2)
843 mock(a=3)
844 mock(3, 4)
845 mock(b=6)
846
847 for kall in call(1, 2), call(a=3), call(3, 4), call(b=6):
848 self.assertTrue(kall in mock.call_args_list)
849
850 calls = [call(a=3), call(3, 4)]
851 self.assertTrue(calls in mock.call_args_list)
852 calls = [call(1, 2), call(a=3)]
853 self.assertTrue(calls in mock.call_args_list)
854 calls = [call(3, 4), call(b=6)]
855 self.assertTrue(calls in mock.call_args_list)
856 calls = [call(3, 4)]
857 self.assertTrue(calls in mock.call_args_list)
858
859 self.assertFalse(call('fish') in mock.call_args_list)
860 self.assertFalse([call('fish')] in mock.call_args_list)
861
862
863 def test_call_list_str(self):
864 mock = Mock()
865 mock(1, 2)
866 mock.foo(a=3)
867 mock.foo.bar().baz('fish', cat='dog')
868
869 expected = (
870 "[call(1, 2),\n"
871 " call.foo(a=3),\n"
872 " call.foo.bar(),\n"
873 " call.foo.bar().baz('fish', cat='dog')]"
874 )
875 self.assertEqual(str(mock.mock_calls), expected)
876
877
878 def test_propertymock(self):
879 p = patch('%s.SomeClass.one' % __name__, new_callable=PropertyMock)
880 mock = p.start()
881 try:
882 SomeClass.one
883 mock.assert_called_once_with()
884
885 s = SomeClass()
886 s.one
887 mock.assert_called_with()
888 self.assertEqual(mock.mock_calls, [call(), call()])
889
890 s.one = 3
891 self.assertEqual(mock.mock_calls, [call(), call(), call(3)])
892 finally:
893 p.stop()
894
895
Michael Foordc2870622012-04-13 16:57:22 +0100896 def test_propertymock_returnvalue(self):
897 m = MagicMock()
898 p = PropertyMock()
899 type(m).foo = p
900
901 returned = m.foo
902 p.assert_called_once_with()
903 self.assertIsInstance(returned, MagicMock)
904 self.assertNotIsInstance(returned, PropertyMock)
905
906
Michael Foord345266a2012-03-14 12:24:34 -0700907if __name__ == '__main__':
908 unittest.main()