1 | n/a | from collections import abc |
---|
2 | n/a | import array |
---|
3 | n/a | import math |
---|
4 | n/a | import operator |
---|
5 | n/a | import unittest |
---|
6 | n/a | import struct |
---|
7 | n/a | import sys |
---|
8 | n/a | |
---|
9 | n/a | from test import support |
---|
10 | n/a | |
---|
11 | n/a | ISBIGENDIAN = sys.byteorder == "big" |
---|
12 | n/a | |
---|
13 | n/a | integer_codes = 'b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q', 'n', 'N' |
---|
14 | n/a | byteorders = '', '@', '=', '<', '>', '!' |
---|
15 | n/a | |
---|
16 | n/a | def iter_integer_formats(byteorders=byteorders): |
---|
17 | n/a | for code in integer_codes: |
---|
18 | n/a | for byteorder in byteorders: |
---|
19 | n/a | if (byteorder not in ('', '@') and code in ('n', 'N')): |
---|
20 | n/a | continue |
---|
21 | n/a | yield code, byteorder |
---|
22 | n/a | |
---|
23 | n/a | def string_reverse(s): |
---|
24 | n/a | return s[::-1] |
---|
25 | n/a | |
---|
26 | n/a | def bigendian_to_native(value): |
---|
27 | n/a | if ISBIGENDIAN: |
---|
28 | n/a | return value |
---|
29 | n/a | else: |
---|
30 | n/a | return string_reverse(value) |
---|
31 | n/a | |
---|
32 | n/a | class StructTest(unittest.TestCase): |
---|
33 | n/a | def test_isbigendian(self): |
---|
34 | n/a | self.assertEqual((struct.pack('=i', 1)[0] == 0), ISBIGENDIAN) |
---|
35 | n/a | |
---|
36 | n/a | def test_consistence(self): |
---|
37 | n/a | self.assertRaises(struct.error, struct.calcsize, 'Z') |
---|
38 | n/a | |
---|
39 | n/a | sz = struct.calcsize('i') |
---|
40 | n/a | self.assertEqual(sz * 3, struct.calcsize('iii')) |
---|
41 | n/a | |
---|
42 | n/a | fmt = 'cbxxxxxxhhhhiillffd?' |
---|
43 | n/a | fmt3 = '3c3b18x12h6i6l6f3d3?' |
---|
44 | n/a | sz = struct.calcsize(fmt) |
---|
45 | n/a | sz3 = struct.calcsize(fmt3) |
---|
46 | n/a | self.assertEqual(sz * 3, sz3) |
---|
47 | n/a | |
---|
48 | n/a | self.assertRaises(struct.error, struct.pack, 'iii', 3) |
---|
49 | n/a | self.assertRaises(struct.error, struct.pack, 'i', 3, 3, 3) |
---|
50 | n/a | self.assertRaises((TypeError, struct.error), struct.pack, 'i', 'foo') |
---|
51 | n/a | self.assertRaises((TypeError, struct.error), struct.pack, 'P', 'foo') |
---|
52 | n/a | self.assertRaises(struct.error, struct.unpack, 'd', b'flap') |
---|
53 | n/a | s = struct.pack('ii', 1, 2) |
---|
54 | n/a | self.assertRaises(struct.error, struct.unpack, 'iii', s) |
---|
55 | n/a | self.assertRaises(struct.error, struct.unpack, 'i', s) |
---|
56 | n/a | |
---|
57 | n/a | def test_transitiveness(self): |
---|
58 | n/a | c = b'a' |
---|
59 | n/a | b = 1 |
---|
60 | n/a | h = 255 |
---|
61 | n/a | i = 65535 |
---|
62 | n/a | l = 65536 |
---|
63 | n/a | f = 3.1415 |
---|
64 | n/a | d = 3.1415 |
---|
65 | n/a | t = True |
---|
66 | n/a | |
---|
67 | n/a | for prefix in ('', '@', '<', '>', '=', '!'): |
---|
68 | n/a | for format in ('xcbhilfd?', 'xcBHILfd?'): |
---|
69 | n/a | format = prefix + format |
---|
70 | n/a | s = struct.pack(format, c, b, h, i, l, f, d, t) |
---|
71 | n/a | cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s) |
---|
72 | n/a | self.assertEqual(cp, c) |
---|
73 | n/a | self.assertEqual(bp, b) |
---|
74 | n/a | self.assertEqual(hp, h) |
---|
75 | n/a | self.assertEqual(ip, i) |
---|
76 | n/a | self.assertEqual(lp, l) |
---|
77 | n/a | self.assertEqual(int(100 * fp), int(100 * f)) |
---|
78 | n/a | self.assertEqual(int(100 * dp), int(100 * d)) |
---|
79 | n/a | self.assertEqual(tp, t) |
---|
80 | n/a | |
---|
81 | n/a | def test_new_features(self): |
---|
82 | n/a | # Test some of the new features in detail |
---|
83 | n/a | # (format, argument, big-endian result, little-endian result, asymmetric) |
---|
84 | n/a | tests = [ |
---|
85 | n/a | ('c', b'a', b'a', b'a', 0), |
---|
86 | n/a | ('xc', b'a', b'\0a', b'\0a', 0), |
---|
87 | n/a | ('cx', b'a', b'a\0', b'a\0', 0), |
---|
88 | n/a | ('s', b'a', b'a', b'a', 0), |
---|
89 | n/a | ('0s', b'helloworld', b'', b'', 1), |
---|
90 | n/a | ('1s', b'helloworld', b'h', b'h', 1), |
---|
91 | n/a | ('9s', b'helloworld', b'helloworl', b'helloworl', 1), |
---|
92 | n/a | ('10s', b'helloworld', b'helloworld', b'helloworld', 0), |
---|
93 | n/a | ('11s', b'helloworld', b'helloworld\0', b'helloworld\0', 1), |
---|
94 | n/a | ('20s', b'helloworld', b'helloworld'+10*b'\0', b'helloworld'+10*b'\0', 1), |
---|
95 | n/a | ('b', 7, b'\7', b'\7', 0), |
---|
96 | n/a | ('b', -7, b'\371', b'\371', 0), |
---|
97 | n/a | ('B', 7, b'\7', b'\7', 0), |
---|
98 | n/a | ('B', 249, b'\371', b'\371', 0), |
---|
99 | n/a | ('h', 700, b'\002\274', b'\274\002', 0), |
---|
100 | n/a | ('h', -700, b'\375D', b'D\375', 0), |
---|
101 | n/a | ('H', 700, b'\002\274', b'\274\002', 0), |
---|
102 | n/a | ('H', 0x10000-700, b'\375D', b'D\375', 0), |
---|
103 | n/a | ('i', 70000000, b'\004,\035\200', b'\200\035,\004', 0), |
---|
104 | n/a | ('i', -70000000, b'\373\323\342\200', b'\200\342\323\373', 0), |
---|
105 | n/a | ('I', 70000000, b'\004,\035\200', b'\200\035,\004', 0), |
---|
106 | n/a | ('I', 0x100000000-70000000, b'\373\323\342\200', b'\200\342\323\373', 0), |
---|
107 | n/a | ('l', 70000000, b'\004,\035\200', b'\200\035,\004', 0), |
---|
108 | n/a | ('l', -70000000, b'\373\323\342\200', b'\200\342\323\373', 0), |
---|
109 | n/a | ('L', 70000000, b'\004,\035\200', b'\200\035,\004', 0), |
---|
110 | n/a | ('L', 0x100000000-70000000, b'\373\323\342\200', b'\200\342\323\373', 0), |
---|
111 | n/a | ('f', 2.0, b'@\000\000\000', b'\000\000\000@', 0), |
---|
112 | n/a | ('d', 2.0, b'@\000\000\000\000\000\000\000', |
---|
113 | n/a | b'\000\000\000\000\000\000\000@', 0), |
---|
114 | n/a | ('f', -2.0, b'\300\000\000\000', b'\000\000\000\300', 0), |
---|
115 | n/a | ('d', -2.0, b'\300\000\000\000\000\000\000\000', |
---|
116 | n/a | b'\000\000\000\000\000\000\000\300', 0), |
---|
117 | n/a | ('?', 0, b'\0', b'\0', 0), |
---|
118 | n/a | ('?', 3, b'\1', b'\1', 1), |
---|
119 | n/a | ('?', True, b'\1', b'\1', 0), |
---|
120 | n/a | ('?', [], b'\0', b'\0', 1), |
---|
121 | n/a | ('?', (1,), b'\1', b'\1', 1), |
---|
122 | n/a | ] |
---|
123 | n/a | |
---|
124 | n/a | for fmt, arg, big, lil, asy in tests: |
---|
125 | n/a | for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil), |
---|
126 | n/a | ('='+fmt, ISBIGENDIAN and big or lil)]: |
---|
127 | n/a | res = struct.pack(xfmt, arg) |
---|
128 | n/a | self.assertEqual(res, exp) |
---|
129 | n/a | self.assertEqual(struct.calcsize(xfmt), len(res)) |
---|
130 | n/a | rev = struct.unpack(xfmt, res)[0] |
---|
131 | n/a | if rev != arg: |
---|
132 | n/a | self.assertTrue(asy) |
---|
133 | n/a | |
---|
134 | n/a | def test_calcsize(self): |
---|
135 | n/a | expected_size = { |
---|
136 | n/a | 'b': 1, 'B': 1, |
---|
137 | n/a | 'h': 2, 'H': 2, |
---|
138 | n/a | 'i': 4, 'I': 4, |
---|
139 | n/a | 'l': 4, 'L': 4, |
---|
140 | n/a | 'q': 8, 'Q': 8, |
---|
141 | n/a | } |
---|
142 | n/a | |
---|
143 | n/a | # standard integer sizes |
---|
144 | n/a | for code, byteorder in iter_integer_formats(('=', '<', '>', '!')): |
---|
145 | n/a | format = byteorder+code |
---|
146 | n/a | size = struct.calcsize(format) |
---|
147 | n/a | self.assertEqual(size, expected_size[code]) |
---|
148 | n/a | |
---|
149 | n/a | # native integer sizes |
---|
150 | n/a | native_pairs = 'bB', 'hH', 'iI', 'lL', 'nN', 'qQ' |
---|
151 | n/a | for format_pair in native_pairs: |
---|
152 | n/a | for byteorder in '', '@': |
---|
153 | n/a | signed_size = struct.calcsize(byteorder + format_pair[0]) |
---|
154 | n/a | unsigned_size = struct.calcsize(byteorder + format_pair[1]) |
---|
155 | n/a | self.assertEqual(signed_size, unsigned_size) |
---|
156 | n/a | |
---|
157 | n/a | # bounds for native integer sizes |
---|
158 | n/a | self.assertEqual(struct.calcsize('b'), 1) |
---|
159 | n/a | self.assertLessEqual(2, struct.calcsize('h')) |
---|
160 | n/a | self.assertLessEqual(4, struct.calcsize('l')) |
---|
161 | n/a | self.assertLessEqual(struct.calcsize('h'), struct.calcsize('i')) |
---|
162 | n/a | self.assertLessEqual(struct.calcsize('i'), struct.calcsize('l')) |
---|
163 | n/a | self.assertLessEqual(8, struct.calcsize('q')) |
---|
164 | n/a | self.assertLessEqual(struct.calcsize('l'), struct.calcsize('q')) |
---|
165 | n/a | self.assertGreaterEqual(struct.calcsize('n'), struct.calcsize('i')) |
---|
166 | n/a | self.assertGreaterEqual(struct.calcsize('n'), struct.calcsize('P')) |
---|
167 | n/a | |
---|
168 | n/a | def test_integers(self): |
---|
169 | n/a | # Integer tests (bBhHiIlLqQnN). |
---|
170 | n/a | import binascii |
---|
171 | n/a | |
---|
172 | n/a | class IntTester(unittest.TestCase): |
---|
173 | n/a | def __init__(self, format): |
---|
174 | n/a | super(IntTester, self).__init__(methodName='test_one') |
---|
175 | n/a | self.format = format |
---|
176 | n/a | self.code = format[-1] |
---|
177 | n/a | self.byteorder = format[:-1] |
---|
178 | n/a | if not self.byteorder in byteorders: |
---|
179 | n/a | raise ValueError("unrecognized packing byteorder: %s" % |
---|
180 | n/a | self.byteorder) |
---|
181 | n/a | self.bytesize = struct.calcsize(format) |
---|
182 | n/a | self.bitsize = self.bytesize * 8 |
---|
183 | n/a | if self.code in tuple('bhilqn'): |
---|
184 | n/a | self.signed = True |
---|
185 | n/a | self.min_value = -(2**(self.bitsize-1)) |
---|
186 | n/a | self.max_value = 2**(self.bitsize-1) - 1 |
---|
187 | n/a | elif self.code in tuple('BHILQN'): |
---|
188 | n/a | self.signed = False |
---|
189 | n/a | self.min_value = 0 |
---|
190 | n/a | self.max_value = 2**self.bitsize - 1 |
---|
191 | n/a | else: |
---|
192 | n/a | raise ValueError("unrecognized format code: %s" % |
---|
193 | n/a | self.code) |
---|
194 | n/a | |
---|
195 | n/a | def test_one(self, x, pack=struct.pack, |
---|
196 | n/a | unpack=struct.unpack, |
---|
197 | n/a | unhexlify=binascii.unhexlify): |
---|
198 | n/a | |
---|
199 | n/a | format = self.format |
---|
200 | n/a | if self.min_value <= x <= self.max_value: |
---|
201 | n/a | expected = x |
---|
202 | n/a | if self.signed and x < 0: |
---|
203 | n/a | expected += 1 << self.bitsize |
---|
204 | n/a | self.assertGreaterEqual(expected, 0) |
---|
205 | n/a | expected = '%x' % expected |
---|
206 | n/a | if len(expected) & 1: |
---|
207 | n/a | expected = "0" + expected |
---|
208 | n/a | expected = expected.encode('ascii') |
---|
209 | n/a | expected = unhexlify(expected) |
---|
210 | n/a | expected = (b"\x00" * (self.bytesize - len(expected)) + |
---|
211 | n/a | expected) |
---|
212 | n/a | if (self.byteorder == '<' or |
---|
213 | n/a | self.byteorder in ('', '@', '=') and not ISBIGENDIAN): |
---|
214 | n/a | expected = string_reverse(expected) |
---|
215 | n/a | self.assertEqual(len(expected), self.bytesize) |
---|
216 | n/a | |
---|
217 | n/a | # Pack work? |
---|
218 | n/a | got = pack(format, x) |
---|
219 | n/a | self.assertEqual(got, expected) |
---|
220 | n/a | |
---|
221 | n/a | # Unpack work? |
---|
222 | n/a | retrieved = unpack(format, got)[0] |
---|
223 | n/a | self.assertEqual(x, retrieved) |
---|
224 | n/a | |
---|
225 | n/a | # Adding any byte should cause a "too big" error. |
---|
226 | n/a | self.assertRaises((struct.error, TypeError), unpack, format, |
---|
227 | n/a | b'\x01' + got) |
---|
228 | n/a | else: |
---|
229 | n/a | # x is out of range -- verify pack realizes that. |
---|
230 | n/a | self.assertRaises((OverflowError, ValueError, struct.error), |
---|
231 | n/a | pack, format, x) |
---|
232 | n/a | |
---|
233 | n/a | def run(self): |
---|
234 | n/a | from random import randrange |
---|
235 | n/a | |
---|
236 | n/a | # Create all interesting powers of 2. |
---|
237 | n/a | values = [] |
---|
238 | n/a | for exp in range(self.bitsize + 3): |
---|
239 | n/a | values.append(1 << exp) |
---|
240 | n/a | |
---|
241 | n/a | # Add some random values. |
---|
242 | n/a | for i in range(self.bitsize): |
---|
243 | n/a | val = 0 |
---|
244 | n/a | for j in range(self.bytesize): |
---|
245 | n/a | val = (val << 8) | randrange(256) |
---|
246 | n/a | values.append(val) |
---|
247 | n/a | |
---|
248 | n/a | # Values absorbed from other tests |
---|
249 | n/a | values.extend([300, 700000, sys.maxsize*4]) |
---|
250 | n/a | |
---|
251 | n/a | # Try all those, and their negations, and +-1 from |
---|
252 | n/a | # them. Note that this tests all power-of-2 |
---|
253 | n/a | # boundaries in range, and a few out of range, plus |
---|
254 | n/a | # +-(2**n +- 1). |
---|
255 | n/a | for base in values: |
---|
256 | n/a | for val in -base, base: |
---|
257 | n/a | for incr in -1, 0, 1: |
---|
258 | n/a | x = val + incr |
---|
259 | n/a | self.test_one(x) |
---|
260 | n/a | |
---|
261 | n/a | # Some error cases. |
---|
262 | n/a | class NotAnInt: |
---|
263 | n/a | def __int__(self): |
---|
264 | n/a | return 42 |
---|
265 | n/a | |
---|
266 | n/a | # Objects with an '__index__' method should be allowed |
---|
267 | n/a | # to pack as integers. That is assuming the implemented |
---|
268 | n/a | # '__index__' method returns an 'int'. |
---|
269 | n/a | class Indexable(object): |
---|
270 | n/a | def __init__(self, value): |
---|
271 | n/a | self._value = value |
---|
272 | n/a | |
---|
273 | n/a | def __index__(self): |
---|
274 | n/a | return self._value |
---|
275 | n/a | |
---|
276 | n/a | # If the '__index__' method raises a type error, then |
---|
277 | n/a | # '__int__' should be used with a deprecation warning. |
---|
278 | n/a | class BadIndex(object): |
---|
279 | n/a | def __index__(self): |
---|
280 | n/a | raise TypeError |
---|
281 | n/a | |
---|
282 | n/a | def __int__(self): |
---|
283 | n/a | return 42 |
---|
284 | n/a | |
---|
285 | n/a | self.assertRaises((TypeError, struct.error), |
---|
286 | n/a | struct.pack, self.format, |
---|
287 | n/a | "a string") |
---|
288 | n/a | self.assertRaises((TypeError, struct.error), |
---|
289 | n/a | struct.pack, self.format, |
---|
290 | n/a | randrange) |
---|
291 | n/a | self.assertRaises((TypeError, struct.error), |
---|
292 | n/a | struct.pack, self.format, |
---|
293 | n/a | 3+42j) |
---|
294 | n/a | self.assertRaises((TypeError, struct.error), |
---|
295 | n/a | struct.pack, self.format, |
---|
296 | n/a | NotAnInt()) |
---|
297 | n/a | self.assertRaises((TypeError, struct.error), |
---|
298 | n/a | struct.pack, self.format, |
---|
299 | n/a | BadIndex()) |
---|
300 | n/a | |
---|
301 | n/a | # Check for legitimate values from '__index__'. |
---|
302 | n/a | for obj in (Indexable(0), Indexable(10), Indexable(17), |
---|
303 | n/a | Indexable(42), Indexable(100), Indexable(127)): |
---|
304 | n/a | try: |
---|
305 | n/a | struct.pack(format, obj) |
---|
306 | n/a | except: |
---|
307 | n/a | self.fail("integer code pack failed on object " |
---|
308 | n/a | "with '__index__' method") |
---|
309 | n/a | |
---|
310 | n/a | # Check for bogus values from '__index__'. |
---|
311 | n/a | for obj in (Indexable(b'a'), Indexable('b'), Indexable(None), |
---|
312 | n/a | Indexable({'a': 1}), Indexable([1, 2, 3])): |
---|
313 | n/a | self.assertRaises((TypeError, struct.error), |
---|
314 | n/a | struct.pack, self.format, |
---|
315 | n/a | obj) |
---|
316 | n/a | |
---|
317 | n/a | for code, byteorder in iter_integer_formats(): |
---|
318 | n/a | format = byteorder+code |
---|
319 | n/a | t = IntTester(format) |
---|
320 | n/a | t.run() |
---|
321 | n/a | |
---|
322 | n/a | def test_nN_code(self): |
---|
323 | n/a | # n and N don't exist in standard sizes |
---|
324 | n/a | def assertStructError(func, *args, **kwargs): |
---|
325 | n/a | with self.assertRaises(struct.error) as cm: |
---|
326 | n/a | func(*args, **kwargs) |
---|
327 | n/a | self.assertIn("bad char in struct format", str(cm.exception)) |
---|
328 | n/a | for code in 'nN': |
---|
329 | n/a | for byteorder in ('=', '<', '>', '!'): |
---|
330 | n/a | format = byteorder+code |
---|
331 | n/a | assertStructError(struct.calcsize, format) |
---|
332 | n/a | assertStructError(struct.pack, format, 0) |
---|
333 | n/a | assertStructError(struct.unpack, format, b"") |
---|
334 | n/a | |
---|
335 | n/a | def test_p_code(self): |
---|
336 | n/a | # Test p ("Pascal string") code. |
---|
337 | n/a | for code, input, expected, expectedback in [ |
---|
338 | n/a | ('p', b'abc', b'\x00', b''), |
---|
339 | n/a | ('1p', b'abc', b'\x00', b''), |
---|
340 | n/a | ('2p', b'abc', b'\x01a', b'a'), |
---|
341 | n/a | ('3p', b'abc', b'\x02ab', b'ab'), |
---|
342 | n/a | ('4p', b'abc', b'\x03abc', b'abc'), |
---|
343 | n/a | ('5p', b'abc', b'\x03abc\x00', b'abc'), |
---|
344 | n/a | ('6p', b'abc', b'\x03abc\x00\x00', b'abc'), |
---|
345 | n/a | ('1000p', b'x'*1000, b'\xff' + b'x'*999, b'x'*255)]: |
---|
346 | n/a | got = struct.pack(code, input) |
---|
347 | n/a | self.assertEqual(got, expected) |
---|
348 | n/a | (got,) = struct.unpack(code, got) |
---|
349 | n/a | self.assertEqual(got, expectedback) |
---|
350 | n/a | |
---|
351 | n/a | def test_705836(self): |
---|
352 | n/a | # SF bug 705836. "<f" and ">f" had a severe rounding bug, where a carry |
---|
353 | n/a | # from the low-order discarded bits could propagate into the exponent |
---|
354 | n/a | # field, causing the result to be wrong by a factor of 2. |
---|
355 | n/a | for base in range(1, 33): |
---|
356 | n/a | # smaller <- largest representable float less than base. |
---|
357 | n/a | delta = 0.5 |
---|
358 | n/a | while base - delta / 2.0 != base: |
---|
359 | n/a | delta /= 2.0 |
---|
360 | n/a | smaller = base - delta |
---|
361 | n/a | # Packing this rounds away a solid string of trailing 1 bits. |
---|
362 | n/a | packed = struct.pack("<f", smaller) |
---|
363 | n/a | unpacked = struct.unpack("<f", packed)[0] |
---|
364 | n/a | # This failed at base = 2, 4, and 32, with unpacked = 1, 2, and |
---|
365 | n/a | # 16, respectively. |
---|
366 | n/a | self.assertEqual(base, unpacked) |
---|
367 | n/a | bigpacked = struct.pack(">f", smaller) |
---|
368 | n/a | self.assertEqual(bigpacked, string_reverse(packed)) |
---|
369 | n/a | unpacked = struct.unpack(">f", bigpacked)[0] |
---|
370 | n/a | self.assertEqual(base, unpacked) |
---|
371 | n/a | |
---|
372 | n/a | # Largest finite IEEE single. |
---|
373 | n/a | big = (1 << 24) - 1 |
---|
374 | n/a | big = math.ldexp(big, 127 - 23) |
---|
375 | n/a | packed = struct.pack(">f", big) |
---|
376 | n/a | unpacked = struct.unpack(">f", packed)[0] |
---|
377 | n/a | self.assertEqual(big, unpacked) |
---|
378 | n/a | |
---|
379 | n/a | # The same, but tack on a 1 bit so it rounds up to infinity. |
---|
380 | n/a | big = (1 << 25) - 1 |
---|
381 | n/a | big = math.ldexp(big, 127 - 24) |
---|
382 | n/a | self.assertRaises(OverflowError, struct.pack, ">f", big) |
---|
383 | n/a | |
---|
384 | n/a | def test_1530559(self): |
---|
385 | n/a | for code, byteorder in iter_integer_formats(): |
---|
386 | n/a | format = byteorder + code |
---|
387 | n/a | self.assertRaises(struct.error, struct.pack, format, 1.0) |
---|
388 | n/a | self.assertRaises(struct.error, struct.pack, format, 1.5) |
---|
389 | n/a | self.assertRaises(struct.error, struct.pack, 'P', 1.0) |
---|
390 | n/a | self.assertRaises(struct.error, struct.pack, 'P', 1.5) |
---|
391 | n/a | |
---|
392 | n/a | def test_unpack_from(self): |
---|
393 | n/a | test_string = b'abcd01234' |
---|
394 | n/a | fmt = '4s' |
---|
395 | n/a | s = struct.Struct(fmt) |
---|
396 | n/a | for cls in (bytes, bytearray): |
---|
397 | n/a | data = cls(test_string) |
---|
398 | n/a | self.assertEqual(s.unpack_from(data), (b'abcd',)) |
---|
399 | n/a | self.assertEqual(s.unpack_from(data, 2), (b'cd01',)) |
---|
400 | n/a | self.assertEqual(s.unpack_from(data, 4), (b'0123',)) |
---|
401 | n/a | for i in range(6): |
---|
402 | n/a | self.assertEqual(s.unpack_from(data, i), (data[i:i+4],)) |
---|
403 | n/a | for i in range(6, len(test_string) + 1): |
---|
404 | n/a | self.assertRaises(struct.error, s.unpack_from, data, i) |
---|
405 | n/a | for cls in (bytes, bytearray): |
---|
406 | n/a | data = cls(test_string) |
---|
407 | n/a | self.assertEqual(struct.unpack_from(fmt, data), (b'abcd',)) |
---|
408 | n/a | self.assertEqual(struct.unpack_from(fmt, data, 2), (b'cd01',)) |
---|
409 | n/a | self.assertEqual(struct.unpack_from(fmt, data, 4), (b'0123',)) |
---|
410 | n/a | for i in range(6): |
---|
411 | n/a | self.assertEqual(struct.unpack_from(fmt, data, i), (data[i:i+4],)) |
---|
412 | n/a | for i in range(6, len(test_string) + 1): |
---|
413 | n/a | self.assertRaises(struct.error, struct.unpack_from, fmt, data, i) |
---|
414 | n/a | |
---|
415 | n/a | # keyword arguments |
---|
416 | n/a | self.assertEqual(s.unpack_from(buffer=test_string, offset=2), |
---|
417 | n/a | (b'cd01',)) |
---|
418 | n/a | |
---|
419 | n/a | def test_pack_into(self): |
---|
420 | n/a | test_string = b'Reykjavik rocks, eow!' |
---|
421 | n/a | writable_buf = array.array('b', b' '*100) |
---|
422 | n/a | fmt = '21s' |
---|
423 | n/a | s = struct.Struct(fmt) |
---|
424 | n/a | |
---|
425 | n/a | # Test without offset |
---|
426 | n/a | s.pack_into(writable_buf, 0, test_string) |
---|
427 | n/a | from_buf = writable_buf.tobytes()[:len(test_string)] |
---|
428 | n/a | self.assertEqual(from_buf, test_string) |
---|
429 | n/a | |
---|
430 | n/a | # Test with offset. |
---|
431 | n/a | s.pack_into(writable_buf, 10, test_string) |
---|
432 | n/a | from_buf = writable_buf.tobytes()[:len(test_string)+10] |
---|
433 | n/a | self.assertEqual(from_buf, test_string[:10] + test_string) |
---|
434 | n/a | |
---|
435 | n/a | # Go beyond boundaries. |
---|
436 | n/a | small_buf = array.array('b', b' '*10) |
---|
437 | n/a | self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 0, |
---|
438 | n/a | test_string) |
---|
439 | n/a | self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 2, |
---|
440 | n/a | test_string) |
---|
441 | n/a | |
---|
442 | n/a | # Test bogus offset (issue 3694) |
---|
443 | n/a | sb = small_buf |
---|
444 | n/a | self.assertRaises((TypeError, struct.error), struct.pack_into, b'', sb, |
---|
445 | n/a | None) |
---|
446 | n/a | |
---|
447 | n/a | def test_pack_into_fn(self): |
---|
448 | n/a | test_string = b'Reykjavik rocks, eow!' |
---|
449 | n/a | writable_buf = array.array('b', b' '*100) |
---|
450 | n/a | fmt = '21s' |
---|
451 | n/a | pack_into = lambda *args: struct.pack_into(fmt, *args) |
---|
452 | n/a | |
---|
453 | n/a | # Test without offset. |
---|
454 | n/a | pack_into(writable_buf, 0, test_string) |
---|
455 | n/a | from_buf = writable_buf.tobytes()[:len(test_string)] |
---|
456 | n/a | self.assertEqual(from_buf, test_string) |
---|
457 | n/a | |
---|
458 | n/a | # Test with offset. |
---|
459 | n/a | pack_into(writable_buf, 10, test_string) |
---|
460 | n/a | from_buf = writable_buf.tobytes()[:len(test_string)+10] |
---|
461 | n/a | self.assertEqual(from_buf, test_string[:10] + test_string) |
---|
462 | n/a | |
---|
463 | n/a | # Go beyond boundaries. |
---|
464 | n/a | small_buf = array.array('b', b' '*10) |
---|
465 | n/a | self.assertRaises((ValueError, struct.error), pack_into, small_buf, 0, |
---|
466 | n/a | test_string) |
---|
467 | n/a | self.assertRaises((ValueError, struct.error), pack_into, small_buf, 2, |
---|
468 | n/a | test_string) |
---|
469 | n/a | |
---|
470 | n/a | def test_unpack_with_buffer(self): |
---|
471 | n/a | # SF bug 1563759: struct.unpack doesn't support buffer protocol objects |
---|
472 | n/a | data1 = array.array('B', b'\x12\x34\x56\x78') |
---|
473 | n/a | data2 = memoryview(b'\x12\x34\x56\x78') # XXX b'......XXXX......', 6, 4 |
---|
474 | n/a | for data in [data1, data2]: |
---|
475 | n/a | value, = struct.unpack('>I', data) |
---|
476 | n/a | self.assertEqual(value, 0x12345678) |
---|
477 | n/a | |
---|
478 | n/a | def test_bool(self): |
---|
479 | n/a | class ExplodingBool(object): |
---|
480 | n/a | def __bool__(self): |
---|
481 | n/a | raise OSError |
---|
482 | n/a | for prefix in tuple("<>!=")+('',): |
---|
483 | n/a | false = (), [], [], '', 0 |
---|
484 | n/a | true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2 |
---|
485 | n/a | |
---|
486 | n/a | falseFormat = prefix + '?' * len(false) |
---|
487 | n/a | packedFalse = struct.pack(falseFormat, *false) |
---|
488 | n/a | unpackedFalse = struct.unpack(falseFormat, packedFalse) |
---|
489 | n/a | |
---|
490 | n/a | trueFormat = prefix + '?' * len(true) |
---|
491 | n/a | packedTrue = struct.pack(trueFormat, *true) |
---|
492 | n/a | unpackedTrue = struct.unpack(trueFormat, packedTrue) |
---|
493 | n/a | |
---|
494 | n/a | self.assertEqual(len(true), len(unpackedTrue)) |
---|
495 | n/a | self.assertEqual(len(false), len(unpackedFalse)) |
---|
496 | n/a | |
---|
497 | n/a | for t in unpackedFalse: |
---|
498 | n/a | self.assertFalse(t) |
---|
499 | n/a | for t in unpackedTrue: |
---|
500 | n/a | self.assertTrue(t) |
---|
501 | n/a | |
---|
502 | n/a | packed = struct.pack(prefix+'?', 1) |
---|
503 | n/a | |
---|
504 | n/a | self.assertEqual(len(packed), struct.calcsize(prefix+'?')) |
---|
505 | n/a | |
---|
506 | n/a | if len(packed) != 1: |
---|
507 | n/a | self.assertFalse(prefix, msg='encoded bool is not one byte: %r' |
---|
508 | n/a | %packed) |
---|
509 | n/a | |
---|
510 | n/a | try: |
---|
511 | n/a | struct.pack(prefix + '?', ExplodingBool()) |
---|
512 | n/a | except OSError: |
---|
513 | n/a | pass |
---|
514 | n/a | else: |
---|
515 | n/a | self.fail("Expected OSError: struct.pack(%r, " |
---|
516 | n/a | "ExplodingBool())" % (prefix + '?')) |
---|
517 | n/a | |
---|
518 | n/a | for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']: |
---|
519 | n/a | self.assertTrue(struct.unpack('>?', c)[0]) |
---|
520 | n/a | |
---|
521 | n/a | def test_count_overflow(self): |
---|
522 | n/a | hugecount = '{}b'.format(sys.maxsize+1) |
---|
523 | n/a | self.assertRaises(struct.error, struct.calcsize, hugecount) |
---|
524 | n/a | |
---|
525 | n/a | hugecount2 = '{}b{}H'.format(sys.maxsize//2, sys.maxsize//2) |
---|
526 | n/a | self.assertRaises(struct.error, struct.calcsize, hugecount2) |
---|
527 | n/a | |
---|
528 | n/a | def test_trailing_counter(self): |
---|
529 | n/a | store = array.array('b', b' '*100) |
---|
530 | n/a | |
---|
531 | n/a | # format lists containing only count spec should result in an error |
---|
532 | n/a | self.assertRaises(struct.error, struct.pack, '12345') |
---|
533 | n/a | self.assertRaises(struct.error, struct.unpack, '12345', b'') |
---|
534 | n/a | self.assertRaises(struct.error, struct.pack_into, '12345', store, 0) |
---|
535 | n/a | self.assertRaises(struct.error, struct.unpack_from, '12345', store, 0) |
---|
536 | n/a | |
---|
537 | n/a | # Format lists with trailing count spec should result in an error |
---|
538 | n/a | self.assertRaises(struct.error, struct.pack, 'c12345', 'x') |
---|
539 | n/a | self.assertRaises(struct.error, struct.unpack, 'c12345', b'x') |
---|
540 | n/a | self.assertRaises(struct.error, struct.pack_into, 'c12345', store, 0, |
---|
541 | n/a | 'x') |
---|
542 | n/a | self.assertRaises(struct.error, struct.unpack_from, 'c12345', store, |
---|
543 | n/a | 0) |
---|
544 | n/a | |
---|
545 | n/a | # Mixed format tests |
---|
546 | n/a | self.assertRaises(struct.error, struct.pack, '14s42', 'spam and eggs') |
---|
547 | n/a | self.assertRaises(struct.error, struct.unpack, '14s42', |
---|
548 | n/a | b'spam and eggs') |
---|
549 | n/a | self.assertRaises(struct.error, struct.pack_into, '14s42', store, 0, |
---|
550 | n/a | 'spam and eggs') |
---|
551 | n/a | self.assertRaises(struct.error, struct.unpack_from, '14s42', store, 0) |
---|
552 | n/a | |
---|
553 | n/a | def test_Struct_reinitialization(self): |
---|
554 | n/a | # Issue 9422: there was a memory leak when reinitializing a |
---|
555 | n/a | # Struct instance. This test can be used to detect the leak |
---|
556 | n/a | # when running with regrtest -L. |
---|
557 | n/a | s = struct.Struct('i') |
---|
558 | n/a | s.__init__('ii') |
---|
559 | n/a | |
---|
560 | n/a | def check_sizeof(self, format_str, number_of_codes): |
---|
561 | n/a | # The size of 'PyStructObject' |
---|
562 | n/a | totalsize = support.calcobjsize('2n3P') |
---|
563 | n/a | # The size taken up by the 'formatcode' dynamic array |
---|
564 | n/a | totalsize += struct.calcsize('P3n0P') * (number_of_codes + 1) |
---|
565 | n/a | support.check_sizeof(self, struct.Struct(format_str), totalsize) |
---|
566 | n/a | |
---|
567 | n/a | @support.cpython_only |
---|
568 | n/a | def test__sizeof__(self): |
---|
569 | n/a | for code in integer_codes: |
---|
570 | n/a | self.check_sizeof(code, 1) |
---|
571 | n/a | self.check_sizeof('BHILfdspP', 9) |
---|
572 | n/a | self.check_sizeof('B' * 1234, 1234) |
---|
573 | n/a | self.check_sizeof('fd', 2) |
---|
574 | n/a | self.check_sizeof('xxxxxxxxxxxxxx', 0) |
---|
575 | n/a | self.check_sizeof('100H', 1) |
---|
576 | n/a | self.check_sizeof('187s', 1) |
---|
577 | n/a | self.check_sizeof('20p', 1) |
---|
578 | n/a | self.check_sizeof('0s', 1) |
---|
579 | n/a | self.check_sizeof('0c', 0) |
---|
580 | n/a | |
---|
581 | n/a | |
---|
582 | n/a | class UnpackIteratorTest(unittest.TestCase): |
---|
583 | n/a | """ |
---|
584 | n/a | Tests for iterative unpacking (struct.Struct.iter_unpack). |
---|
585 | n/a | """ |
---|
586 | n/a | |
---|
587 | n/a | def test_construct(self): |
---|
588 | n/a | def _check_iterator(it): |
---|
589 | n/a | self.assertIsInstance(it, abc.Iterator) |
---|
590 | n/a | self.assertIsInstance(it, abc.Iterable) |
---|
591 | n/a | s = struct.Struct('>ibcp') |
---|
592 | n/a | it = s.iter_unpack(b"") |
---|
593 | n/a | _check_iterator(it) |
---|
594 | n/a | it = s.iter_unpack(b"1234567") |
---|
595 | n/a | _check_iterator(it) |
---|
596 | n/a | # Wrong bytes length |
---|
597 | n/a | with self.assertRaises(struct.error): |
---|
598 | n/a | s.iter_unpack(b"123456") |
---|
599 | n/a | with self.assertRaises(struct.error): |
---|
600 | n/a | s.iter_unpack(b"12345678") |
---|
601 | n/a | # Zero-length struct |
---|
602 | n/a | s = struct.Struct('>') |
---|
603 | n/a | with self.assertRaises(struct.error): |
---|
604 | n/a | s.iter_unpack(b"") |
---|
605 | n/a | with self.assertRaises(struct.error): |
---|
606 | n/a | s.iter_unpack(b"12") |
---|
607 | n/a | |
---|
608 | n/a | def test_iterate(self): |
---|
609 | n/a | s = struct.Struct('>IB') |
---|
610 | n/a | b = bytes(range(1, 16)) |
---|
611 | n/a | it = s.iter_unpack(b) |
---|
612 | n/a | self.assertEqual(next(it), (0x01020304, 5)) |
---|
613 | n/a | self.assertEqual(next(it), (0x06070809, 10)) |
---|
614 | n/a | self.assertEqual(next(it), (0x0b0c0d0e, 15)) |
---|
615 | n/a | self.assertRaises(StopIteration, next, it) |
---|
616 | n/a | self.assertRaises(StopIteration, next, it) |
---|
617 | n/a | |
---|
618 | n/a | def test_arbitrary_buffer(self): |
---|
619 | n/a | s = struct.Struct('>IB') |
---|
620 | n/a | b = bytes(range(1, 11)) |
---|
621 | n/a | it = s.iter_unpack(memoryview(b)) |
---|
622 | n/a | self.assertEqual(next(it), (0x01020304, 5)) |
---|
623 | n/a | self.assertEqual(next(it), (0x06070809, 10)) |
---|
624 | n/a | self.assertRaises(StopIteration, next, it) |
---|
625 | n/a | self.assertRaises(StopIteration, next, it) |
---|
626 | n/a | |
---|
627 | n/a | def test_length_hint(self): |
---|
628 | n/a | lh = operator.length_hint |
---|
629 | n/a | s = struct.Struct('>IB') |
---|
630 | n/a | b = bytes(range(1, 16)) |
---|
631 | n/a | it = s.iter_unpack(b) |
---|
632 | n/a | self.assertEqual(lh(it), 3) |
---|
633 | n/a | next(it) |
---|
634 | n/a | self.assertEqual(lh(it), 2) |
---|
635 | n/a | next(it) |
---|
636 | n/a | self.assertEqual(lh(it), 1) |
---|
637 | n/a | next(it) |
---|
638 | n/a | self.assertEqual(lh(it), 0) |
---|
639 | n/a | self.assertRaises(StopIteration, next, it) |
---|
640 | n/a | self.assertEqual(lh(it), 0) |
---|
641 | n/a | |
---|
642 | n/a | def test_module_func(self): |
---|
643 | n/a | # Sanity check for the global struct.iter_unpack() |
---|
644 | n/a | it = struct.iter_unpack('>IB', bytes(range(1, 11))) |
---|
645 | n/a | self.assertEqual(next(it), (0x01020304, 5)) |
---|
646 | n/a | self.assertEqual(next(it), (0x06070809, 10)) |
---|
647 | n/a | self.assertRaises(StopIteration, next, it) |
---|
648 | n/a | self.assertRaises(StopIteration, next, it) |
---|
649 | n/a | |
---|
650 | n/a | def test_half_float(self): |
---|
651 | n/a | # Little-endian examples from: |
---|
652 | n/a | # http://en.wikipedia.org/wiki/Half_precision_floating-point_format |
---|
653 | n/a | format_bits_float__cleanRoundtrip_list = [ |
---|
654 | n/a | (b'\x00\x3c', 1.0), |
---|
655 | n/a | (b'\x00\xc0', -2.0), |
---|
656 | n/a | (b'\xff\x7b', 65504.0), # (max half precision) |
---|
657 | n/a | (b'\x00\x04', 2**-14), # ~= 6.10352 * 10**-5 (min pos normal) |
---|
658 | n/a | (b'\x01\x00', 2**-24), # ~= 5.96046 * 10**-8 (min pos subnormal) |
---|
659 | n/a | (b'\x00\x00', 0.0), |
---|
660 | n/a | (b'\x00\x80', -0.0), |
---|
661 | n/a | (b'\x00\x7c', float('+inf')), |
---|
662 | n/a | (b'\x00\xfc', float('-inf')), |
---|
663 | n/a | (b'\x55\x35', 0.333251953125), # ~= 1/3 |
---|
664 | n/a | ] |
---|
665 | n/a | |
---|
666 | n/a | for le_bits, f in format_bits_float__cleanRoundtrip_list: |
---|
667 | n/a | be_bits = le_bits[::-1] |
---|
668 | n/a | self.assertEqual(f, struct.unpack('<e', le_bits)[0]) |
---|
669 | n/a | self.assertEqual(le_bits, struct.pack('<e', f)) |
---|
670 | n/a | self.assertEqual(f, struct.unpack('>e', be_bits)[0]) |
---|
671 | n/a | self.assertEqual(be_bits, struct.pack('>e', f)) |
---|
672 | n/a | if sys.byteorder == 'little': |
---|
673 | n/a | self.assertEqual(f, struct.unpack('e', le_bits)[0]) |
---|
674 | n/a | self.assertEqual(le_bits, struct.pack('e', f)) |
---|
675 | n/a | else: |
---|
676 | n/a | self.assertEqual(f, struct.unpack('e', be_bits)[0]) |
---|
677 | n/a | self.assertEqual(be_bits, struct.pack('e', f)) |
---|
678 | n/a | |
---|
679 | n/a | # Check for NaN handling: |
---|
680 | n/a | format_bits__nan_list = [ |
---|
681 | n/a | ('<e', b'\x01\xfc'), |
---|
682 | n/a | ('<e', b'\x00\xfe'), |
---|
683 | n/a | ('<e', b'\xff\xff'), |
---|
684 | n/a | ('<e', b'\x01\x7c'), |
---|
685 | n/a | ('<e', b'\x00\x7e'), |
---|
686 | n/a | ('<e', b'\xff\x7f'), |
---|
687 | n/a | ] |
---|
688 | n/a | |
---|
689 | n/a | for formatcode, bits in format_bits__nan_list: |
---|
690 | n/a | self.assertTrue(math.isnan(struct.unpack('<e', bits)[0])) |
---|
691 | n/a | self.assertTrue(math.isnan(struct.unpack('>e', bits[::-1])[0])) |
---|
692 | n/a | |
---|
693 | n/a | # Check that packing produces a bit pattern representing a quiet NaN: |
---|
694 | n/a | # all exponent bits and the msb of the fraction should all be 1. |
---|
695 | n/a | packed = struct.pack('<e', math.nan) |
---|
696 | n/a | self.assertEqual(packed[1] & 0x7e, 0x7e) |
---|
697 | n/a | packed = struct.pack('<e', -math.nan) |
---|
698 | n/a | self.assertEqual(packed[1] & 0x7e, 0x7e) |
---|
699 | n/a | |
---|
700 | n/a | # Checks for round-to-even behavior |
---|
701 | n/a | format_bits_float__rounding_list = [ |
---|
702 | n/a | ('>e', b'\x00\x01', 2.0**-25 + 2.0**-35), # Rounds to minimum subnormal |
---|
703 | n/a | ('>e', b'\x00\x00', 2.0**-25), # Underflows to zero (nearest even mode) |
---|
704 | n/a | ('>e', b'\x00\x00', 2.0**-26), # Underflows to zero |
---|
705 | n/a | ('>e', b'\x03\xff', 2.0**-14 - 2.0**-24), # Largest subnormal. |
---|
706 | n/a | ('>e', b'\x03\xff', 2.0**-14 - 2.0**-25 - 2.0**-65), |
---|
707 | n/a | ('>e', b'\x04\x00', 2.0**-14 - 2.0**-25), |
---|
708 | n/a | ('>e', b'\x04\x00', 2.0**-14), # Smallest normal. |
---|
709 | n/a | ('>e', b'\x3c\x01', 1.0+2.0**-11 + 2.0**-16), # rounds to 1.0+2**(-10) |
---|
710 | n/a | ('>e', b'\x3c\x00', 1.0+2.0**-11), # rounds to 1.0 (nearest even mode) |
---|
711 | n/a | ('>e', b'\x3c\x00', 1.0+2.0**-12), # rounds to 1.0 |
---|
712 | n/a | ('>e', b'\x7b\xff', 65504), # largest normal |
---|
713 | n/a | ('>e', b'\x7b\xff', 65519), # rounds to 65504 |
---|
714 | n/a | ('>e', b'\x80\x01', -2.0**-25 - 2.0**-35), # Rounds to minimum subnormal |
---|
715 | n/a | ('>e', b'\x80\x00', -2.0**-25), # Underflows to zero (nearest even mode) |
---|
716 | n/a | ('>e', b'\x80\x00', -2.0**-26), # Underflows to zero |
---|
717 | n/a | ('>e', b'\xbc\x01', -1.0-2.0**-11 - 2.0**-16), # rounds to 1.0+2**(-10) |
---|
718 | n/a | ('>e', b'\xbc\x00', -1.0-2.0**-11), # rounds to 1.0 (nearest even mode) |
---|
719 | n/a | ('>e', b'\xbc\x00', -1.0-2.0**-12), # rounds to 1.0 |
---|
720 | n/a | ('>e', b'\xfb\xff', -65519), # rounds to 65504 |
---|
721 | n/a | ] |
---|
722 | n/a | |
---|
723 | n/a | for formatcode, bits, f in format_bits_float__rounding_list: |
---|
724 | n/a | self.assertEqual(bits, struct.pack(formatcode, f)) |
---|
725 | n/a | |
---|
726 | n/a | # This overflows, and so raises an error |
---|
727 | n/a | format_bits_float__roundingError_list = [ |
---|
728 | n/a | # Values that round to infinity. |
---|
729 | n/a | ('>e', 65520.0), |
---|
730 | n/a | ('>e', 65536.0), |
---|
731 | n/a | ('>e', 1e300), |
---|
732 | n/a | ('>e', -65520.0), |
---|
733 | n/a | ('>e', -65536.0), |
---|
734 | n/a | ('>e', -1e300), |
---|
735 | n/a | ('<e', 65520.0), |
---|
736 | n/a | ('<e', 65536.0), |
---|
737 | n/a | ('<e', 1e300), |
---|
738 | n/a | ('<e', -65520.0), |
---|
739 | n/a | ('<e', -65536.0), |
---|
740 | n/a | ('<e', -1e300), |
---|
741 | n/a | ] |
---|
742 | n/a | |
---|
743 | n/a | for formatcode, f in format_bits_float__roundingError_list: |
---|
744 | n/a | self.assertRaises(OverflowError, struct.pack, formatcode, f) |
---|
745 | n/a | |
---|
746 | n/a | # Double rounding |
---|
747 | n/a | format_bits_float__doubleRoundingError_list = [ |
---|
748 | n/a | ('>e', b'\x67\xff', 0x1ffdffffff * 2**-26), # should be 2047, if double-rounded 64>32>16, becomes 2048 |
---|
749 | n/a | ] |
---|
750 | n/a | |
---|
751 | n/a | for formatcode, bits, f in format_bits_float__doubleRoundingError_list: |
---|
752 | n/a | self.assertEqual(bits, struct.pack(formatcode, f)) |
---|
753 | n/a | |
---|
754 | n/a | |
---|
755 | n/a | if __name__ == '__main__': |
---|
756 | n/a | unittest.main() |
---|