[3.13] gh-123934: Fix MagicMock not to reset magic method return values (GH-124038) (#124231)

gh-123934: Fix `MagicMock` not to reset magic method return values (GH-124038)
(cherry picked from commit 7628f67d55)

Co-authored-by: sobolevn <mail@sobolevn.me>
This commit is contained in:
Miss Islington (bot) 2024-09-30 03:11:03 +02:00 committed by GitHub
parent dceac5b8ea
commit 0a868db982
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 53 additions and 1 deletions

View file

@ -331,6 +331,45 @@ class TestMockingMagicMethods(unittest.TestCase):
self.assertEqual(os.fspath(mock), expected_path)
mock.__fspath__.assert_called_once()
def test_magic_mock_does_not_reset_magic_returns(self):
# https://github.com/python/cpython/issues/123934
for reset in (True, False):
with self.subTest(reset=reset):
mm = MagicMock()
self.assertIs(type(mm.__str__()), str)
mm.__str__.assert_called_once()
self.assertIs(type(mm.__hash__()), int)
mm.__hash__.assert_called_once()
for _ in range(3):
# Repeat reset several times to be sure:
mm.reset_mock(return_value=reset)
self.assertIs(type(mm.__str__()), str)
mm.__str__.assert_called_once()
self.assertIs(type(mm.__hash__()), int)
mm.__hash__.assert_called_once()
def test_magic_mock_resets_manual_mocks(self):
mm = MagicMock()
mm.__iter__ = MagicMock(return_value=iter([1]))
mm.custom = MagicMock(return_value=2)
self.assertEqual(list(iter(mm)), [1])
self.assertEqual(mm.custom(), 2)
mm.reset_mock(return_value=True)
self.assertEqual(list(iter(mm)), [])
self.assertIsInstance(mm.custom(), MagicMock)
def test_magic_mock_resets_manual_mocks_empty_iter(self):
mm = MagicMock()
mm.__iter__.return_value = []
self.assertEqual(list(iter(mm)), [])
mm.reset_mock(return_value=True)
self.assertEqual(list(iter(mm)), [])
def test_magic_methods_and_spec(self):
class Iterable(object):