summaryrefslogtreecommitdiff
path: root/isso/tests/test_utils_hash.py
blob: 626d75ef8af2c7505c1d7aca8a449e202c33abc0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# -*- encoding: utf-8 -*-

from __future__ import unicode_literals

try:
    import unittest2 as unittest
except ImportError:
    import unittest

from isso import config

from isso.compat import PY2K, string_types
from isso.utils.hash import Hash, PBKDF2, new


class TestHasher(unittest.TestCase):

    def test_hash(self):
        self.assertRaises(TypeError, Hash, "Foo")

        self.assertEqual(Hash(b"").salt, b"")
        self.assertEqual(Hash().salt, Hash.salt)

        h = Hash(b"", func=None)

        self.assertRaises(TypeError, h.hash, "...")
        self.assertEqual(h.hash(b"..."), b"...")
        self.assertIsInstance(h.uhash(u"..."), string_types)

    @unittest.skipIf(PY2K, "byte/str quirks")
    def test_uhash(self):
        h = Hash(b"", func=None)
        self.assertRaises(TypeError, h.uhash, b"...")


class TestPBKDF2(unittest.TestCase):

    def test_default(self):
        pbkdf2 = PBKDF2(iterations=1000)  # original setting (and still default)
        self.assertEqual(pbkdf2.uhash(""), "42476aafe2e4")

    def test_different_salt(self):
        a = PBKDF2(b"a", iterations=1)
        b = PBKDF2(b"b", iterations=1)
        self.assertNotEqual(a.hash(b""), b.hash(b""))


class TestCreate(unittest.TestCase):

    def test_custom(self):

        def _new(val):
            conf = config.new({
                "hash": {
                    "algorithm": val,
                    "salt": ""
                }
            })
            return new(conf.section("hash"))

        sha1 = _new("sha1")
        self.assertIsInstance(sha1, Hash)
        self.assertEqual(sha1.func, "sha1")
        self.assertRaises(ValueError, _new, "foo")

        pbkdf2 = _new("pbkdf2:16")
        self.assertIsInstance(pbkdf2, PBKDF2)
        self.assertEqual(pbkdf2.iterations, 16)

        pbkdf2 = _new("pbkdf2:16:2:md5")
        self.assertIsInstance(pbkdf2, PBKDF2)
        self.assertEqual(pbkdf2.dklen, 2)
        self.assertEqual(pbkdf2.func, "md5")