Debian Codegraph @

Lib/test/test_unittest/testmock/testmock.py

raw
1 import copy
2 import re
3 import sys
4 import tempfile
5
6 from test.support import ALWAYS_EQ
7 import unittest
8 from test.test_unittest.testmock.support import is_instance
9 from unittest import mock
10 from unittest.mock import (
11 call, DEFAULT, patch, sentinel,
12 MagicMock, Mock, NonCallableMock,
13 NonCallableMagicMock, AsyncMock, _Call, _CallList,
14 create_autospec, InvalidSpecError
15 )
16
17
18 class Iter(object):
19 def __init__(self):
20 self.thing = iter(['this', 'is', 'an', 'iter'])
21
22 def __iter__(self):
23 return self
24
25 def next(self):
26 return next(self.thing)
27
28 __next__ = next
29
30
31 class Something(object):
32 def meth(self, a, b, c, d=None): pass
33
34 @classmethod
35 def cmeth(cls, a, b, c, d=None): pass
36
37 @staticmethod
38 def smeth(a, b, c, d=None): pass
39
40
41 class SomethingElse(object):
42 def __init__(self):
43 self._instance = None
44
45 @property
46 def instance(self):
47 if not self._instance:
48 self._instance = 'object'
49 return self._instance
50
51
52 class Typos():
53 autospect = None
54 auto_spec = None
55 set_spec = None
56
57
58 def something(a): pass
59
60
61 class MockTest(unittest.TestCase):
62
63 def test_all(self):
64 # if __all__ is badly defined then import * will raise an error
65 # We have to exec it because you can't import * inside a method
66 # in Python 3
67 exec("from unittest.mock import *")
68
69
70 def test_constructor(self):
71 mock = Mock()
72
73 self.assertFalse(mock.called, "called not initialised correctly")
74 self.assertEqual(mock.call_count, 0,
75 "call_count not initialised correctly")
76 self.assertTrue(is_instance(mock.return_value, Mock),
77 "return_value not initialised correctly")
78
79 self.assertEqual(mock.call_args, None,
80 "call_args not initialised correctly")
81 self.assertEqual(mock.call_args_list, [],
82 "call_args_list not initialised correctly")
83 self.assertEqual(mock.method_calls, [],
84 "method_calls not initialised correctly")
85
86 # Can't use hasattr for this test as it always returns True on a mock
87 self.assertNotIn('_items', mock.__dict__,
88 "default mock should not have '_items' attribute")
89
90 self.assertIsNone(mock._mock_parent,
91 "parent not initialised correctly")
92 self.assertIsNone(mock._mock_methods,
93 "methods not initialised correctly")
94 self.assertEqual(mock._mock_children, {},
95 "children not initialised incorrectly")
96
97
98 def test_return_value_in_constructor(self):
99 mock = Mock(return_value=None)
100 self.assertIsNone(mock.return_value,
101 "return value in constructor not honoured")
102
103
104 def test_change_return_value_via_delegate(self):
105 def f(): pass
106 mock = create_autospec(f)
107 mock.mock.return_value = 1
108 self.assertEqual(mock(), 1)
109
110
111 def test_change_side_effect_via_delegate(self):
112 def f(): pass
113 mock = create_autospec(f)
114 mock.mock.side_effect = TypeError()
115 with self.assertRaises(TypeError):
116 mock()
117
118 def test_create_autospec_should_be_configurable_by_kwargs(self):
119 """If kwargs are given to configure mock, the function must configure
120 the parent mock during initialization."""
121 mocked_result = 'mocked value'
122 class_mock = create_autospec(spec=Something, **{
123 'return_value.meth.side_effect': [ValueError, DEFAULT],
124 'return_value.meth.return_value': mocked_result})
125 with self.assertRaises(ValueError):
126 class_mock().meth(a=None, b=None, c=None)
127 self.assertEqual(class_mock().meth(a=None, b=None, c=None), mocked_result)
128 # Only the parent mock should be configurable because the user will
129 # pass kwargs with respect to the parent mock.
130 self.assertEqual(class_mock().return_value.meth.side_effect, None)
131
132 def test_create_autospec_correctly_handles_name(self):
133 class X: ...
134 mock = create_autospec(X, spec_set=True, name="Y")
135 self.assertEqual(mock._mock_name, "Y")
136
137 def test_repr(self):
138 mock = Mock(name='foo')
139 self.assertIn('foo', repr(mock))
140 self.assertIn("'%s'" % id(mock), repr(mock))
141
142 mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')]
143 for mock, name in mocks:
144 self.assertIn('%s.bar' % name, repr(mock.bar))
145 self.assertIn('%s.foo()' % name, repr(mock.foo()))
146 self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing))
147 self.assertIn('%s()' % name, repr(mock()))
148 self.assertIn('%s()()' % name, repr(mock()()))
149 self.assertIn('%s()().foo.bar.baz().bing' % name,
150 repr(mock()().foo.bar.baz().bing))
151
152
153 def test_repr_with_spec(self):
154 class X(object):
155 pass
156
157 mock = Mock(spec=X)
158 self.assertIn(" spec='X' ", repr(mock))
159
160 mock = Mock(spec=X())
161 self.assertIn(" spec='X' ", repr(mock))
162
163 mock = Mock(spec_set=X)
164 self.assertIn(" spec_set='X' ", repr(mock))
165
166 mock = Mock(spec_set=X())
167 self.assertIn(" spec_set='X' ", repr(mock))
168
169 mock = Mock(spec=X, name='foo')
170 self.assertIn(" spec='X' ", repr(mock))
171 self.assertIn(" name='foo' ", repr(mock))
172
173 mock = Mock(name='foo')
174 self.assertNotIn("spec", repr(mock))
175
176 mock = Mock()
177 self.assertNotIn("spec", repr(mock))
178
179 mock = Mock(spec=['foo'])
180 self.assertNotIn("spec", repr(mock))
181
182
183 def test_side_effect(self):
184 mock = Mock()
185
186 def effect(*args, **kwargs):
187 raise SystemError('kablooie')
188
189 mock.side_effect = effect
190 self.assertRaises(SystemError, mock, 1, 2, fish=3)
191 mock.assert_called_with(1, 2, fish=3)
192
193 results = [1, 2, 3]
194 def effect():
195 return results.pop()
196 mock.side_effect = effect
197
198 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
199 "side effect not used correctly")
200
201 mock = Mock(side_effect=sentinel.SideEffect)
202 self.assertEqual(mock.side_effect, sentinel.SideEffect,
203 "side effect in constructor not used")
204
205 def side_effect():
206 return DEFAULT
207 mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
208 self.assertEqual(mock(), sentinel.RETURN)
209
210 def test_autospec_side_effect(self):
211 # Test for issue17826
212 results = [1, 2, 3]
213 def effect():
214 return results.pop()
215 def f(): pass
216
217 mock = create_autospec(f)
218 mock.side_effect = [1, 2, 3]
219 self.assertEqual([mock(), mock(), mock()], [1, 2, 3],
220 "side effect not used correctly in create_autospec")
221 # Test where side effect is a callable
222 results = [1, 2, 3]
223 mock = create_autospec(f)
224 mock.side_effect = effect
225 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
226 "callable side effect not used correctly")
227
228 def test_autospec_side_effect_exception(self):
229 # Test for issue 23661
230 def f(): pass
231
232 mock = create_autospec(f)
233 mock.side_effect = ValueError('Bazinga!')
234 self.assertRaisesRegex(ValueError, 'Bazinga!', mock)
235
236
237 def test_autospec_mock(self):
238 class A(object):
239 class B(object):
240 C = None
241
242 with mock.patch.object(A, 'B'):
243 with self.assertRaisesRegex(InvalidSpecError,
244 "Cannot autospec attr 'B' from target <MagicMock spec='A'"):
245 create_autospec(A).B
246 with self.assertRaisesRegex(InvalidSpecError,
247 "Cannot autospec attr 'B' from target 'A'"):
248 mock.patch.object(A, 'B', autospec=True).start()
249 with self.assertRaisesRegex(InvalidSpecError,
250 "Cannot autospec attr 'C' as the patch target "):
251 mock.patch.object(A.B, 'C', autospec=True).start()
252 with self.assertRaisesRegex(InvalidSpecError,
253 "Cannot spec attr 'B' as the spec "):
254 mock.patch.object(A, 'B', spec=A.B).start()
255 with self.assertRaisesRegex(InvalidSpecError,
256 "Cannot spec attr 'B' as the spec_set "):
257 mock.patch.object(A, 'B', spec_set=A.B).start()
258 with self.assertRaisesRegex(InvalidSpecError,
259 "Cannot spec attr 'B' as the spec_set "):
260 mock.patch.object(A, 'B', spec_set=A.B).start()
261 with self.assertRaisesRegex(InvalidSpecError, "Cannot spec a Mock object."):
262 mock.Mock(A.B)
263 with mock.patch('builtins.open', mock.mock_open()):
264 mock.mock_open() # should still be valid with open() mocked
265
266 def test_create_autospec_wraps_class(self):
267 """Autospec a class with wraps & test if the call is passed to the
268 wrapped object."""
269 result = "real result"
270
271 class Result:
272 def get_result(self):
273 return result
274 class_mock = create_autospec(spec=Result, wraps=Result)
275 # Have to reassign the return_value to DEFAULT to return the real
276 # result (actual instance of "Result") when the mock is called.
277 class_mock.return_value = mock.DEFAULT
278 self.assertEqual(class_mock().get_result(), result)
279 # Autospec should also wrap child attributes of parent.
280 self.assertEqual(class_mock.get_result._mock_wraps, Result.get_result)
281
282 def test_create_autospec_instance_wraps_class(self):
283 """Autospec a class instance with wraps & test if the call is passed
284 to the wrapped object."""
285 result = "real result"
286
287 class Result:
288 @staticmethod
289 def get_result():
290 """This is a static method because when the mocked instance of
291 'Result' will call this method, it won't be able to consume
292 'self' argument."""
293 return result
294 instance_mock = create_autospec(spec=Result, instance=True, wraps=Result)
295 # Have to reassign the return_value to DEFAULT to return the real
296 # result from "Result.get_result" when the mocked instance of "Result"
297 # calls "get_result".
298 instance_mock.get_result.return_value = mock.DEFAULT
299 self.assertEqual(instance_mock.get_result(), result)
300 # Autospec should also wrap child attributes of the instance.
301 self.assertEqual(instance_mock.get_result._mock_wraps, Result.get_result)
302
303 def test_create_autospec_wraps_function_type(self):
304 """Autospec a function or a method with wraps & test if the call is
305 passed to the wrapped object."""
306 result = "real result"
307
308 class Result:
309 def get_result(self):
310 return result
311 func_mock = create_autospec(spec=Result.get_result, wraps=Result.get_result)
312 self.assertEqual(func_mock(Result()), result)
313
314 def test_explicit_return_value_even_if_mock_wraps_object(self):
315 """If the mock has an explicit return_value set then calls are not
316 passed to the wrapped object and the return_value is returned instead.
317 """
318 def my_func():
319 return None # pragma: no cover
320 func_mock = create_autospec(spec=my_func, wraps=my_func)
321 return_value = "explicit return value"
322 func_mock.return_value = return_value
323 self.assertEqual(func_mock(), return_value)
324
325 def test_explicit_parent(self):
326 parent = Mock()
327 mock1 = Mock(parent=parent, return_value=None)
328 mock1(1, 2, 3)
329 mock2 = Mock(parent=parent, return_value=None)
330 mock2(4, 5, 6)
331
332 self.assertEqual(parent.mock_calls, [call(1, 2, 3), call(4, 5, 6)])
333
334 def test_reset_mock(self):
335 parent = Mock()
336 spec = ["something"]
337 mock = Mock(name="child", parent=parent, spec=spec)
338 mock(sentinel.Something, something=sentinel.SomethingElse)
339 something = mock.something
340 mock.something()
341 mock.side_effect = sentinel.SideEffect
342 return_value = mock.return_value
343 return_value()
344
345 mock.reset_mock()
346
347 self.assertEqual(mock._mock_name, "child",
348 "name incorrectly reset")
349 self.assertEqual(mock._mock_parent, parent,
350 "parent incorrectly reset")
351 self.assertEqual(mock._mock_methods, spec,
352 "methods incorrectly reset")
353
354 self.assertFalse(mock.called, "called not reset")
355 self.assertEqual(mock.call_count, 0, "call_count not reset")
356 self.assertEqual(mock.call_args, None, "call_args not reset")
357 self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
358 self.assertEqual(mock.method_calls, [],
359 "method_calls not initialised correctly: %r != %r" %
360 (mock.method_calls, []))
361 self.assertEqual(mock.mock_calls, [])
362
363 self.assertEqual(mock.side_effect, sentinel.SideEffect,
364 "side_effect incorrectly reset")
365 self.assertEqual(mock.return_value, return_value,
366 "return_value incorrectly reset")
367 self.assertFalse(return_value.called, "return value mock not reset")
368 self.assertEqual(mock._mock_children, {'something': something},
369 "children reset incorrectly")
370 self.assertEqual(mock.something, something,
371 "children incorrectly cleared")
372 self.assertFalse(mock.something.called, "child not reset")
373
374
375 def test_reset_mock_recursion(self):
376 mock = Mock()
377 mock.return_value = mock
378
379 # used to cause recursion
380 mock.reset_mock()
381
382 def test_reset_mock_on_mock_open_issue_18622(self):
383 a = mock.mock_open()
384 a.reset_mock()
385
386 def test_call(self):
387 mock = Mock()
388 self.assertTrue(is_instance(mock.return_value, Mock),
389 "Default return_value should be a Mock")
390
391 result = mock()
392 self.assertEqual(mock(), result,
393 "different result from consecutive calls")
394 mock.reset_mock()
395
396 ret_val = mock(sentinel.Arg)
397 self.assertTrue(mock.called, "called not set")
398 self.assertEqual(mock.call_count, 1, "call_count incorrect")
399 self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
400 "call_args not set")
401 self.assertEqual(mock.call_args.args, (sentinel.Arg,),
402 "call_args not set")
403 self.assertEqual(mock.call_args.kwargs, {},
404 "call_args not set")
405 self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
406 "call_args_list not initialised correctly")
407
408 mock.return_value = sentinel.ReturnValue
409 ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
410 self.assertEqual(ret_val, sentinel.ReturnValue,
411 "incorrect return value")
412
413 self.assertEqual(mock.call_count, 2, "call_count incorrect")
414 self.assertEqual(mock.call_args,
415 ((sentinel.Arg,), {'key': sentinel.KeyArg}),
416 "call_args not set")
417 self.assertEqual(mock.call_args_list, [
418 ((sentinel.Arg,), {}),
419 ((sentinel.Arg,), {'key': sentinel.KeyArg})
420 ],
421 "call_args_list not set")
422
423
424 def test_call_args_comparison(self):
425 mock = Mock()
426 mock()
427 mock(sentinel.Arg)
428 mock(kw=sentinel.Kwarg)
429 mock(sentinel.Arg, kw=sentinel.Kwarg)
430 self.assertEqual(mock.call_args_list, [
431 (),
432 ((sentinel.Arg,),),
433 ({"kw": sentinel.Kwarg},),
434 ((sentinel.Arg,), {"kw": sentinel.Kwarg})
435 ])
436 self.assertEqual(mock.call_args,
437 ((sentinel.Arg,), {"kw": sentinel.Kwarg}))
438 self.assertEqual(mock.call_args.args, (sentinel.Arg,))
439 self.assertEqual(mock.call_args.kwargs, {"kw": sentinel.Kwarg})
440
441 # Comparing call_args to a long sequence should not raise
442 # an exception. See issue 24857.
443 self.assertFalse(mock.call_args == "a long sequence")
444
445
446 def test_calls_equal_with_any(self):
447 # Check that equality and non-equality is consistent even when
448 # comparing with mock.ANY
449 mm = mock.MagicMock()
450 self.assertTrue(mm == mm)
451 self.assertFalse(mm != mm)
452 self.assertFalse(mm == mock.MagicMock())
453 self.assertTrue(mm != mock.MagicMock())
454 self.assertTrue(mm == mock.ANY)
455 self.assertFalse(mm != mock.ANY)
456 self.assertTrue(mock.ANY == mm)
457 self.assertFalse(mock.ANY != mm)
458 self.assertTrue(mm == ALWAYS_EQ)
459 self.assertFalse(mm != ALWAYS_EQ)
460
461 call1 = mock.call(mock.MagicMock())
462 call2 = mock.call(mock.ANY)
463 self.assertTrue(call1 == call2)
464 self.assertFalse(call1 != call2)
465 self.assertTrue(call2 == call1)
466 self.assertFalse(call2 != call1)
467
468 self.assertTrue(call1 == ALWAYS_EQ)
469 self.assertFalse(call1 != ALWAYS_EQ)
470 self.assertFalse(call1 == 1)
471 self.assertTrue(call1 != 1)
472
473
474 def test_assert_called_with(self):
475 mock = Mock()
476 mock()
477
478 # Will raise an exception if it fails
479 mock.assert_called_with()
480 self.assertRaises(AssertionError, mock.assert_called_with, 1)
481
482 mock.reset_mock()
483 self.assertRaises(AssertionError, mock.assert_called_with)
484
485 mock(1, 2, 3, a='fish', b='nothing')
486 mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
487
488
489 def test_assert_called_with_any(self):
490 m = MagicMock()
491 m(MagicMock())
492 m.assert_called_with(mock.ANY)
493
494
495 def test_assert_called_with_function_spec(self):
496 def f(a, b, c, d=None): pass
497
498 mock = Mock(spec=f)
499
500 mock(1, b=2, c=3)
501 mock.assert_called_with(1, 2, 3)
502 mock.assert_called_with(a=1, b=2, c=3)
503 self.assertRaises(AssertionError, mock.assert_called_with,
504 1, b=3, c=2)
505 # Expected call doesn't match the spec's signature
506 with self.assertRaises(AssertionError) as cm:
507 mock.assert_called_with(e=8)
508 self.assertIsInstance(cm.exception.__cause__, TypeError)
509
510
511 def test_assert_called_with_method_spec(self):
512 def _check(mock):
513 mock(1, b=2, c=3)
514 mock.assert_called_with(1, 2, 3)
515 mock.assert_called_with(a=1, b=2, c=3)
516 self.assertRaises(AssertionError, mock.assert_called_with,
517 1, b=3, c=2)
518
519 mock = Mock(spec=Something().meth)
520 _check(mock)
521 mock = Mock(spec=Something.cmeth)
522 _check(mock)
523 mock = Mock(spec=Something().cmeth)
524 _check(mock)
525 mock = Mock(spec=Something.smeth)
526 _check(mock)
527 mock = Mock(spec=Something().smeth)
528 _check(mock)
529
530
531 def test_assert_called_exception_message(self):
532 msg = "Expected '{0}' to have been called"
533 with self.assertRaisesRegex(AssertionError, msg.format('mock')):
534 Mock().assert_called()
535 with self.assertRaisesRegex(AssertionError, msg.format('test_name')):
536 Mock(name="test_name").assert_called()
537
538
539 def test_assert_called_once_with(self):
540 mock = Mock()
541 mock()
542
543 # Will raise an exception if it fails
544 mock.assert_called_once_with()
545
546 mock()
547 self.assertRaises(AssertionError, mock.assert_called_once_with)
548
549 mock.reset_mock()
550 self.assertRaises(AssertionError, mock.assert_called_once_with)
551
552 mock('foo', 'bar', baz=2)
553 mock.assert_called_once_with('foo', 'bar', baz=2)
554
555 mock.reset_mock()
556 mock('foo', 'bar', baz=2)
557 self.assertRaises(
558 AssertionError,
559 lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
560 )
561
562 def test_assert_called_once_with_call_list(self):
563 m = Mock()
564 m(1)
565 m(2)
566 self.assertRaisesRegex(AssertionError,
567 re.escape("Calls: [call(1), call(2)]"),
568 lambda: m.assert_called_once_with(2))
569
570
571 def test_assert_called_once_with_function_spec(self):
572 def f(a, b, c, d=None): pass
573
574 mock = Mock(spec=f)
575
576 mock(1, b=2, c=3)
577 mock.assert_called_once_with(1, 2, 3)
578 mock.assert_called_once_with(a=1, b=2, c=3)
579 self.assertRaises(AssertionError, mock.assert_called_once_with,
580 1, b=3, c=2)
581 # Expected call doesn't match the spec's signature
582 with self.assertRaises(AssertionError) as cm:
583 mock.assert_called_once_with(e=8)
584 self.assertIsInstance(cm.exception.__cause__, TypeError)
585 # Mock called more than once => always fails
586 mock(4, 5, 6)
587 self.assertRaises(AssertionError, mock.assert_called_once_with,
588 1, 2, 3)
589 self.assertRaises(AssertionError, mock.assert_called_once_with,
590 4, 5, 6)
591
592
593 def test_attribute_access_returns_mocks(self):
594 mock = Mock()
595 something = mock.something
596 self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
597 self.assertEqual(mock.something, something,
598 "different attributes returned for same name")
599
600 # Usage example
601 mock = Mock()
602 mock.something.return_value = 3
603
604 self.assertEqual(mock.something(), 3, "method returned wrong value")
605 self.assertTrue(mock.something.called,
606 "method didn't record being called")
607
608
609 def test_attributes_have_name_and_parent_set(self):
610 mock = Mock()
611 something = mock.something
612
613 self.assertEqual(something._mock_name, "something",
614 "attribute name not set correctly")
615 self.assertEqual(something._mock_parent, mock,
616 "attribute parent not set correctly")
617
618
619 def test_method_calls_recorded(self):
620 mock = Mock()
621 mock.something(3, fish=None)
622 mock.something_else.something(6, cake=sentinel.Cake)
623
624 self.assertEqual(mock.something_else.method_calls,
625 [("something", (6,), {'cake': sentinel.Cake})],
626 "method calls not recorded correctly")
627 self.assertEqual(mock.method_calls, [
628 ("something", (3,), {'fish': None}),
629 ("something_else.something", (6,), {'cake': sentinel.Cake})
630 ],
631 "method calls not recorded correctly")
632
633
634 def test_method_calls_compare_easily(self):
635 mock = Mock()
636 mock.something()
637 self.assertEqual(mock.method_calls, [('something',)])
638 self.assertEqual(mock.method_calls, [('something', (), {})])
639
640 mock = Mock()
641 mock.something('different')
642 self.assertEqual(mock.method_calls, [('something', ('different',))])
643 self.assertEqual(mock.method_calls,
644 [('something', ('different',), {})])
645
646 mock = Mock()
647 mock.something(x=1)
648 self.assertEqual(mock.method_calls, [('something', {'x': 1})])
649 self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
650
651 mock = Mock()
652 mock.something('different', some='more')
653 self.assertEqual(mock.method_calls, [
654 ('something', ('different',), {'some': 'more'})
655 ])
656
657
658 def test_only_allowed_methods_exist(self):
659 for spec in ['something'], ('something',):
660 for arg in 'spec', 'spec_set':
661 mock = Mock(**{arg: spec})
662
663 # this should be allowed
664 mock.something
665 self.assertRaisesRegex(
666 AttributeError,
667 "Mock object has no attribute 'something_else'",
668 getattr, mock, 'something_else'
669 )
670
671
672 def test_from_spec(self):
673 class Something(object):
674 x = 3
675 __something__ = None
676 def y(self): pass
677
678 def test_attributes(mock):
679 # should work
680 mock.x
681 mock.y
682 mock.__something__
683 self.assertRaisesRegex(
684 AttributeError,
685 "Mock object has no attribute 'z'",
686 getattr, mock, 'z'
687 )
688 self.assertRaisesRegex(
689 AttributeError,
690 "Mock object has no attribute '__foobar__'",
691 getattr, mock, '__foobar__'
692 )
693
694 test_attributes(Mock(spec=Something))
695 test_attributes(Mock(spec=Something()))
696
697
698 def test_wraps_calls(self):
699 real = Mock()
700
701 mock = Mock(wraps=real)
702 # If "Mock" wraps an object, just accessing its
703 # "return_value" ("NonCallableMock.__get_return_value") should not
704 # trigger its descriptor ("NonCallableMock.__set_return_value") so
705 # the default "return_value" should always be "sentinel.DEFAULT".
706 self.assertEqual(mock.return_value, DEFAULT)
707 # It will not be "sentinel.DEFAULT" if the mock is not wrapping any
708 # object.
709 self.assertNotEqual(real.return_value, DEFAULT)
710 self.assertEqual(mock(), real())
711
712 real.reset_mock()
713
714 mock(1, 2, fish=3)
715 real.assert_called_with(1, 2, fish=3)
716
717
718 def test_wraps_prevents_automatic_creation_of_mocks(self):
719 class Real(object):
720 pass
721
722 real = Real()
723 mock = Mock(wraps=real)
724
725 self.assertRaises(AttributeError, lambda: mock.new_attr())
726
727
728 def test_wraps_call_with_nondefault_return_value(self):
729 real = Mock()
730
731 mock = Mock(wraps=real)
732 mock.return_value = 3
733
734 self.assertEqual(mock(), 3)
735 self.assertFalse(real.called)
736
737
738 def test_wraps_attributes(self):
739 class Real(object):
740 attribute = Mock()
741
742 real = Real()
743
744 mock = Mock(wraps=real)
745 self.assertEqual(mock.attribute(), real.attribute())
746 self.assertRaises(AttributeError, lambda: mock.fish)
747
748 self.assertNotEqual(mock.attribute, real.attribute)
749 result = mock.attribute.frog(1, 2, fish=3)
750 Real.attribute.frog.assert_called_with(1, 2, fish=3)
751 self.assertEqual(result, Real.attribute.frog())
752
753
754 def test_customize_wrapped_object_with_side_effect_iterable_with_default(self):
755 class Real(object):
756 def method(self):
757 return sentinel.ORIGINAL_VALUE
758
759 real = Real()
760 mock = Mock(wraps=real)
761 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
762
763 self.assertEqual(mock.method(), sentinel.VALUE1)
764 self.assertEqual(mock.method(), sentinel.ORIGINAL_VALUE)
765 self.assertRaises(StopIteration, mock.method)
766
767
768 def test_customize_wrapped_object_with_side_effect_iterable(self):
769 class Real(object):
770 def method(self): pass
771
772 real = Real()
773 mock = Mock(wraps=real)
774 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
775
776 self.assertEqual(mock.method(), sentinel.VALUE1)
777 self.assertEqual(mock.method(), sentinel.VALUE2)
778 self.assertRaises(StopIteration, mock.method)
779
780
781 def test_customize_wrapped_object_with_side_effect_exception(self):
782 class Real(object):
783 def method(self): pass
784
785 real = Real()
786 mock = Mock(wraps=real)
787 mock.method.side_effect = RuntimeError
788
789 self.assertRaises(RuntimeError, mock.method)
790
791
792 def test_customize_wrapped_object_with_side_effect_function(self):
793 class Real(object):
794 def method(self): pass
795 def side_effect():
796 return sentinel.VALUE
797
798 real = Real()
799 mock = Mock(wraps=real)
800 mock.method.side_effect = side_effect
801
802 self.assertEqual(mock.method(), sentinel.VALUE)
803
804
805 def test_customize_wrapped_object_with_return_value(self):
806 class Real(object):
807 def method(self): pass
808
809 real = Real()
810 mock = Mock(wraps=real)
811 mock.method.return_value = sentinel.VALUE
812
813 self.assertEqual(mock.method(), sentinel.VALUE)
814
815
816 def test_customize_wrapped_object_with_return_value_and_side_effect(self):
817 # side_effect should always take precedence over return_value.
818 class Real(object):
819 def method(self): pass
820
821 real = Real()
822 mock = Mock(wraps=real)
823 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
824 mock.method.return_value = sentinel.WRONG_VALUE
825
826 self.assertEqual(mock.method(), sentinel.VALUE1)
827 self.assertEqual(mock.method(), sentinel.VALUE2)
828 self.assertRaises(StopIteration, mock.method)
829
830
831 def test_customize_wrapped_object_with_return_value_and_side_effect2(self):
832 # side_effect can return DEFAULT to default to return_value
833 class Real(object):
834 def method(self): pass
835
836 real = Real()
837 mock = Mock(wraps=real)
838 mock.method.side_effect = lambda: DEFAULT
839 mock.method.return_value = sentinel.VALUE
840
841 self.assertEqual(mock.method(), sentinel.VALUE)
842
843
844 def test_customize_wrapped_object_with_return_value_and_side_effect_default(self):
845 class Real(object):
846 def method(self): pass
847
848 real = Real()
849 mock = Mock(wraps=real)
850 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
851 mock.method.return_value = sentinel.RETURN
852
853 self.assertEqual(mock.method(), sentinel.VALUE1)
854 self.assertEqual(mock.method(), sentinel.RETURN)
855 self.assertRaises(StopIteration, mock.method)
856
857
858 def test_magic_method_wraps_dict(self):
859 # bpo-25597: MagicMock with wrap doesn't call wrapped object's
860 # method for magic methods with default values.
861 data = {'foo': 'bar'}
862
863 wrapped_dict = MagicMock(wraps=data)
864 self.assertEqual(wrapped_dict.get('foo'), 'bar')
865 # Accessing key gives a MagicMock
866 self.assertIsInstance(wrapped_dict['foo'], MagicMock)
867 # __contains__ method has a default value of False
868 self.assertFalse('foo' in wrapped_dict)
869
870 # return_value is non-sentinel and takes precedence over wrapped value.
871 wrapped_dict.get.return_value = 'return_value'
872 self.assertEqual(wrapped_dict.get('foo'), 'return_value')
873
874 # return_value is sentinel and hence wrapped value is returned.
875 wrapped_dict.get.return_value = sentinel.DEFAULT
876 self.assertEqual(wrapped_dict.get('foo'), 'bar')
877
878 self.assertEqual(wrapped_dict.get('baz'), None)
879 self.assertIsInstance(wrapped_dict['baz'], MagicMock)
880 self.assertFalse('bar' in wrapped_dict)
881
882 data['baz'] = 'spam'
883 self.assertEqual(wrapped_dict.get('baz'), 'spam')
884 self.assertIsInstance(wrapped_dict['baz'], MagicMock)
885 self.assertFalse('bar' in wrapped_dict)
886
887 del data['baz']
888 self.assertEqual(wrapped_dict.get('baz'), None)
889
890
891 def test_magic_method_wraps_class(self):
892
893 class Foo:
894
895 def __getitem__(self, index):
896 return index
897
898 def __custom_method__(self):
899 return "foo"
900
901
902 klass = MagicMock(wraps=Foo)
903 obj = klass()
904 self.assertEqual(obj.__getitem__(2), 2)
905 self.assertEqual(obj[2], 2)
906 self.assertEqual(obj.__custom_method__(), "foo")
907
908
909 def test_exceptional_side_effect(self):
910 mock = Mock(side_effect=AttributeError)
911 self.assertRaises(AttributeError, mock)
912
913 mock = Mock(side_effect=AttributeError('foo'))
914 self.assertRaises(AttributeError, mock)
915
916
917 def test_baseexceptional_side_effect(self):
918 mock = Mock(side_effect=KeyboardInterrupt)
919 self.assertRaises(KeyboardInterrupt, mock)
920
921 mock = Mock(side_effect=KeyboardInterrupt('foo'))
922 self.assertRaises(KeyboardInterrupt, mock)
923
924
925 def test_assert_called_with_message(self):
926 mock = Mock()
927 self.assertRaisesRegex(AssertionError, 'not called',
928 mock.assert_called_with)
929
930
931 def test_assert_called_once_with_message(self):
932 mock = Mock(name='geoffrey')
933 self.assertRaisesRegex(AssertionError,
934 r"Expected 'geoffrey' to be called once\.",
935 mock.assert_called_once_with)
936
937
938 def test__name__(self):
939 mock = Mock()
940 self.assertRaises(AttributeError, lambda: mock.__name__)
941
942 mock.__name__ = 'foo'
943 self.assertEqual(mock.__name__, 'foo')
944
945
946 def test_spec_list_subclass(self):
947 class Sub(list):
948 pass
949 mock = Mock(spec=Sub(['foo']))
950
951 mock.append(3)
952 mock.append.assert_called_with(3)
953 self.assertRaises(AttributeError, getattr, mock, 'foo')
954
955
956 def test_spec_class(self):
957 class X(object):
958 pass
959
960 mock = Mock(spec=X)
961 self.assertIsInstance(mock, X)
962
963 mock = Mock(spec=X())
964 self.assertIsInstance(mock, X)
965
966 self.assertIs(mock.__class__, X)
967 self.assertEqual(Mock().__class__.__name__, 'Mock')
968
969 mock = Mock(spec_set=X)
970 self.assertIsInstance(mock, X)
971
972 mock = Mock(spec_set=X())
973 self.assertIsInstance(mock, X)
974
975
976 def test_spec_class_no_object_base(self):
977 class X:
978 pass
979
980 mock = Mock(spec=X)
981 self.assertIsInstance(mock, X)
982
983 mock = Mock(spec=X())
984 self.assertIsInstance(mock, X)
985
986 self.assertIs(mock.__class__, X)
987 self.assertEqual(Mock().__class__.__name__, 'Mock')
988
989 mock = Mock(spec_set=X)
990 self.assertIsInstance(mock, X)
991
992 mock = Mock(spec_set=X())
993 self.assertIsInstance(mock, X)
994
995
996 def test_setting_attribute_with_spec_set(self):
997 class X(object):
998 y = 3
999
1000 mock = Mock(spec=X)
1001 mock.x = 'foo'
1002
1003 mock = Mock(spec_set=X)
1004 def set_attr():
1005 mock.x = 'foo'
1006
1007 mock.y = 'foo'
1008 self.assertRaises(AttributeError, set_attr)
1009
1010
1011 def test_copy(self):
1012 current = sys.getrecursionlimit()
1013 self.addCleanup(sys.setrecursionlimit, current)
1014
1015 # can't use sys.maxint as this doesn't exist in Python 3
1016 sys.setrecursionlimit(int(10e8))
1017 # this segfaults without the fix in place
1018 copy.copy(Mock())
1019
1020
1021 def test_subclass_with_properties(self):
1022 class SubClass(Mock):
1023 def _get(self):
1024 return 3
1025 def _set(self, value):
1026 raise NameError('strange error')
1027 some_attribute = property(_get, _set)
1028
1029 s = SubClass(spec_set=SubClass)
1030 self.assertEqual(s.some_attribute, 3)
1031
1032 def test():
1033 s.some_attribute = 3
1034 self.assertRaises(NameError, test)
1035
1036 def test():
1037 s.foo = 'bar'
1038 self.assertRaises(AttributeError, test)
1039
1040
1041 def test_setting_call(self):
1042 mock = Mock()
1043 def __call__(self, a):
1044 self._increment_mock_call(a)
1045 return self._mock_call(a)
1046
1047 type(mock).__call__ = __call__
1048 mock('one')
1049 mock.assert_called_with('one')
1050
1051 self.assertRaises(TypeError, mock, 'one', 'two')
1052
1053
1054 def test_dir(self):
1055 mock = Mock()
1056 attrs = set(dir(mock))
1057 type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
1058
1059 # all public attributes from the type are included
1060 self.assertEqual(set(), type_attrs - attrs)
1061
1062 # creates these attributes
1063 mock.a, mock.b
1064 self.assertIn('a', dir(mock))
1065 self.assertIn('b', dir(mock))
1066
1067 # instance attributes
1068 mock.c = mock.d = None
1069 self.assertIn('c', dir(mock))
1070 self.assertIn('d', dir(mock))
1071
1072 # magic methods
1073 mock.__iter__ = lambda s: iter([])
1074 self.assertIn('__iter__', dir(mock))
1075
1076
1077 def test_dir_from_spec(self):
1078 mock = Mock(spec=unittest.TestCase)
1079 testcase_attrs = set(dir(unittest.TestCase))
1080 attrs = set(dir(mock))
1081
1082 # all attributes from the spec are included
1083 self.assertEqual(set(), testcase_attrs - attrs)
1084
1085 # shadow a sys attribute
1086 mock.version = 3
1087 self.assertEqual(dir(mock).count('version'), 1)
1088
1089
1090 def test_filter_dir(self):
1091 patcher = patch.object(mock, 'FILTER_DIR', False)
1092 patcher.start()
1093 try:
1094 attrs = set(dir(Mock()))
1095 type_attrs = set(dir(Mock))
1096
1097 # ALL attributes from the type are included
1098 self.assertEqual(set(), type_attrs - attrs)
1099 finally:
1100 patcher.stop()
1101
1102
1103 def test_dir_does_not_include_deleted_attributes(self):
1104 mock = Mock()
1105 mock.child.return_value = 1
1106
1107 self.assertIn('child', dir(mock))
1108 del mock.child
1109 self.assertNotIn('child', dir(mock))
1110
1111
1112 def test_configure_mock(self):
1113 mock = Mock(foo='bar')
1114 self.assertEqual(mock.foo, 'bar')
1115
1116 mock = MagicMock(foo='bar')
1117 self.assertEqual(mock.foo, 'bar')
1118
1119 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
1120 'foo': MagicMock()}
1121 mock = Mock(**kwargs)
1122 self.assertRaises(KeyError, mock)
1123 self.assertEqual(mock.foo.bar(), 33)
1124 self.assertIsInstance(mock.foo, MagicMock)
1125
1126 mock = Mock()
1127 mock.configure_mock(**kwargs)
1128 self.assertRaises(KeyError, mock)
1129 self.assertEqual(mock.foo.bar(), 33)
1130 self.assertIsInstance(mock.foo, MagicMock)
1131
1132
1133 def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
1134 # needed because assertRaisesRegex doesn't work easily with newlines
1135 with self.assertRaises(exception) as context:
1136 func(*args, **kwargs)
1137 msg = str(context.exception)
1138 self.assertEqual(msg, message)
1139
1140
1141 def test_assert_called_with_failure_message(self):
1142 mock = NonCallableMock()
1143
1144 actual = 'not called.'
1145 expected = "mock(1, '2', 3, bar='foo')"
1146 message = 'expected call not found.\nExpected: %s\n Actual: %s'
1147 self.assertRaisesWithMsg(
1148 AssertionError, message % (expected, actual),
1149 mock.assert_called_with, 1, '2', 3, bar='foo'
1150 )
1151
1152 mock.foo(1, '2', 3, foo='foo')
1153
1154
1155 asserters = [
1156 mock.foo.assert_called_with, mock.foo.assert_called_once_with
1157 ]
1158 for meth in asserters:
1159 actual = "foo(1, '2', 3, foo='foo')"
1160 expected = "foo(1, '2', 3, bar='foo')"
1161 message = 'expected call not found.\nExpected: %s\n Actual: %s'
1162 self.assertRaisesWithMsg(
1163 AssertionError, message % (expected, actual),
1164 meth, 1, '2', 3, bar='foo'
1165 )
1166
1167 # just kwargs
1168 for meth in asserters:
1169 actual = "foo(1, '2', 3, foo='foo')"
1170 expected = "foo(bar='foo')"
1171 message = 'expected call not found.\nExpected: %s\n Actual: %s'
1172 self.assertRaisesWithMsg(
1173 AssertionError, message % (expected, actual),
1174 meth, bar='foo'
1175 )
1176
1177 # just args
1178 for meth in asserters:
1179 actual = "foo(1, '2', 3, foo='foo')"
1180 expected = "foo(1, 2, 3)"
1181 message = 'expected call not found.\nExpected: %s\n Actual: %s'
1182 self.assertRaisesWithMsg(
1183 AssertionError, message % (expected, actual),
1184 meth, 1, 2, 3
1185 )
1186
1187 # empty
1188 for meth in asserters:
1189 actual = "foo(1, '2', 3, foo='foo')"
1190 expected = "foo()"
1191 message = 'expected call not found.\nExpected: %s\n Actual: %s'
1192 self.assertRaisesWithMsg(
1193 AssertionError, message % (expected, actual), meth
1194 )
1195
1196
1197 def test_mock_calls(self):
1198 mock = MagicMock()
1199
1200 # need to do this because MagicMock.mock_calls used to just return
1201 # a MagicMock which also returned a MagicMock when __eq__ was called
1202 self.assertIs(mock.mock_calls == [], True)
1203
1204 mock = MagicMock()
1205 mock()
1206 expected = [('', (), {})]
1207 self.assertEqual(mock.mock_calls, expected)
1208
1209 mock.foo()
1210 expected.append(call.foo())
1211 self.assertEqual(mock.mock_calls, expected)
1212 # intermediate mock_calls work too
1213 self.assertEqual(mock.foo.mock_calls, [('', (), {})])
1214
1215 mock = MagicMock()
1216 mock().foo(1, 2, 3, a=4, b=5)
1217 expected = [
1218 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
1219 ]
1220 self.assertEqual(mock.mock_calls, expected)
1221 self.assertEqual(mock.return_value.foo.mock_calls,
1222 [('', (1, 2, 3), dict(a=4, b=5))])
1223 self.assertEqual(mock.return_value.mock_calls,
1224 [('foo', (1, 2, 3), dict(a=4, b=5))])
1225
1226 mock = MagicMock()
1227 mock().foo.bar().baz()
1228 expected = [
1229 ('', (), {}), ('().foo.bar', (), {}),
1230 ('().foo.bar().baz', (), {})
1231 ]
1232 self.assertEqual(mock.mock_calls, expected)
1233 self.assertEqual(mock().mock_calls,
1234 call.foo.bar().baz().call_list())
1235
1236 for kwargs in dict(), dict(name='bar'):
1237 mock = MagicMock(**kwargs)
1238 int(mock.foo)
1239 expected = [('foo.__int__', (), {})]
1240 self.assertEqual(mock.mock_calls, expected)
1241
1242 mock = MagicMock(**kwargs)
1243 mock.a()()
1244 expected = [('a', (), {}), ('a()', (), {})]
1245 self.assertEqual(mock.mock_calls, expected)
1246 self.assertEqual(mock.a().mock_calls, [call()])
1247
1248 mock = MagicMock(**kwargs)
1249 mock(1)(2)(3)
1250 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
1251 self.assertEqual(mock().mock_calls, call(2)(3).call_list())
1252 self.assertEqual(mock()().mock_calls, call(3).call_list())
1253
1254 mock = MagicMock(**kwargs)
1255 mock(1)(2)(3).a.b.c(4)
1256 self.assertEqual(mock.mock_calls,
1257 call(1)(2)(3).a.b.c(4).call_list())
1258 self.assertEqual(mock().mock_calls,
1259 call(2)(3).a.b.c(4).call_list())
1260 self.assertEqual(mock()().mock_calls,
1261 call(3).a.b.c(4).call_list())
1262
1263 mock = MagicMock(**kwargs)
1264 int(mock().foo.bar().baz())
1265 last_call = ('().foo.bar().baz().__int__', (), {})
1266 self.assertEqual(mock.mock_calls[-1], last_call)
1267 self.assertEqual(mock().mock_calls,
1268 call.foo.bar().baz().__int__().call_list())
1269 self.assertEqual(mock().foo.bar().mock_calls,
1270 call.baz().__int__().call_list())
1271 self.assertEqual(mock().foo.bar().baz.mock_calls,
1272 call().__int__().call_list())
1273
1274
1275 def test_child_mock_call_equal(self):
1276 m = Mock()
1277 result = m()
1278 result.wibble()
1279 # parent looks like this:
1280 self.assertEqual(m.mock_calls, [call(), call().wibble()])
1281 # but child should look like this:
1282 self.assertEqual(result.mock_calls, [call.wibble()])
1283
1284
1285 def test_mock_call_not_equal_leaf(self):
1286 m = Mock()
1287 m.foo().something()
1288 self.assertNotEqual(m.mock_calls[1], call.foo().different())
1289 self.assertEqual(m.mock_calls[0], call.foo())
1290
1291
1292 def test_mock_call_not_equal_non_leaf(self):
1293 m = Mock()
1294 m.foo().bar()
1295 self.assertNotEqual(m.mock_calls[1], call.baz().bar())
1296 self.assertNotEqual(m.mock_calls[0], call.baz())
1297
1298
1299 def test_mock_call_not_equal_non_leaf_params_different(self):
1300 m = Mock()
1301 m.foo(x=1).bar()
1302 # This isn't ideal, but there's no way to fix it without breaking backwards compatibility:
1303 self.assertEqual(m.mock_calls[1], call.foo(x=2).bar())
1304
1305
1306 def test_mock_call_not_equal_non_leaf_attr(self):
1307 m = Mock()
1308 m.foo.bar()
1309 self.assertNotEqual(m.mock_calls[0], call.baz.bar())
1310
1311
1312 def test_mock_call_not_equal_non_leaf_call_versus_attr(self):
1313 m = Mock()
1314 m.foo.bar()
1315 self.assertNotEqual(m.mock_calls[0], call.foo().bar())
1316
1317
1318 def test_mock_call_repr(self):
1319 m = Mock()
1320 m.foo().bar().baz.bob()
1321 self.assertEqual(repr(m.mock_calls[0]), 'call.foo()')
1322 self.assertEqual(repr(m.mock_calls[1]), 'call.foo().bar()')
1323 self.assertEqual(repr(m.mock_calls[2]), 'call.foo().bar().baz.bob()')
1324
1325
1326 def test_mock_call_repr_loop(self):
1327 m = Mock()
1328 m.foo = m
1329 repr(m.foo())
1330 self.assertRegex(repr(m.foo()), r"<Mock name='mock\(\)' id='\d+'>")
1331
1332
1333 def test_mock_calls_contains(self):
1334 m = Mock()
1335 self.assertFalse([call()] in m.mock_calls)
1336
1337
1338 def test_subclassing(self):
1339 class Subclass(Mock):
1340 pass
1341
1342 mock = Subclass()
1343 self.assertIsInstance(mock.foo, Subclass)
1344 self.assertIsInstance(mock(), Subclass)
1345
1346 class Subclass(Mock):
1347 def _get_child_mock(self, **kwargs):
1348 return Mock(**kwargs)
1349
1350 mock = Subclass()
1351 self.assertNotIsInstance(mock.foo, Subclass)
1352 self.assertNotIsInstance(mock(), Subclass)
1353
1354
1355 def test_arg_lists(self):
1356 mocks = [
1357 Mock(),
1358 MagicMock(),
1359 NonCallableMock(),
1360 NonCallableMagicMock()
1361 ]
1362
1363 def assert_attrs(mock):
1364 names = 'call_args_list', 'method_calls', 'mock_calls'
1365 for name in names:
1366 attr = getattr(mock, name)
1367 self.assertIsInstance(attr, _CallList)
1368 self.assertIsInstance(attr, list)
1369 self.assertEqual(attr, [])
1370
1371 for mock in mocks:
1372 assert_attrs(mock)
1373
1374 if callable(mock):
1375 mock()
1376 mock(1, 2)
1377 mock(a=3)
1378
1379 mock.reset_mock()
1380 assert_attrs(mock)
1381
1382 mock.foo()
1383 mock.foo.bar(1, a=3)
1384 mock.foo(1).bar().baz(3)
1385
1386 mock.reset_mock()
1387 assert_attrs(mock)
1388
1389
1390 def test_call_args_two_tuple(self):
1391 mock = Mock()
1392 mock(1, a=3)
1393 mock(2, b=4)
1394
1395 self.assertEqual(len(mock.call_args), 2)
1396 self.assertEqual(mock.call_args.args, (2,))
1397 self.assertEqual(mock.call_args.kwargs, dict(b=4))
1398
1399 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
1400 for expected, call_args in zip(expected_list, mock.call_args_list):
1401 self.assertEqual(len(call_args), 2)
1402 self.assertEqual(expected[0], call_args[0])
1403 self.assertEqual(expected[1], call_args[1])
1404
1405
1406 def test_side_effect_iterator(self):
1407 mock = Mock(side_effect=iter([1, 2, 3]))
1408 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1409 self.assertRaises(StopIteration, mock)
1410
1411 mock = MagicMock(side_effect=['a', 'b', 'c'])
1412 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1413 self.assertRaises(StopIteration, mock)
1414
1415 mock = Mock(side_effect='ghi')
1416 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
1417 self.assertRaises(StopIteration, mock)
1418
1419 class Foo(object):
1420 pass
1421 mock = MagicMock(side_effect=Foo)
1422 self.assertIsInstance(mock(), Foo)
1423
1424 mock = Mock(side_effect=Iter())
1425 self.assertEqual([mock(), mock(), mock(), mock()],
1426 ['this', 'is', 'an', 'iter'])
1427 self.assertRaises(StopIteration, mock)
1428
1429
1430 def test_side_effect_iterator_exceptions(self):
1431 for Klass in Mock, MagicMock:
1432 iterable = (ValueError, 3, KeyError, 6)
1433 m = Klass(side_effect=iterable)
1434 self.assertRaises(ValueError, m)
1435 self.assertEqual(m(), 3)
1436 self.assertRaises(KeyError, m)
1437 self.assertEqual(m(), 6)
1438
1439
1440 def test_side_effect_setting_iterator(self):
1441 mock = Mock()
1442 mock.side_effect = iter([1, 2, 3])
1443 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1444 self.assertRaises(StopIteration, mock)
1445 side_effect = mock.side_effect
1446 self.assertIsInstance(side_effect, type(iter([])))
1447
1448 mock.side_effect = ['a', 'b', 'c']
1449 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1450 self.assertRaises(StopIteration, mock)
1451 side_effect = mock.side_effect
1452 self.assertIsInstance(side_effect, type(iter([])))
1453
1454 this_iter = Iter()
1455 mock.side_effect = this_iter
1456 self.assertEqual([mock(), mock(), mock(), mock()],
1457 ['this', 'is', 'an', 'iter'])
1458 self.assertRaises(StopIteration, mock)
1459 self.assertIs(mock.side_effect, this_iter)
1460
1461 def test_side_effect_iterator_default(self):
1462 mock = Mock(return_value=2)
1463 mock.side_effect = iter([1, DEFAULT])
1464 self.assertEqual([mock(), mock()], [1, 2])
1465
1466 def test_assert_has_calls_any_order(self):
1467 mock = Mock()
1468 mock(1, 2)
1469 mock(a=3)
1470 mock(3, 4)
1471 mock(b=6)
1472 mock(b=6)
1473
1474 kalls = [
1475 call(1, 2), ({'a': 3},),
1476 ((3, 4),), ((), {'a': 3}),
1477 ('', (1, 2)), ('', {'a': 3}),
1478 ('', (1, 2), {}), ('', (), {'a': 3})
1479 ]
1480 for kall in kalls:
1481 mock.assert_has_calls([kall], any_order=True)
1482
1483 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
1484 self.assertRaises(
1485 AssertionError, mock.assert_has_calls,
1486 [kall], any_order=True
1487 )
1488
1489 kall_lists = [
1490 [call(1, 2), call(b=6)],
1491 [call(3, 4), call(1, 2)],
1492 [call(b=6), call(b=6)],
1493 ]
1494
1495 for kall_list in kall_lists:
1496 mock.assert_has_calls(kall_list, any_order=True)
1497
1498 kall_lists = [
1499 [call(b=6), call(b=6), call(b=6)],
1500 [call(1, 2), call(1, 2)],
1501 [call(3, 4), call(1, 2), call(5, 7)],
1502 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
1503 ]
1504 for kall_list in kall_lists:
1505 self.assertRaises(
1506 AssertionError, mock.assert_has_calls,
1507 kall_list, any_order=True
1508 )
1509
1510 def test_assert_has_calls(self):
1511 kalls1 = [
1512 call(1, 2), ({'a': 3},),
1513 ((3, 4),), call(b=6),
1514 ('', (1,), {'b': 6}),
1515 ]
1516 kalls2 = [call.foo(), call.bar(1)]
1517 kalls2.extend(call.spam().baz(a=3).call_list())
1518 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
1519
1520 mocks = []
1521 for mock in Mock(), MagicMock():
1522 mock(1, 2)
1523 mock(a=3)
1524 mock(3, 4)
1525 mock(b=6)
1526 mock(1, b=6)
1527 mocks.append((mock, kalls1))
1528
1529 mock = Mock()
1530 mock.foo()
1531 mock.bar(1)
1532 mock.spam().baz(a=3)
1533 mock.bam(set(), foo={}).fish([1])
1534 mocks.append((mock, kalls2))
1535
1536 for mock, kalls in mocks:
1537 for i in range(len(kalls)):
1538 for step in 1, 2, 3:
1539 these = kalls[i:i+step]
1540 mock.assert_has_calls(these)
1541
1542 if len(these) > 1:
1543 self.assertRaises(
1544 AssertionError,
1545 mock.assert_has_calls,
1546 list(reversed(these))
1547 )
1548
1549
1550 def test_assert_has_calls_nested_spec(self):
1551 class Something:
1552
1553 def __init__(self): pass
1554 def meth(self, a, b, c, d=None): pass
1555
1556 class Foo:
1557
1558 def __init__(self, a): pass
1559 def meth1(self, a, b): pass
1560
1561 mock_class = create_autospec(Something)
1562
1563 for m in [mock_class, mock_class()]:
1564 m.meth(1, 2, 3, d=1)
1565 m.assert_has_calls([call.meth(1, 2, 3, d=1)])
1566 m.assert_has_calls([call.meth(1, 2, 3, 1)])
1567
1568 mock_class.reset_mock()
1569
1570 for m in [mock_class, mock_class()]:
1571 self.assertRaises(AssertionError, m.assert_has_calls, [call.Foo()])
1572 m.Foo(1).meth1(1, 2)
1573 m.assert_has_calls([call.Foo(1), call.Foo(1).meth1(1, 2)])
1574 m.Foo.assert_has_calls([call(1), call().meth1(1, 2)])
1575
1576 mock_class.reset_mock()
1577
1578 invalid_calls = [call.meth(1),
1579 call.non_existent(1),
1580 call.Foo().non_existent(1),
1581 call.Foo().meth(1, 2, 3, 4)]
1582
1583 for kall in invalid_calls:
1584 self.assertRaises(AssertionError,
1585 mock_class.assert_has_calls,
1586 [kall]
1587 )
1588
1589
1590 def test_assert_has_calls_nested_without_spec(self):
1591 m = MagicMock()
1592 m().foo().bar().baz()
1593 m.one().two().three()
1594 calls = call.one().two().three().call_list()
1595 m.assert_has_calls(calls)
1596
1597
1598 def test_assert_has_calls_with_function_spec(self):
1599 def f(a, b, c, d=None): pass
1600
1601 mock = Mock(spec=f)
1602
1603 mock(1, b=2, c=3)
1604 mock(4, 5, c=6, d=7)
1605 mock(10, 11, c=12)
1606 calls = [
1607 ('', (1, 2, 3), {}),
1608 ('', (4, 5, 6), {'d': 7}),
1609 ((10, 11, 12), {}),
1610 ]
1611 mock.assert_has_calls(calls)
1612 mock.assert_has_calls(calls, any_order=True)
1613 mock.assert_has_calls(calls[1:])
1614 mock.assert_has_calls(calls[1:], any_order=True)
1615 mock.assert_has_calls(calls[:-1])
1616 mock.assert_has_calls(calls[:-1], any_order=True)
1617 # Reversed order
1618 calls = list(reversed(calls))
1619 with self.assertRaises(AssertionError):
1620 mock.assert_has_calls(calls)
1621 mock.assert_has_calls(calls, any_order=True)
1622 with self.assertRaises(AssertionError):
1623 mock.assert_has_calls(calls[1:])
1624 mock.assert_has_calls(calls[1:], any_order=True)
1625 with self.assertRaises(AssertionError):
1626 mock.assert_has_calls(calls[:-1])
1627 mock.assert_has_calls(calls[:-1], any_order=True)
1628
1629 def test_assert_has_calls_not_matching_spec_error(self):
1630 def f(x=None): pass
1631
1632 mock = Mock(spec=f)
1633 mock(1)
1634
1635 with self.assertRaises(AssertionError) as cm:
1636 mock.assert_has_calls([call()])
1637 self.assertEqual(str(cm.exception),
1638 'Calls not found.\n'
1639 'Expected: [call()]\n'
1640 ' Actual: [call(1)]'
1641 )
1642 self.assertIsNone(cm.exception.__cause__)
1643
1644 uncalled_mock = Mock()
1645 with self.assertRaises(AssertionError) as cm:
1646 uncalled_mock.assert_has_calls([call()])
1647 self.assertEqual(str(cm.exception),
1648 'Calls not found.\n'
1649 'Expected: [call()]\n'
1650 ' Actual: []'
1651 )
1652 self.assertIsNone(cm.exception.__cause__)
1653
1654 with self.assertRaises(AssertionError) as cm:
1655 mock.assert_has_calls([call(), call(1, 2)])
1656 self.assertEqual(str(cm.exception),
1657 'Error processing expected calls.\n'
1658 "Errors: [None, TypeError('too many positional arguments')]\n"
1659 'Expected: [call(), call(1, 2)]\n'
1660 ' Actual: [call(1)]'
1661 )
1662 self.assertIsInstance(cm.exception.__cause__, TypeError)
1663
1664 def test_assert_any_call(self):
1665 mock = Mock()
1666 mock(1, 2)
1667 mock(a=3)
1668 mock(1, b=6)
1669
1670 mock.assert_any_call(1, 2)
1671 mock.assert_any_call(a=3)
1672 mock.assert_any_call(1, b=6)
1673
1674 self.assertRaises(
1675 AssertionError,
1676 mock.assert_any_call
1677 )
1678 self.assertRaises(
1679 AssertionError,
1680 mock.assert_any_call,
1681 1, 3
1682 )
1683 self.assertRaises(
1684 AssertionError,
1685 mock.assert_any_call,
1686 a=4
1687 )
1688
1689
1690 def test_assert_any_call_with_function_spec(self):
1691 def f(a, b, c, d=None): pass
1692
1693 mock = Mock(spec=f)
1694
1695 mock(1, b=2, c=3)
1696 mock(4, 5, c=6, d=7)
1697 mock.assert_any_call(1, 2, 3)
1698 mock.assert_any_call(a=1, b=2, c=3)
1699 mock.assert_any_call(4, 5, 6, 7)
1700 mock.assert_any_call(a=4, b=5, c=6, d=7)
1701 self.assertRaises(AssertionError, mock.assert_any_call,
1702 1, b=3, c=2)
1703 # Expected call doesn't match the spec's signature
1704 with self.assertRaises(AssertionError) as cm:
1705 mock.assert_any_call(e=8)
1706 self.assertIsInstance(cm.exception.__cause__, TypeError)
1707
1708
1709 def test_mock_calls_create_autospec(self):
1710 def f(a, b): pass
1711 obj = Iter()
1712 obj.f = f
1713
1714 funcs = [
1715 create_autospec(f),
1716 create_autospec(obj).f
1717 ]
1718 for func in funcs:
1719 func(1, 2)
1720 func(3, 4)
1721
1722 self.assertEqual(
1723 func.mock_calls, [call(1, 2), call(3, 4)]
1724 )
1725
1726 #Issue21222
1727 def test_create_autospec_with_name(self):
1728 m = mock.create_autospec(object(), name='sweet_func')
1729 self.assertIn('sweet_func', repr(m))
1730
1731 #Issue23078
1732 def test_create_autospec_classmethod_and_staticmethod(self):
1733 class TestClass:
1734 @classmethod
1735 def class_method(cls): pass
1736
1737 @staticmethod
1738 def static_method(): pass
1739 for method in ('class_method', 'static_method'):
1740 with self.subTest(method=method):
1741 mock_method = mock.create_autospec(getattr(TestClass, method))
1742 mock_method()
1743 mock_method.assert_called_once_with()
1744 self.assertRaises(TypeError, mock_method, 'extra_arg')
1745
1746 # gh-145754
1747 def test_create_autospec_type_hints_typechecking(self):
1748 def foo(x: Tuple[int, ...]) -> None:
1749 pass
1750
1751 mock.create_autospec(foo)
1752
1753 #Issue21238
1754 def test_mock_unsafe(self):
1755 m = Mock()
1756 msg = "is not a valid assertion. Use a spec for the mock"
1757 with self.assertRaisesRegex(AttributeError, msg):
1758 m.assert_foo_call()
1759 with self.assertRaisesRegex(AttributeError, msg):
1760 m.assret_foo_call()
1761 with self.assertRaisesRegex(AttributeError, msg):
1762 m.asert_foo_call()
1763 with self.assertRaisesRegex(AttributeError, msg):
1764 m.aseert_foo_call()
1765 with self.assertRaisesRegex(AttributeError, msg):
1766 m.assrt_foo_call()
1767 with self.assertRaisesRegex(AttributeError, msg):
1768 m.called_once_with()
1769 with self.assertRaisesRegex(AttributeError, msg):
1770 m.called_once()
1771 with self.assertRaisesRegex(AttributeError, msg):
1772 m.has_calls()
1773
1774 class Foo(object):
1775 def called_once(self): pass
1776
1777 def has_calls(self): pass
1778
1779 m = Mock(spec=Foo)
1780 m.called_once()
1781 m.has_calls()
1782
1783 m.called_once.assert_called_once()
1784 m.has_calls.assert_called_once()
1785
1786 m = Mock(unsafe=True)
1787 m.assert_foo_call()
1788 m.assret_foo_call()
1789 m.asert_foo_call()
1790 m.aseert_foo_call()
1791 m.assrt_foo_call()
1792 m.called_once()
1793 m.called_once_with()
1794 m.has_calls()
1795
1796 # gh-100739
1797 def test_mock_safe_with_spec(self):
1798 class Foo(object):
1799 def assert_bar(self): pass
1800
1801 def assertSome(self): pass
1802
1803 m = Mock(spec=Foo)
1804 m.assert_bar()
1805 m.assertSome()
1806
1807 m.assert_bar.assert_called_once()
1808 m.assertSome.assert_called_once()
1809
1810 #Issue21262
1811 def test_assert_not_called(self):
1812 m = Mock()
1813 m.hello.assert_not_called()
1814 m.hello()
1815 with self.assertRaises(AssertionError):
1816 m.hello.assert_not_called()
1817
1818 def test_assert_not_called_message(self):
1819 m = Mock()
1820 m(1, 2)
1821 self.assertRaisesRegex(AssertionError,
1822 re.escape("Calls: [call(1, 2)]"),
1823 m.assert_not_called)
1824
1825 def test_assert_called(self):
1826 m = Mock()
1827 with self.assertRaises(AssertionError):
1828 m.hello.assert_called()
1829 m.hello()
1830 m.hello.assert_called()
1831
1832 m.hello()
1833 m.hello.assert_called()
1834
1835 def test_assert_called_once(self):
1836 m = Mock()
1837 with self.assertRaises(AssertionError):
1838 m.hello.assert_called_once()
1839 m.hello()
1840 m.hello.assert_called_once()
1841
1842 m.hello()
1843 with self.assertRaises(AssertionError):
1844 m.hello.assert_called_once()
1845
1846 def test_assert_called_once_message(self):
1847 m = Mock()
1848 m(1, 2)
1849 m(3)
1850 self.assertRaisesRegex(AssertionError,
1851 re.escape("Calls: [call(1, 2), call(3)]"),
1852 m.assert_called_once)
1853
1854 def test_assert_called_once_message_not_called(self):
1855 m = Mock()
1856 with self.assertRaises(AssertionError) as e:
1857 m.assert_called_once()
1858 self.assertNotIn("Calls:", str(e.exception))
1859
1860 #Issue37212 printout of keyword args now preserves the original order
1861 def test_ordered_call_signature(self):
1862 m = Mock()
1863 m.hello(name='hello', daddy='hero')
1864 text = "call(name='hello', daddy='hero')"
1865 self.assertEqual(repr(m.hello.call_args), text)
1866
1867 #Issue21270 overrides tuple methods for mock.call objects
1868 def test_override_tuple_methods(self):
1869 c = call.count()
1870 i = call.index(132,'hello')
1871 m = Mock()
1872 m.count()
1873 m.index(132,"hello")
1874 self.assertEqual(m.method_calls[0], c)
1875 self.assertEqual(m.method_calls[1], i)
1876
1877 def test_reset_return_sideeffect(self):
1878 m = Mock(return_value=10, side_effect=[2,3])
1879 m.reset_mock(return_value=True, side_effect=True)
1880 self.assertIsInstance(m.return_value, Mock)
1881 self.assertEqual(m.side_effect, None)
1882
1883 def test_reset_return(self):
1884 m = Mock(return_value=10, side_effect=[2,3])
1885 m.reset_mock(return_value=True)
1886 self.assertIsInstance(m.return_value, Mock)
1887 self.assertNotEqual(m.side_effect, None)
1888
1889 def test_reset_sideeffect(self):
1890 m = Mock(return_value=10, side_effect=[2, 3])
1891 m.reset_mock(side_effect=True)
1892 self.assertEqual(m.return_value, 10)
1893 self.assertEqual(m.side_effect, None)
1894
1895 def test_reset_return_with_children(self):
1896 m = MagicMock(f=MagicMock(return_value=1))
1897 self.assertEqual(m.f(), 1)
1898 m.reset_mock(return_value=True)
1899 self.assertNotEqual(m.f(), 1)
1900
1901 def test_reset_return_with_children_side_effect(self):
1902 m = MagicMock(f=MagicMock(side_effect=[2, 3]))
1903 self.assertNotEqual(m.f.side_effect, None)
1904 m.reset_mock(side_effect=True)
1905 self.assertEqual(m.f.side_effect, None)
1906
1907 def test_mock_add_spec(self):
1908 class _One(object):
1909 one = 1
1910 class _Two(object):
1911 two = 2
1912 class Anything(object):
1913 one = two = three = 'four'
1914
1915 klasses = [
1916 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1917 ]
1918 for Klass in list(klasses):
1919 klasses.append(lambda K=Klass: K(spec=Anything))
1920 klasses.append(lambda K=Klass: K(spec_set=Anything))
1921
1922 for Klass in klasses:
1923 for kwargs in dict(), dict(spec_set=True):
1924 mock = Klass()
1925 #no error
1926 mock.one, mock.two, mock.three
1927
1928 for One, Two in [(_One, _Two), (['one'], ['two'])]:
1929 for kwargs in dict(), dict(spec_set=True):
1930 mock.mock_add_spec(One, **kwargs)
1931
1932 mock.one
1933 self.assertRaises(
1934 AttributeError, getattr, mock, 'two'
1935 )
1936 self.assertRaises(
1937 AttributeError, getattr, mock, 'three'
1938 )
1939 if 'spec_set' in kwargs:
1940 self.assertRaises(
1941 AttributeError, setattr, mock, 'three', None
1942 )
1943
1944 mock.mock_add_spec(Two, **kwargs)
1945 self.assertRaises(
1946 AttributeError, getattr, mock, 'one'
1947 )
1948 mock.two
1949 self.assertRaises(
1950 AttributeError, getattr, mock, 'three'
1951 )
1952 if 'spec_set' in kwargs:
1953 self.assertRaises(
1954 AttributeError, setattr, mock, 'three', None
1955 )
1956 # note that creating a mock, setting an instance attribute, and
1957 # *then* setting a spec doesn't work. Not the intended use case
1958
1959
1960 def test_mock_add_spec_magic_methods(self):
1961 for Klass in MagicMock, NonCallableMagicMock:
1962 mock = Klass()
1963 int(mock)
1964
1965 mock.mock_add_spec(object)
1966 self.assertRaises(TypeError, int, mock)
1967
1968 mock = Klass()
1969 mock['foo']
1970 mock.__int__.return_value =4
1971
1972 mock.mock_add_spec(int)
1973 self.assertEqual(int(mock), 4)
1974 self.assertRaises(TypeError, lambda: mock['foo'])
1975
1976
1977 def test_adding_child_mock(self):
1978 for Klass in (NonCallableMock, Mock, MagicMock, NonCallableMagicMock,
1979 AsyncMock):
1980 mock = Klass()
1981
1982 mock.foo = Mock()
1983 mock.foo()
1984
1985 self.assertEqual(mock.method_calls, [call.foo()])
1986 self.assertEqual(mock.mock_calls, [call.foo()])
1987
1988 mock = Klass()
1989 mock.bar = Mock(name='name')
1990 mock.bar()
1991 self.assertEqual(mock.method_calls, [])
1992 self.assertEqual(mock.mock_calls, [])
1993
1994 # mock with an existing _new_parent but no name
1995 mock = Klass()
1996 mock.baz = MagicMock()()
1997 mock.baz()
1998 self.assertEqual(mock.method_calls, [])
1999 self.assertEqual(mock.mock_calls, [])
2000
2001
2002 def test_adding_return_value_mock(self):
2003 for Klass in Mock, MagicMock:
2004 mock = Klass()
2005 mock.return_value = MagicMock()
2006
2007 mock()()
2008 self.assertEqual(mock.mock_calls, [call(), call()()])
2009
2010
2011 def test_manager_mock(self):
2012 class Foo(object):
2013 one = 'one'
2014 two = 'two'
2015 manager = Mock()
2016 p1 = patch.object(Foo, 'one')
2017 p2 = patch.object(Foo, 'two')
2018
2019 mock_one = p1.start()
2020 self.addCleanup(p1.stop)
2021 mock_two = p2.start()
2022 self.addCleanup(p2.stop)
2023
2024 manager.attach_mock(mock_one, 'one')
2025 manager.attach_mock(mock_two, 'two')
2026
2027 Foo.two()
2028 Foo.one()
2029
2030 self.assertEqual(manager.mock_calls, [call.two(), call.one()])
2031
2032
2033 def test_magic_methods_mock_calls(self):
2034 for Klass in Mock, MagicMock:
2035 m = Klass()
2036 m.__int__ = Mock(return_value=3)
2037 m.__float__ = MagicMock(return_value=3.0)
2038 int(m)
2039 float(m)
2040
2041 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
2042 self.assertEqual(m.method_calls, [])
2043
2044 def test_mock_open_reuse_issue_21750(self):
2045 mocked_open = mock.mock_open(read_data='data')
2046 f1 = mocked_open('a-name')
2047 f1_data = f1.read()
2048 f2 = mocked_open('another-name')
2049 f2_data = f2.read()
2050 self.assertEqual(f1_data, f2_data)
2051
2052 def test_mock_open_dunder_iter_issue(self):
2053 # Test dunder_iter method generates the expected result and
2054 # consumes the iterator.
2055 mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue')
2056 f1 = mocked_open('a-name')
2057 lines = [line for line in f1]
2058 self.assertEqual(lines[0], 'Remarkable\n')
2059 self.assertEqual(lines[1], 'Norwegian Blue')
2060 self.assertEqual(list(f1), [])
2061
2062 def test_mock_open_using_next(self):
2063 mocked_open = mock.mock_open(read_data='1st line\n2nd line\n3rd line')
2064 f1 = mocked_open('a-name')
2065 line1 = next(f1)
2066 line2 = f1.__next__()
2067 lines = [line for line in f1]
2068 self.assertEqual(line1, '1st line\n')
2069 self.assertEqual(line2, '2nd line\n')
2070 self.assertEqual(lines[0], '3rd line')
2071 self.assertEqual(list(f1), [])
2072 with self.assertRaises(StopIteration):
2073 next(f1)
2074
2075 def test_mock_open_next_with_readline_with_return_value(self):
2076 mopen = mock.mock_open(read_data='foo\nbarn')
2077 mopen.return_value.readline.return_value = 'abc'
2078 self.assertEqual('abc', next(mopen()))
2079
2080 def test_mock_open_write(self):
2081 # Test exception in file writing write()
2082 mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
2083 with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
2084 mock_filehandle = mock_namedtemp.return_value
2085 mock_write = mock_filehandle.write
2086 mock_write.side_effect = OSError('Test 2 Error')
2087 def attempt():
2088 tempfile.NamedTemporaryFile().write('asd')
2089 self.assertRaises(OSError, attempt)
2090
2091 def test_mock_open_alter_readline(self):
2092 mopen = mock.mock_open(read_data='foo\nbarn')
2093 mopen.return_value.readline.side_effect = lambda *args:'abc'
2094 first = mopen().readline()
2095 second = mopen().readline()
2096 self.assertEqual('abc', first)
2097 self.assertEqual('abc', second)
2098
2099 def test_mock_open_after_eof(self):
2100 # read, readline and readlines should work after end of file.
2101 _open = mock.mock_open(read_data='foo')
2102 h = _open('bar')
2103 h.read()
2104 self.assertEqual('', h.read())
2105 self.assertEqual('', h.read())
2106 self.assertEqual('', h.readline())
2107 self.assertEqual('', h.readline())
2108 self.assertEqual([], h.readlines())
2109 self.assertEqual([], h.readlines())
2110
2111 def test_mock_parents(self):
2112 for Klass in Mock, MagicMock:
2113 m = Klass()
2114 original_repr = repr(m)
2115 m.return_value = m
2116 self.assertIs(m(), m)
2117 self.assertEqual(repr(m), original_repr)
2118
2119 m.reset_mock()
2120 self.assertIs(m(), m)
2121 self.assertEqual(repr(m), original_repr)
2122
2123 m = Klass()
2124 m.b = m.a
2125 self.assertIn("name='mock.a'", repr(m.b))
2126 self.assertIn("name='mock.a'", repr(m.a))
2127 m.reset_mock()
2128 self.assertIn("name='mock.a'", repr(m.b))
2129 self.assertIn("name='mock.a'", repr(m.a))
2130
2131 m = Klass()
2132 original_repr = repr(m)
2133 m.a = m()
2134 m.a.return_value = m
2135
2136 self.assertEqual(repr(m), original_repr)
2137 self.assertEqual(repr(m.a()), original_repr)
2138
2139
2140 def test_attach_mock(self):
2141 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
2142 for Klass in classes:
2143 for Klass2 in classes:
2144 m = Klass()
2145
2146 m2 = Klass2(name='foo')
2147 m.attach_mock(m2, 'bar')
2148
2149 self.assertIs(m.bar, m2)
2150 self.assertIn("name='mock.bar'", repr(m2))
2151
2152 m.bar.baz(1)
2153 self.assertEqual(m.mock_calls, [call.bar.baz(1)])
2154 self.assertEqual(m.method_calls, [call.bar.baz(1)])
2155
2156
2157 def test_attach_mock_return_value(self):
2158 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
2159 for Klass in Mock, MagicMock:
2160 for Klass2 in classes:
2161 m = Klass()
2162
2163 m2 = Klass2(name='foo')
2164 m.attach_mock(m2, 'return_value')
2165
2166 self.assertIs(m(), m2)
2167 self.assertIn("name='mock()'", repr(m2))
2168
2169 m2.foo()
2170 self.assertEqual(m.mock_calls, call().foo().call_list())
2171
2172
2173 def test_attach_mock_patch_autospec(self):
2174 parent = Mock()
2175
2176 with mock.patch(f'{__name__}.something', autospec=True) as mock_func:
2177 self.assertEqual(mock_func.mock._extract_mock_name(), 'something')
2178 parent.attach_mock(mock_func, 'child')
2179 parent.child(1)
2180 something(2)
2181 mock_func(3)
2182
2183 parent_calls = [call.child(1), call.child(2), call.child(3)]
2184 child_calls = [call(1), call(2), call(3)]
2185 self.assertEqual(parent.mock_calls, parent_calls)
2186 self.assertEqual(parent.child.mock_calls, child_calls)
2187 self.assertEqual(something.mock_calls, child_calls)
2188 self.assertEqual(mock_func.mock_calls, child_calls)
2189 self.assertIn('mock.child', repr(parent.child.mock))
2190 self.assertEqual(mock_func.mock._extract_mock_name(), 'mock.child')
2191
2192
2193 def test_attach_mock_patch_autospec_signature(self):
2194 with mock.patch(f'{__name__}.Something.meth', autospec=True) as mocked:
2195 manager = Mock()
2196 manager.attach_mock(mocked, 'attach_meth')
2197 obj = Something()
2198 obj.meth(1, 2, 3, d=4)
2199 manager.assert_has_calls([call.attach_meth(mock.ANY, 1, 2, 3, d=4)])
2200 obj.meth.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)])
2201 mocked.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)])
2202
2203 with mock.patch(f'{__name__}.something', autospec=True) as mocked:
2204 manager = Mock()
2205 manager.attach_mock(mocked, 'attach_func')
2206 something(1)
2207 manager.assert_has_calls([call.attach_func(1)])
2208 something.assert_has_calls([call(1)])
2209 mocked.assert_has_calls([call(1)])
2210
2211 with mock.patch(f'{__name__}.Something', autospec=True) as mocked:
2212 manager = Mock()
2213 manager.attach_mock(mocked, 'attach_obj')
2214 obj = Something()
2215 obj.meth(1, 2, 3, d=4)
2216 manager.assert_has_calls([call.attach_obj(),
2217 call.attach_obj().meth(1, 2, 3, d=4)])
2218 obj.meth.assert_has_calls([call(1, 2, 3, d=4)])
2219 mocked.assert_has_calls([call(), call().meth(1, 2, 3, d=4)])
2220
2221
2222 def test_attribute_deletion(self):
2223 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
2224 NonCallableMock()):
2225 self.assertHasAttr(mock, 'm')
2226
2227 del mock.m
2228 self.assertNotHasAttr(mock, 'm')
2229
2230 del mock.f
2231 self.assertNotHasAttr(mock, 'f')
2232 self.assertRaises(AttributeError, getattr, mock, 'f')
2233
2234
2235 def test_mock_does_not_raise_on_repeated_attribute_deletion(self):
2236 # bpo-20239: Assigning and deleting twice an attribute raises.
2237 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
2238 NonCallableMock()):
2239 mock.foo = 3
2240 self.assertHasAttr(mock, 'foo')
2241 self.assertEqual(mock.foo, 3)
2242
2243 del mock.foo
2244 self.assertNotHasAttr(mock, 'foo')
2245
2246 mock.foo = 4
2247 self.assertHasAttr(mock, 'foo')
2248 self.assertEqual(mock.foo, 4)
2249
2250 del mock.foo
2251 self.assertNotHasAttr(mock, 'foo')
2252
2253
2254 def test_mock_raises_when_deleting_nonexistent_attribute(self):
2255 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
2256 NonCallableMock()):
2257 del mock.foo
2258 with self.assertRaises(AttributeError):
2259 del mock.foo
2260
2261
2262 def test_reset_mock_does_not_raise_on_attr_deletion(self):
2263 # bpo-31177: reset_mock should not raise AttributeError when attributes
2264 # were deleted in a mock instance
2265 mock = Mock()
2266 mock.child = True
2267 del mock.child
2268 mock.reset_mock()
2269 self.assertNotHasAttr(mock, 'child')
2270
2271
2272 def test_class_assignable(self):
2273 for mock in Mock(), MagicMock():
2274 self.assertNotIsInstance(mock, int)
2275
2276 mock.__class__ = int
2277 self.assertIsInstance(mock, int)
2278 mock.foo
2279
2280 def test_name_attribute_of_call(self):
2281 # bpo-35357: _Call should not disclose any attributes whose names
2282 # may clash with popular ones (such as ".name")
2283 self.assertIsNotNone(call.name)
2284 self.assertEqual(type(call.name), _Call)
2285 self.assertEqual(type(call.name().name), _Call)
2286
2287 def test_parent_attribute_of_call(self):
2288 # bpo-35357: _Call should not disclose any attributes whose names
2289 # may clash with popular ones (such as ".parent")
2290 self.assertIsNotNone(call.parent)
2291 self.assertEqual(type(call.parent), _Call)
2292 self.assertEqual(type(call.parent().parent), _Call)
2293
2294
2295 def test_parent_propagation_with_create_autospec(self):
2296
2297 def foo(a, b): pass
2298
2299 mock = Mock()
2300 mock.child = create_autospec(foo)
2301 mock.child(1, 2)
2302
2303 self.assertRaises(TypeError, mock.child, 1)
2304 self.assertEqual(mock.mock_calls, [call.child(1, 2)])
2305 self.assertIn('mock.child', repr(mock.child.mock))
2306
2307 def test_parent_propagation_with_autospec_attach_mock(self):
2308
2309 def foo(a, b): pass
2310
2311 parent = Mock()
2312 parent.attach_mock(create_autospec(foo, name='bar'), 'child')
2313 parent.child(1, 2)
2314
2315 self.assertRaises(TypeError, parent.child, 1)
2316 self.assertEqual(parent.child.mock_calls, [call.child(1, 2)])
2317 self.assertIn('mock.child', repr(parent.child.mock))
2318
2319
2320 def test_isinstance_under_settrace(self):
2321 # bpo-36593 : __class__ is not set for a class that has __class__
2322 # property defined when it's used with sys.settrace(trace) set.
2323 # Delete the module to force reimport with tracing function set
2324 # restore the old reference later since there are other tests that are
2325 # dependent on unittest.mock.patch. In testpatch.PatchTest
2326 # test_patch_dict_test_prefix and test_patch_test_prefix not restoring
2327 # causes the objects patched to go out of sync
2328
2329 old_patch = unittest.mock.patch
2330
2331 # Directly using __setattr__ on unittest.mock causes current imported
2332 # reference to be updated. Use a lambda so that during cleanup the
2333 # re-imported new reference is updated.
2334 self.addCleanup(lambda patch: setattr(unittest.mock, 'patch', patch),
2335 old_patch)
2336
2337 with patch.dict('sys.modules'):
2338 del sys.modules['unittest.mock']
2339
2340 # This trace will stop coverage being measured ;-)
2341 def trace(frame, event, arg): # pragma: no cover
2342 return trace
2343
2344 self.addCleanup(sys.settrace, sys.gettrace())
2345 sys.settrace(trace)
2346
2347 from unittest.mock import (
2348 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
2349 )
2350
2351 mocks = [
2352 Mock, MagicMock, NonCallableMock, NonCallableMagicMock, AsyncMock
2353 ]
2354
2355 for mock in mocks:
2356 obj = mock(spec=Something)
2357 self.assertIsInstance(obj, Something)
2358
2359 def test_bool_not_called_when_passing_spec_arg(self):
2360 class Something:
2361 def __init__(self):
2362 self.obj_with_bool_func = unittest.mock.MagicMock()
2363
2364 obj = Something()
2365 with unittest.mock.patch.object(obj, 'obj_with_bool_func', spec=object): pass
2366
2367 self.assertEqual(obj.obj_with_bool_func.__bool__.call_count, 0)
2368
2369 def test_misspelled_arguments(self):
2370 class Foo():
2371 one = 'one'
2372 # patch, patch.object and create_autospec need to check for misspelled
2373 # arguments explicitly and throw a RuntimeError if found.
2374 with self.assertRaises(RuntimeError):
2375 with patch(f'{__name__}.Something.meth', autospect=True): pass
2376 with self.assertRaises(RuntimeError):
2377 with patch.object(Foo, 'one', autospect=True): pass
2378 with self.assertRaises(RuntimeError):
2379 with patch(f'{__name__}.Something.meth', auto_spec=True): pass
2380 with self.assertRaises(RuntimeError):
2381 with patch.object(Foo, 'one', auto_spec=True): pass
2382 with self.assertRaises(RuntimeError):
2383 with patch(f'{__name__}.Something.meth', set_spec=True): pass
2384 with self.assertRaises(RuntimeError):
2385 with patch.object(Foo, 'one', set_spec=True): pass
2386 with self.assertRaises(RuntimeError):
2387 m = create_autospec(Foo, set_spec=True)
2388 # patch.multiple, on the other hand, should flag misspelled arguments
2389 # through an AttributeError, when trying to find the keys from kwargs
2390 # as attributes on the target.
2391 with self.assertRaises(AttributeError):
2392 with patch.multiple(
2393 f'{__name__}.Something', meth=DEFAULT, autospect=True): pass
2394 with self.assertRaises(AttributeError):
2395 with patch.multiple(
2396 f'{__name__}.Something', meth=DEFAULT, auto_spec=True): pass
2397 with self.assertRaises(AttributeError):
2398 with patch.multiple(
2399 f'{__name__}.Something', meth=DEFAULT, set_spec=True): pass
2400
2401 with patch(f'{__name__}.Something.meth', unsafe=True, autospect=True):
2402 pass
2403 with patch.object(Foo, 'one', unsafe=True, autospect=True): pass
2404 with patch(f'{__name__}.Something.meth', unsafe=True, auto_spec=True):
2405 pass
2406 with patch.object(Foo, 'one', unsafe=True, auto_spec=True): pass
2407 with patch(f'{__name__}.Something.meth', unsafe=True, set_spec=True):
2408 pass
2409 with patch.object(Foo, 'one', unsafe=True, set_spec=True): pass
2410 m = create_autospec(Foo, set_spec=True, unsafe=True)
2411 with patch.multiple(
2412 f'{__name__}.Typos', autospect=True, set_spec=True, auto_spec=True):
2413 pass
2414
2415 def test_property_not_called_with_spec_mock(self):
2416 obj = SomethingElse()
2417 self.assertIsNone(obj._instance, msg='before mock')
2418 mock = Mock(spec=obj)
2419 self.assertIsNone(obj._instance, msg='after mock')
2420 self.assertEqual('object', obj.instance)
2421
2422 def test_decorated_async_methods_with_spec_mock(self):
2423 class Foo():
2424 @classmethod
2425 async def class_method(cls):
2426 pass
2427 @staticmethod
2428 async def static_method():
2429 pass
2430 async def method(self):
2431 pass
2432 mock = Mock(spec=Foo)
2433 for m in (mock.method, mock.class_method, mock.static_method):
2434 self.assertIsInstance(m, AsyncMock)
2435
2436 if __name__ == '__main__':
2437 unittest.main()