blob: 64e2fcf61c12333282457818973674f672a6caab [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001import copy
Petter Strandmark47d94242018-10-28 21:37:10 +01002import re
Michael Foord345266a2012-03-14 12:24:34 -07003import sys
Robert Collinsca647ef2015-07-24 03:48:20 +12004import tempfile
Michael Foord345266a2012-03-14 12:24:34 -07005
6import unittest
7from unittest.test.testmock.support import is_instance
8from unittest import mock
9from unittest.mock import (
10 call, DEFAULT, patch, sentinel,
11 MagicMock, Mock, NonCallableMock,
Andrew Dunaie63e6172018-12-04 11:08:45 +020012 NonCallableMagicMock, _Call, _CallList,
Michael Foord345266a2012-03-14 12:24:34 -070013 create_autospec
14)
15
16
17class Iter(object):
18 def __init__(self):
19 self.thing = iter(['this', 'is', 'an', 'iter'])
20
21 def __iter__(self):
22 return self
23
24 def next(self):
25 return next(self.thing)
26
27 __next__ = next
28
29
Antoine Pitrou5c64df72013-02-03 00:23:58 +010030class Something(object):
31 def meth(self, a, b, c, d=None):
32 pass
33
34 @classmethod
35 def cmeth(cls, a, b, c, d=None):
36 pass
37
38 @staticmethod
39 def smeth(a, b, c, d=None):
40 pass
41
Michael Foord345266a2012-03-14 12:24:34 -070042
43class MockTest(unittest.TestCase):
44
45 def test_all(self):
46 # if __all__ is badly defined then import * will raise an error
47 # We have to exec it because you can't import * inside a method
48 # in Python 3
Michael Foord83a16852012-03-14 12:58:46 -070049 exec("from unittest.mock import *")
Michael Foord345266a2012-03-14 12:24:34 -070050
51
52 def test_constructor(self):
53 mock = Mock()
54
55 self.assertFalse(mock.called, "called not initialised correctly")
56 self.assertEqual(mock.call_count, 0,
57 "call_count not initialised correctly")
58 self.assertTrue(is_instance(mock.return_value, Mock),
59 "return_value not initialised correctly")
60
61 self.assertEqual(mock.call_args, None,
62 "call_args not initialised correctly")
63 self.assertEqual(mock.call_args_list, [],
64 "call_args_list not initialised correctly")
65 self.assertEqual(mock.method_calls, [],
66 "method_calls not initialised correctly")
67
68 # Can't use hasattr for this test as it always returns True on a mock
Serhiy Storchaka5665bc52013-11-17 00:12:21 +020069 self.assertNotIn('_items', mock.__dict__,
Michael Foord345266a2012-03-14 12:24:34 -070070 "default mock should not have '_items' attribute")
71
72 self.assertIsNone(mock._mock_parent,
73 "parent not initialised correctly")
74 self.assertIsNone(mock._mock_methods,
75 "methods not initialised correctly")
76 self.assertEqual(mock._mock_children, {},
77 "children not initialised incorrectly")
78
79
80 def test_return_value_in_constructor(self):
81 mock = Mock(return_value=None)
82 self.assertIsNone(mock.return_value,
83 "return value in constructor not honoured")
84
85
86 def test_repr(self):
87 mock = Mock(name='foo')
88 self.assertIn('foo', repr(mock))
89 self.assertIn("'%s'" % id(mock), repr(mock))
90
91 mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')]
92 for mock, name in mocks:
93 self.assertIn('%s.bar' % name, repr(mock.bar))
94 self.assertIn('%s.foo()' % name, repr(mock.foo()))
95 self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing))
96 self.assertIn('%s()' % name, repr(mock()))
97 self.assertIn('%s()()' % name, repr(mock()()))
98 self.assertIn('%s()().foo.bar.baz().bing' % name,
99 repr(mock()().foo.bar.baz().bing))
100
101
102 def test_repr_with_spec(self):
103 class X(object):
104 pass
105
106 mock = Mock(spec=X)
107 self.assertIn(" spec='X' ", repr(mock))
108
109 mock = Mock(spec=X())
110 self.assertIn(" spec='X' ", repr(mock))
111
112 mock = Mock(spec_set=X)
113 self.assertIn(" spec_set='X' ", repr(mock))
114
115 mock = Mock(spec_set=X())
116 self.assertIn(" spec_set='X' ", repr(mock))
117
118 mock = Mock(spec=X, name='foo')
119 self.assertIn(" spec='X' ", repr(mock))
120 self.assertIn(" name='foo' ", repr(mock))
121
122 mock = Mock(name='foo')
123 self.assertNotIn("spec", repr(mock))
124
125 mock = Mock()
126 self.assertNotIn("spec", repr(mock))
127
128 mock = Mock(spec=['foo'])
129 self.assertNotIn("spec", repr(mock))
130
131
132 def test_side_effect(self):
133 mock = Mock()
134
135 def effect(*args, **kwargs):
136 raise SystemError('kablooie')
137
138 mock.side_effect = effect
139 self.assertRaises(SystemError, mock, 1, 2, fish=3)
140 mock.assert_called_with(1, 2, fish=3)
141
142 results = [1, 2, 3]
143 def effect():
144 return results.pop()
145 mock.side_effect = effect
146
147 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
148 "side effect not used correctly")
149
150 mock = Mock(side_effect=sentinel.SideEffect)
151 self.assertEqual(mock.side_effect, sentinel.SideEffect,
152 "side effect in constructor not used")
153
154 def side_effect():
155 return DEFAULT
156 mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
157 self.assertEqual(mock(), sentinel.RETURN)
158
Michael Foord01bafdc2014-04-14 16:09:42 -0400159 def test_autospec_side_effect(self):
160 # Test for issue17826
161 results = [1, 2, 3]
162 def effect():
163 return results.pop()
164 def f():
165 pass
166
167 mock = create_autospec(f)
168 mock.side_effect = [1, 2, 3]
169 self.assertEqual([mock(), mock(), mock()], [1, 2, 3],
170 "side effect not used correctly in create_autospec")
171 # Test where side effect is a callable
172 results = [1, 2, 3]
173 mock = create_autospec(f)
174 mock.side_effect = effect
175 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
176 "callable side effect not used correctly")
Michael Foord345266a2012-03-14 12:24:34 -0700177
Robert Collinsf58f88c2015-07-14 13:51:40 +1200178 def test_autospec_side_effect_exception(self):
179 # Test for issue 23661
180 def f():
181 pass
182
183 mock = create_autospec(f)
184 mock.side_effect = ValueError('Bazinga!')
185 self.assertRaisesRegex(ValueError, 'Bazinga!', mock)
186
Michael Foord345266a2012-03-14 12:24:34 -0700187 @unittest.skipUnless('java' in sys.platform,
188 'This test only applies to Jython')
189 def test_java_exception_side_effect(self):
190 import java
191 mock = Mock(side_effect=java.lang.RuntimeException("Boom!"))
192
193 # can't use assertRaises with java exceptions
194 try:
195 mock(1, 2, fish=3)
196 except java.lang.RuntimeException:
197 pass
198 else:
199 self.fail('java exception not raised')
200 mock.assert_called_with(1,2, fish=3)
201
202
203 def test_reset_mock(self):
204 parent = Mock()
205 spec = ["something"]
206 mock = Mock(name="child", parent=parent, spec=spec)
207 mock(sentinel.Something, something=sentinel.SomethingElse)
208 something = mock.something
209 mock.something()
210 mock.side_effect = sentinel.SideEffect
211 return_value = mock.return_value
212 return_value()
213
214 mock.reset_mock()
215
216 self.assertEqual(mock._mock_name, "child",
217 "name incorrectly reset")
218 self.assertEqual(mock._mock_parent, parent,
219 "parent incorrectly reset")
220 self.assertEqual(mock._mock_methods, spec,
221 "methods incorrectly reset")
222
223 self.assertFalse(mock.called, "called not reset")
224 self.assertEqual(mock.call_count, 0, "call_count not reset")
225 self.assertEqual(mock.call_args, None, "call_args not reset")
226 self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
227 self.assertEqual(mock.method_calls, [],
228 "method_calls not initialised correctly: %r != %r" %
229 (mock.method_calls, []))
230 self.assertEqual(mock.mock_calls, [])
231
232 self.assertEqual(mock.side_effect, sentinel.SideEffect,
233 "side_effect incorrectly reset")
234 self.assertEqual(mock.return_value, return_value,
235 "return_value incorrectly reset")
236 self.assertFalse(return_value.called, "return value mock not reset")
237 self.assertEqual(mock._mock_children, {'something': something},
238 "children reset incorrectly")
239 self.assertEqual(mock.something, something,
240 "children incorrectly cleared")
241 self.assertFalse(mock.something.called, "child not reset")
242
243
244 def test_reset_mock_recursion(self):
245 mock = Mock()
246 mock.return_value = mock
247
248 # used to cause recursion
249 mock.reset_mock()
250
Robert Collinsb37f43f2015-07-15 11:42:28 +1200251 def test_reset_mock_on_mock_open_issue_18622(self):
252 a = mock.mock_open()
253 a.reset_mock()
Michael Foord345266a2012-03-14 12:24:34 -0700254
255 def test_call(self):
256 mock = Mock()
257 self.assertTrue(is_instance(mock.return_value, Mock),
258 "Default return_value should be a Mock")
259
260 result = mock()
261 self.assertEqual(mock(), result,
262 "different result from consecutive calls")
263 mock.reset_mock()
264
265 ret_val = mock(sentinel.Arg)
266 self.assertTrue(mock.called, "called not set")
267 self.assertEqual(mock.call_count, 1, "call_count incoreect")
268 self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
269 "call_args not set")
270 self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
271 "call_args_list not initialised correctly")
272
273 mock.return_value = sentinel.ReturnValue
274 ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
275 self.assertEqual(ret_val, sentinel.ReturnValue,
276 "incorrect return value")
277
278 self.assertEqual(mock.call_count, 2, "call_count incorrect")
279 self.assertEqual(mock.call_args,
280 ((sentinel.Arg,), {'key': sentinel.KeyArg}),
281 "call_args not set")
282 self.assertEqual(mock.call_args_list, [
283 ((sentinel.Arg,), {}),
284 ((sentinel.Arg,), {'key': sentinel.KeyArg})
285 ],
286 "call_args_list not set")
287
288
289 def test_call_args_comparison(self):
290 mock = Mock()
291 mock()
292 mock(sentinel.Arg)
293 mock(kw=sentinel.Kwarg)
294 mock(sentinel.Arg, kw=sentinel.Kwarg)
295 self.assertEqual(mock.call_args_list, [
296 (),
297 ((sentinel.Arg,),),
298 ({"kw": sentinel.Kwarg},),
299 ((sentinel.Arg,), {"kw": sentinel.Kwarg})
300 ])
301 self.assertEqual(mock.call_args,
302 ((sentinel.Arg,), {"kw": sentinel.Kwarg}))
303
Berker Peksag3fc536f2015-09-09 23:35:25 +0300304 # Comparing call_args to a long sequence should not raise
305 # an exception. See issue 24857.
306 self.assertFalse(mock.call_args == "a long sequence")
Michael Foord345266a2012-03-14 12:24:34 -0700307
Berker Peksagce913872016-03-28 00:30:02 +0300308
309 def test_calls_equal_with_any(self):
Berker Peksagce913872016-03-28 00:30:02 +0300310 # Check that equality and non-equality is consistent even when
311 # comparing with mock.ANY
Serhiy Storchaka362f0582017-01-21 23:12:58 +0200312 mm = mock.MagicMock()
313 self.assertTrue(mm == mm)
314 self.assertFalse(mm != mm)
315 self.assertFalse(mm == mock.MagicMock())
316 self.assertTrue(mm != mock.MagicMock())
317 self.assertTrue(mm == mock.ANY)
318 self.assertFalse(mm != mock.ANY)
319 self.assertTrue(mock.ANY == mm)
320 self.assertFalse(mock.ANY != mm)
321
322 call1 = mock.call(mock.MagicMock())
323 call2 = mock.call(mock.ANY)
Berker Peksagce913872016-03-28 00:30:02 +0300324 self.assertTrue(call1 == call2)
325 self.assertFalse(call1 != call2)
Serhiy Storchaka362f0582017-01-21 23:12:58 +0200326 self.assertTrue(call2 == call1)
327 self.assertFalse(call2 != call1)
Berker Peksagce913872016-03-28 00:30:02 +0300328
329
Michael Foord345266a2012-03-14 12:24:34 -0700330 def test_assert_called_with(self):
331 mock = Mock()
332 mock()
333
334 # Will raise an exception if it fails
335 mock.assert_called_with()
336 self.assertRaises(AssertionError, mock.assert_called_with, 1)
337
338 mock.reset_mock()
339 self.assertRaises(AssertionError, mock.assert_called_with)
340
341 mock(1, 2, 3, a='fish', b='nothing')
342 mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
343
344
Berker Peksagce913872016-03-28 00:30:02 +0300345 def test_assert_called_with_any(self):
346 m = MagicMock()
347 m(MagicMock())
348 m.assert_called_with(mock.ANY)
349
350
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100351 def test_assert_called_with_function_spec(self):
352 def f(a, b, c, d=None):
353 pass
354
355 mock = Mock(spec=f)
356
357 mock(1, b=2, c=3)
358 mock.assert_called_with(1, 2, 3)
359 mock.assert_called_with(a=1, b=2, c=3)
360 self.assertRaises(AssertionError, mock.assert_called_with,
361 1, b=3, c=2)
362 # Expected call doesn't match the spec's signature
363 with self.assertRaises(AssertionError) as cm:
364 mock.assert_called_with(e=8)
365 self.assertIsInstance(cm.exception.__cause__, TypeError)
366
367
368 def test_assert_called_with_method_spec(self):
369 def _check(mock):
370 mock(1, b=2, c=3)
371 mock.assert_called_with(1, 2, 3)
372 mock.assert_called_with(a=1, b=2, c=3)
373 self.assertRaises(AssertionError, mock.assert_called_with,
374 1, b=3, c=2)
375
376 mock = Mock(spec=Something().meth)
377 _check(mock)
378 mock = Mock(spec=Something.cmeth)
379 _check(mock)
380 mock = Mock(spec=Something().cmeth)
381 _check(mock)
382 mock = Mock(spec=Something.smeth)
383 _check(mock)
384 mock = Mock(spec=Something().smeth)
385 _check(mock)
386
387
Michael Foord345266a2012-03-14 12:24:34 -0700388 def test_assert_called_once_with(self):
389 mock = Mock()
390 mock()
391
392 # Will raise an exception if it fails
393 mock.assert_called_once_with()
394
395 mock()
396 self.assertRaises(AssertionError, mock.assert_called_once_with)
397
398 mock.reset_mock()
399 self.assertRaises(AssertionError, mock.assert_called_once_with)
400
401 mock('foo', 'bar', baz=2)
402 mock.assert_called_once_with('foo', 'bar', baz=2)
403
404 mock.reset_mock()
405 mock('foo', 'bar', baz=2)
406 self.assertRaises(
407 AssertionError,
408 lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
409 )
410
Petter Strandmark47d94242018-10-28 21:37:10 +0100411 def test_assert_called_once_with_call_list(self):
412 m = Mock()
413 m(1)
414 m(2)
415 self.assertRaisesRegex(AssertionError,
416 re.escape("Calls: [call(1), call(2)]"),
417 lambda: m.assert_called_once_with(2))
418
Michael Foord345266a2012-03-14 12:24:34 -0700419
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100420 def test_assert_called_once_with_function_spec(self):
421 def f(a, b, c, d=None):
422 pass
423
424 mock = Mock(spec=f)
425
426 mock(1, b=2, c=3)
427 mock.assert_called_once_with(1, 2, 3)
428 mock.assert_called_once_with(a=1, b=2, c=3)
429 self.assertRaises(AssertionError, mock.assert_called_once_with,
430 1, b=3, c=2)
431 # Expected call doesn't match the spec's signature
432 with self.assertRaises(AssertionError) as cm:
433 mock.assert_called_once_with(e=8)
434 self.assertIsInstance(cm.exception.__cause__, TypeError)
435 # Mock called more than once => always fails
436 mock(4, 5, 6)
437 self.assertRaises(AssertionError, mock.assert_called_once_with,
438 1, 2, 3)
439 self.assertRaises(AssertionError, mock.assert_called_once_with,
440 4, 5, 6)
441
442
Michael Foord345266a2012-03-14 12:24:34 -0700443 def test_attribute_access_returns_mocks(self):
444 mock = Mock()
445 something = mock.something
446 self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
447 self.assertEqual(mock.something, something,
448 "different attributes returned for same name")
449
450 # Usage example
451 mock = Mock()
452 mock.something.return_value = 3
453
454 self.assertEqual(mock.something(), 3, "method returned wrong value")
455 self.assertTrue(mock.something.called,
456 "method didn't record being called")
457
458
459 def test_attributes_have_name_and_parent_set(self):
460 mock = Mock()
461 something = mock.something
462
463 self.assertEqual(something._mock_name, "something",
464 "attribute name not set correctly")
465 self.assertEqual(something._mock_parent, mock,
466 "attribute parent not set correctly")
467
468
469 def test_method_calls_recorded(self):
470 mock = Mock()
471 mock.something(3, fish=None)
472 mock.something_else.something(6, cake=sentinel.Cake)
473
474 self.assertEqual(mock.something_else.method_calls,
475 [("something", (6,), {'cake': sentinel.Cake})],
476 "method calls not recorded correctly")
477 self.assertEqual(mock.method_calls, [
478 ("something", (3,), {'fish': None}),
479 ("something_else.something", (6,), {'cake': sentinel.Cake})
480 ],
481 "method calls not recorded correctly")
482
483
484 def test_method_calls_compare_easily(self):
485 mock = Mock()
486 mock.something()
487 self.assertEqual(mock.method_calls, [('something',)])
488 self.assertEqual(mock.method_calls, [('something', (), {})])
489
490 mock = Mock()
491 mock.something('different')
492 self.assertEqual(mock.method_calls, [('something', ('different',))])
493 self.assertEqual(mock.method_calls,
494 [('something', ('different',), {})])
495
496 mock = Mock()
497 mock.something(x=1)
498 self.assertEqual(mock.method_calls, [('something', {'x': 1})])
499 self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
500
501 mock = Mock()
502 mock.something('different', some='more')
503 self.assertEqual(mock.method_calls, [
504 ('something', ('different',), {'some': 'more'})
505 ])
506
507
508 def test_only_allowed_methods_exist(self):
509 for spec in ['something'], ('something',):
510 for arg in 'spec', 'spec_set':
511 mock = Mock(**{arg: spec})
512
513 # this should be allowed
514 mock.something
515 self.assertRaisesRegex(
516 AttributeError,
517 "Mock object has no attribute 'something_else'",
518 getattr, mock, 'something_else'
519 )
520
521
522 def test_from_spec(self):
523 class Something(object):
524 x = 3
525 __something__ = None
526 def y(self):
527 pass
528
529 def test_attributes(mock):
530 # should work
531 mock.x
532 mock.y
533 mock.__something__
534 self.assertRaisesRegex(
535 AttributeError,
536 "Mock object has no attribute 'z'",
537 getattr, mock, 'z'
538 )
539 self.assertRaisesRegex(
540 AttributeError,
541 "Mock object has no attribute '__foobar__'",
542 getattr, mock, '__foobar__'
543 )
544
545 test_attributes(Mock(spec=Something))
546 test_attributes(Mock(spec=Something()))
547
548
549 def test_wraps_calls(self):
550 real = Mock()
551
552 mock = Mock(wraps=real)
553 self.assertEqual(mock(), real())
554
555 real.reset_mock()
556
557 mock(1, 2, fish=3)
558 real.assert_called_with(1, 2, fish=3)
559
560
Mario Corcherof05df0a2018-12-08 11:25:02 +0000561 def test_wraps_prevents_automatic_creation_of_mocks(self):
562 class Real(object):
563 pass
564
565 real = Real()
566 mock = Mock(wraps=real)
567
568 self.assertRaises(AttributeError, lambda: mock.new_attr())
569
570
Michael Foord345266a2012-03-14 12:24:34 -0700571 def test_wraps_call_with_nondefault_return_value(self):
572 real = Mock()
573
574 mock = Mock(wraps=real)
575 mock.return_value = 3
576
577 self.assertEqual(mock(), 3)
578 self.assertFalse(real.called)
579
580
581 def test_wraps_attributes(self):
582 class Real(object):
583 attribute = Mock()
584
585 real = Real()
586
587 mock = Mock(wraps=real)
588 self.assertEqual(mock.attribute(), real.attribute())
589 self.assertRaises(AttributeError, lambda: mock.fish)
590
591 self.assertNotEqual(mock.attribute, real.attribute)
592 result = mock.attribute.frog(1, 2, fish=3)
593 Real.attribute.frog.assert_called_with(1, 2, fish=3)
594 self.assertEqual(result, Real.attribute.frog())
595
596
Mario Corcherof05df0a2018-12-08 11:25:02 +0000597 def test_customize_wrapped_object_with_side_effect_iterable_with_default(self):
598 class Real(object):
599 def method(self):
600 return sentinel.ORIGINAL_VALUE
601
602 real = Real()
603 mock = Mock(wraps=real)
604 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
605
606 self.assertEqual(mock.method(), sentinel.VALUE1)
607 self.assertEqual(mock.method(), sentinel.ORIGINAL_VALUE)
608 self.assertRaises(StopIteration, mock.method)
609
610
611 def test_customize_wrapped_object_with_side_effect_iterable(self):
612 class Real(object):
613 def method(self):
614 raise NotImplementedError()
615
616 real = Real()
617 mock = Mock(wraps=real)
618 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
619
620 self.assertEqual(mock.method(), sentinel.VALUE1)
621 self.assertEqual(mock.method(), sentinel.VALUE2)
622 self.assertRaises(StopIteration, mock.method)
623
624
625 def test_customize_wrapped_object_with_side_effect_exception(self):
626 class Real(object):
627 def method(self):
628 raise NotImplementedError()
629
630 real = Real()
631 mock = Mock(wraps=real)
632 mock.method.side_effect = RuntimeError
633
634 self.assertRaises(RuntimeError, mock.method)
635
636
637 def test_customize_wrapped_object_with_side_effect_function(self):
638 class Real(object):
639 def method(self):
640 raise NotImplementedError()
641
642 def side_effect():
643 return sentinel.VALUE
644
645 real = Real()
646 mock = Mock(wraps=real)
647 mock.method.side_effect = side_effect
648
649 self.assertEqual(mock.method(), sentinel.VALUE)
650
651
652 def test_customize_wrapped_object_with_return_value(self):
653 class Real(object):
654 def method(self):
655 raise NotImplementedError()
656
657 real = Real()
658 mock = Mock(wraps=real)
659 mock.method.return_value = sentinel.VALUE
660
661 self.assertEqual(mock.method(), sentinel.VALUE)
662
663
664 def test_customize_wrapped_object_with_return_value_and_side_effect(self):
665 # side_effect should always take precedence over return_value.
666 class Real(object):
667 def method(self):
668 raise NotImplementedError()
669
670 real = Real()
671 mock = Mock(wraps=real)
672 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
673 mock.method.return_value = sentinel.WRONG_VALUE
674
675 self.assertEqual(mock.method(), sentinel.VALUE1)
676 self.assertEqual(mock.method(), sentinel.VALUE2)
677 self.assertRaises(StopIteration, mock.method)
678
679
680 def test_customize_wrapped_object_with_return_value_and_side_effect2(self):
681 # side_effect can return DEFAULT to default to return_value
682 class Real(object):
683 def method(self):
684 raise NotImplementedError()
685
686 real = Real()
687 mock = Mock(wraps=real)
688 mock.method.side_effect = lambda: DEFAULT
689 mock.method.return_value = sentinel.VALUE
690
691 self.assertEqual(mock.method(), sentinel.VALUE)
692
693
694 def test_customize_wrapped_object_with_return_value_and_side_effect_default(self):
695 class Real(object):
696 def method(self):
697 raise NotImplementedError()
698
699 real = Real()
700 mock = Mock(wraps=real)
701 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
702 mock.method.return_value = sentinel.RETURN
703
704 self.assertEqual(mock.method(), sentinel.VALUE1)
705 self.assertEqual(mock.method(), sentinel.RETURN)
706 self.assertRaises(StopIteration, mock.method)
707
708
Michael Foord345266a2012-03-14 12:24:34 -0700709 def test_exceptional_side_effect(self):
710 mock = Mock(side_effect=AttributeError)
711 self.assertRaises(AttributeError, mock)
712
713 mock = Mock(side_effect=AttributeError('foo'))
714 self.assertRaises(AttributeError, mock)
715
716
717 def test_baseexceptional_side_effect(self):
718 mock = Mock(side_effect=KeyboardInterrupt)
719 self.assertRaises(KeyboardInterrupt, mock)
720
721 mock = Mock(side_effect=KeyboardInterrupt('foo'))
722 self.assertRaises(KeyboardInterrupt, mock)
723
724
725 def test_assert_called_with_message(self):
726 mock = Mock()
727 self.assertRaisesRegex(AssertionError, 'Not called',
728 mock.assert_called_with)
729
730
Michael Foord28d591c2012-09-28 16:15:22 +0100731 def test_assert_called_once_with_message(self):
732 mock = Mock(name='geoffrey')
733 self.assertRaisesRegex(AssertionError,
734 r"Expected 'geoffrey' to be called once\.",
735 mock.assert_called_once_with)
736
737
Michael Foord345266a2012-03-14 12:24:34 -0700738 def test__name__(self):
739 mock = Mock()
740 self.assertRaises(AttributeError, lambda: mock.__name__)
741
742 mock.__name__ = 'foo'
743 self.assertEqual(mock.__name__, 'foo')
744
745
746 def test_spec_list_subclass(self):
747 class Sub(list):
748 pass
749 mock = Mock(spec=Sub(['foo']))
750
751 mock.append(3)
752 mock.append.assert_called_with(3)
753 self.assertRaises(AttributeError, getattr, mock, 'foo')
754
755
756 def test_spec_class(self):
757 class X(object):
758 pass
759
760 mock = Mock(spec=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200761 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700762
763 mock = Mock(spec=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200764 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700765
766 self.assertIs(mock.__class__, X)
767 self.assertEqual(Mock().__class__.__name__, 'Mock')
768
769 mock = Mock(spec_set=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200770 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700771
772 mock = Mock(spec_set=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200773 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700774
775
776 def test_setting_attribute_with_spec_set(self):
777 class X(object):
778 y = 3
779
780 mock = Mock(spec=X)
781 mock.x = 'foo'
782
783 mock = Mock(spec_set=X)
784 def set_attr():
785 mock.x = 'foo'
786
787 mock.y = 'foo'
788 self.assertRaises(AttributeError, set_attr)
789
790
791 def test_copy(self):
792 current = sys.getrecursionlimit()
793 self.addCleanup(sys.setrecursionlimit, current)
794
795 # can't use sys.maxint as this doesn't exist in Python 3
796 sys.setrecursionlimit(int(10e8))
797 # this segfaults without the fix in place
798 copy.copy(Mock())
799
800
801 def test_subclass_with_properties(self):
802 class SubClass(Mock):
803 def _get(self):
804 return 3
805 def _set(self, value):
806 raise NameError('strange error')
807 some_attribute = property(_get, _set)
808
809 s = SubClass(spec_set=SubClass)
810 self.assertEqual(s.some_attribute, 3)
811
812 def test():
813 s.some_attribute = 3
814 self.assertRaises(NameError, test)
815
816 def test():
817 s.foo = 'bar'
818 self.assertRaises(AttributeError, test)
819
820
821 def test_setting_call(self):
822 mock = Mock()
823 def __call__(self, a):
824 return self._mock_call(a)
825
826 type(mock).__call__ = __call__
827 mock('one')
828 mock.assert_called_with('one')
829
830 self.assertRaises(TypeError, mock, 'one', 'two')
831
832
833 def test_dir(self):
834 mock = Mock()
835 attrs = set(dir(mock))
836 type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
837
838 # all public attributes from the type are included
839 self.assertEqual(set(), type_attrs - attrs)
840
841 # creates these attributes
842 mock.a, mock.b
843 self.assertIn('a', dir(mock))
844 self.assertIn('b', dir(mock))
845
846 # instance attributes
847 mock.c = mock.d = None
848 self.assertIn('c', dir(mock))
849 self.assertIn('d', dir(mock))
850
851 # magic methods
852 mock.__iter__ = lambda s: iter([])
853 self.assertIn('__iter__', dir(mock))
854
855
856 def test_dir_from_spec(self):
857 mock = Mock(spec=unittest.TestCase)
858 testcase_attrs = set(dir(unittest.TestCase))
859 attrs = set(dir(mock))
860
861 # all attributes from the spec are included
862 self.assertEqual(set(), testcase_attrs - attrs)
863
864 # shadow a sys attribute
865 mock.version = 3
866 self.assertEqual(dir(mock).count('version'), 1)
867
868
869 def test_filter_dir(self):
870 patcher = patch.object(mock, 'FILTER_DIR', False)
871 patcher.start()
872 try:
873 attrs = set(dir(Mock()))
874 type_attrs = set(dir(Mock))
875
876 # ALL attributes from the type are included
877 self.assertEqual(set(), type_attrs - attrs)
878 finally:
879 patcher.stop()
880
881
882 def test_configure_mock(self):
883 mock = Mock(foo='bar')
884 self.assertEqual(mock.foo, 'bar')
885
886 mock = MagicMock(foo='bar')
887 self.assertEqual(mock.foo, 'bar')
888
889 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
890 'foo': MagicMock()}
891 mock = Mock(**kwargs)
892 self.assertRaises(KeyError, mock)
893 self.assertEqual(mock.foo.bar(), 33)
894 self.assertIsInstance(mock.foo, MagicMock)
895
896 mock = Mock()
897 mock.configure_mock(**kwargs)
898 self.assertRaises(KeyError, mock)
899 self.assertEqual(mock.foo.bar(), 33)
900 self.assertIsInstance(mock.foo, MagicMock)
901
902
903 def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
904 # needed because assertRaisesRegex doesn't work easily with newlines
905 try:
906 func(*args, **kwargs)
907 except:
908 instance = sys.exc_info()[1]
909 self.assertIsInstance(instance, exception)
910 else:
911 self.fail('Exception %r not raised' % (exception,))
912
913 msg = str(instance)
914 self.assertEqual(msg, message)
915
916
917 def test_assert_called_with_failure_message(self):
918 mock = NonCallableMock()
919
920 expected = "mock(1, '2', 3, bar='foo')"
921 message = 'Expected call: %s\nNot called'
922 self.assertRaisesWithMsg(
923 AssertionError, message % (expected,),
924 mock.assert_called_with, 1, '2', 3, bar='foo'
925 )
926
927 mock.foo(1, '2', 3, foo='foo')
928
929
930 asserters = [
931 mock.foo.assert_called_with, mock.foo.assert_called_once_with
932 ]
933 for meth in asserters:
934 actual = "foo(1, '2', 3, foo='foo')"
935 expected = "foo(1, '2', 3, bar='foo')"
936 message = 'Expected call: %s\nActual call: %s'
937 self.assertRaisesWithMsg(
938 AssertionError, message % (expected, actual),
939 meth, 1, '2', 3, bar='foo'
940 )
941
942 # just kwargs
943 for meth in asserters:
944 actual = "foo(1, '2', 3, foo='foo')"
945 expected = "foo(bar='foo')"
946 message = 'Expected call: %s\nActual call: %s'
947 self.assertRaisesWithMsg(
948 AssertionError, message % (expected, actual),
949 meth, bar='foo'
950 )
951
952 # just args
953 for meth in asserters:
954 actual = "foo(1, '2', 3, foo='foo')"
955 expected = "foo(1, 2, 3)"
956 message = 'Expected call: %s\nActual call: %s'
957 self.assertRaisesWithMsg(
958 AssertionError, message % (expected, actual),
959 meth, 1, 2, 3
960 )
961
962 # empty
963 for meth in asserters:
964 actual = "foo(1, '2', 3, foo='foo')"
965 expected = "foo()"
966 message = 'Expected call: %s\nActual call: %s'
967 self.assertRaisesWithMsg(
968 AssertionError, message % (expected, actual), meth
969 )
970
971
972 def test_mock_calls(self):
973 mock = MagicMock()
974
975 # need to do this because MagicMock.mock_calls used to just return
976 # a MagicMock which also returned a MagicMock when __eq__ was called
977 self.assertIs(mock.mock_calls == [], True)
978
979 mock = MagicMock()
980 mock()
981 expected = [('', (), {})]
982 self.assertEqual(mock.mock_calls, expected)
983
984 mock.foo()
985 expected.append(call.foo())
986 self.assertEqual(mock.mock_calls, expected)
987 # intermediate mock_calls work too
988 self.assertEqual(mock.foo.mock_calls, [('', (), {})])
989
990 mock = MagicMock()
991 mock().foo(1, 2, 3, a=4, b=5)
992 expected = [
993 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
994 ]
995 self.assertEqual(mock.mock_calls, expected)
996 self.assertEqual(mock.return_value.foo.mock_calls,
997 [('', (1, 2, 3), dict(a=4, b=5))])
998 self.assertEqual(mock.return_value.mock_calls,
999 [('foo', (1, 2, 3), dict(a=4, b=5))])
1000
1001 mock = MagicMock()
1002 mock().foo.bar().baz()
1003 expected = [
1004 ('', (), {}), ('().foo.bar', (), {}),
1005 ('().foo.bar().baz', (), {})
1006 ]
1007 self.assertEqual(mock.mock_calls, expected)
1008 self.assertEqual(mock().mock_calls,
1009 call.foo.bar().baz().call_list())
1010
1011 for kwargs in dict(), dict(name='bar'):
1012 mock = MagicMock(**kwargs)
1013 int(mock.foo)
1014 expected = [('foo.__int__', (), {})]
1015 self.assertEqual(mock.mock_calls, expected)
1016
1017 mock = MagicMock(**kwargs)
1018 mock.a()()
1019 expected = [('a', (), {}), ('a()', (), {})]
1020 self.assertEqual(mock.mock_calls, expected)
1021 self.assertEqual(mock.a().mock_calls, [call()])
1022
1023 mock = MagicMock(**kwargs)
1024 mock(1)(2)(3)
1025 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
1026 self.assertEqual(mock().mock_calls, call(2)(3).call_list())
1027 self.assertEqual(mock()().mock_calls, call(3).call_list())
1028
1029 mock = MagicMock(**kwargs)
1030 mock(1)(2)(3).a.b.c(4)
1031 self.assertEqual(mock.mock_calls,
1032 call(1)(2)(3).a.b.c(4).call_list())
1033 self.assertEqual(mock().mock_calls,
1034 call(2)(3).a.b.c(4).call_list())
1035 self.assertEqual(mock()().mock_calls,
1036 call(3).a.b.c(4).call_list())
1037
1038 mock = MagicMock(**kwargs)
1039 int(mock().foo.bar().baz())
1040 last_call = ('().foo.bar().baz().__int__', (), {})
1041 self.assertEqual(mock.mock_calls[-1], last_call)
1042 self.assertEqual(mock().mock_calls,
1043 call.foo.bar().baz().__int__().call_list())
1044 self.assertEqual(mock().foo.bar().mock_calls,
1045 call.baz().__int__().call_list())
1046 self.assertEqual(mock().foo.bar().baz.mock_calls,
1047 call().__int__().call_list())
1048
1049
Chris Withers8ca0fa92018-12-03 21:31:37 +00001050 def test_child_mock_call_equal(self):
1051 m = Mock()
1052 result = m()
1053 result.wibble()
1054 # parent looks like this:
1055 self.assertEqual(m.mock_calls, [call(), call().wibble()])
1056 # but child should look like this:
1057 self.assertEqual(result.mock_calls, [call.wibble()])
1058
1059
1060 def test_mock_call_not_equal_leaf(self):
1061 m = Mock()
1062 m.foo().something()
1063 self.assertNotEqual(m.mock_calls[1], call.foo().different())
1064 self.assertEqual(m.mock_calls[0], call.foo())
1065
1066
1067 def test_mock_call_not_equal_non_leaf(self):
1068 m = Mock()
1069 m.foo().bar()
1070 self.assertNotEqual(m.mock_calls[1], call.baz().bar())
1071 self.assertNotEqual(m.mock_calls[0], call.baz())
1072
1073
1074 def test_mock_call_not_equal_non_leaf_params_different(self):
1075 m = Mock()
1076 m.foo(x=1).bar()
1077 # This isn't ideal, but there's no way to fix it without breaking backwards compatibility:
1078 self.assertEqual(m.mock_calls[1], call.foo(x=2).bar())
1079
1080
1081 def test_mock_call_not_equal_non_leaf_attr(self):
1082 m = Mock()
1083 m.foo.bar()
1084 self.assertNotEqual(m.mock_calls[0], call.baz.bar())
1085
1086
1087 def test_mock_call_not_equal_non_leaf_call_versus_attr(self):
1088 m = Mock()
1089 m.foo.bar()
1090 self.assertNotEqual(m.mock_calls[0], call.foo().bar())
1091
1092
1093 def test_mock_call_repr(self):
1094 m = Mock()
1095 m.foo().bar().baz.bob()
1096 self.assertEqual(repr(m.mock_calls[0]), 'call.foo()')
1097 self.assertEqual(repr(m.mock_calls[1]), 'call.foo().bar()')
1098 self.assertEqual(repr(m.mock_calls[2]), 'call.foo().bar().baz.bob()')
1099
1100
Michael Foord345266a2012-03-14 12:24:34 -07001101 def test_subclassing(self):
1102 class Subclass(Mock):
1103 pass
1104
1105 mock = Subclass()
1106 self.assertIsInstance(mock.foo, Subclass)
1107 self.assertIsInstance(mock(), Subclass)
1108
1109 class Subclass(Mock):
1110 def _get_child_mock(self, **kwargs):
1111 return Mock(**kwargs)
1112
1113 mock = Subclass()
1114 self.assertNotIsInstance(mock.foo, Subclass)
1115 self.assertNotIsInstance(mock(), Subclass)
1116
1117
1118 def test_arg_lists(self):
1119 mocks = [
1120 Mock(),
1121 MagicMock(),
1122 NonCallableMock(),
1123 NonCallableMagicMock()
1124 ]
1125
1126 def assert_attrs(mock):
1127 names = 'call_args_list', 'method_calls', 'mock_calls'
1128 for name in names:
1129 attr = getattr(mock, name)
1130 self.assertIsInstance(attr, _CallList)
1131 self.assertIsInstance(attr, list)
1132 self.assertEqual(attr, [])
1133
1134 for mock in mocks:
1135 assert_attrs(mock)
1136
1137 if callable(mock):
1138 mock()
1139 mock(1, 2)
1140 mock(a=3)
1141
1142 mock.reset_mock()
1143 assert_attrs(mock)
1144
1145 mock.foo()
1146 mock.foo.bar(1, a=3)
1147 mock.foo(1).bar().baz(3)
1148
1149 mock.reset_mock()
1150 assert_attrs(mock)
1151
1152
1153 def test_call_args_two_tuple(self):
1154 mock = Mock()
1155 mock(1, a=3)
1156 mock(2, b=4)
1157
1158 self.assertEqual(len(mock.call_args), 2)
1159 args, kwargs = mock.call_args
1160 self.assertEqual(args, (2,))
1161 self.assertEqual(kwargs, dict(b=4))
1162
1163 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
1164 for expected, call_args in zip(expected_list, mock.call_args_list):
1165 self.assertEqual(len(call_args), 2)
1166 self.assertEqual(expected[0], call_args[0])
1167 self.assertEqual(expected[1], call_args[1])
1168
1169
1170 def test_side_effect_iterator(self):
1171 mock = Mock(side_effect=iter([1, 2, 3]))
1172 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1173 self.assertRaises(StopIteration, mock)
1174
1175 mock = MagicMock(side_effect=['a', 'b', 'c'])
1176 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1177 self.assertRaises(StopIteration, mock)
1178
1179 mock = Mock(side_effect='ghi')
1180 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
1181 self.assertRaises(StopIteration, mock)
1182
1183 class Foo(object):
1184 pass
1185 mock = MagicMock(side_effect=Foo)
1186 self.assertIsInstance(mock(), Foo)
1187
1188 mock = Mock(side_effect=Iter())
1189 self.assertEqual([mock(), mock(), mock(), mock()],
1190 ['this', 'is', 'an', 'iter'])
1191 self.assertRaises(StopIteration, mock)
1192
1193
Michael Foord2cd48732012-04-21 15:52:11 +01001194 def test_side_effect_iterator_exceptions(self):
1195 for Klass in Mock, MagicMock:
1196 iterable = (ValueError, 3, KeyError, 6)
1197 m = Klass(side_effect=iterable)
1198 self.assertRaises(ValueError, m)
1199 self.assertEqual(m(), 3)
1200 self.assertRaises(KeyError, m)
1201 self.assertEqual(m(), 6)
1202
1203
Michael Foord345266a2012-03-14 12:24:34 -07001204 def test_side_effect_setting_iterator(self):
1205 mock = Mock()
1206 mock.side_effect = iter([1, 2, 3])
1207 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1208 self.assertRaises(StopIteration, mock)
1209 side_effect = mock.side_effect
1210 self.assertIsInstance(side_effect, type(iter([])))
1211
1212 mock.side_effect = ['a', 'b', 'c']
1213 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1214 self.assertRaises(StopIteration, mock)
1215 side_effect = mock.side_effect
1216 self.assertIsInstance(side_effect, type(iter([])))
1217
1218 this_iter = Iter()
1219 mock.side_effect = this_iter
1220 self.assertEqual([mock(), mock(), mock(), mock()],
1221 ['this', 'is', 'an', 'iter'])
1222 self.assertRaises(StopIteration, mock)
1223 self.assertIs(mock.side_effect, this_iter)
1224
Andrew Svetlov8b2cd752013-04-07 16:42:24 +03001225 def test_side_effect_iterator_default(self):
1226 mock = Mock(return_value=2)
1227 mock.side_effect = iter([1, DEFAULT])
1228 self.assertEqual([mock(), mock()], [1, 2])
Michael Foord345266a2012-03-14 12:24:34 -07001229
1230 def test_assert_has_calls_any_order(self):
1231 mock = Mock()
1232 mock(1, 2)
1233 mock(a=3)
1234 mock(3, 4)
1235 mock(b=6)
1236 mock(b=6)
1237
1238 kalls = [
1239 call(1, 2), ({'a': 3},),
1240 ((3, 4),), ((), {'a': 3}),
1241 ('', (1, 2)), ('', {'a': 3}),
1242 ('', (1, 2), {}), ('', (), {'a': 3})
1243 ]
1244 for kall in kalls:
1245 mock.assert_has_calls([kall], any_order=True)
1246
1247 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
1248 self.assertRaises(
1249 AssertionError, mock.assert_has_calls,
1250 [kall], any_order=True
1251 )
1252
1253 kall_lists = [
1254 [call(1, 2), call(b=6)],
1255 [call(3, 4), call(1, 2)],
1256 [call(b=6), call(b=6)],
1257 ]
1258
1259 for kall_list in kall_lists:
1260 mock.assert_has_calls(kall_list, any_order=True)
1261
1262 kall_lists = [
1263 [call(b=6), call(b=6), call(b=6)],
1264 [call(1, 2), call(1, 2)],
1265 [call(3, 4), call(1, 2), call(5, 7)],
1266 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
1267 ]
1268 for kall_list in kall_lists:
1269 self.assertRaises(
1270 AssertionError, mock.assert_has_calls,
1271 kall_list, any_order=True
1272 )
1273
1274 def test_assert_has_calls(self):
1275 kalls1 = [
1276 call(1, 2), ({'a': 3},),
1277 ((3, 4),), call(b=6),
1278 ('', (1,), {'b': 6}),
1279 ]
1280 kalls2 = [call.foo(), call.bar(1)]
1281 kalls2.extend(call.spam().baz(a=3).call_list())
1282 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
1283
1284 mocks = []
1285 for mock in Mock(), MagicMock():
1286 mock(1, 2)
1287 mock(a=3)
1288 mock(3, 4)
1289 mock(b=6)
1290 mock(1, b=6)
1291 mocks.append((mock, kalls1))
1292
1293 mock = Mock()
1294 mock.foo()
1295 mock.bar(1)
1296 mock.spam().baz(a=3)
1297 mock.bam(set(), foo={}).fish([1])
1298 mocks.append((mock, kalls2))
1299
1300 for mock, kalls in mocks:
1301 for i in range(len(kalls)):
1302 for step in 1, 2, 3:
1303 these = kalls[i:i+step]
1304 mock.assert_has_calls(these)
1305
1306 if len(these) > 1:
1307 self.assertRaises(
1308 AssertionError,
1309 mock.assert_has_calls,
1310 list(reversed(these))
1311 )
1312
1313
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001314 def test_assert_has_calls_with_function_spec(self):
1315 def f(a, b, c, d=None):
1316 pass
1317
1318 mock = Mock(spec=f)
1319
1320 mock(1, b=2, c=3)
1321 mock(4, 5, c=6, d=7)
1322 mock(10, 11, c=12)
1323 calls = [
1324 ('', (1, 2, 3), {}),
1325 ('', (4, 5, 6), {'d': 7}),
1326 ((10, 11, 12), {}),
1327 ]
1328 mock.assert_has_calls(calls)
1329 mock.assert_has_calls(calls, any_order=True)
1330 mock.assert_has_calls(calls[1:])
1331 mock.assert_has_calls(calls[1:], any_order=True)
1332 mock.assert_has_calls(calls[:-1])
1333 mock.assert_has_calls(calls[:-1], any_order=True)
1334 # Reversed order
1335 calls = list(reversed(calls))
1336 with self.assertRaises(AssertionError):
1337 mock.assert_has_calls(calls)
1338 mock.assert_has_calls(calls, any_order=True)
1339 with self.assertRaises(AssertionError):
1340 mock.assert_has_calls(calls[1:])
1341 mock.assert_has_calls(calls[1:], any_order=True)
1342 with self.assertRaises(AssertionError):
1343 mock.assert_has_calls(calls[:-1])
1344 mock.assert_has_calls(calls[:-1], any_order=True)
1345
1346
Michael Foord345266a2012-03-14 12:24:34 -07001347 def test_assert_any_call(self):
1348 mock = Mock()
1349 mock(1, 2)
1350 mock(a=3)
1351 mock(1, b=6)
1352
1353 mock.assert_any_call(1, 2)
1354 mock.assert_any_call(a=3)
1355 mock.assert_any_call(1, b=6)
1356
1357 self.assertRaises(
1358 AssertionError,
1359 mock.assert_any_call
1360 )
1361 self.assertRaises(
1362 AssertionError,
1363 mock.assert_any_call,
1364 1, 3
1365 )
1366 self.assertRaises(
1367 AssertionError,
1368 mock.assert_any_call,
1369 a=4
1370 )
1371
1372
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001373 def test_assert_any_call_with_function_spec(self):
1374 def f(a, b, c, d=None):
1375 pass
1376
1377 mock = Mock(spec=f)
1378
1379 mock(1, b=2, c=3)
1380 mock(4, 5, c=6, d=7)
1381 mock.assert_any_call(1, 2, 3)
1382 mock.assert_any_call(a=1, b=2, c=3)
1383 mock.assert_any_call(4, 5, 6, 7)
1384 mock.assert_any_call(a=4, b=5, c=6, d=7)
1385 self.assertRaises(AssertionError, mock.assert_any_call,
1386 1, b=3, c=2)
1387 # Expected call doesn't match the spec's signature
1388 with self.assertRaises(AssertionError) as cm:
1389 mock.assert_any_call(e=8)
1390 self.assertIsInstance(cm.exception.__cause__, TypeError)
1391
1392
Michael Foord345266a2012-03-14 12:24:34 -07001393 def test_mock_calls_create_autospec(self):
1394 def f(a, b):
1395 pass
1396 obj = Iter()
1397 obj.f = f
1398
1399 funcs = [
1400 create_autospec(f),
1401 create_autospec(obj).f
1402 ]
1403 for func in funcs:
1404 func(1, 2)
1405 func(3, 4)
1406
1407 self.assertEqual(
1408 func.mock_calls, [call(1, 2), call(3, 4)]
1409 )
1410
Kushal Das484f8a82014-04-16 01:05:50 +05301411 #Issue21222
1412 def test_create_autospec_with_name(self):
1413 m = mock.create_autospec(object(), name='sweet_func')
1414 self.assertIn('sweet_func', repr(m))
Michael Foord345266a2012-03-14 12:24:34 -07001415
Kushal Das8c145342014-04-16 23:32:21 +05301416 #Issue21238
1417 def test_mock_unsafe(self):
1418 m = Mock()
1419 with self.assertRaises(AttributeError):
1420 m.assert_foo_call()
1421 with self.assertRaises(AttributeError):
1422 m.assret_foo_call()
1423 m = Mock(unsafe=True)
1424 m.assert_foo_call()
1425 m.assret_foo_call()
1426
Kushal Das8af9db32014-04-17 01:36:14 +05301427 #Issue21262
1428 def test_assert_not_called(self):
1429 m = Mock()
1430 m.hello.assert_not_called()
1431 m.hello()
1432 with self.assertRaises(AssertionError):
1433 m.hello.assert_not_called()
1434
Petter Strandmark47d94242018-10-28 21:37:10 +01001435 def test_assert_not_called_message(self):
1436 m = Mock()
1437 m(1, 2)
1438 self.assertRaisesRegex(AssertionError,
1439 re.escape("Calls: [call(1, 2)]"),
1440 m.assert_not_called)
1441
Victor Stinner2c2a4e62016-03-11 22:17:48 +01001442 def test_assert_called(self):
1443 m = Mock()
1444 with self.assertRaises(AssertionError):
1445 m.hello.assert_called()
1446 m.hello()
1447 m.hello.assert_called()
1448
1449 m.hello()
1450 m.hello.assert_called()
1451
1452 def test_assert_called_once(self):
1453 m = Mock()
1454 with self.assertRaises(AssertionError):
1455 m.hello.assert_called_once()
1456 m.hello()
1457 m.hello.assert_called_once()
1458
1459 m.hello()
1460 with self.assertRaises(AssertionError):
1461 m.hello.assert_called_once()
1462
Petter Strandmark47d94242018-10-28 21:37:10 +01001463 def test_assert_called_once_message(self):
1464 m = Mock()
1465 m(1, 2)
1466 m(3)
1467 self.assertRaisesRegex(AssertionError,
1468 re.escape("Calls: [call(1, 2), call(3)]"),
1469 m.assert_called_once)
1470
1471 def test_assert_called_once_message_not_called(self):
1472 m = Mock()
1473 with self.assertRaises(AssertionError) as e:
1474 m.assert_called_once()
1475 self.assertNotIn("Calls:", str(e.exception))
1476
Kushal Das047f14c2014-06-09 13:45:56 +05301477 #Issue21256 printout of keyword args should be in deterministic order
1478 def test_sorted_call_signature(self):
1479 m = Mock()
1480 m.hello(name='hello', daddy='hero')
1481 text = "call(daddy='hero', name='hello')"
R David Murray130a5662014-06-11 17:09:43 -04001482 self.assertEqual(repr(m.hello.call_args), text)
Kushal Das8af9db32014-04-17 01:36:14 +05301483
Kushal Dasa37b9582014-09-16 18:33:37 +05301484 #Issue21270 overrides tuple methods for mock.call objects
1485 def test_override_tuple_methods(self):
1486 c = call.count()
1487 i = call.index(132,'hello')
1488 m = Mock()
1489 m.count()
1490 m.index(132,"hello")
1491 self.assertEqual(m.method_calls[0], c)
1492 self.assertEqual(m.method_calls[1], i)
1493
Kushal Das9cd39a12016-06-02 10:20:16 -07001494 def test_reset_return_sideeffect(self):
1495 m = Mock(return_value=10, side_effect=[2,3])
1496 m.reset_mock(return_value=True, side_effect=True)
1497 self.assertIsInstance(m.return_value, Mock)
1498 self.assertEqual(m.side_effect, None)
1499
1500 def test_reset_return(self):
1501 m = Mock(return_value=10, side_effect=[2,3])
1502 m.reset_mock(return_value=True)
1503 self.assertIsInstance(m.return_value, Mock)
1504 self.assertNotEqual(m.side_effect, None)
1505
1506 def test_reset_sideeffect(self):
1507 m = Mock(return_value=10, side_effect=[2,3])
1508 m.reset_mock(side_effect=True)
1509 self.assertEqual(m.return_value, 10)
1510 self.assertEqual(m.side_effect, None)
1511
Michael Foord345266a2012-03-14 12:24:34 -07001512 def test_mock_add_spec(self):
1513 class _One(object):
1514 one = 1
1515 class _Two(object):
1516 two = 2
1517 class Anything(object):
1518 one = two = three = 'four'
1519
1520 klasses = [
1521 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1522 ]
1523 for Klass in list(klasses):
1524 klasses.append(lambda K=Klass: K(spec=Anything))
1525 klasses.append(lambda K=Klass: K(spec_set=Anything))
1526
1527 for Klass in klasses:
1528 for kwargs in dict(), dict(spec_set=True):
1529 mock = Klass()
1530 #no error
1531 mock.one, mock.two, mock.three
1532
1533 for One, Two in [(_One, _Two), (['one'], ['two'])]:
1534 for kwargs in dict(), dict(spec_set=True):
1535 mock.mock_add_spec(One, **kwargs)
1536
1537 mock.one
1538 self.assertRaises(
1539 AttributeError, getattr, mock, 'two'
1540 )
1541 self.assertRaises(
1542 AttributeError, getattr, mock, 'three'
1543 )
1544 if 'spec_set' in kwargs:
1545 self.assertRaises(
1546 AttributeError, setattr, mock, 'three', None
1547 )
1548
1549 mock.mock_add_spec(Two, **kwargs)
1550 self.assertRaises(
1551 AttributeError, getattr, mock, 'one'
1552 )
1553 mock.two
1554 self.assertRaises(
1555 AttributeError, getattr, mock, 'three'
1556 )
1557 if 'spec_set' in kwargs:
1558 self.assertRaises(
1559 AttributeError, setattr, mock, 'three', None
1560 )
1561 # note that creating a mock, setting an instance attribute, and
1562 # *then* setting a spec doesn't work. Not the intended use case
1563
1564
1565 def test_mock_add_spec_magic_methods(self):
1566 for Klass in MagicMock, NonCallableMagicMock:
1567 mock = Klass()
1568 int(mock)
1569
1570 mock.mock_add_spec(object)
1571 self.assertRaises(TypeError, int, mock)
1572
1573 mock = Klass()
1574 mock['foo']
1575 mock.__int__.return_value =4
1576
1577 mock.mock_add_spec(int)
1578 self.assertEqual(int(mock), 4)
1579 self.assertRaises(TypeError, lambda: mock['foo'])
1580
1581
1582 def test_adding_child_mock(self):
1583 for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock:
1584 mock = Klass()
1585
1586 mock.foo = Mock()
1587 mock.foo()
1588
1589 self.assertEqual(mock.method_calls, [call.foo()])
1590 self.assertEqual(mock.mock_calls, [call.foo()])
1591
1592 mock = Klass()
1593 mock.bar = Mock(name='name')
1594 mock.bar()
1595 self.assertEqual(mock.method_calls, [])
1596 self.assertEqual(mock.mock_calls, [])
1597
1598 # mock with an existing _new_parent but no name
1599 mock = Klass()
1600 mock.baz = MagicMock()()
1601 mock.baz()
1602 self.assertEqual(mock.method_calls, [])
1603 self.assertEqual(mock.mock_calls, [])
1604
1605
1606 def test_adding_return_value_mock(self):
1607 for Klass in Mock, MagicMock:
1608 mock = Klass()
1609 mock.return_value = MagicMock()
1610
1611 mock()()
1612 self.assertEqual(mock.mock_calls, [call(), call()()])
1613
1614
1615 def test_manager_mock(self):
1616 class Foo(object):
1617 one = 'one'
1618 two = 'two'
1619 manager = Mock()
1620 p1 = patch.object(Foo, 'one')
1621 p2 = patch.object(Foo, 'two')
1622
1623 mock_one = p1.start()
1624 self.addCleanup(p1.stop)
1625 mock_two = p2.start()
1626 self.addCleanup(p2.stop)
1627
1628 manager.attach_mock(mock_one, 'one')
1629 manager.attach_mock(mock_two, 'two')
1630
1631 Foo.two()
1632 Foo.one()
1633
1634 self.assertEqual(manager.mock_calls, [call.two(), call.one()])
1635
1636
1637 def test_magic_methods_mock_calls(self):
1638 for Klass in Mock, MagicMock:
1639 m = Klass()
1640 m.__int__ = Mock(return_value=3)
1641 m.__float__ = MagicMock(return_value=3.0)
1642 int(m)
1643 float(m)
1644
1645 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
1646 self.assertEqual(m.method_calls, [])
1647
Robert Collins5329aaa2015-07-17 20:08:45 +12001648 def test_mock_open_reuse_issue_21750(self):
1649 mocked_open = mock.mock_open(read_data='data')
1650 f1 = mocked_open('a-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001651 f1_data = f1.read()
Robert Collins5329aaa2015-07-17 20:08:45 +12001652 f2 = mocked_open('another-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001653 f2_data = f2.read()
1654 self.assertEqual(f1_data, f2_data)
1655
Tony Flury20870232018-09-12 23:21:16 +01001656 def test_mock_open_dunder_iter_issue(self):
1657 # Test dunder_iter method generates the expected result and
1658 # consumes the iterator.
1659 mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue')
1660 f1 = mocked_open('a-name')
1661 lines = [line for line in f1]
1662 self.assertEqual(lines[0], 'Remarkable\n')
1663 self.assertEqual(lines[1], 'Norwegian Blue')
1664 self.assertEqual(list(f1), [])
1665
Robert Collinsca647ef2015-07-24 03:48:20 +12001666 def test_mock_open_write(self):
1667 # Test exception in file writing write()
1668 mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
1669 with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
1670 mock_filehandle = mock_namedtemp.return_value
1671 mock_write = mock_filehandle.write
1672 mock_write.side_effect = OSError('Test 2 Error')
1673 def attempt():
1674 tempfile.NamedTemporaryFile().write('asd')
1675 self.assertRaises(OSError, attempt)
1676
1677 def test_mock_open_alter_readline(self):
1678 mopen = mock.mock_open(read_data='foo\nbarn')
1679 mopen.return_value.readline.side_effect = lambda *args:'abc'
1680 first = mopen().readline()
1681 second = mopen().readline()
1682 self.assertEqual('abc', first)
1683 self.assertEqual('abc', second)
Michael Foord345266a2012-03-14 12:24:34 -07001684
Robert Collins9549a3e2016-05-16 15:22:01 +12001685 def test_mock_open_after_eof(self):
1686 # read, readline and readlines should work after end of file.
1687 _open = mock.mock_open(read_data='foo')
1688 h = _open('bar')
1689 h.read()
1690 self.assertEqual('', h.read())
1691 self.assertEqual('', h.read())
1692 self.assertEqual('', h.readline())
1693 self.assertEqual('', h.readline())
1694 self.assertEqual([], h.readlines())
1695 self.assertEqual([], h.readlines())
1696
Michael Foord345266a2012-03-14 12:24:34 -07001697 def test_mock_parents(self):
1698 for Klass in Mock, MagicMock:
1699 m = Klass()
1700 original_repr = repr(m)
1701 m.return_value = m
1702 self.assertIs(m(), m)
1703 self.assertEqual(repr(m), original_repr)
1704
1705 m.reset_mock()
1706 self.assertIs(m(), m)
1707 self.assertEqual(repr(m), original_repr)
1708
1709 m = Klass()
1710 m.b = m.a
1711 self.assertIn("name='mock.a'", repr(m.b))
1712 self.assertIn("name='mock.a'", repr(m.a))
1713 m.reset_mock()
1714 self.assertIn("name='mock.a'", repr(m.b))
1715 self.assertIn("name='mock.a'", repr(m.a))
1716
1717 m = Klass()
1718 original_repr = repr(m)
1719 m.a = m()
1720 m.a.return_value = m
1721
1722 self.assertEqual(repr(m), original_repr)
1723 self.assertEqual(repr(m.a()), original_repr)
1724
1725
1726 def test_attach_mock(self):
1727 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1728 for Klass in classes:
1729 for Klass2 in classes:
1730 m = Klass()
1731
1732 m2 = Klass2(name='foo')
1733 m.attach_mock(m2, 'bar')
1734
1735 self.assertIs(m.bar, m2)
1736 self.assertIn("name='mock.bar'", repr(m2))
1737
1738 m.bar.baz(1)
1739 self.assertEqual(m.mock_calls, [call.bar.baz(1)])
1740 self.assertEqual(m.method_calls, [call.bar.baz(1)])
1741
1742
1743 def test_attach_mock_return_value(self):
1744 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1745 for Klass in Mock, MagicMock:
1746 for Klass2 in classes:
1747 m = Klass()
1748
1749 m2 = Klass2(name='foo')
1750 m.attach_mock(m2, 'return_value')
1751
1752 self.assertIs(m(), m2)
1753 self.assertIn("name='mock()'", repr(m2))
1754
1755 m2.foo()
1756 self.assertEqual(m.mock_calls, call().foo().call_list())
1757
1758
1759 def test_attribute_deletion(self):
Michael Foord468ec342013-09-15 20:05:19 +12001760 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1761 NonCallableMock()):
Michael Foord345266a2012-03-14 12:24:34 -07001762 self.assertTrue(hasattr(mock, 'm'))
1763
1764 del mock.m
1765 self.assertFalse(hasattr(mock, 'm'))
1766
1767 del mock.f
1768 self.assertFalse(hasattr(mock, 'f'))
1769 self.assertRaises(AttributeError, getattr, mock, 'f')
1770
1771
Pablo Galindo222d3032019-01-21 08:57:46 +00001772 def test_mock_does_not_raise_on_repeated_attribute_deletion(self):
1773 # bpo-20239: Assigning and deleting twice an attribute raises.
1774 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1775 NonCallableMock()):
1776 mock.foo = 3
1777 self.assertTrue(hasattr(mock, 'foo'))
1778 self.assertEqual(mock.foo, 3)
1779
1780 del mock.foo
1781 self.assertFalse(hasattr(mock, 'foo'))
1782
1783 mock.foo = 4
1784 self.assertTrue(hasattr(mock, 'foo'))
1785 self.assertEqual(mock.foo, 4)
1786
1787 del mock.foo
1788 self.assertFalse(hasattr(mock, 'foo'))
1789
1790
1791 def test_mock_raises_when_deleting_nonexistent_attribute(self):
1792 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1793 NonCallableMock()):
1794 del mock.foo
1795 with self.assertRaises(AttributeError):
1796 del mock.foo
1797
1798
Xtreakedeca922018-12-01 15:33:54 +05301799 def test_reset_mock_does_not_raise_on_attr_deletion(self):
1800 # bpo-31177: reset_mock should not raise AttributeError when attributes
1801 # were deleted in a mock instance
1802 mock = Mock()
1803 mock.child = True
1804 del mock.child
1805 mock.reset_mock()
1806 self.assertFalse(hasattr(mock, 'child'))
1807
1808
Michael Foord345266a2012-03-14 12:24:34 -07001809 def test_class_assignable(self):
1810 for mock in Mock(), MagicMock():
1811 self.assertNotIsInstance(mock, int)
1812
1813 mock.__class__ = int
1814 self.assertIsInstance(mock, int)
1815 mock.foo
1816
Andrew Dunaie63e6172018-12-04 11:08:45 +02001817 def test_name_attribute_of_call(self):
1818 # bpo-35357: _Call should not disclose any attributes whose names
1819 # may clash with popular ones (such as ".name")
1820 self.assertIsNotNone(call.name)
1821 self.assertEqual(type(call.name), _Call)
1822 self.assertEqual(type(call.name().name), _Call)
1823
1824 def test_parent_attribute_of_call(self):
1825 # bpo-35357: _Call should not disclose any attributes whose names
1826 # may clash with popular ones (such as ".parent")
1827 self.assertIsNotNone(call.parent)
1828 self.assertEqual(type(call.parent), _Call)
1829 self.assertEqual(type(call.parent().parent), _Call)
1830
Michael Foord345266a2012-03-14 12:24:34 -07001831
Michael Foord345266a2012-03-14 12:24:34 -07001832if __name__ == '__main__':
1833 unittest.main()