|
2 | 2 | import functools |
3 | 3 | import hmac |
4 | 4 | import hashlib |
| 5 | +import random |
5 | 6 | import test.support.hashlib_helper as hashlib_helper |
6 | 7 | import unittest |
7 | 8 | import unittest.mock |
@@ -626,12 +627,47 @@ def test_exercise_all_methods(self): |
626 | 627 | self.fail("Exception raised during normal usage of HMAC class.") |
627 | 628 |
|
628 | 629 |
|
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') |
635 | 671 |
|
636 | 672 |
|
637 | 673 | @hashlib_helper.requires_hashdigest('sha256') |
|
0 commit comments