| 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 |  | 
 | 6 | import md5, sha, hmac | 
 | 7 |  | 
 | 8 | def check_hash_module(module, key=None): | 
 | 9 |     assert hasattr(module, 'digest_size'), "Must have digest_size" | 
 | 10 |     assert (module.digest_size is None or | 
 | 11 |             module.digest_size > 0), "digest_size must be None or positive" | 
 | 12 |  | 
 | 13 |     if key is not None: | 
 | 14 |         obj1 = module.new(key) | 
 | 15 |         obj2 = module.new(key, "string") | 
 | 16 |  | 
 | 17 |         h1 = module.new(key, "string").digest() | 
 | 18 |         obj3 = module.new(key) ; obj3.update("string") ; h2 = obj3.digest() | 
 | 19 |         assert h1 == h2, "Hashes must match" | 
 | 20 |  | 
 | 21 |     else: | 
 | 22 |         obj1 = module.new() | 
 | 23 |         obj2 = module.new("string") | 
 | 24 |  | 
 | 25 |         h1 = module.new("string").digest() | 
 | 26 |         obj3 = module.new() ; obj3.update("string") ; h2 = obj3.digest() | 
 | 27 |         assert h1 == h2, "Hashes must match" | 
 | 28 |  | 
 | 29 |     assert hasattr(obj1, 'digest_size'), "Objects must have digest_size attr" | 
 | 30 |     if module.digest_size is not None: | 
 | 31 |         assert obj1.digest_size == module.digest_size, "digest_size must match" | 
 | 32 |     assert obj1.digest_size == len(h1), "digest_size must match actual size" | 
 | 33 |     obj1.update("string") | 
 | 34 |     obj_copy = obj1.copy() | 
 | 35 |     assert obj1.digest() == obj_copy.digest(), "Copied objects must match" | 
 | 36 |     assert obj1.hexdigest() == obj_copy.hexdigest(), \ | 
 | 37 |            "Copied objects must match" | 
 | 38 |     digest, hexdigest = obj1.digest(), obj1.hexdigest() | 
 | 39 |     hd2 = "" | 
 | 40 |     for byte in digest: | 
 | 41 |         hd2 += "%02x" % ord(byte) | 
 | 42 |     assert hd2 == hexdigest, "hexdigest doesn't appear correct" | 
 | 43 |  | 
 | 44 |     print 'Module', module.__name__, 'seems to comply with PEP 247' | 
 | 45 |  | 
 | 46 |  | 
 | 47 | if __name__ == '__main__': | 
 | 48 |     check_hash_module(md5) | 
 | 49 |     check_hash_module(sha) | 
 | 50 |     check_hash_module(hmac, key='abc') |