Package openid :: Package test :: Module cryptutil
[frames] | no frames]

Source Code for Module openid.test.cryptutil

  1  import sys 
  2  import random 
  3  import os.path 
  4   
  5  from openid import cryptutil 
  6   
  7  # Most of the purpose of this test is to make sure that cryptutil can 
  8  # find a good source of randomness on this machine. 
  9   
10 -def test_cryptrand():
11 # It's possible, but HIGHLY unlikely that a correct implementation 12 # will fail by returning the same number twice 13 14 s = cryptutil.getBytes(32) 15 t = cryptutil.getBytes(32) 16 assert len(s) == 32 17 assert len(t) == 32 18 assert s != t 19 20 a = cryptutil.randrange(2L ** 128) 21 b = cryptutil.randrange(2L ** 128) 22 assert type(a) is long 23 assert type(b) is long 24 assert b != a 25 26 # Make sure that we can generate random numbers that are larger 27 # than platform int size 28 cryptutil.randrange(long(sys.maxint) + 1L)
29
30 -def test_reversed():
31 if hasattr(cryptutil, 'reversed'): 32 cases = [ 33 ('', ''), 34 ('a', 'a'), 35 ('ab', 'ba'), 36 ('abc', 'cba'), 37 ('abcdefg', 'gfedcba'), 38 ([], []), 39 ([1], [1]), 40 ([1,2], [2,1]), 41 ([1,2,3], [3,2,1]), 42 (range(1000), range(999, -1, -1)), 43 ] 44 45 for case, expected in cases: 46 expected = list(expected) 47 actual = list(cryptutil.reversed(case)) 48 assert actual == expected, (case, expected, actual) 49 twice = list(cryptutil.reversed(actual)) 50 assert twice == list(case), (actual, case, twice)
51
52 -def test_binaryLongConvert():
53 MAX = sys.maxint 54 for iteration in xrange(500): 55 n = 0L 56 for i in range(10): 57 n += long(random.randrange(MAX)) 58 59 s = cryptutil.longToBinary(n) 60 assert type(s) is str 61 n_prime = cryptutil.binaryToLong(s) 62 assert n == n_prime, (n, n_prime) 63 64 cases = [ 65 ('\x00', 0L), 66 ('\x01', 1L), 67 ('\x7F', 127L), 68 ('\x00\xFF', 255L), 69 ('\x00\x80', 128L), 70 ('\x00\x81', 129L), 71 ('\x00\x80\x00', 32768L), 72 ('OpenID is cool', 1611215304203901150134421257416556L) 73 ] 74 75 for s, n in cases: 76 n_prime = cryptutil.binaryToLong(s) 77 s_prime = cryptutil.longToBinary(n) 78 assert n == n_prime, (s, n, n_prime) 79 assert s == s_prime, (n, s, s_prime)
80
81 -def test_longToBase64():
82 f = file(os.path.join(os.path.dirname(__file__), 'n2b64')) 83 try: 84 for line in f: 85 parts = line.strip().split(' ') 86 assert parts[0] == cryptutil.longToBase64(long(parts[1])) 87 finally: 88 f.close()
89
90 -def test_base64ToLong():
91 f = file(os.path.join(os.path.dirname(__file__), 'n2b64')) 92 try: 93 for line in f: 94 parts = line.strip().split(' ') 95 assert long(parts[1]) == cryptutil.base64ToLong(parts[0]) 96 finally: 97 f.close()
98 99
100 -def test():
101 test_reversed() 102 test_binaryLongConvert() 103 test_cryptrand() 104 test_longToBase64() 105 test_base64ToLong()
106 107 if __name__ == '__main__': 108 test() 109