dumprar: rar5 support
[rarfile.git] / test / testseek.py
blobe6925ebfe30e941575b339474da157dce3edc27d
1 #! /usr/bin/env python
3 import rarfile, os, os.path, time, sys
5 def show_fds():
6 fdir = "/proc/%d/fd" % os.getpid()
7 if os.path.isdir(fdir):
8 os.system('printf "fds = "; ls -l %s | wc -l' % fdir)
10 def do_seek(f, pos, lim):
11 ofs = pos*4
12 fsize = lim*4
14 if ofs < 0:
15 exp = 0
16 elif ofs > fsize:
17 exp = fsize
18 else:
19 exp = ofs
21 f.seek(ofs)
23 got = f.tell()
25 if got != exp:
26 raise Exception('seek failed (got=%d, exp=%d)' % (got, exp))
27 ln = f.read(4)
28 if got == fsize and ln:
29 raise Exception('unexpected read')
30 if not ln and got < fsize:
31 raise Exception('unexpected read failure')
32 if ln:
33 spos = int(ln)
34 if spos*4 != got:
35 raise Exception('unexpected pos: spos=%d pos=%d' % (spos, pos))
37 def test_seek(rf, fn):
38 inf = rf.getinfo(fn)
39 cnt = int(inf.file_size / 4)
40 f = rf.open(fn)
42 do_seek(f, int(cnt/2), cnt)
43 do_seek(f, 0, cnt)
45 for i in range(int(cnt/2)):
46 do_seek(f, i*2, cnt)
48 for i in range(cnt):
49 do_seek(f, i*2 - int(cnt / 2), cnt)
51 for i in range(cnt + 10):
52 do_seek(f, cnt - i - 5, cnt)
54 f.close()
56 print('OK')
58 def test_arc(arc, desc):
59 files = ['stest1.txt', 'stest2.txt']
60 rf = rarfile.RarFile(arc, crc_check=0)
61 for fn in files:
62 sys.stdout.write('%s | test/seek %s .. ' % (desc, fn))
63 sys.stdout.flush()
64 test_seek(rf, fn)
66 def main():
67 arc = 'files/seektest.rar'
68 data = open(arc, 'rb').read()
70 # filename
71 test_arc(arc, "fn")
73 # filelike: cStringIO
74 try:
75 import cStringIO
76 test_arc(cStringIO.StringIO(data), "cStringIO")
77 except ImportError:
78 pass
80 # filelike: io.BytesIO, io.open()
81 try:
82 import io
83 test_arc(io.BytesIO(data), "io.BytesIO")
84 test_arc(io.open(arc, 'rb'), "io.open")
85 except ImportError:
86 pass
88 # filelike: StringIO
89 try:
90 import StringIO
91 test_arc(StringIO.StringIO(data), "StringIO")
92 except ImportError:
93 pass
95 # filelike: file()
96 test_arc(open(arc, 'rb'), "file")
98 time.sleep(1)
99 show_fds()
101 if __name__ == '__main__':
102 main()