blob: 2a2d7aca0a9b9184cb8a7654438266a1193f73db [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
Guido van Rossuma8add0e2007-05-14 22:03:55 +00006import hmac
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +00007
Christian Heimes180510d2008-03-03 19:15:45 +00008import hmac
9from test.test_support import verbose
10
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000011def check_hash_module(module, key=None):
12 assert hasattr(module, 'digest_size'), "Must have digest_size"
13 assert (module.digest_size is None or
14 module.digest_size > 0), "digest_size must be None or positive"
15
16 if key is not None:
17 obj1 = module.new(key)
Alexandre Vassalottia351f772008-03-03 02:59:49 +000018 obj2 = module.new(key, b"string")
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000019
Alexandre Vassalottia351f772008-03-03 02:59:49 +000020 h1 = module.new(key, b"string").digest()
21 obj3 = module.new(key) ; obj3.update(b"string") ; h2 = obj3.digest()
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000022 assert h1 == h2, "Hashes must match"
23
24 else:
25 obj1 = module.new()
Alexandre Vassalottia351f772008-03-03 02:59:49 +000026 obj2 = module.new(b"string")
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000027
Alexandre Vassalottia351f772008-03-03 02:59:49 +000028 h1 = module.new(b"string").digest()
29 obj3 = module.new() ; obj3.update(b"string") ; h2 = obj3.digest()
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000030 assert h1 == h2, "Hashes must match"
31
32 assert hasattr(obj1, 'digest_size'), "Objects must have digest_size attr"
33 if module.digest_size is not None:
34 assert obj1.digest_size == module.digest_size, "digest_size must match"
35 assert obj1.digest_size == len(h1), "digest_size must match actual size"
Alexandre Vassalottia351f772008-03-03 02:59:49 +000036 obj1.update(b"string")
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000037 obj_copy = obj1.copy()
38 assert obj1.digest() == obj_copy.digest(), "Copied objects must match"
39 assert obj1.hexdigest() == obj_copy.hexdigest(), \
40 "Copied objects must match"
41 digest, hexdigest = obj1.digest(), obj1.hexdigest()
42 hd2 = ""
43 for byte in digest:
Alexandre Vassalottia351f772008-03-03 02:59:49 +000044 hd2 += "%02x" % byte
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000045 assert hd2 == hexdigest, "hexdigest doesn't appear correct"
46
Christian Heimes180510d2008-03-03 19:15:45 +000047 if verbose:
48 print('Module', module.__name__, 'seems to comply with PEP 247')
49
50
51def test_main():
52 check_hash_module(hmac, key=b'abc')
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000053
54
55if __name__ == '__main__':
Christian Heimes180510d2008-03-03 19:15:45 +000056 test_main()