blob: 04ab5227157801e67a12eba5a6f07e8313114f1d [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()
Susan Su2bdd5852019-02-13 18:22:29 -0800727 self.assertRaisesRegex(AssertionError, 'not called',
Michael Foord345266a2012-03-14 12:24:34 -0700728 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
Susan Su2bdd5852019-02-13 18:22:29 -0800920 actual = 'not called.'
Michael Foord345266a2012-03-14 12:24:34 -0700921 expected = "mock(1, '2', 3, bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -0800922 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700923 self.assertRaisesWithMsg(
Susan Su2bdd5852019-02-13 18:22:29 -0800924 AssertionError, message % (expected, actual),
Michael Foord345266a2012-03-14 12:24:34 -0700925 mock.assert_called_with, 1, '2', 3, bar='foo'
926 )
927
928 mock.foo(1, '2', 3, foo='foo')
929
930
931 asserters = [
932 mock.foo.assert_called_with, mock.foo.assert_called_once_with
933 ]
934 for meth in asserters:
935 actual = "foo(1, '2', 3, foo='foo')"
936 expected = "foo(1, '2', 3, bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -0800937 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700938 self.assertRaisesWithMsg(
939 AssertionError, message % (expected, actual),
940 meth, 1, '2', 3, bar='foo'
941 )
942
943 # just kwargs
944 for meth in asserters:
945 actual = "foo(1, '2', 3, foo='foo')"
946 expected = "foo(bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -0800947 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700948 self.assertRaisesWithMsg(
949 AssertionError, message % (expected, actual),
950 meth, bar='foo'
951 )
952
953 # just args
954 for meth in asserters:
955 actual = "foo(1, '2', 3, foo='foo')"
956 expected = "foo(1, 2, 3)"
Susan Su2bdd5852019-02-13 18:22:29 -0800957 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700958 self.assertRaisesWithMsg(
959 AssertionError, message % (expected, actual),
960 meth, 1, 2, 3
961 )
962
963 # empty
964 for meth in asserters:
965 actual = "foo(1, '2', 3, foo='foo')"
966 expected = "foo()"
Susan Su2bdd5852019-02-13 18:22:29 -0800967 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700968 self.assertRaisesWithMsg(
969 AssertionError, message % (expected, actual), meth
970 )
971
972
973 def test_mock_calls(self):
974 mock = MagicMock()
975
976 # need to do this because MagicMock.mock_calls used to just return
977 # a MagicMock which also returned a MagicMock when __eq__ was called
978 self.assertIs(mock.mock_calls == [], True)
979
980 mock = MagicMock()
981 mock()
982 expected = [('', (), {})]
983 self.assertEqual(mock.mock_calls, expected)
984
985 mock.foo()
986 expected.append(call.foo())
987 self.assertEqual(mock.mock_calls, expected)
988 # intermediate mock_calls work too
989 self.assertEqual(mock.foo.mock_calls, [('', (), {})])
990
991 mock = MagicMock()
992 mock().foo(1, 2, 3, a=4, b=5)
993 expected = [
994 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
995 ]
996 self.assertEqual(mock.mock_calls, expected)
997 self.assertEqual(mock.return_value.foo.mock_calls,
998 [('', (1, 2, 3), dict(a=4, b=5))])
999 self.assertEqual(mock.return_value.mock_calls,
1000 [('foo', (1, 2, 3), dict(a=4, b=5))])
1001
1002 mock = MagicMock()
1003 mock().foo.bar().baz()
1004 expected = [
1005 ('', (), {}), ('().foo.bar', (), {}),
1006 ('().foo.bar().baz', (), {})
1007 ]
1008 self.assertEqual(mock.mock_calls, expected)
1009 self.assertEqual(mock().mock_calls,
1010 call.foo.bar().baz().call_list())
1011
1012 for kwargs in dict(), dict(name='bar'):
1013 mock = MagicMock(**kwargs)
1014 int(mock.foo)
1015 expected = [('foo.__int__', (), {})]
1016 self.assertEqual(mock.mock_calls, expected)
1017
1018 mock = MagicMock(**kwargs)
1019 mock.a()()
1020 expected = [('a', (), {}), ('a()', (), {})]
1021 self.assertEqual(mock.mock_calls, expected)
1022 self.assertEqual(mock.a().mock_calls, [call()])
1023
1024 mock = MagicMock(**kwargs)
1025 mock(1)(2)(3)
1026 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
1027 self.assertEqual(mock().mock_calls, call(2)(3).call_list())
1028 self.assertEqual(mock()().mock_calls, call(3).call_list())
1029
1030 mock = MagicMock(**kwargs)
1031 mock(1)(2)(3).a.b.c(4)
1032 self.assertEqual(mock.mock_calls,
1033 call(1)(2)(3).a.b.c(4).call_list())
1034 self.assertEqual(mock().mock_calls,
1035 call(2)(3).a.b.c(4).call_list())
1036 self.assertEqual(mock()().mock_calls,
1037 call(3).a.b.c(4).call_list())
1038
1039 mock = MagicMock(**kwargs)
1040 int(mock().foo.bar().baz())
1041 last_call = ('().foo.bar().baz().__int__', (), {})
1042 self.assertEqual(mock.mock_calls[-1], last_call)
1043 self.assertEqual(mock().mock_calls,
1044 call.foo.bar().baz().__int__().call_list())
1045 self.assertEqual(mock().foo.bar().mock_calls,
1046 call.baz().__int__().call_list())
1047 self.assertEqual(mock().foo.bar().baz.mock_calls,
1048 call().__int__().call_list())
1049
1050
Chris Withers8ca0fa92018-12-03 21:31:37 +00001051 def test_child_mock_call_equal(self):
1052 m = Mock()
1053 result = m()
1054 result.wibble()
1055 # parent looks like this:
1056 self.assertEqual(m.mock_calls, [call(), call().wibble()])
1057 # but child should look like this:
1058 self.assertEqual(result.mock_calls, [call.wibble()])
1059
1060
1061 def test_mock_call_not_equal_leaf(self):
1062 m = Mock()
1063 m.foo().something()
1064 self.assertNotEqual(m.mock_calls[1], call.foo().different())
1065 self.assertEqual(m.mock_calls[0], call.foo())
1066
1067
1068 def test_mock_call_not_equal_non_leaf(self):
1069 m = Mock()
1070 m.foo().bar()
1071 self.assertNotEqual(m.mock_calls[1], call.baz().bar())
1072 self.assertNotEqual(m.mock_calls[0], call.baz())
1073
1074
1075 def test_mock_call_not_equal_non_leaf_params_different(self):
1076 m = Mock()
1077 m.foo(x=1).bar()
1078 # This isn't ideal, but there's no way to fix it without breaking backwards compatibility:
1079 self.assertEqual(m.mock_calls[1], call.foo(x=2).bar())
1080
1081
1082 def test_mock_call_not_equal_non_leaf_attr(self):
1083 m = Mock()
1084 m.foo.bar()
1085 self.assertNotEqual(m.mock_calls[0], call.baz.bar())
1086
1087
1088 def test_mock_call_not_equal_non_leaf_call_versus_attr(self):
1089 m = Mock()
1090 m.foo.bar()
1091 self.assertNotEqual(m.mock_calls[0], call.foo().bar())
1092
1093
1094 def test_mock_call_repr(self):
1095 m = Mock()
1096 m.foo().bar().baz.bob()
1097 self.assertEqual(repr(m.mock_calls[0]), 'call.foo()')
1098 self.assertEqual(repr(m.mock_calls[1]), 'call.foo().bar()')
1099 self.assertEqual(repr(m.mock_calls[2]), 'call.foo().bar().baz.bob()')
1100
1101
Michael Foord345266a2012-03-14 12:24:34 -07001102 def test_subclassing(self):
1103 class Subclass(Mock):
1104 pass
1105
1106 mock = Subclass()
1107 self.assertIsInstance(mock.foo, Subclass)
1108 self.assertIsInstance(mock(), Subclass)
1109
1110 class Subclass(Mock):
1111 def _get_child_mock(self, **kwargs):
1112 return Mock(**kwargs)
1113
1114 mock = Subclass()
1115 self.assertNotIsInstance(mock.foo, Subclass)
1116 self.assertNotIsInstance(mock(), Subclass)
1117
1118
1119 def test_arg_lists(self):
1120 mocks = [
1121 Mock(),
1122 MagicMock(),
1123 NonCallableMock(),
1124 NonCallableMagicMock()
1125 ]
1126
1127 def assert_attrs(mock):
1128 names = 'call_args_list', 'method_calls', 'mock_calls'
1129 for name in names:
1130 attr = getattr(mock, name)
1131 self.assertIsInstance(attr, _CallList)
1132 self.assertIsInstance(attr, list)
1133 self.assertEqual(attr, [])
1134
1135 for mock in mocks:
1136 assert_attrs(mock)
1137
1138 if callable(mock):
1139 mock()
1140 mock(1, 2)
1141 mock(a=3)
1142
1143 mock.reset_mock()
1144 assert_attrs(mock)
1145
1146 mock.foo()
1147 mock.foo.bar(1, a=3)
1148 mock.foo(1).bar().baz(3)
1149
1150 mock.reset_mock()
1151 assert_attrs(mock)
1152
1153
1154 def test_call_args_two_tuple(self):
1155 mock = Mock()
1156 mock(1, a=3)
1157 mock(2, b=4)
1158
1159 self.assertEqual(len(mock.call_args), 2)
1160 args, kwargs = mock.call_args
1161 self.assertEqual(args, (2,))
1162 self.assertEqual(kwargs, dict(b=4))
1163
1164 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
1165 for expected, call_args in zip(expected_list, mock.call_args_list):
1166 self.assertEqual(len(call_args), 2)
1167 self.assertEqual(expected[0], call_args[0])
1168 self.assertEqual(expected[1], call_args[1])
1169
1170
1171 def test_side_effect_iterator(self):
1172 mock = Mock(side_effect=iter([1, 2, 3]))
1173 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1174 self.assertRaises(StopIteration, mock)
1175
1176 mock = MagicMock(side_effect=['a', 'b', 'c'])
1177 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1178 self.assertRaises(StopIteration, mock)
1179
1180 mock = Mock(side_effect='ghi')
1181 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
1182 self.assertRaises(StopIteration, mock)
1183
1184 class Foo(object):
1185 pass
1186 mock = MagicMock(side_effect=Foo)
1187 self.assertIsInstance(mock(), Foo)
1188
1189 mock = Mock(side_effect=Iter())
1190 self.assertEqual([mock(), mock(), mock(), mock()],
1191 ['this', 'is', 'an', 'iter'])
1192 self.assertRaises(StopIteration, mock)
1193
1194
Michael Foord2cd48732012-04-21 15:52:11 +01001195 def test_side_effect_iterator_exceptions(self):
1196 for Klass in Mock, MagicMock:
1197 iterable = (ValueError, 3, KeyError, 6)
1198 m = Klass(side_effect=iterable)
1199 self.assertRaises(ValueError, m)
1200 self.assertEqual(m(), 3)
1201 self.assertRaises(KeyError, m)
1202 self.assertEqual(m(), 6)
1203
1204
Michael Foord345266a2012-03-14 12:24:34 -07001205 def test_side_effect_setting_iterator(self):
1206 mock = Mock()
1207 mock.side_effect = iter([1, 2, 3])
1208 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1209 self.assertRaises(StopIteration, mock)
1210 side_effect = mock.side_effect
1211 self.assertIsInstance(side_effect, type(iter([])))
1212
1213 mock.side_effect = ['a', 'b', 'c']
1214 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1215 self.assertRaises(StopIteration, mock)
1216 side_effect = mock.side_effect
1217 self.assertIsInstance(side_effect, type(iter([])))
1218
1219 this_iter = Iter()
1220 mock.side_effect = this_iter
1221 self.assertEqual([mock(), mock(), mock(), mock()],
1222 ['this', 'is', 'an', 'iter'])
1223 self.assertRaises(StopIteration, mock)
1224 self.assertIs(mock.side_effect, this_iter)
1225
Andrew Svetlov8b2cd752013-04-07 16:42:24 +03001226 def test_side_effect_iterator_default(self):
1227 mock = Mock(return_value=2)
1228 mock.side_effect = iter([1, DEFAULT])
1229 self.assertEqual([mock(), mock()], [1, 2])
Michael Foord345266a2012-03-14 12:24:34 -07001230
1231 def test_assert_has_calls_any_order(self):
1232 mock = Mock()
1233 mock(1, 2)
1234 mock(a=3)
1235 mock(3, 4)
1236 mock(b=6)
1237 mock(b=6)
1238
1239 kalls = [
1240 call(1, 2), ({'a': 3},),
1241 ((3, 4),), ((), {'a': 3}),
1242 ('', (1, 2)), ('', {'a': 3}),
1243 ('', (1, 2), {}), ('', (), {'a': 3})
1244 ]
1245 for kall in kalls:
1246 mock.assert_has_calls([kall], any_order=True)
1247
1248 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
1249 self.assertRaises(
1250 AssertionError, mock.assert_has_calls,
1251 [kall], any_order=True
1252 )
1253
1254 kall_lists = [
1255 [call(1, 2), call(b=6)],
1256 [call(3, 4), call(1, 2)],
1257 [call(b=6), call(b=6)],
1258 ]
1259
1260 for kall_list in kall_lists:
1261 mock.assert_has_calls(kall_list, any_order=True)
1262
1263 kall_lists = [
1264 [call(b=6), call(b=6), call(b=6)],
1265 [call(1, 2), call(1, 2)],
1266 [call(3, 4), call(1, 2), call(5, 7)],
1267 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
1268 ]
1269 for kall_list in kall_lists:
1270 self.assertRaises(
1271 AssertionError, mock.assert_has_calls,
1272 kall_list, any_order=True
1273 )
1274
1275 def test_assert_has_calls(self):
1276 kalls1 = [
1277 call(1, 2), ({'a': 3},),
1278 ((3, 4),), call(b=6),
1279 ('', (1,), {'b': 6}),
1280 ]
1281 kalls2 = [call.foo(), call.bar(1)]
1282 kalls2.extend(call.spam().baz(a=3).call_list())
1283 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
1284
1285 mocks = []
1286 for mock in Mock(), MagicMock():
1287 mock(1, 2)
1288 mock(a=3)
1289 mock(3, 4)
1290 mock(b=6)
1291 mock(1, b=6)
1292 mocks.append((mock, kalls1))
1293
1294 mock = Mock()
1295 mock.foo()
1296 mock.bar(1)
1297 mock.spam().baz(a=3)
1298 mock.bam(set(), foo={}).fish([1])
1299 mocks.append((mock, kalls2))
1300
1301 for mock, kalls in mocks:
1302 for i in range(len(kalls)):
1303 for step in 1, 2, 3:
1304 these = kalls[i:i+step]
1305 mock.assert_has_calls(these)
1306
1307 if len(these) > 1:
1308 self.assertRaises(
1309 AssertionError,
1310 mock.assert_has_calls,
1311 list(reversed(these))
1312 )
1313
1314
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001315 def test_assert_has_calls_with_function_spec(self):
1316 def f(a, b, c, d=None):
1317 pass
1318
1319 mock = Mock(spec=f)
1320
1321 mock(1, b=2, c=3)
1322 mock(4, 5, c=6, d=7)
1323 mock(10, 11, c=12)
1324 calls = [
1325 ('', (1, 2, 3), {}),
1326 ('', (4, 5, 6), {'d': 7}),
1327 ((10, 11, 12), {}),
1328 ]
1329 mock.assert_has_calls(calls)
1330 mock.assert_has_calls(calls, any_order=True)
1331 mock.assert_has_calls(calls[1:])
1332 mock.assert_has_calls(calls[1:], any_order=True)
1333 mock.assert_has_calls(calls[:-1])
1334 mock.assert_has_calls(calls[:-1], any_order=True)
1335 # Reversed order
1336 calls = list(reversed(calls))
1337 with self.assertRaises(AssertionError):
1338 mock.assert_has_calls(calls)
1339 mock.assert_has_calls(calls, any_order=True)
1340 with self.assertRaises(AssertionError):
1341 mock.assert_has_calls(calls[1:])
1342 mock.assert_has_calls(calls[1:], any_order=True)
1343 with self.assertRaises(AssertionError):
1344 mock.assert_has_calls(calls[:-1])
1345 mock.assert_has_calls(calls[:-1], any_order=True)
1346
1347
Michael Foord345266a2012-03-14 12:24:34 -07001348 def test_assert_any_call(self):
1349 mock = Mock()
1350 mock(1, 2)
1351 mock(a=3)
1352 mock(1, b=6)
1353
1354 mock.assert_any_call(1, 2)
1355 mock.assert_any_call(a=3)
1356 mock.assert_any_call(1, b=6)
1357
1358 self.assertRaises(
1359 AssertionError,
1360 mock.assert_any_call
1361 )
1362 self.assertRaises(
1363 AssertionError,
1364 mock.assert_any_call,
1365 1, 3
1366 )
1367 self.assertRaises(
1368 AssertionError,
1369 mock.assert_any_call,
1370 a=4
1371 )
1372
1373
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001374 def test_assert_any_call_with_function_spec(self):
1375 def f(a, b, c, d=None):
1376 pass
1377
1378 mock = Mock(spec=f)
1379
1380 mock(1, b=2, c=3)
1381 mock(4, 5, c=6, d=7)
1382 mock.assert_any_call(1, 2, 3)
1383 mock.assert_any_call(a=1, b=2, c=3)
1384 mock.assert_any_call(4, 5, 6, 7)
1385 mock.assert_any_call(a=4, b=5, c=6, d=7)
1386 self.assertRaises(AssertionError, mock.assert_any_call,
1387 1, b=3, c=2)
1388 # Expected call doesn't match the spec's signature
1389 with self.assertRaises(AssertionError) as cm:
1390 mock.assert_any_call(e=8)
1391 self.assertIsInstance(cm.exception.__cause__, TypeError)
1392
1393
Michael Foord345266a2012-03-14 12:24:34 -07001394 def test_mock_calls_create_autospec(self):
1395 def f(a, b):
1396 pass
1397 obj = Iter()
1398 obj.f = f
1399
1400 funcs = [
1401 create_autospec(f),
1402 create_autospec(obj).f
1403 ]
1404 for func in funcs:
1405 func(1, 2)
1406 func(3, 4)
1407
1408 self.assertEqual(
1409 func.mock_calls, [call(1, 2), call(3, 4)]
1410 )
1411
Kushal Das484f8a82014-04-16 01:05:50 +05301412 #Issue21222
1413 def test_create_autospec_with_name(self):
1414 m = mock.create_autospec(object(), name='sweet_func')
1415 self.assertIn('sweet_func', repr(m))
Michael Foord345266a2012-03-14 12:24:34 -07001416
Kushal Das8c145342014-04-16 23:32:21 +05301417 #Issue21238
1418 def test_mock_unsafe(self):
1419 m = Mock()
1420 with self.assertRaises(AttributeError):
1421 m.assert_foo_call()
1422 with self.assertRaises(AttributeError):
1423 m.assret_foo_call()
1424 m = Mock(unsafe=True)
1425 m.assert_foo_call()
1426 m.assret_foo_call()
1427
Kushal Das8af9db32014-04-17 01:36:14 +05301428 #Issue21262
1429 def test_assert_not_called(self):
1430 m = Mock()
1431 m.hello.assert_not_called()
1432 m.hello()
1433 with self.assertRaises(AssertionError):
1434 m.hello.assert_not_called()
1435
Petter Strandmark47d94242018-10-28 21:37:10 +01001436 def test_assert_not_called_message(self):
1437 m = Mock()
1438 m(1, 2)
1439 self.assertRaisesRegex(AssertionError,
1440 re.escape("Calls: [call(1, 2)]"),
1441 m.assert_not_called)
1442
Victor Stinner2c2a4e62016-03-11 22:17:48 +01001443 def test_assert_called(self):
1444 m = Mock()
1445 with self.assertRaises(AssertionError):
1446 m.hello.assert_called()
1447 m.hello()
1448 m.hello.assert_called()
1449
1450 m.hello()
1451 m.hello.assert_called()
1452
1453 def test_assert_called_once(self):
1454 m = Mock()
1455 with self.assertRaises(AssertionError):
1456 m.hello.assert_called_once()
1457 m.hello()
1458 m.hello.assert_called_once()
1459
1460 m.hello()
1461 with self.assertRaises(AssertionError):
1462 m.hello.assert_called_once()
1463
Petter Strandmark47d94242018-10-28 21:37:10 +01001464 def test_assert_called_once_message(self):
1465 m = Mock()
1466 m(1, 2)
1467 m(3)
1468 self.assertRaisesRegex(AssertionError,
1469 re.escape("Calls: [call(1, 2), call(3)]"),
1470 m.assert_called_once)
1471
1472 def test_assert_called_once_message_not_called(self):
1473 m = Mock()
1474 with self.assertRaises(AssertionError) as e:
1475 m.assert_called_once()
1476 self.assertNotIn("Calls:", str(e.exception))
1477
Kushal Das047f14c2014-06-09 13:45:56 +05301478 #Issue21256 printout of keyword args should be in deterministic order
1479 def test_sorted_call_signature(self):
1480 m = Mock()
1481 m.hello(name='hello', daddy='hero')
1482 text = "call(daddy='hero', name='hello')"
R David Murray130a5662014-06-11 17:09:43 -04001483 self.assertEqual(repr(m.hello.call_args), text)
Kushal Das8af9db32014-04-17 01:36:14 +05301484
Kushal Dasa37b9582014-09-16 18:33:37 +05301485 #Issue21270 overrides tuple methods for mock.call objects
1486 def test_override_tuple_methods(self):
1487 c = call.count()
1488 i = call.index(132,'hello')
1489 m = Mock()
1490 m.count()
1491 m.index(132,"hello")
1492 self.assertEqual(m.method_calls[0], c)
1493 self.assertEqual(m.method_calls[1], i)
1494
Kushal Das9cd39a12016-06-02 10:20:16 -07001495 def test_reset_return_sideeffect(self):
1496 m = Mock(return_value=10, side_effect=[2,3])
1497 m.reset_mock(return_value=True, side_effect=True)
1498 self.assertIsInstance(m.return_value, Mock)
1499 self.assertEqual(m.side_effect, None)
1500
1501 def test_reset_return(self):
1502 m = Mock(return_value=10, side_effect=[2,3])
1503 m.reset_mock(return_value=True)
1504 self.assertIsInstance(m.return_value, Mock)
1505 self.assertNotEqual(m.side_effect, None)
1506
1507 def test_reset_sideeffect(self):
1508 m = Mock(return_value=10, side_effect=[2,3])
1509 m.reset_mock(side_effect=True)
1510 self.assertEqual(m.return_value, 10)
1511 self.assertEqual(m.side_effect, None)
1512
Michael Foord345266a2012-03-14 12:24:34 -07001513 def test_mock_add_spec(self):
1514 class _One(object):
1515 one = 1
1516 class _Two(object):
1517 two = 2
1518 class Anything(object):
1519 one = two = three = 'four'
1520
1521 klasses = [
1522 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1523 ]
1524 for Klass in list(klasses):
1525 klasses.append(lambda K=Klass: K(spec=Anything))
1526 klasses.append(lambda K=Klass: K(spec_set=Anything))
1527
1528 for Klass in klasses:
1529 for kwargs in dict(), dict(spec_set=True):
1530 mock = Klass()
1531 #no error
1532 mock.one, mock.two, mock.three
1533
1534 for One, Two in [(_One, _Two), (['one'], ['two'])]:
1535 for kwargs in dict(), dict(spec_set=True):
1536 mock.mock_add_spec(One, **kwargs)
1537
1538 mock.one
1539 self.assertRaises(
1540 AttributeError, getattr, mock, 'two'
1541 )
1542 self.assertRaises(
1543 AttributeError, getattr, mock, 'three'
1544 )
1545 if 'spec_set' in kwargs:
1546 self.assertRaises(
1547 AttributeError, setattr, mock, 'three', None
1548 )
1549
1550 mock.mock_add_spec(Two, **kwargs)
1551 self.assertRaises(
1552 AttributeError, getattr, mock, 'one'
1553 )
1554 mock.two
1555 self.assertRaises(
1556 AttributeError, getattr, mock, 'three'
1557 )
1558 if 'spec_set' in kwargs:
1559 self.assertRaises(
1560 AttributeError, setattr, mock, 'three', None
1561 )
1562 # note that creating a mock, setting an instance attribute, and
1563 # *then* setting a spec doesn't work. Not the intended use case
1564
1565
1566 def test_mock_add_spec_magic_methods(self):
1567 for Klass in MagicMock, NonCallableMagicMock:
1568 mock = Klass()
1569 int(mock)
1570
1571 mock.mock_add_spec(object)
1572 self.assertRaises(TypeError, int, mock)
1573
1574 mock = Klass()
1575 mock['foo']
1576 mock.__int__.return_value =4
1577
1578 mock.mock_add_spec(int)
1579 self.assertEqual(int(mock), 4)
1580 self.assertRaises(TypeError, lambda: mock['foo'])
1581
1582
1583 def test_adding_child_mock(self):
1584 for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock:
1585 mock = Klass()
1586
1587 mock.foo = Mock()
1588 mock.foo()
1589
1590 self.assertEqual(mock.method_calls, [call.foo()])
1591 self.assertEqual(mock.mock_calls, [call.foo()])
1592
1593 mock = Klass()
1594 mock.bar = Mock(name='name')
1595 mock.bar()
1596 self.assertEqual(mock.method_calls, [])
1597 self.assertEqual(mock.mock_calls, [])
1598
1599 # mock with an existing _new_parent but no name
1600 mock = Klass()
1601 mock.baz = MagicMock()()
1602 mock.baz()
1603 self.assertEqual(mock.method_calls, [])
1604 self.assertEqual(mock.mock_calls, [])
1605
1606
1607 def test_adding_return_value_mock(self):
1608 for Klass in Mock, MagicMock:
1609 mock = Klass()
1610 mock.return_value = MagicMock()
1611
1612 mock()()
1613 self.assertEqual(mock.mock_calls, [call(), call()()])
1614
1615
1616 def test_manager_mock(self):
1617 class Foo(object):
1618 one = 'one'
1619 two = 'two'
1620 manager = Mock()
1621 p1 = patch.object(Foo, 'one')
1622 p2 = patch.object(Foo, 'two')
1623
1624 mock_one = p1.start()
1625 self.addCleanup(p1.stop)
1626 mock_two = p2.start()
1627 self.addCleanup(p2.stop)
1628
1629 manager.attach_mock(mock_one, 'one')
1630 manager.attach_mock(mock_two, 'two')
1631
1632 Foo.two()
1633 Foo.one()
1634
1635 self.assertEqual(manager.mock_calls, [call.two(), call.one()])
1636
1637
1638 def test_magic_methods_mock_calls(self):
1639 for Klass in Mock, MagicMock:
1640 m = Klass()
1641 m.__int__ = Mock(return_value=3)
1642 m.__float__ = MagicMock(return_value=3.0)
1643 int(m)
1644 float(m)
1645
1646 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
1647 self.assertEqual(m.method_calls, [])
1648
Robert Collins5329aaa2015-07-17 20:08:45 +12001649 def test_mock_open_reuse_issue_21750(self):
1650 mocked_open = mock.mock_open(read_data='data')
1651 f1 = mocked_open('a-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001652 f1_data = f1.read()
Robert Collins5329aaa2015-07-17 20:08:45 +12001653 f2 = mocked_open('another-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001654 f2_data = f2.read()
1655 self.assertEqual(f1_data, f2_data)
1656
Tony Flury20870232018-09-12 23:21:16 +01001657 def test_mock_open_dunder_iter_issue(self):
1658 # Test dunder_iter method generates the expected result and
1659 # consumes the iterator.
1660 mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue')
1661 f1 = mocked_open('a-name')
1662 lines = [line for line in f1]
1663 self.assertEqual(lines[0], 'Remarkable\n')
1664 self.assertEqual(lines[1], 'Norwegian Blue')
1665 self.assertEqual(list(f1), [])
1666
Robert Collinsca647ef2015-07-24 03:48:20 +12001667 def test_mock_open_write(self):
1668 # Test exception in file writing write()
1669 mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
1670 with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
1671 mock_filehandle = mock_namedtemp.return_value
1672 mock_write = mock_filehandle.write
1673 mock_write.side_effect = OSError('Test 2 Error')
1674 def attempt():
1675 tempfile.NamedTemporaryFile().write('asd')
1676 self.assertRaises(OSError, attempt)
1677
1678 def test_mock_open_alter_readline(self):
1679 mopen = mock.mock_open(read_data='foo\nbarn')
1680 mopen.return_value.readline.side_effect = lambda *args:'abc'
1681 first = mopen().readline()
1682 second = mopen().readline()
1683 self.assertEqual('abc', first)
1684 self.assertEqual('abc', second)
Michael Foord345266a2012-03-14 12:24:34 -07001685
Robert Collins9549a3e2016-05-16 15:22:01 +12001686 def test_mock_open_after_eof(self):
1687 # read, readline and readlines should work after end of file.
1688 _open = mock.mock_open(read_data='foo')
1689 h = _open('bar')
1690 h.read()
1691 self.assertEqual('', h.read())
1692 self.assertEqual('', h.read())
1693 self.assertEqual('', h.readline())
1694 self.assertEqual('', h.readline())
1695 self.assertEqual([], h.readlines())
1696 self.assertEqual([], h.readlines())
1697
Michael Foord345266a2012-03-14 12:24:34 -07001698 def test_mock_parents(self):
1699 for Klass in Mock, MagicMock:
1700 m = Klass()
1701 original_repr = repr(m)
1702 m.return_value = m
1703 self.assertIs(m(), m)
1704 self.assertEqual(repr(m), original_repr)
1705
1706 m.reset_mock()
1707 self.assertIs(m(), m)
1708 self.assertEqual(repr(m), original_repr)
1709
1710 m = Klass()
1711 m.b = m.a
1712 self.assertIn("name='mock.a'", repr(m.b))
1713 self.assertIn("name='mock.a'", repr(m.a))
1714 m.reset_mock()
1715 self.assertIn("name='mock.a'", repr(m.b))
1716 self.assertIn("name='mock.a'", repr(m.a))
1717
1718 m = Klass()
1719 original_repr = repr(m)
1720 m.a = m()
1721 m.a.return_value = m
1722
1723 self.assertEqual(repr(m), original_repr)
1724 self.assertEqual(repr(m.a()), original_repr)
1725
1726
1727 def test_attach_mock(self):
1728 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1729 for Klass in classes:
1730 for Klass2 in classes:
1731 m = Klass()
1732
1733 m2 = Klass2(name='foo')
1734 m.attach_mock(m2, 'bar')
1735
1736 self.assertIs(m.bar, m2)
1737 self.assertIn("name='mock.bar'", repr(m2))
1738
1739 m.bar.baz(1)
1740 self.assertEqual(m.mock_calls, [call.bar.baz(1)])
1741 self.assertEqual(m.method_calls, [call.bar.baz(1)])
1742
1743
1744 def test_attach_mock_return_value(self):
1745 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1746 for Klass in Mock, MagicMock:
1747 for Klass2 in classes:
1748 m = Klass()
1749
1750 m2 = Klass2(name='foo')
1751 m.attach_mock(m2, 'return_value')
1752
1753 self.assertIs(m(), m2)
1754 self.assertIn("name='mock()'", repr(m2))
1755
1756 m2.foo()
1757 self.assertEqual(m.mock_calls, call().foo().call_list())
1758
1759
1760 def test_attribute_deletion(self):
Michael Foord468ec342013-09-15 20:05:19 +12001761 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1762 NonCallableMock()):
Michael Foord345266a2012-03-14 12:24:34 -07001763 self.assertTrue(hasattr(mock, 'm'))
1764
1765 del mock.m
1766 self.assertFalse(hasattr(mock, 'm'))
1767
1768 del mock.f
1769 self.assertFalse(hasattr(mock, 'f'))
1770 self.assertRaises(AttributeError, getattr, mock, 'f')
1771
1772
Pablo Galindo222d3032019-01-21 08:57:46 +00001773 def test_mock_does_not_raise_on_repeated_attribute_deletion(self):
1774 # bpo-20239: Assigning and deleting twice an attribute raises.
1775 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1776 NonCallableMock()):
1777 mock.foo = 3
1778 self.assertTrue(hasattr(mock, 'foo'))
1779 self.assertEqual(mock.foo, 3)
1780
1781 del mock.foo
1782 self.assertFalse(hasattr(mock, 'foo'))
1783
1784 mock.foo = 4
1785 self.assertTrue(hasattr(mock, 'foo'))
1786 self.assertEqual(mock.foo, 4)
1787
1788 del mock.foo
1789 self.assertFalse(hasattr(mock, 'foo'))
1790
1791
1792 def test_mock_raises_when_deleting_nonexistent_attribute(self):
1793 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1794 NonCallableMock()):
1795 del mock.foo
1796 with self.assertRaises(AttributeError):
1797 del mock.foo
1798
1799
Xtreakedeca922018-12-01 15:33:54 +05301800 def test_reset_mock_does_not_raise_on_attr_deletion(self):
1801 # bpo-31177: reset_mock should not raise AttributeError when attributes
1802 # were deleted in a mock instance
1803 mock = Mock()
1804 mock.child = True
1805 del mock.child
1806 mock.reset_mock()
1807 self.assertFalse(hasattr(mock, 'child'))
1808
1809
Michael Foord345266a2012-03-14 12:24:34 -07001810 def test_class_assignable(self):
1811 for mock in Mock(), MagicMock():
1812 self.assertNotIsInstance(mock, int)
1813
1814 mock.__class__ = int
1815 self.assertIsInstance(mock, int)
1816 mock.foo
1817
Andrew Dunaie63e6172018-12-04 11:08:45 +02001818 def test_name_attribute_of_call(self):
1819 # bpo-35357: _Call should not disclose any attributes whose names
1820 # may clash with popular ones (such as ".name")
1821 self.assertIsNotNone(call.name)
1822 self.assertEqual(type(call.name), _Call)
1823 self.assertEqual(type(call.name().name), _Call)
1824
1825 def test_parent_attribute_of_call(self):
1826 # bpo-35357: _Call should not disclose any attributes whose names
1827 # may clash with popular ones (such as ".parent")
1828 self.assertIsNotNone(call.parent)
1829 self.assertEqual(type(call.parent), _Call)
1830 self.assertEqual(type(call.parent().parent), _Call)
1831
Michael Foord345266a2012-03-14 12:24:34 -07001832
Michael Foord345266a2012-03-14 12:24:34 -07001833if __name__ == '__main__':
1834 unittest.main()