|
4 | 4 | # Licensed under the MIT license. See LICENSE file in the project root for details. |
5 | 5 | # |
6 | 6 |
|
| 7 | +import struct as pystruct |
7 | 8 | import unittest |
8 | 9 |
|
9 | 10 | from libdestruct.c.struct_parser import definition_to_type |
| 11 | +from libdestruct import inflater |
10 | 12 |
|
11 | 13 |
|
12 | 14 | class StructParserTest(unittest.TestCase): |
@@ -39,5 +41,52 @@ def test_nested_struct_definition(self): |
39 | 41 | self.assertIn("b", t.__annotations__) |
40 | 42 |
|
41 | 43 |
|
| 44 | +class TypedefTest(unittest.TestCase): |
| 45 | + """Typedef support in C struct parser.""" |
| 46 | + |
| 47 | + def test_simple_typedef(self): |
| 48 | + t = definition_to_type(""" |
| 49 | + typedef unsigned int uint32_t; |
| 50 | + struct S { uint32_t x; }; |
| 51 | + """) |
| 52 | + self.assertIn("x", t.__annotations__) |
| 53 | + |
| 54 | + def test_typedef_of_struct(self): |
| 55 | + t = definition_to_type(""" |
| 56 | + typedef struct { int x; } Point; |
| 57 | + struct S { Point p; }; |
| 58 | + """) |
| 59 | + self.assertIn("p", t.__annotations__) |
| 60 | + |
| 61 | + def test_typedef_of_pointer(self): |
| 62 | + t = definition_to_type(""" |
| 63 | + typedef int *intptr; |
| 64 | + struct S { intptr p; }; |
| 65 | + """) |
| 66 | + self.assertIn("p", t.__annotations__) |
| 67 | + |
| 68 | + def test_typedef_chain(self): |
| 69 | + t = definition_to_type(""" |
| 70 | + typedef unsigned int u32; |
| 71 | + typedef u32 mytype; |
| 72 | + struct S { mytype x; }; |
| 73 | + """) |
| 74 | + self.assertIn("x", t.__annotations__) |
| 75 | + |
| 76 | + def test_typedef_inflate_and_read(self): |
| 77 | + t = definition_to_type(""" |
| 78 | + typedef unsigned int uint32_t; |
| 79 | + struct S { uint32_t x; int y; }; |
| 80 | + """) |
| 81 | + memory = bytearray(8) |
| 82 | + memory[0:4] = pystruct.pack("<I", 0xDEADBEEF) |
| 83 | + memory[4:8] = pystruct.pack("<i", -42) |
| 84 | + |
| 85 | + lib = inflater(memory) |
| 86 | + s = lib.inflate(t, 0) |
| 87 | + self.assertEqual(s.x.value, 0xDEADBEEF) |
| 88 | + self.assertEqual(s.y.value, -42) |
| 89 | + |
| 90 | + |
42 | 91 | if __name__ == "__main__": |
43 | 92 | unittest.main() |
0 commit comments