]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/test/test_base62.py
9eff8aba15916ade3d499296bfcd10f742b5838c
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / test / test_base62.py
1 #!/usr/bin/env python
2
3 import random, unittest
4
5 from allmydata.util import base62, mathutil
6
7 def insecurerandstr(n):
8     return ''.join(map(chr, map(random.randrange, [0]*n, [256]*n)))
9
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)
13
14     def _test_ende(self, bs):
15         ascii=base62.b2a(bs)
16         bs2=base62.a2b(ascii)
17         assert bs2 == bs, "bs2: %s:%s, bs: %s:%s, ascii: %s:%s" % (len(bs2), `bs2`, len(bs), `bs`, len(ascii), `ascii`)
18
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)
24
25     def test_ende_0x00(self):
26         return self._test_ende('\x00')
27
28     def test_ende_0x01(self):
29         return self._test_ende('\x01')
30
31     def test_ende_0x0100(self):
32         return self._test_ende('\x01\x00')
33
34     def test_ende_0x000000(self):
35         return self._test_ende('\x00\x00\x00')
36
37     def test_ende_0x010000(self):
38         return self._test_ende('\x01\x00\x00')
39
40     def test_ende_randstr(self):
41         return self._test_ende(insecurerandstr(2**4))
42
43     def test_ende_longrandstr(self):
44         return self._test_ende(insecurerandstr(random.randrange(0, 2**10)))
45
46     def test_odd_sizes(self):
47         for j in range(2**6):
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
52             if lib%8:
53                 b=ord(bs[-1])
54                 b = b >> (8 - (lib%8))
55                 b = b << (8 - (lib%8))
56                 bs = bs[:-1] + chr(b)
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
61             assert bs == bs2l
62
63 def suite():
64     suite = unittest.makeSuite(T, 'test')
65     return suite
66
67 if __name__ == "__main__":
68     unittest.main()