test_pep247.py 2.02 KB
Newer Older
Christian Heimes's avatar
Christian Heimes committed
1 2 3 4
"""
Test suite to check compilance with PEP 247, the standard API
for hashing algorithms
"""
5

6
import hmac
Christian Heimes's avatar
Christian Heimes committed
7
import unittest
8
from hashlib import md5, sha1, sha224, sha256, sha384, sha512
9
from test import support
10

Christian Heimes's avatar
Christian Heimes committed
11
class Pep247Test(unittest.TestCase):
12

Christian Heimes's avatar
Christian Heimes committed
13 14 15
    def check_module(self, module, key=None):
        self.assert_(hasattr(module, 'digest_size'))
        self.assert_(module.digest_size is None or module.digest_size > 0)
16 17 18 19 20 21 22 23 24
        self.check_object(module.new, module.digest_size, key)

    def check_object(self, cls, digest_size, key):
        if key is not None:
            obj1 = cls(key)
            obj2 = cls(key, b'string')
            h1 = cls(key, b'string').digest()
            obj3 = cls(key)
            obj3.update(b'string')
Christian Heimes's avatar
Christian Heimes committed
25 26
            h2 = obj3.digest()
        else:
27 28 29 30 31
            obj1 = cls()
            obj2 = cls(b'string')
            h1 = cls(b'string').digest()
            obj3 = cls()
            obj3.update(b'string')
Christian Heimes's avatar
Christian Heimes committed
32 33 34
            h2 = obj3.digest()
        self.assertEquals(h1, h2)
        self.assert_(hasattr(obj1, 'digest_size'))
35

36 37
        if digest_size is not None:
            self.assertEquals(obj1.digest_size, digest_size)
Christian Heimes's avatar
Christian Heimes committed
38 39

        self.assertEquals(obj1.digest_size, len(h1))
40
        obj1.update(b'string')
Christian Heimes's avatar
Christian Heimes committed
41 42 43 44 45 46 47
        obj_copy = obj1.copy()
        self.assertEquals(obj1.digest(), obj_copy.digest())
        self.assertEquals(obj1.hexdigest(), obj_copy.hexdigest())

        digest, hexdigest = obj1.digest(), obj1.hexdigest()
        hd2 = ""
        for byte in digest:
48
            hd2 += '%02x' % byte
Christian Heimes's avatar
Christian Heimes committed
49
        self.assertEquals(hd2, hexdigest)
50

Christian Heimes's avatar
Christian Heimes committed
51
    def test_md5(self):
52
        self.check_object(md5, None, None)
Christian Heimes's avatar
Christian Heimes committed
53 54

    def test_sha(self):
55 56 57 58 59
        self.check_object(sha1, None, None)
        self.check_object(sha224, None, None)
        self.check_object(sha256, None, None)
        self.check_object(sha384, None, None)
        self.check_object(sha512, None, None)
Christian Heimes's avatar
Christian Heimes committed
60 61

    def test_hmac(self):
62
        self.check_module(hmac, key=b'abc')
Christian Heimes's avatar
Christian Heimes committed
63 64

def test_main():
65
    support.run_unittest(Pep247Test)
66 67 68

if __name__ == '__main__':
    test_main()