1import copy 2import re 3import sys 4import tempfile 5 6from test.support import ALWAYS_EQ 7import unittest 8from unittest.test.testmock.support import is_instance 9from unittest import mock 10from unittest.mock import ( 11 call, DEFAULT, patch, sentinel, 12 MagicMock, Mock, NonCallableMock, 13 NonCallableMagicMock, AsyncMock, _Call, _CallList, 14 create_autospec 15) 16 17 18class Iter(object): 19 def __init__(self): 20 self.thing = iter(['this', 'is', 'an', 'iter']) 21 22 def __iter__(self): 23 return self 24 25 def next(self): 26 return next(self.thing) 27 28 __next__ = next 29 30 31class Something(object): 32 def meth(self, a, b, c, d=None): pass 33 34 @classmethod 35 def cmeth(cls, a, b, c, d=None): pass 36 37 @staticmethod 38 def smeth(a, b, c, d=None): pass 39 40 41def something(a): pass 42 43 44class MockTest(unittest.TestCase): 45 46 def test_all(self): 47 # if __all__ is badly defined then import * will raise an error 48 # We have to exec it because you can't import * inside a method 49 # in Python 3 50 exec("from unittest.mock import *") 51 52 53 def test_constructor(self): 54 mock = Mock() 55 56 self.assertFalse(mock.called, "called not initialised correctly") 57 self.assertEqual(mock.call_count, 0, 58 "call_count not initialised correctly") 59 self.assertTrue(is_instance(mock.return_value, Mock), 60 "return_value not initialised correctly") 61 62 self.assertEqual(mock.call_args, None, 63 "call_args not initialised correctly") 64 self.assertEqual(mock.call_args_list, [], 65 "call_args_list not initialised correctly") 66 self.assertEqual(mock.method_calls, [], 67 "method_calls not initialised correctly") 68 69 # Can't use hasattr for this test as it always returns True on a mock 70 self.assertNotIn('_items', mock.__dict__, 71 "default mock should not have '_items' attribute") 72 73 self.assertIsNone(mock._mock_parent, 74 "parent not initialised correctly") 75 self.assertIsNone(mock._mock_methods, 76 "methods not initialised correctly") 77 self.assertEqual(mock._mock_children, {}, 78 "children not initialised incorrectly") 79 80 81 def test_return_value_in_constructor(self): 82 mock = Mock(return_value=None) 83 self.assertIsNone(mock.return_value, 84 "return value in constructor not honoured") 85 86 87 def test_change_return_value_via_delegate(self): 88 def f(): pass 89 mock = create_autospec(f) 90 mock.mock.return_value = 1 91 self.assertEqual(mock(), 1) 92 93 94 def test_change_side_effect_via_delegate(self): 95 def f(): pass 96 mock = create_autospec(f) 97 mock.mock.side_effect = TypeError() 98 with self.assertRaises(TypeError): 99 mock() 100 101 102 def test_repr(self): 103 mock = Mock(name='foo') 104 self.assertIn('foo', repr(mock)) 105 self.assertIn("'%s'" % id(mock), repr(mock)) 106 107 mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')] 108 for mock, name in mocks: 109 self.assertIn('%s.bar' % name, repr(mock.bar)) 110 self.assertIn('%s.foo()' % name, repr(mock.foo())) 111 self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing)) 112 self.assertIn('%s()' % name, repr(mock())) 113 self.assertIn('%s()()' % name, repr(mock()())) 114 self.assertIn('%s()().foo.bar.baz().bing' % name, 115 repr(mock()().foo.bar.baz().bing)) 116 117 118 def test_repr_with_spec(self): 119 class X(object): 120 pass 121 122 mock = Mock(spec=X) 123 self.assertIn(" spec='X' ", repr(mock)) 124 125 mock = Mock(spec=X()) 126 self.assertIn(" spec='X' ", repr(mock)) 127 128 mock = Mock(spec_set=X) 129 self.assertIn(" spec_set='X' ", repr(mock)) 130 131 mock = Mock(spec_set=X()) 132 self.assertIn(" spec_set='X' ", repr(mock)) 133 134 mock = Mock(spec=X, name='foo') 135 self.assertIn(" spec='X' ", repr(mock)) 136 self.assertIn(" name='foo' ", repr(mock)) 137 138 mock = Mock(name='foo') 139 self.assertNotIn("spec", repr(mock)) 140 141 mock = Mock() 142 self.assertNotIn("spec", repr(mock)) 143 144 mock = Mock(spec=['foo']) 145 self.assertNotIn("spec", repr(mock)) 146 147 148 def test_side_effect(self): 149 mock = Mock() 150 151 def effect(*args, **kwargs): 152 raise SystemError('kablooie') 153 154 mock.side_effect = effect 155 self.assertRaises(SystemError, mock, 1, 2, fish=3) 156 mock.assert_called_with(1, 2, fish=3) 157 158 results = [1, 2, 3] 159 def effect(): 160 return results.pop() 161 mock.side_effect = effect 162 163 self.assertEqual([mock(), mock(), mock()], [3, 2, 1], 164 "side effect not used correctly") 165 166 mock = Mock(side_effect=sentinel.SideEffect) 167 self.assertEqual(mock.side_effect, sentinel.SideEffect, 168 "side effect in constructor not used") 169 170 def side_effect(): 171 return DEFAULT 172 mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN) 173 self.assertEqual(mock(), sentinel.RETURN) 174 175 def test_autospec_side_effect(self): 176 # Test for issue17826 177 results = [1, 2, 3] 178 def effect(): 179 return results.pop() 180 def f(): pass 181 182 mock = create_autospec(f) 183 mock.side_effect = [1, 2, 3] 184 self.assertEqual([mock(), mock(), mock()], [1, 2, 3], 185 "side effect not used correctly in create_autospec") 186 # Test where side effect is a callable 187 results = [1, 2, 3] 188 mock = create_autospec(f) 189 mock.side_effect = effect 190 self.assertEqual([mock(), mock(), mock()], [3, 2, 1], 191 "callable side effect not used correctly") 192 193 def test_autospec_side_effect_exception(self): 194 # Test for issue 23661 195 def f(): pass 196 197 mock = create_autospec(f) 198 mock.side_effect = ValueError('Bazinga!') 199 self.assertRaisesRegex(ValueError, 'Bazinga!', mock) 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 250 def test_reset_mock_on_mock_open_issue_18622(self): 251 a = mock.mock_open() 252 a.reset_mock() 253 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 incorrect") 267 self.assertEqual(mock.call_args, ((sentinel.Arg,), {}), 268 "call_args not set") 269 self.assertEqual(mock.call_args.args, (sentinel.Arg,), 270 "call_args not set") 271 self.assertEqual(mock.call_args.kwargs, {}, 272 "call_args not set") 273 self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})], 274 "call_args_list not initialised correctly") 275 276 mock.return_value = sentinel.ReturnValue 277 ret_val = mock(sentinel.Arg, key=sentinel.KeyArg) 278 self.assertEqual(ret_val, sentinel.ReturnValue, 279 "incorrect return value") 280 281 self.assertEqual(mock.call_count, 2, "call_count incorrect") 282 self.assertEqual(mock.call_args, 283 ((sentinel.Arg,), {'key': sentinel.KeyArg}), 284 "call_args not set") 285 self.assertEqual(mock.call_args_list, [ 286 ((sentinel.Arg,), {}), 287 ((sentinel.Arg,), {'key': sentinel.KeyArg}) 288 ], 289 "call_args_list not set") 290 291 292 def test_call_args_comparison(self): 293 mock = Mock() 294 mock() 295 mock(sentinel.Arg) 296 mock(kw=sentinel.Kwarg) 297 mock(sentinel.Arg, kw=sentinel.Kwarg) 298 self.assertEqual(mock.call_args_list, [ 299 (), 300 ((sentinel.Arg,),), 301 ({"kw": sentinel.Kwarg},), 302 ((sentinel.Arg,), {"kw": sentinel.Kwarg}) 303 ]) 304 self.assertEqual(mock.call_args, 305 ((sentinel.Arg,), {"kw": sentinel.Kwarg})) 306 self.assertEqual(mock.call_args.args, (sentinel.Arg,)) 307 self.assertEqual(mock.call_args.kwargs, {"kw": sentinel.Kwarg}) 308 309 # Comparing call_args to a long sequence should not raise 310 # an exception. See issue 24857. 311 self.assertFalse(mock.call_args == "a long sequence") 312 313 314 def test_calls_equal_with_any(self): 315 # Check that equality and non-equality is consistent even when 316 # comparing with mock.ANY 317 mm = mock.MagicMock() 318 self.assertTrue(mm == mm) 319 self.assertFalse(mm != mm) 320 self.assertFalse(mm == mock.MagicMock()) 321 self.assertTrue(mm != mock.MagicMock()) 322 self.assertTrue(mm == mock.ANY) 323 self.assertFalse(mm != mock.ANY) 324 self.assertTrue(mock.ANY == mm) 325 self.assertFalse(mock.ANY != mm) 326 self.assertTrue(mm == ALWAYS_EQ) 327 self.assertFalse(mm != ALWAYS_EQ) 328 329 call1 = mock.call(mock.MagicMock()) 330 call2 = mock.call(mock.ANY) 331 self.assertTrue(call1 == call2) 332 self.assertFalse(call1 != call2) 333 self.assertTrue(call2 == call1) 334 self.assertFalse(call2 != call1) 335 336 self.assertTrue(call1 == ALWAYS_EQ) 337 self.assertFalse(call1 != ALWAYS_EQ) 338 self.assertFalse(call1 == 1) 339 self.assertTrue(call1 != 1) 340 341 342 def test_assert_called_with(self): 343 mock = Mock() 344 mock() 345 346 # Will raise an exception if it fails 347 mock.assert_called_with() 348 self.assertRaises(AssertionError, mock.assert_called_with, 1) 349 350 mock.reset_mock() 351 self.assertRaises(AssertionError, mock.assert_called_with) 352 353 mock(1, 2, 3, a='fish', b='nothing') 354 mock.assert_called_with(1, 2, 3, a='fish', b='nothing') 355 356 357 def test_assert_called_with_any(self): 358 m = MagicMock() 359 m(MagicMock()) 360 m.assert_called_with(mock.ANY) 361 362 363 def test_assert_called_with_function_spec(self): 364 def f(a, b, c, d=None): pass 365 366 mock = Mock(spec=f) 367 368 mock(1, b=2, c=3) 369 mock.assert_called_with(1, 2, 3) 370 mock.assert_called_with(a=1, b=2, c=3) 371 self.assertRaises(AssertionError, mock.assert_called_with, 372 1, b=3, c=2) 373 # Expected call doesn't match the spec's signature 374 with self.assertRaises(AssertionError) as cm: 375 mock.assert_called_with(e=8) 376 self.assertIsInstance(cm.exception.__cause__, TypeError) 377 378 379 def test_assert_called_with_method_spec(self): 380 def _check(mock): 381 mock(1, b=2, c=3) 382 mock.assert_called_with(1, 2, 3) 383 mock.assert_called_with(a=1, b=2, c=3) 384 self.assertRaises(AssertionError, mock.assert_called_with, 385 1, b=3, c=2) 386 387 mock = Mock(spec=Something().meth) 388 _check(mock) 389 mock = Mock(spec=Something.cmeth) 390 _check(mock) 391 mock = Mock(spec=Something().cmeth) 392 _check(mock) 393 mock = Mock(spec=Something.smeth) 394 _check(mock) 395 mock = Mock(spec=Something().smeth) 396 _check(mock) 397 398 399 def test_assert_called_exception_message(self): 400 msg = "Expected '{0}' to have been called" 401 with self.assertRaisesRegex(AssertionError, msg.format('mock')): 402 Mock().assert_called() 403 with self.assertRaisesRegex(AssertionError, msg.format('test_name')): 404 Mock(name="test_name").assert_called() 405 406 407 def test_assert_called_once_with(self): 408 mock = Mock() 409 mock() 410 411 # Will raise an exception if it fails 412 mock.assert_called_once_with() 413 414 mock() 415 self.assertRaises(AssertionError, mock.assert_called_once_with) 416 417 mock.reset_mock() 418 self.assertRaises(AssertionError, mock.assert_called_once_with) 419 420 mock('foo', 'bar', baz=2) 421 mock.assert_called_once_with('foo', 'bar', baz=2) 422 423 mock.reset_mock() 424 mock('foo', 'bar', baz=2) 425 self.assertRaises( 426 AssertionError, 427 lambda: mock.assert_called_once_with('bob', 'bar', baz=2) 428 ) 429 430 def test_assert_called_once_with_call_list(self): 431 m = Mock() 432 m(1) 433 m(2) 434 self.assertRaisesRegex(AssertionError, 435 re.escape("Calls: [call(1), call(2)]"), 436 lambda: m.assert_called_once_with(2)) 437 438 439 def test_assert_called_once_with_function_spec(self): 440 def f(a, b, c, d=None): pass 441 442 mock = Mock(spec=f) 443 444 mock(1, b=2, c=3) 445 mock.assert_called_once_with(1, 2, 3) 446 mock.assert_called_once_with(a=1, b=2, c=3) 447 self.assertRaises(AssertionError, mock.assert_called_once_with, 448 1, b=3, c=2) 449 # Expected call doesn't match the spec's signature 450 with self.assertRaises(AssertionError) as cm: 451 mock.assert_called_once_with(e=8) 452 self.assertIsInstance(cm.exception.__cause__, TypeError) 453 # Mock called more than once => always fails 454 mock(4, 5, 6) 455 self.assertRaises(AssertionError, mock.assert_called_once_with, 456 1, 2, 3) 457 self.assertRaises(AssertionError, mock.assert_called_once_with, 458 4, 5, 6) 459 460 461 def test_attribute_access_returns_mocks(self): 462 mock = Mock() 463 something = mock.something 464 self.assertTrue(is_instance(something, Mock), "attribute isn't a mock") 465 self.assertEqual(mock.something, something, 466 "different attributes returned for same name") 467 468 # Usage example 469 mock = Mock() 470 mock.something.return_value = 3 471 472 self.assertEqual(mock.something(), 3, "method returned wrong value") 473 self.assertTrue(mock.something.called, 474 "method didn't record being called") 475 476 477 def test_attributes_have_name_and_parent_set(self): 478 mock = Mock() 479 something = mock.something 480 481 self.assertEqual(something._mock_name, "something", 482 "attribute name not set correctly") 483 self.assertEqual(something._mock_parent, mock, 484 "attribute parent not set correctly") 485 486 487 def test_method_calls_recorded(self): 488 mock = Mock() 489 mock.something(3, fish=None) 490 mock.something_else.something(6, cake=sentinel.Cake) 491 492 self.assertEqual(mock.something_else.method_calls, 493 [("something", (6,), {'cake': sentinel.Cake})], 494 "method calls not recorded correctly") 495 self.assertEqual(mock.method_calls, [ 496 ("something", (3,), {'fish': None}), 497 ("something_else.something", (6,), {'cake': sentinel.Cake}) 498 ], 499 "method calls not recorded correctly") 500 501 502 def test_method_calls_compare_easily(self): 503 mock = Mock() 504 mock.something() 505 self.assertEqual(mock.method_calls, [('something',)]) 506 self.assertEqual(mock.method_calls, [('something', (), {})]) 507 508 mock = Mock() 509 mock.something('different') 510 self.assertEqual(mock.method_calls, [('something', ('different',))]) 511 self.assertEqual(mock.method_calls, 512 [('something', ('different',), {})]) 513 514 mock = Mock() 515 mock.something(x=1) 516 self.assertEqual(mock.method_calls, [('something', {'x': 1})]) 517 self.assertEqual(mock.method_calls, [('something', (), {'x': 1})]) 518 519 mock = Mock() 520 mock.something('different', some='more') 521 self.assertEqual(mock.method_calls, [ 522 ('something', ('different',), {'some': 'more'}) 523 ]) 524 525 526 def test_only_allowed_methods_exist(self): 527 for spec in ['something'], ('something',): 528 for arg in 'spec', 'spec_set': 529 mock = Mock(**{arg: spec}) 530 531 # this should be allowed 532 mock.something 533 self.assertRaisesRegex( 534 AttributeError, 535 "Mock object has no attribute 'something_else'", 536 getattr, mock, 'something_else' 537 ) 538 539 540 def test_from_spec(self): 541 class Something(object): 542 x = 3 543 __something__ = None 544 def y(self): pass 545 546 def test_attributes(mock): 547 # should work 548 mock.x 549 mock.y 550 mock.__something__ 551 self.assertRaisesRegex( 552 AttributeError, 553 "Mock object has no attribute 'z'", 554 getattr, mock, 'z' 555 ) 556 self.assertRaisesRegex( 557 AttributeError, 558 "Mock object has no attribute '__foobar__'", 559 getattr, mock, '__foobar__' 560 ) 561 562 test_attributes(Mock(spec=Something)) 563 test_attributes(Mock(spec=Something())) 564 565 566 def test_wraps_calls(self): 567 real = Mock() 568 569 mock = Mock(wraps=real) 570 self.assertEqual(mock(), real()) 571 572 real.reset_mock() 573 574 mock(1, 2, fish=3) 575 real.assert_called_with(1, 2, fish=3) 576 577 578 def test_wraps_prevents_automatic_creation_of_mocks(self): 579 class Real(object): 580 pass 581 582 real = Real() 583 mock = Mock(wraps=real) 584 585 self.assertRaises(AttributeError, lambda: mock.new_attr()) 586 587 588 def test_wraps_call_with_nondefault_return_value(self): 589 real = Mock() 590 591 mock = Mock(wraps=real) 592 mock.return_value = 3 593 594 self.assertEqual(mock(), 3) 595 self.assertFalse(real.called) 596 597 598 def test_wraps_attributes(self): 599 class Real(object): 600 attribute = Mock() 601 602 real = Real() 603 604 mock = Mock(wraps=real) 605 self.assertEqual(mock.attribute(), real.attribute()) 606 self.assertRaises(AttributeError, lambda: mock.fish) 607 608 self.assertNotEqual(mock.attribute, real.attribute) 609 result = mock.attribute.frog(1, 2, fish=3) 610 Real.attribute.frog.assert_called_with(1, 2, fish=3) 611 self.assertEqual(result, Real.attribute.frog()) 612 613 614 def test_customize_wrapped_object_with_side_effect_iterable_with_default(self): 615 class Real(object): 616 def method(self): 617 return sentinel.ORIGINAL_VALUE 618 619 real = Real() 620 mock = Mock(wraps=real) 621 mock.method.side_effect = [sentinel.VALUE1, DEFAULT] 622 623 self.assertEqual(mock.method(), sentinel.VALUE1) 624 self.assertEqual(mock.method(), sentinel.ORIGINAL_VALUE) 625 self.assertRaises(StopIteration, mock.method) 626 627 628 def test_customize_wrapped_object_with_side_effect_iterable(self): 629 class Real(object): 630 def method(self): pass 631 632 real = Real() 633 mock = Mock(wraps=real) 634 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2] 635 636 self.assertEqual(mock.method(), sentinel.VALUE1) 637 self.assertEqual(mock.method(), sentinel.VALUE2) 638 self.assertRaises(StopIteration, mock.method) 639 640 641 def test_customize_wrapped_object_with_side_effect_exception(self): 642 class Real(object): 643 def method(self): pass 644 645 real = Real() 646 mock = Mock(wraps=real) 647 mock.method.side_effect = RuntimeError 648 649 self.assertRaises(RuntimeError, mock.method) 650 651 652 def test_customize_wrapped_object_with_side_effect_function(self): 653 class Real(object): 654 def method(self): pass 655 def side_effect(): 656 return sentinel.VALUE 657 658 real = Real() 659 mock = Mock(wraps=real) 660 mock.method.side_effect = side_effect 661 662 self.assertEqual(mock.method(), sentinel.VALUE) 663 664 665 def test_customize_wrapped_object_with_return_value(self): 666 class Real(object): 667 def method(self): pass 668 669 real = Real() 670 mock = Mock(wraps=real) 671 mock.method.return_value = sentinel.VALUE 672 673 self.assertEqual(mock.method(), sentinel.VALUE) 674 675 676 def test_customize_wrapped_object_with_return_value_and_side_effect(self): 677 # side_effect should always take precedence over return_value. 678 class Real(object): 679 def method(self): pass 680 681 real = Real() 682 mock = Mock(wraps=real) 683 mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2] 684 mock.method.return_value = sentinel.WRONG_VALUE 685 686 self.assertEqual(mock.method(), sentinel.VALUE1) 687 self.assertEqual(mock.method(), sentinel.VALUE2) 688 self.assertRaises(StopIteration, mock.method) 689 690 691 def test_customize_wrapped_object_with_return_value_and_side_effect2(self): 692 # side_effect can return DEFAULT to default to return_value 693 class Real(object): 694 def method(self): pass 695 696 real = Real() 697 mock = Mock(wraps=real) 698 mock.method.side_effect = lambda: DEFAULT 699 mock.method.return_value = sentinel.VALUE 700 701 self.assertEqual(mock.method(), sentinel.VALUE) 702 703 704 def test_customize_wrapped_object_with_return_value_and_side_effect_default(self): 705 class Real(object): 706 def method(self): pass 707 708 real = Real() 709 mock = Mock(wraps=real) 710 mock.method.side_effect = [sentinel.VALUE1, DEFAULT] 711 mock.method.return_value = sentinel.RETURN 712 713 self.assertEqual(mock.method(), sentinel.VALUE1) 714 self.assertEqual(mock.method(), sentinel.RETURN) 715 self.assertRaises(StopIteration, mock.method) 716 717 718 def test_magic_method_wraps_dict(self): 719 # bpo-25597: MagicMock with wrap doesn't call wrapped object's 720 # method for magic methods with default values. 721 data = {'foo': 'bar'} 722 723 wrapped_dict = MagicMock(wraps=data) 724 self.assertEqual(wrapped_dict.get('foo'), 'bar') 725 # Accessing key gives a MagicMock 726 self.assertIsInstance(wrapped_dict['foo'], MagicMock) 727 # __contains__ method has a default value of False 728 self.assertFalse('foo' in wrapped_dict) 729 730 # return_value is non-sentinel and takes precedence over wrapped value. 731 wrapped_dict.get.return_value = 'return_value' 732 self.assertEqual(wrapped_dict.get('foo'), 'return_value') 733 734 # return_value is sentinel and hence wrapped value is returned. 735 wrapped_dict.get.return_value = sentinel.DEFAULT 736 self.assertEqual(wrapped_dict.get('foo'), 'bar') 737 738 self.assertEqual(wrapped_dict.get('baz'), None) 739 self.assertIsInstance(wrapped_dict['baz'], MagicMock) 740 self.assertFalse('bar' in wrapped_dict) 741 742 data['baz'] = 'spam' 743 self.assertEqual(wrapped_dict.get('baz'), 'spam') 744 self.assertIsInstance(wrapped_dict['baz'], MagicMock) 745 self.assertFalse('bar' in wrapped_dict) 746 747 del data['baz'] 748 self.assertEqual(wrapped_dict.get('baz'), None) 749 750 751 def test_magic_method_wraps_class(self): 752 753 class Foo: 754 755 def __getitem__(self, index): 756 return index 757 758 def __custom_method__(self): 759 return "foo" 760 761 762 klass = MagicMock(wraps=Foo) 763 obj = klass() 764 self.assertEqual(obj.__getitem__(2), 2) 765 self.assertEqual(obj[2], 2) 766 self.assertEqual(obj.__custom_method__(), "foo") 767 768 769 def test_exceptional_side_effect(self): 770 mock = Mock(side_effect=AttributeError) 771 self.assertRaises(AttributeError, mock) 772 773 mock = Mock(side_effect=AttributeError('foo')) 774 self.assertRaises(AttributeError, mock) 775 776 777 def test_baseexceptional_side_effect(self): 778 mock = Mock(side_effect=KeyboardInterrupt) 779 self.assertRaises(KeyboardInterrupt, mock) 780 781 mock = Mock(side_effect=KeyboardInterrupt('foo')) 782 self.assertRaises(KeyboardInterrupt, mock) 783 784 785 def test_assert_called_with_message(self): 786 mock = Mock() 787 self.assertRaisesRegex(AssertionError, 'not called', 788 mock.assert_called_with) 789 790 791 def test_assert_called_once_with_message(self): 792 mock = Mock(name='geoffrey') 793 self.assertRaisesRegex(AssertionError, 794 r"Expected 'geoffrey' to be called once\.", 795 mock.assert_called_once_with) 796 797 798 def test__name__(self): 799 mock = Mock() 800 self.assertRaises(AttributeError, lambda: mock.__name__) 801 802 mock.__name__ = 'foo' 803 self.assertEqual(mock.__name__, 'foo') 804 805 806 def test_spec_list_subclass(self): 807 class Sub(list): 808 pass 809 mock = Mock(spec=Sub(['foo'])) 810 811 mock.append(3) 812 mock.append.assert_called_with(3) 813 self.assertRaises(AttributeError, getattr, mock, 'foo') 814 815 816 def test_spec_class(self): 817 class X(object): 818 pass 819 820 mock = Mock(spec=X) 821 self.assertIsInstance(mock, X) 822 823 mock = Mock(spec=X()) 824 self.assertIsInstance(mock, X) 825 826 self.assertIs(mock.__class__, X) 827 self.assertEqual(Mock().__class__.__name__, 'Mock') 828 829 mock = Mock(spec_set=X) 830 self.assertIsInstance(mock, X) 831 832 mock = Mock(spec_set=X()) 833 self.assertIsInstance(mock, X) 834 835 836 def test_spec_class_no_object_base(self): 837 class X: 838 pass 839 840 mock = Mock(spec=X) 841 self.assertIsInstance(mock, X) 842 843 mock = Mock(spec=X()) 844 self.assertIsInstance(mock, X) 845 846 self.assertIs(mock.__class__, X) 847 self.assertEqual(Mock().__class__.__name__, 'Mock') 848 849 mock = Mock(spec_set=X) 850 self.assertIsInstance(mock, X) 851 852 mock = Mock(spec_set=X()) 853 self.assertIsInstance(mock, X) 854 855 856 def test_setting_attribute_with_spec_set(self): 857 class X(object): 858 y = 3 859 860 mock = Mock(spec=X) 861 mock.x = 'foo' 862 863 mock = Mock(spec_set=X) 864 def set_attr(): 865 mock.x = 'foo' 866 867 mock.y = 'foo' 868 self.assertRaises(AttributeError, set_attr) 869 870 871 def test_copy(self): 872 current = sys.getrecursionlimit() 873 self.addCleanup(sys.setrecursionlimit, current) 874 875 # can't use sys.maxint as this doesn't exist in Python 3 876 sys.setrecursionlimit(int(10e8)) 877 # this segfaults without the fix in place 878 copy.copy(Mock()) 879 880 881 def test_subclass_with_properties(self): 882 class SubClass(Mock): 883 def _get(self): 884 return 3 885 def _set(self, value): 886 raise NameError('strange error') 887 some_attribute = property(_get, _set) 888 889 s = SubClass(spec_set=SubClass) 890 self.assertEqual(s.some_attribute, 3) 891 892 def test(): 893 s.some_attribute = 3 894 self.assertRaises(NameError, test) 895 896 def test(): 897 s.foo = 'bar' 898 self.assertRaises(AttributeError, test) 899 900 901 def test_setting_call(self): 902 mock = Mock() 903 def __call__(self, a): 904 self._increment_mock_call(a) 905 return self._mock_call(a) 906 907 type(mock).__call__ = __call__ 908 mock('one') 909 mock.assert_called_with('one') 910 911 self.assertRaises(TypeError, mock, 'one', 'two') 912 913 914 def test_dir(self): 915 mock = Mock() 916 attrs = set(dir(mock)) 917 type_attrs = set([m for m in dir(Mock) if not m.startswith('_')]) 918 919 # all public attributes from the type are included 920 self.assertEqual(set(), type_attrs - attrs) 921 922 # creates these attributes 923 mock.a, mock.b 924 self.assertIn('a', dir(mock)) 925 self.assertIn('b', dir(mock)) 926 927 # instance attributes 928 mock.c = mock.d = None 929 self.assertIn('c', dir(mock)) 930 self.assertIn('d', dir(mock)) 931 932 # magic methods 933 mock.__iter__ = lambda s: iter([]) 934 self.assertIn('__iter__', dir(mock)) 935 936 937 def test_dir_from_spec(self): 938 mock = Mock(spec=unittest.TestCase) 939 testcase_attrs = set(dir(unittest.TestCase)) 940 attrs = set(dir(mock)) 941 942 # all attributes from the spec are included 943 self.assertEqual(set(), testcase_attrs - attrs) 944 945 # shadow a sys attribute 946 mock.version = 3 947 self.assertEqual(dir(mock).count('version'), 1) 948 949 950 def test_filter_dir(self): 951 patcher = patch.object(mock, 'FILTER_DIR', False) 952 patcher.start() 953 try: 954 attrs = set(dir(Mock())) 955 type_attrs = set(dir(Mock)) 956 957 # ALL attributes from the type are included 958 self.assertEqual(set(), type_attrs - attrs) 959 finally: 960 patcher.stop() 961 962 963 def test_dir_does_not_include_deleted_attributes(self): 964 mock = Mock() 965 mock.child.return_value = 1 966 967 self.assertIn('child', dir(mock)) 968 del mock.child 969 self.assertNotIn('child', dir(mock)) 970 971 972 def test_configure_mock(self): 973 mock = Mock(foo='bar') 974 self.assertEqual(mock.foo, 'bar') 975 976 mock = MagicMock(foo='bar') 977 self.assertEqual(mock.foo, 'bar') 978 979 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33, 980 'foo': MagicMock()} 981 mock = Mock(**kwargs) 982 self.assertRaises(KeyError, mock) 983 self.assertEqual(mock.foo.bar(), 33) 984 self.assertIsInstance(mock.foo, MagicMock) 985 986 mock = Mock() 987 mock.configure_mock(**kwargs) 988 self.assertRaises(KeyError, mock) 989 self.assertEqual(mock.foo.bar(), 33) 990 self.assertIsInstance(mock.foo, MagicMock) 991 992 993 def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs): 994 # needed because assertRaisesRegex doesn't work easily with newlines 995 with self.assertRaises(exception) as context: 996 func(*args, **kwargs) 997 msg = str(context.exception) 998 self.assertEqual(msg, message) 999 1000 1001 def test_assert_called_with_failure_message(self): 1002 mock = NonCallableMock() 1003 1004 actual = 'not called.' 1005 expected = "mock(1, '2', 3, bar='foo')" 1006 message = 'expected call not found.\nExpected: %s\nActual: %s' 1007 self.assertRaisesWithMsg( 1008 AssertionError, message % (expected, actual), 1009 mock.assert_called_with, 1, '2', 3, bar='foo' 1010 ) 1011 1012 mock.foo(1, '2', 3, foo='foo') 1013 1014 1015 asserters = [ 1016 mock.foo.assert_called_with, mock.foo.assert_called_once_with 1017 ] 1018 for meth in asserters: 1019 actual = "foo(1, '2', 3, foo='foo')" 1020 expected = "foo(1, '2', 3, bar='foo')" 1021 message = 'expected call not found.\nExpected: %s\nActual: %s' 1022 self.assertRaisesWithMsg( 1023 AssertionError, message % (expected, actual), 1024 meth, 1, '2', 3, bar='foo' 1025 ) 1026 1027 # just kwargs 1028 for meth in asserters: 1029 actual = "foo(1, '2', 3, foo='foo')" 1030 expected = "foo(bar='foo')" 1031 message = 'expected call not found.\nExpected: %s\nActual: %s' 1032 self.assertRaisesWithMsg( 1033 AssertionError, message % (expected, actual), 1034 meth, bar='foo' 1035 ) 1036 1037 # just args 1038 for meth in asserters: 1039 actual = "foo(1, '2', 3, foo='foo')" 1040 expected = "foo(1, 2, 3)" 1041 message = 'expected call not found.\nExpected: %s\nActual: %s' 1042 self.assertRaisesWithMsg( 1043 AssertionError, message % (expected, actual), 1044 meth, 1, 2, 3 1045 ) 1046 1047 # empty 1048 for meth in asserters: 1049 actual = "foo(1, '2', 3, foo='foo')" 1050 expected = "foo()" 1051 message = 'expected call not found.\nExpected: %s\nActual: %s' 1052 self.assertRaisesWithMsg( 1053 AssertionError, message % (expected, actual), meth 1054 ) 1055 1056 1057 def test_mock_calls(self): 1058 mock = MagicMock() 1059 1060 # need to do this because MagicMock.mock_calls used to just return 1061 # a MagicMock which also returned a MagicMock when __eq__ was called 1062 self.assertIs(mock.mock_calls == [], True) 1063 1064 mock = MagicMock() 1065 mock() 1066 expected = [('', (), {})] 1067 self.assertEqual(mock.mock_calls, expected) 1068 1069 mock.foo() 1070 expected.append(call.foo()) 1071 self.assertEqual(mock.mock_calls, expected) 1072 # intermediate mock_calls work too 1073 self.assertEqual(mock.foo.mock_calls, [('', (), {})]) 1074 1075 mock = MagicMock() 1076 mock().foo(1, 2, 3, a=4, b=5) 1077 expected = [ 1078 ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5)) 1079 ] 1080 self.assertEqual(mock.mock_calls, expected) 1081 self.assertEqual(mock.return_value.foo.mock_calls, 1082 [('', (1, 2, 3), dict(a=4, b=5))]) 1083 self.assertEqual(mock.return_value.mock_calls, 1084 [('foo', (1, 2, 3), dict(a=4, b=5))]) 1085 1086 mock = MagicMock() 1087 mock().foo.bar().baz() 1088 expected = [ 1089 ('', (), {}), ('().foo.bar', (), {}), 1090 ('().foo.bar().baz', (), {}) 1091 ] 1092 self.assertEqual(mock.mock_calls, expected) 1093 self.assertEqual(mock().mock_calls, 1094 call.foo.bar().baz().call_list()) 1095 1096 for kwargs in dict(), dict(name='bar'): 1097 mock = MagicMock(**kwargs) 1098 int(mock.foo) 1099 expected = [('foo.__int__', (), {})] 1100 self.assertEqual(mock.mock_calls, expected) 1101 1102 mock = MagicMock(**kwargs) 1103 mock.a()() 1104 expected = [('a', (), {}), ('a()', (), {})] 1105 self.assertEqual(mock.mock_calls, expected) 1106 self.assertEqual(mock.a().mock_calls, [call()]) 1107 1108 mock = MagicMock(**kwargs) 1109 mock(1)(2)(3) 1110 self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list()) 1111 self.assertEqual(mock().mock_calls, call(2)(3).call_list()) 1112 self.assertEqual(mock()().mock_calls, call(3).call_list()) 1113 1114 mock = MagicMock(**kwargs) 1115 mock(1)(2)(3).a.b.c(4) 1116 self.assertEqual(mock.mock_calls, 1117 call(1)(2)(3).a.b.c(4).call_list()) 1118 self.assertEqual(mock().mock_calls, 1119 call(2)(3).a.b.c(4).call_list()) 1120 self.assertEqual(mock()().mock_calls, 1121 call(3).a.b.c(4).call_list()) 1122 1123 mock = MagicMock(**kwargs) 1124 int(mock().foo.bar().baz()) 1125 last_call = ('().foo.bar().baz().__int__', (), {}) 1126 self.assertEqual(mock.mock_calls[-1], last_call) 1127 self.assertEqual(mock().mock_calls, 1128 call.foo.bar().baz().__int__().call_list()) 1129 self.assertEqual(mock().foo.bar().mock_calls, 1130 call.baz().__int__().call_list()) 1131 self.assertEqual(mock().foo.bar().baz.mock_calls, 1132 call().__int__().call_list()) 1133 1134 1135 def test_child_mock_call_equal(self): 1136 m = Mock() 1137 result = m() 1138 result.wibble() 1139 # parent looks like this: 1140 self.assertEqual(m.mock_calls, [call(), call().wibble()]) 1141 # but child should look like this: 1142 self.assertEqual(result.mock_calls, [call.wibble()]) 1143 1144 1145 def test_mock_call_not_equal_leaf(self): 1146 m = Mock() 1147 m.foo().something() 1148 self.assertNotEqual(m.mock_calls[1], call.foo().different()) 1149 self.assertEqual(m.mock_calls[0], call.foo()) 1150 1151 1152 def test_mock_call_not_equal_non_leaf(self): 1153 m = Mock() 1154 m.foo().bar() 1155 self.assertNotEqual(m.mock_calls[1], call.baz().bar()) 1156 self.assertNotEqual(m.mock_calls[0], call.baz()) 1157 1158 1159 def test_mock_call_not_equal_non_leaf_params_different(self): 1160 m = Mock() 1161 m.foo(x=1).bar() 1162 # This isn't ideal, but there's no way to fix it without breaking backwards compatibility: 1163 self.assertEqual(m.mock_calls[1], call.foo(x=2).bar()) 1164 1165 1166 def test_mock_call_not_equal_non_leaf_attr(self): 1167 m = Mock() 1168 m.foo.bar() 1169 self.assertNotEqual(m.mock_calls[0], call.baz.bar()) 1170 1171 1172 def test_mock_call_not_equal_non_leaf_call_versus_attr(self): 1173 m = Mock() 1174 m.foo.bar() 1175 self.assertNotEqual(m.mock_calls[0], call.foo().bar()) 1176 1177 1178 def test_mock_call_repr(self): 1179 m = Mock() 1180 m.foo().bar().baz.bob() 1181 self.assertEqual(repr(m.mock_calls[0]), 'call.foo()') 1182 self.assertEqual(repr(m.mock_calls[1]), 'call.foo().bar()') 1183 self.assertEqual(repr(m.mock_calls[2]), 'call.foo().bar().baz.bob()') 1184 1185 1186 def test_mock_call_repr_loop(self): 1187 m = Mock() 1188 m.foo = m 1189 repr(m.foo()) 1190 self.assertRegex(repr(m.foo()), r"<Mock name='mock\(\)' id='\d+'>") 1191 1192 1193 def test_mock_calls_contains(self): 1194 m = Mock() 1195 self.assertFalse([call()] in m.mock_calls) 1196 1197 1198 def test_subclassing(self): 1199 class Subclass(Mock): 1200 pass 1201 1202 mock = Subclass() 1203 self.assertIsInstance(mock.foo, Subclass) 1204 self.assertIsInstance(mock(), Subclass) 1205 1206 class Subclass(Mock): 1207 def _get_child_mock(self, **kwargs): 1208 return Mock(**kwargs) 1209 1210 mock = Subclass() 1211 self.assertNotIsInstance(mock.foo, Subclass) 1212 self.assertNotIsInstance(mock(), Subclass) 1213 1214 1215 def test_arg_lists(self): 1216 mocks = [ 1217 Mock(), 1218 MagicMock(), 1219 NonCallableMock(), 1220 NonCallableMagicMock() 1221 ] 1222 1223 def assert_attrs(mock): 1224 names = 'call_args_list', 'method_calls', 'mock_calls' 1225 for name in names: 1226 attr = getattr(mock, name) 1227 self.assertIsInstance(attr, _CallList) 1228 self.assertIsInstance(attr, list) 1229 self.assertEqual(attr, []) 1230 1231 for mock in mocks: 1232 assert_attrs(mock) 1233 1234 if callable(mock): 1235 mock() 1236 mock(1, 2) 1237 mock(a=3) 1238 1239 mock.reset_mock() 1240 assert_attrs(mock) 1241 1242 mock.foo() 1243 mock.foo.bar(1, a=3) 1244 mock.foo(1).bar().baz(3) 1245 1246 mock.reset_mock() 1247 assert_attrs(mock) 1248 1249 1250 def test_call_args_two_tuple(self): 1251 mock = Mock() 1252 mock(1, a=3) 1253 mock(2, b=4) 1254 1255 self.assertEqual(len(mock.call_args), 2) 1256 self.assertEqual(mock.call_args.args, (2,)) 1257 self.assertEqual(mock.call_args.kwargs, dict(b=4)) 1258 1259 expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))] 1260 for expected, call_args in zip(expected_list, mock.call_args_list): 1261 self.assertEqual(len(call_args), 2) 1262 self.assertEqual(expected[0], call_args[0]) 1263 self.assertEqual(expected[1], call_args[1]) 1264 1265 1266 def test_side_effect_iterator(self): 1267 mock = Mock(side_effect=iter([1, 2, 3])) 1268 self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) 1269 self.assertRaises(StopIteration, mock) 1270 1271 mock = MagicMock(side_effect=['a', 'b', 'c']) 1272 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) 1273 self.assertRaises(StopIteration, mock) 1274 1275 mock = Mock(side_effect='ghi') 1276 self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i']) 1277 self.assertRaises(StopIteration, mock) 1278 1279 class Foo(object): 1280 pass 1281 mock = MagicMock(side_effect=Foo) 1282 self.assertIsInstance(mock(), Foo) 1283 1284 mock = Mock(side_effect=Iter()) 1285 self.assertEqual([mock(), mock(), mock(), mock()], 1286 ['this', 'is', 'an', 'iter']) 1287 self.assertRaises(StopIteration, mock) 1288 1289 1290 def test_side_effect_iterator_exceptions(self): 1291 for Klass in Mock, MagicMock: 1292 iterable = (ValueError, 3, KeyError, 6) 1293 m = Klass(side_effect=iterable) 1294 self.assertRaises(ValueError, m) 1295 self.assertEqual(m(), 3) 1296 self.assertRaises(KeyError, m) 1297 self.assertEqual(m(), 6) 1298 1299 1300 def test_side_effect_setting_iterator(self): 1301 mock = Mock() 1302 mock.side_effect = iter([1, 2, 3]) 1303 self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) 1304 self.assertRaises(StopIteration, mock) 1305 side_effect = mock.side_effect 1306 self.assertIsInstance(side_effect, type(iter([]))) 1307 1308 mock.side_effect = ['a', 'b', 'c'] 1309 self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) 1310 self.assertRaises(StopIteration, mock) 1311 side_effect = mock.side_effect 1312 self.assertIsInstance(side_effect, type(iter([]))) 1313 1314 this_iter = Iter() 1315 mock.side_effect = this_iter 1316 self.assertEqual([mock(), mock(), mock(), mock()], 1317 ['this', 'is', 'an', 'iter']) 1318 self.assertRaises(StopIteration, mock) 1319 self.assertIs(mock.side_effect, this_iter) 1320 1321 def test_side_effect_iterator_default(self): 1322 mock = Mock(return_value=2) 1323 mock.side_effect = iter([1, DEFAULT]) 1324 self.assertEqual([mock(), mock()], [1, 2]) 1325 1326 def test_assert_has_calls_any_order(self): 1327 mock = Mock() 1328 mock(1, 2) 1329 mock(a=3) 1330 mock(3, 4) 1331 mock(b=6) 1332 mock(b=6) 1333 1334 kalls = [ 1335 call(1, 2), ({'a': 3},), 1336 ((3, 4),), ((), {'a': 3}), 1337 ('', (1, 2)), ('', {'a': 3}), 1338 ('', (1, 2), {}), ('', (), {'a': 3}) 1339 ] 1340 for kall in kalls: 1341 mock.assert_has_calls([kall], any_order=True) 1342 1343 for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo': 1344 self.assertRaises( 1345 AssertionError, mock.assert_has_calls, 1346 [kall], any_order=True 1347 ) 1348 1349 kall_lists = [ 1350 [call(1, 2), call(b=6)], 1351 [call(3, 4), call(1, 2)], 1352 [call(b=6), call(b=6)], 1353 ] 1354 1355 for kall_list in kall_lists: 1356 mock.assert_has_calls(kall_list, any_order=True) 1357 1358 kall_lists = [ 1359 [call(b=6), call(b=6), call(b=6)], 1360 [call(1, 2), call(1, 2)], 1361 [call(3, 4), call(1, 2), call(5, 7)], 1362 [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)], 1363 ] 1364 for kall_list in kall_lists: 1365 self.assertRaises( 1366 AssertionError, mock.assert_has_calls, 1367 kall_list, any_order=True 1368 ) 1369 1370 def test_assert_has_calls(self): 1371 kalls1 = [ 1372 call(1, 2), ({'a': 3},), 1373 ((3, 4),), call(b=6), 1374 ('', (1,), {'b': 6}), 1375 ] 1376 kalls2 = [call.foo(), call.bar(1)] 1377 kalls2.extend(call.spam().baz(a=3).call_list()) 1378 kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list()) 1379 1380 mocks = [] 1381 for mock in Mock(), MagicMock(): 1382 mock(1, 2) 1383 mock(a=3) 1384 mock(3, 4) 1385 mock(b=6) 1386 mock(1, b=6) 1387 mocks.append((mock, kalls1)) 1388 1389 mock = Mock() 1390 mock.foo() 1391 mock.bar(1) 1392 mock.spam().baz(a=3) 1393 mock.bam(set(), foo={}).fish([1]) 1394 mocks.append((mock, kalls2)) 1395 1396 for mock, kalls in mocks: 1397 for i in range(len(kalls)): 1398 for step in 1, 2, 3: 1399 these = kalls[i:i+step] 1400 mock.assert_has_calls(these) 1401 1402 if len(these) > 1: 1403 self.assertRaises( 1404 AssertionError, 1405 mock.assert_has_calls, 1406 list(reversed(these)) 1407 ) 1408 1409 1410 def test_assert_has_calls_nested_spec(self): 1411 class Something: 1412 1413 def __init__(self): pass 1414 def meth(self, a, b, c, d=None): pass 1415 1416 class Foo: 1417 1418 def __init__(self, a): pass 1419 def meth1(self, a, b): pass 1420 1421 mock_class = create_autospec(Something) 1422 1423 for m in [mock_class, mock_class()]: 1424 m.meth(1, 2, 3, d=1) 1425 m.assert_has_calls([call.meth(1, 2, 3, d=1)]) 1426 m.assert_has_calls([call.meth(1, 2, 3, 1)]) 1427 1428 mock_class.reset_mock() 1429 1430 for m in [mock_class, mock_class()]: 1431 self.assertRaises(AssertionError, m.assert_has_calls, [call.Foo()]) 1432 m.Foo(1).meth1(1, 2) 1433 m.assert_has_calls([call.Foo(1), call.Foo(1).meth1(1, 2)]) 1434 m.Foo.assert_has_calls([call(1), call().meth1(1, 2)]) 1435 1436 mock_class.reset_mock() 1437 1438 invalid_calls = [call.meth(1), 1439 call.non_existent(1), 1440 call.Foo().non_existent(1), 1441 call.Foo().meth(1, 2, 3, 4)] 1442 1443 for kall in invalid_calls: 1444 self.assertRaises(AssertionError, 1445 mock_class.assert_has_calls, 1446 [kall] 1447 ) 1448 1449 1450 def test_assert_has_calls_nested_without_spec(self): 1451 m = MagicMock() 1452 m().foo().bar().baz() 1453 m.one().two().three() 1454 calls = call.one().two().three().call_list() 1455 m.assert_has_calls(calls) 1456 1457 1458 def test_assert_has_calls_with_function_spec(self): 1459 def f(a, b, c, d=None): pass 1460 1461 mock = Mock(spec=f) 1462 1463 mock(1, b=2, c=3) 1464 mock(4, 5, c=6, d=7) 1465 mock(10, 11, c=12) 1466 calls = [ 1467 ('', (1, 2, 3), {}), 1468 ('', (4, 5, 6), {'d': 7}), 1469 ((10, 11, 12), {}), 1470 ] 1471 mock.assert_has_calls(calls) 1472 mock.assert_has_calls(calls, any_order=True) 1473 mock.assert_has_calls(calls[1:]) 1474 mock.assert_has_calls(calls[1:], any_order=True) 1475 mock.assert_has_calls(calls[:-1]) 1476 mock.assert_has_calls(calls[:-1], any_order=True) 1477 # Reversed order 1478 calls = list(reversed(calls)) 1479 with self.assertRaises(AssertionError): 1480 mock.assert_has_calls(calls) 1481 mock.assert_has_calls(calls, any_order=True) 1482 with self.assertRaises(AssertionError): 1483 mock.assert_has_calls(calls[1:]) 1484 mock.assert_has_calls(calls[1:], any_order=True) 1485 with self.assertRaises(AssertionError): 1486 mock.assert_has_calls(calls[:-1]) 1487 mock.assert_has_calls(calls[:-1], any_order=True) 1488 1489 def test_assert_has_calls_not_matching_spec_error(self): 1490 def f(x=None): pass 1491 1492 mock = Mock(spec=f) 1493 mock(1) 1494 1495 with self.assertRaisesRegex( 1496 AssertionError, 1497 '^{}$'.format( 1498 re.escape('Calls not found.\n' 1499 'Expected: [call()]\n' 1500 'Actual: [call(1)]'))) as cm: 1501 mock.assert_has_calls([call()]) 1502 self.assertIsNone(cm.exception.__cause__) 1503 1504 1505 with self.assertRaisesRegex( 1506 AssertionError, 1507 '^{}$'.format( 1508 re.escape( 1509 'Error processing expected calls.\n' 1510 "Errors: [None, TypeError('too many positional arguments')]\n" 1511 "Expected: [call(), call(1, 2)]\n" 1512 'Actual: [call(1)]'))) as cm: 1513 mock.assert_has_calls([call(), call(1, 2)]) 1514 self.assertIsInstance(cm.exception.__cause__, TypeError) 1515 1516 def test_assert_any_call(self): 1517 mock = Mock() 1518 mock(1, 2) 1519 mock(a=3) 1520 mock(1, b=6) 1521 1522 mock.assert_any_call(1, 2) 1523 mock.assert_any_call(a=3) 1524 mock.assert_any_call(1, b=6) 1525 1526 self.assertRaises( 1527 AssertionError, 1528 mock.assert_any_call 1529 ) 1530 self.assertRaises( 1531 AssertionError, 1532 mock.assert_any_call, 1533 1, 3 1534 ) 1535 self.assertRaises( 1536 AssertionError, 1537 mock.assert_any_call, 1538 a=4 1539 ) 1540 1541 1542 def test_assert_any_call_with_function_spec(self): 1543 def f(a, b, c, d=None): pass 1544 1545 mock = Mock(spec=f) 1546 1547 mock(1, b=2, c=3) 1548 mock(4, 5, c=6, d=7) 1549 mock.assert_any_call(1, 2, 3) 1550 mock.assert_any_call(a=1, b=2, c=3) 1551 mock.assert_any_call(4, 5, 6, 7) 1552 mock.assert_any_call(a=4, b=5, c=6, d=7) 1553 self.assertRaises(AssertionError, mock.assert_any_call, 1554 1, b=3, c=2) 1555 # Expected call doesn't match the spec's signature 1556 with self.assertRaises(AssertionError) as cm: 1557 mock.assert_any_call(e=8) 1558 self.assertIsInstance(cm.exception.__cause__, TypeError) 1559 1560 1561 def test_mock_calls_create_autospec(self): 1562 def f(a, b): pass 1563 obj = Iter() 1564 obj.f = f 1565 1566 funcs = [ 1567 create_autospec(f), 1568 create_autospec(obj).f 1569 ] 1570 for func in funcs: 1571 func(1, 2) 1572 func(3, 4) 1573 1574 self.assertEqual( 1575 func.mock_calls, [call(1, 2), call(3, 4)] 1576 ) 1577 1578 #Issue21222 1579 def test_create_autospec_with_name(self): 1580 m = mock.create_autospec(object(), name='sweet_func') 1581 self.assertIn('sweet_func', repr(m)) 1582 1583 #Issue23078 1584 def test_create_autospec_classmethod_and_staticmethod(self): 1585 class TestClass: 1586 @classmethod 1587 def class_method(cls): pass 1588 1589 @staticmethod 1590 def static_method(): pass 1591 for method in ('class_method', 'static_method'): 1592 with self.subTest(method=method): 1593 mock_method = mock.create_autospec(getattr(TestClass, method)) 1594 mock_method() 1595 mock_method.assert_called_once_with() 1596 self.assertRaises(TypeError, mock_method, 'extra_arg') 1597 1598 #Issue21238 1599 def test_mock_unsafe(self): 1600 m = Mock() 1601 msg = "Attributes cannot start with 'assert' or 'assret'" 1602 with self.assertRaisesRegex(AttributeError, msg): 1603 m.assert_foo_call() 1604 with self.assertRaisesRegex(AttributeError, msg): 1605 m.assret_foo_call() 1606 m = Mock(unsafe=True) 1607 m.assert_foo_call() 1608 m.assret_foo_call() 1609 1610 #Issue21262 1611 def test_assert_not_called(self): 1612 m = Mock() 1613 m.hello.assert_not_called() 1614 m.hello() 1615 with self.assertRaises(AssertionError): 1616 m.hello.assert_not_called() 1617 1618 def test_assert_not_called_message(self): 1619 m = Mock() 1620 m(1, 2) 1621 self.assertRaisesRegex(AssertionError, 1622 re.escape("Calls: [call(1, 2)]"), 1623 m.assert_not_called) 1624 1625 def test_assert_called(self): 1626 m = Mock() 1627 with self.assertRaises(AssertionError): 1628 m.hello.assert_called() 1629 m.hello() 1630 m.hello.assert_called() 1631 1632 m.hello() 1633 m.hello.assert_called() 1634 1635 def test_assert_called_once(self): 1636 m = Mock() 1637 with self.assertRaises(AssertionError): 1638 m.hello.assert_called_once() 1639 m.hello() 1640 m.hello.assert_called_once() 1641 1642 m.hello() 1643 with self.assertRaises(AssertionError): 1644 m.hello.assert_called_once() 1645 1646 def test_assert_called_once_message(self): 1647 m = Mock() 1648 m(1, 2) 1649 m(3) 1650 self.assertRaisesRegex(AssertionError, 1651 re.escape("Calls: [call(1, 2), call(3)]"), 1652 m.assert_called_once) 1653 1654 def test_assert_called_once_message_not_called(self): 1655 m = Mock() 1656 with self.assertRaises(AssertionError) as e: 1657 m.assert_called_once() 1658 self.assertNotIn("Calls:", str(e.exception)) 1659 1660 #Issue37212 printout of keyword args now preserves the original order 1661 def test_ordered_call_signature(self): 1662 m = Mock() 1663 m.hello(name='hello', daddy='hero') 1664 text = "call(name='hello', daddy='hero')" 1665 self.assertEqual(repr(m.hello.call_args), text) 1666 1667 #Issue21270 overrides tuple methods for mock.call objects 1668 def test_override_tuple_methods(self): 1669 c = call.count() 1670 i = call.index(132,'hello') 1671 m = Mock() 1672 m.count() 1673 m.index(132,"hello") 1674 self.assertEqual(m.method_calls[0], c) 1675 self.assertEqual(m.method_calls[1], i) 1676 1677 def test_reset_return_sideeffect(self): 1678 m = Mock(return_value=10, side_effect=[2,3]) 1679 m.reset_mock(return_value=True, side_effect=True) 1680 self.assertIsInstance(m.return_value, Mock) 1681 self.assertEqual(m.side_effect, None) 1682 1683 def test_reset_return(self): 1684 m = Mock(return_value=10, side_effect=[2,3]) 1685 m.reset_mock(return_value=True) 1686 self.assertIsInstance(m.return_value, Mock) 1687 self.assertNotEqual(m.side_effect, None) 1688 1689 def test_reset_sideeffect(self): 1690 m = Mock(return_value=10, side_effect=[2, 3]) 1691 m.reset_mock(side_effect=True) 1692 self.assertEqual(m.return_value, 10) 1693 self.assertEqual(m.side_effect, None) 1694 1695 def test_reset_return_with_children(self): 1696 m = MagicMock(f=MagicMock(return_value=1)) 1697 self.assertEqual(m.f(), 1) 1698 m.reset_mock(return_value=True) 1699 self.assertNotEqual(m.f(), 1) 1700 1701 def test_reset_return_with_children_side_effect(self): 1702 m = MagicMock(f=MagicMock(side_effect=[2, 3])) 1703 self.assertNotEqual(m.f.side_effect, None) 1704 m.reset_mock(side_effect=True) 1705 self.assertEqual(m.f.side_effect, None) 1706 1707 def test_mock_add_spec(self): 1708 class _One(object): 1709 one = 1 1710 class _Two(object): 1711 two = 2 1712 class Anything(object): 1713 one = two = three = 'four' 1714 1715 klasses = [ 1716 Mock, MagicMock, NonCallableMock, NonCallableMagicMock 1717 ] 1718 for Klass in list(klasses): 1719 klasses.append(lambda K=Klass: K(spec=Anything)) 1720 klasses.append(lambda K=Klass: K(spec_set=Anything)) 1721 1722 for Klass in klasses: 1723 for kwargs in dict(), dict(spec_set=True): 1724 mock = Klass() 1725 #no error 1726 mock.one, mock.two, mock.three 1727 1728 for One, Two in [(_One, _Two), (['one'], ['two'])]: 1729 for kwargs in dict(), dict(spec_set=True): 1730 mock.mock_add_spec(One, **kwargs) 1731 1732 mock.one 1733 self.assertRaises( 1734 AttributeError, getattr, mock, 'two' 1735 ) 1736 self.assertRaises( 1737 AttributeError, getattr, mock, 'three' 1738 ) 1739 if 'spec_set' in kwargs: 1740 self.assertRaises( 1741 AttributeError, setattr, mock, 'three', None 1742 ) 1743 1744 mock.mock_add_spec(Two, **kwargs) 1745 self.assertRaises( 1746 AttributeError, getattr, mock, 'one' 1747 ) 1748 mock.two 1749 self.assertRaises( 1750 AttributeError, getattr, mock, 'three' 1751 ) 1752 if 'spec_set' in kwargs: 1753 self.assertRaises( 1754 AttributeError, setattr, mock, 'three', None 1755 ) 1756 # note that creating a mock, setting an instance attribute, and 1757 # *then* setting a spec doesn't work. Not the intended use case 1758 1759 1760 def test_mock_add_spec_magic_methods(self): 1761 for Klass in MagicMock, NonCallableMagicMock: 1762 mock = Klass() 1763 int(mock) 1764 1765 mock.mock_add_spec(object) 1766 self.assertRaises(TypeError, int, mock) 1767 1768 mock = Klass() 1769 mock['foo'] 1770 mock.__int__.return_value =4 1771 1772 mock.mock_add_spec(int) 1773 self.assertEqual(int(mock), 4) 1774 self.assertRaises(TypeError, lambda: mock['foo']) 1775 1776 1777 def test_adding_child_mock(self): 1778 for Klass in (NonCallableMock, Mock, MagicMock, NonCallableMagicMock, 1779 AsyncMock): 1780 mock = Klass() 1781 1782 mock.foo = Mock() 1783 mock.foo() 1784 1785 self.assertEqual(mock.method_calls, [call.foo()]) 1786 self.assertEqual(mock.mock_calls, [call.foo()]) 1787 1788 mock = Klass() 1789 mock.bar = Mock(name='name') 1790 mock.bar() 1791 self.assertEqual(mock.method_calls, []) 1792 self.assertEqual(mock.mock_calls, []) 1793 1794 # mock with an existing _new_parent but no name 1795 mock = Klass() 1796 mock.baz = MagicMock()() 1797 mock.baz() 1798 self.assertEqual(mock.method_calls, []) 1799 self.assertEqual(mock.mock_calls, []) 1800 1801 1802 def test_adding_return_value_mock(self): 1803 for Klass in Mock, MagicMock: 1804 mock = Klass() 1805 mock.return_value = MagicMock() 1806 1807 mock()() 1808 self.assertEqual(mock.mock_calls, [call(), call()()]) 1809 1810 1811 def test_manager_mock(self): 1812 class Foo(object): 1813 one = 'one' 1814 two = 'two' 1815 manager = Mock() 1816 p1 = patch.object(Foo, 'one') 1817 p2 = patch.object(Foo, 'two') 1818 1819 mock_one = p1.start() 1820 self.addCleanup(p1.stop) 1821 mock_two = p2.start() 1822 self.addCleanup(p2.stop) 1823 1824 manager.attach_mock(mock_one, 'one') 1825 manager.attach_mock(mock_two, 'two') 1826 1827 Foo.two() 1828 Foo.one() 1829 1830 self.assertEqual(manager.mock_calls, [call.two(), call.one()]) 1831 1832 1833 def test_magic_methods_mock_calls(self): 1834 for Klass in Mock, MagicMock: 1835 m = Klass() 1836 m.__int__ = Mock(return_value=3) 1837 m.__float__ = MagicMock(return_value=3.0) 1838 int(m) 1839 float(m) 1840 1841 self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()]) 1842 self.assertEqual(m.method_calls, []) 1843 1844 def test_mock_open_reuse_issue_21750(self): 1845 mocked_open = mock.mock_open(read_data='data') 1846 f1 = mocked_open('a-name') 1847 f1_data = f1.read() 1848 f2 = mocked_open('another-name') 1849 f2_data = f2.read() 1850 self.assertEqual(f1_data, f2_data) 1851 1852 def test_mock_open_dunder_iter_issue(self): 1853 # Test dunder_iter method generates the expected result and 1854 # consumes the iterator. 1855 mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue') 1856 f1 = mocked_open('a-name') 1857 lines = [line for line in f1] 1858 self.assertEqual(lines[0], 'Remarkable\n') 1859 self.assertEqual(lines[1], 'Norwegian Blue') 1860 self.assertEqual(list(f1), []) 1861 1862 def test_mock_open_using_next(self): 1863 mocked_open = mock.mock_open(read_data='1st line\n2nd line\n3rd line') 1864 f1 = mocked_open('a-name') 1865 line1 = next(f1) 1866 line2 = f1.__next__() 1867 lines = [line for line in f1] 1868 self.assertEqual(line1, '1st line\n') 1869 self.assertEqual(line2, '2nd line\n') 1870 self.assertEqual(lines[0], '3rd line') 1871 self.assertEqual(list(f1), []) 1872 with self.assertRaises(StopIteration): 1873 next(f1) 1874 1875 def test_mock_open_next_with_readline_with_return_value(self): 1876 mopen = mock.mock_open(read_data='foo\nbarn') 1877 mopen.return_value.readline.return_value = 'abc' 1878 self.assertEqual('abc', next(mopen())) 1879 1880 def test_mock_open_write(self): 1881 # Test exception in file writing write() 1882 mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV')) 1883 with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp): 1884 mock_filehandle = mock_namedtemp.return_value 1885 mock_write = mock_filehandle.write 1886 mock_write.side_effect = OSError('Test 2 Error') 1887 def attempt(): 1888 tempfile.NamedTemporaryFile().write('asd') 1889 self.assertRaises(OSError, attempt) 1890 1891 def test_mock_open_alter_readline(self): 1892 mopen = mock.mock_open(read_data='foo\nbarn') 1893 mopen.return_value.readline.side_effect = lambda *args:'abc' 1894 first = mopen().readline() 1895 second = mopen().readline() 1896 self.assertEqual('abc', first) 1897 self.assertEqual('abc', second) 1898 1899 def test_mock_open_after_eof(self): 1900 # read, readline and readlines should work after end of file. 1901 _open = mock.mock_open(read_data='foo') 1902 h = _open('bar') 1903 h.read() 1904 self.assertEqual('', h.read()) 1905 self.assertEqual('', h.read()) 1906 self.assertEqual('', h.readline()) 1907 self.assertEqual('', h.readline()) 1908 self.assertEqual([], h.readlines()) 1909 self.assertEqual([], h.readlines()) 1910 1911 def test_mock_parents(self): 1912 for Klass in Mock, MagicMock: 1913 m = Klass() 1914 original_repr = repr(m) 1915 m.return_value = m 1916 self.assertIs(m(), m) 1917 self.assertEqual(repr(m), original_repr) 1918 1919 m.reset_mock() 1920 self.assertIs(m(), m) 1921 self.assertEqual(repr(m), original_repr) 1922 1923 m = Klass() 1924 m.b = m.a 1925 self.assertIn("name='mock.a'", repr(m.b)) 1926 self.assertIn("name='mock.a'", repr(m.a)) 1927 m.reset_mock() 1928 self.assertIn("name='mock.a'", repr(m.b)) 1929 self.assertIn("name='mock.a'", repr(m.a)) 1930 1931 m = Klass() 1932 original_repr = repr(m) 1933 m.a = m() 1934 m.a.return_value = m 1935 1936 self.assertEqual(repr(m), original_repr) 1937 self.assertEqual(repr(m.a()), original_repr) 1938 1939 1940 def test_attach_mock(self): 1941 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock 1942 for Klass in classes: 1943 for Klass2 in classes: 1944 m = Klass() 1945 1946 m2 = Klass2(name='foo') 1947 m.attach_mock(m2, 'bar') 1948 1949 self.assertIs(m.bar, m2) 1950 self.assertIn("name='mock.bar'", repr(m2)) 1951 1952 m.bar.baz(1) 1953 self.assertEqual(m.mock_calls, [call.bar.baz(1)]) 1954 self.assertEqual(m.method_calls, [call.bar.baz(1)]) 1955 1956 1957 def test_attach_mock_return_value(self): 1958 classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock 1959 for Klass in Mock, MagicMock: 1960 for Klass2 in classes: 1961 m = Klass() 1962 1963 m2 = Klass2(name='foo') 1964 m.attach_mock(m2, 'return_value') 1965 1966 self.assertIs(m(), m2) 1967 self.assertIn("name='mock()'", repr(m2)) 1968 1969 m2.foo() 1970 self.assertEqual(m.mock_calls, call().foo().call_list()) 1971 1972 1973 def test_attach_mock_patch_autospec(self): 1974 parent = Mock() 1975 1976 with mock.patch(f'{__name__}.something', autospec=True) as mock_func: 1977 self.assertEqual(mock_func.mock._extract_mock_name(), 'something') 1978 parent.attach_mock(mock_func, 'child') 1979 parent.child(1) 1980 something(2) 1981 mock_func(3) 1982 1983 parent_calls = [call.child(1), call.child(2), call.child(3)] 1984 child_calls = [call(1), call(2), call(3)] 1985 self.assertEqual(parent.mock_calls, parent_calls) 1986 self.assertEqual(parent.child.mock_calls, child_calls) 1987 self.assertEqual(something.mock_calls, child_calls) 1988 self.assertEqual(mock_func.mock_calls, child_calls) 1989 self.assertIn('mock.child', repr(parent.child.mock)) 1990 self.assertEqual(mock_func.mock._extract_mock_name(), 'mock.child') 1991 1992 1993 def test_attach_mock_patch_autospec_signature(self): 1994 with mock.patch(f'{__name__}.Something.meth', autospec=True) as mocked: 1995 manager = Mock() 1996 manager.attach_mock(mocked, 'attach_meth') 1997 obj = Something() 1998 obj.meth(1, 2, 3, d=4) 1999 manager.assert_has_calls([call.attach_meth(mock.ANY, 1, 2, 3, d=4)]) 2000 obj.meth.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)]) 2001 mocked.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)]) 2002 2003 with mock.patch(f'{__name__}.something', autospec=True) as mocked: 2004 manager = Mock() 2005 manager.attach_mock(mocked, 'attach_func') 2006 something(1) 2007 manager.assert_has_calls([call.attach_func(1)]) 2008 something.assert_has_calls([call(1)]) 2009 mocked.assert_has_calls([call(1)]) 2010 2011 with mock.patch(f'{__name__}.Something', autospec=True) as mocked: 2012 manager = Mock() 2013 manager.attach_mock(mocked, 'attach_obj') 2014 obj = Something() 2015 obj.meth(1, 2, 3, d=4) 2016 manager.assert_has_calls([call.attach_obj(), 2017 call.attach_obj().meth(1, 2, 3, d=4)]) 2018 obj.meth.assert_has_calls([call(1, 2, 3, d=4)]) 2019 mocked.assert_has_calls([call(), call().meth(1, 2, 3, d=4)]) 2020 2021 2022 def test_attribute_deletion(self): 2023 for mock in (Mock(), MagicMock(), NonCallableMagicMock(), 2024 NonCallableMock()): 2025 self.assertTrue(hasattr(mock, 'm')) 2026 2027 del mock.m 2028 self.assertFalse(hasattr(mock, 'm')) 2029 2030 del mock.f 2031 self.assertFalse(hasattr(mock, 'f')) 2032 self.assertRaises(AttributeError, getattr, mock, 'f') 2033 2034 2035 def test_mock_does_not_raise_on_repeated_attribute_deletion(self): 2036 # bpo-20239: Assigning and deleting twice an attribute raises. 2037 for mock in (Mock(), MagicMock(), NonCallableMagicMock(), 2038 NonCallableMock()): 2039 mock.foo = 3 2040 self.assertTrue(hasattr(mock, 'foo')) 2041 self.assertEqual(mock.foo, 3) 2042 2043 del mock.foo 2044 self.assertFalse(hasattr(mock, 'foo')) 2045 2046 mock.foo = 4 2047 self.assertTrue(hasattr(mock, 'foo')) 2048 self.assertEqual(mock.foo, 4) 2049 2050 del mock.foo 2051 self.assertFalse(hasattr(mock, 'foo')) 2052 2053 2054 def test_mock_raises_when_deleting_nonexistent_attribute(self): 2055 for mock in (Mock(), MagicMock(), NonCallableMagicMock(), 2056 NonCallableMock()): 2057 del mock.foo 2058 with self.assertRaises(AttributeError): 2059 del mock.foo 2060 2061 2062 def test_reset_mock_does_not_raise_on_attr_deletion(self): 2063 # bpo-31177: reset_mock should not raise AttributeError when attributes 2064 # were deleted in a mock instance 2065 mock = Mock() 2066 mock.child = True 2067 del mock.child 2068 mock.reset_mock() 2069 self.assertFalse(hasattr(mock, 'child')) 2070 2071 2072 def test_class_assignable(self): 2073 for mock in Mock(), MagicMock(): 2074 self.assertNotIsInstance(mock, int) 2075 2076 mock.__class__ = int 2077 self.assertIsInstance(mock, int) 2078 mock.foo 2079 2080 def test_name_attribute_of_call(self): 2081 # bpo-35357: _Call should not disclose any attributes whose names 2082 # may clash with popular ones (such as ".name") 2083 self.assertIsNotNone(call.name) 2084 self.assertEqual(type(call.name), _Call) 2085 self.assertEqual(type(call.name().name), _Call) 2086 2087 def test_parent_attribute_of_call(self): 2088 # bpo-35357: _Call should not disclose any attributes whose names 2089 # may clash with popular ones (such as ".parent") 2090 self.assertIsNotNone(call.parent) 2091 self.assertEqual(type(call.parent), _Call) 2092 self.assertEqual(type(call.parent().parent), _Call) 2093 2094 2095 def test_parent_propagation_with_create_autospec(self): 2096 2097 def foo(a, b): pass 2098 2099 mock = Mock() 2100 mock.child = create_autospec(foo) 2101 mock.child(1, 2) 2102 2103 self.assertRaises(TypeError, mock.child, 1) 2104 self.assertEqual(mock.mock_calls, [call.child(1, 2)]) 2105 self.assertIn('mock.child', repr(mock.child.mock)) 2106 2107 def test_parent_propagation_with_autospec_attach_mock(self): 2108 2109 def foo(a, b): pass 2110 2111 parent = Mock() 2112 parent.attach_mock(create_autospec(foo, name='bar'), 'child') 2113 parent.child(1, 2) 2114 2115 self.assertRaises(TypeError, parent.child, 1) 2116 self.assertEqual(parent.child.mock_calls, [call.child(1, 2)]) 2117 self.assertIn('mock.child', repr(parent.child.mock)) 2118 2119 2120 def test_isinstance_under_settrace(self): 2121 # bpo-36593 : __class__ is not set for a class that has __class__ 2122 # property defined when it's used with sys.settrace(trace) set. 2123 # Delete the module to force reimport with tracing function set 2124 # restore the old reference later since there are other tests that are 2125 # dependent on unittest.mock.patch. In testpatch.PatchTest 2126 # test_patch_dict_test_prefix and test_patch_test_prefix not restoring 2127 # causes the objects patched to go out of sync 2128 2129 old_patch = unittest.mock.patch 2130 2131 # Directly using __setattr__ on unittest.mock causes current imported 2132 # reference to be updated. Use a lambda so that during cleanup the 2133 # re-imported new reference is updated. 2134 self.addCleanup(lambda patch: setattr(unittest.mock, 'patch', patch), 2135 old_patch) 2136 2137 with patch.dict('sys.modules'): 2138 del sys.modules['unittest.mock'] 2139 2140 # This trace will stop coverage being measured ;-) 2141 def trace(frame, event, arg): # pragma: no cover 2142 return trace 2143 2144 self.addCleanup(sys.settrace, sys.gettrace()) 2145 sys.settrace(trace) 2146 2147 from unittest.mock import ( 2148 Mock, MagicMock, NonCallableMock, NonCallableMagicMock 2149 ) 2150 2151 mocks = [ 2152 Mock, MagicMock, NonCallableMock, NonCallableMagicMock, AsyncMock 2153 ] 2154 2155 for mock in mocks: 2156 obj = mock(spec=Something) 2157 self.assertIsInstance(obj, Something) 2158 2159 def test_bool_not_called_when_passing_spec_arg(self): 2160 class Something: 2161 def __init__(self): 2162 self.obj_with_bool_func = unittest.mock.MagicMock() 2163 2164 obj = Something() 2165 with unittest.mock.patch.object(obj, 'obj_with_bool_func', autospec=True): pass 2166 2167 self.assertEqual(obj.obj_with_bool_func.__bool__.call_count, 0) 2168 2169 2170if __name__ == '__main__': 2171 unittest.main() 2172