]> git.rkrishnan.org Git - tahoe-lafs/zfec.git/blob - zfec/zfec/test/test_zfec.py
3e51a783db4ddf3a03953fbc76300dd98310601f
[tahoe-lafs/zfec.git] / zfec / zfec / test / test_zfec.py
1 #!/usr/bin/env python
2
3 import cStringIO, os, random, re
4
5 import unittest
6
7 global VERBOSE
8 VERBOSE=False
9
10 import zfec
11
12 from pyutil import fileutil
13
14 from base64 import b32encode
15 def ab(x): # debuggery
16     if len(x) >= 3:
17         return "%s:%s" % (len(x), b32encode(x[-3:]),)
18     elif len(x) == 2:
19         return "%s:%s" % (len(x), b32encode(x[-2:]),)
20     elif len(x) == 1:
21         return "%s:%s" % (len(x), b32encode(x[-1:]),)
22     elif len(x) == 0:
23         return "%s:%s" % (len(x), "--empty--",)
24
25 def randstr(n):
26     return ''.join(map(chr, map(random.randrange, [0]*n, [256]*n)))
27
28 def _h(k, m, ss):
29     encer = zfec.Encoder(k, m)
30     nums_and_blocks = list(enumerate(encer.encode(ss)))
31     assert isinstance(nums_and_blocks, list), nums_and_blocks
32     assert len(nums_and_blocks) == m, (len(nums_and_blocks), m,)
33     nums_and_blocks = random.sample(nums_and_blocks, k)
34     blocks = [ x[1] for x in nums_and_blocks ]
35     nums = [ x[0] for x in nums_and_blocks ]
36     decer = zfec.Decoder(k, m)
37     decoded = decer.decode(blocks, nums)
38     assert len(decoded) == len(ss), (len(decoded), len(ss),)
39     assert tuple([str(s) for s in decoded]) == tuple([str(s) for s in ss]), (tuple([ab(str(s)) for s in decoded]), tuple([ab(str(s)) for s in ss]),)
40
41 def _help_test_random():
42     m = random.randrange(1, 257)
43     k = random.randrange(1, m+1)
44     l = random.randrange(0, 2**9)
45     ss = [ randstr(l/k) for x in range(k) ]
46     _h(k, m, ss)
47
48 def _help_test_random_with_l(l):
49     m = random.randrange(1, 257)
50     k = random.randrange(1, m+1)
51     ss = [ randstr(l/k) for x in range(k) ]
52     _h(k, m, ss)
53
54 def _h_easy(k, m, s):
55     encer = zfec.easyfec.Encoder(k, m)
56     nums_and_blocks = list(enumerate(encer.encode(s)))
57     assert isinstance(nums_and_blocks, list), nums_and_blocks
58     assert len(nums_and_blocks) == m, (len(nums_and_blocks), m,)
59     nums_and_blocks = random.sample(nums_and_blocks, k)
60     blocks = [ x[1] for x in nums_and_blocks ]
61     nums = [ x[0] for x in nums_and_blocks ]
62     decer = zfec.easyfec.Decoder(k, m)
63     
64     decodeds = decer.decode(blocks, nums, padlen=k*len(blocks[0]) - len(s))
65     assert len(decodeds) == len(s), (ab(decodeds), ab(s), k, m)
66     assert decodeds == s, (ab(decodeds), ab(s),)
67
68 def _help_test_random_easy():
69     m = random.randrange(1, 257)
70     k = random.randrange(1, m+1)
71     l = random.randrange(0, 2**9)
72     s = randstr(l)
73     _h_easy(k, m, s)
74
75 def _help_test_random_with_l_easy(l):
76     m = random.randrange(1, 257)
77     k = random.randrange(1, m+1)
78     s = randstr(l)
79     _h_easy(k, m, s)
80     
81 class ZFecTest(unittest.TestCase):
82     def test_from_agl_c(self):
83         self.failUnless(zfec._fec.test_from_agl())
84             
85     def test_from_agl_py(self):
86         e = zfec.Encoder(3, 5)
87         b0 = '\x01'*8 ; b1 = '\x02'*8 ; b2 = '\x03'*8
88         # print "_from_py before encoding:"
89         # print "b0: %s, b1: %s, b2: %s" % tuple(base64.b16encode(x) for x in [b0, b1, b2])
90
91         b3, b4 = e.encode([b0, b1, b2], (3, 4))
92         # print "after encoding:"
93         # print "b3: %s, b4: %s" % tuple(base64.b16encode(x) for x in [b3, b4])
94
95         d = zfec.Decoder(3, 5)
96         r0, r1, r2 = d.decode((b2, b3, b4), (1, 2, 3))
97         
98         # print "after decoding:"
99         # print "b0: %s, b1: %s" % tuple(base64.b16encode(x) for x in [b0, b1])
100
101     def test_small(self):
102         for i in range(16):
103             _help_test_random_with_l(i)
104         if VERBOSE:
105             print "%d randomized tests pass." % (i+1)
106
107     def test_random(self):
108         for i in range(3):
109             _help_test_random()
110         if VERBOSE:
111             print "%d randomized tests pass." % (i+1)
112
113     def test_bad_args_dec(self):
114         decer = zfec.Decoder(2, 4)
115
116         try:
117             decer.decode(98, []) # first argument is not a sequence
118         except TypeError, e:
119             assert "First argument was not a sequence" in str(e), e
120         else:
121             raise "Should have gotten TypeError for wrong type of second argument."
122
123         try:
124             decer.decode(["a", "b", ], ["c", "d",])
125         except zfec.Error, e:
126             assert "Precondition violation: second argument is required to contain int" in str(e), e
127         else:
128             raise "Should have gotten zfec.Error for wrong type of second argument."
129
130         try:
131             decer.decode(["a", "b", ], 98) # not a sequence at all
132         except TypeError, e:
133             assert "Second argument was not a sequence" in str(e), e
134         else:
135             raise "Should have gotten TypeError for wrong type of second argument."
136
137 class EasyFecTest(unittest.TestCase):
138     def test_small(self):
139         for i in range(16):
140             _help_test_random_with_l_easy(i)
141         if VERBOSE:
142             print "%d randomized tests pass." % (i+1)
143
144     def test_random(self):
145         for i in range(3):
146             _help_test_random_easy()
147         if VERBOSE:
148             print "%d randomized tests pass." % (i+1)
149
150     def test_bad_args_dec(self):
151         decer = zfec.easyfec.Decoder(2, 4)
152
153         try:
154             decer.decode(98, [0, 1], 0) # first argument is not a sequence
155         except TypeError, e:
156             assert "First argument was not a sequence" in str(e), e
157         else:
158             raise "Should have gotten TypeError for wrong type of second argument."
159
160         try:
161             decer.decode("ab", ["c", "d",], 0)
162         except zfec.Error, e:
163             assert "Precondition violation: second argument is required to contain int" in str(e), e
164         else:
165             raise "Should have gotten zfec.Error for wrong type of second argument."
166
167         try:
168             decer.decode("ab", 98, 0) # not a sequence at all
169         except TypeError, e:
170             assert "Second argument was not a sequence" in str(e), e
171         else:
172             raise "Should have gotten TypeError for wrong type of second argument."
173
174 class FileFec(unittest.TestCase):
175     def test_filefec_header(self):
176         for m in [1, 2, 3, 5, 7, 9, 11, 17, 19, 33, 35, 65, 66, 67, 129, 130, 131, 254, 255, 256,]:
177             for k in [1, 2, 3, 5, 9, 17, 33, 65, 129, 255, 256,]:
178                 if k >= m:
179                     continue
180                 for pad in [0, 1, k-1,]:
181                     if pad >= k:
182                         continue
183                     for sh in [0, 1, m-1,]:
184                         if sh >= m:
185                             continue
186                         h = zfec.filefec._build_header(m, k, pad, sh)
187                         hio = cStringIO.StringIO(h)
188                         (rm, rk, rpad, rsh,) = zfec.filefec._parse_header(hio)
189                         assert (rm, rk, rpad, rsh,) == (m, k, pad, sh,), h
190
191     def _help_test_filefec(self, teststr, k, m, numshs=None):
192         if numshs == None:
193             numshs = m
194
195         TESTFNAME = "testfile.txt"
196         PREFIX = "test"
197         SUFFIX = ".fec"
198
199         fsize = len(teststr)
200
201         tempdir = fileutil.NamedTemporaryDirectory(cleanup=True)
202         try:
203             tempf = tempdir.file(TESTFNAME, 'w+b')
204             tempf.write(teststr)
205             tempf.flush()
206             tempf.seek(0)
207
208             # encode the file
209             zfec.filefec.encode_to_files(tempf, fsize, tempdir.name, PREFIX, k, m, SUFFIX, verbose=VERBOSE)
210
211             # select some share files
212             RE=re.compile(zfec.filefec.RE_FORMAT % (PREFIX, SUFFIX,))
213             fns = os.listdir(tempdir.name)
214             assert len(fns) >= m, (fns, tempdir, tempdir.name,)
215             sharefs = [ open(os.path.join(tempdir.name, fn), "rb") for fn in fns if RE.match(fn) ]
216             for sharef in sharefs:
217                 tempdir.register_file(sharef)
218             random.shuffle(sharefs)
219             del sharefs[numshs:]
220
221             # decode from the share files
222             outf = tempdir.file('recovered-testfile.txt', 'w+b')
223             zfec.filefec.decode_from_files(outf, sharefs, verbose=VERBOSE)
224             outf.flush()
225             outf.seek(0)
226             recovereddata = outf.read()
227             assert recovereddata == teststr, (ab(recovereddata), ab(teststr),)
228         finally:
229             tempdir.shutdown()
230
231     def test_filefec_all_shares(self):
232         return self._help_test_filefec("Yellow Whirled!", 3, 8)
233
234     def test_filefec_all_shares_1_b(self):
235         return self._help_test_filefec("Yellow Whirled!", 4, 16)
236
237     def test_filefec_all_shares_2(self):
238         return self._help_test_filefec("Yellow Whirled", 3, 8)
239
240     def test_filefec_all_shares_2_b(self):
241         return self._help_test_filefec("Yellow Whirled", 4, 16)
242
243     def test_filefec_all_shares_3(self):
244         return self._help_test_filefec("Yellow Whirle", 3, 8)
245
246     def test_filefec_all_shares_3_b(self):
247         return self._help_test_filefec("Yellow Whirle", 4, 16)
248
249     def test_filefec_all_shares_with_padding(self, noisy=VERBOSE):
250         return self._help_test_filefec("Yellow Whirled!A", 3, 8)
251
252     def test_filefec_min_shares_with_padding(self, noisy=VERBOSE):
253         return self._help_test_filefec("Yellow Whirled!A", 3, 8, numshs=3)
254
255     def test_filefec_min_shares_with_crlf(self, noisy=VERBOSE):
256         return self._help_test_filefec("llow Whirled!A\r\n", 3, 8, numshs=3)
257
258     def test_filefec_min_shares_with_lf(self, noisy=VERBOSE):
259         return self._help_test_filefec("Yellow Whirled!A\n", 3, 8, numshs=3)
260
261     def test_filefec_min_shares_with_lflf(self, noisy=VERBOSE):
262         return self._help_test_filefec("Yellow Whirled!A\n\n", 3, 8, numshs=3)
263
264     def test_filefec_min_shares_with_crcrlflf(self, noisy=VERBOSE):
265         return self._help_test_filefec("Yellow Whirled!A\r\r\n\n", 3, 8, numshs=3)
266
267  
268 class Cmdline(unittest.TestCase):
269     def test_basic(self, noisy=VERBOSE):
270         tempdir = fileutil.NamedTemporaryDirectory(cleanup=True)
271         fo = tempdir.file("test.data", "w+b")
272         fo.write("WHEHWHJEKWAHDLJAWDHWALKDHA")
273
274         import sys
275         realargv = sys.argv
276         try:
277             DEFAULT_M=8
278             DEFAULT_K=3
279             sys.argv = ["zfec", os.path.join(tempdir.name, "test.data"),]
280         
281             retcode = zfec.cmdline_zfec.main()
282             assert retcode == 0, retcode
283
284             RE=re.compile(zfec.filefec.RE_FORMAT % ('test.data', ".fec",))
285             fns = os.listdir(tempdir.name)
286             assert len(fns) >= DEFAULT_M, (fns, DEFAULT_M, tempdir, tempdir.name,)
287             sharefns = [ os.path.join(tempdir.name, fn) for fn in fns if RE.match(fn) ]
288             random.shuffle(sharefns)
289             del sharefns[DEFAULT_K:]
290
291             sys.argv = ["zunfec",]
292             sys.argv.extend(sharefns)
293             sys.argv.extend(['-o', os.path.join(tempdir.name, 'test.data-recovered'),])
294             
295             retcode = zfec.cmdline_zunfec.main()
296             assert retcode == 0, retcode
297             import filecmp
298             assert filecmp.cmp(os.path.join(tempdir.name, 'test.data'), os.path.join(tempdir.name, 'test.data-recovered'))
299         finally:
300             sys.argv = realargv
301
302 if __name__ == "__main__":
303     unittest.main()