blob: 0497ee9ea681831b1a26f81481f1b51c74dcbee8 [file] [log] [blame]
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +00001#
2# Test suite to check compliance with PEP 247, the standard API for
Tim Peters88768482001-11-13 21:51:26 +00003# hashing algorithms.
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +00004#
5
Brett Cannon7eec2172007-05-30 22:24:28 +00006import warnings
7warnings.filterwarnings("ignore", "the md5 module is deprecated.*",
8 DeprecationWarning)
Brett Cannonc2aa09a2007-05-31 19:20:00 +00009warnings.filterwarnings("ignore", "the sha module is deprecated.*",
10 DeprecationWarning)
Brett Cannon7eec2172007-05-30 22:24:28 +000011
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000012import md5, sha, hmac
Brett Cannon963c80f2008-03-03 03:26:43 +000013from test.test_support import verbose
14
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000015
16def check_hash_module(module, key=None):
17 assert hasattr(module, 'digest_size'), "Must have digest_size"
18 assert (module.digest_size is None or
19 module.digest_size > 0), "digest_size must be None or positive"
20
21 if key is not None:
22 obj1 = module.new(key)
23 obj2 = module.new(key, "string")
24
25 h1 = module.new(key, "string").digest()
26 obj3 = module.new(key) ; obj3.update("string") ; h2 = obj3.digest()
27 assert h1 == h2, "Hashes must match"
28
29 else:
30 obj1 = module.new()
31 obj2 = module.new("string")
32
33 h1 = module.new("string").digest()
34 obj3 = module.new() ; obj3.update("string") ; h2 = obj3.digest()
35 assert h1 == h2, "Hashes must match"
36
37 assert hasattr(obj1, 'digest_size'), "Objects must have digest_size attr"
38 if module.digest_size is not None:
39 assert obj1.digest_size == module.digest_size, "digest_size must match"
40 assert obj1.digest_size == len(h1), "digest_size must match actual size"
41 obj1.update("string")
42 obj_copy = obj1.copy()
43 assert obj1.digest() == obj_copy.digest(), "Copied objects must match"
44 assert obj1.hexdigest() == obj_copy.hexdigest(), \
45 "Copied objects must match"
46 digest, hexdigest = obj1.digest(), obj1.hexdigest()
47 hd2 = ""
48 for byte in digest:
49 hd2 += "%02x" % ord(byte)
50 assert hd2 == hexdigest, "hexdigest doesn't appear correct"
51
Brett Cannon963c80f2008-03-03 03:26:43 +000052 if verbose:
53 print 'Module', module.__name__, 'seems to comply with PEP 247'
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000054
55
Brett Cannon963c80f2008-03-03 03:26:43 +000056def test_main():
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000057 check_hash_module(md5)
58 check_hash_module(sha)
59 check_hash_module(hmac, key='abc')
Brett Cannon963c80f2008-03-03 03:26:43 +000060
61
62if __name__ == '__main__':
63 test_main()