blob: 18efd311f9e61960dc711b4bf7765f999850510b [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001import copy
Petter Strandmark47d94242018-10-28 21:37:10 +01002import re
Michael Foord345266a2012-03-14 12:24:34 -07003import sys
Robert Collinsca647ef2015-07-24 03:48:20 +12004import tempfile
Michael Foord345266a2012-03-14 12:24:34 -07005
6import unittest
7from unittest.test.testmock.support import is_instance
8from unittest import mock
9from unittest.mock import (
10 call, DEFAULT, patch, sentinel,
11 MagicMock, Mock, NonCallableMock,
Lisa Roach77b3b772019-05-20 09:19:53 -070012 NonCallableMagicMock, AsyncMock, _Call, _CallList,
Michael Foord345266a2012-03-14 12:24:34 -070013 create_autospec
14)
15
16
17class Iter(object):
18 def __init__(self):
19 self.thing = iter(['this', 'is', 'an', 'iter'])
20
21 def __iter__(self):
22 return self
23
24 def next(self):
25 return next(self.thing)
26
27 __next__ = next
28
29
Antoine Pitrou5c64df72013-02-03 00:23:58 +010030class Something(object):
Chris Withersadbf1782019-05-01 23:04:04 +010031 def meth(self, a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +010032
33 @classmethod
Chris Withersadbf1782019-05-01 23:04:04 +010034 def cmeth(cls, a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +010035
36 @staticmethod
Chris Withersadbf1782019-05-01 23:04:04 +010037 def smeth(a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +010038
Michael Foord345266a2012-03-14 12:24:34 -070039
Xtreak7397cda2019-07-22 13:08:22 +053040def something(a): pass
41
42
Michael Foord345266a2012-03-14 12:24:34 -070043class MockTest(unittest.TestCase):
44
45 def test_all(self):
46 # if __all__ is badly defined then import * will raise an error
47 # We have to exec it because you can't import * inside a method
48 # in Python 3
Michael Foord83a16852012-03-14 12:58:46 -070049 exec("from unittest.mock import *")
Michael Foord345266a2012-03-14 12:24:34 -070050
51
52 def test_constructor(self):
53 mock = Mock()
54
55 self.assertFalse(mock.called, "called not initialised correctly")
56 self.assertEqual(mock.call_count, 0,
57 "call_count not initialised correctly")
58 self.assertTrue(is_instance(mock.return_value, Mock),
59 "return_value not initialised correctly")
60
61 self.assertEqual(mock.call_args, None,
62 "call_args not initialised correctly")
63 self.assertEqual(mock.call_args_list, [],
64 "call_args_list not initialised correctly")
65 self.assertEqual(mock.method_calls, [],
66 "method_calls not initialised correctly")
67
68 # Can't use hasattr for this test as it always returns True on a mock
Serhiy Storchaka5665bc52013-11-17 00:12:21 +020069 self.assertNotIn('_items', mock.__dict__,
Michael Foord345266a2012-03-14 12:24:34 -070070 "default mock should not have '_items' attribute")
71
72 self.assertIsNone(mock._mock_parent,
73 "parent not initialised correctly")
74 self.assertIsNone(mock._mock_methods,
75 "methods not initialised correctly")
76 self.assertEqual(mock._mock_children, {},
77 "children not initialised incorrectly")
78
79
80 def test_return_value_in_constructor(self):
81 mock = Mock(return_value=None)
82 self.assertIsNone(mock.return_value,
83 "return value in constructor not honoured")
84
85
Chris Withersadbf1782019-05-01 23:04:04 +010086 def test_change_return_value_via_delegate(self):
87 def f(): pass
88 mock = create_autospec(f)
89 mock.mock.return_value = 1
90 self.assertEqual(mock(), 1)
91
92
93 def test_change_side_effect_via_delegate(self):
94 def f(): pass
95 mock = create_autospec(f)
96 mock.mock.side_effect = TypeError()
97 with self.assertRaises(TypeError):
98 mock()
99
100
Michael Foord345266a2012-03-14 12:24:34 -0700101 def test_repr(self):
102 mock = Mock(name='foo')
103 self.assertIn('foo', repr(mock))
104 self.assertIn("'%s'" % id(mock), repr(mock))
105
106 mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')]
107 for mock, name in mocks:
108 self.assertIn('%s.bar' % name, repr(mock.bar))
109 self.assertIn('%s.foo()' % name, repr(mock.foo()))
110 self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing))
111 self.assertIn('%s()' % name, repr(mock()))
112 self.assertIn('%s()()' % name, repr(mock()()))
113 self.assertIn('%s()().foo.bar.baz().bing' % name,
114 repr(mock()().foo.bar.baz().bing))
115
116
117 def test_repr_with_spec(self):
118 class X(object):
119 pass
120
121 mock = Mock(spec=X)
122 self.assertIn(" spec='X' ", repr(mock))
123
124 mock = Mock(spec=X())
125 self.assertIn(" spec='X' ", repr(mock))
126
127 mock = Mock(spec_set=X)
128 self.assertIn(" spec_set='X' ", repr(mock))
129
130 mock = Mock(spec_set=X())
131 self.assertIn(" spec_set='X' ", repr(mock))
132
133 mock = Mock(spec=X, name='foo')
134 self.assertIn(" spec='X' ", repr(mock))
135 self.assertIn(" name='foo' ", repr(mock))
136
137 mock = Mock(name='foo')
138 self.assertNotIn("spec", repr(mock))
139
140 mock = Mock()
141 self.assertNotIn("spec", repr(mock))
142
143 mock = Mock(spec=['foo'])
144 self.assertNotIn("spec", repr(mock))
145
146
147 def test_side_effect(self):
148 mock = Mock()
149
150 def effect(*args, **kwargs):
151 raise SystemError('kablooie')
152
153 mock.side_effect = effect
154 self.assertRaises(SystemError, mock, 1, 2, fish=3)
155 mock.assert_called_with(1, 2, fish=3)
156
157 results = [1, 2, 3]
158 def effect():
159 return results.pop()
160 mock.side_effect = effect
161
162 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
163 "side effect not used correctly")
164
165 mock = Mock(side_effect=sentinel.SideEffect)
166 self.assertEqual(mock.side_effect, sentinel.SideEffect,
167 "side effect in constructor not used")
168
169 def side_effect():
170 return DEFAULT
171 mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
172 self.assertEqual(mock(), sentinel.RETURN)
173
Michael Foord01bafdc2014-04-14 16:09:42 -0400174 def test_autospec_side_effect(self):
175 # Test for issue17826
176 results = [1, 2, 3]
177 def effect():
178 return results.pop()
Chris Withersadbf1782019-05-01 23:04:04 +0100179 def f(): pass
Michael Foord01bafdc2014-04-14 16:09:42 -0400180
181 mock = create_autospec(f)
182 mock.side_effect = [1, 2, 3]
183 self.assertEqual([mock(), mock(), mock()], [1, 2, 3],
184 "side effect not used correctly in create_autospec")
185 # Test where side effect is a callable
186 results = [1, 2, 3]
187 mock = create_autospec(f)
188 mock.side_effect = effect
189 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
190 "callable side effect not used correctly")
Michael Foord345266a2012-03-14 12:24:34 -0700191
Robert Collinsf58f88c2015-07-14 13:51:40 +1200192 def test_autospec_side_effect_exception(self):
193 # Test for issue 23661
Chris Withersadbf1782019-05-01 23:04:04 +0100194 def f(): pass
Robert Collinsf58f88c2015-07-14 13:51:40 +1200195
196 mock = create_autospec(f)
197 mock.side_effect = ValueError('Bazinga!')
198 self.assertRaisesRegex(ValueError, 'Bazinga!', mock)
199
Michael Foord345266a2012-03-14 12:24:34 -0700200
201 def test_reset_mock(self):
202 parent = Mock()
203 spec = ["something"]
204 mock = Mock(name="child", parent=parent, spec=spec)
205 mock(sentinel.Something, something=sentinel.SomethingElse)
206 something = mock.something
207 mock.something()
208 mock.side_effect = sentinel.SideEffect
209 return_value = mock.return_value
210 return_value()
211
212 mock.reset_mock()
213
214 self.assertEqual(mock._mock_name, "child",
215 "name incorrectly reset")
216 self.assertEqual(mock._mock_parent, parent,
217 "parent incorrectly reset")
218 self.assertEqual(mock._mock_methods, spec,
219 "methods incorrectly reset")
220
221 self.assertFalse(mock.called, "called not reset")
222 self.assertEqual(mock.call_count, 0, "call_count not reset")
223 self.assertEqual(mock.call_args, None, "call_args not reset")
224 self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
225 self.assertEqual(mock.method_calls, [],
226 "method_calls not initialised correctly: %r != %r" %
227 (mock.method_calls, []))
228 self.assertEqual(mock.mock_calls, [])
229
230 self.assertEqual(mock.side_effect, sentinel.SideEffect,
231 "side_effect incorrectly reset")
232 self.assertEqual(mock.return_value, return_value,
233 "return_value incorrectly reset")
234 self.assertFalse(return_value.called, "return value mock not reset")
235 self.assertEqual(mock._mock_children, {'something': something},
236 "children reset incorrectly")
237 self.assertEqual(mock.something, something,
238 "children incorrectly cleared")
239 self.assertFalse(mock.something.called, "child not reset")
240
241
242 def test_reset_mock_recursion(self):
243 mock = Mock()
244 mock.return_value = mock
245
246 # used to cause recursion
247 mock.reset_mock()
248
Robert Collinsb37f43f2015-07-15 11:42:28 +1200249 def test_reset_mock_on_mock_open_issue_18622(self):
250 a = mock.mock_open()
251 a.reset_mock()
Michael Foord345266a2012-03-14 12:24:34 -0700252
253 def test_call(self):
254 mock = Mock()
255 self.assertTrue(is_instance(mock.return_value, Mock),
256 "Default return_value should be a Mock")
257
258 result = mock()
259 self.assertEqual(mock(), result,
260 "different result from consecutive calls")
261 mock.reset_mock()
262
263 ret_val = mock(sentinel.Arg)
264 self.assertTrue(mock.called, "called not set")
Min ho Kimc4cacc82019-07-31 08:16:13 +1000265 self.assertEqual(mock.call_count, 1, "call_count incorrect")
Michael Foord345266a2012-03-14 12:24:34 -0700266 self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
267 "call_args not set")
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530268 self.assertEqual(mock.call_args.args, (sentinel.Arg,),
269 "call_args not set")
270 self.assertEqual(mock.call_args.kwargs, {},
271 "call_args not set")
Michael Foord345266a2012-03-14 12:24:34 -0700272 self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
273 "call_args_list not initialised correctly")
274
275 mock.return_value = sentinel.ReturnValue
276 ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
277 self.assertEqual(ret_val, sentinel.ReturnValue,
278 "incorrect return value")
279
280 self.assertEqual(mock.call_count, 2, "call_count incorrect")
281 self.assertEqual(mock.call_args,
282 ((sentinel.Arg,), {'key': sentinel.KeyArg}),
283 "call_args not set")
284 self.assertEqual(mock.call_args_list, [
285 ((sentinel.Arg,), {}),
286 ((sentinel.Arg,), {'key': sentinel.KeyArg})
287 ],
288 "call_args_list not set")
289
290
291 def test_call_args_comparison(self):
292 mock = Mock()
293 mock()
294 mock(sentinel.Arg)
295 mock(kw=sentinel.Kwarg)
296 mock(sentinel.Arg, kw=sentinel.Kwarg)
297 self.assertEqual(mock.call_args_list, [
298 (),
299 ((sentinel.Arg,),),
300 ({"kw": sentinel.Kwarg},),
301 ((sentinel.Arg,), {"kw": sentinel.Kwarg})
302 ])
303 self.assertEqual(mock.call_args,
304 ((sentinel.Arg,), {"kw": sentinel.Kwarg}))
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530305 self.assertEqual(mock.call_args.args, (sentinel.Arg,))
306 self.assertEqual(mock.call_args.kwargs, {"kw": sentinel.Kwarg})
Michael Foord345266a2012-03-14 12:24:34 -0700307
Berker Peksag3fc536f2015-09-09 23:35:25 +0300308 # Comparing call_args to a long sequence should not raise
309 # an exception. See issue 24857.
310 self.assertFalse(mock.call_args == "a long sequence")
Michael Foord345266a2012-03-14 12:24:34 -0700311
Berker Peksagce913872016-03-28 00:30:02 +0300312
313 def test_calls_equal_with_any(self):
Berker Peksagce913872016-03-28 00:30:02 +0300314 # Check that equality and non-equality is consistent even when
315 # comparing with mock.ANY
Serhiy Storchaka362f0582017-01-21 23:12:58 +0200316 mm = mock.MagicMock()
317 self.assertTrue(mm == mm)
318 self.assertFalse(mm != mm)
319 self.assertFalse(mm == mock.MagicMock())
320 self.assertTrue(mm != mock.MagicMock())
321 self.assertTrue(mm == mock.ANY)
322 self.assertFalse(mm != mock.ANY)
323 self.assertTrue(mock.ANY == mm)
324 self.assertFalse(mock.ANY != mm)
325
326 call1 = mock.call(mock.MagicMock())
327 call2 = mock.call(mock.ANY)
Berker Peksagce913872016-03-28 00:30:02 +0300328 self.assertTrue(call1 == call2)
329 self.assertFalse(call1 != call2)
Serhiy Storchaka362f0582017-01-21 23:12:58 +0200330 self.assertTrue(call2 == call1)
331 self.assertFalse(call2 != call1)
Berker Peksagce913872016-03-28 00:30:02 +0300332
333
Michael Foord345266a2012-03-14 12:24:34 -0700334 def test_assert_called_with(self):
335 mock = Mock()
336 mock()
337
338 # Will raise an exception if it fails
339 mock.assert_called_with()
340 self.assertRaises(AssertionError, mock.assert_called_with, 1)
341
342 mock.reset_mock()
343 self.assertRaises(AssertionError, mock.assert_called_with)
344
345 mock(1, 2, 3, a='fish', b='nothing')
346 mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
347
348
Berker Peksagce913872016-03-28 00:30:02 +0300349 def test_assert_called_with_any(self):
350 m = MagicMock()
351 m(MagicMock())
352 m.assert_called_with(mock.ANY)
353
354
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100355 def test_assert_called_with_function_spec(self):
Chris Withersadbf1782019-05-01 23:04:04 +0100356 def f(a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100357
358 mock = Mock(spec=f)
359
360 mock(1, b=2, c=3)
361 mock.assert_called_with(1, 2, 3)
362 mock.assert_called_with(a=1, b=2, c=3)
363 self.assertRaises(AssertionError, mock.assert_called_with,
364 1, b=3, c=2)
365 # Expected call doesn't match the spec's signature
366 with self.assertRaises(AssertionError) as cm:
367 mock.assert_called_with(e=8)
368 self.assertIsInstance(cm.exception.__cause__, TypeError)
369
370
371 def test_assert_called_with_method_spec(self):
372 def _check(mock):
373 mock(1, b=2, c=3)
374 mock.assert_called_with(1, 2, 3)
375 mock.assert_called_with(a=1, b=2, c=3)
376 self.assertRaises(AssertionError, mock.assert_called_with,
377 1, b=3, c=2)
378
379 mock = Mock(spec=Something().meth)
380 _check(mock)
381 mock = Mock(spec=Something.cmeth)
382 _check(mock)
383 mock = Mock(spec=Something().cmeth)
384 _check(mock)
385 mock = Mock(spec=Something.smeth)
386 _check(mock)
387 mock = Mock(spec=Something().smeth)
388 _check(mock)
389
390
Michael Foord345266a2012-03-14 12:24:34 -0700391 def test_assert_called_once_with(self):
392 mock = Mock()
393 mock()
394
395 # Will raise an exception if it fails
396 mock.assert_called_once_with()
397
398 mock()
399 self.assertRaises(AssertionError, mock.assert_called_once_with)
400
401 mock.reset_mock()
402 self.assertRaises(AssertionError, mock.assert_called_once_with)
403
404 mock('foo', 'bar', baz=2)
405 mock.assert_called_once_with('foo', 'bar', baz=2)
406
407 mock.reset_mock()
408 mock('foo', 'bar', baz=2)
409 self.assertRaises(
410 AssertionError,
411 lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
412 )
413
Petter Strandmark47d94242018-10-28 21:37:10 +0100414 def test_assert_called_once_with_call_list(self):
415 m = Mock()
416 m(1)
417 m(2)
418 self.assertRaisesRegex(AssertionError,
419 re.escape("Calls: [call(1), call(2)]"),
420 lambda: m.assert_called_once_with(2))
421
Michael Foord345266a2012-03-14 12:24:34 -0700422
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100423 def test_assert_called_once_with_function_spec(self):
Chris Withersadbf1782019-05-01 23:04:04 +0100424 def f(a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100425
426 mock = Mock(spec=f)
427
428 mock(1, b=2, c=3)
429 mock.assert_called_once_with(1, 2, 3)
430 mock.assert_called_once_with(a=1, b=2, c=3)
431 self.assertRaises(AssertionError, mock.assert_called_once_with,
432 1, b=3, c=2)
433 # Expected call doesn't match the spec's signature
434 with self.assertRaises(AssertionError) as cm:
435 mock.assert_called_once_with(e=8)
436 self.assertIsInstance(cm.exception.__cause__, TypeError)
437 # Mock called more than once => always fails
438 mock(4, 5, 6)
439 self.assertRaises(AssertionError, mock.assert_called_once_with,
440 1, 2, 3)
441 self.assertRaises(AssertionError, mock.assert_called_once_with,
442 4, 5, 6)
443
444
Michael Foord345266a2012-03-14 12:24:34 -0700445 def test_attribute_access_returns_mocks(self):
446 mock = Mock()
447 something = mock.something
448 self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
449 self.assertEqual(mock.something, something,
450 "different attributes returned for same name")
451
452 # Usage example
453 mock = Mock()
454 mock.something.return_value = 3
455
456 self.assertEqual(mock.something(), 3, "method returned wrong value")
457 self.assertTrue(mock.something.called,
458 "method didn't record being called")
459
460
461 def test_attributes_have_name_and_parent_set(self):
462 mock = Mock()
463 something = mock.something
464
465 self.assertEqual(something._mock_name, "something",
466 "attribute name not set correctly")
467 self.assertEqual(something._mock_parent, mock,
468 "attribute parent not set correctly")
469
470
471 def test_method_calls_recorded(self):
472 mock = Mock()
473 mock.something(3, fish=None)
474 mock.something_else.something(6, cake=sentinel.Cake)
475
476 self.assertEqual(mock.something_else.method_calls,
477 [("something", (6,), {'cake': sentinel.Cake})],
478 "method calls not recorded correctly")
479 self.assertEqual(mock.method_calls, [
480 ("something", (3,), {'fish': None}),
481 ("something_else.something", (6,), {'cake': sentinel.Cake})
482 ],
483 "method calls not recorded correctly")
484
485
486 def test_method_calls_compare_easily(self):
487 mock = Mock()
488 mock.something()
489 self.assertEqual(mock.method_calls, [('something',)])
490 self.assertEqual(mock.method_calls, [('something', (), {})])
491
492 mock = Mock()
493 mock.something('different')
494 self.assertEqual(mock.method_calls, [('something', ('different',))])
495 self.assertEqual(mock.method_calls,
496 [('something', ('different',), {})])
497
498 mock = Mock()
499 mock.something(x=1)
500 self.assertEqual(mock.method_calls, [('something', {'x': 1})])
501 self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
502
503 mock = Mock()
504 mock.something('different', some='more')
505 self.assertEqual(mock.method_calls, [
506 ('something', ('different',), {'some': 'more'})
507 ])
508
509
510 def test_only_allowed_methods_exist(self):
511 for spec in ['something'], ('something',):
512 for arg in 'spec', 'spec_set':
513 mock = Mock(**{arg: spec})
514
515 # this should be allowed
516 mock.something
517 self.assertRaisesRegex(
518 AttributeError,
519 "Mock object has no attribute 'something_else'",
520 getattr, mock, 'something_else'
521 )
522
523
524 def test_from_spec(self):
525 class Something(object):
526 x = 3
527 __something__ = None
Chris Withersadbf1782019-05-01 23:04:04 +0100528 def y(self): pass
Michael Foord345266a2012-03-14 12:24:34 -0700529
530 def test_attributes(mock):
531 # should work
532 mock.x
533 mock.y
534 mock.__something__
535 self.assertRaisesRegex(
536 AttributeError,
537 "Mock object has no attribute 'z'",
538 getattr, mock, 'z'
539 )
540 self.assertRaisesRegex(
541 AttributeError,
542 "Mock object has no attribute '__foobar__'",
543 getattr, mock, '__foobar__'
544 )
545
546 test_attributes(Mock(spec=Something))
547 test_attributes(Mock(spec=Something()))
548
549
550 def test_wraps_calls(self):
551 real = Mock()
552
553 mock = Mock(wraps=real)
554 self.assertEqual(mock(), real())
555
556 real.reset_mock()
557
558 mock(1, 2, fish=3)
559 real.assert_called_with(1, 2, fish=3)
560
561
Mario Corcherof05df0a2018-12-08 11:25:02 +0000562 def test_wraps_prevents_automatic_creation_of_mocks(self):
563 class Real(object):
564 pass
565
566 real = Real()
567 mock = Mock(wraps=real)
568
569 self.assertRaises(AttributeError, lambda: mock.new_attr())
570
571
Michael Foord345266a2012-03-14 12:24:34 -0700572 def test_wraps_call_with_nondefault_return_value(self):
573 real = Mock()
574
575 mock = Mock(wraps=real)
576 mock.return_value = 3
577
578 self.assertEqual(mock(), 3)
579 self.assertFalse(real.called)
580
581
582 def test_wraps_attributes(self):
583 class Real(object):
584 attribute = Mock()
585
586 real = Real()
587
588 mock = Mock(wraps=real)
589 self.assertEqual(mock.attribute(), real.attribute())
590 self.assertRaises(AttributeError, lambda: mock.fish)
591
592 self.assertNotEqual(mock.attribute, real.attribute)
593 result = mock.attribute.frog(1, 2, fish=3)
594 Real.attribute.frog.assert_called_with(1, 2, fish=3)
595 self.assertEqual(result, Real.attribute.frog())
596
597
Mario Corcherof05df0a2018-12-08 11:25:02 +0000598 def test_customize_wrapped_object_with_side_effect_iterable_with_default(self):
599 class Real(object):
600 def method(self):
601 return sentinel.ORIGINAL_VALUE
602
603 real = Real()
604 mock = Mock(wraps=real)
605 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
606
607 self.assertEqual(mock.method(), sentinel.VALUE1)
608 self.assertEqual(mock.method(), sentinel.ORIGINAL_VALUE)
609 self.assertRaises(StopIteration, mock.method)
610
611
612 def test_customize_wrapped_object_with_side_effect_iterable(self):
613 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100614 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000615
616 real = Real()
617 mock = Mock(wraps=real)
618 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
619
620 self.assertEqual(mock.method(), sentinel.VALUE1)
621 self.assertEqual(mock.method(), sentinel.VALUE2)
622 self.assertRaises(StopIteration, mock.method)
623
624
625 def test_customize_wrapped_object_with_side_effect_exception(self):
626 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100627 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000628
629 real = Real()
630 mock = Mock(wraps=real)
631 mock.method.side_effect = RuntimeError
632
633 self.assertRaises(RuntimeError, mock.method)
634
635
636 def test_customize_wrapped_object_with_side_effect_function(self):
637 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100638 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000639 def side_effect():
640 return sentinel.VALUE
641
642 real = Real()
643 mock = Mock(wraps=real)
644 mock.method.side_effect = side_effect
645
646 self.assertEqual(mock.method(), sentinel.VALUE)
647
648
649 def test_customize_wrapped_object_with_return_value(self):
650 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100651 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000652
653 real = Real()
654 mock = Mock(wraps=real)
655 mock.method.return_value = sentinel.VALUE
656
657 self.assertEqual(mock.method(), sentinel.VALUE)
658
659
660 def test_customize_wrapped_object_with_return_value_and_side_effect(self):
661 # side_effect should always take precedence over return_value.
662 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100663 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000664
665 real = Real()
666 mock = Mock(wraps=real)
667 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
668 mock.method.return_value = sentinel.WRONG_VALUE
669
670 self.assertEqual(mock.method(), sentinel.VALUE1)
671 self.assertEqual(mock.method(), sentinel.VALUE2)
672 self.assertRaises(StopIteration, mock.method)
673
674
675 def test_customize_wrapped_object_with_return_value_and_side_effect2(self):
676 # side_effect can return DEFAULT to default to return_value
677 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100678 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000679
680 real = Real()
681 mock = Mock(wraps=real)
682 mock.method.side_effect = lambda: DEFAULT
683 mock.method.return_value = sentinel.VALUE
684
685 self.assertEqual(mock.method(), sentinel.VALUE)
686
687
688 def test_customize_wrapped_object_with_return_value_and_side_effect_default(self):
689 class Real(object):
Chris Withersadbf1782019-05-01 23:04:04 +0100690 def method(self): pass
Mario Corcherof05df0a2018-12-08 11:25:02 +0000691
692 real = Real()
693 mock = Mock(wraps=real)
694 mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
695 mock.method.return_value = sentinel.RETURN
696
697 self.assertEqual(mock.method(), sentinel.VALUE1)
698 self.assertEqual(mock.method(), sentinel.RETURN)
699 self.assertRaises(StopIteration, mock.method)
700
701
Michael Foord345266a2012-03-14 12:24:34 -0700702 def test_exceptional_side_effect(self):
703 mock = Mock(side_effect=AttributeError)
704 self.assertRaises(AttributeError, mock)
705
706 mock = Mock(side_effect=AttributeError('foo'))
707 self.assertRaises(AttributeError, mock)
708
709
710 def test_baseexceptional_side_effect(self):
711 mock = Mock(side_effect=KeyboardInterrupt)
712 self.assertRaises(KeyboardInterrupt, mock)
713
714 mock = Mock(side_effect=KeyboardInterrupt('foo'))
715 self.assertRaises(KeyboardInterrupt, mock)
716
717
718 def test_assert_called_with_message(self):
719 mock = Mock()
Susan Su2bdd5852019-02-13 18:22:29 -0800720 self.assertRaisesRegex(AssertionError, 'not called',
Michael Foord345266a2012-03-14 12:24:34 -0700721 mock.assert_called_with)
722
723
Michael Foord28d591c2012-09-28 16:15:22 +0100724 def test_assert_called_once_with_message(self):
725 mock = Mock(name='geoffrey')
726 self.assertRaisesRegex(AssertionError,
727 r"Expected 'geoffrey' to be called once\.",
728 mock.assert_called_once_with)
729
730
Michael Foord345266a2012-03-14 12:24:34 -0700731 def test__name__(self):
732 mock = Mock()
733 self.assertRaises(AttributeError, lambda: mock.__name__)
734
735 mock.__name__ = 'foo'
736 self.assertEqual(mock.__name__, 'foo')
737
738
739 def test_spec_list_subclass(self):
740 class Sub(list):
741 pass
742 mock = Mock(spec=Sub(['foo']))
743
744 mock.append(3)
745 mock.append.assert_called_with(3)
746 self.assertRaises(AttributeError, getattr, mock, 'foo')
747
748
749 def test_spec_class(self):
750 class X(object):
751 pass
752
753 mock = Mock(spec=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200754 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700755
756 mock = Mock(spec=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200757 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700758
759 self.assertIs(mock.__class__, X)
760 self.assertEqual(Mock().__class__.__name__, 'Mock')
761
762 mock = Mock(spec_set=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200763 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700764
765 mock = Mock(spec_set=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200766 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700767
768
Chris Withersadbf1782019-05-01 23:04:04 +0100769 def test_spec_class_no_object_base(self):
770 class X:
771 pass
772
773 mock = Mock(spec=X)
774 self.assertIsInstance(mock, X)
775
776 mock = Mock(spec=X())
777 self.assertIsInstance(mock, X)
778
779 self.assertIs(mock.__class__, X)
780 self.assertEqual(Mock().__class__.__name__, 'Mock')
781
782 mock = Mock(spec_set=X)
783 self.assertIsInstance(mock, X)
784
785 mock = Mock(spec_set=X())
786 self.assertIsInstance(mock, X)
787
788
Michael Foord345266a2012-03-14 12:24:34 -0700789 def test_setting_attribute_with_spec_set(self):
790 class X(object):
791 y = 3
792
793 mock = Mock(spec=X)
794 mock.x = 'foo'
795
796 mock = Mock(spec_set=X)
797 def set_attr():
798 mock.x = 'foo'
799
800 mock.y = 'foo'
801 self.assertRaises(AttributeError, set_attr)
802
803
804 def test_copy(self):
805 current = sys.getrecursionlimit()
806 self.addCleanup(sys.setrecursionlimit, current)
807
808 # can't use sys.maxint as this doesn't exist in Python 3
809 sys.setrecursionlimit(int(10e8))
810 # this segfaults without the fix in place
811 copy.copy(Mock())
812
813
814 def test_subclass_with_properties(self):
815 class SubClass(Mock):
816 def _get(self):
817 return 3
818 def _set(self, value):
819 raise NameError('strange error')
820 some_attribute = property(_get, _set)
821
822 s = SubClass(spec_set=SubClass)
823 self.assertEqual(s.some_attribute, 3)
824
825 def test():
826 s.some_attribute = 3
827 self.assertRaises(NameError, test)
828
829 def test():
830 s.foo = 'bar'
831 self.assertRaises(AttributeError, test)
832
833
834 def test_setting_call(self):
835 mock = Mock()
836 def __call__(self, a):
837 return self._mock_call(a)
838
839 type(mock).__call__ = __call__
840 mock('one')
841 mock.assert_called_with('one')
842
843 self.assertRaises(TypeError, mock, 'one', 'two')
844
845
846 def test_dir(self):
847 mock = Mock()
848 attrs = set(dir(mock))
849 type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
850
851 # all public attributes from the type are included
852 self.assertEqual(set(), type_attrs - attrs)
853
854 # creates these attributes
855 mock.a, mock.b
856 self.assertIn('a', dir(mock))
857 self.assertIn('b', dir(mock))
858
859 # instance attributes
860 mock.c = mock.d = None
861 self.assertIn('c', dir(mock))
862 self.assertIn('d', dir(mock))
863
864 # magic methods
865 mock.__iter__ = lambda s: iter([])
866 self.assertIn('__iter__', dir(mock))
867
868
869 def test_dir_from_spec(self):
870 mock = Mock(spec=unittest.TestCase)
871 testcase_attrs = set(dir(unittest.TestCase))
872 attrs = set(dir(mock))
873
874 # all attributes from the spec are included
875 self.assertEqual(set(), testcase_attrs - attrs)
876
877 # shadow a sys attribute
878 mock.version = 3
879 self.assertEqual(dir(mock).count('version'), 1)
880
881
882 def test_filter_dir(self):
883 patcher = patch.object(mock, 'FILTER_DIR', False)
884 patcher.start()
885 try:
886 attrs = set(dir(Mock()))
887 type_attrs = set(dir(Mock))
888
889 # ALL attributes from the type are included
890 self.assertEqual(set(), type_attrs - attrs)
891 finally:
892 patcher.stop()
893
894
Mario Corchero0df635c2019-04-30 19:56:36 +0100895 def test_dir_does_not_include_deleted_attributes(self):
896 mock = Mock()
897 mock.child.return_value = 1
898
899 self.assertIn('child', dir(mock))
900 del mock.child
901 self.assertNotIn('child', dir(mock))
902
903
Michael Foord345266a2012-03-14 12:24:34 -0700904 def test_configure_mock(self):
905 mock = Mock(foo='bar')
906 self.assertEqual(mock.foo, 'bar')
907
908 mock = MagicMock(foo='bar')
909 self.assertEqual(mock.foo, 'bar')
910
911 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
912 'foo': MagicMock()}
913 mock = Mock(**kwargs)
914 self.assertRaises(KeyError, mock)
915 self.assertEqual(mock.foo.bar(), 33)
916 self.assertIsInstance(mock.foo, MagicMock)
917
918 mock = Mock()
919 mock.configure_mock(**kwargs)
920 self.assertRaises(KeyError, mock)
921 self.assertEqual(mock.foo.bar(), 33)
922 self.assertIsInstance(mock.foo, MagicMock)
923
924
925 def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
926 # needed because assertRaisesRegex doesn't work easily with newlines
Chris Withersadbf1782019-05-01 23:04:04 +0100927 with self.assertRaises(exception) as context:
Michael Foord345266a2012-03-14 12:24:34 -0700928 func(*args, **kwargs)
Chris Withersadbf1782019-05-01 23:04:04 +0100929 msg = str(context.exception)
Michael Foord345266a2012-03-14 12:24:34 -0700930 self.assertEqual(msg, message)
931
932
933 def test_assert_called_with_failure_message(self):
934 mock = NonCallableMock()
935
Susan Su2bdd5852019-02-13 18:22:29 -0800936 actual = 'not called.'
Michael Foord345266a2012-03-14 12:24:34 -0700937 expected = "mock(1, '2', 3, bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -0800938 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700939 self.assertRaisesWithMsg(
Susan Su2bdd5852019-02-13 18:22:29 -0800940 AssertionError, message % (expected, actual),
Michael Foord345266a2012-03-14 12:24:34 -0700941 mock.assert_called_with, 1, '2', 3, bar='foo'
942 )
943
944 mock.foo(1, '2', 3, foo='foo')
945
946
947 asserters = [
948 mock.foo.assert_called_with, mock.foo.assert_called_once_with
949 ]
950 for meth in asserters:
951 actual = "foo(1, '2', 3, foo='foo')"
952 expected = "foo(1, '2', 3, bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -0800953 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700954 self.assertRaisesWithMsg(
955 AssertionError, message % (expected, actual),
956 meth, 1, '2', 3, bar='foo'
957 )
958
959 # just kwargs
960 for meth in asserters:
961 actual = "foo(1, '2', 3, foo='foo')"
962 expected = "foo(bar='foo')"
Susan Su2bdd5852019-02-13 18:22:29 -0800963 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700964 self.assertRaisesWithMsg(
965 AssertionError, message % (expected, actual),
966 meth, bar='foo'
967 )
968
969 # just args
970 for meth in asserters:
971 actual = "foo(1, '2', 3, foo='foo')"
972 expected = "foo(1, 2, 3)"
Susan Su2bdd5852019-02-13 18:22:29 -0800973 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700974 self.assertRaisesWithMsg(
975 AssertionError, message % (expected, actual),
976 meth, 1, 2, 3
977 )
978
979 # empty
980 for meth in asserters:
981 actual = "foo(1, '2', 3, foo='foo')"
982 expected = "foo()"
Susan Su2bdd5852019-02-13 18:22:29 -0800983 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700984 self.assertRaisesWithMsg(
985 AssertionError, message % (expected, actual), meth
986 )
987
988
989 def test_mock_calls(self):
990 mock = MagicMock()
991
992 # need to do this because MagicMock.mock_calls used to just return
993 # a MagicMock which also returned a MagicMock when __eq__ was called
994 self.assertIs(mock.mock_calls == [], True)
995
996 mock = MagicMock()
997 mock()
998 expected = [('', (), {})]
999 self.assertEqual(mock.mock_calls, expected)
1000
1001 mock.foo()
1002 expected.append(call.foo())
1003 self.assertEqual(mock.mock_calls, expected)
1004 # intermediate mock_calls work too
1005 self.assertEqual(mock.foo.mock_calls, [('', (), {})])
1006
1007 mock = MagicMock()
1008 mock().foo(1, 2, 3, a=4, b=5)
1009 expected = [
1010 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
1011 ]
1012 self.assertEqual(mock.mock_calls, expected)
1013 self.assertEqual(mock.return_value.foo.mock_calls,
1014 [('', (1, 2, 3), dict(a=4, b=5))])
1015 self.assertEqual(mock.return_value.mock_calls,
1016 [('foo', (1, 2, 3), dict(a=4, b=5))])
1017
1018 mock = MagicMock()
1019 mock().foo.bar().baz()
1020 expected = [
1021 ('', (), {}), ('().foo.bar', (), {}),
1022 ('().foo.bar().baz', (), {})
1023 ]
1024 self.assertEqual(mock.mock_calls, expected)
1025 self.assertEqual(mock().mock_calls,
1026 call.foo.bar().baz().call_list())
1027
1028 for kwargs in dict(), dict(name='bar'):
1029 mock = MagicMock(**kwargs)
1030 int(mock.foo)
1031 expected = [('foo.__int__', (), {})]
1032 self.assertEqual(mock.mock_calls, expected)
1033
1034 mock = MagicMock(**kwargs)
1035 mock.a()()
1036 expected = [('a', (), {}), ('a()', (), {})]
1037 self.assertEqual(mock.mock_calls, expected)
1038 self.assertEqual(mock.a().mock_calls, [call()])
1039
1040 mock = MagicMock(**kwargs)
1041 mock(1)(2)(3)
1042 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
1043 self.assertEqual(mock().mock_calls, call(2)(3).call_list())
1044 self.assertEqual(mock()().mock_calls, call(3).call_list())
1045
1046 mock = MagicMock(**kwargs)
1047 mock(1)(2)(3).a.b.c(4)
1048 self.assertEqual(mock.mock_calls,
1049 call(1)(2)(3).a.b.c(4).call_list())
1050 self.assertEqual(mock().mock_calls,
1051 call(2)(3).a.b.c(4).call_list())
1052 self.assertEqual(mock()().mock_calls,
1053 call(3).a.b.c(4).call_list())
1054
1055 mock = MagicMock(**kwargs)
1056 int(mock().foo.bar().baz())
1057 last_call = ('().foo.bar().baz().__int__', (), {})
1058 self.assertEqual(mock.mock_calls[-1], last_call)
1059 self.assertEqual(mock().mock_calls,
1060 call.foo.bar().baz().__int__().call_list())
1061 self.assertEqual(mock().foo.bar().mock_calls,
1062 call.baz().__int__().call_list())
1063 self.assertEqual(mock().foo.bar().baz.mock_calls,
1064 call().__int__().call_list())
1065
1066
Chris Withers8ca0fa92018-12-03 21:31:37 +00001067 def test_child_mock_call_equal(self):
1068 m = Mock()
1069 result = m()
1070 result.wibble()
1071 # parent looks like this:
1072 self.assertEqual(m.mock_calls, [call(), call().wibble()])
1073 # but child should look like this:
1074 self.assertEqual(result.mock_calls, [call.wibble()])
1075
1076
1077 def test_mock_call_not_equal_leaf(self):
1078 m = Mock()
1079 m.foo().something()
1080 self.assertNotEqual(m.mock_calls[1], call.foo().different())
1081 self.assertEqual(m.mock_calls[0], call.foo())
1082
1083
1084 def test_mock_call_not_equal_non_leaf(self):
1085 m = Mock()
1086 m.foo().bar()
1087 self.assertNotEqual(m.mock_calls[1], call.baz().bar())
1088 self.assertNotEqual(m.mock_calls[0], call.baz())
1089
1090
1091 def test_mock_call_not_equal_non_leaf_params_different(self):
1092 m = Mock()
1093 m.foo(x=1).bar()
1094 # This isn't ideal, but there's no way to fix it without breaking backwards compatibility:
1095 self.assertEqual(m.mock_calls[1], call.foo(x=2).bar())
1096
1097
1098 def test_mock_call_not_equal_non_leaf_attr(self):
1099 m = Mock()
1100 m.foo.bar()
1101 self.assertNotEqual(m.mock_calls[0], call.baz.bar())
1102
1103
1104 def test_mock_call_not_equal_non_leaf_call_versus_attr(self):
1105 m = Mock()
1106 m.foo.bar()
1107 self.assertNotEqual(m.mock_calls[0], call.foo().bar())
1108
1109
1110 def test_mock_call_repr(self):
1111 m = Mock()
1112 m.foo().bar().baz.bob()
1113 self.assertEqual(repr(m.mock_calls[0]), 'call.foo()')
1114 self.assertEqual(repr(m.mock_calls[1]), 'call.foo().bar()')
1115 self.assertEqual(repr(m.mock_calls[2]), 'call.foo().bar().baz.bob()')
1116
1117
Chris Withersadbf1782019-05-01 23:04:04 +01001118 def test_mock_call_repr_loop(self):
1119 m = Mock()
1120 m.foo = m
1121 repr(m.foo())
1122 self.assertRegex(repr(m.foo()), r"<Mock name='mock\(\)' id='\d+'>")
1123
1124
1125 def test_mock_calls_contains(self):
1126 m = Mock()
1127 self.assertFalse([call()] in m.mock_calls)
1128
1129
Michael Foord345266a2012-03-14 12:24:34 -07001130 def test_subclassing(self):
1131 class Subclass(Mock):
1132 pass
1133
1134 mock = Subclass()
1135 self.assertIsInstance(mock.foo, Subclass)
1136 self.assertIsInstance(mock(), Subclass)
1137
1138 class Subclass(Mock):
1139 def _get_child_mock(self, **kwargs):
1140 return Mock(**kwargs)
1141
1142 mock = Subclass()
1143 self.assertNotIsInstance(mock.foo, Subclass)
1144 self.assertNotIsInstance(mock(), Subclass)
1145
1146
1147 def test_arg_lists(self):
1148 mocks = [
1149 Mock(),
1150 MagicMock(),
1151 NonCallableMock(),
1152 NonCallableMagicMock()
1153 ]
1154
1155 def assert_attrs(mock):
1156 names = 'call_args_list', 'method_calls', 'mock_calls'
1157 for name in names:
1158 attr = getattr(mock, name)
1159 self.assertIsInstance(attr, _CallList)
1160 self.assertIsInstance(attr, list)
1161 self.assertEqual(attr, [])
1162
1163 for mock in mocks:
1164 assert_attrs(mock)
1165
1166 if callable(mock):
1167 mock()
1168 mock(1, 2)
1169 mock(a=3)
1170
1171 mock.reset_mock()
1172 assert_attrs(mock)
1173
1174 mock.foo()
1175 mock.foo.bar(1, a=3)
1176 mock.foo(1).bar().baz(3)
1177
1178 mock.reset_mock()
1179 assert_attrs(mock)
1180
1181
1182 def test_call_args_two_tuple(self):
1183 mock = Mock()
1184 mock(1, a=3)
1185 mock(2, b=4)
1186
1187 self.assertEqual(len(mock.call_args), 2)
Kumar Akshayb0df45e2019-03-22 13:40:40 +05301188 self.assertEqual(mock.call_args.args, (2,))
1189 self.assertEqual(mock.call_args.kwargs, dict(b=4))
Michael Foord345266a2012-03-14 12:24:34 -07001190
1191 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
1192 for expected, call_args in zip(expected_list, mock.call_args_list):
1193 self.assertEqual(len(call_args), 2)
1194 self.assertEqual(expected[0], call_args[0])
1195 self.assertEqual(expected[1], call_args[1])
1196
1197
1198 def test_side_effect_iterator(self):
1199 mock = Mock(side_effect=iter([1, 2, 3]))
1200 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1201 self.assertRaises(StopIteration, mock)
1202
1203 mock = MagicMock(side_effect=['a', 'b', 'c'])
1204 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1205 self.assertRaises(StopIteration, mock)
1206
1207 mock = Mock(side_effect='ghi')
1208 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
1209 self.assertRaises(StopIteration, mock)
1210
1211 class Foo(object):
1212 pass
1213 mock = MagicMock(side_effect=Foo)
1214 self.assertIsInstance(mock(), Foo)
1215
1216 mock = Mock(side_effect=Iter())
1217 self.assertEqual([mock(), mock(), mock(), mock()],
1218 ['this', 'is', 'an', 'iter'])
1219 self.assertRaises(StopIteration, mock)
1220
1221
Michael Foord2cd48732012-04-21 15:52:11 +01001222 def test_side_effect_iterator_exceptions(self):
1223 for Klass in Mock, MagicMock:
1224 iterable = (ValueError, 3, KeyError, 6)
1225 m = Klass(side_effect=iterable)
1226 self.assertRaises(ValueError, m)
1227 self.assertEqual(m(), 3)
1228 self.assertRaises(KeyError, m)
1229 self.assertEqual(m(), 6)
1230
1231
Michael Foord345266a2012-03-14 12:24:34 -07001232 def test_side_effect_setting_iterator(self):
1233 mock = Mock()
1234 mock.side_effect = iter([1, 2, 3])
1235 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1236 self.assertRaises(StopIteration, mock)
1237 side_effect = mock.side_effect
1238 self.assertIsInstance(side_effect, type(iter([])))
1239
1240 mock.side_effect = ['a', 'b', 'c']
1241 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1242 self.assertRaises(StopIteration, mock)
1243 side_effect = mock.side_effect
1244 self.assertIsInstance(side_effect, type(iter([])))
1245
1246 this_iter = Iter()
1247 mock.side_effect = this_iter
1248 self.assertEqual([mock(), mock(), mock(), mock()],
1249 ['this', 'is', 'an', 'iter'])
1250 self.assertRaises(StopIteration, mock)
1251 self.assertIs(mock.side_effect, this_iter)
1252
Andrew Svetlov8b2cd752013-04-07 16:42:24 +03001253 def test_side_effect_iterator_default(self):
1254 mock = Mock(return_value=2)
1255 mock.side_effect = iter([1, DEFAULT])
1256 self.assertEqual([mock(), mock()], [1, 2])
Michael Foord345266a2012-03-14 12:24:34 -07001257
1258 def test_assert_has_calls_any_order(self):
1259 mock = Mock()
1260 mock(1, 2)
1261 mock(a=3)
1262 mock(3, 4)
1263 mock(b=6)
1264 mock(b=6)
1265
1266 kalls = [
1267 call(1, 2), ({'a': 3},),
1268 ((3, 4),), ((), {'a': 3}),
1269 ('', (1, 2)), ('', {'a': 3}),
1270 ('', (1, 2), {}), ('', (), {'a': 3})
1271 ]
1272 for kall in kalls:
1273 mock.assert_has_calls([kall], any_order=True)
1274
1275 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
1276 self.assertRaises(
1277 AssertionError, mock.assert_has_calls,
1278 [kall], any_order=True
1279 )
1280
1281 kall_lists = [
1282 [call(1, 2), call(b=6)],
1283 [call(3, 4), call(1, 2)],
1284 [call(b=6), call(b=6)],
1285 ]
1286
1287 for kall_list in kall_lists:
1288 mock.assert_has_calls(kall_list, any_order=True)
1289
1290 kall_lists = [
1291 [call(b=6), call(b=6), call(b=6)],
1292 [call(1, 2), call(1, 2)],
1293 [call(3, 4), call(1, 2), call(5, 7)],
1294 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
1295 ]
1296 for kall_list in kall_lists:
1297 self.assertRaises(
1298 AssertionError, mock.assert_has_calls,
1299 kall_list, any_order=True
1300 )
1301
1302 def test_assert_has_calls(self):
1303 kalls1 = [
1304 call(1, 2), ({'a': 3},),
1305 ((3, 4),), call(b=6),
1306 ('', (1,), {'b': 6}),
1307 ]
1308 kalls2 = [call.foo(), call.bar(1)]
1309 kalls2.extend(call.spam().baz(a=3).call_list())
1310 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
1311
1312 mocks = []
1313 for mock in Mock(), MagicMock():
1314 mock(1, 2)
1315 mock(a=3)
1316 mock(3, 4)
1317 mock(b=6)
1318 mock(1, b=6)
1319 mocks.append((mock, kalls1))
1320
1321 mock = Mock()
1322 mock.foo()
1323 mock.bar(1)
1324 mock.spam().baz(a=3)
1325 mock.bam(set(), foo={}).fish([1])
1326 mocks.append((mock, kalls2))
1327
1328 for mock, kalls in mocks:
1329 for i in range(len(kalls)):
1330 for step in 1, 2, 3:
1331 these = kalls[i:i+step]
1332 mock.assert_has_calls(these)
1333
1334 if len(these) > 1:
1335 self.assertRaises(
1336 AssertionError,
1337 mock.assert_has_calls,
1338 list(reversed(these))
1339 )
1340
1341
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001342 def test_assert_has_calls_with_function_spec(self):
Chris Withersadbf1782019-05-01 23:04:04 +01001343 def f(a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001344
1345 mock = Mock(spec=f)
1346
1347 mock(1, b=2, c=3)
1348 mock(4, 5, c=6, d=7)
1349 mock(10, 11, c=12)
1350 calls = [
1351 ('', (1, 2, 3), {}),
1352 ('', (4, 5, 6), {'d': 7}),
1353 ((10, 11, 12), {}),
1354 ]
1355 mock.assert_has_calls(calls)
1356 mock.assert_has_calls(calls, any_order=True)
1357 mock.assert_has_calls(calls[1:])
1358 mock.assert_has_calls(calls[1:], any_order=True)
1359 mock.assert_has_calls(calls[:-1])
1360 mock.assert_has_calls(calls[:-1], any_order=True)
1361 # Reversed order
1362 calls = list(reversed(calls))
1363 with self.assertRaises(AssertionError):
1364 mock.assert_has_calls(calls)
1365 mock.assert_has_calls(calls, any_order=True)
1366 with self.assertRaises(AssertionError):
1367 mock.assert_has_calls(calls[1:])
1368 mock.assert_has_calls(calls[1:], any_order=True)
1369 with self.assertRaises(AssertionError):
1370 mock.assert_has_calls(calls[:-1])
1371 mock.assert_has_calls(calls[:-1], any_order=True)
1372
1373
Michael Foord345266a2012-03-14 12:24:34 -07001374 def test_assert_any_call(self):
1375 mock = Mock()
1376 mock(1, 2)
1377 mock(a=3)
1378 mock(1, b=6)
1379
1380 mock.assert_any_call(1, 2)
1381 mock.assert_any_call(a=3)
1382 mock.assert_any_call(1, b=6)
1383
1384 self.assertRaises(
1385 AssertionError,
1386 mock.assert_any_call
1387 )
1388 self.assertRaises(
1389 AssertionError,
1390 mock.assert_any_call,
1391 1, 3
1392 )
1393 self.assertRaises(
1394 AssertionError,
1395 mock.assert_any_call,
1396 a=4
1397 )
1398
1399
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001400 def test_assert_any_call_with_function_spec(self):
Chris Withersadbf1782019-05-01 23:04:04 +01001401 def f(a, b, c, d=None): pass
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001402
1403 mock = Mock(spec=f)
1404
1405 mock(1, b=2, c=3)
1406 mock(4, 5, c=6, d=7)
1407 mock.assert_any_call(1, 2, 3)
1408 mock.assert_any_call(a=1, b=2, c=3)
1409 mock.assert_any_call(4, 5, 6, 7)
1410 mock.assert_any_call(a=4, b=5, c=6, d=7)
1411 self.assertRaises(AssertionError, mock.assert_any_call,
1412 1, b=3, c=2)
1413 # Expected call doesn't match the spec's signature
1414 with self.assertRaises(AssertionError) as cm:
1415 mock.assert_any_call(e=8)
1416 self.assertIsInstance(cm.exception.__cause__, TypeError)
1417
1418
Michael Foord345266a2012-03-14 12:24:34 -07001419 def test_mock_calls_create_autospec(self):
Chris Withersadbf1782019-05-01 23:04:04 +01001420 def f(a, b): pass
Michael Foord345266a2012-03-14 12:24:34 -07001421 obj = Iter()
1422 obj.f = f
1423
1424 funcs = [
1425 create_autospec(f),
1426 create_autospec(obj).f
1427 ]
1428 for func in funcs:
1429 func(1, 2)
1430 func(3, 4)
1431
1432 self.assertEqual(
1433 func.mock_calls, [call(1, 2), call(3, 4)]
1434 )
1435
Kushal Das484f8a82014-04-16 01:05:50 +05301436 #Issue21222
1437 def test_create_autospec_with_name(self):
1438 m = mock.create_autospec(object(), name='sweet_func')
1439 self.assertIn('sweet_func', repr(m))
Michael Foord345266a2012-03-14 12:24:34 -07001440
Xtreak9b218562019-04-22 08:00:23 +05301441 #Issue23078
1442 def test_create_autospec_classmethod_and_staticmethod(self):
1443 class TestClass:
1444 @classmethod
Chris Withersadbf1782019-05-01 23:04:04 +01001445 def class_method(cls): pass
Xtreak9b218562019-04-22 08:00:23 +05301446
1447 @staticmethod
Chris Withersadbf1782019-05-01 23:04:04 +01001448 def static_method(): pass
Xtreak9b218562019-04-22 08:00:23 +05301449 for method in ('class_method', 'static_method'):
1450 with self.subTest(method=method):
1451 mock_method = mock.create_autospec(getattr(TestClass, method))
1452 mock_method()
1453 mock_method.assert_called_once_with()
1454 self.assertRaises(TypeError, mock_method, 'extra_arg')
1455
Kushal Das8c145342014-04-16 23:32:21 +05301456 #Issue21238
1457 def test_mock_unsafe(self):
1458 m = Mock()
Zackery Spytzb9b08cd2019-05-08 11:32:24 -06001459 msg = "Attributes cannot start with 'assert' or 'assret'"
1460 with self.assertRaisesRegex(AttributeError, msg):
Kushal Das8c145342014-04-16 23:32:21 +05301461 m.assert_foo_call()
Zackery Spytzb9b08cd2019-05-08 11:32:24 -06001462 with self.assertRaisesRegex(AttributeError, msg):
Kushal Das8c145342014-04-16 23:32:21 +05301463 m.assret_foo_call()
1464 m = Mock(unsafe=True)
1465 m.assert_foo_call()
1466 m.assret_foo_call()
1467
Kushal Das8af9db32014-04-17 01:36:14 +05301468 #Issue21262
1469 def test_assert_not_called(self):
1470 m = Mock()
1471 m.hello.assert_not_called()
1472 m.hello()
1473 with self.assertRaises(AssertionError):
1474 m.hello.assert_not_called()
1475
Petter Strandmark47d94242018-10-28 21:37:10 +01001476 def test_assert_not_called_message(self):
1477 m = Mock()
1478 m(1, 2)
1479 self.assertRaisesRegex(AssertionError,
1480 re.escape("Calls: [call(1, 2)]"),
1481 m.assert_not_called)
1482
Victor Stinner2c2a4e62016-03-11 22:17:48 +01001483 def test_assert_called(self):
1484 m = Mock()
1485 with self.assertRaises(AssertionError):
1486 m.hello.assert_called()
1487 m.hello()
1488 m.hello.assert_called()
1489
1490 m.hello()
1491 m.hello.assert_called()
1492
1493 def test_assert_called_once(self):
1494 m = Mock()
1495 with self.assertRaises(AssertionError):
1496 m.hello.assert_called_once()
1497 m.hello()
1498 m.hello.assert_called_once()
1499
1500 m.hello()
1501 with self.assertRaises(AssertionError):
1502 m.hello.assert_called_once()
1503
Petter Strandmark47d94242018-10-28 21:37:10 +01001504 def test_assert_called_once_message(self):
1505 m = Mock()
1506 m(1, 2)
1507 m(3)
1508 self.assertRaisesRegex(AssertionError,
1509 re.escape("Calls: [call(1, 2), call(3)]"),
1510 m.assert_called_once)
1511
1512 def test_assert_called_once_message_not_called(self):
1513 m = Mock()
1514 with self.assertRaises(AssertionError) as e:
1515 m.assert_called_once()
1516 self.assertNotIn("Calls:", str(e.exception))
1517
Kushal Das047f14c2014-06-09 13:45:56 +05301518 #Issue21256 printout of keyword args should be in deterministic order
1519 def test_sorted_call_signature(self):
1520 m = Mock()
1521 m.hello(name='hello', daddy='hero')
1522 text = "call(daddy='hero', name='hello')"
R David Murray130a5662014-06-11 17:09:43 -04001523 self.assertEqual(repr(m.hello.call_args), text)
Kushal Das8af9db32014-04-17 01:36:14 +05301524
Kushal Dasa37b9582014-09-16 18:33:37 +05301525 #Issue21270 overrides tuple methods for mock.call objects
1526 def test_override_tuple_methods(self):
1527 c = call.count()
1528 i = call.index(132,'hello')
1529 m = Mock()
1530 m.count()
1531 m.index(132,"hello")
1532 self.assertEqual(m.method_calls[0], c)
1533 self.assertEqual(m.method_calls[1], i)
1534
Kushal Das9cd39a12016-06-02 10:20:16 -07001535 def test_reset_return_sideeffect(self):
1536 m = Mock(return_value=10, side_effect=[2,3])
1537 m.reset_mock(return_value=True, side_effect=True)
1538 self.assertIsInstance(m.return_value, Mock)
1539 self.assertEqual(m.side_effect, None)
1540
1541 def test_reset_return(self):
1542 m = Mock(return_value=10, side_effect=[2,3])
1543 m.reset_mock(return_value=True)
1544 self.assertIsInstance(m.return_value, Mock)
1545 self.assertNotEqual(m.side_effect, None)
1546
1547 def test_reset_sideeffect(self):
1548 m = Mock(return_value=10, side_effect=[2,3])
1549 m.reset_mock(side_effect=True)
1550 self.assertEqual(m.return_value, 10)
1551 self.assertEqual(m.side_effect, None)
1552
Michael Foord345266a2012-03-14 12:24:34 -07001553 def test_mock_add_spec(self):
1554 class _One(object):
1555 one = 1
1556 class _Two(object):
1557 two = 2
1558 class Anything(object):
1559 one = two = three = 'four'
1560
1561 klasses = [
1562 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1563 ]
1564 for Klass in list(klasses):
1565 klasses.append(lambda K=Klass: K(spec=Anything))
1566 klasses.append(lambda K=Klass: K(spec_set=Anything))
1567
1568 for Klass in klasses:
1569 for kwargs in dict(), dict(spec_set=True):
1570 mock = Klass()
1571 #no error
1572 mock.one, mock.two, mock.three
1573
1574 for One, Two in [(_One, _Two), (['one'], ['two'])]:
1575 for kwargs in dict(), dict(spec_set=True):
1576 mock.mock_add_spec(One, **kwargs)
1577
1578 mock.one
1579 self.assertRaises(
1580 AttributeError, getattr, mock, 'two'
1581 )
1582 self.assertRaises(
1583 AttributeError, getattr, mock, 'three'
1584 )
1585 if 'spec_set' in kwargs:
1586 self.assertRaises(
1587 AttributeError, setattr, mock, 'three', None
1588 )
1589
1590 mock.mock_add_spec(Two, **kwargs)
1591 self.assertRaises(
1592 AttributeError, getattr, mock, 'one'
1593 )
1594 mock.two
1595 self.assertRaises(
1596 AttributeError, getattr, mock, 'three'
1597 )
1598 if 'spec_set' in kwargs:
1599 self.assertRaises(
1600 AttributeError, setattr, mock, 'three', None
1601 )
1602 # note that creating a mock, setting an instance attribute, and
1603 # *then* setting a spec doesn't work. Not the intended use case
1604
1605
1606 def test_mock_add_spec_magic_methods(self):
1607 for Klass in MagicMock, NonCallableMagicMock:
1608 mock = Klass()
1609 int(mock)
1610
1611 mock.mock_add_spec(object)
1612 self.assertRaises(TypeError, int, mock)
1613
1614 mock = Klass()
1615 mock['foo']
1616 mock.__int__.return_value =4
1617
1618 mock.mock_add_spec(int)
1619 self.assertEqual(int(mock), 4)
1620 self.assertRaises(TypeError, lambda: mock['foo'])
1621
1622
1623 def test_adding_child_mock(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07001624 for Klass in (NonCallableMock, Mock, MagicMock, NonCallableMagicMock,
1625 AsyncMock):
Michael Foord345266a2012-03-14 12:24:34 -07001626 mock = Klass()
1627
1628 mock.foo = Mock()
1629 mock.foo()
1630
1631 self.assertEqual(mock.method_calls, [call.foo()])
1632 self.assertEqual(mock.mock_calls, [call.foo()])
1633
1634 mock = Klass()
1635 mock.bar = Mock(name='name')
1636 mock.bar()
1637 self.assertEqual(mock.method_calls, [])
1638 self.assertEqual(mock.mock_calls, [])
1639
1640 # mock with an existing _new_parent but no name
1641 mock = Klass()
1642 mock.baz = MagicMock()()
1643 mock.baz()
1644 self.assertEqual(mock.method_calls, [])
1645 self.assertEqual(mock.mock_calls, [])
1646
1647
1648 def test_adding_return_value_mock(self):
1649 for Klass in Mock, MagicMock:
1650 mock = Klass()
1651 mock.return_value = MagicMock()
1652
1653 mock()()
1654 self.assertEqual(mock.mock_calls, [call(), call()()])
1655
1656
1657 def test_manager_mock(self):
1658 class Foo(object):
1659 one = 'one'
1660 two = 'two'
1661 manager = Mock()
1662 p1 = patch.object(Foo, 'one')
1663 p2 = patch.object(Foo, 'two')
1664
1665 mock_one = p1.start()
1666 self.addCleanup(p1.stop)
1667 mock_two = p2.start()
1668 self.addCleanup(p2.stop)
1669
1670 manager.attach_mock(mock_one, 'one')
1671 manager.attach_mock(mock_two, 'two')
1672
1673 Foo.two()
1674 Foo.one()
1675
1676 self.assertEqual(manager.mock_calls, [call.two(), call.one()])
1677
1678
1679 def test_magic_methods_mock_calls(self):
1680 for Klass in Mock, MagicMock:
1681 m = Klass()
1682 m.__int__ = Mock(return_value=3)
1683 m.__float__ = MagicMock(return_value=3.0)
1684 int(m)
1685 float(m)
1686
1687 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
1688 self.assertEqual(m.method_calls, [])
1689
Robert Collins5329aaa2015-07-17 20:08:45 +12001690 def test_mock_open_reuse_issue_21750(self):
1691 mocked_open = mock.mock_open(read_data='data')
1692 f1 = mocked_open('a-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001693 f1_data = f1.read()
Robert Collins5329aaa2015-07-17 20:08:45 +12001694 f2 = mocked_open('another-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001695 f2_data = f2.read()
1696 self.assertEqual(f1_data, f2_data)
1697
Tony Flury20870232018-09-12 23:21:16 +01001698 def test_mock_open_dunder_iter_issue(self):
1699 # Test dunder_iter method generates the expected result and
1700 # consumes the iterator.
1701 mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue')
1702 f1 = mocked_open('a-name')
1703 lines = [line for line in f1]
1704 self.assertEqual(lines[0], 'Remarkable\n')
1705 self.assertEqual(lines[1], 'Norwegian Blue')
1706 self.assertEqual(list(f1), [])
1707
Damien Nadé394119a2019-05-23 12:03:25 +02001708 def test_mock_open_using_next(self):
1709 mocked_open = mock.mock_open(read_data='1st line\n2nd line\n3rd line')
1710 f1 = mocked_open('a-name')
1711 line1 = next(f1)
1712 line2 = f1.__next__()
1713 lines = [line for line in f1]
1714 self.assertEqual(line1, '1st line\n')
1715 self.assertEqual(line2, '2nd line\n')
1716 self.assertEqual(lines[0], '3rd line')
1717 self.assertEqual(list(f1), [])
1718 with self.assertRaises(StopIteration):
1719 next(f1)
1720
Robert Collinsca647ef2015-07-24 03:48:20 +12001721 def test_mock_open_write(self):
1722 # Test exception in file writing write()
1723 mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
1724 with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
1725 mock_filehandle = mock_namedtemp.return_value
1726 mock_write = mock_filehandle.write
1727 mock_write.side_effect = OSError('Test 2 Error')
1728 def attempt():
1729 tempfile.NamedTemporaryFile().write('asd')
1730 self.assertRaises(OSError, attempt)
1731
1732 def test_mock_open_alter_readline(self):
1733 mopen = mock.mock_open(read_data='foo\nbarn')
1734 mopen.return_value.readline.side_effect = lambda *args:'abc'
1735 first = mopen().readline()
1736 second = mopen().readline()
1737 self.assertEqual('abc', first)
1738 self.assertEqual('abc', second)
Michael Foord345266a2012-03-14 12:24:34 -07001739
Robert Collins9549a3e2016-05-16 15:22:01 +12001740 def test_mock_open_after_eof(self):
1741 # read, readline and readlines should work after end of file.
1742 _open = mock.mock_open(read_data='foo')
1743 h = _open('bar')
1744 h.read()
1745 self.assertEqual('', h.read())
1746 self.assertEqual('', h.read())
1747 self.assertEqual('', h.readline())
1748 self.assertEqual('', h.readline())
1749 self.assertEqual([], h.readlines())
1750 self.assertEqual([], h.readlines())
1751
Michael Foord345266a2012-03-14 12:24:34 -07001752 def test_mock_parents(self):
1753 for Klass in Mock, MagicMock:
1754 m = Klass()
1755 original_repr = repr(m)
1756 m.return_value = m
1757 self.assertIs(m(), m)
1758 self.assertEqual(repr(m), original_repr)
1759
1760 m.reset_mock()
1761 self.assertIs(m(), m)
1762 self.assertEqual(repr(m), original_repr)
1763
1764 m = Klass()
1765 m.b = m.a
1766 self.assertIn("name='mock.a'", repr(m.b))
1767 self.assertIn("name='mock.a'", repr(m.a))
1768 m.reset_mock()
1769 self.assertIn("name='mock.a'", repr(m.b))
1770 self.assertIn("name='mock.a'", repr(m.a))
1771
1772 m = Klass()
1773 original_repr = repr(m)
1774 m.a = m()
1775 m.a.return_value = m
1776
1777 self.assertEqual(repr(m), original_repr)
1778 self.assertEqual(repr(m.a()), original_repr)
1779
1780
1781 def test_attach_mock(self):
1782 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1783 for Klass in classes:
1784 for Klass2 in classes:
1785 m = Klass()
1786
1787 m2 = Klass2(name='foo')
1788 m.attach_mock(m2, 'bar')
1789
1790 self.assertIs(m.bar, m2)
1791 self.assertIn("name='mock.bar'", repr(m2))
1792
1793 m.bar.baz(1)
1794 self.assertEqual(m.mock_calls, [call.bar.baz(1)])
1795 self.assertEqual(m.method_calls, [call.bar.baz(1)])
1796
1797
1798 def test_attach_mock_return_value(self):
1799 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1800 for Klass in Mock, MagicMock:
1801 for Klass2 in classes:
1802 m = Klass()
1803
1804 m2 = Klass2(name='foo')
1805 m.attach_mock(m2, 'return_value')
1806
1807 self.assertIs(m(), m2)
1808 self.assertIn("name='mock()'", repr(m2))
1809
1810 m2.foo()
1811 self.assertEqual(m.mock_calls, call().foo().call_list())
1812
1813
Xtreak7397cda2019-07-22 13:08:22 +05301814 def test_attach_mock_patch_autospec(self):
1815 parent = Mock()
1816
1817 with mock.patch(f'{__name__}.something', autospec=True) as mock_func:
1818 self.assertEqual(mock_func.mock._extract_mock_name(), 'something')
1819 parent.attach_mock(mock_func, 'child')
1820 parent.child(1)
1821 something(2)
1822 mock_func(3)
1823
1824 parent_calls = [call.child(1), call.child(2), call.child(3)]
1825 child_calls = [call(1), call(2), call(3)]
1826 self.assertEqual(parent.mock_calls, parent_calls)
1827 self.assertEqual(parent.child.mock_calls, child_calls)
1828 self.assertEqual(something.mock_calls, child_calls)
1829 self.assertEqual(mock_func.mock_calls, child_calls)
1830 self.assertIn('mock.child', repr(parent.child.mock))
1831 self.assertEqual(mock_func.mock._extract_mock_name(), 'mock.child')
1832
1833
Michael Foord345266a2012-03-14 12:24:34 -07001834 def test_attribute_deletion(self):
Michael Foord468ec342013-09-15 20:05:19 +12001835 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1836 NonCallableMock()):
Michael Foord345266a2012-03-14 12:24:34 -07001837 self.assertTrue(hasattr(mock, 'm'))
1838
1839 del mock.m
1840 self.assertFalse(hasattr(mock, 'm'))
1841
1842 del mock.f
1843 self.assertFalse(hasattr(mock, 'f'))
1844 self.assertRaises(AttributeError, getattr, mock, 'f')
1845
1846
Pablo Galindo222d3032019-01-21 08:57:46 +00001847 def test_mock_does_not_raise_on_repeated_attribute_deletion(self):
1848 # bpo-20239: Assigning and deleting twice an attribute raises.
1849 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1850 NonCallableMock()):
1851 mock.foo = 3
1852 self.assertTrue(hasattr(mock, 'foo'))
1853 self.assertEqual(mock.foo, 3)
1854
1855 del mock.foo
1856 self.assertFalse(hasattr(mock, 'foo'))
1857
1858 mock.foo = 4
1859 self.assertTrue(hasattr(mock, 'foo'))
1860 self.assertEqual(mock.foo, 4)
1861
1862 del mock.foo
1863 self.assertFalse(hasattr(mock, 'foo'))
1864
1865
1866 def test_mock_raises_when_deleting_nonexistent_attribute(self):
1867 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1868 NonCallableMock()):
1869 del mock.foo
1870 with self.assertRaises(AttributeError):
1871 del mock.foo
1872
1873
Xtreakedeca922018-12-01 15:33:54 +05301874 def test_reset_mock_does_not_raise_on_attr_deletion(self):
1875 # bpo-31177: reset_mock should not raise AttributeError when attributes
1876 # were deleted in a mock instance
1877 mock = Mock()
1878 mock.child = True
1879 del mock.child
1880 mock.reset_mock()
1881 self.assertFalse(hasattr(mock, 'child'))
1882
1883
Michael Foord345266a2012-03-14 12:24:34 -07001884 def test_class_assignable(self):
1885 for mock in Mock(), MagicMock():
1886 self.assertNotIsInstance(mock, int)
1887
1888 mock.__class__ = int
1889 self.assertIsInstance(mock, int)
1890 mock.foo
1891
Andrew Dunaie63e6172018-12-04 11:08:45 +02001892 def test_name_attribute_of_call(self):
1893 # bpo-35357: _Call should not disclose any attributes whose names
1894 # may clash with popular ones (such as ".name")
1895 self.assertIsNotNone(call.name)
1896 self.assertEqual(type(call.name), _Call)
1897 self.assertEqual(type(call.name().name), _Call)
1898
1899 def test_parent_attribute_of_call(self):
1900 # bpo-35357: _Call should not disclose any attributes whose names
1901 # may clash with popular ones (such as ".parent")
1902 self.assertIsNotNone(call.parent)
1903 self.assertEqual(type(call.parent), _Call)
1904 self.assertEqual(type(call.parent().parent), _Call)
1905
Michael Foord345266a2012-03-14 12:24:34 -07001906
Xtreak9c3f2842019-02-26 03:16:34 +05301907 def test_parent_propagation_with_create_autospec(self):
1908
Chris Withersadbf1782019-05-01 23:04:04 +01001909 def foo(a, b): pass
Xtreak9c3f2842019-02-26 03:16:34 +05301910
1911 mock = Mock()
1912 mock.child = create_autospec(foo)
1913 mock.child(1, 2)
1914
1915 self.assertRaises(TypeError, mock.child, 1)
1916 self.assertEqual(mock.mock_calls, [call.child(1, 2)])
Xtreak7397cda2019-07-22 13:08:22 +05301917 self.assertIn('mock.child', repr(mock.child.mock))
1918
1919 def test_parent_propagation_with_autospec_attach_mock(self):
1920
1921 def foo(a, b): pass
1922
1923 parent = Mock()
1924 parent.attach_mock(create_autospec(foo, name='bar'), 'child')
1925 parent.child(1, 2)
1926
1927 self.assertRaises(TypeError, parent.child, 1)
1928 self.assertEqual(parent.child.mock_calls, [call.child(1, 2)])
1929 self.assertIn('mock.child', repr(parent.child.mock))
1930
Xtreak9c3f2842019-02-26 03:16:34 +05301931
Xtreak830b43d2019-04-14 00:42:33 +05301932 def test_isinstance_under_settrace(self):
1933 # bpo-36593 : __class__ is not set for a class that has __class__
1934 # property defined when it's used with sys.settrace(trace) set.
1935 # Delete the module to force reimport with tracing function set
1936 # restore the old reference later since there are other tests that are
1937 # dependent on unittest.mock.patch. In testpatch.PatchTest
1938 # test_patch_dict_test_prefix and test_patch_test_prefix not restoring
1939 # causes the objects patched to go out of sync
1940
1941 old_patch = unittest.mock.patch
1942
1943 # Directly using __setattr__ on unittest.mock causes current imported
1944 # reference to be updated. Use a lambda so that during cleanup the
1945 # re-imported new reference is updated.
1946 self.addCleanup(lambda patch: setattr(unittest.mock, 'patch', patch),
1947 old_patch)
1948
1949 with patch.dict('sys.modules'):
1950 del sys.modules['unittest.mock']
1951
Chris Withersadbf1782019-05-01 23:04:04 +01001952 # This trace will stop coverage being measured ;-)
1953 def trace(frame, event, arg): # pragma: no cover
Xtreak830b43d2019-04-14 00:42:33 +05301954 return trace
1955
Chris Withersadbf1782019-05-01 23:04:04 +01001956 self.addCleanup(sys.settrace, sys.gettrace())
Xtreak830b43d2019-04-14 00:42:33 +05301957 sys.settrace(trace)
Xtreak830b43d2019-04-14 00:42:33 +05301958
1959 from unittest.mock import (
1960 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1961 )
1962
1963 mocks = [
1964 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1965 ]
1966
1967 for mock in mocks:
1968 obj = mock(spec=Something)
1969 self.assertIsInstance(obj, Something)
1970
Xtreak9c3f2842019-02-26 03:16:34 +05301971
Michael Foord345266a2012-03-14 12:24:34 -07001972if __name__ == '__main__':
1973 unittest.main()