Fix for mixed version loclists, tests (#521)
[pyelftools.git] / test / test_utils.py
1 #-------------------------------------------------------------------------------
2 # elftools tests
3 #
4 # Eli Bendersky (eliben@gmail.com)
5 # This code is in the public domain
6 #-------------------------------------------------------------------------------
7 import unittest
8 from io import BytesIO
9 from random import randint
10
11 from elftools.common.utils import (parse_cstring_from_stream, merge_dicts,
12 preserve_stream_pos)
13
14
15 class Test_parse_cstring_from_stream(unittest.TestCase):
16 def _make_random_bytes(self, n):
17 return b''.join(bytes((randint(32, 127),)) for i in range(n))
18
19 def test_small1(self):
20 sio = BytesIO(b'abcdefgh\x0012345')
21 self.assertEqual(parse_cstring_from_stream(sio), b'abcdefgh')
22 self.assertEqual(parse_cstring_from_stream(sio, 2), b'cdefgh')
23 self.assertEqual(parse_cstring_from_stream(sio, 8), b'')
24
25 def test_small2(self):
26 sio = BytesIO(b'12345\x006789\x00abcdefg\x00iii')
27 self.assertEqual(parse_cstring_from_stream(sio), b'12345')
28 self.assertEqual(parse_cstring_from_stream(sio, 5), b'')
29 self.assertEqual(parse_cstring_from_stream(sio, 6), b'6789')
30
31 def test_large1(self):
32 text = b'i' * 400 + b'\x00' + b'bb'
33 sio = BytesIO(text)
34 self.assertEqual(parse_cstring_from_stream(sio), b'i' * 400)
35 self.assertEqual(parse_cstring_from_stream(sio, 150), b'i' * 250)
36
37 def test_large2(self):
38 text = self._make_random_bytes(5000) + b'\x00' + b'jujajaja'
39 sio = BytesIO(text)
40 self.assertEqual(parse_cstring_from_stream(sio), text[:5000])
41 self.assertEqual(parse_cstring_from_stream(sio, 2348), text[2348:5000])
42
43
44 class Test_preserve_stream_pos(unittest.TestCase):
45 def test_basic(self):
46 sio = BytesIO(b'abcdef')
47 with preserve_stream_pos(sio):
48 sio.seek(4)
49 self.assertEqual(sio.tell(), 0)
50
51 sio.seek(5)
52 with preserve_stream_pos(sio):
53 sio.seek(0)
54 self.assertEqual(sio.tell(), 5)
55
56
57 class Test_merge_dicts(unittest.TestCase):
58 def test_basic(self):
59 md = merge_dicts({10: 20, 20: 30}, {30: 40, 50: 60})
60 self.assertEqual(md, {10: 20, 20: 30, 30: 40, 50: 60})
61
62 def test_keys_resolve(self):
63 md = merge_dicts({10: 20, 20: 30}, {20: 40, 50: 60})
64 self.assertEqual(md, {10: 20, 20: 40, 50: 60})
65
66
67 if __name__ == '__main__':
68 unittest.main()