3 import random, unittest
5 from allmydata.util import base62, mathutil
7 def insecurerandstr(n):
8 return ''.join(map(chr, map(random.randrange, [0]*n, [256]*n)))
10 class T(unittest.TestCase):
11 def _test_num_octets_that_encode_to_this_many_chars(self, chars, octets):
12 assert base62.num_octets_that_encode_to_this_many_chars(chars) == octets, "%s != %s <- %s" % (octets, base62.num_octets_that_encode_to_this_many_chars(chars), chars)
14 def _test_ende(self, bs):
17 assert bs2 == bs, "bs2: %s:%s, bs: %s:%s, ascii: %s:%s" % (len(bs2), `bs2`, len(bs), `bs`, len(ascii), `ascii`)
19 def test_num_octets_that_encode_to_this_many_chars(self):
20 return self._test_num_octets_that_encode_to_this_many_chars(2, 1)
21 return self._test_num_octets_that_encode_to_this_many_chars(3, 2)
22 return self._test_num_octets_that_encode_to_this_many_chars(5, 3)
23 return self._test_num_octets_that_encode_to_this_many_chars(6, 4)
25 def test_ende_0x00(self):
26 return self._test_ende('\x00')
28 def test_ende_0x01(self):
29 return self._test_ende('\x01')
31 def test_ende_0x0100(self):
32 return self._test_ende('\x01\x00')
34 def test_ende_0x000000(self):
35 return self._test_ende('\x00\x00\x00')
37 def test_ende_0x010000(self):
38 return self._test_ende('\x01\x00\x00')
40 def test_ende_randstr(self):
41 return self._test_ende(insecurerandstr(2**4))
43 def test_ende_longrandstr(self):
44 return self._test_ende(insecurerandstr(random.randrange(0, 2**10)))
46 def test_odd_sizes(self):
48 lib = random.randrange(1, 2**8)
49 numos = mathutil.div_ceil(lib, 8)
50 bs = insecurerandstr(numos)
51 # zero-out unused least-sig bits
54 b = b >> (8 - (lib%8))
55 b = b << (8 - (lib%8))
57 asl = base62.b2a_l(bs, lib)
58 assert len(asl) == base62.num_chars_that_this_many_octets_encode_to(numos) # the size of the base-62 encoding must be just right
59 bs2l = base62.a2b_l(asl, lib)
60 assert len(bs2l) == numos # the size of the result must be just right
64 suite = unittest.makeSuite(T, 'test')
67 if __name__ == "__main__":