blob: 0a638b7c2107fe3c2cc3d65e3b78d0a8cf5ffc15 [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001import copy
Petter Strandmark47d94242018-10-28 21:37:10 +01002import re
Michael Foord345266a2012-03-14 12:24:34 -07003import sys
Robert Collinsca647ef2015-07-24 03:48:20 +12004import tempfile
Michael Foord345266a2012-03-14 12:24:34 -07005
6import unittest
7from unittest.test.testmock.support import is_instance
8from unittest import mock
9from unittest.mock import (
10 call, DEFAULT, patch, sentinel,
11 MagicMock, Mock, NonCallableMock,
Andrew Dunaie63e6172018-12-04 11:08:45 +020012 NonCallableMagicMock, _Call, _CallList,
Michael Foord345266a2012-03-14 12:24:34 -070013 create_autospec
14)
15
16
17class Iter(object):
18 def __init__(self):
19 self.thing = iter(['this', 'is', 'an', 'iter'])
20
21 def __iter__(self):
22 return self
23
24 def next(self):
25 return next(self.thing)
26
27 __next__ = next
28
29
Antoine Pitrou5c64df72013-02-03 00:23:58 +010030class Something(object):
31 def meth(self, a, b, c, d=None):
32 pass
33
34 @classmethod
35 def cmeth(cls, a, b, c, d=None):
36 pass
37
38 @staticmethod
39 def smeth(a, b, c, d=None):
40 pass
41
Michael Foord345266a2012-03-14 12:24:34 -070042
43class MockTest(unittest.TestCase):
44
45 def test_all(self):
46 # if __all__ is badly defined then import * will raise an error
47 # We have to exec it because you can't import * inside a method
48 # in Python 3
Michael Foord83a16852012-03-14 12:58:46 -070049 exec("from unittest.mock import *")
Michael Foord345266a2012-03-14 12:24:34 -070050
51
52 def test_constructor(self):
53 mock = Mock()
54
55 self.assertFalse(mock.called, "called not initialised correctly")
56 self.assertEqual(mock.call_count, 0,
57 "call_count not initialised correctly")
58 self.assertTrue(is_instance(mock.return_value, Mock),
59 "return_value not initialised correctly")
60
61 self.assertEqual(mock.call_args, None,
62 "call_args not initialised correctly")
63 self.assertEqual(mock.call_args_list, [],
64 "call_args_list not initialised correctly")
65 self.assertEqual(mock.method_calls, [],
66 "method_calls not initialised correctly")
67
68 # Can't use hasattr for this test as it always returns True on a mock
Serhiy Storchaka5665bc52013-11-17 00:12:21 +020069 self.assertNotIn('_items', mock.__dict__,
Michael Foord345266a2012-03-14 12:24:34 -070070 "default mock should not have '_items' attribute")
71
72 self.assertIsNone(mock._mock_parent,
73 "parent not initialised correctly")
74 self.assertIsNone(mock._mock_methods,
75 "methods not initialised correctly")
76 self.assertEqual(mock._mock_children, {},
77 "children not initialised incorrectly")
78
79
80 def test_return_value_in_constructor(self):
81 mock = Mock(return_value=None)
82 self.assertIsNone(mock.return_value,
83 "return value in constructor not honoured")
84
85
86 def test_repr(self):
87 mock = Mock(name='foo')
88 self.assertIn('foo', repr(mock))
89 self.assertIn("'%s'" % id(mock), repr(mock))
90
91 mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')]
92 for mock, name in mocks:
93 self.assertIn('%s.bar' % name, repr(mock.bar))
94 self.assertIn('%s.foo()' % name, repr(mock.foo()))
95 self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing))
96 self.assertIn('%s()' % name, repr(mock()))
97 self.assertIn('%s()()' % name, repr(mock()()))
98 self.assertIn('%s()().foo.bar.baz().bing' % name,
99 repr(mock()().foo.bar.baz().bing))
100
101
102 def test_repr_with_spec(self):
103 class X(object):
104 pass
105
106 mock = Mock(spec=X)
107 self.assertIn(" spec='X' ", repr(mock))
108
109 mock = Mock(spec=X())
110 self.assertIn(" spec='X' ", repr(mock))
111
112 mock = Mock(spec_set=X)
113 self.assertIn(" spec_set='X' ", repr(mock))
114
115 mock = Mock(spec_set=X())
116 self.assertIn(" spec_set='X' ", repr(mock))
117
118 mock = Mock(spec=X, name='foo')
119 self.assertIn(" spec='X' ", repr(mock))
120 self.assertIn(" name='foo' ", repr(mock))
121
122 mock = Mock(name='foo')
123 self.assertNotIn("spec", repr(mock))
124
125 mock = Mock()
126 self.assertNotIn("spec", repr(mock))
127
128 mock = Mock(spec=['foo'])
129 self.assertNotIn("spec", repr(mock))
130
131
132 def test_side_effect(self):
133 mock = Mock()
134
135 def effect(*args, **kwargs):
136 raise SystemError('kablooie')
137
138 mock.side_effect = effect
139 self.assertRaises(SystemError, mock, 1, 2, fish=3)
140 mock.assert_called_with(1, 2, fish=3)
141
142 results = [1, 2, 3]
143 def effect():
144 return results.pop()
145 mock.side_effect = effect
146
147 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
148 "side effect not used correctly")
149
150 mock = Mock(side_effect=sentinel.SideEffect)
151 self.assertEqual(mock.side_effect, sentinel.SideEffect,
152 "side effect in constructor not used")
153
154 def side_effect():
155 return DEFAULT
156 mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
157 self.assertEqual(mock(), sentinel.RETURN)
158
Michael Foord01bafdc2014-04-14 16:09:42 -0400159 def test_autospec_side_effect(self):
160 # Test for issue17826
161 results = [1, 2, 3]
162 def effect():
163 return results.pop()
164 def f():
165 pass
166
167 mock = create_autospec(f)
168 mock.side_effect = [1, 2, 3]
169 self.assertEqual([mock(), mock(), mock()], [1, 2, 3],
170 "side effect not used correctly in create_autospec")
171 # Test where side effect is a callable
172 results = [1, 2, 3]
173 mock = create_autospec(f)
174 mock.side_effect = effect
175 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
176 "callable side effect not used correctly")
Michael Foord345266a2012-03-14 12:24:34 -0700177
Robert Collinsf58f88c2015-07-14 13:51:40 +1200178 def test_autospec_side_effect_exception(self):
179 # Test for issue 23661
180 def f():
181 pass
182
183 mock = create_autospec(f)
184 mock.side_effect = ValueError('Bazinga!')
185 self.assertRaisesRegex(ValueError, 'Bazinga!', mock)
186
Michael Foord345266a2012-03-14 12:24:34 -0700187 @unittest.skipUnless('java' in sys.platform,
188 'This test only applies to Jython')
189 def test_java_exception_side_effect(self):
190 import java
191 mock = Mock(side_effect=java.lang.RuntimeException("Boom!"))
192
193 # can't use assertRaises with java exceptions
194 try:
195 mock(1, 2, fish=3)
196 except java.lang.RuntimeException:
197 pass
198 else:
199 self.fail('java exception not raised')
200 mock.assert_called_with(1,2, fish=3)
201
202
203 def test_reset_mock(self):
204 parent = Mock()
205 spec = ["something"]
206 mock = Mock(name="child", parent=parent, spec=spec)
207 mock(sentinel.Something, something=sentinel.SomethingElse)
208 something = mock.something
209 mock.something()
210 mock.side_effect = sentinel.SideEffect
211 return_value = mock.return_value
212 return_value()
213
214 mock.reset_mock()
215
216 self.assertEqual(mock._mock_name, "child",
217 "name incorrectly reset")
218 self.assertEqual(mock._mock_parent, parent,
219 "parent incorrectly reset")
220 self.assertEqual(mock._mock_methods, spec,
221 "methods incorrectly reset")
222
223 self.assertFalse(mock.called, "called not reset")
224 self.assertEqual(mock.call_count, 0, "call_count not reset")
225 self.assertEqual(mock.call_args, None, "call_args not reset")
226 self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
227 self.assertEqual(mock.method_calls, [],
228 "method_calls not initialised correctly: %r != %r" %
229 (mock.method_calls, []))
230 self.assertEqual(mock.mock_calls, [])
231
232 self.assertEqual(mock.side_effect, sentinel.SideEffect,
233 "side_effect incorrectly reset")
234 self.assertEqual(mock.return_value, return_value,
235 "return_value incorrectly reset")
236 self.assertFalse(return_value.called, "return value mock not reset")
237 self.assertEqual(mock._mock_children, {'something': something},
238 "children reset incorrectly")
239 self.assertEqual(mock.something, something,
240 "children incorrectly cleared")
241 self.assertFalse(mock.something.called, "child not reset")
242
243
244 def test_reset_mock_recursion(self):
245 mock = Mock()
246 mock.return_value = mock
247
248 # used to cause recursion
249 mock.reset_mock()
250
Robert Collinsb37f43f2015-07-15 11:42:28 +1200251 def test_reset_mock_on_mock_open_issue_18622(self):
252 a = mock.mock_open()
253 a.reset_mock()
Michael Foord345266a2012-03-14 12:24:34 -0700254
255 def test_call(self):
256 mock = Mock()
257 self.assertTrue(is_instance(mock.return_value, Mock),
258 "Default return_value should be a Mock")
259
260 result = mock()
261 self.assertEqual(mock(), result,
262 "different result from consecutive calls")
263 mock.reset_mock()
264
265 ret_val = mock(sentinel.Arg)
266 self.assertTrue(mock.called, "called not set")
267 self.assertEqual(mock.call_count, 1, "call_count incoreect")
268 self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
269 "call_args not set")
270 self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
271 "call_args_list not initialised correctly")
272
273 mock.return_value = sentinel.ReturnValue
274 ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
275 self.assertEqual(ret_val, sentinel.ReturnValue,
276 "incorrect return value")
277
278 self.assertEqual(mock.call_count, 2, "call_count incorrect")
279 self.assertEqual(mock.call_args,
280 ((sentinel.Arg,), {'key': sentinel.KeyArg}),
281 "call_args not set")
282 self.assertEqual(mock.call_args_list, [
283 ((sentinel.Arg,), {}),
284 ((sentinel.Arg,), {'key': sentinel.KeyArg})
285 ],
286 "call_args_list not set")
287
288
289 def test_call_args_comparison(self):
290 mock = Mock()
291 mock()
292 mock(sentinel.Arg)
293 mock(kw=sentinel.Kwarg)
294 mock(sentinel.Arg, kw=sentinel.Kwarg)
295 self.assertEqual(mock.call_args_list, [
296 (),
297 ((sentinel.Arg,),),
298 ({"kw": sentinel.Kwarg},),
299 ((sentinel.Arg,), {"kw": sentinel.Kwarg})
300 ])
301 self.assertEqual(mock.call_args,
302 ((sentinel.Arg,), {"kw": sentinel.Kwarg}))
303
Berker Peksag3fc536f2015-09-09 23:35:25 +0300304 # Comparing call_args to a long sequence should not raise
305 # an exception. See issue 24857.
306 self.assertFalse(mock.call_args == "a long sequence")
Michael Foord345266a2012-03-14 12:24:34 -0700307
Berker Peksagce913872016-03-28 00:30:02 +0300308
309 def test_calls_equal_with_any(self):
Berker Peksagce913872016-03-28 00:30:02 +0300310 # Check that equality and non-equality is consistent even when
311 # comparing with mock.ANY
Serhiy Storchaka362f0582017-01-21 23:12:58 +0200312 mm = mock.MagicMock()
313 self.assertTrue(mm == mm)
314 self.assertFalse(mm != mm)
315 self.assertFalse(mm == mock.MagicMock())
316 self.assertTrue(mm != mock.MagicMock())
317 self.assertTrue(mm == mock.ANY)
318 self.assertFalse(mm != mock.ANY)
319 self.assertTrue(mock.ANY == mm)
320 self.assertFalse(mock.ANY != mm)
321
322 call1 = mock.call(mock.MagicMock())
323 call2 = mock.call(mock.ANY)
Berker Peksagce913872016-03-28 00:30:02 +0300324 self.assertTrue(call1 == call2)
325 self.assertFalse(call1 != call2)
Serhiy Storchaka362f0582017-01-21 23:12:58 +0200326 self.assertTrue(call2 == call1)
327 self.assertFalse(call2 != call1)
Berker Peksagce913872016-03-28 00:30:02 +0300328
329
Michael Foord345266a2012-03-14 12:24:34 -0700330 def test_assert_called_with(self):
331 mock = Mock()
332 mock()
333
334 # Will raise an exception if it fails
335 mock.assert_called_with()
336 self.assertRaises(AssertionError, mock.assert_called_with, 1)
337
338 mock.reset_mock()
339 self.assertRaises(AssertionError, mock.assert_called_with)
340
341 mock(1, 2, 3, a='fish', b='nothing')
342 mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
343
344
Berker Peksagce913872016-03-28 00:30:02 +0300345 def test_assert_called_with_any(self):
346 m = MagicMock()
347 m(MagicMock())
348 m.assert_called_with(mock.ANY)
349
350
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100351 def test_assert_called_with_function_spec(self):
352 def f(a, b, c, d=None):
353 pass
354
355 mock = Mock(spec=f)
356
357 mock(1, b=2, c=3)
358 mock.assert_called_with(1, 2, 3)
359 mock.assert_called_with(a=1, b=2, c=3)
360 self.assertRaises(AssertionError, mock.assert_called_with,
361 1, b=3, c=2)
362 # Expected call doesn't match the spec's signature
363 with self.assertRaises(AssertionError) as cm:
364 mock.assert_called_with(e=8)
365 self.assertIsInstance(cm.exception.__cause__, TypeError)
366
367
368 def test_assert_called_with_method_spec(self):
369 def _check(mock):
370 mock(1, b=2, c=3)
371 mock.assert_called_with(1, 2, 3)
372 mock.assert_called_with(a=1, b=2, c=3)
373 self.assertRaises(AssertionError, mock.assert_called_with,
374 1, b=3, c=2)
375
376 mock = Mock(spec=Something().meth)
377 _check(mock)
378 mock = Mock(spec=Something.cmeth)
379 _check(mock)
380 mock = Mock(spec=Something().cmeth)
381 _check(mock)
382 mock = Mock(spec=Something.smeth)
383 _check(mock)
384 mock = Mock(spec=Something().smeth)
385 _check(mock)
386
387
Michael Foord345266a2012-03-14 12:24:34 -0700388 def test_assert_called_once_with(self):
389 mock = Mock()
390 mock()
391
392 # Will raise an exception if it fails
393 mock.assert_called_once_with()
394
395 mock()
396 self.assertRaises(AssertionError, mock.assert_called_once_with)
397
398 mock.reset_mock()
399 self.assertRaises(AssertionError, mock.assert_called_once_with)
400
401 mock('foo', 'bar', baz=2)
402 mock.assert_called_once_with('foo', 'bar', baz=2)
403
404 mock.reset_mock()
405 mock('foo', 'bar', baz=2)
406 self.assertRaises(
407 AssertionError,
408 lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
409 )
410
Petter Strandmark47d94242018-10-28 21:37:10 +0100411 def test_assert_called_once_with_call_list(self):
412 m = Mock()
413 m(1)
414 m(2)
415 self.assertRaisesRegex(AssertionError,
416 re.escape("Calls: [call(1), call(2)]"),
417 lambda: m.assert_called_once_with(2))
418
Michael Foord345266a2012-03-14 12:24:34 -0700419
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100420 def test_assert_called_once_with_function_spec(self):
421 def f(a, b, c, d=None):
422 pass
423
424 mock = Mock(spec=f)
425
426 mock(1, b=2, c=3)
427 mock.assert_called_once_with(1, 2, 3)
428 mock.assert_called_once_with(a=1, b=2, c=3)
429 self.assertRaises(AssertionError, mock.assert_called_once_with,
430 1, b=3, c=2)
431 # Expected call doesn't match the spec's signature
432 with self.assertRaises(AssertionError) as cm:
433 mock.assert_called_once_with(e=8)
434 self.assertIsInstance(cm.exception.__cause__, TypeError)
435 # Mock called more than once => always fails
436 mock(4, 5, 6)
437 self.assertRaises(AssertionError, mock.assert_called_once_with,
438 1, 2, 3)
439 self.assertRaises(AssertionError, mock.assert_called_once_with,
440 4, 5, 6)
441
442
Michael Foord345266a2012-03-14 12:24:34 -0700443 def test_attribute_access_returns_mocks(self):
444 mock = Mock()
445 something = mock.something
446 self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
447 self.assertEqual(mock.something, something,
448 "different attributes returned for same name")
449
450 # Usage example
451 mock = Mock()
452 mock.something.return_value = 3
453
454 self.assertEqual(mock.something(), 3, "method returned wrong value")
455 self.assertTrue(mock.something.called,
456 "method didn't record being called")
457
458
459 def test_attributes_have_name_and_parent_set(self):
460 mock = Mock()
461 something = mock.something
462
463 self.assertEqual(something._mock_name, "something",
464 "attribute name not set correctly")
465 self.assertEqual(something._mock_parent, mock,
466 "attribute parent not set correctly")
467
468
469 def test_method_calls_recorded(self):
470 mock = Mock()
471 mock.something(3, fish=None)
472 mock.something_else.something(6, cake=sentinel.Cake)
473
474 self.assertEqual(mock.something_else.method_calls,
475 [("something", (6,), {'cake': sentinel.Cake})],
476 "method calls not recorded correctly")
477 self.assertEqual(mock.method_calls, [
478 ("something", (3,), {'fish': None}),
479 ("something_else.something", (6,), {'cake': sentinel.Cake})
480 ],
481 "method calls not recorded correctly")
482
483
484 def test_method_calls_compare_easily(self):
485 mock = Mock()
486 mock.something()
487 self.assertEqual(mock.method_calls, [('something',)])
488 self.assertEqual(mock.method_calls, [('something', (), {})])
489
490 mock = Mock()
491 mock.something('different')
492 self.assertEqual(mock.method_calls, [('something', ('different',))])
493 self.assertEqual(mock.method_calls,
494 [('something', ('different',), {})])
495
496 mock = Mock()
497 mock.something(x=1)
498 self.assertEqual(mock.method_calls, [('something', {'x': 1})])
499 self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
500
501 mock = Mock()
502 mock.something('different', some='more')
503 self.assertEqual(mock.method_calls, [
504 ('something', ('different',), {'some': 'more'})
505 ])
506
507
508 def test_only_allowed_methods_exist(self):
509 for spec in ['something'], ('something',):
510 for arg in 'spec', 'spec_set':
511 mock = Mock(**{arg: spec})
512
513 # this should be allowed
514 mock.something
515 self.assertRaisesRegex(
516 AttributeError,
517 "Mock object has no attribute 'something_else'",
518 getattr, mock, 'something_else'
519 )
520
521
522 def test_from_spec(self):
523 class Something(object):
524 x = 3
525 __something__ = None
526 def y(self):
527 pass
528
529 def test_attributes(mock):
530 # should work
531 mock.x
532 mock.y
533 mock.__something__
534 self.assertRaisesRegex(
535 AttributeError,
536 "Mock object has no attribute 'z'",
537 getattr, mock, 'z'
538 )
539 self.assertRaisesRegex(
540 AttributeError,
541 "Mock object has no attribute '__foobar__'",
542 getattr, mock, '__foobar__'
543 )
544
545 test_attributes(Mock(spec=Something))
546 test_attributes(Mock(spec=Something()))
547
548
549 def test_wraps_calls(self):
550 real = Mock()
551
552 mock = Mock(wraps=real)
553 self.assertEqual(mock(), real())
554
555 real.reset_mock()
556
557 mock(1, 2, fish=3)
558 real.assert_called_with(1, 2, fish=3)
559
560
561 def test_wraps_call_with_nondefault_return_value(self):
562 real = Mock()
563
564 mock = Mock(wraps=real)
565 mock.return_value = 3
566
567 self.assertEqual(mock(), 3)
568 self.assertFalse(real.called)
569
570
571 def test_wraps_attributes(self):
572 class Real(object):
573 attribute = Mock()
574
575 real = Real()
576
577 mock = Mock(wraps=real)
578 self.assertEqual(mock.attribute(), real.attribute())
579 self.assertRaises(AttributeError, lambda: mock.fish)
580
581 self.assertNotEqual(mock.attribute, real.attribute)
582 result = mock.attribute.frog(1, 2, fish=3)
583 Real.attribute.frog.assert_called_with(1, 2, fish=3)
584 self.assertEqual(result, Real.attribute.frog())
585
586
587 def test_exceptional_side_effect(self):
588 mock = Mock(side_effect=AttributeError)
589 self.assertRaises(AttributeError, mock)
590
591 mock = Mock(side_effect=AttributeError('foo'))
592 self.assertRaises(AttributeError, mock)
593
594
595 def test_baseexceptional_side_effect(self):
596 mock = Mock(side_effect=KeyboardInterrupt)
597 self.assertRaises(KeyboardInterrupt, mock)
598
599 mock = Mock(side_effect=KeyboardInterrupt('foo'))
600 self.assertRaises(KeyboardInterrupt, mock)
601
602
603 def test_assert_called_with_message(self):
604 mock = Mock()
605 self.assertRaisesRegex(AssertionError, 'Not called',
606 mock.assert_called_with)
607
608
Michael Foord28d591c2012-09-28 16:15:22 +0100609 def test_assert_called_once_with_message(self):
610 mock = Mock(name='geoffrey')
611 self.assertRaisesRegex(AssertionError,
612 r"Expected 'geoffrey' to be called once\.",
613 mock.assert_called_once_with)
614
615
Michael Foord345266a2012-03-14 12:24:34 -0700616 def test__name__(self):
617 mock = Mock()
618 self.assertRaises(AttributeError, lambda: mock.__name__)
619
620 mock.__name__ = 'foo'
621 self.assertEqual(mock.__name__, 'foo')
622
623
624 def test_spec_list_subclass(self):
625 class Sub(list):
626 pass
627 mock = Mock(spec=Sub(['foo']))
628
629 mock.append(3)
630 mock.append.assert_called_with(3)
631 self.assertRaises(AttributeError, getattr, mock, 'foo')
632
633
634 def test_spec_class(self):
635 class X(object):
636 pass
637
638 mock = Mock(spec=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200639 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700640
641 mock = Mock(spec=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200642 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700643
644 self.assertIs(mock.__class__, X)
645 self.assertEqual(Mock().__class__.__name__, 'Mock')
646
647 mock = Mock(spec_set=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200648 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700649
650 mock = Mock(spec_set=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200651 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700652
653
654 def test_setting_attribute_with_spec_set(self):
655 class X(object):
656 y = 3
657
658 mock = Mock(spec=X)
659 mock.x = 'foo'
660
661 mock = Mock(spec_set=X)
662 def set_attr():
663 mock.x = 'foo'
664
665 mock.y = 'foo'
666 self.assertRaises(AttributeError, set_attr)
667
668
669 def test_copy(self):
670 current = sys.getrecursionlimit()
671 self.addCleanup(sys.setrecursionlimit, current)
672
673 # can't use sys.maxint as this doesn't exist in Python 3
674 sys.setrecursionlimit(int(10e8))
675 # this segfaults without the fix in place
676 copy.copy(Mock())
677
678
679 def test_subclass_with_properties(self):
680 class SubClass(Mock):
681 def _get(self):
682 return 3
683 def _set(self, value):
684 raise NameError('strange error')
685 some_attribute = property(_get, _set)
686
687 s = SubClass(spec_set=SubClass)
688 self.assertEqual(s.some_attribute, 3)
689
690 def test():
691 s.some_attribute = 3
692 self.assertRaises(NameError, test)
693
694 def test():
695 s.foo = 'bar'
696 self.assertRaises(AttributeError, test)
697
698
699 def test_setting_call(self):
700 mock = Mock()
701 def __call__(self, a):
702 return self._mock_call(a)
703
704 type(mock).__call__ = __call__
705 mock('one')
706 mock.assert_called_with('one')
707
708 self.assertRaises(TypeError, mock, 'one', 'two')
709
710
711 def test_dir(self):
712 mock = Mock()
713 attrs = set(dir(mock))
714 type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
715
716 # all public attributes from the type are included
717 self.assertEqual(set(), type_attrs - attrs)
718
719 # creates these attributes
720 mock.a, mock.b
721 self.assertIn('a', dir(mock))
722 self.assertIn('b', dir(mock))
723
724 # instance attributes
725 mock.c = mock.d = None
726 self.assertIn('c', dir(mock))
727 self.assertIn('d', dir(mock))
728
729 # magic methods
730 mock.__iter__ = lambda s: iter([])
731 self.assertIn('__iter__', dir(mock))
732
733
734 def test_dir_from_spec(self):
735 mock = Mock(spec=unittest.TestCase)
736 testcase_attrs = set(dir(unittest.TestCase))
737 attrs = set(dir(mock))
738
739 # all attributes from the spec are included
740 self.assertEqual(set(), testcase_attrs - attrs)
741
742 # shadow a sys attribute
743 mock.version = 3
744 self.assertEqual(dir(mock).count('version'), 1)
745
746
747 def test_filter_dir(self):
748 patcher = patch.object(mock, 'FILTER_DIR', False)
749 patcher.start()
750 try:
751 attrs = set(dir(Mock()))
752 type_attrs = set(dir(Mock))
753
754 # ALL attributes from the type are included
755 self.assertEqual(set(), type_attrs - attrs)
756 finally:
757 patcher.stop()
758
759
760 def test_configure_mock(self):
761 mock = Mock(foo='bar')
762 self.assertEqual(mock.foo, 'bar')
763
764 mock = MagicMock(foo='bar')
765 self.assertEqual(mock.foo, 'bar')
766
767 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
768 'foo': MagicMock()}
769 mock = Mock(**kwargs)
770 self.assertRaises(KeyError, mock)
771 self.assertEqual(mock.foo.bar(), 33)
772 self.assertIsInstance(mock.foo, MagicMock)
773
774 mock = Mock()
775 mock.configure_mock(**kwargs)
776 self.assertRaises(KeyError, mock)
777 self.assertEqual(mock.foo.bar(), 33)
778 self.assertIsInstance(mock.foo, MagicMock)
779
780
781 def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
782 # needed because assertRaisesRegex doesn't work easily with newlines
783 try:
784 func(*args, **kwargs)
785 except:
786 instance = sys.exc_info()[1]
787 self.assertIsInstance(instance, exception)
788 else:
789 self.fail('Exception %r not raised' % (exception,))
790
791 msg = str(instance)
792 self.assertEqual(msg, message)
793
794
795 def test_assert_called_with_failure_message(self):
796 mock = NonCallableMock()
797
798 expected = "mock(1, '2', 3, bar='foo')"
799 message = 'Expected call: %s\nNot called'
800 self.assertRaisesWithMsg(
801 AssertionError, message % (expected,),
802 mock.assert_called_with, 1, '2', 3, bar='foo'
803 )
804
805 mock.foo(1, '2', 3, foo='foo')
806
807
808 asserters = [
809 mock.foo.assert_called_with, mock.foo.assert_called_once_with
810 ]
811 for meth in asserters:
812 actual = "foo(1, '2', 3, foo='foo')"
813 expected = "foo(1, '2', 3, bar='foo')"
814 message = 'Expected call: %s\nActual call: %s'
815 self.assertRaisesWithMsg(
816 AssertionError, message % (expected, actual),
817 meth, 1, '2', 3, bar='foo'
818 )
819
820 # just kwargs
821 for meth in asserters:
822 actual = "foo(1, '2', 3, foo='foo')"
823 expected = "foo(bar='foo')"
824 message = 'Expected call: %s\nActual call: %s'
825 self.assertRaisesWithMsg(
826 AssertionError, message % (expected, actual),
827 meth, bar='foo'
828 )
829
830 # just args
831 for meth in asserters:
832 actual = "foo(1, '2', 3, foo='foo')"
833 expected = "foo(1, 2, 3)"
834 message = 'Expected call: %s\nActual call: %s'
835 self.assertRaisesWithMsg(
836 AssertionError, message % (expected, actual),
837 meth, 1, 2, 3
838 )
839
840 # empty
841 for meth in asserters:
842 actual = "foo(1, '2', 3, foo='foo')"
843 expected = "foo()"
844 message = 'Expected call: %s\nActual call: %s'
845 self.assertRaisesWithMsg(
846 AssertionError, message % (expected, actual), meth
847 )
848
849
850 def test_mock_calls(self):
851 mock = MagicMock()
852
853 # need to do this because MagicMock.mock_calls used to just return
854 # a MagicMock which also returned a MagicMock when __eq__ was called
855 self.assertIs(mock.mock_calls == [], True)
856
857 mock = MagicMock()
858 mock()
859 expected = [('', (), {})]
860 self.assertEqual(mock.mock_calls, expected)
861
862 mock.foo()
863 expected.append(call.foo())
864 self.assertEqual(mock.mock_calls, expected)
865 # intermediate mock_calls work too
866 self.assertEqual(mock.foo.mock_calls, [('', (), {})])
867
868 mock = MagicMock()
869 mock().foo(1, 2, 3, a=4, b=5)
870 expected = [
871 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
872 ]
873 self.assertEqual(mock.mock_calls, expected)
874 self.assertEqual(mock.return_value.foo.mock_calls,
875 [('', (1, 2, 3), dict(a=4, b=5))])
876 self.assertEqual(mock.return_value.mock_calls,
877 [('foo', (1, 2, 3), dict(a=4, b=5))])
878
879 mock = MagicMock()
880 mock().foo.bar().baz()
881 expected = [
882 ('', (), {}), ('().foo.bar', (), {}),
883 ('().foo.bar().baz', (), {})
884 ]
885 self.assertEqual(mock.mock_calls, expected)
886 self.assertEqual(mock().mock_calls,
887 call.foo.bar().baz().call_list())
888
889 for kwargs in dict(), dict(name='bar'):
890 mock = MagicMock(**kwargs)
891 int(mock.foo)
892 expected = [('foo.__int__', (), {})]
893 self.assertEqual(mock.mock_calls, expected)
894
895 mock = MagicMock(**kwargs)
896 mock.a()()
897 expected = [('a', (), {}), ('a()', (), {})]
898 self.assertEqual(mock.mock_calls, expected)
899 self.assertEqual(mock.a().mock_calls, [call()])
900
901 mock = MagicMock(**kwargs)
902 mock(1)(2)(3)
903 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
904 self.assertEqual(mock().mock_calls, call(2)(3).call_list())
905 self.assertEqual(mock()().mock_calls, call(3).call_list())
906
907 mock = MagicMock(**kwargs)
908 mock(1)(2)(3).a.b.c(4)
909 self.assertEqual(mock.mock_calls,
910 call(1)(2)(3).a.b.c(4).call_list())
911 self.assertEqual(mock().mock_calls,
912 call(2)(3).a.b.c(4).call_list())
913 self.assertEqual(mock()().mock_calls,
914 call(3).a.b.c(4).call_list())
915
916 mock = MagicMock(**kwargs)
917 int(mock().foo.bar().baz())
918 last_call = ('().foo.bar().baz().__int__', (), {})
919 self.assertEqual(mock.mock_calls[-1], last_call)
920 self.assertEqual(mock().mock_calls,
921 call.foo.bar().baz().__int__().call_list())
922 self.assertEqual(mock().foo.bar().mock_calls,
923 call.baz().__int__().call_list())
924 self.assertEqual(mock().foo.bar().baz.mock_calls,
925 call().__int__().call_list())
926
927
Chris Withers8ca0fa92018-12-03 21:31:37 +0000928 def test_child_mock_call_equal(self):
929 m = Mock()
930 result = m()
931 result.wibble()
932 # parent looks like this:
933 self.assertEqual(m.mock_calls, [call(), call().wibble()])
934 # but child should look like this:
935 self.assertEqual(result.mock_calls, [call.wibble()])
936
937
938 def test_mock_call_not_equal_leaf(self):
939 m = Mock()
940 m.foo().something()
941 self.assertNotEqual(m.mock_calls[1], call.foo().different())
942 self.assertEqual(m.mock_calls[0], call.foo())
943
944
945 def test_mock_call_not_equal_non_leaf(self):
946 m = Mock()
947 m.foo().bar()
948 self.assertNotEqual(m.mock_calls[1], call.baz().bar())
949 self.assertNotEqual(m.mock_calls[0], call.baz())
950
951
952 def test_mock_call_not_equal_non_leaf_params_different(self):
953 m = Mock()
954 m.foo(x=1).bar()
955 # This isn't ideal, but there's no way to fix it without breaking backwards compatibility:
956 self.assertEqual(m.mock_calls[1], call.foo(x=2).bar())
957
958
959 def test_mock_call_not_equal_non_leaf_attr(self):
960 m = Mock()
961 m.foo.bar()
962 self.assertNotEqual(m.mock_calls[0], call.baz.bar())
963
964
965 def test_mock_call_not_equal_non_leaf_call_versus_attr(self):
966 m = Mock()
967 m.foo.bar()
968 self.assertNotEqual(m.mock_calls[0], call.foo().bar())
969
970
971 def test_mock_call_repr(self):
972 m = Mock()
973 m.foo().bar().baz.bob()
974 self.assertEqual(repr(m.mock_calls[0]), 'call.foo()')
975 self.assertEqual(repr(m.mock_calls[1]), 'call.foo().bar()')
976 self.assertEqual(repr(m.mock_calls[2]), 'call.foo().bar().baz.bob()')
977
978
Michael Foord345266a2012-03-14 12:24:34 -0700979 def test_subclassing(self):
980 class Subclass(Mock):
981 pass
982
983 mock = Subclass()
984 self.assertIsInstance(mock.foo, Subclass)
985 self.assertIsInstance(mock(), Subclass)
986
987 class Subclass(Mock):
988 def _get_child_mock(self, **kwargs):
989 return Mock(**kwargs)
990
991 mock = Subclass()
992 self.assertNotIsInstance(mock.foo, Subclass)
993 self.assertNotIsInstance(mock(), Subclass)
994
995
996 def test_arg_lists(self):
997 mocks = [
998 Mock(),
999 MagicMock(),
1000 NonCallableMock(),
1001 NonCallableMagicMock()
1002 ]
1003
1004 def assert_attrs(mock):
1005 names = 'call_args_list', 'method_calls', 'mock_calls'
1006 for name in names:
1007 attr = getattr(mock, name)
1008 self.assertIsInstance(attr, _CallList)
1009 self.assertIsInstance(attr, list)
1010 self.assertEqual(attr, [])
1011
1012 for mock in mocks:
1013 assert_attrs(mock)
1014
1015 if callable(mock):
1016 mock()
1017 mock(1, 2)
1018 mock(a=3)
1019
1020 mock.reset_mock()
1021 assert_attrs(mock)
1022
1023 mock.foo()
1024 mock.foo.bar(1, a=3)
1025 mock.foo(1).bar().baz(3)
1026
1027 mock.reset_mock()
1028 assert_attrs(mock)
1029
1030
1031 def test_call_args_two_tuple(self):
1032 mock = Mock()
1033 mock(1, a=3)
1034 mock(2, b=4)
1035
1036 self.assertEqual(len(mock.call_args), 2)
1037 args, kwargs = mock.call_args
1038 self.assertEqual(args, (2,))
1039 self.assertEqual(kwargs, dict(b=4))
1040
1041 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
1042 for expected, call_args in zip(expected_list, mock.call_args_list):
1043 self.assertEqual(len(call_args), 2)
1044 self.assertEqual(expected[0], call_args[0])
1045 self.assertEqual(expected[1], call_args[1])
1046
1047
1048 def test_side_effect_iterator(self):
1049 mock = Mock(side_effect=iter([1, 2, 3]))
1050 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1051 self.assertRaises(StopIteration, mock)
1052
1053 mock = MagicMock(side_effect=['a', 'b', 'c'])
1054 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1055 self.assertRaises(StopIteration, mock)
1056
1057 mock = Mock(side_effect='ghi')
1058 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
1059 self.assertRaises(StopIteration, mock)
1060
1061 class Foo(object):
1062 pass
1063 mock = MagicMock(side_effect=Foo)
1064 self.assertIsInstance(mock(), Foo)
1065
1066 mock = Mock(side_effect=Iter())
1067 self.assertEqual([mock(), mock(), mock(), mock()],
1068 ['this', 'is', 'an', 'iter'])
1069 self.assertRaises(StopIteration, mock)
1070
1071
Michael Foord2cd48732012-04-21 15:52:11 +01001072 def test_side_effect_iterator_exceptions(self):
1073 for Klass in Mock, MagicMock:
1074 iterable = (ValueError, 3, KeyError, 6)
1075 m = Klass(side_effect=iterable)
1076 self.assertRaises(ValueError, m)
1077 self.assertEqual(m(), 3)
1078 self.assertRaises(KeyError, m)
1079 self.assertEqual(m(), 6)
1080
1081
Michael Foord345266a2012-03-14 12:24:34 -07001082 def test_side_effect_setting_iterator(self):
1083 mock = Mock()
1084 mock.side_effect = iter([1, 2, 3])
1085 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1086 self.assertRaises(StopIteration, mock)
1087 side_effect = mock.side_effect
1088 self.assertIsInstance(side_effect, type(iter([])))
1089
1090 mock.side_effect = ['a', 'b', 'c']
1091 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1092 self.assertRaises(StopIteration, mock)
1093 side_effect = mock.side_effect
1094 self.assertIsInstance(side_effect, type(iter([])))
1095
1096 this_iter = Iter()
1097 mock.side_effect = this_iter
1098 self.assertEqual([mock(), mock(), mock(), mock()],
1099 ['this', 'is', 'an', 'iter'])
1100 self.assertRaises(StopIteration, mock)
1101 self.assertIs(mock.side_effect, this_iter)
1102
Andrew Svetlov8b2cd752013-04-07 16:42:24 +03001103 def test_side_effect_iterator_default(self):
1104 mock = Mock(return_value=2)
1105 mock.side_effect = iter([1, DEFAULT])
1106 self.assertEqual([mock(), mock()], [1, 2])
Michael Foord345266a2012-03-14 12:24:34 -07001107
1108 def test_assert_has_calls_any_order(self):
1109 mock = Mock()
1110 mock(1, 2)
1111 mock(a=3)
1112 mock(3, 4)
1113 mock(b=6)
1114 mock(b=6)
1115
1116 kalls = [
1117 call(1, 2), ({'a': 3},),
1118 ((3, 4),), ((), {'a': 3}),
1119 ('', (1, 2)), ('', {'a': 3}),
1120 ('', (1, 2), {}), ('', (), {'a': 3})
1121 ]
1122 for kall in kalls:
1123 mock.assert_has_calls([kall], any_order=True)
1124
1125 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
1126 self.assertRaises(
1127 AssertionError, mock.assert_has_calls,
1128 [kall], any_order=True
1129 )
1130
1131 kall_lists = [
1132 [call(1, 2), call(b=6)],
1133 [call(3, 4), call(1, 2)],
1134 [call(b=6), call(b=6)],
1135 ]
1136
1137 for kall_list in kall_lists:
1138 mock.assert_has_calls(kall_list, any_order=True)
1139
1140 kall_lists = [
1141 [call(b=6), call(b=6), call(b=6)],
1142 [call(1, 2), call(1, 2)],
1143 [call(3, 4), call(1, 2), call(5, 7)],
1144 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
1145 ]
1146 for kall_list in kall_lists:
1147 self.assertRaises(
1148 AssertionError, mock.assert_has_calls,
1149 kall_list, any_order=True
1150 )
1151
1152 def test_assert_has_calls(self):
1153 kalls1 = [
1154 call(1, 2), ({'a': 3},),
1155 ((3, 4),), call(b=6),
1156 ('', (1,), {'b': 6}),
1157 ]
1158 kalls2 = [call.foo(), call.bar(1)]
1159 kalls2.extend(call.spam().baz(a=3).call_list())
1160 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
1161
1162 mocks = []
1163 for mock in Mock(), MagicMock():
1164 mock(1, 2)
1165 mock(a=3)
1166 mock(3, 4)
1167 mock(b=6)
1168 mock(1, b=6)
1169 mocks.append((mock, kalls1))
1170
1171 mock = Mock()
1172 mock.foo()
1173 mock.bar(1)
1174 mock.spam().baz(a=3)
1175 mock.bam(set(), foo={}).fish([1])
1176 mocks.append((mock, kalls2))
1177
1178 for mock, kalls in mocks:
1179 for i in range(len(kalls)):
1180 for step in 1, 2, 3:
1181 these = kalls[i:i+step]
1182 mock.assert_has_calls(these)
1183
1184 if len(these) > 1:
1185 self.assertRaises(
1186 AssertionError,
1187 mock.assert_has_calls,
1188 list(reversed(these))
1189 )
1190
1191
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001192 def test_assert_has_calls_with_function_spec(self):
1193 def f(a, b, c, d=None):
1194 pass
1195
1196 mock = Mock(spec=f)
1197
1198 mock(1, b=2, c=3)
1199 mock(4, 5, c=6, d=7)
1200 mock(10, 11, c=12)
1201 calls = [
1202 ('', (1, 2, 3), {}),
1203 ('', (4, 5, 6), {'d': 7}),
1204 ((10, 11, 12), {}),
1205 ]
1206 mock.assert_has_calls(calls)
1207 mock.assert_has_calls(calls, any_order=True)
1208 mock.assert_has_calls(calls[1:])
1209 mock.assert_has_calls(calls[1:], any_order=True)
1210 mock.assert_has_calls(calls[:-1])
1211 mock.assert_has_calls(calls[:-1], any_order=True)
1212 # Reversed order
1213 calls = list(reversed(calls))
1214 with self.assertRaises(AssertionError):
1215 mock.assert_has_calls(calls)
1216 mock.assert_has_calls(calls, any_order=True)
1217 with self.assertRaises(AssertionError):
1218 mock.assert_has_calls(calls[1:])
1219 mock.assert_has_calls(calls[1:], any_order=True)
1220 with self.assertRaises(AssertionError):
1221 mock.assert_has_calls(calls[:-1])
1222 mock.assert_has_calls(calls[:-1], any_order=True)
1223
1224
Michael Foord345266a2012-03-14 12:24:34 -07001225 def test_assert_any_call(self):
1226 mock = Mock()
1227 mock(1, 2)
1228 mock(a=3)
1229 mock(1, b=6)
1230
1231 mock.assert_any_call(1, 2)
1232 mock.assert_any_call(a=3)
1233 mock.assert_any_call(1, b=6)
1234
1235 self.assertRaises(
1236 AssertionError,
1237 mock.assert_any_call
1238 )
1239 self.assertRaises(
1240 AssertionError,
1241 mock.assert_any_call,
1242 1, 3
1243 )
1244 self.assertRaises(
1245 AssertionError,
1246 mock.assert_any_call,
1247 a=4
1248 )
1249
1250
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001251 def test_assert_any_call_with_function_spec(self):
1252 def f(a, b, c, d=None):
1253 pass
1254
1255 mock = Mock(spec=f)
1256
1257 mock(1, b=2, c=3)
1258 mock(4, 5, c=6, d=7)
1259 mock.assert_any_call(1, 2, 3)
1260 mock.assert_any_call(a=1, b=2, c=3)
1261 mock.assert_any_call(4, 5, 6, 7)
1262 mock.assert_any_call(a=4, b=5, c=6, d=7)
1263 self.assertRaises(AssertionError, mock.assert_any_call,
1264 1, b=3, c=2)
1265 # Expected call doesn't match the spec's signature
1266 with self.assertRaises(AssertionError) as cm:
1267 mock.assert_any_call(e=8)
1268 self.assertIsInstance(cm.exception.__cause__, TypeError)
1269
1270
Michael Foord345266a2012-03-14 12:24:34 -07001271 def test_mock_calls_create_autospec(self):
1272 def f(a, b):
1273 pass
1274 obj = Iter()
1275 obj.f = f
1276
1277 funcs = [
1278 create_autospec(f),
1279 create_autospec(obj).f
1280 ]
1281 for func in funcs:
1282 func(1, 2)
1283 func(3, 4)
1284
1285 self.assertEqual(
1286 func.mock_calls, [call(1, 2), call(3, 4)]
1287 )
1288
Kushal Das484f8a82014-04-16 01:05:50 +05301289 #Issue21222
1290 def test_create_autospec_with_name(self):
1291 m = mock.create_autospec(object(), name='sweet_func')
1292 self.assertIn('sweet_func', repr(m))
Michael Foord345266a2012-03-14 12:24:34 -07001293
Kushal Das8c145342014-04-16 23:32:21 +05301294 #Issue21238
1295 def test_mock_unsafe(self):
1296 m = Mock()
1297 with self.assertRaises(AttributeError):
1298 m.assert_foo_call()
1299 with self.assertRaises(AttributeError):
1300 m.assret_foo_call()
1301 m = Mock(unsafe=True)
1302 m.assert_foo_call()
1303 m.assret_foo_call()
1304
Kushal Das8af9db32014-04-17 01:36:14 +05301305 #Issue21262
1306 def test_assert_not_called(self):
1307 m = Mock()
1308 m.hello.assert_not_called()
1309 m.hello()
1310 with self.assertRaises(AssertionError):
1311 m.hello.assert_not_called()
1312
Petter Strandmark47d94242018-10-28 21:37:10 +01001313 def test_assert_not_called_message(self):
1314 m = Mock()
1315 m(1, 2)
1316 self.assertRaisesRegex(AssertionError,
1317 re.escape("Calls: [call(1, 2)]"),
1318 m.assert_not_called)
1319
Victor Stinner2c2a4e62016-03-11 22:17:48 +01001320 def test_assert_called(self):
1321 m = Mock()
1322 with self.assertRaises(AssertionError):
1323 m.hello.assert_called()
1324 m.hello()
1325 m.hello.assert_called()
1326
1327 m.hello()
1328 m.hello.assert_called()
1329
1330 def test_assert_called_once(self):
1331 m = Mock()
1332 with self.assertRaises(AssertionError):
1333 m.hello.assert_called_once()
1334 m.hello()
1335 m.hello.assert_called_once()
1336
1337 m.hello()
1338 with self.assertRaises(AssertionError):
1339 m.hello.assert_called_once()
1340
Petter Strandmark47d94242018-10-28 21:37:10 +01001341 def test_assert_called_once_message(self):
1342 m = Mock()
1343 m(1, 2)
1344 m(3)
1345 self.assertRaisesRegex(AssertionError,
1346 re.escape("Calls: [call(1, 2), call(3)]"),
1347 m.assert_called_once)
1348
1349 def test_assert_called_once_message_not_called(self):
1350 m = Mock()
1351 with self.assertRaises(AssertionError) as e:
1352 m.assert_called_once()
1353 self.assertNotIn("Calls:", str(e.exception))
1354
Kushal Das047f14c2014-06-09 13:45:56 +05301355 #Issue21256 printout of keyword args should be in deterministic order
1356 def test_sorted_call_signature(self):
1357 m = Mock()
1358 m.hello(name='hello', daddy='hero')
1359 text = "call(daddy='hero', name='hello')"
R David Murray130a5662014-06-11 17:09:43 -04001360 self.assertEqual(repr(m.hello.call_args), text)
Kushal Das8af9db32014-04-17 01:36:14 +05301361
Kushal Dasa37b9582014-09-16 18:33:37 +05301362 #Issue21270 overrides tuple methods for mock.call objects
1363 def test_override_tuple_methods(self):
1364 c = call.count()
1365 i = call.index(132,'hello')
1366 m = Mock()
1367 m.count()
1368 m.index(132,"hello")
1369 self.assertEqual(m.method_calls[0], c)
1370 self.assertEqual(m.method_calls[1], i)
1371
Kushal Das9cd39a12016-06-02 10:20:16 -07001372 def test_reset_return_sideeffect(self):
1373 m = Mock(return_value=10, side_effect=[2,3])
1374 m.reset_mock(return_value=True, side_effect=True)
1375 self.assertIsInstance(m.return_value, Mock)
1376 self.assertEqual(m.side_effect, None)
1377
1378 def test_reset_return(self):
1379 m = Mock(return_value=10, side_effect=[2,3])
1380 m.reset_mock(return_value=True)
1381 self.assertIsInstance(m.return_value, Mock)
1382 self.assertNotEqual(m.side_effect, None)
1383
1384 def test_reset_sideeffect(self):
1385 m = Mock(return_value=10, side_effect=[2,3])
1386 m.reset_mock(side_effect=True)
1387 self.assertEqual(m.return_value, 10)
1388 self.assertEqual(m.side_effect, None)
1389
Michael Foord345266a2012-03-14 12:24:34 -07001390 def test_mock_add_spec(self):
1391 class _One(object):
1392 one = 1
1393 class _Two(object):
1394 two = 2
1395 class Anything(object):
1396 one = two = three = 'four'
1397
1398 klasses = [
1399 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1400 ]
1401 for Klass in list(klasses):
1402 klasses.append(lambda K=Klass: K(spec=Anything))
1403 klasses.append(lambda K=Klass: K(spec_set=Anything))
1404
1405 for Klass in klasses:
1406 for kwargs in dict(), dict(spec_set=True):
1407 mock = Klass()
1408 #no error
1409 mock.one, mock.two, mock.three
1410
1411 for One, Two in [(_One, _Two), (['one'], ['two'])]:
1412 for kwargs in dict(), dict(spec_set=True):
1413 mock.mock_add_spec(One, **kwargs)
1414
1415 mock.one
1416 self.assertRaises(
1417 AttributeError, getattr, mock, 'two'
1418 )
1419 self.assertRaises(
1420 AttributeError, getattr, mock, 'three'
1421 )
1422 if 'spec_set' in kwargs:
1423 self.assertRaises(
1424 AttributeError, setattr, mock, 'three', None
1425 )
1426
1427 mock.mock_add_spec(Two, **kwargs)
1428 self.assertRaises(
1429 AttributeError, getattr, mock, 'one'
1430 )
1431 mock.two
1432 self.assertRaises(
1433 AttributeError, getattr, mock, 'three'
1434 )
1435 if 'spec_set' in kwargs:
1436 self.assertRaises(
1437 AttributeError, setattr, mock, 'three', None
1438 )
1439 # note that creating a mock, setting an instance attribute, and
1440 # *then* setting a spec doesn't work. Not the intended use case
1441
1442
1443 def test_mock_add_spec_magic_methods(self):
1444 for Klass in MagicMock, NonCallableMagicMock:
1445 mock = Klass()
1446 int(mock)
1447
1448 mock.mock_add_spec(object)
1449 self.assertRaises(TypeError, int, mock)
1450
1451 mock = Klass()
1452 mock['foo']
1453 mock.__int__.return_value =4
1454
1455 mock.mock_add_spec(int)
1456 self.assertEqual(int(mock), 4)
1457 self.assertRaises(TypeError, lambda: mock['foo'])
1458
1459
1460 def test_adding_child_mock(self):
1461 for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock:
1462 mock = Klass()
1463
1464 mock.foo = Mock()
1465 mock.foo()
1466
1467 self.assertEqual(mock.method_calls, [call.foo()])
1468 self.assertEqual(mock.mock_calls, [call.foo()])
1469
1470 mock = Klass()
1471 mock.bar = Mock(name='name')
1472 mock.bar()
1473 self.assertEqual(mock.method_calls, [])
1474 self.assertEqual(mock.mock_calls, [])
1475
1476 # mock with an existing _new_parent but no name
1477 mock = Klass()
1478 mock.baz = MagicMock()()
1479 mock.baz()
1480 self.assertEqual(mock.method_calls, [])
1481 self.assertEqual(mock.mock_calls, [])
1482
1483
1484 def test_adding_return_value_mock(self):
1485 for Klass in Mock, MagicMock:
1486 mock = Klass()
1487 mock.return_value = MagicMock()
1488
1489 mock()()
1490 self.assertEqual(mock.mock_calls, [call(), call()()])
1491
1492
1493 def test_manager_mock(self):
1494 class Foo(object):
1495 one = 'one'
1496 two = 'two'
1497 manager = Mock()
1498 p1 = patch.object(Foo, 'one')
1499 p2 = patch.object(Foo, 'two')
1500
1501 mock_one = p1.start()
1502 self.addCleanup(p1.stop)
1503 mock_two = p2.start()
1504 self.addCleanup(p2.stop)
1505
1506 manager.attach_mock(mock_one, 'one')
1507 manager.attach_mock(mock_two, 'two')
1508
1509 Foo.two()
1510 Foo.one()
1511
1512 self.assertEqual(manager.mock_calls, [call.two(), call.one()])
1513
1514
1515 def test_magic_methods_mock_calls(self):
1516 for Klass in Mock, MagicMock:
1517 m = Klass()
1518 m.__int__ = Mock(return_value=3)
1519 m.__float__ = MagicMock(return_value=3.0)
1520 int(m)
1521 float(m)
1522
1523 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
1524 self.assertEqual(m.method_calls, [])
1525
Robert Collins5329aaa2015-07-17 20:08:45 +12001526 def test_mock_open_reuse_issue_21750(self):
1527 mocked_open = mock.mock_open(read_data='data')
1528 f1 = mocked_open('a-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001529 f1_data = f1.read()
Robert Collins5329aaa2015-07-17 20:08:45 +12001530 f2 = mocked_open('another-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001531 f2_data = f2.read()
1532 self.assertEqual(f1_data, f2_data)
1533
Tony Flury20870232018-09-12 23:21:16 +01001534 def test_mock_open_dunder_iter_issue(self):
1535 # Test dunder_iter method generates the expected result and
1536 # consumes the iterator.
1537 mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue')
1538 f1 = mocked_open('a-name')
1539 lines = [line for line in f1]
1540 self.assertEqual(lines[0], 'Remarkable\n')
1541 self.assertEqual(lines[1], 'Norwegian Blue')
1542 self.assertEqual(list(f1), [])
1543
Robert Collinsca647ef2015-07-24 03:48:20 +12001544 def test_mock_open_write(self):
1545 # Test exception in file writing write()
1546 mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
1547 with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
1548 mock_filehandle = mock_namedtemp.return_value
1549 mock_write = mock_filehandle.write
1550 mock_write.side_effect = OSError('Test 2 Error')
1551 def attempt():
1552 tempfile.NamedTemporaryFile().write('asd')
1553 self.assertRaises(OSError, attempt)
1554
1555 def test_mock_open_alter_readline(self):
1556 mopen = mock.mock_open(read_data='foo\nbarn')
1557 mopen.return_value.readline.side_effect = lambda *args:'abc'
1558 first = mopen().readline()
1559 second = mopen().readline()
1560 self.assertEqual('abc', first)
1561 self.assertEqual('abc', second)
Michael Foord345266a2012-03-14 12:24:34 -07001562
Robert Collins9549a3e2016-05-16 15:22:01 +12001563 def test_mock_open_after_eof(self):
1564 # read, readline and readlines should work after end of file.
1565 _open = mock.mock_open(read_data='foo')
1566 h = _open('bar')
1567 h.read()
1568 self.assertEqual('', h.read())
1569 self.assertEqual('', h.read())
1570 self.assertEqual('', h.readline())
1571 self.assertEqual('', h.readline())
1572 self.assertEqual([], h.readlines())
1573 self.assertEqual([], h.readlines())
1574
Michael Foord345266a2012-03-14 12:24:34 -07001575 def test_mock_parents(self):
1576 for Klass in Mock, MagicMock:
1577 m = Klass()
1578 original_repr = repr(m)
1579 m.return_value = m
1580 self.assertIs(m(), m)
1581 self.assertEqual(repr(m), original_repr)
1582
1583 m.reset_mock()
1584 self.assertIs(m(), m)
1585 self.assertEqual(repr(m), original_repr)
1586
1587 m = Klass()
1588 m.b = m.a
1589 self.assertIn("name='mock.a'", repr(m.b))
1590 self.assertIn("name='mock.a'", repr(m.a))
1591 m.reset_mock()
1592 self.assertIn("name='mock.a'", repr(m.b))
1593 self.assertIn("name='mock.a'", repr(m.a))
1594
1595 m = Klass()
1596 original_repr = repr(m)
1597 m.a = m()
1598 m.a.return_value = m
1599
1600 self.assertEqual(repr(m), original_repr)
1601 self.assertEqual(repr(m.a()), original_repr)
1602
1603
1604 def test_attach_mock(self):
1605 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1606 for Klass in classes:
1607 for Klass2 in classes:
1608 m = Klass()
1609
1610 m2 = Klass2(name='foo')
1611 m.attach_mock(m2, 'bar')
1612
1613 self.assertIs(m.bar, m2)
1614 self.assertIn("name='mock.bar'", repr(m2))
1615
1616 m.bar.baz(1)
1617 self.assertEqual(m.mock_calls, [call.bar.baz(1)])
1618 self.assertEqual(m.method_calls, [call.bar.baz(1)])
1619
1620
1621 def test_attach_mock_return_value(self):
1622 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1623 for Klass in Mock, MagicMock:
1624 for Klass2 in classes:
1625 m = Klass()
1626
1627 m2 = Klass2(name='foo')
1628 m.attach_mock(m2, 'return_value')
1629
1630 self.assertIs(m(), m2)
1631 self.assertIn("name='mock()'", repr(m2))
1632
1633 m2.foo()
1634 self.assertEqual(m.mock_calls, call().foo().call_list())
1635
1636
1637 def test_attribute_deletion(self):
Michael Foord468ec342013-09-15 20:05:19 +12001638 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1639 NonCallableMock()):
Michael Foord345266a2012-03-14 12:24:34 -07001640 self.assertTrue(hasattr(mock, 'm'))
1641
1642 del mock.m
1643 self.assertFalse(hasattr(mock, 'm'))
1644
1645 del mock.f
1646 self.assertFalse(hasattr(mock, 'f'))
1647 self.assertRaises(AttributeError, getattr, mock, 'f')
1648
1649
Xtreakedeca922018-12-01 15:33:54 +05301650 def test_reset_mock_does_not_raise_on_attr_deletion(self):
1651 # bpo-31177: reset_mock should not raise AttributeError when attributes
1652 # were deleted in a mock instance
1653 mock = Mock()
1654 mock.child = True
1655 del mock.child
1656 mock.reset_mock()
1657 self.assertFalse(hasattr(mock, 'child'))
1658
1659
Michael Foord345266a2012-03-14 12:24:34 -07001660 def test_class_assignable(self):
1661 for mock in Mock(), MagicMock():
1662 self.assertNotIsInstance(mock, int)
1663
1664 mock.__class__ = int
1665 self.assertIsInstance(mock, int)
1666 mock.foo
1667
Andrew Dunaie63e6172018-12-04 11:08:45 +02001668 def test_name_attribute_of_call(self):
1669 # bpo-35357: _Call should not disclose any attributes whose names
1670 # may clash with popular ones (such as ".name")
1671 self.assertIsNotNone(call.name)
1672 self.assertEqual(type(call.name), _Call)
1673 self.assertEqual(type(call.name().name), _Call)
1674
1675 def test_parent_attribute_of_call(self):
1676 # bpo-35357: _Call should not disclose any attributes whose names
1677 # may clash with popular ones (such as ".parent")
1678 self.assertIsNotNone(call.parent)
1679 self.assertEqual(type(call.parent), _Call)
1680 self.assertEqual(type(call.parent().parent), _Call)
1681
Michael Foord345266a2012-03-14 12:24:34 -07001682
Michael Foord345266a2012-03-14 12:24:34 -07001683if __name__ == '__main__':
1684 unittest.main()