Andrew M. Kuchling | a0b6035 | 2001-11-02 21:46:17 +0000 | [diff] [blame] | 1 | # |
| 2 | # Test suite to check compliance with PEP 247, the standard API for |
Tim Peters | 8876848 | 2001-11-13 21:51:26 +0000 | [diff] [blame] | 3 | # hashing algorithms. |
Andrew M. Kuchling | a0b6035 | 2001-11-02 21:46:17 +0000 | [diff] [blame] | 4 | # |
| 5 | |
Brett Cannon | 7eec217 | 2007-05-30 22:24:28 +0000 | [diff] [blame] | 6 | import warnings |
| 7 | warnings.filterwarnings("ignore", "the md5 module is deprecated.*", |
| 8 | DeprecationWarning) |
Brett Cannon | c2aa09a | 2007-05-31 19:20:00 +0000 | [diff] [blame] | 9 | warnings.filterwarnings("ignore", "the sha module is deprecated.*", |
| 10 | DeprecationWarning) |
Brett Cannon | 7eec217 | 2007-05-30 22:24:28 +0000 | [diff] [blame] | 11 | |
Andrew M. Kuchling | a0b6035 | 2001-11-02 21:46:17 +0000 | [diff] [blame] | 12 | import md5, sha, hmac |
| 13 | |
| 14 | def check_hash_module(module, key=None): |
| 15 | assert hasattr(module, 'digest_size'), "Must have digest_size" |
| 16 | assert (module.digest_size is None or |
| 17 | module.digest_size > 0), "digest_size must be None or positive" |
| 18 | |
| 19 | if key is not None: |
| 20 | obj1 = module.new(key) |
| 21 | obj2 = module.new(key, "string") |
| 22 | |
| 23 | h1 = module.new(key, "string").digest() |
| 24 | obj3 = module.new(key) ; obj3.update("string") ; h2 = obj3.digest() |
| 25 | assert h1 == h2, "Hashes must match" |
| 26 | |
| 27 | else: |
| 28 | obj1 = module.new() |
| 29 | obj2 = module.new("string") |
| 30 | |
| 31 | h1 = module.new("string").digest() |
| 32 | obj3 = module.new() ; obj3.update("string") ; h2 = obj3.digest() |
| 33 | assert h1 == h2, "Hashes must match" |
| 34 | |
| 35 | assert hasattr(obj1, 'digest_size'), "Objects must have digest_size attr" |
| 36 | if module.digest_size is not None: |
| 37 | assert obj1.digest_size == module.digest_size, "digest_size must match" |
| 38 | assert obj1.digest_size == len(h1), "digest_size must match actual size" |
| 39 | obj1.update("string") |
| 40 | obj_copy = obj1.copy() |
| 41 | assert obj1.digest() == obj_copy.digest(), "Copied objects must match" |
| 42 | assert obj1.hexdigest() == obj_copy.hexdigest(), \ |
| 43 | "Copied objects must match" |
| 44 | digest, hexdigest = obj1.digest(), obj1.hexdigest() |
| 45 | hd2 = "" |
| 46 | for byte in digest: |
| 47 | hd2 += "%02x" % ord(byte) |
| 48 | assert hd2 == hexdigest, "hexdigest doesn't appear correct" |
| 49 | |
| 50 | print 'Module', module.__name__, 'seems to comply with PEP 247' |
| 51 | |
| 52 | |
| 53 | if __name__ == '__main__': |
| 54 | check_hash_module(md5) |
| 55 | check_hash_module(sha) |
| 56 | check_hash_module(hmac, key='abc') |