0001 # 0002 # Test suite to check compliance with PEP 247, the standard API for 0003 # hashing algorithms. 0004 # 0005 0006 import md5, sha, hmac 0007 0008 def check_hash_module(module, key=None): 0009 assert hasattr(module, 'digest_size'), "Must have digest_size" 0010 assert (module.digest_size is None or 0011 module.digest_size > 0), "digest_size must be None or positive" 0012 0013 if key is not None: 0014 obj1 = module.new(key) 0015 obj2 = module.new(key, "string") 0016 0017 h1 = module.new(key, "string").digest() 0018 obj3 = module.new(key) ; obj3.update("string") ; h2 = obj3.digest() 0019 assert h1 == h2, "Hashes must match" 0020 0021 else: 0022 obj1 = module.new() 0023 obj2 = module.new("string") 0024 0025 h1 = module.new("string").digest() 0026 obj3 = module.new() ; obj3.update("string") ; h2 = obj3.digest() 0027 assert h1 == h2, "Hashes must match" 0028 0029 assert hasattr(obj1, 'digest_size'), "Objects must have digest_size attr" 0030 if module.digest_size is not None: 0031 assert obj1.digest_size == module.digest_size, "digest_size must match" 0032 assert obj1.digest_size == len(h1), "digest_size must match actual size" 0033 obj1.update("string") 0034 obj_copy = obj1.copy() 0035 assert obj1.digest() == obj_copy.digest(), "Copied objects must match" 0036 assert obj1.hexdigest() == obj_copy.hexdigest(), \ 0037 "Copied objects must match" 0038 digest, hexdigest = obj1.digest(), obj1.hexdigest() 0039 hd2 = "" 0040 for byte in digest: 0041 hd2 += "%02x" % ord(byte) 0042 assert hd2 == hexdigest, "hexdigest doesn't appear correct" 0043 0044 print 'Module', module.__name__, 'seems to comply with PEP 247' 0045 0046 0047 if __name__ == '__main__': 0048 check_hash_module(md5) 0049 check_hash_module(sha) 0050 check_hash_module(hmac, key='abc') 0051
Generated by PyXR 0.9.4