blob: 37f14c37f47d592ca4026a46d578d2a1c489f9f0 [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")
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530270 self.assertEqual(mock.call_args.args, (sentinel.Arg,),
271 "call_args not set")
272 self.assertEqual(mock.call_args.kwargs, {},
273 "call_args not set")
Michael Foord345266a2012-03-14 12:24:34 -0700274 self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
275 "call_args_list not initialised correctly")
276
277 mock.return_value = sentinel.ReturnValue
278 ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
279 self.assertEqual(ret_val, sentinel.ReturnValue,
280 "incorrect return value")
281
282 self.assertEqual(mock.call_count, 2, "call_count incorrect")
283 self.assertEqual(mock.call_args,
284 ((sentinel.Arg,), {'key': sentinel.KeyArg}),
285 "call_args not set")
286 self.assertEqual(mock.call_args_list, [
287 ((sentinel.Arg,), {}),
288 ((sentinel.Arg,), {'key': sentinel.KeyArg})
289 ],
290 "call_args_list not set")
291
292
293 def test_call_args_comparison(self):
294 mock = Mock()
295 mock()
296 mock(sentinel.Arg)
297 mock(kw=sentinel.Kwarg)
298 mock(sentinel.Arg, kw=sentinel.Kwarg)
299 self.assertEqual(mock.call_args_list, [
300 (),
301 ((sentinel.Arg,),),
302 ({"kw": sentinel.Kwarg},),
303 ((sentinel.Arg,), {"kw": sentinel.Kwarg})
304 ])
305 self.assertEqual(mock.call_args,
306 ((sentinel.Arg,), {"kw": sentinel.Kwarg}))
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530307 self.assertEqual(mock.call_args.args, (sentinel.Arg,))
308 self.assertEqual(mock.call_args.kwargs, {"kw": sentinel.Kwarg})
Michael Foord345266a2012-03-14 12:24:34 -0700309
Berker Peksag3fc536f2015-09-09 23:35:25 +0300310 # Comparing call_args to a long sequence should not raise
311 # an exception. See issue 24857.
312 self.assertFalse(mock.call_args == "a long sequence")
Michael Foord345266a2012-03-14 12:24:34 -0700313
Berker Peksagce913872016-03-28 00:30:02 +0300314
315 def test_calls_equal_with_any(self):
Berker Peksagce913872016-03-28 00:30:02 +0300316 # Check that equality and non-equality is consistent even when
317 # comparing with mock.ANY
Serhiy Storchaka362f0582017-01-21 23:12:58 +0200318 mm = mock.MagicMock()
319 self.assertTrue(mm == mm)
320 self.assertFalse(mm != mm)
321 self.assertFalse(mm == mock.MagicMock())
322 self.assertTrue(mm != mock.MagicMock())
323 self.assertTrue(mm == mock.ANY)
324 self.assertFalse(mm != mock.ANY)
325 self.assertTrue(mock.ANY == mm)
326 self.assertFalse(mock.ANY != mm)
327
328 call1 = mock.call(mock.MagicMock())
329 call2 = mock.call(mock.ANY)
Berker Peksagce913872016-03-28 00:30:02 +0300330 self.assertTrue(call1 == call2)
331 self.assertFalse(call1 != call2)
Serhiy Storchaka362f0582017-01-21 23:12:58 +0200332 self.assertTrue(call2 == call1)
333 self.assertFalse(call2 != call1)
Berker Peksagce913872016-03-28 00:30:02 +0300334
335
Michael Foord345266a2012-03-14 12:24:34 -0700336 def test_assert_called_with(self):
337 mock = Mock()
338 mock()
339
340 # Will raise an exception if it fails
341 mock.assert_called_with()
342 self.assertRaises(AssertionError, mock.assert_called_with, 1)
343
344 mock.reset_mock()
345 self.assertRaises(AssertionError, mock.assert_called_with)
346
347 mock(1, 2, 3, a='fish', b='nothing')
348 mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
349
350
Berker Peksagce913872016-03-28 00:30:02 +0300351 def test_assert_called_with_any(self):
352 m = MagicMock()
353 m(MagicMock())
354 m.assert_called_with(mock.ANY)
355
356
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100357 def test_assert_called_with_function_spec(self):
358 def f(a, b, c, d=None):
359 pass
360
361 mock = Mock(spec=f)
362
363 mock(1, b=2, c=3)
364 mock.assert_called_with(1, 2, 3)
365 mock.assert_called_with(a=1, b=2, c=3)
366 self.assertRaises(AssertionError, mock.assert_called_with,
367 1, b=3, c=2)
368 # Expected call doesn't match the spec's signature
369 with self.assertRaises(AssertionError) as cm:
370 mock.assert_called_with(e=8)
371 self.assertIsInstance(cm.exception.__cause__, TypeError)
372
373
374 def test_assert_called_with_method_spec(self):
375 def _check(mock):
376 mock(1, b=2, c=3)
377 mock.assert_called_with(1, 2, 3)
378 mock.assert_called_with(a=1, b=2, c=3)
379 self.assertRaises(AssertionError, mock.assert_called_with,
380 1, b=3, c=2)
381
382 mock = Mock(spec=Something().meth)
383 _check(mock)
384 mock = Mock(spec=Something.cmeth)
385 _check(mock)
386 mock = Mock(spec=Something().cmeth)
387 _check(mock)
388 mock = Mock(spec=Something.smeth)
389 _check(mock)
390 mock = Mock(spec=Something().smeth)
391 _check(mock)
392
393
Michael Foord345266a2012-03-14 12:24:34 -0700394 def test_assert_called_once_with(self):
395 mock = Mock()
396 mock()
397
398 # Will raise an exception if it fails
399 mock.assert_called_once_with()
400
401 mock()
402 self.assertRaises(AssertionError, mock.assert_called_once_with)
403
404 mock.reset_mock()
405 self.assertRaises(AssertionError, mock.assert_called_once_with)
406
407 mock('foo', 'bar', baz=2)
408 mock.assert_called_once_with('foo', 'bar', baz=2)
409
410 mock.reset_mock()
411 mock('foo', 'bar', baz=2)
412 self.assertRaises(
413 AssertionError,
414 lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
415 )
416
Petter Strandmark47d94242018-10-28 21:37:10 +0100417 def test_assert_called_once_with_call_list(self):
418 m = Mock()
419 m(1)
420 m(2)
421 self.assertRaisesRegex(AssertionError,
422 re.escape("Calls: [call(1), call(2)]"),
423 lambda: m.assert_called_once_with(2))
424
Michael Foord345266a2012-03-14 12:24:34 -0700425
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100426 def test_assert_called_once_with_function_spec(self):
427 def f(a, b, c, d=None):
428 pass
429
430 mock = Mock(spec=f)
431
432 mock(1, b=2, c=3)
433 mock.assert_called_once_with(1, 2, 3)
434 mock.assert_called_once_with(a=1, b=2, c=3)
435 self.assertRaises(AssertionError, mock.assert_called_once_with,
436 1, b=3, c=2)
437 # Expected call doesn't match the spec's signature
438 with self.assertRaises(AssertionError) as cm:
439 mock.assert_called_once_with(e=8)
440 self.assertIsInstance(cm.exception.__cause__, TypeError)
441 # Mock called more than once => always fails
442 mock(4, 5, 6)
443 self.assertRaises(AssertionError, mock.assert_called_once_with,
444 1, 2, 3)
445 self.assertRaises(AssertionError, mock.assert_called_once_with,
446 4, 5, 6)
447
448
Michael Foord345266a2012-03-14 12:24:34 -0700449 def test_attribute_access_returns_mocks(self):
450 mock = Mock()
451 something = mock.something
452 self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
453 self.assertEqual(mock.something, something,
454 "different attributes returned for same name")
455
456 # Usage example
457 mock = Mock()
458 mock.something.return_value = 3
459
460 self.assertEqual(mock.something(), 3, "method returned wrong value")
461 self.assertTrue(mock.something.called,
462 "method didn't record being called")
463
464
465 def test_attributes_have_name_and_parent_set(self):
466 mock = Mock()
467 something = mock.something
468
469 self.assertEqual(something._mock_name, "something",
470 "attribute name not set correctly")
471 self.assertEqual(something._mock_parent, mock,
472 "attribute parent not set correctly")
473
474
475 def test_method_calls_recorded(self):
476 mock = Mock()
477 mock.something(3, fish=None)
478 mock.something_else.something(6, cake=sentinel.Cake)
479
480 self.assertEqual(mock.something_else.method_calls,
481 [("something", (6,), {'cake': sentinel.Cake})],
482 "method calls not recorded correctly")
483 self.assertEqual(mock.method_calls, [
484 ("something", (3,), {'fish': None}),
485 ("something_else.something", (6,), {'cake': sentinel.Cake})
486 ],
487 "method calls not recorded correctly")
488
489
490 def test_method_calls_compare_easily(self):
491 mock = Mock()
492 mock.something()
493 self.assertEqual(mock.method_calls, [('something',)])
494 self.assertEqual(mock.method_calls, [('something', (), {})])
495
496 mock = Mock()
497 mock.something('different')
498 self.assertEqual(mock.method_calls, [('something', ('different',))])
499 self.assertEqual(mock.method_calls,
500 [('something', ('different',), {})])
501
502 mock = Mock()
503 mock.something(x=1)
504 self.assertEqual(mock.method_calls, [('something', {'x': 1})])
505 self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
506
507 mock = Mock()
508 mock.something('different', some='more')
509 self.assertEqual(mock.method_calls, [
510 ('something', ('different',), {'some': 'more'})
511 ])
512
513
514 def test_only_allowed_methods_exist(self):
515 for spec in ['something'], ('something',):
516 for arg in 'spec', 'spec_set':
517 mock = Mock(**{arg: spec})
518
519 # this should be allowed
520 mock.something
521 self.assertRaisesRegex(
522 AttributeError,
523 "Mock object has no attribute 'something_else'",
524 getattr, mock, 'something_else'
525 )
526
527
528 def test_from_spec(self):
529 class Something(object):
530 x = 3
531 __something__ = None
532 def y(self):
533 pass
534
535 def test_attributes(mock):
536 # should work
537 mock.x
538 mock.y
539 mock.__something__
540 self.assertRaisesRegex(
541 AttributeError,
542 "Mock object has no attribute 'z'",
543 getattr, mock, 'z'
544 )
545 self.assertRaisesRegex(
546 AttributeError,
547 "Mock object has no attribute '__foobar__'",
548 getattr, mock, '__foobar__'
549 )
550
551 test_attributes(Mock(spec=Something))
552 test_attributes(Mock(spec=Something()))
553
554
555 def test_wraps_calls(self):
556 real = Mock()
557
558 mock = Mock(wraps=real)
559 self.assertEqual(mock(), real())
560
561 real.reset_mock()
562
563 mock(1, 2, fish=3)
564 real.assert_called_with(1, 2, fish=3)
565
566
Mario Corcherof05df0a2018-12-08 11:25:02 +0000567 def test_wraps_prevents_automatic_creation_of_mocks(self):
568 class Real(object):
569 pass
570
571 real = Real()
572 mock = Mock(wraps=real)
573
574 self.assertRaises(AttributeError, lambda: mock.new_attr())
575
576
Michael Foord345266a2012-03-14 12:24:34 -0700577 def test_wraps_call_with_nondefault_return_value(self):
578 real = Mock()
579
580 mock = Mock(wraps=real)
581 mock.return_value = 3
582
583 self.assertEqual(mock(), 3)
584 self.assertFalse(real.called)
585
586
587 def test_wraps_attributes(self):
588 class Real(object):
589 attribute = Mock()
590
591 real = Real()
592
593 mock = Mock(wraps=real)
594 self.assertEqual(mock.attribute(), real.attribute())
595 self.assertRaises(AttributeError, lambda: mock.fish)
596
597 self.assertNotEqual(mock.attribute, real.attribute)
598 result = mock.attribute.frog(1, 2, fish=3)
599 Real.attribute.frog.assert_called_with(1, 2, fish=3)
600 self.assertEqual(result, Real.attribute.frog())
601
602
Mario Corcherof05df0a2018-12-08 11:25:02 +0000603 def test_customize_wrapped_object_with_side_effect_iterable_with_default(self):
604 class Real(object):
605 def method(self):
606 return sentinel.ORIGINAL_VALUE
607
608 real = Real()
609 mock = Mock(wraps=real)
610 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
611
612 self.assertEqual(mock.method(), sentinel.VALUE1)
613 self.assertEqual(mock.method(), sentinel.ORIGINAL_VALUE)
614 self.assertRaises(StopIteration, mock.method)
615
616
617 def test_customize_wrapped_object_with_side_effect_iterable(self):
618 class Real(object):
619 def method(self):
620 raise NotImplementedError()
621
622 real = Real()
623 mock = Mock(wraps=real)
624 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
625
626 self.assertEqual(mock.method(), sentinel.VALUE1)
627 self.assertEqual(mock.method(), sentinel.VALUE2)
628 self.assertRaises(StopIteration, mock.method)
629
630
631 def test_customize_wrapped_object_with_side_effect_exception(self):
632 class Real(object):
633 def method(self):
634 raise NotImplementedError()
635
636 real = Real()
637 mock = Mock(wraps=real)
638 mock.method.side_effect = RuntimeError
639
640 self.assertRaises(RuntimeError, mock.method)
641
642
643 def test_customize_wrapped_object_with_side_effect_function(self):
644 class Real(object):
645 def method(self):
646 raise NotImplementedError()
647
648 def side_effect():
649 return sentinel.VALUE
650
651 real = Real()
652 mock = Mock(wraps=real)
653 mock.method.side_effect = side_effect
654
655 self.assertEqual(mock.method(), sentinel.VALUE)
656
657
658 def test_customize_wrapped_object_with_return_value(self):
659 class Real(object):
660 def method(self):
661 raise NotImplementedError()
662
663 real = Real()
664 mock = Mock(wraps=real)
665 mock.method.return_value = sentinel.VALUE
666
667 self.assertEqual(mock.method(), sentinel.VALUE)
668
669
670 def test_customize_wrapped_object_with_return_value_and_side_effect(self):
671 # side_effect should always take precedence over return_value.
672 class Real(object):
673 def method(self):
674 raise NotImplementedError()
675
676 real = Real()
677 mock = Mock(wraps=real)
678 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
679 mock.method.return_value = sentinel.WRONG_VALUE
680
681 self.assertEqual(mock.method(), sentinel.VALUE1)
682 self.assertEqual(mock.method(), sentinel.VALUE2)
683 self.assertRaises(StopIteration, mock.method)
684
685
686 def test_customize_wrapped_object_with_return_value_and_side_effect2(self):
687 # side_effect can return DEFAULT to default to return_value
688 class Real(object):
689 def method(self):
690 raise NotImplementedError()
691
692 real = Real()
693 mock = Mock(wraps=real)
694 mock.method.side_effect = lambda: DEFAULT
695 mock.method.return_value = sentinel.VALUE
696
697 self.assertEqual(mock.method(), sentinel.VALUE)
698
699
700 def test_customize_wrapped_object_with_return_value_and_side_effect_default(self):
701 class Real(object):
702 def method(self):
703 raise NotImplementedError()
704
705 real = Real()
706 mock = Mock(wraps=real)
707 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
708 mock.method.return_value = sentinel.RETURN
709
710 self.assertEqual(mock.method(), sentinel.VALUE1)
711 self.assertEqual(mock.method(), sentinel.RETURN)
712 self.assertRaises(StopIteration, mock.method)
713
714
Michael Foord345266a2012-03-14 12:24:34 -0700715 def test_exceptional_side_effect(self):
716 mock = Mock(side_effect=AttributeError)
717 self.assertRaises(AttributeError, mock)
718
719 mock = Mock(side_effect=AttributeError('foo'))
720 self.assertRaises(AttributeError, mock)
721
722
723 def test_baseexceptional_side_effect(self):
724 mock = Mock(side_effect=KeyboardInterrupt)
725 self.assertRaises(KeyboardInterrupt, mock)
726
727 mock = Mock(side_effect=KeyboardInterrupt('foo'))
728 self.assertRaises(KeyboardInterrupt, mock)
729
730
731 def test_assert_called_with_message(self):
732 mock = Mock()
Susan Su2bdd5852019-02-13 18:22:29 -0800733 self.assertRaisesRegex(AssertionError, 'not called',
Michael Foord345266a2012-03-14 12:24:34 -0700734 mock.assert_called_with)
735
736
Michael Foord28d591c2012-09-28 16:15:22 +0100737 def test_assert_called_once_with_message(self):
738 mock = Mock(name='geoffrey')
739 self.assertRaisesRegex(AssertionError,
740 r"Expected 'geoffrey' to be called once\.",
741 mock.assert_called_once_with)
742
743
Michael Foord345266a2012-03-14 12:24:34 -0700744 def test__name__(self):
745 mock = Mock()
746 self.assertRaises(AttributeError, lambda: mock.__name__)
747
748 mock.__name__ = 'foo'
749 self.assertEqual(mock.__name__, 'foo')
750
751
752 def test_spec_list_subclass(self):
753 class Sub(list):
754 pass
755 mock = Mock(spec=Sub(['foo']))
756
757 mock.append(3)
758 mock.append.assert_called_with(3)
759 self.assertRaises(AttributeError, getattr, mock, 'foo')
760
761
762 def test_spec_class(self):
763 class X(object):
764 pass
765
766 mock = Mock(spec=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200767 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700768
769 mock = Mock(spec=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200770 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700771
772 self.assertIs(mock.__class__, X)
773 self.assertEqual(Mock().__class__.__name__, 'Mock')
774
775 mock = Mock(spec_set=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200776 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700777
778 mock = Mock(spec_set=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200779 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700780
781
782 def test_setting_attribute_with_spec_set(self):
783 class X(object):
784 y = 3
785
786 mock = Mock(spec=X)
787 mock.x = 'foo'
788
789 mock = Mock(spec_set=X)
790 def set_attr():
791 mock.x = 'foo'
792
793 mock.y = 'foo'
794 self.assertRaises(AttributeError, set_attr)
795
796
797 def test_copy(self):
798 current = sys.getrecursionlimit()
799 self.addCleanup(sys.setrecursionlimit, current)
800
801 # can't use sys.maxint as this doesn't exist in Python 3
802 sys.setrecursionlimit(int(10e8))
803 # this segfaults without the fix in place
804 copy.copy(Mock())
805
806
807 def test_subclass_with_properties(self):
808 class SubClass(Mock):
809 def _get(self):
810 return 3
811 def _set(self, value):
812 raise NameError('strange error')
813 some_attribute = property(_get, _set)
814
815 s = SubClass(spec_set=SubClass)
816 self.assertEqual(s.some_attribute, 3)
817
818 def test():
819 s.some_attribute = 3
820 self.assertRaises(NameError, test)
821
822 def test():
823 s.foo = 'bar'
824 self.assertRaises(AttributeError, test)
825
826
827 def test_setting_call(self):
828 mock = Mock()
829 def __call__(self, a):
830 return self._mock_call(a)
831
832 type(mock).__call__ = __call__
833 mock('one')
834 mock.assert_called_with('one')
835
836 self.assertRaises(TypeError, mock, 'one', 'two')
837
838
839 def test_dir(self):
840 mock = Mock()
841 attrs = set(dir(mock))
842 type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
843
844 # all public attributes from the type are included
845 self.assertEqual(set(), type_attrs - attrs)
846
847 # creates these attributes
848 mock.a, mock.b
849 self.assertIn('a', dir(mock))
850 self.assertIn('b', dir(mock))
851
852 # instance attributes
853 mock.c = mock.d = None
854 self.assertIn('c', dir(mock))
855 self.assertIn('d', dir(mock))
856
857 # magic methods
858 mock.__iter__ = lambda s: iter([])
859 self.assertIn('__iter__', dir(mock))
860
861
862 def test_dir_from_spec(self):
863 mock = Mock(spec=unittest.TestCase)
864 testcase_attrs = set(dir(unittest.TestCase))
865 attrs = set(dir(mock))
866
867 # all attributes from the spec are included
868 self.assertEqual(set(), testcase_attrs - attrs)
869
870 # shadow a sys attribute
871 mock.version = 3
872 self.assertEqual(dir(mock).count('version'), 1)
873
874
875 def test_filter_dir(self):
876 patcher = patch.object(mock, 'FILTER_DIR', False)
877 patcher.start()
878 try:
879 attrs = set(dir(Mock()))
880 type_attrs = set(dir(Mock))
881
882 # ALL attributes from the type are included
883 self.assertEqual(set(), type_attrs - attrs)
884 finally:
885 patcher.stop()
886
887
888 def test_configure_mock(self):
889 mock = Mock(foo='bar')
890 self.assertEqual(mock.foo, 'bar')
891
892 mock = MagicMock(foo='bar')
893 self.assertEqual(mock.foo, 'bar')
894
895 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
896 'foo': MagicMock()}
897 mock = Mock(**kwargs)
898 self.assertRaises(KeyError, mock)
899 self.assertEqual(mock.foo.bar(), 33)
900 self.assertIsInstance(mock.foo, MagicMock)
901
902 mock = Mock()
903 mock.configure_mock(**kwargs)
904 self.assertRaises(KeyError, mock)
905 self.assertEqual(mock.foo.bar(), 33)
906 self.assertIsInstance(mock.foo, MagicMock)
907
908
909 def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
910 # needed because assertRaisesRegex doesn't work easily with newlines
911 try:
912 func(*args, **kwargs)
913 except:
914 instance = sys.exc_info()[1]
915 self.assertIsInstance(instance, exception)
916 else:
917 self.fail('Exception %r not raised' % (exception,))
918
919 msg = str(instance)
920 self.assertEqual(msg, message)
921
922
923 def test_assert_called_with_failure_message(self):
924 mock = NonCallableMock()
925
Susan Su2bdd5852019-02-13 18:22:29 -0800926 actual = 'not called.'
Michael Foord345266a2012-03-14 12:24:34 -0700927 expected = "mock(1, '2', 3, bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -0800928 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700929 self.assertRaisesWithMsg(
Susan Su2bdd5852019-02-13 18:22:29 -0800930 AssertionError, message % (expected, actual),
Michael Foord345266a2012-03-14 12:24:34 -0700931 mock.assert_called_with, 1, '2', 3, bar='foo'
932 )
933
934 mock.foo(1, '2', 3, foo='foo')
935
936
937 asserters = [
938 mock.foo.assert_called_with, mock.foo.assert_called_once_with
939 ]
940 for meth in asserters:
941 actual = "foo(1, '2', 3, foo='foo')"
942 expected = "foo(1, '2', 3, bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -0800943 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700944 self.assertRaisesWithMsg(
945 AssertionError, message % (expected, actual),
946 meth, 1, '2', 3, bar='foo'
947 )
948
949 # just kwargs
950 for meth in asserters:
951 actual = "foo(1, '2', 3, foo='foo')"
952 expected = "foo(bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -0800953 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700954 self.assertRaisesWithMsg(
955 AssertionError, message % (expected, actual),
956 meth, bar='foo'
957 )
958
959 # just args
960 for meth in asserters:
961 actual = "foo(1, '2', 3, foo='foo')"
962 expected = "foo(1, 2, 3)"
Susan Su2bdd5852019-02-13 18:22:29 -0800963 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700964 self.assertRaisesWithMsg(
965 AssertionError, message % (expected, actual),
966 meth, 1, 2, 3
967 )
968
969 # empty
970 for meth in asserters:
971 actual = "foo(1, '2', 3, foo='foo')"
972 expected = "foo()"
Susan Su2bdd5852019-02-13 18:22:29 -0800973 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700974 self.assertRaisesWithMsg(
975 AssertionError, message % (expected, actual), meth
976 )
977
978
979 def test_mock_calls(self):
980 mock = MagicMock()
981
982 # need to do this because MagicMock.mock_calls used to just return
983 # a MagicMock which also returned a MagicMock when __eq__ was called
984 self.assertIs(mock.mock_calls == [], True)
985
986 mock = MagicMock()
987 mock()
988 expected = [('', (), {})]
989 self.assertEqual(mock.mock_calls, expected)
990
991 mock.foo()
992 expected.append(call.foo())
993 self.assertEqual(mock.mock_calls, expected)
994 # intermediate mock_calls work too
995 self.assertEqual(mock.foo.mock_calls, [('', (), {})])
996
997 mock = MagicMock()
998 mock().foo(1, 2, 3, a=4, b=5)
999 expected = [
1000 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
1001 ]
1002 self.assertEqual(mock.mock_calls, expected)
1003 self.assertEqual(mock.return_value.foo.mock_calls,
1004 [('', (1, 2, 3), dict(a=4, b=5))])
1005 self.assertEqual(mock.return_value.mock_calls,
1006 [('foo', (1, 2, 3), dict(a=4, b=5))])
1007
1008 mock = MagicMock()
1009 mock().foo.bar().baz()
1010 expected = [
1011 ('', (), {}), ('().foo.bar', (), {}),
1012 ('().foo.bar().baz', (), {})
1013 ]
1014 self.assertEqual(mock.mock_calls, expected)
1015 self.assertEqual(mock().mock_calls,
1016 call.foo.bar().baz().call_list())
1017
1018 for kwargs in dict(), dict(name='bar'):
1019 mock = MagicMock(**kwargs)
1020 int(mock.foo)
1021 expected = [('foo.__int__', (), {})]
1022 self.assertEqual(mock.mock_calls, expected)
1023
1024 mock = MagicMock(**kwargs)
1025 mock.a()()
1026 expected = [('a', (), {}), ('a()', (), {})]
1027 self.assertEqual(mock.mock_calls, expected)
1028 self.assertEqual(mock.a().mock_calls, [call()])
1029
1030 mock = MagicMock(**kwargs)
1031 mock(1)(2)(3)
1032 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
1033 self.assertEqual(mock().mock_calls, call(2)(3).call_list())
1034 self.assertEqual(mock()().mock_calls, call(3).call_list())
1035
1036 mock = MagicMock(**kwargs)
1037 mock(1)(2)(3).a.b.c(4)
1038 self.assertEqual(mock.mock_calls,
1039 call(1)(2)(3).a.b.c(4).call_list())
1040 self.assertEqual(mock().mock_calls,
1041 call(2)(3).a.b.c(4).call_list())
1042 self.assertEqual(mock()().mock_calls,
1043 call(3).a.b.c(4).call_list())
1044
1045 mock = MagicMock(**kwargs)
1046 int(mock().foo.bar().baz())
1047 last_call = ('().foo.bar().baz().__int__', (), {})
1048 self.assertEqual(mock.mock_calls[-1], last_call)
1049 self.assertEqual(mock().mock_calls,
1050 call.foo.bar().baz().__int__().call_list())
1051 self.assertEqual(mock().foo.bar().mock_calls,
1052 call.baz().__int__().call_list())
1053 self.assertEqual(mock().foo.bar().baz.mock_calls,
1054 call().__int__().call_list())
1055
1056
Chris Withers8ca0fa92018-12-03 21:31:37 +00001057 def test_child_mock_call_equal(self):
1058 m = Mock()
1059 result = m()
1060 result.wibble()
1061 # parent looks like this:
1062 self.assertEqual(m.mock_calls, [call(), call().wibble()])
1063 # but child should look like this:
1064 self.assertEqual(result.mock_calls, [call.wibble()])
1065
1066
1067 def test_mock_call_not_equal_leaf(self):
1068 m = Mock()
1069 m.foo().something()
1070 self.assertNotEqual(m.mock_calls[1], call.foo().different())
1071 self.assertEqual(m.mock_calls[0], call.foo())
1072
1073
1074 def test_mock_call_not_equal_non_leaf(self):
1075 m = Mock()
1076 m.foo().bar()
1077 self.assertNotEqual(m.mock_calls[1], call.baz().bar())
1078 self.assertNotEqual(m.mock_calls[0], call.baz())
1079
1080
1081 def test_mock_call_not_equal_non_leaf_params_different(self):
1082 m = Mock()
1083 m.foo(x=1).bar()
1084 # This isn't ideal, but there's no way to fix it without breaking backwards compatibility:
1085 self.assertEqual(m.mock_calls[1], call.foo(x=2).bar())
1086
1087
1088 def test_mock_call_not_equal_non_leaf_attr(self):
1089 m = Mock()
1090 m.foo.bar()
1091 self.assertNotEqual(m.mock_calls[0], call.baz.bar())
1092
1093
1094 def test_mock_call_not_equal_non_leaf_call_versus_attr(self):
1095 m = Mock()
1096 m.foo.bar()
1097 self.assertNotEqual(m.mock_calls[0], call.foo().bar())
1098
1099
1100 def test_mock_call_repr(self):
1101 m = Mock()
1102 m.foo().bar().baz.bob()
1103 self.assertEqual(repr(m.mock_calls[0]), 'call.foo()')
1104 self.assertEqual(repr(m.mock_calls[1]), 'call.foo().bar()')
1105 self.assertEqual(repr(m.mock_calls[2]), 'call.foo().bar().baz.bob()')
1106
1107
Michael Foord345266a2012-03-14 12:24:34 -07001108 def test_subclassing(self):
1109 class Subclass(Mock):
1110 pass
1111
1112 mock = Subclass()
1113 self.assertIsInstance(mock.foo, Subclass)
1114 self.assertIsInstance(mock(), Subclass)
1115
1116 class Subclass(Mock):
1117 def _get_child_mock(self, **kwargs):
1118 return Mock(**kwargs)
1119
1120 mock = Subclass()
1121 self.assertNotIsInstance(mock.foo, Subclass)
1122 self.assertNotIsInstance(mock(), Subclass)
1123
1124
1125 def test_arg_lists(self):
1126 mocks = [
1127 Mock(),
1128 MagicMock(),
1129 NonCallableMock(),
1130 NonCallableMagicMock()
1131 ]
1132
1133 def assert_attrs(mock):
1134 names = 'call_args_list', 'method_calls', 'mock_calls'
1135 for name in names:
1136 attr = getattr(mock, name)
1137 self.assertIsInstance(attr, _CallList)
1138 self.assertIsInstance(attr, list)
1139 self.assertEqual(attr, [])
1140
1141 for mock in mocks:
1142 assert_attrs(mock)
1143
1144 if callable(mock):
1145 mock()
1146 mock(1, 2)
1147 mock(a=3)
1148
1149 mock.reset_mock()
1150 assert_attrs(mock)
1151
1152 mock.foo()
1153 mock.foo.bar(1, a=3)
1154 mock.foo(1).bar().baz(3)
1155
1156 mock.reset_mock()
1157 assert_attrs(mock)
1158
1159
1160 def test_call_args_two_tuple(self):
1161 mock = Mock()
1162 mock(1, a=3)
1163 mock(2, b=4)
1164
1165 self.assertEqual(len(mock.call_args), 2)
Kumar Akshayb0df45e2019-03-22 13:40:40 +05301166 self.assertEqual(mock.call_args.args, (2,))
1167 self.assertEqual(mock.call_args.kwargs, dict(b=4))
Michael Foord345266a2012-03-14 12:24:34 -07001168
1169 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
1170 for expected, call_args in zip(expected_list, mock.call_args_list):
1171 self.assertEqual(len(call_args), 2)
1172 self.assertEqual(expected[0], call_args[0])
1173 self.assertEqual(expected[1], call_args[1])
1174
1175
1176 def test_side_effect_iterator(self):
1177 mock = Mock(side_effect=iter([1, 2, 3]))
1178 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1179 self.assertRaises(StopIteration, mock)
1180
1181 mock = MagicMock(side_effect=['a', 'b', 'c'])
1182 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1183 self.assertRaises(StopIteration, mock)
1184
1185 mock = Mock(side_effect='ghi')
1186 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
1187 self.assertRaises(StopIteration, mock)
1188
1189 class Foo(object):
1190 pass
1191 mock = MagicMock(side_effect=Foo)
1192 self.assertIsInstance(mock(), Foo)
1193
1194 mock = Mock(side_effect=Iter())
1195 self.assertEqual([mock(), mock(), mock(), mock()],
1196 ['this', 'is', 'an', 'iter'])
1197 self.assertRaises(StopIteration, mock)
1198
1199
Michael Foord2cd48732012-04-21 15:52:11 +01001200 def test_side_effect_iterator_exceptions(self):
1201 for Klass in Mock, MagicMock:
1202 iterable = (ValueError, 3, KeyError, 6)
1203 m = Klass(side_effect=iterable)
1204 self.assertRaises(ValueError, m)
1205 self.assertEqual(m(), 3)
1206 self.assertRaises(KeyError, m)
1207 self.assertEqual(m(), 6)
1208
1209
Michael Foord345266a2012-03-14 12:24:34 -07001210 def test_side_effect_setting_iterator(self):
1211 mock = Mock()
1212 mock.side_effect = iter([1, 2, 3])
1213 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1214 self.assertRaises(StopIteration, mock)
1215 side_effect = mock.side_effect
1216 self.assertIsInstance(side_effect, type(iter([])))
1217
1218 mock.side_effect = ['a', 'b', 'c']
1219 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1220 self.assertRaises(StopIteration, mock)
1221 side_effect = mock.side_effect
1222 self.assertIsInstance(side_effect, type(iter([])))
1223
1224 this_iter = Iter()
1225 mock.side_effect = this_iter
1226 self.assertEqual([mock(), mock(), mock(), mock()],
1227 ['this', 'is', 'an', 'iter'])
1228 self.assertRaises(StopIteration, mock)
1229 self.assertIs(mock.side_effect, this_iter)
1230
Andrew Svetlov8b2cd752013-04-07 16:42:24 +03001231 def test_side_effect_iterator_default(self):
1232 mock = Mock(return_value=2)
1233 mock.side_effect = iter([1, DEFAULT])
1234 self.assertEqual([mock(), mock()], [1, 2])
Michael Foord345266a2012-03-14 12:24:34 -07001235
1236 def test_assert_has_calls_any_order(self):
1237 mock = Mock()
1238 mock(1, 2)
1239 mock(a=3)
1240 mock(3, 4)
1241 mock(b=6)
1242 mock(b=6)
1243
1244 kalls = [
1245 call(1, 2), ({'a': 3},),
1246 ((3, 4),), ((), {'a': 3}),
1247 ('', (1, 2)), ('', {'a': 3}),
1248 ('', (1, 2), {}), ('', (), {'a': 3})
1249 ]
1250 for kall in kalls:
1251 mock.assert_has_calls([kall], any_order=True)
1252
1253 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
1254 self.assertRaises(
1255 AssertionError, mock.assert_has_calls,
1256 [kall], any_order=True
1257 )
1258
1259 kall_lists = [
1260 [call(1, 2), call(b=6)],
1261 [call(3, 4), call(1, 2)],
1262 [call(b=6), call(b=6)],
1263 ]
1264
1265 for kall_list in kall_lists:
1266 mock.assert_has_calls(kall_list, any_order=True)
1267
1268 kall_lists = [
1269 [call(b=6), call(b=6), call(b=6)],
1270 [call(1, 2), call(1, 2)],
1271 [call(3, 4), call(1, 2), call(5, 7)],
1272 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
1273 ]
1274 for kall_list in kall_lists:
1275 self.assertRaises(
1276 AssertionError, mock.assert_has_calls,
1277 kall_list, any_order=True
1278 )
1279
1280 def test_assert_has_calls(self):
1281 kalls1 = [
1282 call(1, 2), ({'a': 3},),
1283 ((3, 4),), call(b=6),
1284 ('', (1,), {'b': 6}),
1285 ]
1286 kalls2 = [call.foo(), call.bar(1)]
1287 kalls2.extend(call.spam().baz(a=3).call_list())
1288 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
1289
1290 mocks = []
1291 for mock in Mock(), MagicMock():
1292 mock(1, 2)
1293 mock(a=3)
1294 mock(3, 4)
1295 mock(b=6)
1296 mock(1, b=6)
1297 mocks.append((mock, kalls1))
1298
1299 mock = Mock()
1300 mock.foo()
1301 mock.bar(1)
1302 mock.spam().baz(a=3)
1303 mock.bam(set(), foo={}).fish([1])
1304 mocks.append((mock, kalls2))
1305
1306 for mock, kalls in mocks:
1307 for i in range(len(kalls)):
1308 for step in 1, 2, 3:
1309 these = kalls[i:i+step]
1310 mock.assert_has_calls(these)
1311
1312 if len(these) > 1:
1313 self.assertRaises(
1314 AssertionError,
1315 mock.assert_has_calls,
1316 list(reversed(these))
1317 )
1318
1319
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001320 def test_assert_has_calls_with_function_spec(self):
1321 def f(a, b, c, d=None):
1322 pass
1323
1324 mock = Mock(spec=f)
1325
1326 mock(1, b=2, c=3)
1327 mock(4, 5, c=6, d=7)
1328 mock(10, 11, c=12)
1329 calls = [
1330 ('', (1, 2, 3), {}),
1331 ('', (4, 5, 6), {'d': 7}),
1332 ((10, 11, 12), {}),
1333 ]
1334 mock.assert_has_calls(calls)
1335 mock.assert_has_calls(calls, any_order=True)
1336 mock.assert_has_calls(calls[1:])
1337 mock.assert_has_calls(calls[1:], any_order=True)
1338 mock.assert_has_calls(calls[:-1])
1339 mock.assert_has_calls(calls[:-1], any_order=True)
1340 # Reversed order
1341 calls = list(reversed(calls))
1342 with self.assertRaises(AssertionError):
1343 mock.assert_has_calls(calls)
1344 mock.assert_has_calls(calls, any_order=True)
1345 with self.assertRaises(AssertionError):
1346 mock.assert_has_calls(calls[1:])
1347 mock.assert_has_calls(calls[1:], any_order=True)
1348 with self.assertRaises(AssertionError):
1349 mock.assert_has_calls(calls[:-1])
1350 mock.assert_has_calls(calls[:-1], any_order=True)
1351
1352
Michael Foord345266a2012-03-14 12:24:34 -07001353 def test_assert_any_call(self):
1354 mock = Mock()
1355 mock(1, 2)
1356 mock(a=3)
1357 mock(1, b=6)
1358
1359 mock.assert_any_call(1, 2)
1360 mock.assert_any_call(a=3)
1361 mock.assert_any_call(1, b=6)
1362
1363 self.assertRaises(
1364 AssertionError,
1365 mock.assert_any_call
1366 )
1367 self.assertRaises(
1368 AssertionError,
1369 mock.assert_any_call,
1370 1, 3
1371 )
1372 self.assertRaises(
1373 AssertionError,
1374 mock.assert_any_call,
1375 a=4
1376 )
1377
1378
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001379 def test_assert_any_call_with_function_spec(self):
1380 def f(a, b, c, d=None):
1381 pass
1382
1383 mock = Mock(spec=f)
1384
1385 mock(1, b=2, c=3)
1386 mock(4, 5, c=6, d=7)
1387 mock.assert_any_call(1, 2, 3)
1388 mock.assert_any_call(a=1, b=2, c=3)
1389 mock.assert_any_call(4, 5, 6, 7)
1390 mock.assert_any_call(a=4, b=5, c=6, d=7)
1391 self.assertRaises(AssertionError, mock.assert_any_call,
1392 1, b=3, c=2)
1393 # Expected call doesn't match the spec's signature
1394 with self.assertRaises(AssertionError) as cm:
1395 mock.assert_any_call(e=8)
1396 self.assertIsInstance(cm.exception.__cause__, TypeError)
1397
1398
Michael Foord345266a2012-03-14 12:24:34 -07001399 def test_mock_calls_create_autospec(self):
1400 def f(a, b):
1401 pass
1402 obj = Iter()
1403 obj.f = f
1404
1405 funcs = [
1406 create_autospec(f),
1407 create_autospec(obj).f
1408 ]
1409 for func in funcs:
1410 func(1, 2)
1411 func(3, 4)
1412
1413 self.assertEqual(
1414 func.mock_calls, [call(1, 2), call(3, 4)]
1415 )
1416
Kushal Das484f8a82014-04-16 01:05:50 +05301417 #Issue21222
1418 def test_create_autospec_with_name(self):
1419 m = mock.create_autospec(object(), name='sweet_func')
1420 self.assertIn('sweet_func', repr(m))
Michael Foord345266a2012-03-14 12:24:34 -07001421
Kushal Das8c145342014-04-16 23:32:21 +05301422 #Issue21238
1423 def test_mock_unsafe(self):
1424 m = Mock()
1425 with self.assertRaises(AttributeError):
1426 m.assert_foo_call()
1427 with self.assertRaises(AttributeError):
1428 m.assret_foo_call()
1429 m = Mock(unsafe=True)
1430 m.assert_foo_call()
1431 m.assret_foo_call()
1432
Kushal Das8af9db32014-04-17 01:36:14 +05301433 #Issue21262
1434 def test_assert_not_called(self):
1435 m = Mock()
1436 m.hello.assert_not_called()
1437 m.hello()
1438 with self.assertRaises(AssertionError):
1439 m.hello.assert_not_called()
1440
Petter Strandmark47d94242018-10-28 21:37:10 +01001441 def test_assert_not_called_message(self):
1442 m = Mock()
1443 m(1, 2)
1444 self.assertRaisesRegex(AssertionError,
1445 re.escape("Calls: [call(1, 2)]"),
1446 m.assert_not_called)
1447
Victor Stinner2c2a4e62016-03-11 22:17:48 +01001448 def test_assert_called(self):
1449 m = Mock()
1450 with self.assertRaises(AssertionError):
1451 m.hello.assert_called()
1452 m.hello()
1453 m.hello.assert_called()
1454
1455 m.hello()
1456 m.hello.assert_called()
1457
1458 def test_assert_called_once(self):
1459 m = Mock()
1460 with self.assertRaises(AssertionError):
1461 m.hello.assert_called_once()
1462 m.hello()
1463 m.hello.assert_called_once()
1464
1465 m.hello()
1466 with self.assertRaises(AssertionError):
1467 m.hello.assert_called_once()
1468
Petter Strandmark47d94242018-10-28 21:37:10 +01001469 def test_assert_called_once_message(self):
1470 m = Mock()
1471 m(1, 2)
1472 m(3)
1473 self.assertRaisesRegex(AssertionError,
1474 re.escape("Calls: [call(1, 2), call(3)]"),
1475 m.assert_called_once)
1476
1477 def test_assert_called_once_message_not_called(self):
1478 m = Mock()
1479 with self.assertRaises(AssertionError) as e:
1480 m.assert_called_once()
1481 self.assertNotIn("Calls:", str(e.exception))
1482
Kushal Das047f14c2014-06-09 13:45:56 +05301483 #Issue21256 printout of keyword args should be in deterministic order
1484 def test_sorted_call_signature(self):
1485 m = Mock()
1486 m.hello(name='hello', daddy='hero')
1487 text = "call(daddy='hero', name='hello')"
R David Murray130a5662014-06-11 17:09:43 -04001488 self.assertEqual(repr(m.hello.call_args), text)
Kushal Das8af9db32014-04-17 01:36:14 +05301489
Kushal Dasa37b9582014-09-16 18:33:37 +05301490 #Issue21270 overrides tuple methods for mock.call objects
1491 def test_override_tuple_methods(self):
1492 c = call.count()
1493 i = call.index(132,'hello')
1494 m = Mock()
1495 m.count()
1496 m.index(132,"hello")
1497 self.assertEqual(m.method_calls[0], c)
1498 self.assertEqual(m.method_calls[1], i)
1499
Kushal Das9cd39a12016-06-02 10:20:16 -07001500 def test_reset_return_sideeffect(self):
1501 m = Mock(return_value=10, side_effect=[2,3])
1502 m.reset_mock(return_value=True, side_effect=True)
1503 self.assertIsInstance(m.return_value, Mock)
1504 self.assertEqual(m.side_effect, None)
1505
1506 def test_reset_return(self):
1507 m = Mock(return_value=10, side_effect=[2,3])
1508 m.reset_mock(return_value=True)
1509 self.assertIsInstance(m.return_value, Mock)
1510 self.assertNotEqual(m.side_effect, None)
1511
1512 def test_reset_sideeffect(self):
1513 m = Mock(return_value=10, side_effect=[2,3])
1514 m.reset_mock(side_effect=True)
1515 self.assertEqual(m.return_value, 10)
1516 self.assertEqual(m.side_effect, None)
1517
Michael Foord345266a2012-03-14 12:24:34 -07001518 def test_mock_add_spec(self):
1519 class _One(object):
1520 one = 1
1521 class _Two(object):
1522 two = 2
1523 class Anything(object):
1524 one = two = three = 'four'
1525
1526 klasses = [
1527 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1528 ]
1529 for Klass in list(klasses):
1530 klasses.append(lambda K=Klass: K(spec=Anything))
1531 klasses.append(lambda K=Klass: K(spec_set=Anything))
1532
1533 for Klass in klasses:
1534 for kwargs in dict(), dict(spec_set=True):
1535 mock = Klass()
1536 #no error
1537 mock.one, mock.two, mock.three
1538
1539 for One, Two in [(_One, _Two), (['one'], ['two'])]:
1540 for kwargs in dict(), dict(spec_set=True):
1541 mock.mock_add_spec(One, **kwargs)
1542
1543 mock.one
1544 self.assertRaises(
1545 AttributeError, getattr, mock, 'two'
1546 )
1547 self.assertRaises(
1548 AttributeError, getattr, mock, 'three'
1549 )
1550 if 'spec_set' in kwargs:
1551 self.assertRaises(
1552 AttributeError, setattr, mock, 'three', None
1553 )
1554
1555 mock.mock_add_spec(Two, **kwargs)
1556 self.assertRaises(
1557 AttributeError, getattr, mock, 'one'
1558 )
1559 mock.two
1560 self.assertRaises(
1561 AttributeError, getattr, mock, 'three'
1562 )
1563 if 'spec_set' in kwargs:
1564 self.assertRaises(
1565 AttributeError, setattr, mock, 'three', None
1566 )
1567 # note that creating a mock, setting an instance attribute, and
1568 # *then* setting a spec doesn't work. Not the intended use case
1569
1570
1571 def test_mock_add_spec_magic_methods(self):
1572 for Klass in MagicMock, NonCallableMagicMock:
1573 mock = Klass()
1574 int(mock)
1575
1576 mock.mock_add_spec(object)
1577 self.assertRaises(TypeError, int, mock)
1578
1579 mock = Klass()
1580 mock['foo']
1581 mock.__int__.return_value =4
1582
1583 mock.mock_add_spec(int)
1584 self.assertEqual(int(mock), 4)
1585 self.assertRaises(TypeError, lambda: mock['foo'])
1586
1587
1588 def test_adding_child_mock(self):
1589 for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock:
1590 mock = Klass()
1591
1592 mock.foo = Mock()
1593 mock.foo()
1594
1595 self.assertEqual(mock.method_calls, [call.foo()])
1596 self.assertEqual(mock.mock_calls, [call.foo()])
1597
1598 mock = Klass()
1599 mock.bar = Mock(name='name')
1600 mock.bar()
1601 self.assertEqual(mock.method_calls, [])
1602 self.assertEqual(mock.mock_calls, [])
1603
1604 # mock with an existing _new_parent but no name
1605 mock = Klass()
1606 mock.baz = MagicMock()()
1607 mock.baz()
1608 self.assertEqual(mock.method_calls, [])
1609 self.assertEqual(mock.mock_calls, [])
1610
1611
1612 def test_adding_return_value_mock(self):
1613 for Klass in Mock, MagicMock:
1614 mock = Klass()
1615 mock.return_value = MagicMock()
1616
1617 mock()()
1618 self.assertEqual(mock.mock_calls, [call(), call()()])
1619
1620
1621 def test_manager_mock(self):
1622 class Foo(object):
1623 one = 'one'
1624 two = 'two'
1625 manager = Mock()
1626 p1 = patch.object(Foo, 'one')
1627 p2 = patch.object(Foo, 'two')
1628
1629 mock_one = p1.start()
1630 self.addCleanup(p1.stop)
1631 mock_two = p2.start()
1632 self.addCleanup(p2.stop)
1633
1634 manager.attach_mock(mock_one, 'one')
1635 manager.attach_mock(mock_two, 'two')
1636
1637 Foo.two()
1638 Foo.one()
1639
1640 self.assertEqual(manager.mock_calls, [call.two(), call.one()])
1641
1642
1643 def test_magic_methods_mock_calls(self):
1644 for Klass in Mock, MagicMock:
1645 m = Klass()
1646 m.__int__ = Mock(return_value=3)
1647 m.__float__ = MagicMock(return_value=3.0)
1648 int(m)
1649 float(m)
1650
1651 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
1652 self.assertEqual(m.method_calls, [])
1653
Robert Collins5329aaa2015-07-17 20:08:45 +12001654 def test_mock_open_reuse_issue_21750(self):
1655 mocked_open = mock.mock_open(read_data='data')
1656 f1 = mocked_open('a-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001657 f1_data = f1.read()
Robert Collins5329aaa2015-07-17 20:08:45 +12001658 f2 = mocked_open('another-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001659 f2_data = f2.read()
1660 self.assertEqual(f1_data, f2_data)
1661
Tony Flury20870232018-09-12 23:21:16 +01001662 def test_mock_open_dunder_iter_issue(self):
1663 # Test dunder_iter method generates the expected result and
1664 # consumes the iterator.
1665 mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue')
1666 f1 = mocked_open('a-name')
1667 lines = [line for line in f1]
1668 self.assertEqual(lines[0], 'Remarkable\n')
1669 self.assertEqual(lines[1], 'Norwegian Blue')
1670 self.assertEqual(list(f1), [])
1671
Robert Collinsca647ef2015-07-24 03:48:20 +12001672 def test_mock_open_write(self):
1673 # Test exception in file writing write()
1674 mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
1675 with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
1676 mock_filehandle = mock_namedtemp.return_value
1677 mock_write = mock_filehandle.write
1678 mock_write.side_effect = OSError('Test 2 Error')
1679 def attempt():
1680 tempfile.NamedTemporaryFile().write('asd')
1681 self.assertRaises(OSError, attempt)
1682
1683 def test_mock_open_alter_readline(self):
1684 mopen = mock.mock_open(read_data='foo\nbarn')
1685 mopen.return_value.readline.side_effect = lambda *args:'abc'
1686 first = mopen().readline()
1687 second = mopen().readline()
1688 self.assertEqual('abc', first)
1689 self.assertEqual('abc', second)
Michael Foord345266a2012-03-14 12:24:34 -07001690
Robert Collins9549a3e2016-05-16 15:22:01 +12001691 def test_mock_open_after_eof(self):
1692 # read, readline and readlines should work after end of file.
1693 _open = mock.mock_open(read_data='foo')
1694 h = _open('bar')
1695 h.read()
1696 self.assertEqual('', h.read())
1697 self.assertEqual('', h.read())
1698 self.assertEqual('', h.readline())
1699 self.assertEqual('', h.readline())
1700 self.assertEqual([], h.readlines())
1701 self.assertEqual([], h.readlines())
1702
Michael Foord345266a2012-03-14 12:24:34 -07001703 def test_mock_parents(self):
1704 for Klass in Mock, MagicMock:
1705 m = Klass()
1706 original_repr = repr(m)
1707 m.return_value = m
1708 self.assertIs(m(), m)
1709 self.assertEqual(repr(m), original_repr)
1710
1711 m.reset_mock()
1712 self.assertIs(m(), m)
1713 self.assertEqual(repr(m), original_repr)
1714
1715 m = Klass()
1716 m.b = m.a
1717 self.assertIn("name='mock.a'", repr(m.b))
1718 self.assertIn("name='mock.a'", repr(m.a))
1719 m.reset_mock()
1720 self.assertIn("name='mock.a'", repr(m.b))
1721 self.assertIn("name='mock.a'", repr(m.a))
1722
1723 m = Klass()
1724 original_repr = repr(m)
1725 m.a = m()
1726 m.a.return_value = m
1727
1728 self.assertEqual(repr(m), original_repr)
1729 self.assertEqual(repr(m.a()), original_repr)
1730
1731
1732 def test_attach_mock(self):
1733 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1734 for Klass in classes:
1735 for Klass2 in classes:
1736 m = Klass()
1737
1738 m2 = Klass2(name='foo')
1739 m.attach_mock(m2, 'bar')
1740
1741 self.assertIs(m.bar, m2)
1742 self.assertIn("name='mock.bar'", repr(m2))
1743
1744 m.bar.baz(1)
1745 self.assertEqual(m.mock_calls, [call.bar.baz(1)])
1746 self.assertEqual(m.method_calls, [call.bar.baz(1)])
1747
1748
1749 def test_attach_mock_return_value(self):
1750 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1751 for Klass in Mock, MagicMock:
1752 for Klass2 in classes:
1753 m = Klass()
1754
1755 m2 = Klass2(name='foo')
1756 m.attach_mock(m2, 'return_value')
1757
1758 self.assertIs(m(), m2)
1759 self.assertIn("name='mock()'", repr(m2))
1760
1761 m2.foo()
1762 self.assertEqual(m.mock_calls, call().foo().call_list())
1763
1764
1765 def test_attribute_deletion(self):
Michael Foord468ec342013-09-15 20:05:19 +12001766 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1767 NonCallableMock()):
Michael Foord345266a2012-03-14 12:24:34 -07001768 self.assertTrue(hasattr(mock, 'm'))
1769
1770 del mock.m
1771 self.assertFalse(hasattr(mock, 'm'))
1772
1773 del mock.f
1774 self.assertFalse(hasattr(mock, 'f'))
1775 self.assertRaises(AttributeError, getattr, mock, 'f')
1776
1777
Pablo Galindo222d3032019-01-21 08:57:46 +00001778 def test_mock_does_not_raise_on_repeated_attribute_deletion(self):
1779 # bpo-20239: Assigning and deleting twice an attribute raises.
1780 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1781 NonCallableMock()):
1782 mock.foo = 3
1783 self.assertTrue(hasattr(mock, 'foo'))
1784 self.assertEqual(mock.foo, 3)
1785
1786 del mock.foo
1787 self.assertFalse(hasattr(mock, 'foo'))
1788
1789 mock.foo = 4
1790 self.assertTrue(hasattr(mock, 'foo'))
1791 self.assertEqual(mock.foo, 4)
1792
1793 del mock.foo
1794 self.assertFalse(hasattr(mock, 'foo'))
1795
1796
1797 def test_mock_raises_when_deleting_nonexistent_attribute(self):
1798 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1799 NonCallableMock()):
1800 del mock.foo
1801 with self.assertRaises(AttributeError):
1802 del mock.foo
1803
1804
Xtreakedeca922018-12-01 15:33:54 +05301805 def test_reset_mock_does_not_raise_on_attr_deletion(self):
1806 # bpo-31177: reset_mock should not raise AttributeError when attributes
1807 # were deleted in a mock instance
1808 mock = Mock()
1809 mock.child = True
1810 del mock.child
1811 mock.reset_mock()
1812 self.assertFalse(hasattr(mock, 'child'))
1813
1814
Michael Foord345266a2012-03-14 12:24:34 -07001815 def test_class_assignable(self):
1816 for mock in Mock(), MagicMock():
1817 self.assertNotIsInstance(mock, int)
1818
1819 mock.__class__ = int
1820 self.assertIsInstance(mock, int)
1821 mock.foo
1822
Andrew Dunaie63e6172018-12-04 11:08:45 +02001823 def test_name_attribute_of_call(self):
1824 # bpo-35357: _Call should not disclose any attributes whose names
1825 # may clash with popular ones (such as ".name")
1826 self.assertIsNotNone(call.name)
1827 self.assertEqual(type(call.name), _Call)
1828 self.assertEqual(type(call.name().name), _Call)
1829
1830 def test_parent_attribute_of_call(self):
1831 # bpo-35357: _Call should not disclose any attributes whose names
1832 # may clash with popular ones (such as ".parent")
1833 self.assertIsNotNone(call.parent)
1834 self.assertEqual(type(call.parent), _Call)
1835 self.assertEqual(type(call.parent().parent), _Call)
1836
Michael Foord345266a2012-03-14 12:24:34 -07001837
Xtreak9c3f2842019-02-26 03:16:34 +05301838 def test_parent_propagation_with_create_autospec(self):
1839
1840 def foo(a, b):
1841 pass
1842
1843 mock = Mock()
1844 mock.child = create_autospec(foo)
1845 mock.child(1, 2)
1846
1847 self.assertRaises(TypeError, mock.child, 1)
1848 self.assertEqual(mock.mock_calls, [call.child(1, 2)])
1849
Xtreak830b43d2019-04-14 00:42:33 +05301850 def test_isinstance_under_settrace(self):
1851 # bpo-36593 : __class__ is not set for a class that has __class__
1852 # property defined when it's used with sys.settrace(trace) set.
1853 # Delete the module to force reimport with tracing function set
1854 # restore the old reference later since there are other tests that are
1855 # dependent on unittest.mock.patch. In testpatch.PatchTest
1856 # test_patch_dict_test_prefix and test_patch_test_prefix not restoring
1857 # causes the objects patched to go out of sync
1858
1859 old_patch = unittest.mock.patch
1860
1861 # Directly using __setattr__ on unittest.mock causes current imported
1862 # reference to be updated. Use a lambda so that during cleanup the
1863 # re-imported new reference is updated.
1864 self.addCleanup(lambda patch: setattr(unittest.mock, 'patch', patch),
1865 old_patch)
1866
1867 with patch.dict('sys.modules'):
1868 del sys.modules['unittest.mock']
1869
1870 def trace(frame, event, arg):
1871 return trace
1872
1873 sys.settrace(trace)
1874 self.addCleanup(sys.settrace, None)
1875
1876 from unittest.mock import (
1877 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1878 )
1879
1880 mocks = [
1881 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1882 ]
1883
1884 for mock in mocks:
1885 obj = mock(spec=Something)
1886 self.assertIsInstance(obj, Something)
1887
Xtreak9c3f2842019-02-26 03:16:34 +05301888
Michael Foord345266a2012-03-14 12:24:34 -07001889if __name__ == '__main__':
1890 unittest.main()