blob: 677346725bdd244fe71af45ea24166aa48e3a038 [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
Serhiy Storchaka662db122019-08-08 08:42:54 +03006from test.support import ALWAYS_EQ
Michael Foord345266a2012-03-14 12:24:34 -07007import unittest
8from unittest.test.testmock.support import is_instance
9from unittest import mock
10from unittest.mock import (
11 call, DEFAULT, patch, sentinel,
12 MagicMock, Mock, NonCallableMock,
Lisa Roach77b3b772019-05-20 09:19:53 -070013 NonCallableMagicMock, AsyncMock, _Call, _CallList,
Michael Foord345266a2012-03-14 12:24:34 -070014 create_autospec
15)
16
17
18class Iter(object):
19 def __init__(self):
20 self.thing = iter(['this', 'is', 'an', 'iter'])
21
22 def __iter__(self):
23 return self
24
25 def next(self):
26 return next(self.thing)
27
28 __next__ = next
29
30
Antoine Pitrou5c64df72013-02-03 00:23:58 +010031class Something(object):
Chris Withersadbf1782019-05-01 23:04:04 +010032 def meth(self, a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +010033
34 @classmethod
Chris Withersadbf1782019-05-01 23:04:04 +010035 def cmeth(cls, a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +010036
37 @staticmethod
Chris Withersadbf1782019-05-01 23:04:04 +010038 def smeth(a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +010039
Michael Foord345266a2012-03-14 12:24:34 -070040
Xtreak7397cda2019-07-22 13:08:22 +053041def something(a): pass
42
43
Michael Foord345266a2012-03-14 12:24:34 -070044class MockTest(unittest.TestCase):
45
46 def test_all(self):
47 # if __all__ is badly defined then import * will raise an error
48 # We have to exec it because you can't import * inside a method
49 # in Python 3
Michael Foord83a16852012-03-14 12:58:46 -070050 exec("from unittest.mock import *")
Michael Foord345266a2012-03-14 12:24:34 -070051
52
53 def test_constructor(self):
54 mock = Mock()
55
56 self.assertFalse(mock.called, "called not initialised correctly")
57 self.assertEqual(mock.call_count, 0,
58 "call_count not initialised correctly")
59 self.assertTrue(is_instance(mock.return_value, Mock),
60 "return_value not initialised correctly")
61
62 self.assertEqual(mock.call_args, None,
63 "call_args not initialised correctly")
64 self.assertEqual(mock.call_args_list, [],
65 "call_args_list not initialised correctly")
66 self.assertEqual(mock.method_calls, [],
67 "method_calls not initialised correctly")
68
69 # Can't use hasattr for this test as it always returns True on a mock
Serhiy Storchaka5665bc52013-11-17 00:12:21 +020070 self.assertNotIn('_items', mock.__dict__,
Michael Foord345266a2012-03-14 12:24:34 -070071 "default mock should not have '_items' attribute")
72
73 self.assertIsNone(mock._mock_parent,
74 "parent not initialised correctly")
75 self.assertIsNone(mock._mock_methods,
76 "methods not initialised correctly")
77 self.assertEqual(mock._mock_children, {},
78 "children not initialised incorrectly")
79
80
81 def test_return_value_in_constructor(self):
82 mock = Mock(return_value=None)
83 self.assertIsNone(mock.return_value,
84 "return value in constructor not honoured")
85
86
Chris Withersadbf1782019-05-01 23:04:04 +010087 def test_change_return_value_via_delegate(self):
88 def f(): pass
89 mock = create_autospec(f)
90 mock.mock.return_value = 1
91 self.assertEqual(mock(), 1)
92
93
94 def test_change_side_effect_via_delegate(self):
95 def f(): pass
96 mock = create_autospec(f)
97 mock.mock.side_effect = TypeError()
98 with self.assertRaises(TypeError):
99 mock()
100
101
Michael Foord345266a2012-03-14 12:24:34 -0700102 def test_repr(self):
103 mock = Mock(name='foo')
104 self.assertIn('foo', repr(mock))
105 self.assertIn("'%s'" % id(mock), repr(mock))
106
107 mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')]
108 for mock, name in mocks:
109 self.assertIn('%s.bar' % name, repr(mock.bar))
110 self.assertIn('%s.foo()' % name, repr(mock.foo()))
111 self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing))
112 self.assertIn('%s()' % name, repr(mock()))
113 self.assertIn('%s()()' % name, repr(mock()()))
114 self.assertIn('%s()().foo.bar.baz().bing' % name,
115 repr(mock()().foo.bar.baz().bing))
116
117
118 def test_repr_with_spec(self):
119 class X(object):
120 pass
121
122 mock = Mock(spec=X)
123 self.assertIn(" spec='X' ", repr(mock))
124
125 mock = Mock(spec=X())
126 self.assertIn(" spec='X' ", repr(mock))
127
128 mock = Mock(spec_set=X)
129 self.assertIn(" spec_set='X' ", repr(mock))
130
131 mock = Mock(spec_set=X())
132 self.assertIn(" spec_set='X' ", repr(mock))
133
134 mock = Mock(spec=X, name='foo')
135 self.assertIn(" spec='X' ", repr(mock))
136 self.assertIn(" name='foo' ", repr(mock))
137
138 mock = Mock(name='foo')
139 self.assertNotIn("spec", repr(mock))
140
141 mock = Mock()
142 self.assertNotIn("spec", repr(mock))
143
144 mock = Mock(spec=['foo'])
145 self.assertNotIn("spec", repr(mock))
146
147
148 def test_side_effect(self):
149 mock = Mock()
150
151 def effect(*args, **kwargs):
152 raise SystemError('kablooie')
153
154 mock.side_effect = effect
155 self.assertRaises(SystemError, mock, 1, 2, fish=3)
156 mock.assert_called_with(1, 2, fish=3)
157
158 results = [1, 2, 3]
159 def effect():
160 return results.pop()
161 mock.side_effect = effect
162
163 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
164 "side effect not used correctly")
165
166 mock = Mock(side_effect=sentinel.SideEffect)
167 self.assertEqual(mock.side_effect, sentinel.SideEffect,
168 "side effect in constructor not used")
169
170 def side_effect():
171 return DEFAULT
172 mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
173 self.assertEqual(mock(), sentinel.RETURN)
174
Michael Foord01bafdc2014-04-14 16:09:42 -0400175 def test_autospec_side_effect(self):
176 # Test for issue17826
177 results = [1, 2, 3]
178 def effect():
179 return results.pop()
Chris Withersadbf1782019-05-01 23:04:04 +0100180 def f(): pass
Michael Foord01bafdc2014-04-14 16:09:42 -0400181
182 mock = create_autospec(f)
183 mock.side_effect = [1, 2, 3]
184 self.assertEqual([mock(), mock(), mock()], [1, 2, 3],
185 "side effect not used correctly in create_autospec")
186 # Test where side effect is a callable
187 results = [1, 2, 3]
188 mock = create_autospec(f)
189 mock.side_effect = effect
190 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
191 "callable side effect not used correctly")
Michael Foord345266a2012-03-14 12:24:34 -0700192
Robert Collinsf58f88c2015-07-14 13:51:40 +1200193 def test_autospec_side_effect_exception(self):
194 # Test for issue 23661
Chris Withersadbf1782019-05-01 23:04:04 +0100195 def f(): pass
Robert Collinsf58f88c2015-07-14 13:51:40 +1200196
197 mock = create_autospec(f)
198 mock.side_effect = ValueError('Bazinga!')
199 self.assertRaisesRegex(ValueError, 'Bazinga!', mock)
200
Michael Foord345266a2012-03-14 12:24:34 -0700201
202 def test_reset_mock(self):
203 parent = Mock()
204 spec = ["something"]
205 mock = Mock(name="child", parent=parent, spec=spec)
206 mock(sentinel.Something, something=sentinel.SomethingElse)
207 something = mock.something
208 mock.something()
209 mock.side_effect = sentinel.SideEffect
210 return_value = mock.return_value
211 return_value()
212
213 mock.reset_mock()
214
215 self.assertEqual(mock._mock_name, "child",
216 "name incorrectly reset")
217 self.assertEqual(mock._mock_parent, parent,
218 "parent incorrectly reset")
219 self.assertEqual(mock._mock_methods, spec,
220 "methods incorrectly reset")
221
222 self.assertFalse(mock.called, "called not reset")
223 self.assertEqual(mock.call_count, 0, "call_count not reset")
224 self.assertEqual(mock.call_args, None, "call_args not reset")
225 self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
226 self.assertEqual(mock.method_calls, [],
227 "method_calls not initialised correctly: %r != %r" %
228 (mock.method_calls, []))
229 self.assertEqual(mock.mock_calls, [])
230
231 self.assertEqual(mock.side_effect, sentinel.SideEffect,
232 "side_effect incorrectly reset")
233 self.assertEqual(mock.return_value, return_value,
234 "return_value incorrectly reset")
235 self.assertFalse(return_value.called, "return value mock not reset")
236 self.assertEqual(mock._mock_children, {'something': something},
237 "children reset incorrectly")
238 self.assertEqual(mock.something, something,
239 "children incorrectly cleared")
240 self.assertFalse(mock.something.called, "child not reset")
241
242
243 def test_reset_mock_recursion(self):
244 mock = Mock()
245 mock.return_value = mock
246
247 # used to cause recursion
248 mock.reset_mock()
249
Robert Collinsb37f43f2015-07-15 11:42:28 +1200250 def test_reset_mock_on_mock_open_issue_18622(self):
251 a = mock.mock_open()
252 a.reset_mock()
Michael Foord345266a2012-03-14 12:24:34 -0700253
254 def test_call(self):
255 mock = Mock()
256 self.assertTrue(is_instance(mock.return_value, Mock),
257 "Default return_value should be a Mock")
258
259 result = mock()
260 self.assertEqual(mock(), result,
261 "different result from consecutive calls")
262 mock.reset_mock()
263
264 ret_val = mock(sentinel.Arg)
265 self.assertTrue(mock.called, "called not set")
Min ho Kimc4cacc82019-07-31 08:16:13 +1000266 self.assertEqual(mock.call_count, 1, "call_count incorrect")
Michael Foord345266a2012-03-14 12:24:34 -0700267 self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
268 "call_args not set")
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530269 self.assertEqual(mock.call_args.args, (sentinel.Arg,),
270 "call_args not set")
271 self.assertEqual(mock.call_args.kwargs, {},
272 "call_args not set")
Michael Foord345266a2012-03-14 12:24:34 -0700273 self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
274 "call_args_list not initialised correctly")
275
276 mock.return_value = sentinel.ReturnValue
277 ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
278 self.assertEqual(ret_val, sentinel.ReturnValue,
279 "incorrect return value")
280
281 self.assertEqual(mock.call_count, 2, "call_count incorrect")
282 self.assertEqual(mock.call_args,
283 ((sentinel.Arg,), {'key': sentinel.KeyArg}),
284 "call_args not set")
285 self.assertEqual(mock.call_args_list, [
286 ((sentinel.Arg,), {}),
287 ((sentinel.Arg,), {'key': sentinel.KeyArg})
288 ],
289 "call_args_list not set")
290
291
292 def test_call_args_comparison(self):
293 mock = Mock()
294 mock()
295 mock(sentinel.Arg)
296 mock(kw=sentinel.Kwarg)
297 mock(sentinel.Arg, kw=sentinel.Kwarg)
298 self.assertEqual(mock.call_args_list, [
299 (),
300 ((sentinel.Arg,),),
301 ({"kw": sentinel.Kwarg},),
302 ((sentinel.Arg,), {"kw": sentinel.Kwarg})
303 ])
304 self.assertEqual(mock.call_args,
305 ((sentinel.Arg,), {"kw": sentinel.Kwarg}))
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530306 self.assertEqual(mock.call_args.args, (sentinel.Arg,))
307 self.assertEqual(mock.call_args.kwargs, {"kw": sentinel.Kwarg})
Michael Foord345266a2012-03-14 12:24:34 -0700308
Berker Peksag3fc536f2015-09-09 23:35:25 +0300309 # Comparing call_args to a long sequence should not raise
310 # an exception. See issue 24857.
311 self.assertFalse(mock.call_args == "a long sequence")
Michael Foord345266a2012-03-14 12:24:34 -0700312
Berker Peksagce913872016-03-28 00:30:02 +0300313
314 def test_calls_equal_with_any(self):
Berker Peksagce913872016-03-28 00:30:02 +0300315 # Check that equality and non-equality is consistent even when
316 # comparing with mock.ANY
Serhiy Storchaka362f0582017-01-21 23:12:58 +0200317 mm = mock.MagicMock()
318 self.assertTrue(mm == mm)
319 self.assertFalse(mm != mm)
320 self.assertFalse(mm == mock.MagicMock())
321 self.assertTrue(mm != mock.MagicMock())
322 self.assertTrue(mm == mock.ANY)
323 self.assertFalse(mm != mock.ANY)
324 self.assertTrue(mock.ANY == mm)
325 self.assertFalse(mock.ANY != mm)
Serhiy Storchaka662db122019-08-08 08:42:54 +0300326 self.assertTrue(mm == ALWAYS_EQ)
327 self.assertFalse(mm != ALWAYS_EQ)
Serhiy Storchaka362f0582017-01-21 23:12:58 +0200328
329 call1 = mock.call(mock.MagicMock())
330 call2 = mock.call(mock.ANY)
Berker Peksagce913872016-03-28 00:30:02 +0300331 self.assertTrue(call1 == call2)
332 self.assertFalse(call1 != call2)
Serhiy Storchaka362f0582017-01-21 23:12:58 +0200333 self.assertTrue(call2 == call1)
334 self.assertFalse(call2 != call1)
Berker Peksagce913872016-03-28 00:30:02 +0300335
Serhiy Storchaka662db122019-08-08 08:42:54 +0300336 self.assertTrue(call1 == ALWAYS_EQ)
337 self.assertFalse(call1 != ALWAYS_EQ)
338 self.assertFalse(call1 == 1)
339 self.assertTrue(call1 != 1)
340
Berker Peksagce913872016-03-28 00:30:02 +0300341
Michael Foord345266a2012-03-14 12:24:34 -0700342 def test_assert_called_with(self):
343 mock = Mock()
344 mock()
345
346 # Will raise an exception if it fails
347 mock.assert_called_with()
348 self.assertRaises(AssertionError, mock.assert_called_with, 1)
349
350 mock.reset_mock()
351 self.assertRaises(AssertionError, mock.assert_called_with)
352
353 mock(1, 2, 3, a='fish', b='nothing')
354 mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
355
356
Berker Peksagce913872016-03-28 00:30:02 +0300357 def test_assert_called_with_any(self):
358 m = MagicMock()
359 m(MagicMock())
360 m.assert_called_with(mock.ANY)
361
362
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100363 def test_assert_called_with_function_spec(self):
Chris Withersadbf1782019-05-01 23:04:04 +0100364 def f(a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100365
366 mock = Mock(spec=f)
367
368 mock(1, b=2, c=3)
369 mock.assert_called_with(1, 2, 3)
370 mock.assert_called_with(a=1, b=2, c=3)
371 self.assertRaises(AssertionError, mock.assert_called_with,
372 1, b=3, c=2)
373 # Expected call doesn't match the spec's signature
374 with self.assertRaises(AssertionError) as cm:
375 mock.assert_called_with(e=8)
376 self.assertIsInstance(cm.exception.__cause__, TypeError)
377
378
379 def test_assert_called_with_method_spec(self):
380 def _check(mock):
381 mock(1, b=2, c=3)
382 mock.assert_called_with(1, 2, 3)
383 mock.assert_called_with(a=1, b=2, c=3)
384 self.assertRaises(AssertionError, mock.assert_called_with,
385 1, b=3, c=2)
386
387 mock = Mock(spec=Something().meth)
388 _check(mock)
389 mock = Mock(spec=Something.cmeth)
390 _check(mock)
391 mock = Mock(spec=Something().cmeth)
392 _check(mock)
393 mock = Mock(spec=Something.smeth)
394 _check(mock)
395 mock = Mock(spec=Something().smeth)
396 _check(mock)
397
398
Abraham Toriz Cruz5f5f11f2019-09-17 06:16:08 -0500399 def test_assert_called_exception_message(self):
400 msg = "Expected '{0}' to have been called"
401 with self.assertRaisesRegex(AssertionError, msg.format('mock')):
402 Mock().assert_called()
403 with self.assertRaisesRegex(AssertionError, msg.format('test_name')):
404 Mock(name="test_name").assert_called()
405
406
Michael Foord345266a2012-03-14 12:24:34 -0700407 def test_assert_called_once_with(self):
408 mock = Mock()
409 mock()
410
411 # Will raise an exception if it fails
412 mock.assert_called_once_with()
413
414 mock()
415 self.assertRaises(AssertionError, mock.assert_called_once_with)
416
417 mock.reset_mock()
418 self.assertRaises(AssertionError, mock.assert_called_once_with)
419
420 mock('foo', 'bar', baz=2)
421 mock.assert_called_once_with('foo', 'bar', baz=2)
422
423 mock.reset_mock()
424 mock('foo', 'bar', baz=2)
425 self.assertRaises(
426 AssertionError,
427 lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
428 )
429
Petter Strandmark47d94242018-10-28 21:37:10 +0100430 def test_assert_called_once_with_call_list(self):
431 m = Mock()
432 m(1)
433 m(2)
434 self.assertRaisesRegex(AssertionError,
435 re.escape("Calls: [call(1), call(2)]"),
436 lambda: m.assert_called_once_with(2))
437
Michael Foord345266a2012-03-14 12:24:34 -0700438
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100439 def test_assert_called_once_with_function_spec(self):
Chris Withersadbf1782019-05-01 23:04:04 +0100440 def f(a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100441
442 mock = Mock(spec=f)
443
444 mock(1, b=2, c=3)
445 mock.assert_called_once_with(1, 2, 3)
446 mock.assert_called_once_with(a=1, b=2, c=3)
447 self.assertRaises(AssertionError, mock.assert_called_once_with,
448 1, b=3, c=2)
449 # Expected call doesn't match the spec's signature
450 with self.assertRaises(AssertionError) as cm:
451 mock.assert_called_once_with(e=8)
452 self.assertIsInstance(cm.exception.__cause__, TypeError)
453 # Mock called more than once => always fails
454 mock(4, 5, 6)
455 self.assertRaises(AssertionError, mock.assert_called_once_with,
456 1, 2, 3)
457 self.assertRaises(AssertionError, mock.assert_called_once_with,
458 4, 5, 6)
459
460
Michael Foord345266a2012-03-14 12:24:34 -0700461 def test_attribute_access_returns_mocks(self):
462 mock = Mock()
463 something = mock.something
464 self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
465 self.assertEqual(mock.something, something,
466 "different attributes returned for same name")
467
468 # Usage example
469 mock = Mock()
470 mock.something.return_value = 3
471
472 self.assertEqual(mock.something(), 3, "method returned wrong value")
473 self.assertTrue(mock.something.called,
474 "method didn't record being called")
475
476
477 def test_attributes_have_name_and_parent_set(self):
478 mock = Mock()
479 something = mock.something
480
481 self.assertEqual(something._mock_name, "something",
482 "attribute name not set correctly")
483 self.assertEqual(something._mock_parent, mock,
484 "attribute parent not set correctly")
485
486
487 def test_method_calls_recorded(self):
488 mock = Mock()
489 mock.something(3, fish=None)
490 mock.something_else.something(6, cake=sentinel.Cake)
491
492 self.assertEqual(mock.something_else.method_calls,
493 [("something", (6,), {'cake': sentinel.Cake})],
494 "method calls not recorded correctly")
495 self.assertEqual(mock.method_calls, [
496 ("something", (3,), {'fish': None}),
497 ("something_else.something", (6,), {'cake': sentinel.Cake})
498 ],
499 "method calls not recorded correctly")
500
501
502 def test_method_calls_compare_easily(self):
503 mock = Mock()
504 mock.something()
505 self.assertEqual(mock.method_calls, [('something',)])
506 self.assertEqual(mock.method_calls, [('something', (), {})])
507
508 mock = Mock()
509 mock.something('different')
510 self.assertEqual(mock.method_calls, [('something', ('different',))])
511 self.assertEqual(mock.method_calls,
512 [('something', ('different',), {})])
513
514 mock = Mock()
515 mock.something(x=1)
516 self.assertEqual(mock.method_calls, [('something', {'x': 1})])
517 self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
518
519 mock = Mock()
520 mock.something('different', some='more')
521 self.assertEqual(mock.method_calls, [
522 ('something', ('different',), {'some': 'more'})
523 ])
524
525
526 def test_only_allowed_methods_exist(self):
527 for spec in ['something'], ('something',):
528 for arg in 'spec', 'spec_set':
529 mock = Mock(**{arg: spec})
530
531 # this should be allowed
532 mock.something
533 self.assertRaisesRegex(
534 AttributeError,
535 "Mock object has no attribute 'something_else'",
536 getattr, mock, 'something_else'
537 )
538
539
540 def test_from_spec(self):
541 class Something(object):
542 x = 3
543 __something__ = None
Chris Withersadbf1782019-05-01 23:04:04 +0100544 def y(self): pass
Michael Foord345266a2012-03-14 12:24:34 -0700545
546 def test_attributes(mock):
547 # should work
548 mock.x
549 mock.y
550 mock.__something__
551 self.assertRaisesRegex(
552 AttributeError,
553 "Mock object has no attribute 'z'",
554 getattr, mock, 'z'
555 )
556 self.assertRaisesRegex(
557 AttributeError,
558 "Mock object has no attribute '__foobar__'",
559 getattr, mock, '__foobar__'
560 )
561
562 test_attributes(Mock(spec=Something))
563 test_attributes(Mock(spec=Something()))
564
565
566 def test_wraps_calls(self):
567 real = Mock()
568
569 mock = Mock(wraps=real)
570 self.assertEqual(mock(), real())
571
572 real.reset_mock()
573
574 mock(1, 2, fish=3)
575 real.assert_called_with(1, 2, fish=3)
576
577
Mario Corcherof05df0a2018-12-08 11:25:02 +0000578 def test_wraps_prevents_automatic_creation_of_mocks(self):
579 class Real(object):
580 pass
581
582 real = Real()
583 mock = Mock(wraps=real)
584
585 self.assertRaises(AttributeError, lambda: mock.new_attr())
586
587
Michael Foord345266a2012-03-14 12:24:34 -0700588 def test_wraps_call_with_nondefault_return_value(self):
589 real = Mock()
590
591 mock = Mock(wraps=real)
592 mock.return_value = 3
593
594 self.assertEqual(mock(), 3)
595 self.assertFalse(real.called)
596
597
598 def test_wraps_attributes(self):
599 class Real(object):
600 attribute = Mock()
601
602 real = Real()
603
604 mock = Mock(wraps=real)
605 self.assertEqual(mock.attribute(), real.attribute())
606 self.assertRaises(AttributeError, lambda: mock.fish)
607
608 self.assertNotEqual(mock.attribute, real.attribute)
609 result = mock.attribute.frog(1, 2, fish=3)
610 Real.attribute.frog.assert_called_with(1, 2, fish=3)
611 self.assertEqual(result, Real.attribute.frog())
612
613
Mario Corcherof05df0a2018-12-08 11:25:02 +0000614 def test_customize_wrapped_object_with_side_effect_iterable_with_default(self):
615 class Real(object):
616 def method(self):
617 return sentinel.ORIGINAL_VALUE
618
619 real = Real()
620 mock = Mock(wraps=real)
621 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
622
623 self.assertEqual(mock.method(), sentinel.VALUE1)
624 self.assertEqual(mock.method(), sentinel.ORIGINAL_VALUE)
625 self.assertRaises(StopIteration, mock.method)
626
627
628 def test_customize_wrapped_object_with_side_effect_iterable(self):
629 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100630 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000631
632 real = Real()
633 mock = Mock(wraps=real)
634 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
635
636 self.assertEqual(mock.method(), sentinel.VALUE1)
637 self.assertEqual(mock.method(), sentinel.VALUE2)
638 self.assertRaises(StopIteration, mock.method)
639
640
641 def test_customize_wrapped_object_with_side_effect_exception(self):
642 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100643 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000644
645 real = Real()
646 mock = Mock(wraps=real)
647 mock.method.side_effect = RuntimeError
648
649 self.assertRaises(RuntimeError, mock.method)
650
651
652 def test_customize_wrapped_object_with_side_effect_function(self):
653 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100654 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000655 def side_effect():
656 return sentinel.VALUE
657
658 real = Real()
659 mock = Mock(wraps=real)
660 mock.method.side_effect = side_effect
661
662 self.assertEqual(mock.method(), sentinel.VALUE)
663
664
665 def test_customize_wrapped_object_with_return_value(self):
666 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100667 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000668
669 real = Real()
670 mock = Mock(wraps=real)
671 mock.method.return_value = sentinel.VALUE
672
673 self.assertEqual(mock.method(), sentinel.VALUE)
674
675
676 def test_customize_wrapped_object_with_return_value_and_side_effect(self):
677 # side_effect should always take precedence over return_value.
678 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100679 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000680
681 real = Real()
682 mock = Mock(wraps=real)
683 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
684 mock.method.return_value = sentinel.WRONG_VALUE
685
686 self.assertEqual(mock.method(), sentinel.VALUE1)
687 self.assertEqual(mock.method(), sentinel.VALUE2)
688 self.assertRaises(StopIteration, mock.method)
689
690
691 def test_customize_wrapped_object_with_return_value_and_side_effect2(self):
692 # side_effect can return DEFAULT to default to return_value
693 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100694 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000695
696 real = Real()
697 mock = Mock(wraps=real)
698 mock.method.side_effect = lambda: DEFAULT
699 mock.method.return_value = sentinel.VALUE
700
701 self.assertEqual(mock.method(), sentinel.VALUE)
702
703
704 def test_customize_wrapped_object_with_return_value_and_side_effect_default(self):
705 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100706 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000707
708 real = Real()
709 mock = Mock(wraps=real)
710 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
711 mock.method.return_value = sentinel.RETURN
712
713 self.assertEqual(mock.method(), sentinel.VALUE1)
714 self.assertEqual(mock.method(), sentinel.RETURN)
715 self.assertRaises(StopIteration, mock.method)
716
717
Karthikeyan Singaravelan72b10042020-01-27 12:18:15 +0530718 def test_magic_method_wraps_dict(self):
719 data = {'foo': 'bar'}
720
721 wrapped_dict = MagicMock(wraps=data)
722 self.assertEqual(wrapped_dict.get('foo'), 'bar')
723 self.assertEqual(wrapped_dict['foo'], 'bar')
724 self.assertTrue('foo' in wrapped_dict)
725
726 # return_value is non-sentinel and takes precedence over wrapped value.
727 wrapped_dict.get.return_value = 'return_value'
728 self.assertEqual(wrapped_dict.get('foo'), 'return_value')
729
730 # return_value is sentinel and hence wrapped value is returned.
731 wrapped_dict.get.return_value = sentinel.DEFAULT
732 self.assertEqual(wrapped_dict.get('foo'), 'bar')
733
734 self.assertEqual(wrapped_dict.get('baz'), None)
735 with self.assertRaises(KeyError):
736 wrapped_dict['baz']
737 self.assertFalse('bar' in wrapped_dict)
738
739 data['baz'] = 'spam'
740 self.assertEqual(wrapped_dict.get('baz'), 'spam')
741 self.assertEqual(wrapped_dict['baz'], 'spam')
742 self.assertTrue('baz' in wrapped_dict)
743
744 del data['baz']
745 self.assertEqual(wrapped_dict.get('baz'), None)
746
747
748 def test_magic_method_wraps_class(self):
749
750 class Foo:
751
752 def __getitem__(self, index):
753 return index
754
755 def __custom_method__(self):
756 return "foo"
757
758
759 klass = MagicMock(wraps=Foo)
760 obj = klass()
761 self.assertEqual(obj.__getitem__(2), 2)
762 self.assertEqual(obj.__custom_method__(), "foo")
763
764
Michael Foord345266a2012-03-14 12:24:34 -0700765 def test_exceptional_side_effect(self):
766 mock = Mock(side_effect=AttributeError)
767 self.assertRaises(AttributeError, mock)
768
769 mock = Mock(side_effect=AttributeError('foo'))
770 self.assertRaises(AttributeError, mock)
771
772
773 def test_baseexceptional_side_effect(self):
774 mock = Mock(side_effect=KeyboardInterrupt)
775 self.assertRaises(KeyboardInterrupt, mock)
776
777 mock = Mock(side_effect=KeyboardInterrupt('foo'))
778 self.assertRaises(KeyboardInterrupt, mock)
779
780
781 def test_assert_called_with_message(self):
782 mock = Mock()
Susan Su2bdd5852019-02-13 18:22:29 -0800783 self.assertRaisesRegex(AssertionError, 'not called',
Michael Foord345266a2012-03-14 12:24:34 -0700784 mock.assert_called_with)
785
786
Michael Foord28d591c2012-09-28 16:15:22 +0100787 def test_assert_called_once_with_message(self):
788 mock = Mock(name='geoffrey')
789 self.assertRaisesRegex(AssertionError,
790 r"Expected 'geoffrey' to be called once\.",
791 mock.assert_called_once_with)
792
793
Michael Foord345266a2012-03-14 12:24:34 -0700794 def test__name__(self):
795 mock = Mock()
796 self.assertRaises(AttributeError, lambda: mock.__name__)
797
798 mock.__name__ = 'foo'
799 self.assertEqual(mock.__name__, 'foo')
800
801
802 def test_spec_list_subclass(self):
803 class Sub(list):
804 pass
805 mock = Mock(spec=Sub(['foo']))
806
807 mock.append(3)
808 mock.append.assert_called_with(3)
809 self.assertRaises(AttributeError, getattr, mock, 'foo')
810
811
812 def test_spec_class(self):
813 class X(object):
814 pass
815
816 mock = Mock(spec=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200817 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700818
819 mock = Mock(spec=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200820 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700821
822 self.assertIs(mock.__class__, X)
823 self.assertEqual(Mock().__class__.__name__, 'Mock')
824
825 mock = Mock(spec_set=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200826 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700827
828 mock = Mock(spec_set=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200829 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700830
831
Chris Withersadbf1782019-05-01 23:04:04 +0100832 def test_spec_class_no_object_base(self):
833 class X:
834 pass
835
836 mock = Mock(spec=X)
837 self.assertIsInstance(mock, X)
838
839 mock = Mock(spec=X())
840 self.assertIsInstance(mock, X)
841
842 self.assertIs(mock.__class__, X)
843 self.assertEqual(Mock().__class__.__name__, 'Mock')
844
845 mock = Mock(spec_set=X)
846 self.assertIsInstance(mock, X)
847
848 mock = Mock(spec_set=X())
849 self.assertIsInstance(mock, X)
850
851
Michael Foord345266a2012-03-14 12:24:34 -0700852 def test_setting_attribute_with_spec_set(self):
853 class X(object):
854 y = 3
855
856 mock = Mock(spec=X)
857 mock.x = 'foo'
858
859 mock = Mock(spec_set=X)
860 def set_attr():
861 mock.x = 'foo'
862
863 mock.y = 'foo'
864 self.assertRaises(AttributeError, set_attr)
865
866
867 def test_copy(self):
868 current = sys.getrecursionlimit()
869 self.addCleanup(sys.setrecursionlimit, current)
870
871 # can't use sys.maxint as this doesn't exist in Python 3
872 sys.setrecursionlimit(int(10e8))
873 # this segfaults without the fix in place
874 copy.copy(Mock())
875
876
877 def test_subclass_with_properties(self):
878 class SubClass(Mock):
879 def _get(self):
880 return 3
881 def _set(self, value):
882 raise NameError('strange error')
883 some_attribute = property(_get, _set)
884
885 s = SubClass(spec_set=SubClass)
886 self.assertEqual(s.some_attribute, 3)
887
888 def test():
889 s.some_attribute = 3
890 self.assertRaises(NameError, test)
891
892 def test():
893 s.foo = 'bar'
894 self.assertRaises(AttributeError, test)
895
896
897 def test_setting_call(self):
898 mock = Mock()
899 def __call__(self, a):
Lisa Roachef048512019-09-23 20:49:40 -0700900 self._increment_mock_call(a)
Michael Foord345266a2012-03-14 12:24:34 -0700901 return self._mock_call(a)
902
903 type(mock).__call__ = __call__
904 mock('one')
905 mock.assert_called_with('one')
906
907 self.assertRaises(TypeError, mock, 'one', 'two')
908
909
910 def test_dir(self):
911 mock = Mock()
912 attrs = set(dir(mock))
913 type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
914
915 # all public attributes from the type are included
916 self.assertEqual(set(), type_attrs - attrs)
917
918 # creates these attributes
919 mock.a, mock.b
920 self.assertIn('a', dir(mock))
921 self.assertIn('b', dir(mock))
922
923 # instance attributes
924 mock.c = mock.d = None
925 self.assertIn('c', dir(mock))
926 self.assertIn('d', dir(mock))
927
928 # magic methods
929 mock.__iter__ = lambda s: iter([])
930 self.assertIn('__iter__', dir(mock))
931
932
933 def test_dir_from_spec(self):
934 mock = Mock(spec=unittest.TestCase)
935 testcase_attrs = set(dir(unittest.TestCase))
936 attrs = set(dir(mock))
937
938 # all attributes from the spec are included
939 self.assertEqual(set(), testcase_attrs - attrs)
940
941 # shadow a sys attribute
942 mock.version = 3
943 self.assertEqual(dir(mock).count('version'), 1)
944
945
946 def test_filter_dir(self):
947 patcher = patch.object(mock, 'FILTER_DIR', False)
948 patcher.start()
949 try:
950 attrs = set(dir(Mock()))
951 type_attrs = set(dir(Mock))
952
953 # ALL attributes from the type are included
954 self.assertEqual(set(), type_attrs - attrs)
955 finally:
956 patcher.stop()
957
958
Mario Corchero0df635c2019-04-30 19:56:36 +0100959 def test_dir_does_not_include_deleted_attributes(self):
960 mock = Mock()
961 mock.child.return_value = 1
962
963 self.assertIn('child', dir(mock))
964 del mock.child
965 self.assertNotIn('child', dir(mock))
966
967
Michael Foord345266a2012-03-14 12:24:34 -0700968 def test_configure_mock(self):
969 mock = Mock(foo='bar')
970 self.assertEqual(mock.foo, 'bar')
971
972 mock = MagicMock(foo='bar')
973 self.assertEqual(mock.foo, 'bar')
974
975 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
976 'foo': MagicMock()}
977 mock = Mock(**kwargs)
978 self.assertRaises(KeyError, mock)
979 self.assertEqual(mock.foo.bar(), 33)
980 self.assertIsInstance(mock.foo, MagicMock)
981
982 mock = Mock()
983 mock.configure_mock(**kwargs)
984 self.assertRaises(KeyError, mock)
985 self.assertEqual(mock.foo.bar(), 33)
986 self.assertIsInstance(mock.foo, MagicMock)
987
988
989 def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
990 # needed because assertRaisesRegex doesn't work easily with newlines
Chris Withersadbf1782019-05-01 23:04:04 +0100991 with self.assertRaises(exception) as context:
Michael Foord345266a2012-03-14 12:24:34 -0700992 func(*args, **kwargs)
Chris Withersadbf1782019-05-01 23:04:04 +0100993 msg = str(context.exception)
Michael Foord345266a2012-03-14 12:24:34 -0700994 self.assertEqual(msg, message)
995
996
997 def test_assert_called_with_failure_message(self):
998 mock = NonCallableMock()
999
Susan Su2bdd5852019-02-13 18:22:29 -08001000 actual = 'not called.'
Michael Foord345266a2012-03-14 12:24:34 -07001001 expected = "mock(1, '2', 3, bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -08001002 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -07001003 self.assertRaisesWithMsg(
Susan Su2bdd5852019-02-13 18:22:29 -08001004 AssertionError, message % (expected, actual),
Michael Foord345266a2012-03-14 12:24:34 -07001005 mock.assert_called_with, 1, '2', 3, bar='foo'
1006 )
1007
1008 mock.foo(1, '2', 3, foo='foo')
1009
1010
1011 asserters = [
1012 mock.foo.assert_called_with, mock.foo.assert_called_once_with
1013 ]
1014 for meth in asserters:
1015 actual = "foo(1, '2', 3, foo='foo')"
1016 expected = "foo(1, '2', 3, bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -08001017 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -07001018 self.assertRaisesWithMsg(
1019 AssertionError, message % (expected, actual),
1020 meth, 1, '2', 3, bar='foo'
1021 )
1022
1023 # just kwargs
1024 for meth in asserters:
1025 actual = "foo(1, '2', 3, foo='foo')"
1026 expected = "foo(bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -08001027 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -07001028 self.assertRaisesWithMsg(
1029 AssertionError, message % (expected, actual),
1030 meth, bar='foo'
1031 )
1032
1033 # just args
1034 for meth in asserters:
1035 actual = "foo(1, '2', 3, foo='foo')"
1036 expected = "foo(1, 2, 3)"
Susan Su2bdd5852019-02-13 18:22:29 -08001037 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -07001038 self.assertRaisesWithMsg(
1039 AssertionError, message % (expected, actual),
1040 meth, 1, 2, 3
1041 )
1042
1043 # empty
1044 for meth in asserters:
1045 actual = "foo(1, '2', 3, foo='foo')"
1046 expected = "foo()"
Susan Su2bdd5852019-02-13 18:22:29 -08001047 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -07001048 self.assertRaisesWithMsg(
1049 AssertionError, message % (expected, actual), meth
1050 )
1051
1052
1053 def test_mock_calls(self):
1054 mock = MagicMock()
1055
1056 # need to do this because MagicMock.mock_calls used to just return
1057 # a MagicMock which also returned a MagicMock when __eq__ was called
1058 self.assertIs(mock.mock_calls == [], True)
1059
1060 mock = MagicMock()
1061 mock()
1062 expected = [('', (), {})]
1063 self.assertEqual(mock.mock_calls, expected)
1064
1065 mock.foo()
1066 expected.append(call.foo())
1067 self.assertEqual(mock.mock_calls, expected)
1068 # intermediate mock_calls work too
1069 self.assertEqual(mock.foo.mock_calls, [('', (), {})])
1070
1071 mock = MagicMock()
1072 mock().foo(1, 2, 3, a=4, b=5)
1073 expected = [
1074 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
1075 ]
1076 self.assertEqual(mock.mock_calls, expected)
1077 self.assertEqual(mock.return_value.foo.mock_calls,
1078 [('', (1, 2, 3), dict(a=4, b=5))])
1079 self.assertEqual(mock.return_value.mock_calls,
1080 [('foo', (1, 2, 3), dict(a=4, b=5))])
1081
1082 mock = MagicMock()
1083 mock().foo.bar().baz()
1084 expected = [
1085 ('', (), {}), ('().foo.bar', (), {}),
1086 ('().foo.bar().baz', (), {})
1087 ]
1088 self.assertEqual(mock.mock_calls, expected)
1089 self.assertEqual(mock().mock_calls,
1090 call.foo.bar().baz().call_list())
1091
1092 for kwargs in dict(), dict(name='bar'):
1093 mock = MagicMock(**kwargs)
1094 int(mock.foo)
1095 expected = [('foo.__int__', (), {})]
1096 self.assertEqual(mock.mock_calls, expected)
1097
1098 mock = MagicMock(**kwargs)
1099 mock.a()()
1100 expected = [('a', (), {}), ('a()', (), {})]
1101 self.assertEqual(mock.mock_calls, expected)
1102 self.assertEqual(mock.a().mock_calls, [call()])
1103
1104 mock = MagicMock(**kwargs)
1105 mock(1)(2)(3)
1106 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
1107 self.assertEqual(mock().mock_calls, call(2)(3).call_list())
1108 self.assertEqual(mock()().mock_calls, call(3).call_list())
1109
1110 mock = MagicMock(**kwargs)
1111 mock(1)(2)(3).a.b.c(4)
1112 self.assertEqual(mock.mock_calls,
1113 call(1)(2)(3).a.b.c(4).call_list())
1114 self.assertEqual(mock().mock_calls,
1115 call(2)(3).a.b.c(4).call_list())
1116 self.assertEqual(mock()().mock_calls,
1117 call(3).a.b.c(4).call_list())
1118
1119 mock = MagicMock(**kwargs)
1120 int(mock().foo.bar().baz())
1121 last_call = ('().foo.bar().baz().__int__', (), {})
1122 self.assertEqual(mock.mock_calls[-1], last_call)
1123 self.assertEqual(mock().mock_calls,
1124 call.foo.bar().baz().__int__().call_list())
1125 self.assertEqual(mock().foo.bar().mock_calls,
1126 call.baz().__int__().call_list())
1127 self.assertEqual(mock().foo.bar().baz.mock_calls,
1128 call().__int__().call_list())
1129
1130
Chris Withers8ca0fa92018-12-03 21:31:37 +00001131 def test_child_mock_call_equal(self):
1132 m = Mock()
1133 result = m()
1134 result.wibble()
1135 # parent looks like this:
1136 self.assertEqual(m.mock_calls, [call(), call().wibble()])
1137 # but child should look like this:
1138 self.assertEqual(result.mock_calls, [call.wibble()])
1139
1140
1141 def test_mock_call_not_equal_leaf(self):
1142 m = Mock()
1143 m.foo().something()
1144 self.assertNotEqual(m.mock_calls[1], call.foo().different())
1145 self.assertEqual(m.mock_calls[0], call.foo())
1146
1147
1148 def test_mock_call_not_equal_non_leaf(self):
1149 m = Mock()
1150 m.foo().bar()
1151 self.assertNotEqual(m.mock_calls[1], call.baz().bar())
1152 self.assertNotEqual(m.mock_calls[0], call.baz())
1153
1154
1155 def test_mock_call_not_equal_non_leaf_params_different(self):
1156 m = Mock()
1157 m.foo(x=1).bar()
1158 # This isn't ideal, but there's no way to fix it without breaking backwards compatibility:
1159 self.assertEqual(m.mock_calls[1], call.foo(x=2).bar())
1160
1161
1162 def test_mock_call_not_equal_non_leaf_attr(self):
1163 m = Mock()
1164 m.foo.bar()
1165 self.assertNotEqual(m.mock_calls[0], call.baz.bar())
1166
1167
1168 def test_mock_call_not_equal_non_leaf_call_versus_attr(self):
1169 m = Mock()
1170 m.foo.bar()
1171 self.assertNotEqual(m.mock_calls[0], call.foo().bar())
1172
1173
1174 def test_mock_call_repr(self):
1175 m = Mock()
1176 m.foo().bar().baz.bob()
1177 self.assertEqual(repr(m.mock_calls[0]), 'call.foo()')
1178 self.assertEqual(repr(m.mock_calls[1]), 'call.foo().bar()')
1179 self.assertEqual(repr(m.mock_calls[2]), 'call.foo().bar().baz.bob()')
1180
1181
Chris Withersadbf1782019-05-01 23:04:04 +01001182 def test_mock_call_repr_loop(self):
1183 m = Mock()
1184 m.foo = m
1185 repr(m.foo())
1186 self.assertRegex(repr(m.foo()), r"<Mock name='mock\(\)' id='\d+'>")
1187
1188
1189 def test_mock_calls_contains(self):
1190 m = Mock()
1191 self.assertFalse([call()] in m.mock_calls)
1192
1193
Michael Foord345266a2012-03-14 12:24:34 -07001194 def test_subclassing(self):
1195 class Subclass(Mock):
1196 pass
1197
1198 mock = Subclass()
1199 self.assertIsInstance(mock.foo, Subclass)
1200 self.assertIsInstance(mock(), Subclass)
1201
1202 class Subclass(Mock):
1203 def _get_child_mock(self, **kwargs):
1204 return Mock(**kwargs)
1205
1206 mock = Subclass()
1207 self.assertNotIsInstance(mock.foo, Subclass)
1208 self.assertNotIsInstance(mock(), Subclass)
1209
1210
1211 def test_arg_lists(self):
1212 mocks = [
1213 Mock(),
1214 MagicMock(),
1215 NonCallableMock(),
1216 NonCallableMagicMock()
1217 ]
1218
1219 def assert_attrs(mock):
1220 names = 'call_args_list', 'method_calls', 'mock_calls'
1221 for name in names:
1222 attr = getattr(mock, name)
1223 self.assertIsInstance(attr, _CallList)
1224 self.assertIsInstance(attr, list)
1225 self.assertEqual(attr, [])
1226
1227 for mock in mocks:
1228 assert_attrs(mock)
1229
1230 if callable(mock):
1231 mock()
1232 mock(1, 2)
1233 mock(a=3)
1234
1235 mock.reset_mock()
1236 assert_attrs(mock)
1237
1238 mock.foo()
1239 mock.foo.bar(1, a=3)
1240 mock.foo(1).bar().baz(3)
1241
1242 mock.reset_mock()
1243 assert_attrs(mock)
1244
1245
1246 def test_call_args_two_tuple(self):
1247 mock = Mock()
1248 mock(1, a=3)
1249 mock(2, b=4)
1250
1251 self.assertEqual(len(mock.call_args), 2)
Kumar Akshayb0df45e2019-03-22 13:40:40 +05301252 self.assertEqual(mock.call_args.args, (2,))
1253 self.assertEqual(mock.call_args.kwargs, dict(b=4))
Michael Foord345266a2012-03-14 12:24:34 -07001254
1255 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
1256 for expected, call_args in zip(expected_list, mock.call_args_list):
1257 self.assertEqual(len(call_args), 2)
1258 self.assertEqual(expected[0], call_args[0])
1259 self.assertEqual(expected[1], call_args[1])
1260
1261
1262 def test_side_effect_iterator(self):
1263 mock = Mock(side_effect=iter([1, 2, 3]))
1264 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1265 self.assertRaises(StopIteration, mock)
1266
1267 mock = MagicMock(side_effect=['a', 'b', 'c'])
1268 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1269 self.assertRaises(StopIteration, mock)
1270
1271 mock = Mock(side_effect='ghi')
1272 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
1273 self.assertRaises(StopIteration, mock)
1274
1275 class Foo(object):
1276 pass
1277 mock = MagicMock(side_effect=Foo)
1278 self.assertIsInstance(mock(), Foo)
1279
1280 mock = Mock(side_effect=Iter())
1281 self.assertEqual([mock(), mock(), mock(), mock()],
1282 ['this', 'is', 'an', 'iter'])
1283 self.assertRaises(StopIteration, mock)
1284
1285
Michael Foord2cd48732012-04-21 15:52:11 +01001286 def test_side_effect_iterator_exceptions(self):
1287 for Klass in Mock, MagicMock:
1288 iterable = (ValueError, 3, KeyError, 6)
1289 m = Klass(side_effect=iterable)
1290 self.assertRaises(ValueError, m)
1291 self.assertEqual(m(), 3)
1292 self.assertRaises(KeyError, m)
1293 self.assertEqual(m(), 6)
1294
1295
Michael Foord345266a2012-03-14 12:24:34 -07001296 def test_side_effect_setting_iterator(self):
1297 mock = Mock()
1298 mock.side_effect = iter([1, 2, 3])
1299 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1300 self.assertRaises(StopIteration, mock)
1301 side_effect = mock.side_effect
1302 self.assertIsInstance(side_effect, type(iter([])))
1303
1304 mock.side_effect = ['a', 'b', 'c']
1305 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1306 self.assertRaises(StopIteration, mock)
1307 side_effect = mock.side_effect
1308 self.assertIsInstance(side_effect, type(iter([])))
1309
1310 this_iter = Iter()
1311 mock.side_effect = this_iter
1312 self.assertEqual([mock(), mock(), mock(), mock()],
1313 ['this', 'is', 'an', 'iter'])
1314 self.assertRaises(StopIteration, mock)
1315 self.assertIs(mock.side_effect, this_iter)
1316
Andrew Svetlov8b2cd752013-04-07 16:42:24 +03001317 def test_side_effect_iterator_default(self):
1318 mock = Mock(return_value=2)
1319 mock.side_effect = iter([1, DEFAULT])
1320 self.assertEqual([mock(), mock()], [1, 2])
Michael Foord345266a2012-03-14 12:24:34 -07001321
1322 def test_assert_has_calls_any_order(self):
1323 mock = Mock()
1324 mock(1, 2)
1325 mock(a=3)
1326 mock(3, 4)
1327 mock(b=6)
1328 mock(b=6)
1329
1330 kalls = [
1331 call(1, 2), ({'a': 3},),
1332 ((3, 4),), ((), {'a': 3}),
1333 ('', (1, 2)), ('', {'a': 3}),
1334 ('', (1, 2), {}), ('', (), {'a': 3})
1335 ]
1336 for kall in kalls:
1337 mock.assert_has_calls([kall], any_order=True)
1338
1339 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
1340 self.assertRaises(
1341 AssertionError, mock.assert_has_calls,
1342 [kall], any_order=True
1343 )
1344
1345 kall_lists = [
1346 [call(1, 2), call(b=6)],
1347 [call(3, 4), call(1, 2)],
1348 [call(b=6), call(b=6)],
1349 ]
1350
1351 for kall_list in kall_lists:
1352 mock.assert_has_calls(kall_list, any_order=True)
1353
1354 kall_lists = [
1355 [call(b=6), call(b=6), call(b=6)],
1356 [call(1, 2), call(1, 2)],
1357 [call(3, 4), call(1, 2), call(5, 7)],
1358 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
1359 ]
1360 for kall_list in kall_lists:
1361 self.assertRaises(
1362 AssertionError, mock.assert_has_calls,
1363 kall_list, any_order=True
1364 )
1365
1366 def test_assert_has_calls(self):
1367 kalls1 = [
1368 call(1, 2), ({'a': 3},),
1369 ((3, 4),), call(b=6),
1370 ('', (1,), {'b': 6}),
1371 ]
1372 kalls2 = [call.foo(), call.bar(1)]
1373 kalls2.extend(call.spam().baz(a=3).call_list())
1374 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
1375
1376 mocks = []
1377 for mock in Mock(), MagicMock():
1378 mock(1, 2)
1379 mock(a=3)
1380 mock(3, 4)
1381 mock(b=6)
1382 mock(1, b=6)
1383 mocks.append((mock, kalls1))
1384
1385 mock = Mock()
1386 mock.foo()
1387 mock.bar(1)
1388 mock.spam().baz(a=3)
1389 mock.bam(set(), foo={}).fish([1])
1390 mocks.append((mock, kalls2))
1391
1392 for mock, kalls in mocks:
1393 for i in range(len(kalls)):
1394 for step in 1, 2, 3:
1395 these = kalls[i:i+step]
1396 mock.assert_has_calls(these)
1397
1398 if len(these) > 1:
1399 self.assertRaises(
1400 AssertionError,
1401 mock.assert_has_calls,
1402 list(reversed(these))
1403 )
1404
1405
Xtreakc9612782019-08-29 11:39:01 +05301406 def test_assert_has_calls_nested_spec(self):
1407 class Something:
1408
1409 def __init__(self): pass
1410 def meth(self, a, b, c, d=None): pass
1411
1412 class Foo:
1413
1414 def __init__(self, a): pass
1415 def meth1(self, a, b): pass
1416
1417 mock_class = create_autospec(Something)
1418
1419 for m in [mock_class, mock_class()]:
1420 m.meth(1, 2, 3, d=1)
1421 m.assert_has_calls([call.meth(1, 2, 3, d=1)])
1422 m.assert_has_calls([call.meth(1, 2, 3, 1)])
1423
1424 mock_class.reset_mock()
1425
1426 for m in [mock_class, mock_class()]:
1427 self.assertRaises(AssertionError, m.assert_has_calls, [call.Foo()])
1428 m.Foo(1).meth1(1, 2)
1429 m.assert_has_calls([call.Foo(1), call.Foo(1).meth1(1, 2)])
1430 m.Foo.assert_has_calls([call(1), call().meth1(1, 2)])
1431
1432 mock_class.reset_mock()
1433
1434 invalid_calls = [call.meth(1),
1435 call.non_existent(1),
1436 call.Foo().non_existent(1),
1437 call.Foo().meth(1, 2, 3, 4)]
1438
1439 for kall in invalid_calls:
1440 self.assertRaises(AssertionError,
1441 mock_class.assert_has_calls,
1442 [kall]
1443 )
1444
1445
1446 def test_assert_has_calls_nested_without_spec(self):
1447 m = MagicMock()
1448 m().foo().bar().baz()
1449 m.one().two().three()
1450 calls = call.one().two().three().call_list()
1451 m.assert_has_calls(calls)
1452
1453
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001454 def test_assert_has_calls_with_function_spec(self):
Chris Withersadbf1782019-05-01 23:04:04 +01001455 def f(a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001456
1457 mock = Mock(spec=f)
1458
1459 mock(1, b=2, c=3)
1460 mock(4, 5, c=6, d=7)
1461 mock(10, 11, c=12)
1462 calls = [
1463 ('', (1, 2, 3), {}),
1464 ('', (4, 5, 6), {'d': 7}),
1465 ((10, 11, 12), {}),
1466 ]
1467 mock.assert_has_calls(calls)
1468 mock.assert_has_calls(calls, any_order=True)
1469 mock.assert_has_calls(calls[1:])
1470 mock.assert_has_calls(calls[1:], any_order=True)
1471 mock.assert_has_calls(calls[:-1])
1472 mock.assert_has_calls(calls[:-1], any_order=True)
1473 # Reversed order
1474 calls = list(reversed(calls))
1475 with self.assertRaises(AssertionError):
1476 mock.assert_has_calls(calls)
1477 mock.assert_has_calls(calls, any_order=True)
1478 with self.assertRaises(AssertionError):
1479 mock.assert_has_calls(calls[1:])
1480 mock.assert_has_calls(calls[1:], any_order=True)
1481 with self.assertRaises(AssertionError):
1482 mock.assert_has_calls(calls[:-1])
1483 mock.assert_has_calls(calls[:-1], any_order=True)
1484
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04001485 def test_assert_has_calls_not_matching_spec_error(self):
Samuel Freilich2180f6b2019-09-24 18:04:29 -04001486 def f(x=None): pass
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04001487
1488 mock = Mock(spec=f)
Samuel Freilich2180f6b2019-09-24 18:04:29 -04001489 mock(1)
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04001490
1491 with self.assertRaisesRegex(
1492 AssertionError,
Samuel Freilich2180f6b2019-09-24 18:04:29 -04001493 '^{}$'.format(
1494 re.escape('Calls not found.\n'
1495 'Expected: [call()]\n'
1496 'Actual: [call(1)]'))) as cm:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04001497 mock.assert_has_calls([call()])
1498 self.assertIsNone(cm.exception.__cause__)
1499
Samuel Freilich2180f6b2019-09-24 18:04:29 -04001500
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04001501 with self.assertRaisesRegex(
1502 AssertionError,
Samuel Freilich2180f6b2019-09-24 18:04:29 -04001503 '^{}$'.format(
1504 re.escape(
1505 'Error processing expected calls.\n'
1506 "Errors: [None, TypeError('too many positional arguments')]\n"
1507 "Expected: [call(), call(1, 2)]\n"
1508 'Actual: [call(1)]'))) as cm:
1509 mock.assert_has_calls([call(), call(1, 2)])
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04001510 self.assertIsInstance(cm.exception.__cause__, TypeError)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001511
Michael Foord345266a2012-03-14 12:24:34 -07001512 def test_assert_any_call(self):
1513 mock = Mock()
1514 mock(1, 2)
1515 mock(a=3)
1516 mock(1, b=6)
1517
1518 mock.assert_any_call(1, 2)
1519 mock.assert_any_call(a=3)
1520 mock.assert_any_call(1, b=6)
1521
1522 self.assertRaises(
1523 AssertionError,
1524 mock.assert_any_call
1525 )
1526 self.assertRaises(
1527 AssertionError,
1528 mock.assert_any_call,
1529 1, 3
1530 )
1531 self.assertRaises(
1532 AssertionError,
1533 mock.assert_any_call,
1534 a=4
1535 )
1536
1537
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001538 def test_assert_any_call_with_function_spec(self):
Chris Withersadbf1782019-05-01 23:04:04 +01001539 def f(a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001540
1541 mock = Mock(spec=f)
1542
1543 mock(1, b=2, c=3)
1544 mock(4, 5, c=6, d=7)
1545 mock.assert_any_call(1, 2, 3)
1546 mock.assert_any_call(a=1, b=2, c=3)
1547 mock.assert_any_call(4, 5, 6, 7)
1548 mock.assert_any_call(a=4, b=5, c=6, d=7)
1549 self.assertRaises(AssertionError, mock.assert_any_call,
1550 1, b=3, c=2)
1551 # Expected call doesn't match the spec's signature
1552 with self.assertRaises(AssertionError) as cm:
1553 mock.assert_any_call(e=8)
1554 self.assertIsInstance(cm.exception.__cause__, TypeError)
1555
1556
Michael Foord345266a2012-03-14 12:24:34 -07001557 def test_mock_calls_create_autospec(self):
Chris Withersadbf1782019-05-01 23:04:04 +01001558 def f(a, b): pass
Michael Foord345266a2012-03-14 12:24:34 -07001559 obj = Iter()
1560 obj.f = f
1561
1562 funcs = [
1563 create_autospec(f),
1564 create_autospec(obj).f
1565 ]
1566 for func in funcs:
1567 func(1, 2)
1568 func(3, 4)
1569
1570 self.assertEqual(
1571 func.mock_calls, [call(1, 2), call(3, 4)]
1572 )
1573
Kushal Das484f8a82014-04-16 01:05:50 +05301574 #Issue21222
1575 def test_create_autospec_with_name(self):
1576 m = mock.create_autospec(object(), name='sweet_func')
1577 self.assertIn('sweet_func', repr(m))
Michael Foord345266a2012-03-14 12:24:34 -07001578
Xtreak9b218562019-04-22 08:00:23 +05301579 #Issue23078
1580 def test_create_autospec_classmethod_and_staticmethod(self):
1581 class TestClass:
1582 @classmethod
Chris Withersadbf1782019-05-01 23:04:04 +01001583 def class_method(cls): pass
Xtreak9b218562019-04-22 08:00:23 +05301584
1585 @staticmethod
Chris Withersadbf1782019-05-01 23:04:04 +01001586 def static_method(): pass
Xtreak9b218562019-04-22 08:00:23 +05301587 for method in ('class_method', 'static_method'):
1588 with self.subTest(method=method):
1589 mock_method = mock.create_autospec(getattr(TestClass, method))
1590 mock_method()
1591 mock_method.assert_called_once_with()
1592 self.assertRaises(TypeError, mock_method, 'extra_arg')
1593
Kushal Das8c145342014-04-16 23:32:21 +05301594 #Issue21238
1595 def test_mock_unsafe(self):
1596 m = Mock()
Zackery Spytzb9b08cd2019-05-08 11:32:24 -06001597 msg = "Attributes cannot start with 'assert' or 'assret'"
1598 with self.assertRaisesRegex(AttributeError, msg):
Kushal Das8c145342014-04-16 23:32:21 +05301599 m.assert_foo_call()
Zackery Spytzb9b08cd2019-05-08 11:32:24 -06001600 with self.assertRaisesRegex(AttributeError, msg):
Kushal Das8c145342014-04-16 23:32:21 +05301601 m.assret_foo_call()
1602 m = Mock(unsafe=True)
1603 m.assert_foo_call()
1604 m.assret_foo_call()
1605
Kushal Das8af9db32014-04-17 01:36:14 +05301606 #Issue21262
1607 def test_assert_not_called(self):
1608 m = Mock()
1609 m.hello.assert_not_called()
1610 m.hello()
1611 with self.assertRaises(AssertionError):
1612 m.hello.assert_not_called()
1613
Petter Strandmark47d94242018-10-28 21:37:10 +01001614 def test_assert_not_called_message(self):
1615 m = Mock()
1616 m(1, 2)
1617 self.assertRaisesRegex(AssertionError,
1618 re.escape("Calls: [call(1, 2)]"),
1619 m.assert_not_called)
1620
Victor Stinner2c2a4e62016-03-11 22:17:48 +01001621 def test_assert_called(self):
1622 m = Mock()
1623 with self.assertRaises(AssertionError):
1624 m.hello.assert_called()
1625 m.hello()
1626 m.hello.assert_called()
1627
1628 m.hello()
1629 m.hello.assert_called()
1630
1631 def test_assert_called_once(self):
1632 m = Mock()
1633 with self.assertRaises(AssertionError):
1634 m.hello.assert_called_once()
1635 m.hello()
1636 m.hello.assert_called_once()
1637
1638 m.hello()
1639 with self.assertRaises(AssertionError):
1640 m.hello.assert_called_once()
1641
Petter Strandmark47d94242018-10-28 21:37:10 +01001642 def test_assert_called_once_message(self):
1643 m = Mock()
1644 m(1, 2)
1645 m(3)
1646 self.assertRaisesRegex(AssertionError,
1647 re.escape("Calls: [call(1, 2), call(3)]"),
1648 m.assert_called_once)
1649
1650 def test_assert_called_once_message_not_called(self):
1651 m = Mock()
1652 with self.assertRaises(AssertionError) as e:
1653 m.assert_called_once()
1654 self.assertNotIn("Calls:", str(e.exception))
1655
Xtreak9d607062019-09-09 16:25:22 +05301656 #Issue37212 printout of keyword args now preserves the original order
1657 def test_ordered_call_signature(self):
Kushal Das047f14c2014-06-09 13:45:56 +05301658 m = Mock()
1659 m.hello(name='hello', daddy='hero')
Xtreak9d607062019-09-09 16:25:22 +05301660 text = "call(name='hello', daddy='hero')"
R David Murray130a5662014-06-11 17:09:43 -04001661 self.assertEqual(repr(m.hello.call_args), text)
Kushal Das8af9db32014-04-17 01:36:14 +05301662
Kushal Dasa37b9582014-09-16 18:33:37 +05301663 #Issue21270 overrides tuple methods for mock.call objects
1664 def test_override_tuple_methods(self):
1665 c = call.count()
1666 i = call.index(132,'hello')
1667 m = Mock()
1668 m.count()
1669 m.index(132,"hello")
1670 self.assertEqual(m.method_calls[0], c)
1671 self.assertEqual(m.method_calls[1], i)
1672
Kushal Das9cd39a12016-06-02 10:20:16 -07001673 def test_reset_return_sideeffect(self):
1674 m = Mock(return_value=10, side_effect=[2,3])
1675 m.reset_mock(return_value=True, side_effect=True)
1676 self.assertIsInstance(m.return_value, Mock)
1677 self.assertEqual(m.side_effect, None)
1678
1679 def test_reset_return(self):
1680 m = Mock(return_value=10, side_effect=[2,3])
1681 m.reset_mock(return_value=True)
1682 self.assertIsInstance(m.return_value, Mock)
1683 self.assertNotEqual(m.side_effect, None)
1684
1685 def test_reset_sideeffect(self):
Vegard Stikbakkeaef7dc82020-01-25 16:44:46 +01001686 m = Mock(return_value=10, side_effect=[2, 3])
Kushal Das9cd39a12016-06-02 10:20:16 -07001687 m.reset_mock(side_effect=True)
1688 self.assertEqual(m.return_value, 10)
1689 self.assertEqual(m.side_effect, None)
1690
Vegard Stikbakkeaef7dc82020-01-25 16:44:46 +01001691 def test_reset_return_with_children(self):
1692 m = MagicMock(f=MagicMock(return_value=1))
1693 self.assertEqual(m.f(), 1)
1694 m.reset_mock(return_value=True)
1695 self.assertNotEqual(m.f(), 1)
1696
1697 def test_reset_return_with_children_side_effect(self):
1698 m = MagicMock(f=MagicMock(side_effect=[2, 3]))
1699 self.assertNotEqual(m.f.side_effect, None)
1700 m.reset_mock(side_effect=True)
1701 self.assertEqual(m.f.side_effect, None)
1702
Michael Foord345266a2012-03-14 12:24:34 -07001703 def test_mock_add_spec(self):
1704 class _One(object):
1705 one = 1
1706 class _Two(object):
1707 two = 2
1708 class Anything(object):
1709 one = two = three = 'four'
1710
1711 klasses = [
1712 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1713 ]
1714 for Klass in list(klasses):
1715 klasses.append(lambda K=Klass: K(spec=Anything))
1716 klasses.append(lambda K=Klass: K(spec_set=Anything))
1717
1718 for Klass in klasses:
1719 for kwargs in dict(), dict(spec_set=True):
1720 mock = Klass()
1721 #no error
1722 mock.one, mock.two, mock.three
1723
1724 for One, Two in [(_One, _Two), (['one'], ['two'])]:
1725 for kwargs in dict(), dict(spec_set=True):
1726 mock.mock_add_spec(One, **kwargs)
1727
1728 mock.one
1729 self.assertRaises(
1730 AttributeError, getattr, mock, 'two'
1731 )
1732 self.assertRaises(
1733 AttributeError, getattr, mock, 'three'
1734 )
1735 if 'spec_set' in kwargs:
1736 self.assertRaises(
1737 AttributeError, setattr, mock, 'three', None
1738 )
1739
1740 mock.mock_add_spec(Two, **kwargs)
1741 self.assertRaises(
1742 AttributeError, getattr, mock, 'one'
1743 )
1744 mock.two
1745 self.assertRaises(
1746 AttributeError, getattr, mock, 'three'
1747 )
1748 if 'spec_set' in kwargs:
1749 self.assertRaises(
1750 AttributeError, setattr, mock, 'three', None
1751 )
1752 # note that creating a mock, setting an instance attribute, and
1753 # *then* setting a spec doesn't work. Not the intended use case
1754
1755
1756 def test_mock_add_spec_magic_methods(self):
1757 for Klass in MagicMock, NonCallableMagicMock:
1758 mock = Klass()
1759 int(mock)
1760
1761 mock.mock_add_spec(object)
1762 self.assertRaises(TypeError, int, mock)
1763
1764 mock = Klass()
1765 mock['foo']
1766 mock.__int__.return_value =4
1767
1768 mock.mock_add_spec(int)
1769 self.assertEqual(int(mock), 4)
1770 self.assertRaises(TypeError, lambda: mock['foo'])
1771
1772
1773 def test_adding_child_mock(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07001774 for Klass in (NonCallableMock, Mock, MagicMock, NonCallableMagicMock,
1775 AsyncMock):
Michael Foord345266a2012-03-14 12:24:34 -07001776 mock = Klass()
1777
1778 mock.foo = Mock()
1779 mock.foo()
1780
1781 self.assertEqual(mock.method_calls, [call.foo()])
1782 self.assertEqual(mock.mock_calls, [call.foo()])
1783
1784 mock = Klass()
1785 mock.bar = Mock(name='name')
1786 mock.bar()
1787 self.assertEqual(mock.method_calls, [])
1788 self.assertEqual(mock.mock_calls, [])
1789
1790 # mock with an existing _new_parent but no name
1791 mock = Klass()
1792 mock.baz = MagicMock()()
1793 mock.baz()
1794 self.assertEqual(mock.method_calls, [])
1795 self.assertEqual(mock.mock_calls, [])
1796
1797
1798 def test_adding_return_value_mock(self):
1799 for Klass in Mock, MagicMock:
1800 mock = Klass()
1801 mock.return_value = MagicMock()
1802
1803 mock()()
1804 self.assertEqual(mock.mock_calls, [call(), call()()])
1805
1806
1807 def test_manager_mock(self):
1808 class Foo(object):
1809 one = 'one'
1810 two = 'two'
1811 manager = Mock()
1812 p1 = patch.object(Foo, 'one')
1813 p2 = patch.object(Foo, 'two')
1814
1815 mock_one = p1.start()
1816 self.addCleanup(p1.stop)
1817 mock_two = p2.start()
1818 self.addCleanup(p2.stop)
1819
1820 manager.attach_mock(mock_one, 'one')
1821 manager.attach_mock(mock_two, 'two')
1822
1823 Foo.two()
1824 Foo.one()
1825
1826 self.assertEqual(manager.mock_calls, [call.two(), call.one()])
1827
1828
1829 def test_magic_methods_mock_calls(self):
1830 for Klass in Mock, MagicMock:
1831 m = Klass()
1832 m.__int__ = Mock(return_value=3)
1833 m.__float__ = MagicMock(return_value=3.0)
1834 int(m)
1835 float(m)
1836
1837 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
1838 self.assertEqual(m.method_calls, [])
1839
Robert Collins5329aaa2015-07-17 20:08:45 +12001840 def test_mock_open_reuse_issue_21750(self):
1841 mocked_open = mock.mock_open(read_data='data')
1842 f1 = mocked_open('a-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001843 f1_data = f1.read()
Robert Collins5329aaa2015-07-17 20:08:45 +12001844 f2 = mocked_open('another-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001845 f2_data = f2.read()
1846 self.assertEqual(f1_data, f2_data)
1847
Tony Flury20870232018-09-12 23:21:16 +01001848 def test_mock_open_dunder_iter_issue(self):
1849 # Test dunder_iter method generates the expected result and
1850 # consumes the iterator.
1851 mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue')
1852 f1 = mocked_open('a-name')
1853 lines = [line for line in f1]
1854 self.assertEqual(lines[0], 'Remarkable\n')
1855 self.assertEqual(lines[1], 'Norwegian Blue')
1856 self.assertEqual(list(f1), [])
1857
Damien Nadé394119a2019-05-23 12:03:25 +02001858 def test_mock_open_using_next(self):
1859 mocked_open = mock.mock_open(read_data='1st line\n2nd line\n3rd line')
1860 f1 = mocked_open('a-name')
1861 line1 = next(f1)
1862 line2 = f1.__next__()
1863 lines = [line for line in f1]
1864 self.assertEqual(line1, '1st line\n')
1865 self.assertEqual(line2, '2nd line\n')
1866 self.assertEqual(lines[0], '3rd line')
1867 self.assertEqual(list(f1), [])
1868 with self.assertRaises(StopIteration):
1869 next(f1)
1870
Robert Collinsca647ef2015-07-24 03:48:20 +12001871 def test_mock_open_write(self):
1872 # Test exception in file writing write()
1873 mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
1874 with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
1875 mock_filehandle = mock_namedtemp.return_value
1876 mock_write = mock_filehandle.write
1877 mock_write.side_effect = OSError('Test 2 Error')
1878 def attempt():
1879 tempfile.NamedTemporaryFile().write('asd')
1880 self.assertRaises(OSError, attempt)
1881
1882 def test_mock_open_alter_readline(self):
1883 mopen = mock.mock_open(read_data='foo\nbarn')
1884 mopen.return_value.readline.side_effect = lambda *args:'abc'
1885 first = mopen().readline()
1886 second = mopen().readline()
1887 self.assertEqual('abc', first)
1888 self.assertEqual('abc', second)
Michael Foord345266a2012-03-14 12:24:34 -07001889
Robert Collins9549a3e2016-05-16 15:22:01 +12001890 def test_mock_open_after_eof(self):
1891 # read, readline and readlines should work after end of file.
1892 _open = mock.mock_open(read_data='foo')
1893 h = _open('bar')
1894 h.read()
1895 self.assertEqual('', h.read())
1896 self.assertEqual('', h.read())
1897 self.assertEqual('', h.readline())
1898 self.assertEqual('', h.readline())
1899 self.assertEqual([], h.readlines())
1900 self.assertEqual([], h.readlines())
1901
Michael Foord345266a2012-03-14 12:24:34 -07001902 def test_mock_parents(self):
1903 for Klass in Mock, MagicMock:
1904 m = Klass()
1905 original_repr = repr(m)
1906 m.return_value = m
1907 self.assertIs(m(), m)
1908 self.assertEqual(repr(m), original_repr)
1909
1910 m.reset_mock()
1911 self.assertIs(m(), m)
1912 self.assertEqual(repr(m), original_repr)
1913
1914 m = Klass()
1915 m.b = m.a
1916 self.assertIn("name='mock.a'", repr(m.b))
1917 self.assertIn("name='mock.a'", repr(m.a))
1918 m.reset_mock()
1919 self.assertIn("name='mock.a'", repr(m.b))
1920 self.assertIn("name='mock.a'", repr(m.a))
1921
1922 m = Klass()
1923 original_repr = repr(m)
1924 m.a = m()
1925 m.a.return_value = m
1926
1927 self.assertEqual(repr(m), original_repr)
1928 self.assertEqual(repr(m.a()), original_repr)
1929
1930
1931 def test_attach_mock(self):
1932 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1933 for Klass in classes:
1934 for Klass2 in classes:
1935 m = Klass()
1936
1937 m2 = Klass2(name='foo')
1938 m.attach_mock(m2, 'bar')
1939
1940 self.assertIs(m.bar, m2)
1941 self.assertIn("name='mock.bar'", repr(m2))
1942
1943 m.bar.baz(1)
1944 self.assertEqual(m.mock_calls, [call.bar.baz(1)])
1945 self.assertEqual(m.method_calls, [call.bar.baz(1)])
1946
1947
1948 def test_attach_mock_return_value(self):
1949 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1950 for Klass in Mock, MagicMock:
1951 for Klass2 in classes:
1952 m = Klass()
1953
1954 m2 = Klass2(name='foo')
1955 m.attach_mock(m2, 'return_value')
1956
1957 self.assertIs(m(), m2)
1958 self.assertIn("name='mock()'", repr(m2))
1959
1960 m2.foo()
1961 self.assertEqual(m.mock_calls, call().foo().call_list())
1962
1963
Xtreak7397cda2019-07-22 13:08:22 +05301964 def test_attach_mock_patch_autospec(self):
1965 parent = Mock()
1966
1967 with mock.patch(f'{__name__}.something', autospec=True) as mock_func:
1968 self.assertEqual(mock_func.mock._extract_mock_name(), 'something')
1969 parent.attach_mock(mock_func, 'child')
1970 parent.child(1)
1971 something(2)
1972 mock_func(3)
1973
1974 parent_calls = [call.child(1), call.child(2), call.child(3)]
1975 child_calls = [call(1), call(2), call(3)]
1976 self.assertEqual(parent.mock_calls, parent_calls)
1977 self.assertEqual(parent.child.mock_calls, child_calls)
1978 self.assertEqual(something.mock_calls, child_calls)
1979 self.assertEqual(mock_func.mock_calls, child_calls)
1980 self.assertIn('mock.child', repr(parent.child.mock))
1981 self.assertEqual(mock_func.mock._extract_mock_name(), 'mock.child')
1982
1983
Karthikeyan Singaravelan66b00a92020-01-24 18:44:29 +05301984 def test_attach_mock_patch_autospec_signature(self):
1985 with mock.patch(f'{__name__}.Something.meth', autospec=True) as mocked:
1986 manager = Mock()
1987 manager.attach_mock(mocked, 'attach_meth')
1988 obj = Something()
1989 obj.meth(1, 2, 3, d=4)
1990 manager.assert_has_calls([call.attach_meth(mock.ANY, 1, 2, 3, d=4)])
1991 obj.meth.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)])
1992 mocked.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)])
1993
1994 with mock.patch(f'{__name__}.something', autospec=True) as mocked:
1995 manager = Mock()
1996 manager.attach_mock(mocked, 'attach_func')
1997 something(1)
1998 manager.assert_has_calls([call.attach_func(1)])
1999 something.assert_has_calls([call(1)])
2000 mocked.assert_has_calls([call(1)])
2001
2002 with mock.patch(f'{__name__}.Something', autospec=True) as mocked:
2003 manager = Mock()
2004 manager.attach_mock(mocked, 'attach_obj')
2005 obj = Something()
2006 obj.meth(1, 2, 3, d=4)
2007 manager.assert_has_calls([call.attach_obj(),
2008 call.attach_obj().meth(1, 2, 3, d=4)])
2009 obj.meth.assert_has_calls([call(1, 2, 3, d=4)])
2010 mocked.assert_has_calls([call(), call().meth(1, 2, 3, d=4)])
2011
2012
Michael Foord345266a2012-03-14 12:24:34 -07002013 def test_attribute_deletion(self):
Michael Foord468ec342013-09-15 20:05:19 +12002014 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
2015 NonCallableMock()):
Michael Foord345266a2012-03-14 12:24:34 -07002016 self.assertTrue(hasattr(mock, 'm'))
2017
2018 del mock.m
2019 self.assertFalse(hasattr(mock, 'm'))
2020
2021 del mock.f
2022 self.assertFalse(hasattr(mock, 'f'))
2023 self.assertRaises(AttributeError, getattr, mock, 'f')
2024
2025
Pablo Galindo222d3032019-01-21 08:57:46 +00002026 def test_mock_does_not_raise_on_repeated_attribute_deletion(self):
2027 # bpo-20239: Assigning and deleting twice an attribute raises.
2028 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
2029 NonCallableMock()):
2030 mock.foo = 3
2031 self.assertTrue(hasattr(mock, 'foo'))
2032 self.assertEqual(mock.foo, 3)
2033
2034 del mock.foo
2035 self.assertFalse(hasattr(mock, 'foo'))
2036
2037 mock.foo = 4
2038 self.assertTrue(hasattr(mock, 'foo'))
2039 self.assertEqual(mock.foo, 4)
2040
2041 del mock.foo
2042 self.assertFalse(hasattr(mock, 'foo'))
2043
2044
2045 def test_mock_raises_when_deleting_nonexistent_attribute(self):
2046 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
2047 NonCallableMock()):
2048 del mock.foo
2049 with self.assertRaises(AttributeError):
2050 del mock.foo
2051
2052
Xtreakedeca922018-12-01 15:33:54 +05302053 def test_reset_mock_does_not_raise_on_attr_deletion(self):
2054 # bpo-31177: reset_mock should not raise AttributeError when attributes
2055 # were deleted in a mock instance
2056 mock = Mock()
2057 mock.child = True
2058 del mock.child
2059 mock.reset_mock()
2060 self.assertFalse(hasattr(mock, 'child'))
2061
2062
Michael Foord345266a2012-03-14 12:24:34 -07002063 def test_class_assignable(self):
2064 for mock in Mock(), MagicMock():
2065 self.assertNotIsInstance(mock, int)
2066
2067 mock.__class__ = int
2068 self.assertIsInstance(mock, int)
2069 mock.foo
2070
Andrew Dunaie63e6172018-12-04 11:08:45 +02002071 def test_name_attribute_of_call(self):
2072 # bpo-35357: _Call should not disclose any attributes whose names
2073 # may clash with popular ones (such as ".name")
2074 self.assertIsNotNone(call.name)
2075 self.assertEqual(type(call.name), _Call)
2076 self.assertEqual(type(call.name().name), _Call)
2077
2078 def test_parent_attribute_of_call(self):
2079 # bpo-35357: _Call should not disclose any attributes whose names
2080 # may clash with popular ones (such as ".parent")
2081 self.assertIsNotNone(call.parent)
2082 self.assertEqual(type(call.parent), _Call)
2083 self.assertEqual(type(call.parent().parent), _Call)
2084
Michael Foord345266a2012-03-14 12:24:34 -07002085
Xtreak9c3f2842019-02-26 03:16:34 +05302086 def test_parent_propagation_with_create_autospec(self):
2087
Chris Withersadbf1782019-05-01 23:04:04 +01002088 def foo(a, b): pass
Xtreak9c3f2842019-02-26 03:16:34 +05302089
2090 mock = Mock()
2091 mock.child = create_autospec(foo)
2092 mock.child(1, 2)
2093
2094 self.assertRaises(TypeError, mock.child, 1)
2095 self.assertEqual(mock.mock_calls, [call.child(1, 2)])
Xtreak7397cda2019-07-22 13:08:22 +05302096 self.assertIn('mock.child', repr(mock.child.mock))
2097
2098 def test_parent_propagation_with_autospec_attach_mock(self):
2099
2100 def foo(a, b): pass
2101
2102 parent = Mock()
2103 parent.attach_mock(create_autospec(foo, name='bar'), 'child')
2104 parent.child(1, 2)
2105
2106 self.assertRaises(TypeError, parent.child, 1)
2107 self.assertEqual(parent.child.mock_calls, [call.child(1, 2)])
2108 self.assertIn('mock.child', repr(parent.child.mock))
2109
Xtreak9c3f2842019-02-26 03:16:34 +05302110
Xtreak830b43d2019-04-14 00:42:33 +05302111 def test_isinstance_under_settrace(self):
2112 # bpo-36593 : __class__ is not set for a class that has __class__
2113 # property defined when it's used with sys.settrace(trace) set.
2114 # Delete the module to force reimport with tracing function set
2115 # restore the old reference later since there are other tests that are
2116 # dependent on unittest.mock.patch. In testpatch.PatchTest
2117 # test_patch_dict_test_prefix and test_patch_test_prefix not restoring
2118 # causes the objects patched to go out of sync
2119
2120 old_patch = unittest.mock.patch
2121
2122 # Directly using __setattr__ on unittest.mock causes current imported
2123 # reference to be updated. Use a lambda so that during cleanup the
2124 # re-imported new reference is updated.
2125 self.addCleanup(lambda patch: setattr(unittest.mock, 'patch', patch),
2126 old_patch)
2127
2128 with patch.dict('sys.modules'):
2129 del sys.modules['unittest.mock']
2130
Chris Withersadbf1782019-05-01 23:04:04 +01002131 # This trace will stop coverage being measured ;-)
2132 def trace(frame, event, arg): # pragma: no cover
Xtreak830b43d2019-04-14 00:42:33 +05302133 return trace
2134
Chris Withersadbf1782019-05-01 23:04:04 +01002135 self.addCleanup(sys.settrace, sys.gettrace())
Xtreak830b43d2019-04-14 00:42:33 +05302136 sys.settrace(trace)
Xtreak830b43d2019-04-14 00:42:33 +05302137
2138 from unittest.mock import (
2139 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
2140 )
2141
2142 mocks = [
Lisa Roachef048512019-09-23 20:49:40 -07002143 Mock, MagicMock, NonCallableMock, NonCallableMagicMock, AsyncMock
Xtreak830b43d2019-04-14 00:42:33 +05302144 ]
2145
2146 for mock in mocks:
2147 obj = mock(spec=Something)
2148 self.assertIsInstance(obj, Something)
2149
Xtreak9c3f2842019-02-26 03:16:34 +05302150
Michael Foord345266a2012-03-14 12:24:34 -07002151if __name__ == '__main__':
2152 unittest.main()