2010-03-20 19:21:02 -03:00
|
|
|
import os
|
2006-05-26 09:03:27 -03:00
|
|
|
import array
|
2008-06-10 22:31:28 -03:00
|
|
|
import unittest
|
|
|
|
import struct
|
2010-03-20 19:21:02 -03:00
|
|
|
import inspect
|
2012-07-29 11:30:50 -03:00
|
|
|
from test import test_support as support
|
|
|
|
from test.test_support import (check_warnings, check_py3k_warnings)
|
2008-06-10 22:31:28 -03:00
|
|
|
|
2001-06-13 19:45:27 -03:00
|
|
|
import sys
|
|
|
|
ISBIGENDIAN = sys.byteorder == "big"
|
2008-08-22 21:59:14 -03:00
|
|
|
IS32BIT = sys.maxsize == 0x7fffffff
|
2009-07-07 11:15:45 -03:00
|
|
|
|
|
|
|
integer_codes = 'b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q'
|
|
|
|
|
2010-03-20 19:21:02 -03:00
|
|
|
testmod_filename = os.path.splitext(__file__)[0] + '.py'
|
2009-07-07 11:15:45 -03:00
|
|
|
# Native 'q' packing isn't available on systems that don't have the C
|
|
|
|
# long long type.
|
|
|
|
try:
|
|
|
|
struct.pack('q', 5)
|
|
|
|
except struct.error:
|
|
|
|
HAVE_LONG_LONG = False
|
|
|
|
else:
|
|
|
|
HAVE_LONG_LONG = True
|
2001-06-13 19:45:27 -03:00
|
|
|
|
|
|
|
def string_reverse(s):
|
2006-06-05 17:48:49 -03:00
|
|
|
return "".join(reversed(s))
|
2001-06-13 19:45:27 -03:00
|
|
|
|
|
|
|
def bigendian_to_native(value):
|
|
|
|
if ISBIGENDIAN:
|
|
|
|
return value
|
|
|
|
else:
|
|
|
|
return string_reverse(value)
|
|
|
|
|
2008-06-10 22:31:28 -03:00
|
|
|
class StructTest(unittest.TestCase):
|
|
|
|
|
|
|
|
def check_float_coerce(self, format, number):
|
2010-03-07 12:24:45 -04:00
|
|
|
# SF bug 1530559. struct.pack raises TypeError where it used
|
|
|
|
# to convert.
|
2010-03-20 19:21:02 -03:00
|
|
|
with check_warnings((".*integer argument expected, got float",
|
|
|
|
DeprecationWarning)) as w:
|
2010-03-07 12:24:45 -04:00
|
|
|
got = struct.pack(format, number)
|
2010-03-20 19:21:02 -03:00
|
|
|
lineno = inspect.currentframe().f_lineno - 1
|
|
|
|
self.assertEqual(w.filename, testmod_filename)
|
|
|
|
self.assertEqual(w.lineno, lineno)
|
|
|
|
self.assertEqual(len(w.warnings), 1)
|
2010-03-07 12:24:45 -04:00
|
|
|
expected = struct.pack(format, int(number))
|
|
|
|
self.assertEqual(got, expected)
|
2008-06-10 22:31:28 -03:00
|
|
|
|
|
|
|
def test_isbigendian(self):
|
|
|
|
self.assertEqual((struct.pack('=i', 1)[0] == chr(0)), ISBIGENDIAN)
|
|
|
|
|
|
|
|
def test_consistence(self):
|
|
|
|
self.assertRaises(struct.error, struct.calcsize, 'Z')
|
|
|
|
|
|
|
|
sz = struct.calcsize('i')
|
|
|
|
self.assertEqual(sz * 3, struct.calcsize('iii'))
|
|
|
|
|
|
|
|
fmt = 'cbxxxxxxhhhhiillffd?'
|
|
|
|
fmt3 = '3c3b18x12h6i6l6f3d3?'
|
|
|
|
sz = struct.calcsize(fmt)
|
|
|
|
sz3 = struct.calcsize(fmt3)
|
|
|
|
self.assertEqual(sz * 3, sz3)
|
|
|
|
|
|
|
|
self.assertRaises(struct.error, struct.pack, 'iii', 3)
|
|
|
|
self.assertRaises(struct.error, struct.pack, 'i', 3, 3, 3)
|
2010-07-09 10:33:03 -03:00
|
|
|
self.assertRaises((TypeError, struct.error), struct.pack, 'i', 'foo')
|
|
|
|
self.assertRaises((TypeError, struct.error), struct.pack, 'P', 'foo')
|
2008-06-10 22:31:28 -03:00
|
|
|
self.assertRaises(struct.error, struct.unpack, 'd', 'flap')
|
|
|
|
s = struct.pack('ii', 1, 2)
|
|
|
|
self.assertRaises(struct.error, struct.unpack, 'iii', s)
|
|
|
|
self.assertRaises(struct.error, struct.unpack, 'i', s)
|
|
|
|
|
|
|
|
def test_transitiveness(self):
|
|
|
|
c = 'a'
|
|
|
|
b = 1
|
|
|
|
h = 255
|
|
|
|
i = 65535
|
|
|
|
l = 65536
|
|
|
|
f = 3.1415
|
|
|
|
d = 3.1415
|
|
|
|
t = True
|
|
|
|
|
|
|
|
for prefix in ('', '@', '<', '>', '=', '!'):
|
|
|
|
for format in ('xcbhilfd?', 'xcBHILfd?'):
|
|
|
|
format = prefix + format
|
|
|
|
s = struct.pack(format, c, b, h, i, l, f, d, t)
|
|
|
|
cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s)
|
|
|
|
self.assertEqual(cp, c)
|
|
|
|
self.assertEqual(bp, b)
|
|
|
|
self.assertEqual(hp, h)
|
|
|
|
self.assertEqual(ip, i)
|
|
|
|
self.assertEqual(lp, l)
|
|
|
|
self.assertEqual(int(100 * fp), int(100 * f))
|
|
|
|
self.assertEqual(int(100 * dp), int(100 * d))
|
|
|
|
self.assertEqual(tp, t)
|
|
|
|
|
|
|
|
def test_new_features(self):
|
|
|
|
# Test some of the new features in detail
|
|
|
|
# (format, argument, big-endian result, little-endian result, asymmetric)
|
|
|
|
tests = [
|
|
|
|
('c', 'a', 'a', 'a', 0),
|
|
|
|
('xc', 'a', '\0a', '\0a', 0),
|
|
|
|
('cx', 'a', 'a\0', 'a\0', 0),
|
|
|
|
('s', 'a', 'a', 'a', 0),
|
|
|
|
('0s', 'helloworld', '', '', 1),
|
|
|
|
('1s', 'helloworld', 'h', 'h', 1),
|
|
|
|
('9s', 'helloworld', 'helloworl', 'helloworl', 1),
|
|
|
|
('10s', 'helloworld', 'helloworld', 'helloworld', 0),
|
|
|
|
('11s', 'helloworld', 'helloworld\0', 'helloworld\0', 1),
|
|
|
|
('20s', 'helloworld', 'helloworld'+10*'\0', 'helloworld'+10*'\0', 1),
|
|
|
|
('b', 7, '\7', '\7', 0),
|
|
|
|
('b', -7, '\371', '\371', 0),
|
|
|
|
('B', 7, '\7', '\7', 0),
|
|
|
|
('B', 249, '\371', '\371', 0),
|
|
|
|
('h', 700, '\002\274', '\274\002', 0),
|
|
|
|
('h', -700, '\375D', 'D\375', 0),
|
|
|
|
('H', 700, '\002\274', '\274\002', 0),
|
|
|
|
('H', 0x10000-700, '\375D', 'D\375', 0),
|
|
|
|
('i', 70000000, '\004,\035\200', '\200\035,\004', 0),
|
|
|
|
('i', -70000000, '\373\323\342\200', '\200\342\323\373', 0),
|
|
|
|
('I', 70000000L, '\004,\035\200', '\200\035,\004', 0),
|
|
|
|
('I', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0),
|
|
|
|
('l', 70000000, '\004,\035\200', '\200\035,\004', 0),
|
|
|
|
('l', -70000000, '\373\323\342\200', '\200\342\323\373', 0),
|
|
|
|
('L', 70000000L, '\004,\035\200', '\200\035,\004', 0),
|
|
|
|
('L', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0),
|
|
|
|
('f', 2.0, '@\000\000\000', '\000\000\000@', 0),
|
|
|
|
('d', 2.0, '@\000\000\000\000\000\000\000',
|
|
|
|
'\000\000\000\000\000\000\000@', 0),
|
|
|
|
('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0),
|
|
|
|
('d', -2.0, '\300\000\000\000\000\000\000\000',
|
|
|
|
'\000\000\000\000\000\000\000\300', 0),
|
|
|
|
('?', 0, '\0', '\0', 0),
|
|
|
|
('?', 3, '\1', '\1', 1),
|
|
|
|
('?', True, '\1', '\1', 0),
|
|
|
|
('?', [], '\0', '\0', 1),
|
|
|
|
('?', (1,), '\1', '\1', 1),
|
|
|
|
]
|
|
|
|
|
|
|
|
for fmt, arg, big, lil, asy in tests:
|
|
|
|
for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
|
|
|
|
('='+fmt, ISBIGENDIAN and big or lil)]:
|
|
|
|
res = struct.pack(xfmt, arg)
|
|
|
|
self.assertEqual(res, exp)
|
|
|
|
self.assertEqual(struct.calcsize(xfmt), len(res))
|
|
|
|
rev = struct.unpack(xfmt, res)[0]
|
|
|
|
if rev != arg:
|
2009-06-30 19:57:08 -03:00
|
|
|
self.assertTrue(asy)
|
2008-06-10 22:31:28 -03:00
|
|
|
|
2009-07-07 11:15:45 -03:00
|
|
|
def test_calcsize(self):
|
|
|
|
expected_size = {
|
|
|
|
'b': 1, 'B': 1,
|
|
|
|
'h': 2, 'H': 2,
|
|
|
|
'i': 4, 'I': 4,
|
|
|
|
'l': 4, 'L': 4,
|
|
|
|
'q': 8, 'Q': 8,
|
|
|
|
}
|
|
|
|
|
|
|
|
# standard integer sizes
|
|
|
|
for code in integer_codes:
|
|
|
|
for byteorder in ('=', '<', '>', '!'):
|
|
|
|
format = byteorder+code
|
|
|
|
size = struct.calcsize(format)
|
|
|
|
self.assertEqual(size, expected_size[code])
|
|
|
|
|
|
|
|
# native integer sizes, except 'q' and 'Q'
|
|
|
|
for format_pair in ('bB', 'hH', 'iI', 'lL'):
|
|
|
|
for byteorder in ['', '@']:
|
|
|
|
signed_size = struct.calcsize(byteorder + format_pair[0])
|
|
|
|
unsigned_size = struct.calcsize(byteorder + format_pair[1])
|
|
|
|
self.assertEqual(signed_size, unsigned_size)
|
|
|
|
|
|
|
|
# bounds for native integer sizes
|
2010-04-04 04:00:02 -03:00
|
|
|
self.assertEqual(struct.calcsize('b'), 1)
|
|
|
|
self.assertLessEqual(2, struct.calcsize('h'))
|
|
|
|
self.assertLessEqual(4, struct.calcsize('l'))
|
|
|
|
self.assertLessEqual(struct.calcsize('h'), struct.calcsize('i'))
|
|
|
|
self.assertLessEqual(struct.calcsize('i'), struct.calcsize('l'))
|
2009-07-07 11:15:45 -03:00
|
|
|
|
|
|
|
# tests for native 'q' and 'Q' when applicable
|
|
|
|
if HAVE_LONG_LONG:
|
|
|
|
self.assertEqual(struct.calcsize('q'), struct.calcsize('Q'))
|
2010-04-04 04:00:02 -03:00
|
|
|
self.assertLessEqual(8, struct.calcsize('q'))
|
|
|
|
self.assertLessEqual(struct.calcsize('l'), struct.calcsize('q'))
|
2009-07-07 11:15:45 -03:00
|
|
|
|
|
|
|
def test_integers(self):
|
|
|
|
# Integer tests (bBhHiIlLqQ).
|
2008-06-10 22:31:28 -03:00
|
|
|
import binascii
|
|
|
|
|
|
|
|
class IntTester(unittest.TestCase):
|
2009-07-07 11:15:45 -03:00
|
|
|
def __init__(self, format):
|
2009-03-31 13:54:10 -03:00
|
|
|
super(IntTester, self).__init__(methodName='test_one')
|
2009-07-07 11:15:45 -03:00
|
|
|
self.format = format
|
|
|
|
self.code = format[-1]
|
|
|
|
self.direction = format[:-1]
|
|
|
|
if not self.direction in ('', '@', '=', '<', '>', '!'):
|
|
|
|
raise ValueError("unrecognized packing direction: %s" %
|
|
|
|
self.direction)
|
|
|
|
self.bytesize = struct.calcsize(format)
|
|
|
|
self.bitsize = self.bytesize * 8
|
|
|
|
if self.code in tuple('bhilq'):
|
|
|
|
self.signed = True
|
|
|
|
self.min_value = -(2L**(self.bitsize-1))
|
|
|
|
self.max_value = 2L**(self.bitsize-1) - 1
|
|
|
|
elif self.code in tuple('BHILQ'):
|
|
|
|
self.signed = False
|
|
|
|
self.min_value = 0
|
|
|
|
self.max_value = 2L**self.bitsize - 1
|
|
|
|
else:
|
|
|
|
raise ValueError("unrecognized format code: %s" %
|
|
|
|
self.code)
|
2008-06-10 22:31:28 -03:00
|
|
|
|
|
|
|
def test_one(self, x, pack=struct.pack,
|
|
|
|
unpack=struct.unpack,
|
|
|
|
unhexlify=binascii.unhexlify):
|
|
|
|
|
2009-07-07 11:15:45 -03:00
|
|
|
format = self.format
|
|
|
|
if self.min_value <= x <= self.max_value:
|
2008-06-10 22:31:28 -03:00
|
|
|
expected = long(x)
|
2009-07-07 11:15:45 -03:00
|
|
|
if self.signed and x < 0:
|
|
|
|
expected += 1L << self.bitsize
|
2010-04-04 04:00:02 -03:00
|
|
|
self.assertGreaterEqual(expected, 0)
|
2009-07-07 11:15:45 -03:00
|
|
|
expected = '%x' % expected
|
2008-06-10 22:31:28 -03:00
|
|
|
if len(expected) & 1:
|
|
|
|
expected = "0" + expected
|
|
|
|
expected = unhexlify(expected)
|
2009-07-07 11:15:45 -03:00
|
|
|
expected = ("\x00" * (self.bytesize - len(expected)) +
|
|
|
|
expected)
|
|
|
|
if (self.direction == '<' or
|
|
|
|
self.direction in ('', '@', '=') and not ISBIGENDIAN):
|
|
|
|
expected = string_reverse(expected)
|
|
|
|
self.assertEqual(len(expected), self.bytesize)
|
2008-06-10 22:31:28 -03:00
|
|
|
|
|
|
|
# Pack work?
|
|
|
|
got = pack(format, x)
|
|
|
|
self.assertEqual(got, expected)
|
|
|
|
|
|
|
|
# Unpack work?
|
|
|
|
retrieved = unpack(format, got)[0]
|
|
|
|
self.assertEqual(x, retrieved)
|
|
|
|
|
|
|
|
# Adding any byte should cause a "too big" error.
|
|
|
|
self.assertRaises((struct.error, TypeError), unpack, format,
|
|
|
|
'\x01' + got)
|
|
|
|
else:
|
|
|
|
# x is out of range -- verify pack realizes that.
|
2010-07-10 12:17:08 -03:00
|
|
|
self.assertRaises((OverflowError, ValueError, struct.error),
|
|
|
|
pack, format, x)
|
2008-06-10 22:31:28 -03:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
from random import randrange
|
|
|
|
|
|
|
|
# Create all interesting powers of 2.
|
|
|
|
values = []
|
|
|
|
for exp in range(self.bitsize + 3):
|
|
|
|
values.append(1L << exp)
|
|
|
|
|
|
|
|
# Add some random values.
|
|
|
|
for i in range(self.bitsize):
|
|
|
|
val = 0L
|
|
|
|
for j in range(self.bytesize):
|
|
|
|
val = (val << 8) | randrange(256)
|
|
|
|
values.append(val)
|
|
|
|
|
2009-07-07 11:15:45 -03:00
|
|
|
# Values absorbed from other tests
|
|
|
|
values.extend([300, 700000, sys.maxint*4])
|
|
|
|
|
|
|
|
# Try all those, and their negations, and +-1 from
|
|
|
|
# them. Note that this tests all power-of-2
|
|
|
|
# boundaries in range, and a few out of range, plus
|
|
|
|
# +-(2**n +- 1).
|
2008-06-10 22:31:28 -03:00
|
|
|
for base in values:
|
|
|
|
for val in -base, base:
|
|
|
|
for incr in -1, 0, 1:
|
|
|
|
x = val + incr
|
2009-07-07 11:15:45 -03:00
|
|
|
self.test_one(int(x))
|
|
|
|
self.test_one(long(x))
|
2008-06-10 22:31:28 -03:00
|
|
|
|
|
|
|
# Some error cases.
|
2009-07-05 07:01:24 -03:00
|
|
|
class NotAnIntNS(object):
|
|
|
|
def __int__(self):
|
|
|
|
return 42
|
|
|
|
|
|
|
|
def __long__(self):
|
|
|
|
return 1729L
|
|
|
|
|
|
|
|
class NotAnIntOS:
|
|
|
|
def __int__(self):
|
2010-03-07 12:24:45 -04:00
|
|
|
return 85
|
2009-07-05 07:01:24 -03:00
|
|
|
|
|
|
|
def __long__(self):
|
|
|
|
return -163L
|
|
|
|
|
2010-04-04 05:43:04 -03:00
|
|
|
# Objects with an '__index__' method should be allowed
|
|
|
|
# to pack as integers. That is assuming the implemented
|
|
|
|
# '__index__' method returns and 'int' or 'long'.
|
|
|
|
class Indexable(object):
|
|
|
|
def __init__(self, value):
|
|
|
|
self._value = value
|
|
|
|
|
|
|
|
def __index__(self):
|
|
|
|
return self._value
|
|
|
|
|
|
|
|
# If the '__index__' method raises a type error, then
|
|
|
|
# '__int__' should be used with a deprecation warning.
|
|
|
|
class BadIndex(object):
|
|
|
|
def __index__(self):
|
|
|
|
raise TypeError
|
|
|
|
|
|
|
|
def __int__(self):
|
|
|
|
return 42
|
|
|
|
|
2010-03-20 19:21:02 -03:00
|
|
|
self.assertRaises((TypeError, struct.error),
|
|
|
|
struct.pack, self.format,
|
|
|
|
"a string")
|
|
|
|
self.assertRaises((TypeError, struct.error),
|
|
|
|
struct.pack, self.format,
|
|
|
|
randrange)
|
|
|
|
with check_warnings(("integer argument expected, "
|
|
|
|
"got non-integer", DeprecationWarning)):
|
2010-07-09 15:15:28 -03:00
|
|
|
with self.assertRaises((TypeError, struct.error)):
|
|
|
|
struct.pack(self.format, 3+42j)
|
2009-07-07 11:15:45 -03:00
|
|
|
|
2010-03-07 12:24:45 -04:00
|
|
|
# an attempt to convert a non-integer (with an
|
|
|
|
# implicit conversion via __int__) should succeed,
|
|
|
|
# with a DeprecationWarning
|
2010-04-04 05:43:04 -03:00
|
|
|
for nonint in NotAnIntNS(), NotAnIntOS(), BadIndex():
|
2010-03-20 19:21:02 -03:00
|
|
|
with check_warnings((".*integer argument expected, got non"
|
|
|
|
"-integer", DeprecationWarning)) as w:
|
2010-03-07 12:24:45 -04:00
|
|
|
got = struct.pack(self.format, nonint)
|
2010-03-20 19:21:02 -03:00
|
|
|
lineno = inspect.currentframe().f_lineno - 1
|
|
|
|
self.assertEqual(w.filename, testmod_filename)
|
|
|
|
self.assertEqual(w.lineno, lineno)
|
|
|
|
self.assertEqual(len(w.warnings), 1)
|
2010-03-07 12:24:45 -04:00
|
|
|
expected = struct.pack(self.format, int(nonint))
|
|
|
|
self.assertEqual(got, expected)
|
|
|
|
|
2010-04-04 05:43:04 -03:00
|
|
|
# Check for legitimate values from '__index__'.
|
2010-04-03 11:05:10 -03:00
|
|
|
for obj in (Indexable(0), Indexable(10), Indexable(17),
|
|
|
|
Indexable(42), Indexable(100), Indexable(127)):
|
|
|
|
try:
|
|
|
|
struct.pack(format, obj)
|
|
|
|
except:
|
|
|
|
self.fail("integer code pack failed on object "
|
|
|
|
"with '__index__' method")
|
|
|
|
|
2010-04-04 05:43:04 -03:00
|
|
|
# Check for bogus values from '__index__'.
|
|
|
|
for obj in (Indexable('a'), Indexable(u'b'), Indexable(None),
|
|
|
|
Indexable({'a': 1}), Indexable([1, 2, 3])):
|
|
|
|
self.assertRaises((TypeError, struct.error),
|
|
|
|
struct.pack, self.format,
|
|
|
|
obj)
|
2010-04-03 11:05:10 -03:00
|
|
|
|
2009-07-07 11:15:45 -03:00
|
|
|
byteorders = '', '@', '=', '<', '>', '!'
|
|
|
|
for code in integer_codes:
|
|
|
|
for byteorder in byteorders:
|
|
|
|
if (byteorder in ('', '@') and code in ('q', 'Q') and
|
|
|
|
not HAVE_LONG_LONG):
|
|
|
|
continue
|
|
|
|
format = byteorder+code
|
|
|
|
t = IntTester(format)
|
|
|
|
t.run()
|
2008-06-10 22:31:28 -03:00
|
|
|
|
|
|
|
def test_p_code(self):
|
|
|
|
# Test p ("Pascal string") code.
|
|
|
|
for code, input, expected, expectedback in [
|
|
|
|
('p','abc', '\x00', ''),
|
|
|
|
('1p', 'abc', '\x00', ''),
|
|
|
|
('2p', 'abc', '\x01a', 'a'),
|
|
|
|
('3p', 'abc', '\x02ab', 'ab'),
|
|
|
|
('4p', 'abc', '\x03abc', 'abc'),
|
|
|
|
('5p', 'abc', '\x03abc\x00', 'abc'),
|
|
|
|
('6p', 'abc', '\x03abc\x00\x00', 'abc'),
|
|
|
|
('1000p', 'x'*1000, '\xff' + 'x'*999, 'x'*255)]:
|
|
|
|
got = struct.pack(code, input)
|
|
|
|
self.assertEqual(got, expected)
|
|
|
|
(got,) = struct.unpack(code, got)
|
|
|
|
self.assertEqual(got, expectedback)
|
|
|
|
|
|
|
|
def test_705836(self):
|
|
|
|
# SF bug 705836. "<f" and ">f" had a severe rounding bug, where a carry
|
|
|
|
# from the low-order discarded bits could propagate into the exponent
|
|
|
|
# field, causing the result to be wrong by a factor of 2.
|
|
|
|
import math
|
|
|
|
|
|
|
|
for base in range(1, 33):
|
|
|
|
# smaller <- largest representable float less than base.
|
|
|
|
delta = 0.5
|
|
|
|
while base - delta / 2.0 != base:
|
|
|
|
delta /= 2.0
|
|
|
|
smaller = base - delta
|
|
|
|
# Packing this rounds away a solid string of trailing 1 bits.
|
|
|
|
packed = struct.pack("<f", smaller)
|
|
|
|
unpacked = struct.unpack("<f", packed)[0]
|
|
|
|
# This failed at base = 2, 4, and 32, with unpacked = 1, 2, and
|
|
|
|
# 16, respectively.
|
|
|
|
self.assertEqual(base, unpacked)
|
|
|
|
bigpacked = struct.pack(">f", smaller)
|
|
|
|
self.assertEqual(bigpacked, string_reverse(packed))
|
|
|
|
unpacked = struct.unpack(">f", bigpacked)[0]
|
|
|
|
self.assertEqual(base, unpacked)
|
|
|
|
|
|
|
|
# Largest finite IEEE single.
|
|
|
|
big = (1 << 24) - 1
|
|
|
|
big = math.ldexp(big, 127 - 23)
|
2003-03-20 14:32:13 -04:00
|
|
|
packed = struct.pack(">f", big)
|
2008-06-10 22:31:28 -03:00
|
|
|
unpacked = struct.unpack(">f", packed)[0]
|
|
|
|
self.assertEqual(big, unpacked)
|
|
|
|
|
|
|
|
# The same, but tack on a 1 bit so it rounds up to infinity.
|
|
|
|
big = (1 << 25) - 1
|
|
|
|
big = math.ldexp(big, 127 - 24)
|
|
|
|
self.assertRaises(OverflowError, struct.pack, ">f", big)
|
|
|
|
|
2009-07-05 07:01:24 -03:00
|
|
|
def test_1530559(self):
|
2008-06-10 22:31:28 -03:00
|
|
|
# SF bug 1530559. struct.pack raises TypeError where it used to convert.
|
|
|
|
for endian in ('', '>', '<'):
|
2009-07-07 11:15:45 -03:00
|
|
|
for fmt in integer_codes:
|
2008-06-10 22:31:28 -03:00
|
|
|
self.check_float_coerce(endian + fmt, 1.0)
|
|
|
|
self.check_float_coerce(endian + fmt, 1.5)
|
|
|
|
|
2010-03-20 19:21:02 -03:00
|
|
|
def test_unpack_from(self, cls=str):
|
|
|
|
data = cls('abcd01234')
|
2008-06-10 22:31:28 -03:00
|
|
|
fmt = '4s'
|
|
|
|
s = struct.Struct(fmt)
|
2010-03-20 19:21:02 -03:00
|
|
|
|
|
|
|
self.assertEqual(s.unpack_from(data), ('abcd',))
|
|
|
|
self.assertEqual(struct.unpack_from(fmt, data), ('abcd',))
|
|
|
|
for i in xrange(6):
|
|
|
|
self.assertEqual(s.unpack_from(data, i), (data[i:i+4],))
|
|
|
|
self.assertEqual(struct.unpack_from(fmt, data, i), (data[i:i+4],))
|
|
|
|
for i in xrange(6, len(data) + 1):
|
|
|
|
self.assertRaises(struct.error, s.unpack_from, data, i)
|
|
|
|
self.assertRaises(struct.error, struct.unpack_from, fmt, data, i)
|
2008-06-10 22:31:28 -03:00
|
|
|
|
|
|
|
def test_pack_into(self):
|
|
|
|
test_string = 'Reykjavik rocks, eow!'
|
|
|
|
writable_buf = array.array('c', ' '*100)
|
|
|
|
fmt = '21s'
|
|
|
|
s = struct.Struct(fmt)
|
|
|
|
|
|
|
|
# Test without offset
|
|
|
|
s.pack_into(writable_buf, 0, test_string)
|
|
|
|
from_buf = writable_buf.tostring()[:len(test_string)]
|
|
|
|
self.assertEqual(from_buf, test_string)
|
|
|
|
|
|
|
|
# Test with offset.
|
|
|
|
s.pack_into(writable_buf, 10, test_string)
|
|
|
|
from_buf = writable_buf.tostring()[:len(test_string)+10]
|
|
|
|
self.assertEqual(from_buf, test_string[:10] + test_string)
|
|
|
|
|
|
|
|
# Go beyond boundaries.
|
|
|
|
small_buf = array.array('c', ' '*10)
|
2010-07-07 20:26:57 -03:00
|
|
|
self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 0,
|
|
|
|
test_string)
|
|
|
|
self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 2,
|
|
|
|
test_string)
|
2008-06-10 22:31:28 -03:00
|
|
|
|
2009-02-13 07:03:59 -04:00
|
|
|
# Test bogus offset (issue 3694)
|
|
|
|
sb = small_buf
|
2010-07-09 10:33:03 -03:00
|
|
|
self.assertRaises((TypeError, struct.error), struct.pack_into, b'', sb,
|
|
|
|
None)
|
2009-02-13 07:03:59 -04:00
|
|
|
|
2008-06-10 22:31:28 -03:00
|
|
|
def test_pack_into_fn(self):
|
|
|
|
test_string = 'Reykjavik rocks, eow!'
|
|
|
|
writable_buf = array.array('c', ' '*100)
|
|
|
|
fmt = '21s'
|
|
|
|
pack_into = lambda *args: struct.pack_into(fmt, *args)
|
|
|
|
|
|
|
|
# Test without offset.
|
|
|
|
pack_into(writable_buf, 0, test_string)
|
|
|
|
from_buf = writable_buf.tostring()[:len(test_string)]
|
|
|
|
self.assertEqual(from_buf, test_string)
|
|
|
|
|
|
|
|
# Test with offset.
|
|
|
|
pack_into(writable_buf, 10, test_string)
|
|
|
|
from_buf = writable_buf.tostring()[:len(test_string)+10]
|
|
|
|
self.assertEqual(from_buf, test_string[:10] + test_string)
|
|
|
|
|
|
|
|
# Go beyond boundaries.
|
|
|
|
small_buf = array.array('c', ' '*10)
|
2010-07-07 20:26:57 -03:00
|
|
|
self.assertRaises((ValueError, struct.error), pack_into, small_buf, 0,
|
|
|
|
test_string)
|
|
|
|
self.assertRaises((ValueError, struct.error), pack_into, small_buf, 2,
|
|
|
|
test_string)
|
2008-06-10 22:31:28 -03:00
|
|
|
|
|
|
|
def test_unpack_with_buffer(self):
|
2010-03-20 19:21:02 -03:00
|
|
|
with check_py3k_warnings(("buffer.. not supported in 3.x",
|
|
|
|
DeprecationWarning)):
|
|
|
|
# SF bug 1563759: struct.unpack doesn't support buffer protocol objects
|
|
|
|
data1 = array.array('B', '\x12\x34\x56\x78')
|
|
|
|
data2 = buffer('......\x12\x34\x56\x78......', 6, 4)
|
|
|
|
for data in [data1, data2]:
|
|
|
|
value, = struct.unpack('>I', data)
|
|
|
|
self.assertEqual(value, 0x12345678)
|
|
|
|
|
|
|
|
self.test_unpack_from(cls=buffer)
|
2008-06-10 22:31:28 -03:00
|
|
|
|
|
|
|
def test_bool(self):
|
2010-07-07 16:03:36 -03:00
|
|
|
class ExplodingBool(object):
|
|
|
|
def __nonzero__(self):
|
|
|
|
raise IOError
|
2008-06-10 22:31:28 -03:00
|
|
|
for prefix in tuple("<>!=")+('',):
|
|
|
|
false = (), [], [], '', 0
|
2010-03-20 19:21:02 -03:00
|
|
|
true = [1], 'test', 5, -1, 0xffffffffL+1, 0xffffffff//2
|
2008-06-10 22:31:28 -03:00
|
|
|
|
|
|
|
falseFormat = prefix + '?' * len(false)
|
|
|
|
packedFalse = struct.pack(falseFormat, *false)
|
|
|
|
unpackedFalse = struct.unpack(falseFormat, packedFalse)
|
|
|
|
|
|
|
|
trueFormat = prefix + '?' * len(true)
|
|
|
|
packedTrue = struct.pack(trueFormat, *true)
|
|
|
|
unpackedTrue = struct.unpack(trueFormat, packedTrue)
|
|
|
|
|
|
|
|
self.assertEqual(len(true), len(unpackedTrue))
|
|
|
|
self.assertEqual(len(false), len(unpackedFalse))
|
|
|
|
|
|
|
|
for t in unpackedFalse:
|
|
|
|
self.assertFalse(t)
|
|
|
|
for t in unpackedTrue:
|
|
|
|
self.assertTrue(t)
|
|
|
|
|
|
|
|
packed = struct.pack(prefix+'?', 1)
|
|
|
|
|
|
|
|
self.assertEqual(len(packed), struct.calcsize(prefix+'?'))
|
|
|
|
|
|
|
|
if len(packed) != 1:
|
|
|
|
self.assertFalse(prefix, msg='encoded bool is not one byte: %r'
|
|
|
|
%packed)
|
|
|
|
|
2010-07-07 16:03:36 -03:00
|
|
|
self.assertRaises(IOError, struct.pack, prefix + '?',
|
|
|
|
ExplodingBool())
|
|
|
|
|
|
|
|
for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']:
|
|
|
|
self.assertTrue(struct.unpack('>?', c)[0])
|
2008-06-10 22:31:28 -03:00
|
|
|
|
2010-03-20 19:21:02 -03:00
|
|
|
@unittest.skipUnless(IS32BIT, "Specific to 32bit machines")
|
|
|
|
def test_crasher(self):
|
|
|
|
self.assertRaises(MemoryError, struct.pack, "357913941c", "a")
|
2008-06-11 04:41:16 -03:00
|
|
|
|
2010-06-11 17:27:05 -03:00
|
|
|
def test_count_overflow(self):
|
|
|
|
hugecount = '{}b'.format(sys.maxsize+1)
|
|
|
|
self.assertRaises(struct.error, struct.calcsize, hugecount)
|
|
|
|
|
|
|
|
hugecount2 = '{}b{}H'.format(sys.maxsize//2, sys.maxsize//2)
|
|
|
|
self.assertRaises(struct.error, struct.calcsize, hugecount2)
|
2008-06-10 22:31:28 -03:00
|
|
|
|
2012-07-29 11:30:50 -03:00
|
|
|
def check_sizeof(self, format_str, number_of_codes):
|
|
|
|
# The size of 'PyStructObject'
|
|
|
|
totalsize = support.calcobjsize('5P')
|
|
|
|
# The size taken up by the 'formatcode' dynamic array
|
|
|
|
totalsize += struct.calcsize('3P') * (number_of_codes + 1)
|
|
|
|
support.check_sizeof(self, struct.Struct(format_str), totalsize)
|
|
|
|
|
|
|
|
@support.cpython_only
|
2012-07-28 23:58:44 -03:00
|
|
|
def test__sizeof__(self):
|
|
|
|
for code in integer_codes:
|
|
|
|
self.check_sizeof(code, 1)
|
|
|
|
self.check_sizeof('BHILfdspP', 9)
|
|
|
|
self.check_sizeof('B' * 1234, 1234)
|
|
|
|
self.check_sizeof('fd', 2)
|
|
|
|
self.check_sizeof('xxxxxxxxxxxxxx', 0)
|
|
|
|
self.check_sizeof('100H', 100)
|
|
|
|
self.check_sizeof('187s', 1)
|
|
|
|
self.check_sizeof('20p', 1)
|
|
|
|
self.check_sizeof('0s', 1)
|
|
|
|
self.check_sizeof('0c', 0)
|
2012-07-23 11:27:00 -03:00
|
|
|
|
2008-06-10 22:31:28 -03:00
|
|
|
def test_main():
|
2012-07-29 11:30:50 -03:00
|
|
|
support.run_unittest(StructTest)
|
2008-06-10 22:31:28 -03:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
test_main()
|