blob: a96ec683a95b0d0d3a8960675f1007bd004f5279 [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001import copy
2import sys
Robert Collinsca647ef2015-07-24 03:48:20 +12003import tempfile
Michael Foord345266a2012-03-14 12:24:34 -07004
5import unittest
6from unittest.test.testmock.support import is_instance
7from unittest import mock
8from unittest.mock import (
9 call, DEFAULT, patch, sentinel,
10 MagicMock, Mock, NonCallableMock,
11 NonCallableMagicMock, _CallList,
12 create_autospec
13)
14
15
16class Iter(object):
17 def __init__(self):
18 self.thing = iter(['this', 'is', 'an', 'iter'])
19
20 def __iter__(self):
21 return self
22
23 def next(self):
24 return next(self.thing)
25
26 __next__ = next
27
28
Antoine Pitrou5c64df72013-02-03 00:23:58 +010029class Something(object):
30 def meth(self, a, b, c, d=None):
31 pass
32
33 @classmethod
34 def cmeth(cls, a, b, c, d=None):
35 pass
36
37 @staticmethod
38 def smeth(a, b, c, d=None):
39 pass
40
Michael Foord345266a2012-03-14 12:24:34 -070041
42class MockTest(unittest.TestCase):
43
44 def test_all(self):
45 # if __all__ is badly defined then import * will raise an error
46 # We have to exec it because you can't import * inside a method
47 # in Python 3
Michael Foord83a16852012-03-14 12:58:46 -070048 exec("from unittest.mock import *")
Michael Foord345266a2012-03-14 12:24:34 -070049
50
51 def test_constructor(self):
52 mock = Mock()
53
54 self.assertFalse(mock.called, "called not initialised correctly")
55 self.assertEqual(mock.call_count, 0,
56 "call_count not initialised correctly")
57 self.assertTrue(is_instance(mock.return_value, Mock),
58 "return_value not initialised correctly")
59
60 self.assertEqual(mock.call_args, None,
61 "call_args not initialised correctly")
62 self.assertEqual(mock.call_args_list, [],
63 "call_args_list not initialised correctly")
64 self.assertEqual(mock.method_calls, [],
65 "method_calls not initialised correctly")
66
67 # Can't use hasattr for this test as it always returns True on a mock
Serhiy Storchaka5665bc52013-11-17 00:12:21 +020068 self.assertNotIn('_items', mock.__dict__,
Michael Foord345266a2012-03-14 12:24:34 -070069 "default mock should not have '_items' attribute")
70
71 self.assertIsNone(mock._mock_parent,
72 "parent not initialised correctly")
73 self.assertIsNone(mock._mock_methods,
74 "methods not initialised correctly")
75 self.assertEqual(mock._mock_children, {},
76 "children not initialised incorrectly")
77
78
79 def test_return_value_in_constructor(self):
80 mock = Mock(return_value=None)
81 self.assertIsNone(mock.return_value,
82 "return value in constructor not honoured")
83
84
85 def test_repr(self):
86 mock = Mock(name='foo')
87 self.assertIn('foo', repr(mock))
88 self.assertIn("'%s'" % id(mock), repr(mock))
89
90 mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')]
91 for mock, name in mocks:
92 self.assertIn('%s.bar' % name, repr(mock.bar))
93 self.assertIn('%s.foo()' % name, repr(mock.foo()))
94 self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing))
95 self.assertIn('%s()' % name, repr(mock()))
96 self.assertIn('%s()()' % name, repr(mock()()))
97 self.assertIn('%s()().foo.bar.baz().bing' % name,
98 repr(mock()().foo.bar.baz().bing))
99
100
101 def test_repr_with_spec(self):
102 class X(object):
103 pass
104
105 mock = Mock(spec=X)
106 self.assertIn(" spec='X' ", repr(mock))
107
108 mock = Mock(spec=X())
109 self.assertIn(" spec='X' ", repr(mock))
110
111 mock = Mock(spec_set=X)
112 self.assertIn(" spec_set='X' ", repr(mock))
113
114 mock = Mock(spec_set=X())
115 self.assertIn(" spec_set='X' ", repr(mock))
116
117 mock = Mock(spec=X, name='foo')
118 self.assertIn(" spec='X' ", repr(mock))
119 self.assertIn(" name='foo' ", repr(mock))
120
121 mock = Mock(name='foo')
122 self.assertNotIn("spec", repr(mock))
123
124 mock = Mock()
125 self.assertNotIn("spec", repr(mock))
126
127 mock = Mock(spec=['foo'])
128 self.assertNotIn("spec", repr(mock))
129
130
131 def test_side_effect(self):
132 mock = Mock()
133
134 def effect(*args, **kwargs):
135 raise SystemError('kablooie')
136
137 mock.side_effect = effect
138 self.assertRaises(SystemError, mock, 1, 2, fish=3)
139 mock.assert_called_with(1, 2, fish=3)
140
141 results = [1, 2, 3]
142 def effect():
143 return results.pop()
144 mock.side_effect = effect
145
146 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
147 "side effect not used correctly")
148
149 mock = Mock(side_effect=sentinel.SideEffect)
150 self.assertEqual(mock.side_effect, sentinel.SideEffect,
151 "side effect in constructor not used")
152
153 def side_effect():
154 return DEFAULT
155 mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
156 self.assertEqual(mock(), sentinel.RETURN)
157
Michael Foord01bafdc2014-04-14 16:09:42 -0400158 def test_autospec_side_effect(self):
159 # Test for issue17826
160 results = [1, 2, 3]
161 def effect():
162 return results.pop()
163 def f():
164 pass
165
166 mock = create_autospec(f)
167 mock.side_effect = [1, 2, 3]
168 self.assertEqual([mock(), mock(), mock()], [1, 2, 3],
169 "side effect not used correctly in create_autospec")
170 # Test where side effect is a callable
171 results = [1, 2, 3]
172 mock = create_autospec(f)
173 mock.side_effect = effect
174 self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
175 "callable side effect not used correctly")
Michael Foord345266a2012-03-14 12:24:34 -0700176
Robert Collinsf58f88c2015-07-14 13:51:40 +1200177 def test_autospec_side_effect_exception(self):
178 # Test for issue 23661
179 def f():
180 pass
181
182 mock = create_autospec(f)
183 mock.side_effect = ValueError('Bazinga!')
184 self.assertRaisesRegex(ValueError, 'Bazinga!', mock)
185
Michael Foord345266a2012-03-14 12:24:34 -0700186 @unittest.skipUnless('java' in sys.platform,
187 'This test only applies to Jython')
188 def test_java_exception_side_effect(self):
189 import java
190 mock = Mock(side_effect=java.lang.RuntimeException("Boom!"))
191
192 # can't use assertRaises with java exceptions
193 try:
194 mock(1, 2, fish=3)
195 except java.lang.RuntimeException:
196 pass
197 else:
198 self.fail('java exception not raised')
199 mock.assert_called_with(1,2, fish=3)
200
201
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")
266 self.assertEqual(mock.call_count, 1, "call_count incoreect")
267 self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
268 "call_args not set")
269 self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
270 "call_args_list not initialised correctly")
271
272 mock.return_value = sentinel.ReturnValue
273 ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
274 self.assertEqual(ret_val, sentinel.ReturnValue,
275 "incorrect return value")
276
277 self.assertEqual(mock.call_count, 2, "call_count incorrect")
278 self.assertEqual(mock.call_args,
279 ((sentinel.Arg,), {'key': sentinel.KeyArg}),
280 "call_args not set")
281 self.assertEqual(mock.call_args_list, [
282 ((sentinel.Arg,), {}),
283 ((sentinel.Arg,), {'key': sentinel.KeyArg})
284 ],
285 "call_args_list not set")
286
287
288 def test_call_args_comparison(self):
289 mock = Mock()
290 mock()
291 mock(sentinel.Arg)
292 mock(kw=sentinel.Kwarg)
293 mock(sentinel.Arg, kw=sentinel.Kwarg)
294 self.assertEqual(mock.call_args_list, [
295 (),
296 ((sentinel.Arg,),),
297 ({"kw": sentinel.Kwarg},),
298 ((sentinel.Arg,), {"kw": sentinel.Kwarg})
299 ])
300 self.assertEqual(mock.call_args,
301 ((sentinel.Arg,), {"kw": sentinel.Kwarg}))
302
Berker Peksag3fc536f2015-09-09 23:35:25 +0300303 # Comparing call_args to a long sequence should not raise
304 # an exception. See issue 24857.
305 self.assertFalse(mock.call_args == "a long sequence")
Michael Foord345266a2012-03-14 12:24:34 -0700306
Berker Peksagce913872016-03-28 00:30:02 +0300307
308 def test_calls_equal_with_any(self):
Berker Peksagce913872016-03-28 00:30:02 +0300309 # Check that equality and non-equality is consistent even when
310 # comparing with mock.ANY
Serhiy Storchaka362f0582017-01-21 23:12:58 +0200311 mm = mock.MagicMock()
312 self.assertTrue(mm == mm)
313 self.assertFalse(mm != mm)
314 self.assertFalse(mm == mock.MagicMock())
315 self.assertTrue(mm != mock.MagicMock())
316 self.assertTrue(mm == mock.ANY)
317 self.assertFalse(mm != mock.ANY)
318 self.assertTrue(mock.ANY == mm)
319 self.assertFalse(mock.ANY != mm)
320
321 call1 = mock.call(mock.MagicMock())
322 call2 = mock.call(mock.ANY)
Berker Peksagce913872016-03-28 00:30:02 +0300323 self.assertTrue(call1 == call2)
324 self.assertFalse(call1 != call2)
Serhiy Storchaka362f0582017-01-21 23:12:58 +0200325 self.assertTrue(call2 == call1)
326 self.assertFalse(call2 != call1)
Berker Peksagce913872016-03-28 00:30:02 +0300327
328
Michael Foord345266a2012-03-14 12:24:34 -0700329 def test_assert_called_with(self):
330 mock = Mock()
331 mock()
332
333 # Will raise an exception if it fails
334 mock.assert_called_with()
335 self.assertRaises(AssertionError, mock.assert_called_with, 1)
336
337 mock.reset_mock()
338 self.assertRaises(AssertionError, mock.assert_called_with)
339
340 mock(1, 2, 3, a='fish', b='nothing')
341 mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
342
343
Berker Peksagce913872016-03-28 00:30:02 +0300344 def test_assert_called_with_any(self):
345 m = MagicMock()
346 m(MagicMock())
347 m.assert_called_with(mock.ANY)
348
349
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100350 def test_assert_called_with_function_spec(self):
351 def f(a, b, c, d=None):
352 pass
353
354 mock = Mock(spec=f)
355
356 mock(1, b=2, c=3)
357 mock.assert_called_with(1, 2, 3)
358 mock.assert_called_with(a=1, b=2, c=3)
359 self.assertRaises(AssertionError, mock.assert_called_with,
360 1, b=3, c=2)
361 # Expected call doesn't match the spec's signature
362 with self.assertRaises(AssertionError) as cm:
363 mock.assert_called_with(e=8)
364 self.assertIsInstance(cm.exception.__cause__, TypeError)
365
366
367 def test_assert_called_with_method_spec(self):
368 def _check(mock):
369 mock(1, b=2, c=3)
370 mock.assert_called_with(1, 2, 3)
371 mock.assert_called_with(a=1, b=2, c=3)
372 self.assertRaises(AssertionError, mock.assert_called_with,
373 1, b=3, c=2)
374
375 mock = Mock(spec=Something().meth)
376 _check(mock)
377 mock = Mock(spec=Something.cmeth)
378 _check(mock)
379 mock = Mock(spec=Something().cmeth)
380 _check(mock)
381 mock = Mock(spec=Something.smeth)
382 _check(mock)
383 mock = Mock(spec=Something().smeth)
384 _check(mock)
385
386
Michael Foord345266a2012-03-14 12:24:34 -0700387 def test_assert_called_once_with(self):
388 mock = Mock()
389 mock()
390
391 # Will raise an exception if it fails
392 mock.assert_called_once_with()
393
394 mock()
395 self.assertRaises(AssertionError, mock.assert_called_once_with)
396
397 mock.reset_mock()
398 self.assertRaises(AssertionError, mock.assert_called_once_with)
399
400 mock('foo', 'bar', baz=2)
401 mock.assert_called_once_with('foo', 'bar', baz=2)
402
403 mock.reset_mock()
404 mock('foo', 'bar', baz=2)
405 self.assertRaises(
406 AssertionError,
407 lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
408 )
409
410
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100411 def test_assert_called_once_with_function_spec(self):
412 def f(a, b, c, d=None):
413 pass
414
415 mock = Mock(spec=f)
416
417 mock(1, b=2, c=3)
418 mock.assert_called_once_with(1, 2, 3)
419 mock.assert_called_once_with(a=1, b=2, c=3)
420 self.assertRaises(AssertionError, mock.assert_called_once_with,
421 1, b=3, c=2)
422 # Expected call doesn't match the spec's signature
423 with self.assertRaises(AssertionError) as cm:
424 mock.assert_called_once_with(e=8)
425 self.assertIsInstance(cm.exception.__cause__, TypeError)
426 # Mock called more than once => always fails
427 mock(4, 5, 6)
428 self.assertRaises(AssertionError, mock.assert_called_once_with,
429 1, 2, 3)
430 self.assertRaises(AssertionError, mock.assert_called_once_with,
431 4, 5, 6)
432
433
Michael Foord345266a2012-03-14 12:24:34 -0700434 def test_attribute_access_returns_mocks(self):
435 mock = Mock()
436 something = mock.something
437 self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
438 self.assertEqual(mock.something, something,
439 "different attributes returned for same name")
440
441 # Usage example
442 mock = Mock()
443 mock.something.return_value = 3
444
445 self.assertEqual(mock.something(), 3, "method returned wrong value")
446 self.assertTrue(mock.something.called,
447 "method didn't record being called")
448
449
450 def test_attributes_have_name_and_parent_set(self):
451 mock = Mock()
452 something = mock.something
453
454 self.assertEqual(something._mock_name, "something",
455 "attribute name not set correctly")
456 self.assertEqual(something._mock_parent, mock,
457 "attribute parent not set correctly")
458
459
460 def test_method_calls_recorded(self):
461 mock = Mock()
462 mock.something(3, fish=None)
463 mock.something_else.something(6, cake=sentinel.Cake)
464
465 self.assertEqual(mock.something_else.method_calls,
466 [("something", (6,), {'cake': sentinel.Cake})],
467 "method calls not recorded correctly")
468 self.assertEqual(mock.method_calls, [
469 ("something", (3,), {'fish': None}),
470 ("something_else.something", (6,), {'cake': sentinel.Cake})
471 ],
472 "method calls not recorded correctly")
473
474
475 def test_method_calls_compare_easily(self):
476 mock = Mock()
477 mock.something()
478 self.assertEqual(mock.method_calls, [('something',)])
479 self.assertEqual(mock.method_calls, [('something', (), {})])
480
481 mock = Mock()
482 mock.something('different')
483 self.assertEqual(mock.method_calls, [('something', ('different',))])
484 self.assertEqual(mock.method_calls,
485 [('something', ('different',), {})])
486
487 mock = Mock()
488 mock.something(x=1)
489 self.assertEqual(mock.method_calls, [('something', {'x': 1})])
490 self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
491
492 mock = Mock()
493 mock.something('different', some='more')
494 self.assertEqual(mock.method_calls, [
495 ('something', ('different',), {'some': 'more'})
496 ])
497
498
499 def test_only_allowed_methods_exist(self):
500 for spec in ['something'], ('something',):
501 for arg in 'spec', 'spec_set':
502 mock = Mock(**{arg: spec})
503
504 # this should be allowed
505 mock.something
506 self.assertRaisesRegex(
507 AttributeError,
508 "Mock object has no attribute 'something_else'",
509 getattr, mock, 'something_else'
510 )
511
512
513 def test_from_spec(self):
514 class Something(object):
515 x = 3
516 __something__ = None
517 def y(self):
518 pass
519
520 def test_attributes(mock):
521 # should work
522 mock.x
523 mock.y
524 mock.__something__
525 self.assertRaisesRegex(
526 AttributeError,
527 "Mock object has no attribute 'z'",
528 getattr, mock, 'z'
529 )
530 self.assertRaisesRegex(
531 AttributeError,
532 "Mock object has no attribute '__foobar__'",
533 getattr, mock, '__foobar__'
534 )
535
536 test_attributes(Mock(spec=Something))
537 test_attributes(Mock(spec=Something()))
538
539
540 def test_wraps_calls(self):
541 real = Mock()
542
543 mock = Mock(wraps=real)
544 self.assertEqual(mock(), real())
545
546 real.reset_mock()
547
548 mock(1, 2, fish=3)
549 real.assert_called_with(1, 2, fish=3)
550
551
552 def test_wraps_call_with_nondefault_return_value(self):
553 real = Mock()
554
555 mock = Mock(wraps=real)
556 mock.return_value = 3
557
558 self.assertEqual(mock(), 3)
559 self.assertFalse(real.called)
560
561
562 def test_wraps_attributes(self):
563 class Real(object):
564 attribute = Mock()
565
566 real = Real()
567
568 mock = Mock(wraps=real)
569 self.assertEqual(mock.attribute(), real.attribute())
570 self.assertRaises(AttributeError, lambda: mock.fish)
571
572 self.assertNotEqual(mock.attribute, real.attribute)
573 result = mock.attribute.frog(1, 2, fish=3)
574 Real.attribute.frog.assert_called_with(1, 2, fish=3)
575 self.assertEqual(result, Real.attribute.frog())
576
577
578 def test_exceptional_side_effect(self):
579 mock = Mock(side_effect=AttributeError)
580 self.assertRaises(AttributeError, mock)
581
582 mock = Mock(side_effect=AttributeError('foo'))
583 self.assertRaises(AttributeError, mock)
584
585
586 def test_baseexceptional_side_effect(self):
587 mock = Mock(side_effect=KeyboardInterrupt)
588 self.assertRaises(KeyboardInterrupt, mock)
589
590 mock = Mock(side_effect=KeyboardInterrupt('foo'))
591 self.assertRaises(KeyboardInterrupt, mock)
592
593
594 def test_assert_called_with_message(self):
595 mock = Mock()
596 self.assertRaisesRegex(AssertionError, 'Not called',
597 mock.assert_called_with)
598
599
Michael Foord28d591c2012-09-28 16:15:22 +0100600 def test_assert_called_once_with_message(self):
601 mock = Mock(name='geoffrey')
602 self.assertRaisesRegex(AssertionError,
603 r"Expected 'geoffrey' to be called once\.",
604 mock.assert_called_once_with)
605
606
Michael Foord345266a2012-03-14 12:24:34 -0700607 def test__name__(self):
608 mock = Mock()
609 self.assertRaises(AttributeError, lambda: mock.__name__)
610
611 mock.__name__ = 'foo'
612 self.assertEqual(mock.__name__, 'foo')
613
614
615 def test_spec_list_subclass(self):
616 class Sub(list):
617 pass
618 mock = Mock(spec=Sub(['foo']))
619
620 mock.append(3)
621 mock.append.assert_called_with(3)
622 self.assertRaises(AttributeError, getattr, mock, 'foo')
623
624
625 def test_spec_class(self):
626 class X(object):
627 pass
628
629 mock = Mock(spec=X)
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200630 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700631
632 mock = Mock(spec=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200633 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700634
635 self.assertIs(mock.__class__, X)
636 self.assertEqual(Mock().__class__.__name__, 'Mock')
637
638 mock = Mock(spec_set=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_set=X())
Serhiy Storchaka5665bc52013-11-17 00:12:21 +0200642 self.assertIsInstance(mock, X)
Michael Foord345266a2012-03-14 12:24:34 -0700643
644
645 def test_setting_attribute_with_spec_set(self):
646 class X(object):
647 y = 3
648
649 mock = Mock(spec=X)
650 mock.x = 'foo'
651
652 mock = Mock(spec_set=X)
653 def set_attr():
654 mock.x = 'foo'
655
656 mock.y = 'foo'
657 self.assertRaises(AttributeError, set_attr)
658
659
660 def test_copy(self):
661 current = sys.getrecursionlimit()
662 self.addCleanup(sys.setrecursionlimit, current)
663
664 # can't use sys.maxint as this doesn't exist in Python 3
665 sys.setrecursionlimit(int(10e8))
666 # this segfaults without the fix in place
667 copy.copy(Mock())
668
669
670 def test_subclass_with_properties(self):
671 class SubClass(Mock):
672 def _get(self):
673 return 3
674 def _set(self, value):
675 raise NameError('strange error')
676 some_attribute = property(_get, _set)
677
678 s = SubClass(spec_set=SubClass)
679 self.assertEqual(s.some_attribute, 3)
680
681 def test():
682 s.some_attribute = 3
683 self.assertRaises(NameError, test)
684
685 def test():
686 s.foo = 'bar'
687 self.assertRaises(AttributeError, test)
688
689
690 def test_setting_call(self):
691 mock = Mock()
692 def __call__(self, a):
693 return self._mock_call(a)
694
695 type(mock).__call__ = __call__
696 mock('one')
697 mock.assert_called_with('one')
698
699 self.assertRaises(TypeError, mock, 'one', 'two')
700
701
702 def test_dir(self):
703 mock = Mock()
704 attrs = set(dir(mock))
705 type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
706
707 # all public attributes from the type are included
708 self.assertEqual(set(), type_attrs - attrs)
709
710 # creates these attributes
711 mock.a, mock.b
712 self.assertIn('a', dir(mock))
713 self.assertIn('b', dir(mock))
714
715 # instance attributes
716 mock.c = mock.d = None
717 self.assertIn('c', dir(mock))
718 self.assertIn('d', dir(mock))
719
720 # magic methods
721 mock.__iter__ = lambda s: iter([])
722 self.assertIn('__iter__', dir(mock))
723
724
725 def test_dir_from_spec(self):
726 mock = Mock(spec=unittest.TestCase)
727 testcase_attrs = set(dir(unittest.TestCase))
728 attrs = set(dir(mock))
729
730 # all attributes from the spec are included
731 self.assertEqual(set(), testcase_attrs - attrs)
732
733 # shadow a sys attribute
734 mock.version = 3
735 self.assertEqual(dir(mock).count('version'), 1)
736
737
738 def test_filter_dir(self):
739 patcher = patch.object(mock, 'FILTER_DIR', False)
740 patcher.start()
741 try:
742 attrs = set(dir(Mock()))
743 type_attrs = set(dir(Mock))
744
745 # ALL attributes from the type are included
746 self.assertEqual(set(), type_attrs - attrs)
747 finally:
748 patcher.stop()
749
750
751 def test_configure_mock(self):
752 mock = Mock(foo='bar')
753 self.assertEqual(mock.foo, 'bar')
754
755 mock = MagicMock(foo='bar')
756 self.assertEqual(mock.foo, 'bar')
757
758 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
759 'foo': MagicMock()}
760 mock = Mock(**kwargs)
761 self.assertRaises(KeyError, mock)
762 self.assertEqual(mock.foo.bar(), 33)
763 self.assertIsInstance(mock.foo, MagicMock)
764
765 mock = Mock()
766 mock.configure_mock(**kwargs)
767 self.assertRaises(KeyError, mock)
768 self.assertEqual(mock.foo.bar(), 33)
769 self.assertIsInstance(mock.foo, MagicMock)
770
771
772 def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
773 # needed because assertRaisesRegex doesn't work easily with newlines
774 try:
775 func(*args, **kwargs)
776 except:
777 instance = sys.exc_info()[1]
778 self.assertIsInstance(instance, exception)
779 else:
780 self.fail('Exception %r not raised' % (exception,))
781
782 msg = str(instance)
783 self.assertEqual(msg, message)
784
785
786 def test_assert_called_with_failure_message(self):
787 mock = NonCallableMock()
788
789 expected = "mock(1, '2', 3, bar='foo')"
790 message = 'Expected call: %s\nNot called'
791 self.assertRaisesWithMsg(
792 AssertionError, message % (expected,),
793 mock.assert_called_with, 1, '2', 3, bar='foo'
794 )
795
796 mock.foo(1, '2', 3, foo='foo')
797
798
799 asserters = [
800 mock.foo.assert_called_with, mock.foo.assert_called_once_with
801 ]
802 for meth in asserters:
803 actual = "foo(1, '2', 3, foo='foo')"
804 expected = "foo(1, '2', 3, bar='foo')"
805 message = 'Expected call: %s\nActual call: %s'
806 self.assertRaisesWithMsg(
807 AssertionError, message % (expected, actual),
808 meth, 1, '2', 3, bar='foo'
809 )
810
811 # just kwargs
812 for meth in asserters:
813 actual = "foo(1, '2', 3, foo='foo')"
814 expected = "foo(bar='foo')"
815 message = 'Expected call: %s\nActual call: %s'
816 self.assertRaisesWithMsg(
817 AssertionError, message % (expected, actual),
818 meth, bar='foo'
819 )
820
821 # just args
822 for meth in asserters:
823 actual = "foo(1, '2', 3, foo='foo')"
824 expected = "foo(1, 2, 3)"
825 message = 'Expected call: %s\nActual call: %s'
826 self.assertRaisesWithMsg(
827 AssertionError, message % (expected, actual),
828 meth, 1, 2, 3
829 )
830
831 # empty
832 for meth in asserters:
833 actual = "foo(1, '2', 3, foo='foo')"
834 expected = "foo()"
835 message = 'Expected call: %s\nActual call: %s'
836 self.assertRaisesWithMsg(
837 AssertionError, message % (expected, actual), meth
838 )
839
840
841 def test_mock_calls(self):
842 mock = MagicMock()
843
844 # need to do this because MagicMock.mock_calls used to just return
845 # a MagicMock which also returned a MagicMock when __eq__ was called
846 self.assertIs(mock.mock_calls == [], True)
847
848 mock = MagicMock()
849 mock()
850 expected = [('', (), {})]
851 self.assertEqual(mock.mock_calls, expected)
852
853 mock.foo()
854 expected.append(call.foo())
855 self.assertEqual(mock.mock_calls, expected)
856 # intermediate mock_calls work too
857 self.assertEqual(mock.foo.mock_calls, [('', (), {})])
858
859 mock = MagicMock()
860 mock().foo(1, 2, 3, a=4, b=5)
861 expected = [
862 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
863 ]
864 self.assertEqual(mock.mock_calls, expected)
865 self.assertEqual(mock.return_value.foo.mock_calls,
866 [('', (1, 2, 3), dict(a=4, b=5))])
867 self.assertEqual(mock.return_value.mock_calls,
868 [('foo', (1, 2, 3), dict(a=4, b=5))])
869
870 mock = MagicMock()
871 mock().foo.bar().baz()
872 expected = [
873 ('', (), {}), ('().foo.bar', (), {}),
874 ('().foo.bar().baz', (), {})
875 ]
876 self.assertEqual(mock.mock_calls, expected)
877 self.assertEqual(mock().mock_calls,
878 call.foo.bar().baz().call_list())
879
880 for kwargs in dict(), dict(name='bar'):
881 mock = MagicMock(**kwargs)
882 int(mock.foo)
883 expected = [('foo.__int__', (), {})]
884 self.assertEqual(mock.mock_calls, expected)
885
886 mock = MagicMock(**kwargs)
887 mock.a()()
888 expected = [('a', (), {}), ('a()', (), {})]
889 self.assertEqual(mock.mock_calls, expected)
890 self.assertEqual(mock.a().mock_calls, [call()])
891
892 mock = MagicMock(**kwargs)
893 mock(1)(2)(3)
894 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
895 self.assertEqual(mock().mock_calls, call(2)(3).call_list())
896 self.assertEqual(mock()().mock_calls, call(3).call_list())
897
898 mock = MagicMock(**kwargs)
899 mock(1)(2)(3).a.b.c(4)
900 self.assertEqual(mock.mock_calls,
901 call(1)(2)(3).a.b.c(4).call_list())
902 self.assertEqual(mock().mock_calls,
903 call(2)(3).a.b.c(4).call_list())
904 self.assertEqual(mock()().mock_calls,
905 call(3).a.b.c(4).call_list())
906
907 mock = MagicMock(**kwargs)
908 int(mock().foo.bar().baz())
909 last_call = ('().foo.bar().baz().__int__', (), {})
910 self.assertEqual(mock.mock_calls[-1], last_call)
911 self.assertEqual(mock().mock_calls,
912 call.foo.bar().baz().__int__().call_list())
913 self.assertEqual(mock().foo.bar().mock_calls,
914 call.baz().__int__().call_list())
915 self.assertEqual(mock().foo.bar().baz.mock_calls,
916 call().__int__().call_list())
917
918
919 def test_subclassing(self):
920 class Subclass(Mock):
921 pass
922
923 mock = Subclass()
924 self.assertIsInstance(mock.foo, Subclass)
925 self.assertIsInstance(mock(), Subclass)
926
927 class Subclass(Mock):
928 def _get_child_mock(self, **kwargs):
929 return Mock(**kwargs)
930
931 mock = Subclass()
932 self.assertNotIsInstance(mock.foo, Subclass)
933 self.assertNotIsInstance(mock(), Subclass)
934
935
936 def test_arg_lists(self):
937 mocks = [
938 Mock(),
939 MagicMock(),
940 NonCallableMock(),
941 NonCallableMagicMock()
942 ]
943
944 def assert_attrs(mock):
945 names = 'call_args_list', 'method_calls', 'mock_calls'
946 for name in names:
947 attr = getattr(mock, name)
948 self.assertIsInstance(attr, _CallList)
949 self.assertIsInstance(attr, list)
950 self.assertEqual(attr, [])
951
952 for mock in mocks:
953 assert_attrs(mock)
954
955 if callable(mock):
956 mock()
957 mock(1, 2)
958 mock(a=3)
959
960 mock.reset_mock()
961 assert_attrs(mock)
962
963 mock.foo()
964 mock.foo.bar(1, a=3)
965 mock.foo(1).bar().baz(3)
966
967 mock.reset_mock()
968 assert_attrs(mock)
969
970
971 def test_call_args_two_tuple(self):
972 mock = Mock()
973 mock(1, a=3)
974 mock(2, b=4)
975
976 self.assertEqual(len(mock.call_args), 2)
977 args, kwargs = mock.call_args
978 self.assertEqual(args, (2,))
979 self.assertEqual(kwargs, dict(b=4))
980
981 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
982 for expected, call_args in zip(expected_list, mock.call_args_list):
983 self.assertEqual(len(call_args), 2)
984 self.assertEqual(expected[0], call_args[0])
985 self.assertEqual(expected[1], call_args[1])
986
987
988 def test_side_effect_iterator(self):
989 mock = Mock(side_effect=iter([1, 2, 3]))
990 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
991 self.assertRaises(StopIteration, mock)
992
993 mock = MagicMock(side_effect=['a', 'b', 'c'])
994 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
995 self.assertRaises(StopIteration, mock)
996
997 mock = Mock(side_effect='ghi')
998 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
999 self.assertRaises(StopIteration, mock)
1000
1001 class Foo(object):
1002 pass
1003 mock = MagicMock(side_effect=Foo)
1004 self.assertIsInstance(mock(), Foo)
1005
1006 mock = Mock(side_effect=Iter())
1007 self.assertEqual([mock(), mock(), mock(), mock()],
1008 ['this', 'is', 'an', 'iter'])
1009 self.assertRaises(StopIteration, mock)
1010
1011
Michael Foord2cd48732012-04-21 15:52:11 +01001012 def test_side_effect_iterator_exceptions(self):
1013 for Klass in Mock, MagicMock:
1014 iterable = (ValueError, 3, KeyError, 6)
1015 m = Klass(side_effect=iterable)
1016 self.assertRaises(ValueError, m)
1017 self.assertEqual(m(), 3)
1018 self.assertRaises(KeyError, m)
1019 self.assertEqual(m(), 6)
1020
1021
Michael Foord345266a2012-03-14 12:24:34 -07001022 def test_side_effect_setting_iterator(self):
1023 mock = Mock()
1024 mock.side_effect = iter([1, 2, 3])
1025 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1026 self.assertRaises(StopIteration, mock)
1027 side_effect = mock.side_effect
1028 self.assertIsInstance(side_effect, type(iter([])))
1029
1030 mock.side_effect = ['a', 'b', 'c']
1031 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1032 self.assertRaises(StopIteration, mock)
1033 side_effect = mock.side_effect
1034 self.assertIsInstance(side_effect, type(iter([])))
1035
1036 this_iter = Iter()
1037 mock.side_effect = this_iter
1038 self.assertEqual([mock(), mock(), mock(), mock()],
1039 ['this', 'is', 'an', 'iter'])
1040 self.assertRaises(StopIteration, mock)
1041 self.assertIs(mock.side_effect, this_iter)
1042
Andrew Svetlov8b2cd752013-04-07 16:42:24 +03001043 def test_side_effect_iterator_default(self):
1044 mock = Mock(return_value=2)
1045 mock.side_effect = iter([1, DEFAULT])
1046 self.assertEqual([mock(), mock()], [1, 2])
Michael Foord345266a2012-03-14 12:24:34 -07001047
1048 def test_assert_has_calls_any_order(self):
1049 mock = Mock()
1050 mock(1, 2)
1051 mock(a=3)
1052 mock(3, 4)
1053 mock(b=6)
1054 mock(b=6)
1055
1056 kalls = [
1057 call(1, 2), ({'a': 3},),
1058 ((3, 4),), ((), {'a': 3}),
1059 ('', (1, 2)), ('', {'a': 3}),
1060 ('', (1, 2), {}), ('', (), {'a': 3})
1061 ]
1062 for kall in kalls:
1063 mock.assert_has_calls([kall], any_order=True)
1064
1065 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
1066 self.assertRaises(
1067 AssertionError, mock.assert_has_calls,
1068 [kall], any_order=True
1069 )
1070
1071 kall_lists = [
1072 [call(1, 2), call(b=6)],
1073 [call(3, 4), call(1, 2)],
1074 [call(b=6), call(b=6)],
1075 ]
1076
1077 for kall_list in kall_lists:
1078 mock.assert_has_calls(kall_list, any_order=True)
1079
1080 kall_lists = [
1081 [call(b=6), call(b=6), call(b=6)],
1082 [call(1, 2), call(1, 2)],
1083 [call(3, 4), call(1, 2), call(5, 7)],
1084 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
1085 ]
1086 for kall_list in kall_lists:
1087 self.assertRaises(
1088 AssertionError, mock.assert_has_calls,
1089 kall_list, any_order=True
1090 )
1091
1092 def test_assert_has_calls(self):
1093 kalls1 = [
1094 call(1, 2), ({'a': 3},),
1095 ((3, 4),), call(b=6),
1096 ('', (1,), {'b': 6}),
1097 ]
1098 kalls2 = [call.foo(), call.bar(1)]
1099 kalls2.extend(call.spam().baz(a=3).call_list())
1100 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
1101
1102 mocks = []
1103 for mock in Mock(), MagicMock():
1104 mock(1, 2)
1105 mock(a=3)
1106 mock(3, 4)
1107 mock(b=6)
1108 mock(1, b=6)
1109 mocks.append((mock, kalls1))
1110
1111 mock = Mock()
1112 mock.foo()
1113 mock.bar(1)
1114 mock.spam().baz(a=3)
1115 mock.bam(set(), foo={}).fish([1])
1116 mocks.append((mock, kalls2))
1117
1118 for mock, kalls in mocks:
1119 for i in range(len(kalls)):
1120 for step in 1, 2, 3:
1121 these = kalls[i:i+step]
1122 mock.assert_has_calls(these)
1123
1124 if len(these) > 1:
1125 self.assertRaises(
1126 AssertionError,
1127 mock.assert_has_calls,
1128 list(reversed(these))
1129 )
1130
1131
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001132 def test_assert_has_calls_with_function_spec(self):
1133 def f(a, b, c, d=None):
1134 pass
1135
1136 mock = Mock(spec=f)
1137
1138 mock(1, b=2, c=3)
1139 mock(4, 5, c=6, d=7)
1140 mock(10, 11, c=12)
1141 calls = [
1142 ('', (1, 2, 3), {}),
1143 ('', (4, 5, 6), {'d': 7}),
1144 ((10, 11, 12), {}),
1145 ]
1146 mock.assert_has_calls(calls)
1147 mock.assert_has_calls(calls, any_order=True)
1148 mock.assert_has_calls(calls[1:])
1149 mock.assert_has_calls(calls[1:], any_order=True)
1150 mock.assert_has_calls(calls[:-1])
1151 mock.assert_has_calls(calls[:-1], any_order=True)
1152 # Reversed order
1153 calls = list(reversed(calls))
1154 with self.assertRaises(AssertionError):
1155 mock.assert_has_calls(calls)
1156 mock.assert_has_calls(calls, any_order=True)
1157 with self.assertRaises(AssertionError):
1158 mock.assert_has_calls(calls[1:])
1159 mock.assert_has_calls(calls[1:], any_order=True)
1160 with self.assertRaises(AssertionError):
1161 mock.assert_has_calls(calls[:-1])
1162 mock.assert_has_calls(calls[:-1], any_order=True)
1163
1164
Michael Foord345266a2012-03-14 12:24:34 -07001165 def test_assert_any_call(self):
1166 mock = Mock()
1167 mock(1, 2)
1168 mock(a=3)
1169 mock(1, b=6)
1170
1171 mock.assert_any_call(1, 2)
1172 mock.assert_any_call(a=3)
1173 mock.assert_any_call(1, b=6)
1174
1175 self.assertRaises(
1176 AssertionError,
1177 mock.assert_any_call
1178 )
1179 self.assertRaises(
1180 AssertionError,
1181 mock.assert_any_call,
1182 1, 3
1183 )
1184 self.assertRaises(
1185 AssertionError,
1186 mock.assert_any_call,
1187 a=4
1188 )
1189
1190
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001191 def test_assert_any_call_with_function_spec(self):
1192 def f(a, b, c, d=None):
1193 pass
1194
1195 mock = Mock(spec=f)
1196
1197 mock(1, b=2, c=3)
1198 mock(4, 5, c=6, d=7)
1199 mock.assert_any_call(1, 2, 3)
1200 mock.assert_any_call(a=1, b=2, c=3)
1201 mock.assert_any_call(4, 5, 6, 7)
1202 mock.assert_any_call(a=4, b=5, c=6, d=7)
1203 self.assertRaises(AssertionError, mock.assert_any_call,
1204 1, b=3, c=2)
1205 # Expected call doesn't match the spec's signature
1206 with self.assertRaises(AssertionError) as cm:
1207 mock.assert_any_call(e=8)
1208 self.assertIsInstance(cm.exception.__cause__, TypeError)
1209
1210
Michael Foord345266a2012-03-14 12:24:34 -07001211 def test_mock_calls_create_autospec(self):
1212 def f(a, b):
1213 pass
1214 obj = Iter()
1215 obj.f = f
1216
1217 funcs = [
1218 create_autospec(f),
1219 create_autospec(obj).f
1220 ]
1221 for func in funcs:
1222 func(1, 2)
1223 func(3, 4)
1224
1225 self.assertEqual(
1226 func.mock_calls, [call(1, 2), call(3, 4)]
1227 )
1228
Kushal Das484f8a82014-04-16 01:05:50 +05301229 #Issue21222
1230 def test_create_autospec_with_name(self):
1231 m = mock.create_autospec(object(), name='sweet_func')
1232 self.assertIn('sweet_func', repr(m))
Michael Foord345266a2012-03-14 12:24:34 -07001233
Kushal Das8c145342014-04-16 23:32:21 +05301234 #Issue21238
1235 def test_mock_unsafe(self):
1236 m = Mock()
1237 with self.assertRaises(AttributeError):
1238 m.assert_foo_call()
1239 with self.assertRaises(AttributeError):
1240 m.assret_foo_call()
1241 m = Mock(unsafe=True)
1242 m.assert_foo_call()
1243 m.assret_foo_call()
1244
Kushal Das8af9db32014-04-17 01:36:14 +05301245 #Issue21262
1246 def test_assert_not_called(self):
1247 m = Mock()
1248 m.hello.assert_not_called()
1249 m.hello()
1250 with self.assertRaises(AssertionError):
1251 m.hello.assert_not_called()
1252
Kushal Das047f14c2014-06-09 13:45:56 +05301253 #Issue21256 printout of keyword args should be in deterministic order
1254 def test_sorted_call_signature(self):
1255 m = Mock()
1256 m.hello(name='hello', daddy='hero')
1257 text = "call(daddy='hero', name='hello')"
R David Murray130a5662014-06-11 17:09:43 -04001258 self.assertEqual(repr(m.hello.call_args), text)
Kushal Das8af9db32014-04-17 01:36:14 +05301259
Kushal Dasa37b9582014-09-16 18:33:37 +05301260 #Issue21270 overrides tuple methods for mock.call objects
1261 def test_override_tuple_methods(self):
1262 c = call.count()
1263 i = call.index(132,'hello')
1264 m = Mock()
1265 m.count()
1266 m.index(132,"hello")
1267 self.assertEqual(m.method_calls[0], c)
1268 self.assertEqual(m.method_calls[1], i)
1269
Michael Foord345266a2012-03-14 12:24:34 -07001270 def test_mock_add_spec(self):
1271 class _One(object):
1272 one = 1
1273 class _Two(object):
1274 two = 2
1275 class Anything(object):
1276 one = two = three = 'four'
1277
1278 klasses = [
1279 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1280 ]
1281 for Klass in list(klasses):
1282 klasses.append(lambda K=Klass: K(spec=Anything))
1283 klasses.append(lambda K=Klass: K(spec_set=Anything))
1284
1285 for Klass in klasses:
1286 for kwargs in dict(), dict(spec_set=True):
1287 mock = Klass()
1288 #no error
1289 mock.one, mock.two, mock.three
1290
1291 for One, Two in [(_One, _Two), (['one'], ['two'])]:
1292 for kwargs in dict(), dict(spec_set=True):
1293 mock.mock_add_spec(One, **kwargs)
1294
1295 mock.one
1296 self.assertRaises(
1297 AttributeError, getattr, mock, 'two'
1298 )
1299 self.assertRaises(
1300 AttributeError, getattr, mock, 'three'
1301 )
1302 if 'spec_set' in kwargs:
1303 self.assertRaises(
1304 AttributeError, setattr, mock, 'three', None
1305 )
1306
1307 mock.mock_add_spec(Two, **kwargs)
1308 self.assertRaises(
1309 AttributeError, getattr, mock, 'one'
1310 )
1311 mock.two
1312 self.assertRaises(
1313 AttributeError, getattr, mock, 'three'
1314 )
1315 if 'spec_set' in kwargs:
1316 self.assertRaises(
1317 AttributeError, setattr, mock, 'three', None
1318 )
1319 # note that creating a mock, setting an instance attribute, and
1320 # *then* setting a spec doesn't work. Not the intended use case
1321
1322
1323 def test_mock_add_spec_magic_methods(self):
1324 for Klass in MagicMock, NonCallableMagicMock:
1325 mock = Klass()
1326 int(mock)
1327
1328 mock.mock_add_spec(object)
1329 self.assertRaises(TypeError, int, mock)
1330
1331 mock = Klass()
1332 mock['foo']
1333 mock.__int__.return_value =4
1334
1335 mock.mock_add_spec(int)
1336 self.assertEqual(int(mock), 4)
1337 self.assertRaises(TypeError, lambda: mock['foo'])
1338
1339
1340 def test_adding_child_mock(self):
1341 for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock:
1342 mock = Klass()
1343
1344 mock.foo = Mock()
1345 mock.foo()
1346
1347 self.assertEqual(mock.method_calls, [call.foo()])
1348 self.assertEqual(mock.mock_calls, [call.foo()])
1349
1350 mock = Klass()
1351 mock.bar = Mock(name='name')
1352 mock.bar()
1353 self.assertEqual(mock.method_calls, [])
1354 self.assertEqual(mock.mock_calls, [])
1355
1356 # mock with an existing _new_parent but no name
1357 mock = Klass()
1358 mock.baz = MagicMock()()
1359 mock.baz()
1360 self.assertEqual(mock.method_calls, [])
1361 self.assertEqual(mock.mock_calls, [])
1362
1363
1364 def test_adding_return_value_mock(self):
1365 for Klass in Mock, MagicMock:
1366 mock = Klass()
1367 mock.return_value = MagicMock()
1368
1369 mock()()
1370 self.assertEqual(mock.mock_calls, [call(), call()()])
1371
1372
1373 def test_manager_mock(self):
1374 class Foo(object):
1375 one = 'one'
1376 two = 'two'
1377 manager = Mock()
1378 p1 = patch.object(Foo, 'one')
1379 p2 = patch.object(Foo, 'two')
1380
1381 mock_one = p1.start()
1382 self.addCleanup(p1.stop)
1383 mock_two = p2.start()
1384 self.addCleanup(p2.stop)
1385
1386 manager.attach_mock(mock_one, 'one')
1387 manager.attach_mock(mock_two, 'two')
1388
1389 Foo.two()
1390 Foo.one()
1391
1392 self.assertEqual(manager.mock_calls, [call.two(), call.one()])
1393
1394
1395 def test_magic_methods_mock_calls(self):
1396 for Klass in Mock, MagicMock:
1397 m = Klass()
1398 m.__int__ = Mock(return_value=3)
1399 m.__float__ = MagicMock(return_value=3.0)
1400 int(m)
1401 float(m)
1402
1403 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
1404 self.assertEqual(m.method_calls, [])
1405
Robert Collins5329aaa2015-07-17 20:08:45 +12001406 def test_mock_open_reuse_issue_21750(self):
1407 mocked_open = mock.mock_open(read_data='data')
1408 f1 = mocked_open('a-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001409 f1_data = f1.read()
Robert Collins5329aaa2015-07-17 20:08:45 +12001410 f2 = mocked_open('another-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001411 f2_data = f2.read()
1412 self.assertEqual(f1_data, f2_data)
1413
1414 def test_mock_open_write(self):
1415 # Test exception in file writing write()
1416 mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
1417 with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
1418 mock_filehandle = mock_namedtemp.return_value
1419 mock_write = mock_filehandle.write
1420 mock_write.side_effect = OSError('Test 2 Error')
1421 def attempt():
1422 tempfile.NamedTemporaryFile().write('asd')
1423 self.assertRaises(OSError, attempt)
1424
1425 def test_mock_open_alter_readline(self):
1426 mopen = mock.mock_open(read_data='foo\nbarn')
1427 mopen.return_value.readline.side_effect = lambda *args:'abc'
1428 first = mopen().readline()
1429 second = mopen().readline()
1430 self.assertEqual('abc', first)
1431 self.assertEqual('abc', second)
Michael Foord345266a2012-03-14 12:24:34 -07001432
Robert Collins9549a3e2016-05-16 15:22:01 +12001433 def test_mock_open_after_eof(self):
1434 # read, readline and readlines should work after end of file.
1435 _open = mock.mock_open(read_data='foo')
1436 h = _open('bar')
1437 h.read()
1438 self.assertEqual('', h.read())
1439 self.assertEqual('', h.read())
1440 self.assertEqual('', h.readline())
1441 self.assertEqual('', h.readline())
1442 self.assertEqual([], h.readlines())
1443 self.assertEqual([], h.readlines())
1444
Michael Foord345266a2012-03-14 12:24:34 -07001445 def test_mock_parents(self):
1446 for Klass in Mock, MagicMock:
1447 m = Klass()
1448 original_repr = repr(m)
1449 m.return_value = m
1450 self.assertIs(m(), m)
1451 self.assertEqual(repr(m), original_repr)
1452
1453 m.reset_mock()
1454 self.assertIs(m(), m)
1455 self.assertEqual(repr(m), original_repr)
1456
1457 m = Klass()
1458 m.b = m.a
1459 self.assertIn("name='mock.a'", repr(m.b))
1460 self.assertIn("name='mock.a'", repr(m.a))
1461 m.reset_mock()
1462 self.assertIn("name='mock.a'", repr(m.b))
1463 self.assertIn("name='mock.a'", repr(m.a))
1464
1465 m = Klass()
1466 original_repr = repr(m)
1467 m.a = m()
1468 m.a.return_value = m
1469
1470 self.assertEqual(repr(m), original_repr)
1471 self.assertEqual(repr(m.a()), original_repr)
1472
1473
1474 def test_attach_mock(self):
1475 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1476 for Klass in classes:
1477 for Klass2 in classes:
1478 m = Klass()
1479
1480 m2 = Klass2(name='foo')
1481 m.attach_mock(m2, 'bar')
1482
1483 self.assertIs(m.bar, m2)
1484 self.assertIn("name='mock.bar'", repr(m2))
1485
1486 m.bar.baz(1)
1487 self.assertEqual(m.mock_calls, [call.bar.baz(1)])
1488 self.assertEqual(m.method_calls, [call.bar.baz(1)])
1489
1490
1491 def test_attach_mock_return_value(self):
1492 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1493 for Klass in Mock, MagicMock:
1494 for Klass2 in classes:
1495 m = Klass()
1496
1497 m2 = Klass2(name='foo')
1498 m.attach_mock(m2, 'return_value')
1499
1500 self.assertIs(m(), m2)
1501 self.assertIn("name='mock()'", repr(m2))
1502
1503 m2.foo()
1504 self.assertEqual(m.mock_calls, call().foo().call_list())
1505
1506
1507 def test_attribute_deletion(self):
Michael Foord468ec342013-09-15 20:05:19 +12001508 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1509 NonCallableMock()):
Michael Foord345266a2012-03-14 12:24:34 -07001510 self.assertTrue(hasattr(mock, 'm'))
1511
1512 del mock.m
1513 self.assertFalse(hasattr(mock, 'm'))
1514
1515 del mock.f
1516 self.assertFalse(hasattr(mock, 'f'))
1517 self.assertRaises(AttributeError, getattr, mock, 'f')
1518
1519
1520 def test_class_assignable(self):
1521 for mock in Mock(), MagicMock():
1522 self.assertNotIsInstance(mock, int)
1523
1524 mock.__class__ = int
1525 self.assertIsInstance(mock, int)
1526 mock.foo
1527
1528
Michael Foord345266a2012-03-14 12:24:34 -07001529if __name__ == '__main__':
1530 unittest.main()