@@ -1452,19 +1452,25 @@ class OperatorCompareDigestTestCase(CompareDigestMixin, unittest.TestCase):
14521452class PyMiscellaneousTests(unittest.TestCase):
14531453 """Miscellaneous tests for the pure Python HMAC module."""
14541454
1455+ @staticmethod
1456+ def mock__compute_digest_fallback(hmac):
1457+ fn = getattr(hmac, meth := "_compute_digest_fallback")
1458+ return patch.object(hmac, meth, wraps=fn)
1459+
1460+ @staticmethod
1461+ def mock_HMAC_method(hmac, method):
1462+ fn = getattr(hmac.HMAC, method)
1463+ return patch.object(hmac.HMAC, method, autospec=True, wraps=fn)
1464+
14551465 @hashlib_helper.requires_builtin_hmac()
14561466 def test_hmac_constructor_uses_builtin(self):
14571467 # Block the OpenSSL implementation and check that
14581468 # HMAC() uses the built-in implementation instead.
14591469 hmac = import_fresh_module("hmac", blocked=["_hashlib"])
14601470
1461- def watch_method(cls, name):
1462- wraps = getattr(cls, name)
1463- return patch.object(cls, name, autospec=True, wraps=wraps)
1464-
14651471 with (
1466- watch_method (hmac.HMAC , '_init_openssl_hmac') as f,
1467- watch_method (hmac.HMAC , '_init_builtin_hmac') as g,
1472+ self.mock_HMAC_method (hmac, '_init_openssl_hmac') as f,
1473+ self.mock_HMAC_method (hmac, '_init_builtin_hmac') as g,
14681474 ):
14691475 _ = hmac.HMAC(b'key', b'msg', digestmod="sha256")
14701476 f.assert_not_called()
@@ -1535,11 +1541,11 @@ def do_test_hmac_digest_overflow_error_switch_to_slow(self, hmac, size):
15351541 bigkey = b'K' * size
15361542 bigmsg = b'M' * size
15371543
1538- with patch.object (hmac, "_compute_digest_fallback" ) as slow:
1544+ with self.mock__compute_digest_fallback (hmac) as slow:
15391545 hmac.digest(bigkey, b'm', "md5")
15401546 slow.assert_called_once()
15411547
1542- with patch.object (hmac, "_compute_digest_fallback" ) as slow:
1548+ with self.mock__compute_digest_fallback (hmac) as slow:
15431549 hmac.digest(b'k', bigmsg, "md5")
15441550 slow.assert_called_once()
15451551
@@ -1550,7 +1556,7 @@ def test_hmac_digest_no_overflow_error_in_fallback(self, size):
15501556
15511557 for key, msg in [(b'K' * size, b'm'), (b'k', b'M' * size)]:
15521558 with self.subTest(keysize=len(key), msgsize=len(msg)):
1553- with patch.object (hmac, "_compute_digest_fallback" ) as slow:
1559+ with self.mock__compute_digest_fallback (hmac) as slow:
15541560 hmac.digest(key, msg, "md5")
15551561 slow.assert_called_once()
15561562
0 commit comments