blob: 265eb1bba56caaedf132b8887148cef08db7275e [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
Michael Foord345266a2012-03-14 12:24:34 -0700399 def test_assert_called_once_with(self):
400 mock = Mock()
401 mock()
402
403 # Will raise an exception if it fails
404 mock.assert_called_once_with()
405
406 mock()
407 self.assertRaises(AssertionError, mock.assert_called_once_with)
408
409 mock.reset_mock()
410 self.assertRaises(AssertionError, mock.assert_called_once_with)
411
412 mock('foo', 'bar', baz=2)
413 mock.assert_called_once_with('foo', 'bar', baz=2)
414
415 mock.reset_mock()
416 mock('foo', 'bar', baz=2)
417 self.assertRaises(
418 AssertionError,
419 lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
420 )
421
Petter Strandmark47d94242018-10-28 21:37:10 +0100422 def test_assert_called_once_with_call_list(self):
423 m = Mock()
424 m(1)
425 m(2)
426 self.assertRaisesRegex(AssertionError,
427 re.escape("Calls: [call(1), call(2)]"),
428 lambda: m.assert_called_once_with(2))
429
Michael Foord345266a2012-03-14 12:24:34 -0700430
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100431 def test_assert_called_once_with_function_spec(self):
Chris Withersadbf1782019-05-01 23:04:04 +0100432 def f(a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100433
434 mock = Mock(spec=f)
435
436 mock(1, b=2, c=3)
437 mock.assert_called_once_with(1, 2, 3)
438 mock.assert_called_once_with(a=1, b=2, c=3)
439 self.assertRaises(AssertionError, mock.assert_called_once_with,
440 1, b=3, c=2)
441 # Expected call doesn't match the spec's signature
442 with self.assertRaises(AssertionError) as cm:
443 mock.assert_called_once_with(e=8)
444 self.assertIsInstance(cm.exception.__cause__, TypeError)
445 # Mock called more than once => always fails
446 mock(4, 5, 6)
447 self.assertRaises(AssertionError, mock.assert_called_once_with,
448 1, 2, 3)
449 self.assertRaises(AssertionError, mock.assert_called_once_with,
450 4, 5, 6)
451
452
Michael Foord345266a2012-03-14 12:24:34 -0700453 def test_attribute_access_returns_mocks(self):
454 mock = Mock()
455 something = mock.something
456 self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
457 self.assertEqual(mock.something, something,
458 "different attributes returned for same name")
459
460 # Usage example
461 mock = Mock()
462 mock.something.return_value = 3
463
464 self.assertEqual(mock.something(), 3, "method returned wrong value")
465 self.assertTrue(mock.something.called,
466 "method didn't record being called")
467
468
469 def test_attributes_have_name_and_parent_set(self):
470 mock = Mock()
471 something = mock.something
472
473 self.assertEqual(something._mock_name, "something",
474 "attribute name not set correctly")
475 self.assertEqual(something._mock_parent, mock,
476 "attribute parent not set correctly")
477
478
479 def test_method_calls_recorded(self):
480 mock = Mock()
481 mock.something(3, fish=None)
482 mock.something_else.something(6, cake=sentinel.Cake)
483
484 self.assertEqual(mock.something_else.method_calls,
485 [("something", (6,), {'cake': sentinel.Cake})],
486 "method calls not recorded correctly")
487 self.assertEqual(mock.method_calls, [
488 ("something", (3,), {'fish': None}),
489 ("something_else.something", (6,), {'cake': sentinel.Cake})
490 ],
491 "method calls not recorded correctly")
492
493
494 def test_method_calls_compare_easily(self):
495 mock = Mock()
496 mock.something()
497 self.assertEqual(mock.method_calls, [('something',)])
498 self.assertEqual(mock.method_calls, [('something', (), {})])
499
500 mock = Mock()
501 mock.something('different')
502 self.assertEqual(mock.method_calls, [('something', ('different',))])
503 self.assertEqual(mock.method_calls,
504 [('something', ('different',), {})])
505
506 mock = Mock()
507 mock.something(x=1)
508 self.assertEqual(mock.method_calls, [('something', {'x': 1})])
509 self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
510
511 mock = Mock()
512 mock.something('different', some='more')
513 self.assertEqual(mock.method_calls, [
514 ('something', ('different',), {'some': 'more'})
515 ])
516
517
518 def test_only_allowed_methods_exist(self):
519 for spec in ['something'], ('something',):
520 for arg in 'spec', 'spec_set':
521 mock = Mock(**{arg: spec})
522
523 # this should be allowed
524 mock.something
525 self.assertRaisesRegex(
526 AttributeError,
527 "Mock object has no attribute 'something_else'",
528 getattr, mock, 'something_else'
529 )
530
531
532 def test_from_spec(self):
533 class Something(object):
534 x = 3
535 __something__ = None
Chris Withersadbf1782019-05-01 23:04:04 +0100536 def y(self): pass
Michael Foord345266a2012-03-14 12:24:34 -0700537
538 def test_attributes(mock):
539 # should work
540 mock.x
541 mock.y
542 mock.__something__
543 self.assertRaisesRegex(
544 AttributeError,
545 "Mock object has no attribute 'z'",
546 getattr, mock, 'z'
547 )
548 self.assertRaisesRegex(
549 AttributeError,
550 "Mock object has no attribute '__foobar__'",
551 getattr, mock, '__foobar__'
552 )
553
554 test_attributes(Mock(spec=Something))
555 test_attributes(Mock(spec=Something()))
556
557
558 def test_wraps_calls(self):
559 real = Mock()
560
561 mock = Mock(wraps=real)
562 self.assertEqual(mock(), real())
563
564 real.reset_mock()
565
566 mock(1, 2, fish=3)
567 real.assert_called_with(1, 2, fish=3)
568
569
Mario Corcherof05df0a2018-12-08 11:25:02 +0000570 def test_wraps_prevents_automatic_creation_of_mocks(self):
571 class Real(object):
572 pass
573
574 real = Real()
575 mock = Mock(wraps=real)
576
577 self.assertRaises(AttributeError, lambda: mock.new_attr())
578
579
Michael Foord345266a2012-03-14 12:24:34 -0700580 def test_wraps_call_with_nondefault_return_value(self):
581 real = Mock()
582
583 mock = Mock(wraps=real)
584 mock.return_value = 3
585
586 self.assertEqual(mock(), 3)
587 self.assertFalse(real.called)
588
589
590 def test_wraps_attributes(self):
591 class Real(object):
592 attribute = Mock()
593
594 real = Real()
595
596 mock = Mock(wraps=real)
597 self.assertEqual(mock.attribute(), real.attribute())
598 self.assertRaises(AttributeError, lambda: mock.fish)
599
600 self.assertNotEqual(mock.attribute, real.attribute)
601 result = mock.attribute.frog(1, 2, fish=3)
602 Real.attribute.frog.assert_called_with(1, 2, fish=3)
603 self.assertEqual(result, Real.attribute.frog())
604
605
Mario Corcherof05df0a2018-12-08 11:25:02 +0000606 def test_customize_wrapped_object_with_side_effect_iterable_with_default(self):
607 class Real(object):
608 def method(self):
609 return sentinel.ORIGINAL_VALUE
610
611 real = Real()
612 mock = Mock(wraps=real)
613 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
614
615 self.assertEqual(mock.method(), sentinel.VALUE1)
616 self.assertEqual(mock.method(), sentinel.ORIGINAL_VALUE)
617 self.assertRaises(StopIteration, mock.method)
618
619
620 def test_customize_wrapped_object_with_side_effect_iterable(self):
621 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100622 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000623
624 real = Real()
625 mock = Mock(wraps=real)
626 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
627
628 self.assertEqual(mock.method(), sentinel.VALUE1)
629 self.assertEqual(mock.method(), sentinel.VALUE2)
630 self.assertRaises(StopIteration, mock.method)
631
632
633 def test_customize_wrapped_object_with_side_effect_exception(self):
634 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100635 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000636
637 real = Real()
638 mock = Mock(wraps=real)
639 mock.method.side_effect = RuntimeError
640
641 self.assertRaises(RuntimeError, mock.method)
642
643
644 def test_customize_wrapped_object_with_side_effect_function(self):
645 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100646 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000647 def side_effect():
648 return sentinel.VALUE
649
650 real = Real()
651 mock = Mock(wraps=real)
652 mock.method.side_effect = side_effect
653
654 self.assertEqual(mock.method(), sentinel.VALUE)
655
656
657 def test_customize_wrapped_object_with_return_value(self):
658 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100659 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000660
661 real = Real()
662 mock = Mock(wraps=real)
663 mock.method.return_value = sentinel.VALUE
664
665 self.assertEqual(mock.method(), sentinel.VALUE)
666
667
668 def test_customize_wrapped_object_with_return_value_and_side_effect(self):
669 # side_effect should always take precedence over return_value.
670 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100671 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000672
673 real = Real()
674 mock = Mock(wraps=real)
675 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
676 mock.method.return_value = sentinel.WRONG_VALUE
677
678 self.assertEqual(mock.method(), sentinel.VALUE1)
679 self.assertEqual(mock.method(), sentinel.VALUE2)
680 self.assertRaises(StopIteration, mock.method)
681
682
683 def test_customize_wrapped_object_with_return_value_and_side_effect2(self):
684 # side_effect can return DEFAULT to default to return_value
685 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100686 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000687
688 real = Real()
689 mock = Mock(wraps=real)
690 mock.method.side_effect = lambda: DEFAULT
691 mock.method.return_value = sentinel.VALUE
692
693 self.assertEqual(mock.method(), sentinel.VALUE)
694
695
696 def test_customize_wrapped_object_with_return_value_and_side_effect_default(self):
697 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100698 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000699
700 real = Real()
701 mock = Mock(wraps=real)
702 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
703 mock.method.return_value = sentinel.RETURN
704
705 self.assertEqual(mock.method(), sentinel.VALUE1)
706 self.assertEqual(mock.method(), sentinel.RETURN)
707 self.assertRaises(StopIteration, mock.method)
708
709
Michael Foord345266a2012-03-14 12:24:34 -0700710 def test_exceptional_side_effect(self):
711 mock = Mock(side_effect=AttributeError)
712 self.assertRaises(AttributeError, mock)
713
714 mock = Mock(side_effect=AttributeError('foo'))
715 self.assertRaises(AttributeError, mock)
716
717
718 def test_baseexceptional_side_effect(self):
719 mock = Mock(side_effect=KeyboardInterrupt)
720 self.assertRaises(KeyboardInterrupt, mock)
721
722 mock = Mock(side_effect=KeyboardInterrupt('foo'))
723 self.assertRaises(KeyboardInterrupt, mock)
724
725
726 def test_assert_called_with_message(self):
727 mock = Mock()
Susan Su2bdd5852019-02-13 18:22:29 -0800728 self.assertRaisesRegex(AssertionError, 'not called',
Michael Foord345266a2012-03-14 12:24:34 -0700729 mock.assert_called_with)
730
731
Michael Foord28d591c2012-09-28 16:15:22 +0100732 def test_assert_called_once_with_message(self):
733 mock = Mock(name='geoffrey')
734 self.assertRaisesRegex(AssertionError,
735 r"Expected 'geoffrey' to be called once\.",
736 mock.assert_called_once_with)
737
738
Michael Foord345266a2012-03-14 12:24:34 -0700739 def test__name__(self):
740 mock = Mock()
741 self.assertRaises(AttributeError, lambda: mock.__name__)
742
743 mock.__name__ = 'foo'
744 self.assertEqual(mock.__name__, 'foo')
745
746
747 def test_spec_list_subclass(self):
748 class Sub(list):
749 pass
750 mock = Mock(spec=Sub(['foo']))
751
752 mock.append(3)
753 mock.append.assert_called_with(3)
754 self.assertRaises(AttributeError, getattr, mock, 'foo')
755
756
757 def test_spec_class(self):
758 class X(object):
759 pass
760
761 mock = Mock(spec=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200762 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700763
764 mock = Mock(spec=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200765 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700766
767 self.assertIs(mock.__class__, X)
768 self.assertEqual(Mock().__class__.__name__, 'Mock')
769
770 mock = Mock(spec_set=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200771 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700772
773 mock = Mock(spec_set=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200774 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700775
776
Chris Withersadbf1782019-05-01 23:04:04 +0100777 def test_spec_class_no_object_base(self):
778 class X:
779 pass
780
781 mock = Mock(spec=X)
782 self.assertIsInstance(mock, X)
783
784 mock = Mock(spec=X())
785 self.assertIsInstance(mock, X)
786
787 self.assertIs(mock.__class__, X)
788 self.assertEqual(Mock().__class__.__name__, 'Mock')
789
790 mock = Mock(spec_set=X)
791 self.assertIsInstance(mock, X)
792
793 mock = Mock(spec_set=X())
794 self.assertIsInstance(mock, X)
795
796
Michael Foord345266a2012-03-14 12:24:34 -0700797 def test_setting_attribute_with_spec_set(self):
798 class X(object):
799 y = 3
800
801 mock = Mock(spec=X)
802 mock.x = 'foo'
803
804 mock = Mock(spec_set=X)
805 def set_attr():
806 mock.x = 'foo'
807
808 mock.y = 'foo'
809 self.assertRaises(AttributeError, set_attr)
810
811
812 def test_copy(self):
813 current = sys.getrecursionlimit()
814 self.addCleanup(sys.setrecursionlimit, current)
815
816 # can't use sys.maxint as this doesn't exist in Python 3
817 sys.setrecursionlimit(int(10e8))
818 # this segfaults without the fix in place
819 copy.copy(Mock())
820
821
822 def test_subclass_with_properties(self):
823 class SubClass(Mock):
824 def _get(self):
825 return 3
826 def _set(self, value):
827 raise NameError('strange error')
828 some_attribute = property(_get, _set)
829
830 s = SubClass(spec_set=SubClass)
831 self.assertEqual(s.some_attribute, 3)
832
833 def test():
834 s.some_attribute = 3
835 self.assertRaises(NameError, test)
836
837 def test():
838 s.foo = 'bar'
839 self.assertRaises(AttributeError, test)
840
841
842 def test_setting_call(self):
843 mock = Mock()
844 def __call__(self, a):
845 return self._mock_call(a)
846
847 type(mock).__call__ = __call__
848 mock('one')
849 mock.assert_called_with('one')
850
851 self.assertRaises(TypeError, mock, 'one', 'two')
852
853
854 def test_dir(self):
855 mock = Mock()
856 attrs = set(dir(mock))
857 type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
858
859 # all public attributes from the type are included
860 self.assertEqual(set(), type_attrs - attrs)
861
862 # creates these attributes
863 mock.a, mock.b
864 self.assertIn('a', dir(mock))
865 self.assertIn('b', dir(mock))
866
867 # instance attributes
868 mock.c = mock.d = None
869 self.assertIn('c', dir(mock))
870 self.assertIn('d', dir(mock))
871
872 # magic methods
873 mock.__iter__ = lambda s: iter([])
874 self.assertIn('__iter__', dir(mock))
875
876
877 def test_dir_from_spec(self):
878 mock = Mock(spec=unittest.TestCase)
879 testcase_attrs = set(dir(unittest.TestCase))
880 attrs = set(dir(mock))
881
882 # all attributes from the spec are included
883 self.assertEqual(set(), testcase_attrs - attrs)
884
885 # shadow a sys attribute
886 mock.version = 3
887 self.assertEqual(dir(mock).count('version'), 1)
888
889
890 def test_filter_dir(self):
891 patcher = patch.object(mock, 'FILTER_DIR', False)
892 patcher.start()
893 try:
894 attrs = set(dir(Mock()))
895 type_attrs = set(dir(Mock))
896
897 # ALL attributes from the type are included
898 self.assertEqual(set(), type_attrs - attrs)
899 finally:
900 patcher.stop()
901
902
Mario Corchero0df635c2019-04-30 19:56:36 +0100903 def test_dir_does_not_include_deleted_attributes(self):
904 mock = Mock()
905 mock.child.return_value = 1
906
907 self.assertIn('child', dir(mock))
908 del mock.child
909 self.assertNotIn('child', dir(mock))
910
911
Michael Foord345266a2012-03-14 12:24:34 -0700912 def test_configure_mock(self):
913 mock = Mock(foo='bar')
914 self.assertEqual(mock.foo, 'bar')
915
916 mock = MagicMock(foo='bar')
917 self.assertEqual(mock.foo, 'bar')
918
919 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
920 'foo': MagicMock()}
921 mock = Mock(**kwargs)
922 self.assertRaises(KeyError, mock)
923 self.assertEqual(mock.foo.bar(), 33)
924 self.assertIsInstance(mock.foo, MagicMock)
925
926 mock = Mock()
927 mock.configure_mock(**kwargs)
928 self.assertRaises(KeyError, mock)
929 self.assertEqual(mock.foo.bar(), 33)
930 self.assertIsInstance(mock.foo, MagicMock)
931
932
933 def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
934 # needed because assertRaisesRegex doesn't work easily with newlines
Chris Withersadbf1782019-05-01 23:04:04 +0100935 with self.assertRaises(exception) as context:
Michael Foord345266a2012-03-14 12:24:34 -0700936 func(*args, **kwargs)
Chris Withersadbf1782019-05-01 23:04:04 +0100937 msg = str(context.exception)
Michael Foord345266a2012-03-14 12:24:34 -0700938 self.assertEqual(msg, message)
939
940
941 def test_assert_called_with_failure_message(self):
942 mock = NonCallableMock()
943
Susan Su2bdd5852019-02-13 18:22:29 -0800944 actual = 'not called.'
Michael Foord345266a2012-03-14 12:24:34 -0700945 expected = "mock(1, '2', 3, bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -0800946 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700947 self.assertRaisesWithMsg(
Susan Su2bdd5852019-02-13 18:22:29 -0800948 AssertionError, message % (expected, actual),
Michael Foord345266a2012-03-14 12:24:34 -0700949 mock.assert_called_with, 1, '2', 3, bar='foo'
950 )
951
952 mock.foo(1, '2', 3, foo='foo')
953
954
955 asserters = [
956 mock.foo.assert_called_with, mock.foo.assert_called_once_with
957 ]
958 for meth in asserters:
959 actual = "foo(1, '2', 3, foo='foo')"
960 expected = "foo(1, '2', 3, bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -0800961 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700962 self.assertRaisesWithMsg(
963 AssertionError, message % (expected, actual),
964 meth, 1, '2', 3, bar='foo'
965 )
966
967 # just kwargs
968 for meth in asserters:
969 actual = "foo(1, '2', 3, foo='foo')"
970 expected = "foo(bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -0800971 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700972 self.assertRaisesWithMsg(
973 AssertionError, message % (expected, actual),
974 meth, bar='foo'
975 )
976
977 # just args
978 for meth in asserters:
979 actual = "foo(1, '2', 3, foo='foo')"
980 expected = "foo(1, 2, 3)"
Susan Su2bdd5852019-02-13 18:22:29 -0800981 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700982 self.assertRaisesWithMsg(
983 AssertionError, message % (expected, actual),
984 meth, 1, 2, 3
985 )
986
987 # empty
988 for meth in asserters:
989 actual = "foo(1, '2', 3, foo='foo')"
990 expected = "foo()"
Susan Su2bdd5852019-02-13 18:22:29 -0800991 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700992 self.assertRaisesWithMsg(
993 AssertionError, message % (expected, actual), meth
994 )
995
996
997 def test_mock_calls(self):
998 mock = MagicMock()
999
1000 # need to do this because MagicMock.mock_calls used to just return
1001 # a MagicMock which also returned a MagicMock when __eq__ was called
1002 self.assertIs(mock.mock_calls == [], True)
1003
1004 mock = MagicMock()
1005 mock()
1006 expected = [('', (), {})]
1007 self.assertEqual(mock.mock_calls, expected)
1008
1009 mock.foo()
1010 expected.append(call.foo())
1011 self.assertEqual(mock.mock_calls, expected)
1012 # intermediate mock_calls work too
1013 self.assertEqual(mock.foo.mock_calls, [('', (), {})])
1014
1015 mock = MagicMock()
1016 mock().foo(1, 2, 3, a=4, b=5)
1017 expected = [
1018 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
1019 ]
1020 self.assertEqual(mock.mock_calls, expected)
1021 self.assertEqual(mock.return_value.foo.mock_calls,
1022 [('', (1, 2, 3), dict(a=4, b=5))])
1023 self.assertEqual(mock.return_value.mock_calls,
1024 [('foo', (1, 2, 3), dict(a=4, b=5))])
1025
1026 mock = MagicMock()
1027 mock().foo.bar().baz()
1028 expected = [
1029 ('', (), {}), ('().foo.bar', (), {}),
1030 ('().foo.bar().baz', (), {})
1031 ]
1032 self.assertEqual(mock.mock_calls, expected)
1033 self.assertEqual(mock().mock_calls,
1034 call.foo.bar().baz().call_list())
1035
1036 for kwargs in dict(), dict(name='bar'):
1037 mock = MagicMock(**kwargs)
1038 int(mock.foo)
1039 expected = [('foo.__int__', (), {})]
1040 self.assertEqual(mock.mock_calls, expected)
1041
1042 mock = MagicMock(**kwargs)
1043 mock.a()()
1044 expected = [('a', (), {}), ('a()', (), {})]
1045 self.assertEqual(mock.mock_calls, expected)
1046 self.assertEqual(mock.a().mock_calls, [call()])
1047
1048 mock = MagicMock(**kwargs)
1049 mock(1)(2)(3)
1050 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
1051 self.assertEqual(mock().mock_calls, call(2)(3).call_list())
1052 self.assertEqual(mock()().mock_calls, call(3).call_list())
1053
1054 mock = MagicMock(**kwargs)
1055 mock(1)(2)(3).a.b.c(4)
1056 self.assertEqual(mock.mock_calls,
1057 call(1)(2)(3).a.b.c(4).call_list())
1058 self.assertEqual(mock().mock_calls,
1059 call(2)(3).a.b.c(4).call_list())
1060 self.assertEqual(mock()().mock_calls,
1061 call(3).a.b.c(4).call_list())
1062
1063 mock = MagicMock(**kwargs)
1064 int(mock().foo.bar().baz())
1065 last_call = ('().foo.bar().baz().__int__', (), {})
1066 self.assertEqual(mock.mock_calls[-1], last_call)
1067 self.assertEqual(mock().mock_calls,
1068 call.foo.bar().baz().__int__().call_list())
1069 self.assertEqual(mock().foo.bar().mock_calls,
1070 call.baz().__int__().call_list())
1071 self.assertEqual(mock().foo.bar().baz.mock_calls,
1072 call().__int__().call_list())
1073
1074
Chris Withers8ca0fa92018-12-03 21:31:37 +00001075 def test_child_mock_call_equal(self):
1076 m = Mock()
1077 result = m()
1078 result.wibble()
1079 # parent looks like this:
1080 self.assertEqual(m.mock_calls, [call(), call().wibble()])
1081 # but child should look like this:
1082 self.assertEqual(result.mock_calls, [call.wibble()])
1083
1084
1085 def test_mock_call_not_equal_leaf(self):
1086 m = Mock()
1087 m.foo().something()
1088 self.assertNotEqual(m.mock_calls[1], call.foo().different())
1089 self.assertEqual(m.mock_calls[0], call.foo())
1090
1091
1092 def test_mock_call_not_equal_non_leaf(self):
1093 m = Mock()
1094 m.foo().bar()
1095 self.assertNotEqual(m.mock_calls[1], call.baz().bar())
1096 self.assertNotEqual(m.mock_calls[0], call.baz())
1097
1098
1099 def test_mock_call_not_equal_non_leaf_params_different(self):
1100 m = Mock()
1101 m.foo(x=1).bar()
1102 # This isn't ideal, but there's no way to fix it without breaking backwards compatibility:
1103 self.assertEqual(m.mock_calls[1], call.foo(x=2).bar())
1104
1105
1106 def test_mock_call_not_equal_non_leaf_attr(self):
1107 m = Mock()
1108 m.foo.bar()
1109 self.assertNotEqual(m.mock_calls[0], call.baz.bar())
1110
1111
1112 def test_mock_call_not_equal_non_leaf_call_versus_attr(self):
1113 m = Mock()
1114 m.foo.bar()
1115 self.assertNotEqual(m.mock_calls[0], call.foo().bar())
1116
1117
1118 def test_mock_call_repr(self):
1119 m = Mock()
1120 m.foo().bar().baz.bob()
1121 self.assertEqual(repr(m.mock_calls[0]), 'call.foo()')
1122 self.assertEqual(repr(m.mock_calls[1]), 'call.foo().bar()')
1123 self.assertEqual(repr(m.mock_calls[2]), 'call.foo().bar().baz.bob()')
1124
1125
Chris Withersadbf1782019-05-01 23:04:04 +01001126 def test_mock_call_repr_loop(self):
1127 m = Mock()
1128 m.foo = m
1129 repr(m.foo())
1130 self.assertRegex(repr(m.foo()), r"<Mock name='mock\(\)' id='\d+'>")
1131
1132
1133 def test_mock_calls_contains(self):
1134 m = Mock()
1135 self.assertFalse([call()] in m.mock_calls)
1136
1137
Michael Foord345266a2012-03-14 12:24:34 -07001138 def test_subclassing(self):
1139 class Subclass(Mock):
1140 pass
1141
1142 mock = Subclass()
1143 self.assertIsInstance(mock.foo, Subclass)
1144 self.assertIsInstance(mock(), Subclass)
1145
1146 class Subclass(Mock):
1147 def _get_child_mock(self, **kwargs):
1148 return Mock(**kwargs)
1149
1150 mock = Subclass()
1151 self.assertNotIsInstance(mock.foo, Subclass)
1152 self.assertNotIsInstance(mock(), Subclass)
1153
1154
1155 def test_arg_lists(self):
1156 mocks = [
1157 Mock(),
1158 MagicMock(),
1159 NonCallableMock(),
1160 NonCallableMagicMock()
1161 ]
1162
1163 def assert_attrs(mock):
1164 names = 'call_args_list', 'method_calls', 'mock_calls'
1165 for name in names:
1166 attr = getattr(mock, name)
1167 self.assertIsInstance(attr, _CallList)
1168 self.assertIsInstance(attr, list)
1169 self.assertEqual(attr, [])
1170
1171 for mock in mocks:
1172 assert_attrs(mock)
1173
1174 if callable(mock):
1175 mock()
1176 mock(1, 2)
1177 mock(a=3)
1178
1179 mock.reset_mock()
1180 assert_attrs(mock)
1181
1182 mock.foo()
1183 mock.foo.bar(1, a=3)
1184 mock.foo(1).bar().baz(3)
1185
1186 mock.reset_mock()
1187 assert_attrs(mock)
1188
1189
1190 def test_call_args_two_tuple(self):
1191 mock = Mock()
1192 mock(1, a=3)
1193 mock(2, b=4)
1194
1195 self.assertEqual(len(mock.call_args), 2)
Kumar Akshayb0df45e2019-03-22 13:40:40 +05301196 self.assertEqual(mock.call_args.args, (2,))
1197 self.assertEqual(mock.call_args.kwargs, dict(b=4))
Michael Foord345266a2012-03-14 12:24:34 -07001198
1199 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
1200 for expected, call_args in zip(expected_list, mock.call_args_list):
1201 self.assertEqual(len(call_args), 2)
1202 self.assertEqual(expected[0], call_args[0])
1203 self.assertEqual(expected[1], call_args[1])
1204
1205
1206 def test_side_effect_iterator(self):
1207 mock = Mock(side_effect=iter([1, 2, 3]))
1208 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1209 self.assertRaises(StopIteration, mock)
1210
1211 mock = MagicMock(side_effect=['a', 'b', 'c'])
1212 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1213 self.assertRaises(StopIteration, mock)
1214
1215 mock = Mock(side_effect='ghi')
1216 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
1217 self.assertRaises(StopIteration, mock)
1218
1219 class Foo(object):
1220 pass
1221 mock = MagicMock(side_effect=Foo)
1222 self.assertIsInstance(mock(), Foo)
1223
1224 mock = Mock(side_effect=Iter())
1225 self.assertEqual([mock(), mock(), mock(), mock()],
1226 ['this', 'is', 'an', 'iter'])
1227 self.assertRaises(StopIteration, mock)
1228
1229
Michael Foord2cd48732012-04-21 15:52:11 +01001230 def test_side_effect_iterator_exceptions(self):
1231 for Klass in Mock, MagicMock:
1232 iterable = (ValueError, 3, KeyError, 6)
1233 m = Klass(side_effect=iterable)
1234 self.assertRaises(ValueError, m)
1235 self.assertEqual(m(), 3)
1236 self.assertRaises(KeyError, m)
1237 self.assertEqual(m(), 6)
1238
1239
Michael Foord345266a2012-03-14 12:24:34 -07001240 def test_side_effect_setting_iterator(self):
1241 mock = Mock()
1242 mock.side_effect = iter([1, 2, 3])
1243 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1244 self.assertRaises(StopIteration, mock)
1245 side_effect = mock.side_effect
1246 self.assertIsInstance(side_effect, type(iter([])))
1247
1248 mock.side_effect = ['a', 'b', 'c']
1249 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1250 self.assertRaises(StopIteration, mock)
1251 side_effect = mock.side_effect
1252 self.assertIsInstance(side_effect, type(iter([])))
1253
1254 this_iter = Iter()
1255 mock.side_effect = this_iter
1256 self.assertEqual([mock(), mock(), mock(), mock()],
1257 ['this', 'is', 'an', 'iter'])
1258 self.assertRaises(StopIteration, mock)
1259 self.assertIs(mock.side_effect, this_iter)
1260
Andrew Svetlov8b2cd752013-04-07 16:42:24 +03001261 def test_side_effect_iterator_default(self):
1262 mock = Mock(return_value=2)
1263 mock.side_effect = iter([1, DEFAULT])
1264 self.assertEqual([mock(), mock()], [1, 2])
Michael Foord345266a2012-03-14 12:24:34 -07001265
1266 def test_assert_has_calls_any_order(self):
1267 mock = Mock()
1268 mock(1, 2)
1269 mock(a=3)
1270 mock(3, 4)
1271 mock(b=6)
1272 mock(b=6)
1273
1274 kalls = [
1275 call(1, 2), ({'a': 3},),
1276 ((3, 4),), ((), {'a': 3}),
1277 ('', (1, 2)), ('', {'a': 3}),
1278 ('', (1, 2), {}), ('', (), {'a': 3})
1279 ]
1280 for kall in kalls:
1281 mock.assert_has_calls([kall], any_order=True)
1282
1283 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
1284 self.assertRaises(
1285 AssertionError, mock.assert_has_calls,
1286 [kall], any_order=True
1287 )
1288
1289 kall_lists = [
1290 [call(1, 2), call(b=6)],
1291 [call(3, 4), call(1, 2)],
1292 [call(b=6), call(b=6)],
1293 ]
1294
1295 for kall_list in kall_lists:
1296 mock.assert_has_calls(kall_list, any_order=True)
1297
1298 kall_lists = [
1299 [call(b=6), call(b=6), call(b=6)],
1300 [call(1, 2), call(1, 2)],
1301 [call(3, 4), call(1, 2), call(5, 7)],
1302 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
1303 ]
1304 for kall_list in kall_lists:
1305 self.assertRaises(
1306 AssertionError, mock.assert_has_calls,
1307 kall_list, any_order=True
1308 )
1309
1310 def test_assert_has_calls(self):
1311 kalls1 = [
1312 call(1, 2), ({'a': 3},),
1313 ((3, 4),), call(b=6),
1314 ('', (1,), {'b': 6}),
1315 ]
1316 kalls2 = [call.foo(), call.bar(1)]
1317 kalls2.extend(call.spam().baz(a=3).call_list())
1318 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
1319
1320 mocks = []
1321 for mock in Mock(), MagicMock():
1322 mock(1, 2)
1323 mock(a=3)
1324 mock(3, 4)
1325 mock(b=6)
1326 mock(1, b=6)
1327 mocks.append((mock, kalls1))
1328
1329 mock = Mock()
1330 mock.foo()
1331 mock.bar(1)
1332 mock.spam().baz(a=3)
1333 mock.bam(set(), foo={}).fish([1])
1334 mocks.append((mock, kalls2))
1335
1336 for mock, kalls in mocks:
1337 for i in range(len(kalls)):
1338 for step in 1, 2, 3:
1339 these = kalls[i:i+step]
1340 mock.assert_has_calls(these)
1341
1342 if len(these) > 1:
1343 self.assertRaises(
1344 AssertionError,
1345 mock.assert_has_calls,
1346 list(reversed(these))
1347 )
1348
1349
Xtreakc9612782019-08-29 11:39:01 +05301350 def test_assert_has_calls_nested_spec(self):
1351 class Something:
1352
1353 def __init__(self): pass
1354 def meth(self, a, b, c, d=None): pass
1355
1356 class Foo:
1357
1358 def __init__(self, a): pass
1359 def meth1(self, a, b): pass
1360
1361 mock_class = create_autospec(Something)
1362
1363 for m in [mock_class, mock_class()]:
1364 m.meth(1, 2, 3, d=1)
1365 m.assert_has_calls([call.meth(1, 2, 3, d=1)])
1366 m.assert_has_calls([call.meth(1, 2, 3, 1)])
1367
1368 mock_class.reset_mock()
1369
1370 for m in [mock_class, mock_class()]:
1371 self.assertRaises(AssertionError, m.assert_has_calls, [call.Foo()])
1372 m.Foo(1).meth1(1, 2)
1373 m.assert_has_calls([call.Foo(1), call.Foo(1).meth1(1, 2)])
1374 m.Foo.assert_has_calls([call(1), call().meth1(1, 2)])
1375
1376 mock_class.reset_mock()
1377
1378 invalid_calls = [call.meth(1),
1379 call.non_existent(1),
1380 call.Foo().non_existent(1),
1381 call.Foo().meth(1, 2, 3, 4)]
1382
1383 for kall in invalid_calls:
1384 self.assertRaises(AssertionError,
1385 mock_class.assert_has_calls,
1386 [kall]
1387 )
1388
1389
1390 def test_assert_has_calls_nested_without_spec(self):
1391 m = MagicMock()
1392 m().foo().bar().baz()
1393 m.one().two().three()
1394 calls = call.one().two().three().call_list()
1395 m.assert_has_calls(calls)
1396
1397
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001398 def test_assert_has_calls_with_function_spec(self):
Chris Withersadbf1782019-05-01 23:04:04 +01001399 def f(a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001400
1401 mock = Mock(spec=f)
1402
1403 mock(1, b=2, c=3)
1404 mock(4, 5, c=6, d=7)
1405 mock(10, 11, c=12)
1406 calls = [
1407 ('', (1, 2, 3), {}),
1408 ('', (4, 5, 6), {'d': 7}),
1409 ((10, 11, 12), {}),
1410 ]
1411 mock.assert_has_calls(calls)
1412 mock.assert_has_calls(calls, any_order=True)
1413 mock.assert_has_calls(calls[1:])
1414 mock.assert_has_calls(calls[1:], any_order=True)
1415 mock.assert_has_calls(calls[:-1])
1416 mock.assert_has_calls(calls[:-1], any_order=True)
1417 # Reversed order
1418 calls = list(reversed(calls))
1419 with self.assertRaises(AssertionError):
1420 mock.assert_has_calls(calls)
1421 mock.assert_has_calls(calls, any_order=True)
1422 with self.assertRaises(AssertionError):
1423 mock.assert_has_calls(calls[1:])
1424 mock.assert_has_calls(calls[1:], any_order=True)
1425 with self.assertRaises(AssertionError):
1426 mock.assert_has_calls(calls[:-1])
1427 mock.assert_has_calls(calls[:-1], any_order=True)
1428
1429
Michael Foord345266a2012-03-14 12:24:34 -07001430 def test_assert_any_call(self):
1431 mock = Mock()
1432 mock(1, 2)
1433 mock(a=3)
1434 mock(1, b=6)
1435
1436 mock.assert_any_call(1, 2)
1437 mock.assert_any_call(a=3)
1438 mock.assert_any_call(1, b=6)
1439
1440 self.assertRaises(
1441 AssertionError,
1442 mock.assert_any_call
1443 )
1444 self.assertRaises(
1445 AssertionError,
1446 mock.assert_any_call,
1447 1, 3
1448 )
1449 self.assertRaises(
1450 AssertionError,
1451 mock.assert_any_call,
1452 a=4
1453 )
1454
1455
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001456 def test_assert_any_call_with_function_spec(self):
Chris Withersadbf1782019-05-01 23:04:04 +01001457 def f(a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001458
1459 mock = Mock(spec=f)
1460
1461 mock(1, b=2, c=3)
1462 mock(4, 5, c=6, d=7)
1463 mock.assert_any_call(1, 2, 3)
1464 mock.assert_any_call(a=1, b=2, c=3)
1465 mock.assert_any_call(4, 5, 6, 7)
1466 mock.assert_any_call(a=4, b=5, c=6, d=7)
1467 self.assertRaises(AssertionError, mock.assert_any_call,
1468 1, b=3, c=2)
1469 # Expected call doesn't match the spec's signature
1470 with self.assertRaises(AssertionError) as cm:
1471 mock.assert_any_call(e=8)
1472 self.assertIsInstance(cm.exception.__cause__, TypeError)
1473
1474
Michael Foord345266a2012-03-14 12:24:34 -07001475 def test_mock_calls_create_autospec(self):
Chris Withersadbf1782019-05-01 23:04:04 +01001476 def f(a, b): pass
Michael Foord345266a2012-03-14 12:24:34 -07001477 obj = Iter()
1478 obj.f = f
1479
1480 funcs = [
1481 create_autospec(f),
1482 create_autospec(obj).f
1483 ]
1484 for func in funcs:
1485 func(1, 2)
1486 func(3, 4)
1487
1488 self.assertEqual(
1489 func.mock_calls, [call(1, 2), call(3, 4)]
1490 )
1491
Kushal Das484f8a82014-04-16 01:05:50 +05301492 #Issue21222
1493 def test_create_autospec_with_name(self):
1494 m = mock.create_autospec(object(), name='sweet_func')
1495 self.assertIn('sweet_func', repr(m))
Michael Foord345266a2012-03-14 12:24:34 -07001496
Xtreak9b218562019-04-22 08:00:23 +05301497 #Issue23078
1498 def test_create_autospec_classmethod_and_staticmethod(self):
1499 class TestClass:
1500 @classmethod
Chris Withersadbf1782019-05-01 23:04:04 +01001501 def class_method(cls): pass
Xtreak9b218562019-04-22 08:00:23 +05301502
1503 @staticmethod
Chris Withersadbf1782019-05-01 23:04:04 +01001504 def static_method(): pass
Xtreak9b218562019-04-22 08:00:23 +05301505 for method in ('class_method', 'static_method'):
1506 with self.subTest(method=method):
1507 mock_method = mock.create_autospec(getattr(TestClass, method))
1508 mock_method()
1509 mock_method.assert_called_once_with()
1510 self.assertRaises(TypeError, mock_method, 'extra_arg')
1511
Kushal Das8c145342014-04-16 23:32:21 +05301512 #Issue21238
1513 def test_mock_unsafe(self):
1514 m = Mock()
Zackery Spytzb9b08cd2019-05-08 11:32:24 -06001515 msg = "Attributes cannot start with 'assert' or 'assret'"
1516 with self.assertRaisesRegex(AttributeError, msg):
Kushal Das8c145342014-04-16 23:32:21 +05301517 m.assert_foo_call()
Zackery Spytzb9b08cd2019-05-08 11:32:24 -06001518 with self.assertRaisesRegex(AttributeError, msg):
Kushal Das8c145342014-04-16 23:32:21 +05301519 m.assret_foo_call()
1520 m = Mock(unsafe=True)
1521 m.assert_foo_call()
1522 m.assret_foo_call()
1523
Kushal Das8af9db32014-04-17 01:36:14 +05301524 #Issue21262
1525 def test_assert_not_called(self):
1526 m = Mock()
1527 m.hello.assert_not_called()
1528 m.hello()
1529 with self.assertRaises(AssertionError):
1530 m.hello.assert_not_called()
1531
Petter Strandmark47d94242018-10-28 21:37:10 +01001532 def test_assert_not_called_message(self):
1533 m = Mock()
1534 m(1, 2)
1535 self.assertRaisesRegex(AssertionError,
1536 re.escape("Calls: [call(1, 2)]"),
1537 m.assert_not_called)
1538
Victor Stinner2c2a4e62016-03-11 22:17:48 +01001539 def test_assert_called(self):
1540 m = Mock()
1541 with self.assertRaises(AssertionError):
1542 m.hello.assert_called()
1543 m.hello()
1544 m.hello.assert_called()
1545
1546 m.hello()
1547 m.hello.assert_called()
1548
1549 def test_assert_called_once(self):
1550 m = Mock()
1551 with self.assertRaises(AssertionError):
1552 m.hello.assert_called_once()
1553 m.hello()
1554 m.hello.assert_called_once()
1555
1556 m.hello()
1557 with self.assertRaises(AssertionError):
1558 m.hello.assert_called_once()
1559
Petter Strandmark47d94242018-10-28 21:37:10 +01001560 def test_assert_called_once_message(self):
1561 m = Mock()
1562 m(1, 2)
1563 m(3)
1564 self.assertRaisesRegex(AssertionError,
1565 re.escape("Calls: [call(1, 2), call(3)]"),
1566 m.assert_called_once)
1567
1568 def test_assert_called_once_message_not_called(self):
1569 m = Mock()
1570 with self.assertRaises(AssertionError) as e:
1571 m.assert_called_once()
1572 self.assertNotIn("Calls:", str(e.exception))
1573
Kushal Das047f14c2014-06-09 13:45:56 +05301574 #Issue21256 printout of keyword args should be in deterministic order
1575 def test_sorted_call_signature(self):
1576 m = Mock()
1577 m.hello(name='hello', daddy='hero')
1578 text = "call(daddy='hero', name='hello')"
R David Murray130a5662014-06-11 17:09:43 -04001579 self.assertEqual(repr(m.hello.call_args), text)
Kushal Das8af9db32014-04-17 01:36:14 +05301580
Kushal Dasa37b9582014-09-16 18:33:37 +05301581 #Issue21270 overrides tuple methods for mock.call objects
1582 def test_override_tuple_methods(self):
1583 c = call.count()
1584 i = call.index(132,'hello')
1585 m = Mock()
1586 m.count()
1587 m.index(132,"hello")
1588 self.assertEqual(m.method_calls[0], c)
1589 self.assertEqual(m.method_calls[1], i)
1590
Kushal Das9cd39a12016-06-02 10:20:16 -07001591 def test_reset_return_sideeffect(self):
1592 m = Mock(return_value=10, side_effect=[2,3])
1593 m.reset_mock(return_value=True, side_effect=True)
1594 self.assertIsInstance(m.return_value, Mock)
1595 self.assertEqual(m.side_effect, None)
1596
1597 def test_reset_return(self):
1598 m = Mock(return_value=10, side_effect=[2,3])
1599 m.reset_mock(return_value=True)
1600 self.assertIsInstance(m.return_value, Mock)
1601 self.assertNotEqual(m.side_effect, None)
1602
1603 def test_reset_sideeffect(self):
1604 m = Mock(return_value=10, side_effect=[2,3])
1605 m.reset_mock(side_effect=True)
1606 self.assertEqual(m.return_value, 10)
1607 self.assertEqual(m.side_effect, None)
1608
Michael Foord345266a2012-03-14 12:24:34 -07001609 def test_mock_add_spec(self):
1610 class _One(object):
1611 one = 1
1612 class _Two(object):
1613 two = 2
1614 class Anything(object):
1615 one = two = three = 'four'
1616
1617 klasses = [
1618 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1619 ]
1620 for Klass in list(klasses):
1621 klasses.append(lambda K=Klass: K(spec=Anything))
1622 klasses.append(lambda K=Klass: K(spec_set=Anything))
1623
1624 for Klass in klasses:
1625 for kwargs in dict(), dict(spec_set=True):
1626 mock = Klass()
1627 #no error
1628 mock.one, mock.two, mock.three
1629
1630 for One, Two in [(_One, _Two), (['one'], ['two'])]:
1631 for kwargs in dict(), dict(spec_set=True):
1632 mock.mock_add_spec(One, **kwargs)
1633
1634 mock.one
1635 self.assertRaises(
1636 AttributeError, getattr, mock, 'two'
1637 )
1638 self.assertRaises(
1639 AttributeError, getattr, mock, 'three'
1640 )
1641 if 'spec_set' in kwargs:
1642 self.assertRaises(
1643 AttributeError, setattr, mock, 'three', None
1644 )
1645
1646 mock.mock_add_spec(Two, **kwargs)
1647 self.assertRaises(
1648 AttributeError, getattr, mock, 'one'
1649 )
1650 mock.two
1651 self.assertRaises(
1652 AttributeError, getattr, mock, 'three'
1653 )
1654 if 'spec_set' in kwargs:
1655 self.assertRaises(
1656 AttributeError, setattr, mock, 'three', None
1657 )
1658 # note that creating a mock, setting an instance attribute, and
1659 # *then* setting a spec doesn't work. Not the intended use case
1660
1661
1662 def test_mock_add_spec_magic_methods(self):
1663 for Klass in MagicMock, NonCallableMagicMock:
1664 mock = Klass()
1665 int(mock)
1666
1667 mock.mock_add_spec(object)
1668 self.assertRaises(TypeError, int, mock)
1669
1670 mock = Klass()
1671 mock['foo']
1672 mock.__int__.return_value =4
1673
1674 mock.mock_add_spec(int)
1675 self.assertEqual(int(mock), 4)
1676 self.assertRaises(TypeError, lambda: mock['foo'])
1677
1678
1679 def test_adding_child_mock(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07001680 for Klass in (NonCallableMock, Mock, MagicMock, NonCallableMagicMock,
1681 AsyncMock):
Michael Foord345266a2012-03-14 12:24:34 -07001682 mock = Klass()
1683
1684 mock.foo = Mock()
1685 mock.foo()
1686
1687 self.assertEqual(mock.method_calls, [call.foo()])
1688 self.assertEqual(mock.mock_calls, [call.foo()])
1689
1690 mock = Klass()
1691 mock.bar = Mock(name='name')
1692 mock.bar()
1693 self.assertEqual(mock.method_calls, [])
1694 self.assertEqual(mock.mock_calls, [])
1695
1696 # mock with an existing _new_parent but no name
1697 mock = Klass()
1698 mock.baz = MagicMock()()
1699 mock.baz()
1700 self.assertEqual(mock.method_calls, [])
1701 self.assertEqual(mock.mock_calls, [])
1702
1703
1704 def test_adding_return_value_mock(self):
1705 for Klass in Mock, MagicMock:
1706 mock = Klass()
1707 mock.return_value = MagicMock()
1708
1709 mock()()
1710 self.assertEqual(mock.mock_calls, [call(), call()()])
1711
1712
1713 def test_manager_mock(self):
1714 class Foo(object):
1715 one = 'one'
1716 two = 'two'
1717 manager = Mock()
1718 p1 = patch.object(Foo, 'one')
1719 p2 = patch.object(Foo, 'two')
1720
1721 mock_one = p1.start()
1722 self.addCleanup(p1.stop)
1723 mock_two = p2.start()
1724 self.addCleanup(p2.stop)
1725
1726 manager.attach_mock(mock_one, 'one')
1727 manager.attach_mock(mock_two, 'two')
1728
1729 Foo.two()
1730 Foo.one()
1731
1732 self.assertEqual(manager.mock_calls, [call.two(), call.one()])
1733
1734
1735 def test_magic_methods_mock_calls(self):
1736 for Klass in Mock, MagicMock:
1737 m = Klass()
1738 m.__int__ = Mock(return_value=3)
1739 m.__float__ = MagicMock(return_value=3.0)
1740 int(m)
1741 float(m)
1742
1743 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
1744 self.assertEqual(m.method_calls, [])
1745
Robert Collins5329aaa2015-07-17 20:08:45 +12001746 def test_mock_open_reuse_issue_21750(self):
1747 mocked_open = mock.mock_open(read_data='data')
1748 f1 = mocked_open('a-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001749 f1_data = f1.read()
Robert Collins5329aaa2015-07-17 20:08:45 +12001750 f2 = mocked_open('another-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001751 f2_data = f2.read()
1752 self.assertEqual(f1_data, f2_data)
1753
Tony Flury20870232018-09-12 23:21:16 +01001754 def test_mock_open_dunder_iter_issue(self):
1755 # Test dunder_iter method generates the expected result and
1756 # consumes the iterator.
1757 mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue')
1758 f1 = mocked_open('a-name')
1759 lines = [line for line in f1]
1760 self.assertEqual(lines[0], 'Remarkable\n')
1761 self.assertEqual(lines[1], 'Norwegian Blue')
1762 self.assertEqual(list(f1), [])
1763
Damien Nadé394119a2019-05-23 12:03:25 +02001764 def test_mock_open_using_next(self):
1765 mocked_open = mock.mock_open(read_data='1st line\n2nd line\n3rd line')
1766 f1 = mocked_open('a-name')
1767 line1 = next(f1)
1768 line2 = f1.__next__()
1769 lines = [line for line in f1]
1770 self.assertEqual(line1, '1st line\n')
1771 self.assertEqual(line2, '2nd line\n')
1772 self.assertEqual(lines[0], '3rd line')
1773 self.assertEqual(list(f1), [])
1774 with self.assertRaises(StopIteration):
1775 next(f1)
1776
Robert Collinsca647ef2015-07-24 03:48:20 +12001777 def test_mock_open_write(self):
1778 # Test exception in file writing write()
1779 mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
1780 with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
1781 mock_filehandle = mock_namedtemp.return_value
1782 mock_write = mock_filehandle.write
1783 mock_write.side_effect = OSError('Test 2 Error')
1784 def attempt():
1785 tempfile.NamedTemporaryFile().write('asd')
1786 self.assertRaises(OSError, attempt)
1787
1788 def test_mock_open_alter_readline(self):
1789 mopen = mock.mock_open(read_data='foo\nbarn')
1790 mopen.return_value.readline.side_effect = lambda *args:'abc'
1791 first = mopen().readline()
1792 second = mopen().readline()
1793 self.assertEqual('abc', first)
1794 self.assertEqual('abc', second)
Michael Foord345266a2012-03-14 12:24:34 -07001795
Robert Collins9549a3e2016-05-16 15:22:01 +12001796 def test_mock_open_after_eof(self):
1797 # read, readline and readlines should work after end of file.
1798 _open = mock.mock_open(read_data='foo')
1799 h = _open('bar')
1800 h.read()
1801 self.assertEqual('', h.read())
1802 self.assertEqual('', h.read())
1803 self.assertEqual('', h.readline())
1804 self.assertEqual('', h.readline())
1805 self.assertEqual([], h.readlines())
1806 self.assertEqual([], h.readlines())
1807
Michael Foord345266a2012-03-14 12:24:34 -07001808 def test_mock_parents(self):
1809 for Klass in Mock, MagicMock:
1810 m = Klass()
1811 original_repr = repr(m)
1812 m.return_value = m
1813 self.assertIs(m(), m)
1814 self.assertEqual(repr(m), original_repr)
1815
1816 m.reset_mock()
1817 self.assertIs(m(), m)
1818 self.assertEqual(repr(m), original_repr)
1819
1820 m = Klass()
1821 m.b = m.a
1822 self.assertIn("name='mock.a'", repr(m.b))
1823 self.assertIn("name='mock.a'", repr(m.a))
1824 m.reset_mock()
1825 self.assertIn("name='mock.a'", repr(m.b))
1826 self.assertIn("name='mock.a'", repr(m.a))
1827
1828 m = Klass()
1829 original_repr = repr(m)
1830 m.a = m()
1831 m.a.return_value = m
1832
1833 self.assertEqual(repr(m), original_repr)
1834 self.assertEqual(repr(m.a()), original_repr)
1835
1836
1837 def test_attach_mock(self):
1838 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1839 for Klass in classes:
1840 for Klass2 in classes:
1841 m = Klass()
1842
1843 m2 = Klass2(name='foo')
1844 m.attach_mock(m2, 'bar')
1845
1846 self.assertIs(m.bar, m2)
1847 self.assertIn("name='mock.bar'", repr(m2))
1848
1849 m.bar.baz(1)
1850 self.assertEqual(m.mock_calls, [call.bar.baz(1)])
1851 self.assertEqual(m.method_calls, [call.bar.baz(1)])
1852
1853
1854 def test_attach_mock_return_value(self):
1855 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1856 for Klass in Mock, MagicMock:
1857 for Klass2 in classes:
1858 m = Klass()
1859
1860 m2 = Klass2(name='foo')
1861 m.attach_mock(m2, 'return_value')
1862
1863 self.assertIs(m(), m2)
1864 self.assertIn("name='mock()'", repr(m2))
1865
1866 m2.foo()
1867 self.assertEqual(m.mock_calls, call().foo().call_list())
1868
1869
Xtreak7397cda2019-07-22 13:08:22 +05301870 def test_attach_mock_patch_autospec(self):
1871 parent = Mock()
1872
1873 with mock.patch(f'{__name__}.something', autospec=True) as mock_func:
1874 self.assertEqual(mock_func.mock._extract_mock_name(), 'something')
1875 parent.attach_mock(mock_func, 'child')
1876 parent.child(1)
1877 something(2)
1878 mock_func(3)
1879
1880 parent_calls = [call.child(1), call.child(2), call.child(3)]
1881 child_calls = [call(1), call(2), call(3)]
1882 self.assertEqual(parent.mock_calls, parent_calls)
1883 self.assertEqual(parent.child.mock_calls, child_calls)
1884 self.assertEqual(something.mock_calls, child_calls)
1885 self.assertEqual(mock_func.mock_calls, child_calls)
1886 self.assertIn('mock.child', repr(parent.child.mock))
1887 self.assertEqual(mock_func.mock._extract_mock_name(), 'mock.child')
1888
1889
Michael Foord345266a2012-03-14 12:24:34 -07001890 def test_attribute_deletion(self):
Michael Foord468ec342013-09-15 20:05:19 +12001891 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1892 NonCallableMock()):
Michael Foord345266a2012-03-14 12:24:34 -07001893 self.assertTrue(hasattr(mock, 'm'))
1894
1895 del mock.m
1896 self.assertFalse(hasattr(mock, 'm'))
1897
1898 del mock.f
1899 self.assertFalse(hasattr(mock, 'f'))
1900 self.assertRaises(AttributeError, getattr, mock, 'f')
1901
1902
Pablo Galindo222d3032019-01-21 08:57:46 +00001903 def test_mock_does_not_raise_on_repeated_attribute_deletion(self):
1904 # bpo-20239: Assigning and deleting twice an attribute raises.
1905 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1906 NonCallableMock()):
1907 mock.foo = 3
1908 self.assertTrue(hasattr(mock, 'foo'))
1909 self.assertEqual(mock.foo, 3)
1910
1911 del mock.foo
1912 self.assertFalse(hasattr(mock, 'foo'))
1913
1914 mock.foo = 4
1915 self.assertTrue(hasattr(mock, 'foo'))
1916 self.assertEqual(mock.foo, 4)
1917
1918 del mock.foo
1919 self.assertFalse(hasattr(mock, 'foo'))
1920
1921
1922 def test_mock_raises_when_deleting_nonexistent_attribute(self):
1923 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1924 NonCallableMock()):
1925 del mock.foo
1926 with self.assertRaises(AttributeError):
1927 del mock.foo
1928
1929
Xtreakedeca922018-12-01 15:33:54 +05301930 def test_reset_mock_does_not_raise_on_attr_deletion(self):
1931 # bpo-31177: reset_mock should not raise AttributeError when attributes
1932 # were deleted in a mock instance
1933 mock = Mock()
1934 mock.child = True
1935 del mock.child
1936 mock.reset_mock()
1937 self.assertFalse(hasattr(mock, 'child'))
1938
1939
Michael Foord345266a2012-03-14 12:24:34 -07001940 def test_class_assignable(self):
1941 for mock in Mock(), MagicMock():
1942 self.assertNotIsInstance(mock, int)
1943
1944 mock.__class__ = int
1945 self.assertIsInstance(mock, int)
1946 mock.foo
1947
Andrew Dunaie63e6172018-12-04 11:08:45 +02001948 def test_name_attribute_of_call(self):
1949 # bpo-35357: _Call should not disclose any attributes whose names
1950 # may clash with popular ones (such as ".name")
1951 self.assertIsNotNone(call.name)
1952 self.assertEqual(type(call.name), _Call)
1953 self.assertEqual(type(call.name().name), _Call)
1954
1955 def test_parent_attribute_of_call(self):
1956 # bpo-35357: _Call should not disclose any attributes whose names
1957 # may clash with popular ones (such as ".parent")
1958 self.assertIsNotNone(call.parent)
1959 self.assertEqual(type(call.parent), _Call)
1960 self.assertEqual(type(call.parent().parent), _Call)
1961
Michael Foord345266a2012-03-14 12:24:34 -07001962
Xtreak9c3f2842019-02-26 03:16:34 +05301963 def test_parent_propagation_with_create_autospec(self):
1964
Chris Withersadbf1782019-05-01 23:04:04 +01001965 def foo(a, b): pass
Xtreak9c3f2842019-02-26 03:16:34 +05301966
1967 mock = Mock()
1968 mock.child = create_autospec(foo)
1969 mock.child(1, 2)
1970
1971 self.assertRaises(TypeError, mock.child, 1)
1972 self.assertEqual(mock.mock_calls, [call.child(1, 2)])
Xtreak7397cda2019-07-22 13:08:22 +05301973 self.assertIn('mock.child', repr(mock.child.mock))
1974
1975 def test_parent_propagation_with_autospec_attach_mock(self):
1976
1977 def foo(a, b): pass
1978
1979 parent = Mock()
1980 parent.attach_mock(create_autospec(foo, name='bar'), 'child')
1981 parent.child(1, 2)
1982
1983 self.assertRaises(TypeError, parent.child, 1)
1984 self.assertEqual(parent.child.mock_calls, [call.child(1, 2)])
1985 self.assertIn('mock.child', repr(parent.child.mock))
1986
Xtreak9c3f2842019-02-26 03:16:34 +05301987
Xtreak830b43d2019-04-14 00:42:33 +05301988 def test_isinstance_under_settrace(self):
1989 # bpo-36593 : __class__ is not set for a class that has __class__
1990 # property defined when it's used with sys.settrace(trace) set.
1991 # Delete the module to force reimport with tracing function set
1992 # restore the old reference later since there are other tests that are
1993 # dependent on unittest.mock.patch. In testpatch.PatchTest
1994 # test_patch_dict_test_prefix and test_patch_test_prefix not restoring
1995 # causes the objects patched to go out of sync
1996
1997 old_patch = unittest.mock.patch
1998
1999 # Directly using __setattr__ on unittest.mock causes current imported
2000 # reference to be updated. Use a lambda so that during cleanup the
2001 # re-imported new reference is updated.
2002 self.addCleanup(lambda patch: setattr(unittest.mock, 'patch', patch),
2003 old_patch)
2004
2005 with patch.dict('sys.modules'):
2006 del sys.modules['unittest.mock']
2007
Chris Withersadbf1782019-05-01 23:04:04 +01002008 # This trace will stop coverage being measured ;-)
2009 def trace(frame, event, arg): # pragma: no cover
Xtreak830b43d2019-04-14 00:42:33 +05302010 return trace
2011
Chris Withersadbf1782019-05-01 23:04:04 +01002012 self.addCleanup(sys.settrace, sys.gettrace())
Xtreak830b43d2019-04-14 00:42:33 +05302013 sys.settrace(trace)
Xtreak830b43d2019-04-14 00:42:33 +05302014
2015 from unittest.mock import (
2016 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
2017 )
2018
2019 mocks = [
2020 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
2021 ]
2022
2023 for mock in mocks:
2024 obj = mock(spec=Something)
2025 self.assertIsInstance(obj, Something)
2026
Xtreak9c3f2842019-02-26 03:16:34 +05302027
Michael Foord345266a2012-03-14 12:24:34 -07002028if __name__ == '__main__':
2029 unittest.main()