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