1 import random, unittest
3 from allmydata.util import base62, mathutil
5 def insecurerandstr(n):
6 return ''.join(map(chr, map(random.randrange, [0]*n, [256]*n)))
8 class T(unittest.TestCase):
9 def _test_num_octets_that_encode_to_this_many_chars(self, chars, octets):
10 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)
12 def _test_ende(self, bs):
15 assert bs2 == bs, "bs2: %s:%s, bs: %s:%s, ascii: %s:%s" % (len(bs2), `bs2`, len(bs), `bs`, len(ascii), `ascii`)
17 def test_num_octets_that_encode_to_this_many_chars(self):
18 return self._test_num_octets_that_encode_to_this_many_chars(2, 1)
19 return self._test_num_octets_that_encode_to_this_many_chars(3, 2)
20 return self._test_num_octets_that_encode_to_this_many_chars(5, 3)
21 return self._test_num_octets_that_encode_to_this_many_chars(6, 4)
23 def test_ende_0x00(self):
24 return self._test_ende('\x00')
26 def test_ende_0x01(self):
27 return self._test_ende('\x01')
29 def test_ende_0x0100(self):
30 return self._test_ende('\x01\x00')
32 def test_ende_0x000000(self):
33 return self._test_ende('\x00\x00\x00')
35 def test_ende_0x010000(self):
36 return self._test_ende('\x01\x00\x00')
38 def test_ende_randstr(self):
39 return self._test_ende(insecurerandstr(2**4))
41 def test_ende_longrandstr(self):
42 return self._test_ende(insecurerandstr(random.randrange(0, 2**10)))
44 def test_odd_sizes(self):
46 lib = random.randrange(1, 2**8)
47 numos = mathutil.div_ceil(lib, 8)
48 bs = insecurerandstr(numos)
49 # zero-out unused least-sig bits
52 b = b >> (8 - (lib%8))
53 b = b << (8 - (lib%8))
55 asl = base62.b2a_l(bs, lib)
56 assert len(asl) == base62.num_chars_that_this_many_octets_encode_to(numos) # the size of the base-62 encoding must be just right
57 bs2l = base62.a2b_l(asl, lib)
58 assert len(bs2l) == numos # the size of the result must be just right
62 suite = unittest.makeSuite(T, 'test')
65 if __name__ == "__main__":