blob: e788da8447e132a450b582417b866162b1baa8b6 [file] [log] [blame]
Michael Foord1e68bec2012-03-03 22:24:30 +00001# Copyright (C) 2007-2012 Michael Foord & the mock team
2# E-mail: fuzzyman AT voidspace DOT org DOT uk
3# http://www.voidspace.org.uk/python/mock/
4
5from tests.support import unittest2, inPy3k
6
7from mock import (
Michael Foordafc98d42012-03-13 16:38:50 -07008 call, _Call, create_autospec, MagicMock,
Michael Foord4b4c9152012-03-13 23:34:50 -07009 Mock, ANY, _CallList, patch, PropertyMock
Michael Foord1e68bec2012-03-03 22:24:30 +000010)
11
12from datetime import datetime
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(unittest2.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(unittest2.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.assertTrue(call(1, 2, 3) in [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_call_list(self):
275 mock = MagicMock()
276 mock(1)
277 self.assertEqual(call(1).call_list(), mock.mock_calls)
278
279 mock = MagicMock()
280 mock(1).method(2)
281 self.assertEqual(call(1).method(2).call_list(),
282 mock.mock_calls)
283
284 mock = MagicMock()
285 mock(1).method(2)(3)
286 self.assertEqual(call(1).method(2)(3).call_list(),
287 mock.mock_calls)
288
289 mock = MagicMock()
290 int(mock(1).method(2)(3).foo.bar.baz(4)(5))
291 kall = call(1).method(2)(3).foo.bar.baz(4)(5).__int__()
292 self.assertEqual(kall.call_list(), mock.mock_calls)
293
294
295 def test_call_any(self):
296 self.assertEqual(call, ANY)
297
298 m = MagicMock()
299 int(m)
300 self.assertEqual(m.mock_calls, [ANY])
301 self.assertEqual([ANY], m.mock_calls)
302
303
304 def test_two_args_call(self):
305 args = _Call(((1, 2), {'a': 3}), two=True)
306 self.assertEqual(len(args), 2)
307 self.assertEqual(args[0], (1, 2))
308 self.assertEqual(args[1], {'a': 3})
309
310 other_args = _Call(((1, 2), {'a': 3}))
311 self.assertEqual(args, other_args)
312
313
314class SpecSignatureTest(unittest2.TestCase):
315
316 def _check_someclass_mock(self, mock):
317 self.assertRaises(AttributeError, getattr, mock, 'foo')
318 mock.one(1, 2)
319 mock.one.assert_called_with(1, 2)
320 self.assertRaises(AssertionError,
321 mock.one.assert_called_with, 3, 4)
322 self.assertRaises(TypeError, mock.one, 1)
323
324 mock.two()
325 mock.two.assert_called_with()
326 self.assertRaises(AssertionError,
327 mock.two.assert_called_with, 3)
328 self.assertRaises(TypeError, mock.two, 1)
329
330 mock.three()
331 mock.three.assert_called_with()
332 self.assertRaises(AssertionError,
333 mock.three.assert_called_with, 3)
334 self.assertRaises(TypeError, mock.three, 3, 2)
335
336 mock.three(1)
337 mock.three.assert_called_with(1)
338
339 mock.three(a=1)
340 mock.three.assert_called_with(a=1)
341
342
343 def test_basic(self):
344 for spec in (SomeClass, SomeClass()):
345 mock = create_autospec(spec)
346 self._check_someclass_mock(mock)
347
348
349 def test_create_autospec_return_value(self):
350 def f():
351 pass
352 mock = create_autospec(f, return_value='foo')
353 self.assertEqual(mock(), 'foo')
354
355 class Foo(object):
356 pass
357
358 mock = create_autospec(Foo, return_value='foo')
359 self.assertEqual(mock(), 'foo')
360
361
Michael Foord9e6246d2012-06-09 15:45:05 +0100362 def test_autospec_reset_mock(self):
363 m = create_autospec(int)
364 int(m)
365 m.reset_mock()
366 self.assertEqual(m.__int__.call_count, 0)
367
368
Michael Foordaf78a502012-03-13 17:00:04 -0700369 def test_mocking_unbound_methods(self):
370 class Foo(object):
371 def foo(self, foo):
372 pass
373 p = patch.object(Foo, 'foo')
374 mock_foo = p.start()
375 Foo().foo(1)
376
377 mock_foo.assert_called_with(1)
378
379
Michael Foord2b732bc2012-03-13 13:17:34 -0700380 @unittest2.expectedFailure
Michael Foord1e68bec2012-03-03 22:24:30 +0000381 def test_create_autospec_unbound_methods(self):
382 # see issue 128
383 class Foo(object):
384 def foo(self):
385 pass
386
387 klass = create_autospec(Foo)
388 instance = klass()
Michael Foorda87f30c2012-03-04 17:53:24 +0000389 self.assertRaises(TypeError, instance.foo, 1)
390
391 # Note: no type checking on the "self" parameter
392 klass.foo(1)
393 klass.foo.assert_called_with(1)
394 self.assertRaises(TypeError, klass.foo)
Michael Foord1e68bec2012-03-03 22:24:30 +0000395
396
397 def test_create_autospec_keyword_arguments(self):
398 class Foo(object):
399 a = 3
400 m = create_autospec(Foo, a='3')
401 self.assertEqual(m.a, '3')
402
Michael Foordc8dddba2012-04-21 18:39:34 +0100403 @unittest2.skipUnless(inPy3k, "Keyword only arguments Python 3 specific")
404 def test_create_autospec_keyword_only_arguments(self):
405 func_def = "def foo(a, *, b=None):\n pass\n"
406 namespace = {}
407 exec (func_def, namespace)
408 foo = namespace['foo']
409
410 m = create_autospec(foo)
411 m(1)
412 m.assert_called_with(1)
413 self.assertRaises(TypeError, m, 1, 2)
414
415 m(2, b=3)
416 m.assert_called_with(2, b=3)
Michael Foord1e68bec2012-03-03 22:24:30 +0000417
418 def test_function_as_instance_attribute(self):
419 obj = SomeClass()
420 def f(a):
421 pass
422 obj.f = f
423
424 mock = create_autospec(obj)
425 mock.f('bing')
426 mock.f.assert_called_with('bing')
427
428
429 def test_spec_as_list(self):
430 # because spec as a list of strings in the mock constructor means
431 # something very different we treat a list instance as the type.
432 mock = create_autospec([])
433 mock.append('foo')
434 mock.append.assert_called_with('foo')
435
436 self.assertRaises(AttributeError, getattr, mock, 'foo')
437
438 class Foo(object):
439 foo = []
440
441 mock = create_autospec(Foo)
442 mock.foo.append(3)
443 mock.foo.append.assert_called_with(3)
444 self.assertRaises(AttributeError, getattr, mock.foo, 'foo')
445
446
447 def test_attributes(self):
448 class Sub(SomeClass):
449 attr = SomeClass()
450
451 sub_mock = create_autospec(Sub)
452
453 for mock in (sub_mock, sub_mock.attr):
454 self._check_someclass_mock(mock)
455
456
457 def test_builtin_functions_types(self):
Michael Foorda9a8bb92012-03-13 14:39:59 -0700458 # we could replace builtin functions / methods with a function
Michael Foord1e68bec2012-03-03 22:24:30 +0000459 # with *args / **kwargs signature. Using the builtin method type
460 # as a spec seems to work fairly well though.
461 class BuiltinSubclass(list):
462 def bar(self, arg):
463 pass
464 sorted = sorted
465 attr = {}
466
467 mock = create_autospec(BuiltinSubclass)
468 mock.append(3)
469 mock.append.assert_called_with(3)
470 self.assertRaises(AttributeError, getattr, mock.append, 'foo')
471
472 mock.bar('foo')
473 mock.bar.assert_called_with('foo')
474 self.assertRaises(TypeError, mock.bar, 'foo', 'bar')
475 self.assertRaises(AttributeError, getattr, mock.bar, 'foo')
476
477 mock.sorted([1, 2])
478 mock.sorted.assert_called_with([1, 2])
479 self.assertRaises(AttributeError, getattr, mock.sorted, 'foo')
480
481 mock.attr.pop(3)
482 mock.attr.pop.assert_called_with(3)
483 self.assertRaises(AttributeError, getattr, mock.attr, 'foo')
484
485
486 def test_method_calls(self):
487 class Sub(SomeClass):
488 attr = SomeClass()
489
490 mock = create_autospec(Sub)
491 mock.one(1, 2)
492 mock.two()
493 mock.three(3)
494
495 expected = [call.one(1, 2), call.two(), call.three(3)]
496 self.assertEqual(mock.method_calls, expected)
497
498 mock.attr.one(1, 2)
499 mock.attr.two()
500 mock.attr.three(3)
501
502 expected.extend(
503 [call.attr.one(1, 2), call.attr.two(), call.attr.three(3)]
504 )
505 self.assertEqual(mock.method_calls, expected)
506
507
508 def test_magic_methods(self):
509 class BuiltinSubclass(list):
510 attr = {}
511
512 mock = create_autospec(BuiltinSubclass)
513 self.assertEqual(list(mock), [])
514 self.assertRaises(TypeError, int, mock)
515 self.assertRaises(TypeError, int, mock.attr)
516 self.assertEqual(list(mock), [])
517
518 self.assertIsInstance(mock['foo'], MagicMock)
519 self.assertIsInstance(mock.attr['foo'], MagicMock)
520
521
522 def test_spec_set(self):
523 class Sub(SomeClass):
524 attr = SomeClass()
525
526 for spec in (Sub, Sub()):
527 mock = create_autospec(spec, spec_set=True)
528 self._check_someclass_mock(mock)
529
530 self.assertRaises(AttributeError, setattr, mock, 'foo', 'bar')
531 self.assertRaises(AttributeError, setattr, mock.attr, 'foo', 'bar')
532
533
534 def test_descriptors(self):
535 class Foo(object):
536 @classmethod
537 def f(cls, a, b):
538 pass
539 @staticmethod
540 def g(a, b):
541 pass
542
543 class Bar(Foo):
544 pass
545
546 class Baz(SomeClass, Bar):
547 pass
548
549 for spec in (Foo, Foo(), Bar, Bar(), Baz, Baz()):
550 mock = create_autospec(spec)
551 mock.f(1, 2)
552 mock.f.assert_called_once_with(1, 2)
553
554 mock.g(3, 4)
555 mock.g.assert_called_once_with(3, 4)
556
557
558 @unittest2.skipIf(inPy3k, "No old style classes in Python 3")
559 def test_old_style_classes(self):
560 class Foo:
561 def f(self, a, b):
562 pass
563
564 class Bar(Foo):
565 g = Foo()
566
567 for spec in (Foo, Foo(), Bar, Bar()):
568 mock = create_autospec(spec)
569 mock.f(1, 2)
570 mock.f.assert_called_once_with(1, 2)
571
572 self.assertRaises(AttributeError, getattr, mock, 'foo')
573 self.assertRaises(AttributeError, getattr, mock.f, 'foo')
574
575 mock.g.f(1, 2)
576 mock.g.f.assert_called_once_with(1, 2)
577 self.assertRaises(AttributeError, getattr, mock.g, 'foo')
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):
606 pass
607 class Bar(object):
608 def f(self):
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()
617 this_mock.a.assert_called_with()
618 self.assertRaises(TypeError, this_mock.a, 'foo')
619 self.assertRaises(AttributeError, getattr, this_mock, 'b')
620
621 instance_mock = create_autospec(Foo())
622 instance_mock.a()
623 instance_mock.a.assert_called_with()
624 self.assertRaises(TypeError, instance_mock.a, 'foo')
625 self.assertRaises(AttributeError, getattr, instance_mock, 'b')
626
627 # The return value isn't isn't callable
628 self.assertRaises(TypeError, instance_mock)
629
630 instance_mock.Bar.f()
631 instance_mock.Bar.f.assert_called_with()
632 self.assertRaises(AttributeError, getattr, instance_mock.Bar, 'g')
633
634 instance_mock.Bar().f()
635 instance_mock.Bar().f.assert_called_with()
636 self.assertRaises(AttributeError, getattr, instance_mock.Bar(), 'g')
637
638
639 def test_inherit(self):
640 class Foo(object):
641 a = 3
642
643 Foo.Foo = Foo
644
645 # class
646 mock = create_autospec(Foo)
647 instance = mock()
648 self.assertRaises(AttributeError, getattr, instance, 'b')
649
650 attr_instance = mock.Foo()
651 self.assertRaises(AttributeError, getattr, attr_instance, 'b')
652
653 # instance
654 mock = create_autospec(Foo())
655 self.assertRaises(AttributeError, getattr, mock, 'b')
656 self.assertRaises(TypeError, mock)
657
658 # attribute instance
659 call_result = mock.Foo()
660 self.assertRaises(AttributeError, getattr, call_result, 'b')
661
662
663 def test_builtins(self):
664 # used to fail with infinite recursion
665 create_autospec(1)
666
667 create_autospec(int)
668 create_autospec('foo')
669 create_autospec(str)
670 create_autospec({})
671 create_autospec(dict)
672 create_autospec([])
673 create_autospec(list)
674 create_autospec(set())
675 create_autospec(set)
676 create_autospec(1.0)
677 create_autospec(float)
678 create_autospec(1j)
679 create_autospec(complex)
680 create_autospec(False)
681 create_autospec(True)
682
683
684 def test_function(self):
685 def f(a, b):
686 pass
687
688 mock = create_autospec(f)
689 self.assertRaises(TypeError, mock)
690 mock(1, 2)
691 mock.assert_called_with(1, 2)
692
693 f.f = f
694 mock = create_autospec(f)
695 self.assertRaises(TypeError, mock.f)
696 mock.f(3, 4)
697 mock.f.assert_called_with(3, 4)
698
699
Michael Foord7dad0f62012-04-13 17:16:54 +0100700 def test_skip_attributeerrors(self):
701 class Raiser(object):
702 def __get__(self, obj, type=None):
703 if obj is None:
704 raise AttributeError('Can only be accessed via an instance')
705
706 class RaiserClass(object):
707 raiser = Raiser()
708
709 @staticmethod
710 def existing(a, b):
711 return a + b
712
713 s = create_autospec(RaiserClass)
714 self.assertRaises(TypeError, lambda x: s.existing(1, 2, 3))
715 s.existing(1, 2)
716 self.assertRaises(AttributeError, lambda: s.nonexisting)
717
718 # check we can fetch the raiser attribute and it has no spec
719 obj = s.raiser
720 obj.foo, obj.bar
721
722
Michael Foord9e1592e2012-04-13 17:39:31 +0100723 def test_signature_class(self):
724 class Foo(object):
725 def __init__(self, a, b=3):
726 pass
727
728 mock = create_autospec(Foo)
729
730 self.assertRaises(TypeError, mock)
731 mock(1)
732 mock.assert_called_once_with(1)
733
734 mock(4, 5)
735 mock.assert_called_with(4, 5)
736
737
Michael Foord1e68bec2012-03-03 22:24:30 +0000738 @unittest2.skipIf(inPy3k, 'no old style classes in Python 3')
739 def test_signature_old_style_class(self):
740 class Foo:
741 def __init__(self, a, b=3):
742 pass
743
744 mock = create_autospec(Foo)
745
746 self.assertRaises(TypeError, mock)
747 mock(1)
748 mock.assert_called_once_with(1)
749
750 mock(4, 5)
751 mock.assert_called_with(4, 5)
752
753
754 def test_class_with_no_init(self):
755 # this used to raise an exception
756 # due to trying to get a signature from object.__init__
757 class Foo(object):
758 pass
759 create_autospec(Foo)
760
761
762 @unittest2.skipIf(inPy3k, 'no old style classes in Python 3')
763 def test_old_style_class_with_no_init(self):
764 # this used to raise an exception
765 # due to Foo.__init__ raising an AttributeError
766 class Foo:
767 pass
768 create_autospec(Foo)
769
770
771 def test_signature_callable(self):
772 class Callable(object):
773 def __init__(self):
774 pass
775 def __call__(self, a):
776 pass
777
778 mock = create_autospec(Callable)
779 mock()
780 mock.assert_called_once_with()
781 self.assertRaises(TypeError, mock, 'a')
782
783 instance = mock()
784 self.assertRaises(TypeError, instance)
785 instance(a='a')
786 instance.assert_called_once_with(a='a')
787 instance('a')
788 instance.assert_called_with('a')
789
790 mock = create_autospec(Callable())
791 mock(a='a')
792 mock.assert_called_once_with(a='a')
793 self.assertRaises(TypeError, mock)
794 mock('a')
795 mock.assert_called_with('a')
796
797
798 def test_signature_noncallable(self):
799 class NonCallable(object):
800 def __init__(self):
801 pass
802
803 mock = create_autospec(NonCallable)
804 instance = mock()
805 mock.assert_called_once_with()
806 self.assertRaises(TypeError, mock, 'a')
807 self.assertRaises(TypeError, instance)
808 self.assertRaises(TypeError, instance, 'a')
809
810 mock = create_autospec(NonCallable())
811 self.assertRaises(TypeError, mock)
812 self.assertRaises(TypeError, mock, 'a')
813
814
815 def test_create_autospec_none(self):
816 class Foo(object):
817 bar = None
818
819 mock = create_autospec(Foo)
820 none = mock.bar
821 self.assertNotIsInstance(none, type(None))
822
823 none.foo()
824 none.foo.assert_called_once_with()
825
826
827 def test_autospec_functions_with_self_in_odd_place(self):
828 class Foo(object):
829 def f(a, self):
830 pass
831
832 a = create_autospec(Foo)
833 a.f(self=10)
834 a.f.assert_called_with(self=10)
835
836
837 def test_autospec_property(self):
838 class Foo(object):
839 @property
840 def foo(self):
841 return 3
842
843 foo = create_autospec(Foo)
844 mock_property = foo.foo
845
846 # no spec on properties
847 self.assertTrue(isinstance(mock_property, MagicMock))
848 mock_property(1, 2, 3)
849 mock_property.abc(4, 5, 6)
850 mock_property.assert_called_once_with(1, 2, 3)
851 mock_property.abc.assert_called_once_with(4, 5, 6)
852
853
854 def test_autospec_slots(self):
855 class Foo(object):
856 __slots__ = ['a']
857
858 foo = create_autospec(Foo)
859 mock_slot = foo.a
860
861 # no spec on slots
862 mock_slot(1, 2, 3)
863 mock_slot.abc(4, 5, 6)
864 mock_slot.assert_called_once_with(1, 2, 3)
865 mock_slot.abc.assert_called_once_with(4, 5, 6)
866
867
868class TestCallList(unittest2.TestCase):
869
870 def test_args_list_contains_call_list(self):
Michael Foorda9a8bb92012-03-13 14:39:59 -0700871 mock = Mock()
872 self.assertIsInstance(mock.call_args_list, _CallList)
Michael Foord1e68bec2012-03-03 22:24:30 +0000873
Michael Foorda9a8bb92012-03-13 14:39:59 -0700874 mock(1, 2)
875 mock(a=3)
876 mock(3, 4)
877 mock(b=6)
Michael Foord1e68bec2012-03-03 22:24:30 +0000878
Michael Foorda9a8bb92012-03-13 14:39:59 -0700879 for kall in call(1, 2), call(a=3), call(3, 4), call(b=6):
880 self.assertTrue(kall in mock.call_args_list)
Michael Foord1e68bec2012-03-03 22:24:30 +0000881
Michael Foorda9a8bb92012-03-13 14:39:59 -0700882 calls = [call(a=3), call(3, 4)]
883 self.assertTrue(calls in mock.call_args_list)
884 calls = [call(1, 2), call(a=3)]
885 self.assertTrue(calls in mock.call_args_list)
886 calls = [call(3, 4), call(b=6)]
887 self.assertTrue(calls in mock.call_args_list)
888 calls = [call(3, 4)]
889 self.assertTrue(calls in mock.call_args_list)
Michael Foord1e68bec2012-03-03 22:24:30 +0000890
Michael Foorda9a8bb92012-03-13 14:39:59 -0700891 self.assertFalse(call('fish') in mock.call_args_list)
892 self.assertFalse([call('fish')] in mock.call_args_list)
Michael Foord1e68bec2012-03-03 22:24:30 +0000893
894
895 def test_call_list_str(self):
896 mock = Mock()
897 mock(1, 2)
898 mock.foo(a=3)
899 mock.foo.bar().baz('fish', cat='dog')
900
901 expected = (
902 "[call(1, 2),\n"
903 " call.foo(a=3),\n"
904 " call.foo.bar(),\n"
905 " call.foo.bar().baz('fish', cat='dog')]"
906 )
907 self.assertEqual(str(mock.mock_calls), expected)
908
909
Michael Foord4b4c9152012-03-13 23:34:50 -0700910 def test_propertymock(self):
911 p = patch('%s.SomeClass.one' % __name__, new_callable=PropertyMock)
912 mock = p.start()
913 try:
914 SomeClass.one
915 mock.assert_called_once_with()
916
917 s = SomeClass()
918 s.one
919 mock.assert_called_with()
920 self.assertEqual(mock.mock_calls, [call(), call()])
921
922 s.one = 3
923 self.assertEqual(mock.mock_calls, [call(), call(), call(3)])
924 finally:
925 p.stop()
926
Michael Foordafc98d42012-03-13 16:38:50 -0700927
Michael Foord95b4b372012-04-13 16:57:52 +0100928 def test_propertymock_returnvalue(self):
929 m = MagicMock()
930 p = PropertyMock()
931 type(m).foo = p
932
933 returned = m.foo
934 p.assert_called_once_with()
935 self.assertIsInstance(returned, MagicMock)
936 self.assertNotIsInstance(returned, PropertyMock)
937
938
Michael Foord1e68bec2012-03-03 22:24:30 +0000939if __name__ == '__main__':
940 unittest2.main()