diff --git a/Lib/test/test_hmac.py b/Lib/test/test_hmac.py index 1ea182fec4ff18..c43188cc333e88 100644 --- a/Lib/test/test_hmac.py +++ b/Lib/test/test_hmac.py @@ -1459,19 +1459,25 @@ class OperatorCompareDigestTestCase(CompareDigestMixin, unittest.TestCase): class PyMiscellaneousTests(unittest.TestCase): """Miscellaneous tests for the pure Python HMAC module.""" + @staticmethod + def mock__compute_digest_fallback(hmac): + fn = getattr(hmac, meth := "_compute_digest_fallback") + return patch.object(hmac, meth, wraps=fn) + + @staticmethod + def mock_HMAC_method(hmac, method): + fn = getattr(hmac.HMAC, method) + return patch.object(hmac.HMAC, method, autospec=True, wraps=fn) + @hashlib_helper.requires_builtin_hmac() def test_hmac_constructor_uses_builtin(self): # Block the OpenSSL implementation and check that # HMAC() uses the built-in implementation instead. hmac = import_fresh_module("hmac", blocked=["_hashlib"]) - def watch_method(cls, name): - wraps = getattr(cls, name) - return patch.object(cls, name, autospec=True, wraps=wraps) - with ( - watch_method(hmac.HMAC, '_init_openssl_hmac') as f, - watch_method(hmac.HMAC, '_init_builtin_hmac') as g, + self.mock_HMAC_method(hmac, '_init_openssl_hmac') as f, + self.mock_HMAC_method(hmac, '_init_builtin_hmac') as g, ): _ = hmac.HMAC(b'key', b'msg', digestmod="sha256") f.assert_not_called() @@ -1542,11 +1548,11 @@ def do_test_hmac_digest_overflow_error_switch_to_slow(self, hmac, size): bigkey = b'K' * size bigmsg = b'M' * size - with patch.object(hmac, "_compute_digest_fallback") as slow: + with self.mock__compute_digest_fallback(hmac) as slow: hmac.digest(bigkey, b'm', "md5") slow.assert_called_once() - with patch.object(hmac, "_compute_digest_fallback") as slow: + with self.mock__compute_digest_fallback(hmac) as slow: hmac.digest(b'k', bigmsg, "md5") slow.assert_called_once() @@ -1557,7 +1563,7 @@ def test_hmac_digest_no_overflow_error_in_fallback(self, size): for key, msg in [(b'K' * size, b'm'), (b'k', b'M' * size)]: with self.subTest(keysize=len(key), msgsize=len(msg)): - with patch.object(hmac, "_compute_digest_fallback") as slow: + with self.mock__compute_digest_fallback(hmac) as slow: hmac.digest(key, msg, "md5") slow.assert_called_once()