blob: 8cd284a6522d6135890660626636ea7748b61aca [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,
12 NonCallableMagicMock, _CallList,
13 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
928 def test_subclassing(self):
929 class Subclass(Mock):
930 pass
931
932 mock = Subclass()
933 self.assertIsInstance(mock.foo, Subclass)
934 self.assertIsInstance(mock(), Subclass)
935
936 class Subclass(Mock):
937 def _get_child_mock(self, **kwargs):
938 return Mock(**kwargs)
939
940 mock = Subclass()
941 self.assertNotIsInstance(mock.foo, Subclass)
942 self.assertNotIsInstance(mock(), Subclass)
943
944
945 def test_arg_lists(self):
946 mocks = [
947 Mock(),
948 MagicMock(),
949 NonCallableMock(),
950 NonCallableMagicMock()
951 ]
952
953 def assert_attrs(mock):
954 names = 'call_args_list', 'method_calls', 'mock_calls'
955 for name in names:
956 attr = getattr(mock, name)
957 self.assertIsInstance(attr, _CallList)
958 self.assertIsInstance(attr, list)
959 self.assertEqual(attr, [])
960
961 for mock in mocks:
962 assert_attrs(mock)
963
964 if callable(mock):
965 mock()
966 mock(1, 2)
967 mock(a=3)
968
969 mock.reset_mock()
970 assert_attrs(mock)
971
972 mock.foo()
973 mock.foo.bar(1, a=3)
974 mock.foo(1).bar().baz(3)
975
976 mock.reset_mock()
977 assert_attrs(mock)
978
979
980 def test_call_args_two_tuple(self):
981 mock = Mock()
982 mock(1, a=3)
983 mock(2, b=4)
984
985 self.assertEqual(len(mock.call_args), 2)
986 args, kwargs = mock.call_args
987 self.assertEqual(args, (2,))
988 self.assertEqual(kwargs, dict(b=4))
989
990 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
991 for expected, call_args in zip(expected_list, mock.call_args_list):
992 self.assertEqual(len(call_args), 2)
993 self.assertEqual(expected[0], call_args[0])
994 self.assertEqual(expected[1], call_args[1])
995
996
997 def test_side_effect_iterator(self):
998 mock = Mock(side_effect=iter([1, 2, 3]))
999 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1000 self.assertRaises(StopIteration, mock)
1001
1002 mock = MagicMock(side_effect=['a', 'b', 'c'])
1003 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1004 self.assertRaises(StopIteration, mock)
1005
1006 mock = Mock(side_effect='ghi')
1007 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
1008 self.assertRaises(StopIteration, mock)
1009
1010 class Foo(object):
1011 pass
1012 mock = MagicMock(side_effect=Foo)
1013 self.assertIsInstance(mock(), Foo)
1014
1015 mock = Mock(side_effect=Iter())
1016 self.assertEqual([mock(), mock(), mock(), mock()],
1017 ['this', 'is', 'an', 'iter'])
1018 self.assertRaises(StopIteration, mock)
1019
1020
Michael Foord2cd48732012-04-21 15:52:11 +01001021 def test_side_effect_iterator_exceptions(self):
1022 for Klass in Mock, MagicMock:
1023 iterable = (ValueError, 3, KeyError, 6)
1024 m = Klass(side_effect=iterable)
1025 self.assertRaises(ValueError, m)
1026 self.assertEqual(m(), 3)
1027 self.assertRaises(KeyError, m)
1028 self.assertEqual(m(), 6)
1029
1030
Michael Foord345266a2012-03-14 12:24:34 -07001031 def test_side_effect_setting_iterator(self):
1032 mock = Mock()
1033 mock.side_effect = iter([1, 2, 3])
1034 self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
1035 self.assertRaises(StopIteration, mock)
1036 side_effect = mock.side_effect
1037 self.assertIsInstance(side_effect, type(iter([])))
1038
1039 mock.side_effect = ['a', 'b', 'c']
1040 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
1041 self.assertRaises(StopIteration, mock)
1042 side_effect = mock.side_effect
1043 self.assertIsInstance(side_effect, type(iter([])))
1044
1045 this_iter = Iter()
1046 mock.side_effect = this_iter
1047 self.assertEqual([mock(), mock(), mock(), mock()],
1048 ['this', 'is', 'an', 'iter'])
1049 self.assertRaises(StopIteration, mock)
1050 self.assertIs(mock.side_effect, this_iter)
1051
Andrew Svetlov8b2cd752013-04-07 16:42:24 +03001052 def test_side_effect_iterator_default(self):
1053 mock = Mock(return_value=2)
1054 mock.side_effect = iter([1, DEFAULT])
1055 self.assertEqual([mock(), mock()], [1, 2])
Michael Foord345266a2012-03-14 12:24:34 -07001056
1057 def test_assert_has_calls_any_order(self):
1058 mock = Mock()
1059 mock(1, 2)
1060 mock(a=3)
1061 mock(3, 4)
1062 mock(b=6)
1063 mock(b=6)
1064
1065 kalls = [
1066 call(1, 2), ({'a': 3},),
1067 ((3, 4),), ((), {'a': 3}),
1068 ('', (1, 2)), ('', {'a': 3}),
1069 ('', (1, 2), {}), ('', (), {'a': 3})
1070 ]
1071 for kall in kalls:
1072 mock.assert_has_calls([kall], any_order=True)
1073
1074 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
1075 self.assertRaises(
1076 AssertionError, mock.assert_has_calls,
1077 [kall], any_order=True
1078 )
1079
1080 kall_lists = [
1081 [call(1, 2), call(b=6)],
1082 [call(3, 4), call(1, 2)],
1083 [call(b=6), call(b=6)],
1084 ]
1085
1086 for kall_list in kall_lists:
1087 mock.assert_has_calls(kall_list, any_order=True)
1088
1089 kall_lists = [
1090 [call(b=6), call(b=6), call(b=6)],
1091 [call(1, 2), call(1, 2)],
1092 [call(3, 4), call(1, 2), call(5, 7)],
1093 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
1094 ]
1095 for kall_list in kall_lists:
1096 self.assertRaises(
1097 AssertionError, mock.assert_has_calls,
1098 kall_list, any_order=True
1099 )
1100
1101 def test_assert_has_calls(self):
1102 kalls1 = [
1103 call(1, 2), ({'a': 3},),
1104 ((3, 4),), call(b=6),
1105 ('', (1,), {'b': 6}),
1106 ]
1107 kalls2 = [call.foo(), call.bar(1)]
1108 kalls2.extend(call.spam().baz(a=3).call_list())
1109 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
1110
1111 mocks = []
1112 for mock in Mock(), MagicMock():
1113 mock(1, 2)
1114 mock(a=3)
1115 mock(3, 4)
1116 mock(b=6)
1117 mock(1, b=6)
1118 mocks.append((mock, kalls1))
1119
1120 mock = Mock()
1121 mock.foo()
1122 mock.bar(1)
1123 mock.spam().baz(a=3)
1124 mock.bam(set(), foo={}).fish([1])
1125 mocks.append((mock, kalls2))
1126
1127 for mock, kalls in mocks:
1128 for i in range(len(kalls)):
1129 for step in 1, 2, 3:
1130 these = kalls[i:i+step]
1131 mock.assert_has_calls(these)
1132
1133 if len(these) > 1:
1134 self.assertRaises(
1135 AssertionError,
1136 mock.assert_has_calls,
1137 list(reversed(these))
1138 )
1139
1140
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001141 def test_assert_has_calls_with_function_spec(self):
1142 def f(a, b, c, d=None):
1143 pass
1144
1145 mock = Mock(spec=f)
1146
1147 mock(1, b=2, c=3)
1148 mock(4, 5, c=6, d=7)
1149 mock(10, 11, c=12)
1150 calls = [
1151 ('', (1, 2, 3), {}),
1152 ('', (4, 5, 6), {'d': 7}),
1153 ((10, 11, 12), {}),
1154 ]
1155 mock.assert_has_calls(calls)
1156 mock.assert_has_calls(calls, any_order=True)
1157 mock.assert_has_calls(calls[1:])
1158 mock.assert_has_calls(calls[1:], any_order=True)
1159 mock.assert_has_calls(calls[:-1])
1160 mock.assert_has_calls(calls[:-1], any_order=True)
1161 # Reversed order
1162 calls = list(reversed(calls))
1163 with self.assertRaises(AssertionError):
1164 mock.assert_has_calls(calls)
1165 mock.assert_has_calls(calls, any_order=True)
1166 with self.assertRaises(AssertionError):
1167 mock.assert_has_calls(calls[1:])
1168 mock.assert_has_calls(calls[1:], any_order=True)
1169 with self.assertRaises(AssertionError):
1170 mock.assert_has_calls(calls[:-1])
1171 mock.assert_has_calls(calls[:-1], any_order=True)
1172
1173
Michael Foord345266a2012-03-14 12:24:34 -07001174 def test_assert_any_call(self):
1175 mock = Mock()
1176 mock(1, 2)
1177 mock(a=3)
1178 mock(1, b=6)
1179
1180 mock.assert_any_call(1, 2)
1181 mock.assert_any_call(a=3)
1182 mock.assert_any_call(1, b=6)
1183
1184 self.assertRaises(
1185 AssertionError,
1186 mock.assert_any_call
1187 )
1188 self.assertRaises(
1189 AssertionError,
1190 mock.assert_any_call,
1191 1, 3
1192 )
1193 self.assertRaises(
1194 AssertionError,
1195 mock.assert_any_call,
1196 a=4
1197 )
1198
1199
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001200 def test_assert_any_call_with_function_spec(self):
1201 def f(a, b, c, d=None):
1202 pass
1203
1204 mock = Mock(spec=f)
1205
1206 mock(1, b=2, c=3)
1207 mock(4, 5, c=6, d=7)
1208 mock.assert_any_call(1, 2, 3)
1209 mock.assert_any_call(a=1, b=2, c=3)
1210 mock.assert_any_call(4, 5, 6, 7)
1211 mock.assert_any_call(a=4, b=5, c=6, d=7)
1212 self.assertRaises(AssertionError, mock.assert_any_call,
1213 1, b=3, c=2)
1214 # Expected call doesn't match the spec's signature
1215 with self.assertRaises(AssertionError) as cm:
1216 mock.assert_any_call(e=8)
1217 self.assertIsInstance(cm.exception.__cause__, TypeError)
1218
1219
Michael Foord345266a2012-03-14 12:24:34 -07001220 def test_mock_calls_create_autospec(self):
1221 def f(a, b):
1222 pass
1223 obj = Iter()
1224 obj.f = f
1225
1226 funcs = [
1227 create_autospec(f),
1228 create_autospec(obj).f
1229 ]
1230 for func in funcs:
1231 func(1, 2)
1232 func(3, 4)
1233
1234 self.assertEqual(
1235 func.mock_calls, [call(1, 2), call(3, 4)]
1236 )
1237
Kushal Das484f8a82014-04-16 01:05:50 +05301238 #Issue21222
1239 def test_create_autospec_with_name(self):
1240 m = mock.create_autospec(object(), name='sweet_func')
1241 self.assertIn('sweet_func', repr(m))
Michael Foord345266a2012-03-14 12:24:34 -07001242
Kushal Das8c145342014-04-16 23:32:21 +05301243 #Issue21238
1244 def test_mock_unsafe(self):
1245 m = Mock()
1246 with self.assertRaises(AttributeError):
1247 m.assert_foo_call()
1248 with self.assertRaises(AttributeError):
1249 m.assret_foo_call()
1250 m = Mock(unsafe=True)
1251 m.assert_foo_call()
1252 m.assret_foo_call()
1253
Kushal Das8af9db32014-04-17 01:36:14 +05301254 #Issue21262
1255 def test_assert_not_called(self):
1256 m = Mock()
1257 m.hello.assert_not_called()
1258 m.hello()
1259 with self.assertRaises(AssertionError):
1260 m.hello.assert_not_called()
1261
Petter Strandmark47d94242018-10-28 21:37:10 +01001262 def test_assert_not_called_message(self):
1263 m = Mock()
1264 m(1, 2)
1265 self.assertRaisesRegex(AssertionError,
1266 re.escape("Calls: [call(1, 2)]"),
1267 m.assert_not_called)
1268
Victor Stinner2c2a4e62016-03-11 22:17:48 +01001269 def test_assert_called(self):
1270 m = Mock()
1271 with self.assertRaises(AssertionError):
1272 m.hello.assert_called()
1273 m.hello()
1274 m.hello.assert_called()
1275
1276 m.hello()
1277 m.hello.assert_called()
1278
1279 def test_assert_called_once(self):
1280 m = Mock()
1281 with self.assertRaises(AssertionError):
1282 m.hello.assert_called_once()
1283 m.hello()
1284 m.hello.assert_called_once()
1285
1286 m.hello()
1287 with self.assertRaises(AssertionError):
1288 m.hello.assert_called_once()
1289
Petter Strandmark47d94242018-10-28 21:37:10 +01001290 def test_assert_called_once_message(self):
1291 m = Mock()
1292 m(1, 2)
1293 m(3)
1294 self.assertRaisesRegex(AssertionError,
1295 re.escape("Calls: [call(1, 2), call(3)]"),
1296 m.assert_called_once)
1297
1298 def test_assert_called_once_message_not_called(self):
1299 m = Mock()
1300 with self.assertRaises(AssertionError) as e:
1301 m.assert_called_once()
1302 self.assertNotIn("Calls:", str(e.exception))
1303
Kushal Das047f14c2014-06-09 13:45:56 +05301304 #Issue21256 printout of keyword args should be in deterministic order
1305 def test_sorted_call_signature(self):
1306 m = Mock()
1307 m.hello(name='hello', daddy='hero')
1308 text = "call(daddy='hero', name='hello')"
R David Murray130a5662014-06-11 17:09:43 -04001309 self.assertEqual(repr(m.hello.call_args), text)
Kushal Das8af9db32014-04-17 01:36:14 +05301310
Kushal Dasa37b9582014-09-16 18:33:37 +05301311 #Issue21270 overrides tuple methods for mock.call objects
1312 def test_override_tuple_methods(self):
1313 c = call.count()
1314 i = call.index(132,'hello')
1315 m = Mock()
1316 m.count()
1317 m.index(132,"hello")
1318 self.assertEqual(m.method_calls[0], c)
1319 self.assertEqual(m.method_calls[1], i)
1320
Kushal Das9cd39a12016-06-02 10:20:16 -07001321 def test_reset_return_sideeffect(self):
1322 m = Mock(return_value=10, side_effect=[2,3])
1323 m.reset_mock(return_value=True, side_effect=True)
1324 self.assertIsInstance(m.return_value, Mock)
1325 self.assertEqual(m.side_effect, None)
1326
1327 def test_reset_return(self):
1328 m = Mock(return_value=10, side_effect=[2,3])
1329 m.reset_mock(return_value=True)
1330 self.assertIsInstance(m.return_value, Mock)
1331 self.assertNotEqual(m.side_effect, None)
1332
1333 def test_reset_sideeffect(self):
1334 m = Mock(return_value=10, side_effect=[2,3])
1335 m.reset_mock(side_effect=True)
1336 self.assertEqual(m.return_value, 10)
1337 self.assertEqual(m.side_effect, None)
1338
Michael Foord345266a2012-03-14 12:24:34 -07001339 def test_mock_add_spec(self):
1340 class _One(object):
1341 one = 1
1342 class _Two(object):
1343 two = 2
1344 class Anything(object):
1345 one = two = three = 'four'
1346
1347 klasses = [
1348 Mock, MagicMock, NonCallableMock, NonCallableMagicMock
1349 ]
1350 for Klass in list(klasses):
1351 klasses.append(lambda K=Klass: K(spec=Anything))
1352 klasses.append(lambda K=Klass: K(spec_set=Anything))
1353
1354 for Klass in klasses:
1355 for kwargs in dict(), dict(spec_set=True):
1356 mock = Klass()
1357 #no error
1358 mock.one, mock.two, mock.three
1359
1360 for One, Two in [(_One, _Two), (['one'], ['two'])]:
1361 for kwargs in dict(), dict(spec_set=True):
1362 mock.mock_add_spec(One, **kwargs)
1363
1364 mock.one
1365 self.assertRaises(
1366 AttributeError, getattr, mock, 'two'
1367 )
1368 self.assertRaises(
1369 AttributeError, getattr, mock, 'three'
1370 )
1371 if 'spec_set' in kwargs:
1372 self.assertRaises(
1373 AttributeError, setattr, mock, 'three', None
1374 )
1375
1376 mock.mock_add_spec(Two, **kwargs)
1377 self.assertRaises(
1378 AttributeError, getattr, mock, 'one'
1379 )
1380 mock.two
1381 self.assertRaises(
1382 AttributeError, getattr, mock, 'three'
1383 )
1384 if 'spec_set' in kwargs:
1385 self.assertRaises(
1386 AttributeError, setattr, mock, 'three', None
1387 )
1388 # note that creating a mock, setting an instance attribute, and
1389 # *then* setting a spec doesn't work. Not the intended use case
1390
1391
1392 def test_mock_add_spec_magic_methods(self):
1393 for Klass in MagicMock, NonCallableMagicMock:
1394 mock = Klass()
1395 int(mock)
1396
1397 mock.mock_add_spec(object)
1398 self.assertRaises(TypeError, int, mock)
1399
1400 mock = Klass()
1401 mock['foo']
1402 mock.__int__.return_value =4
1403
1404 mock.mock_add_spec(int)
1405 self.assertEqual(int(mock), 4)
1406 self.assertRaises(TypeError, lambda: mock['foo'])
1407
1408
1409 def test_adding_child_mock(self):
1410 for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock:
1411 mock = Klass()
1412
1413 mock.foo = Mock()
1414 mock.foo()
1415
1416 self.assertEqual(mock.method_calls, [call.foo()])
1417 self.assertEqual(mock.mock_calls, [call.foo()])
1418
1419 mock = Klass()
1420 mock.bar = Mock(name='name')
1421 mock.bar()
1422 self.assertEqual(mock.method_calls, [])
1423 self.assertEqual(mock.mock_calls, [])
1424
1425 # mock with an existing _new_parent but no name
1426 mock = Klass()
1427 mock.baz = MagicMock()()
1428 mock.baz()
1429 self.assertEqual(mock.method_calls, [])
1430 self.assertEqual(mock.mock_calls, [])
1431
1432
1433 def test_adding_return_value_mock(self):
1434 for Klass in Mock, MagicMock:
1435 mock = Klass()
1436 mock.return_value = MagicMock()
1437
1438 mock()()
1439 self.assertEqual(mock.mock_calls, [call(), call()()])
1440
1441
1442 def test_manager_mock(self):
1443 class Foo(object):
1444 one = 'one'
1445 two = 'two'
1446 manager = Mock()
1447 p1 = patch.object(Foo, 'one')
1448 p2 = patch.object(Foo, 'two')
1449
1450 mock_one = p1.start()
1451 self.addCleanup(p1.stop)
1452 mock_two = p2.start()
1453 self.addCleanup(p2.stop)
1454
1455 manager.attach_mock(mock_one, 'one')
1456 manager.attach_mock(mock_two, 'two')
1457
1458 Foo.two()
1459 Foo.one()
1460
1461 self.assertEqual(manager.mock_calls, [call.two(), call.one()])
1462
1463
1464 def test_magic_methods_mock_calls(self):
1465 for Klass in Mock, MagicMock:
1466 m = Klass()
1467 m.__int__ = Mock(return_value=3)
1468 m.__float__ = MagicMock(return_value=3.0)
1469 int(m)
1470 float(m)
1471
1472 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
1473 self.assertEqual(m.method_calls, [])
1474
Robert Collins5329aaa2015-07-17 20:08:45 +12001475 def test_mock_open_reuse_issue_21750(self):
1476 mocked_open = mock.mock_open(read_data='data')
1477 f1 = mocked_open('a-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001478 f1_data = f1.read()
Robert Collins5329aaa2015-07-17 20:08:45 +12001479 f2 = mocked_open('another-name')
Robert Collinsca647ef2015-07-24 03:48:20 +12001480 f2_data = f2.read()
1481 self.assertEqual(f1_data, f2_data)
1482
Tony Flury20870232018-09-12 23:21:16 +01001483 def test_mock_open_dunder_iter_issue(self):
1484 # Test dunder_iter method generates the expected result and
1485 # consumes the iterator.
1486 mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue')
1487 f1 = mocked_open('a-name')
1488 lines = [line for line in f1]
1489 self.assertEqual(lines[0], 'Remarkable\n')
1490 self.assertEqual(lines[1], 'Norwegian Blue')
1491 self.assertEqual(list(f1), [])
1492
Robert Collinsca647ef2015-07-24 03:48:20 +12001493 def test_mock_open_write(self):
1494 # Test exception in file writing write()
1495 mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
1496 with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
1497 mock_filehandle = mock_namedtemp.return_value
1498 mock_write = mock_filehandle.write
1499 mock_write.side_effect = OSError('Test 2 Error')
1500 def attempt():
1501 tempfile.NamedTemporaryFile().write('asd')
1502 self.assertRaises(OSError, attempt)
1503
1504 def test_mock_open_alter_readline(self):
1505 mopen = mock.mock_open(read_data='foo\nbarn')
1506 mopen.return_value.readline.side_effect = lambda *args:'abc'
1507 first = mopen().readline()
1508 second = mopen().readline()
1509 self.assertEqual('abc', first)
1510 self.assertEqual('abc', second)
Michael Foord345266a2012-03-14 12:24:34 -07001511
Robert Collins9549a3e2016-05-16 15:22:01 +12001512 def test_mock_open_after_eof(self):
1513 # read, readline and readlines should work after end of file.
1514 _open = mock.mock_open(read_data='foo')
1515 h = _open('bar')
1516 h.read()
1517 self.assertEqual('', h.read())
1518 self.assertEqual('', h.read())
1519 self.assertEqual('', h.readline())
1520 self.assertEqual('', h.readline())
1521 self.assertEqual([], h.readlines())
1522 self.assertEqual([], h.readlines())
1523
Michael Foord345266a2012-03-14 12:24:34 -07001524 def test_mock_parents(self):
1525 for Klass in Mock, MagicMock:
1526 m = Klass()
1527 original_repr = repr(m)
1528 m.return_value = m
1529 self.assertIs(m(), m)
1530 self.assertEqual(repr(m), original_repr)
1531
1532 m.reset_mock()
1533 self.assertIs(m(), m)
1534 self.assertEqual(repr(m), original_repr)
1535
1536 m = Klass()
1537 m.b = m.a
1538 self.assertIn("name='mock.a'", repr(m.b))
1539 self.assertIn("name='mock.a'", repr(m.a))
1540 m.reset_mock()
1541 self.assertIn("name='mock.a'", repr(m.b))
1542 self.assertIn("name='mock.a'", repr(m.a))
1543
1544 m = Klass()
1545 original_repr = repr(m)
1546 m.a = m()
1547 m.a.return_value = m
1548
1549 self.assertEqual(repr(m), original_repr)
1550 self.assertEqual(repr(m.a()), original_repr)
1551
1552
1553 def test_attach_mock(self):
1554 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1555 for Klass in classes:
1556 for Klass2 in classes:
1557 m = Klass()
1558
1559 m2 = Klass2(name='foo')
1560 m.attach_mock(m2, 'bar')
1561
1562 self.assertIs(m.bar, m2)
1563 self.assertIn("name='mock.bar'", repr(m2))
1564
1565 m.bar.baz(1)
1566 self.assertEqual(m.mock_calls, [call.bar.baz(1)])
1567 self.assertEqual(m.method_calls, [call.bar.baz(1)])
1568
1569
1570 def test_attach_mock_return_value(self):
1571 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
1572 for Klass in Mock, MagicMock:
1573 for Klass2 in classes:
1574 m = Klass()
1575
1576 m2 = Klass2(name='foo')
1577 m.attach_mock(m2, 'return_value')
1578
1579 self.assertIs(m(), m2)
1580 self.assertIn("name='mock()'", repr(m2))
1581
1582 m2.foo()
1583 self.assertEqual(m.mock_calls, call().foo().call_list())
1584
1585
1586 def test_attribute_deletion(self):
Michael Foord468ec342013-09-15 20:05:19 +12001587 for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
1588 NonCallableMock()):
Michael Foord345266a2012-03-14 12:24:34 -07001589 self.assertTrue(hasattr(mock, 'm'))
1590
1591 del mock.m
1592 self.assertFalse(hasattr(mock, 'm'))
1593
1594 del mock.f
1595 self.assertFalse(hasattr(mock, 'f'))
1596 self.assertRaises(AttributeError, getattr, mock, 'f')
1597
1598
1599 def test_class_assignable(self):
1600 for mock in Mock(), MagicMock():
1601 self.assertNotIsInstance(mock, int)
1602
1603 mock.__class__ = int
1604 self.assertIsInstance(mock, int)
1605 mock.foo
1606
1607
Michael Foord345266a2012-03-14 12:24:34 -07001608if __name__ == '__main__':
1609 unittest.main()