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