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