Skip to content

Commit 105f6ce

Browse files
committed
refactor UpdateTestCase
1 parent d2eb48a commit 105f6ce

File tree

1 file changed

+42
-6
lines changed

1 file changed

+42
-6
lines changed

Lib/test/test_hmac.py

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import functools
33
import hmac
44
import hashlib
5+
import random
56
import test.support.hashlib_helper as hashlib_helper
67
import unittest
78
import unittest.mock
@@ -626,12 +627,47 @@ def test_exercise_all_methods(self):
626627
self.fail("Exception raised during normal usage of HMAC class.")
627628

628629

629-
class UpdateTestCase(unittest.TestCase):
630-
@hashlib_helper.requires_hashdigest('sha256')
631-
def test_with_str_update(self):
632-
with self.assertRaises(TypeError):
633-
h = hmac.new(b"key", digestmod='sha256')
634-
h.update("invalid update")
630+
class UpdateTestCaseMixin:
631+
632+
def HMAC(self, key, msg=None):
633+
raise NotImplementedError
634+
635+
def test_update(self):
636+
key, msg = random.randbytes(16), random.randbytes(16)
637+
with self.subTest(key=key, msg=msg):
638+
h1 = self.HMAC(key, msg)
639+
640+
h2 = self.HMAC(key)
641+
h2.update(msg)
642+
643+
self.assertEqual(h1.digest(), h2.digest())
644+
self.assertEqual(h1.hexdigest(), h2.hexdigest())
645+
646+
def test_update_exceptions(self):
647+
h = self.HMAC(b"key")
648+
for msg in ['invalid msg', 123, (), []]:
649+
with self.subTest(msg=msg):
650+
self.assertRaises(TypeError, h.update, msg)
651+
652+
653+
@hashlib_helper.requires_hashdigest('sha256')
654+
class PyUpdateTestCase(UpdateTestCaseMixin, unittest.TestCase):
655+
656+
@classmethod
657+
def setUpClass(cls):
658+
super().setUpClass()
659+
cls.hmac = import_fresh_module('hmac', blocked=['_hashlib'])
660+
661+
def HMAC(self, key, msg=None):
662+
return self.hmac.HMAC(key, msg, digestmod='sha256')
663+
664+
665+
@hashlib_helper.requires_hashlib()
666+
@hashlib_helper.requires_hashdigest('sha256', openssl=True)
667+
class OpenSSLUpdateTestCase(UpdateTestCaseMixin, unittest.TestCase):
668+
669+
def HMAC(self, key, msg=None):
670+
return hmac.new(key, msg, digestmod='sha256')
635671

636672

637673
@hashlib_helper.requires_hashdigest('sha256')

0 commit comments

Comments
 (0)