cryptacular / tests / test_bcrypt.py

import unittest
from cryptacular.bcrypt import Bcrypt


try:
    unicode
except NameError:
    unicode = str


class TestBcrypt(unittest.TestCase):

    snowpass = unicode('hashy the \N{SNOWMAN}')

    def setUp(self):
        self.bcrypt = Bcrypt()

    def test_none_1(self):
        self.assertRaises(TypeError, self.bcrypt.encode, None)

    def test_none_2(self):
        self.assertRaises(TypeError, self.bcrypt.check, 'xyzzy', None)

    def test_none_3(self):
        hash = self.bcrypt.encode('xyzzy')
        self.assertRaises(TypeError, self.bcrypt.check, None, hash)

    def test_badhash(self):
        self.assertFalse(
            self.bcrypt.check(
                self.snowpass,
                '$p5k2$400$ZxK4ZBJCfQg=$kBpklVI9kA13kP32HMZL0rloQ1M='
            ))

    def test_shorthash(self):
        def match(hash):
            return True
        bcrypt = Bcrypt()
        bcrypt.match = match
        short_hash = bcrypt.encode(self.snowpass)[:28]
        self.assertRaises(ValueError, bcrypt.check, self.snowpass, short_hash)

    def test_too_few_rounds(self):
        self.assertRaises(ValueError, self.bcrypt.encode, self.snowpass, rounds=1)

    def test_too_many_rounds(self):
        self.assertRaises(ValueError, self.bcrypt.encode,
            self.snowpass, rounds=100)

    def test_emptypass(self):
        self.bcrypt.encode('')

    def test_valid_hash_1(self):
        hash = self.bcrypt.encode(self.snowpass)
        self.assertTrue(self.bcrypt.match(hash))
        self.assertTrue(self.bcrypt.check(self.snowpass, hash))
        self.assertEqual(len(hash), 60)

    def test_valid_hash_2(self):
        password = "xyzzy"
        hash = self.bcrypt.encode(password)
        self.assertTrue(self.bcrypt.check(password, hash))
        self.assertTrue(self.bcrypt.check(password, unicode(hash)))
        self.assertFalse(self.bcrypt.check(password, password))
        self.assertNotEqual(self.bcrypt.encode(password),
            self.bcrypt.encode(password))
        hash = self.bcrypt.encode(password, rounds=4)
        self.assertTrue(self.bcrypt.check(password, hash))


if __name__ == '__main__':
    unittest.main()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.