blob: 54a09bb4f2ab4c57a1b479b5e93e0a2e7605c8fa [file] [log] [blame]
Eli Benderskya1d61402011-11-28 06:25:52 +02001import sys, unittest
2from cStringIO import StringIO
3from random import randint
4
5sys.path.extend(['.', '..'])
6from elftools.common.utils import (parse_cstring_from_stream,
7 preserve_stream_pos)
8
9
10class Test_parse_cstring_from_stream(unittest.TestCase):
11 def _make_random_string(self, n):
12 return ''.join(chr(randint(32, 127)) for i in range(n))
13
14 def test_small1(self):
15 sio = StringIO('abcdefgh\x0012345')
16 self.assertEqual(parse_cstring_from_stream(sio), 'abcdefgh')
17 self.assertEqual(parse_cstring_from_stream(sio, 2), 'cdefgh')
18 self.assertEqual(parse_cstring_from_stream(sio, 8), '')
19
20 def test_small2(self):
21 sio = StringIO('12345\x006789\x00abcdefg\x00iii')
22 self.assertEqual(parse_cstring_from_stream(sio), '12345')
23 self.assertEqual(parse_cstring_from_stream(sio, 5), '')
24 self.assertEqual(parse_cstring_from_stream(sio, 6), '6789')
25
26 def test_large1(self):
27 text = 'i' * 400 + '\x00' + 'bb'
28 sio = StringIO(text)
29 self.assertEqual(parse_cstring_from_stream(sio), 'i' * 400)
30 self.assertEqual(parse_cstring_from_stream(sio, 150), 'i' * 250)
31
32 def test_large2(self):
33 text = self._make_random_string(5000) + '\x00' + 'jujajaja'
34 sio = StringIO(text)
35 self.assertEqual(parse_cstring_from_stream(sio), text[:5000])
36 self.assertEqual(parse_cstring_from_stream(sio, 2348), text[2348:5000])
37
38
39class Test_preserve_stream_pos(object):
40 def test_basic(self):
41 sio = StringIO('abcdef')
42 with preserve_stream_pos(sio):
43 sio.seek(4)
44 self.assertEqual(stream.tell(), 0)
45
46 sio.seek(5)
47 with preserve_stream_pos(sio):
48 sio.seek(0)
49 self.assertEqual(stream.tell(), 5)
50
51
52if __name__ == '__main__':
53 unittest.main()
54
55
56