1# -*- coding: utf-8 -*- 2import re 3 4from webapp2_extras import security 5 6import test_base 7 8 9class TestSecurity(test_base.BaseTestCase): 10 def test_generate_random_string(self): 11 self.assertRaises(ValueError, security.generate_random_string, None) 12 self.assertRaises(ValueError, security.generate_random_string, 0) 13 self.assertRaises(ValueError, security.generate_random_string, -1) 14 self.assertRaises(ValueError, security.generate_random_string, 1, 1) 15 16 token = security.generate_random_string(16) 17 self.assertTrue(re.match(r'^\w{16}$', token) is not None) 18 19 token = security.generate_random_string(32) 20 self.assertTrue(re.match(r'^\w{32}$', token) is not None) 21 22 token = security.generate_random_string(64) 23 self.assertTrue(re.match(r'^\w{64}$', token) is not None) 24 25 token = security.generate_random_string(128) 26 self.assertTrue(re.match(r'^\w{128}$', token) is not None) 27 28 def test_create_check_password_hash(self): 29 self.assertRaises(TypeError, security.generate_password_hash, 'foo', 30 'bar') 31 32 password = 'foo' 33 hashval = security.generate_password_hash(password, 'sha1') 34 self.assertTrue(security.check_password_hash(password, hashval)) 35 36 hashval = security.generate_password_hash(password, 'sha1', pepper='bar') 37 self.assertTrue(security.check_password_hash(password, hashval, 38 pepper='bar')) 39 40 hashval = security.generate_password_hash(password, 'md5') 41 self.assertTrue(security.check_password_hash(password, hashval)) 42 43 hashval = security.generate_password_hash(password, 'plain') 44 self.assertTrue(security.check_password_hash(password, hashval)) 45 46 hashval = security.generate_password_hash(password, 'plain') 47 self.assertFalse(security.check_password_hash(password, '')) 48 49 hashval1 = security.hash_password(unicode(password), 'sha1', u'bar') 50 hashval2 = security.hash_password(unicode(password), 'sha1', u'bar') 51 self.assertTrue(hashval1 is not None) 52 self.assertEqual(hashval1, hashval2) 53 54 hashval1 = security.hash_password(unicode(password), 'md5', None) 55 hashval2 = security.hash_password(unicode(password), 'md5', None) 56 self.assertTrue(hashval1 is not None) 57 self.assertEqual(hashval1, hashval2) 58 59 60if __name__ == '__main__': 61 test_base.main() 62