convert test_struct to a unittest thanks to Giampaolo Rodola
I had to disable one test because it was functioning incorrectly, see #1530559 I also removed the debugging prints
This commit is contained in:
parent
610a93ea26
commit
d5299866f9
|
@ -1,14 +1,14 @@
|
||||||
from test.test_support import TestFailed, verbose, verify, vereq
|
|
||||||
import test.test_support
|
|
||||||
import struct
|
|
||||||
import array
|
import array
|
||||||
|
import unittest
|
||||||
|
import struct
|
||||||
import warnings
|
import warnings
|
||||||
|
|
||||||
|
from functools import wraps
|
||||||
|
from test.test_support import TestFailed, verbose, run_unittest, catch_warning
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
ISBIGENDIAN = sys.byteorder == "big"
|
ISBIGENDIAN = sys.byteorder == "big"
|
||||||
del sys
|
del sys
|
||||||
verify((struct.pack('=i', 1)[0] == chr(0)) == ISBIGENDIAN,
|
|
||||||
"bigendian determination appears wrong")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import _struct
|
import _struct
|
||||||
|
@ -30,39 +30,21 @@ def bigendian_to_native(value):
|
||||||
else:
|
else:
|
||||||
return string_reverse(value)
|
return string_reverse(value)
|
||||||
|
|
||||||
def simple_err(func, *args):
|
|
||||||
try:
|
|
||||||
func(*args)
|
|
||||||
except struct.error:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
raise TestFailed, "%s%s did not raise struct.error" % (
|
|
||||||
func.__name__, args)
|
|
||||||
|
|
||||||
def any_err(func, *args):
|
|
||||||
try:
|
|
||||||
func(*args)
|
|
||||||
except (struct.error, TypeError):
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
raise TestFailed, "%s%s did not raise error" % (
|
|
||||||
func.__name__, args)
|
|
||||||
|
|
||||||
def with_warning_restore(func):
|
def with_warning_restore(func):
|
||||||
def _with_warning_restore(*args, **kw):
|
@wraps(func)
|
||||||
with test.test_support.catch_warning():
|
def decorator(*args, **kw):
|
||||||
|
with catch_warning():
|
||||||
# Grrr, we need this function to warn every time. Without removing
|
# Grrr, we need this function to warn every time. Without removing
|
||||||
# the warningregistry, running test_tarfile then test_struct would fail
|
# the warningregistry, running test_tarfile then test_struct would fail
|
||||||
# on 64-bit platforms.
|
# on 64-bit platforms.
|
||||||
globals = func.func_globals
|
globals = func.func_globals
|
||||||
if '__warningregistry__' in globals:
|
if '__warningregistry__' in globals:
|
||||||
del globals['__warningregistry__']
|
del globals['__warningregistry__']
|
||||||
warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning)
|
warnings.filterwarnings("error", category=DeprecationWarning)
|
||||||
warnings.filterwarnings("error", r""".*format requires.*""",
|
|
||||||
DeprecationWarning)
|
|
||||||
return func(*args, **kw)
|
return func(*args, **kw)
|
||||||
return _with_warning_restore
|
return decorator
|
||||||
|
|
||||||
|
@with_warning_restore
|
||||||
def deprecated_err(func, *args):
|
def deprecated_err(func, *args):
|
||||||
try:
|
try:
|
||||||
func(*args)
|
func(*args)
|
||||||
|
@ -75,32 +57,56 @@ def deprecated_err(func, *args):
|
||||||
else:
|
else:
|
||||||
raise TestFailed, "%s%s did not raise error" % (
|
raise TestFailed, "%s%s did not raise error" % (
|
||||||
func.__name__, args)
|
func.__name__, args)
|
||||||
deprecated_err = with_warning_restore(deprecated_err)
|
|
||||||
|
|
||||||
|
|
||||||
simple_err(struct.calcsize, 'Z')
|
class StructTest(unittest.TestCase):
|
||||||
|
|
||||||
|
@with_warning_restore
|
||||||
|
def check_float_coerce(self, format, number):
|
||||||
|
# SF bug 1530559. struct.pack raises TypeError where it used to convert.
|
||||||
|
if PY_STRUCT_FLOAT_COERCE == 2:
|
||||||
|
# Test for pre-2.5 struct module
|
||||||
|
packed = struct.pack(format, number)
|
||||||
|
floored = struct.unpack(format, packed)[0]
|
||||||
|
self.assertEqual(floored, int(number),
|
||||||
|
"did not correcly coerce float to int")
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
struct.pack(format, number)
|
||||||
|
except (struct.error, TypeError):
|
||||||
|
if PY_STRUCT_FLOAT_COERCE:
|
||||||
|
self.fail("expected DeprecationWarning for float coerce")
|
||||||
|
except DeprecationWarning:
|
||||||
|
if not PY_STRUCT_FLOAT_COERCE:
|
||||||
|
self.fail("expected to raise struct.error for float coerce")
|
||||||
|
else:
|
||||||
|
self.fail("did not raise error for float coerce")
|
||||||
|
|
||||||
|
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')
|
sz = struct.calcsize('i')
|
||||||
if sz * 3 != struct.calcsize('iii'):
|
self.assertEqual(sz * 3, struct.calcsize('iii'))
|
||||||
raise TestFailed, 'inconsistent sizes'
|
|
||||||
|
|
||||||
fmt = 'cbxxxxxxhhhhiillffd?'
|
fmt = 'cbxxxxxxhhhhiillffd?'
|
||||||
fmt3 = '3c3b18x12h6i6l6f3d3?'
|
fmt3 = '3c3b18x12h6i6l6f3d3?'
|
||||||
sz = struct.calcsize(fmt)
|
sz = struct.calcsize(fmt)
|
||||||
sz3 = struct.calcsize(fmt3)
|
sz3 = struct.calcsize(fmt3)
|
||||||
if sz * 3 != sz3:
|
self.assertEqual(sz * 3, sz3)
|
||||||
raise TestFailed, 'inconsistent sizes (3*%r -> 3*%d = %d, %r -> %d)' % (
|
|
||||||
fmt, sz, 3*sz, fmt3, sz3)
|
|
||||||
|
|
||||||
simple_err(struct.pack, 'iii', 3)
|
self.assertRaises(struct.error, struct.pack, 'iii', 3)
|
||||||
simple_err(struct.pack, 'i', 3, 3, 3)
|
self.assertRaises(struct.error, struct.pack, 'i', 3, 3, 3)
|
||||||
simple_err(struct.pack, 'i', 'foo')
|
self.assertRaises(struct.error, struct.pack, 'i', 'foo')
|
||||||
simple_err(struct.pack, 'P', 'foo')
|
self.assertRaises(struct.error, struct.pack, 'P', 'foo')
|
||||||
simple_err(struct.unpack, 'd', 'flap')
|
self.assertRaises(struct.error, struct.unpack, 'd', 'flap')
|
||||||
s = struct.pack('ii', 1, 2)
|
s = struct.pack('ii', 1, 2)
|
||||||
simple_err(struct.unpack, 'iii', s)
|
self.assertRaises(struct.error, struct.unpack, 'iii', s)
|
||||||
simple_err(struct.unpack, 'i', s)
|
self.assertRaises(struct.error, struct.unpack, 'i', s)
|
||||||
|
|
||||||
|
def test_transitiveness(self):
|
||||||
c = 'a'
|
c = 'a'
|
||||||
b = 1
|
b = 1
|
||||||
h = 255
|
h = 255
|
||||||
|
@ -113,19 +119,19 @@ t = True
|
||||||
for prefix in ('', '@', '<', '>', '=', '!'):
|
for prefix in ('', '@', '<', '>', '=', '!'):
|
||||||
for format in ('xcbhilfd?', 'xcBHILfd?'):
|
for format in ('xcbhilfd?', 'xcBHILfd?'):
|
||||||
format = prefix + format
|
format = prefix + format
|
||||||
if verbose:
|
|
||||||
print "trying:", format
|
|
||||||
s = struct.pack(format, c, b, h, i, l, f, d, t)
|
s = struct.pack(format, c, b, h, i, l, f, d, t)
|
||||||
cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s)
|
cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s)
|
||||||
if (cp != c or bp != b or hp != h or ip != i or lp != l or
|
self.assertEqual(cp, c)
|
||||||
int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d) or
|
self.assertEqual(bp, b)
|
||||||
tp != t):
|
self.assertEqual(hp, h)
|
||||||
# ^^^ calculate only to two decimal places
|
self.assertEqual(ip, i)
|
||||||
raise TestFailed, "unpack/pack not transitive (%s, %s)" % (
|
self.assertEqual(lp, l)
|
||||||
str(format), str((cp, bp, hp, ip, lp, fp, dp, tp)))
|
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
|
# Test some of the new features in detail
|
||||||
|
|
||||||
# (format, argument, big-endian result, little-endian result, asymmetric)
|
# (format, argument, big-endian result, little-endian result, asymmetric)
|
||||||
tests = [
|
tests = [
|
||||||
('c', 'a', 'a', 'a', 0),
|
('c', 'a', 'a', 'a', 0),
|
||||||
|
@ -168,44 +174,33 @@ tests = [
|
||||||
]
|
]
|
||||||
|
|
||||||
for fmt, arg, big, lil, asy in tests:
|
for fmt, arg, big, lil, asy in tests:
|
||||||
if verbose:
|
|
||||||
print "%r %r %r %r" % (fmt, arg, big, lil)
|
|
||||||
for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
|
for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
|
||||||
('='+fmt, ISBIGENDIAN and big or lil)]:
|
('='+fmt, ISBIGENDIAN and big or lil)]:
|
||||||
res = struct.pack(xfmt, arg)
|
res = struct.pack(xfmt, arg)
|
||||||
if res != exp:
|
self.assertEqual(res, exp)
|
||||||
raise TestFailed, "pack(%r, %r) -> %r # expected %r" % (
|
self.assertEqual(struct.calcsize(xfmt), len(res))
|
||||||
fmt, arg, res, exp)
|
|
||||||
n = struct.calcsize(xfmt)
|
|
||||||
if n != len(res):
|
|
||||||
raise TestFailed, "calcsize(%r) -> %d # expected %d" % (
|
|
||||||
xfmt, n, len(res))
|
|
||||||
rev = struct.unpack(xfmt, res)[0]
|
rev = struct.unpack(xfmt, res)[0]
|
||||||
if rev != arg and not asy:
|
if rev != arg:
|
||||||
raise TestFailed, "unpack(%r, %r) -> (%r,) # expected (%r,)" % (
|
self.assert_(asy)
|
||||||
fmt, res, rev, arg)
|
|
||||||
|
|
||||||
###########################################################################
|
def test_native_qQ(self):
|
||||||
# Simple native q/Q tests.
|
# can't pack -1 as unsigned regardless
|
||||||
|
self.assertRaises((struct.error, TypeError), struct.pack, "Q", -1)
|
||||||
|
# can't pack string as 'q' regardless
|
||||||
|
self.assertRaises(struct.error, struct.pack, "q", "a")
|
||||||
|
# ditto, but 'Q'
|
||||||
|
self.assertRaises(struct.error, struct.pack, "Q", "a")
|
||||||
|
|
||||||
has_native_qQ = 1
|
|
||||||
try:
|
try:
|
||||||
struct.pack("q", 5)
|
struct.pack("q", 5)
|
||||||
except struct.error:
|
except struct.error:
|
||||||
has_native_qQ = 0
|
# does not have native q/Q
|
||||||
|
pass
|
||||||
if verbose:
|
else:
|
||||||
print "Platform has native q/Q?", has_native_qQ and "Yes." or "No."
|
|
||||||
|
|
||||||
any_err(struct.pack, "Q", -1) # can't pack -1 as unsigned regardless
|
|
||||||
simple_err(struct.pack, "q", "a") # can't pack string as 'q' regardless
|
|
||||||
simple_err(struct.pack, "Q", "a") # ditto, but 'Q'
|
|
||||||
|
|
||||||
def test_native_qQ():
|
|
||||||
bytes = struct.calcsize('q')
|
bytes = struct.calcsize('q')
|
||||||
# The expected values here are in big-endian format, primarily because
|
# The expected values here are in big-endian format, primarily
|
||||||
# I'm on a little-endian machine and so this is the clearest way (for
|
# because I'm on a little-endian machine and so this is the
|
||||||
# me) to force the code to get exercised.
|
# clearest way (for me) to force the code to get exercised.
|
||||||
for format, input, expected in (
|
for format, input, expected in (
|
||||||
('q', -1, '\xff' * bytes),
|
('q', -1, '\xff' * bytes),
|
||||||
('q', 0, '\x00' * bytes),
|
('q', 0, '\x00' * bytes),
|
||||||
|
@ -215,23 +210,15 @@ def test_native_qQ():
|
||||||
('q', (1L << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))):
|
('q', (1L << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))):
|
||||||
got = struct.pack(format, input)
|
got = struct.pack(format, input)
|
||||||
native_expected = bigendian_to_native(expected)
|
native_expected = bigendian_to_native(expected)
|
||||||
verify(got == native_expected,
|
self.assertEqual(got, native_expected)
|
||||||
"%r-pack of %r gave %r, not %r" %
|
|
||||||
(format, input, got, native_expected))
|
|
||||||
retrieved = struct.unpack(format, got)[0]
|
retrieved = struct.unpack(format, got)[0]
|
||||||
verify(retrieved == input,
|
self.assertEqual(retrieved, input)
|
||||||
"%r-unpack of %r gave %r, not %r" %
|
|
||||||
(format, got, retrieved, input))
|
|
||||||
|
|
||||||
if has_native_qQ:
|
def test_standard_integers(self):
|
||||||
test_native_qQ()
|
|
||||||
|
|
||||||
###########################################################################
|
|
||||||
# Standard integer tests (bBhHiIlLqQ).
|
# Standard integer tests (bBhHiIlLqQ).
|
||||||
|
|
||||||
import binascii
|
import binascii
|
||||||
|
|
||||||
class IntTester:
|
class IntTester(unittest.TestCase):
|
||||||
|
|
||||||
# XXX Most std integer modes fail to test for out-of-range.
|
# XXX Most std integer modes fail to test for out-of-range.
|
||||||
# The "i" and "l" codes appear to range-check OK on 32-bit boxes, but
|
# The "i" and "l" codes appear to range-check OK on 32-bit boxes, but
|
||||||
|
@ -240,12 +227,12 @@ class IntTester:
|
||||||
BUGGY_RANGE_CHECK = "bBhHiIlL"
|
BUGGY_RANGE_CHECK = "bBhHiIlL"
|
||||||
|
|
||||||
def __init__(self, formatpair, bytesize):
|
def __init__(self, formatpair, bytesize):
|
||||||
assert len(formatpair) == 2
|
self.assertEqual(len(formatpair), 2)
|
||||||
self.formatpair = formatpair
|
self.formatpair = formatpair
|
||||||
for direction in "<>!=":
|
for direction in "<>!=":
|
||||||
for code in formatpair:
|
for code in formatpair:
|
||||||
format = direction + code
|
format = direction + code
|
||||||
verify(struct.calcsize(format) == bytesize)
|
self.assertEqual(struct.calcsize(format), bytesize)
|
||||||
self.bytesize = bytesize
|
self.bytesize = bytesize
|
||||||
self.bitsize = bytesize * 8
|
self.bitsize = bytesize * 8
|
||||||
self.signed_code, self.unsigned_code = formatpair
|
self.signed_code, self.unsigned_code = formatpair
|
||||||
|
@ -257,9 +244,6 @@ class IntTester:
|
||||||
def test_one(self, x, pack=struct.pack,
|
def test_one(self, x, pack=struct.pack,
|
||||||
unpack=struct.unpack,
|
unpack=struct.unpack,
|
||||||
unhexlify=binascii.unhexlify):
|
unhexlify=binascii.unhexlify):
|
||||||
if verbose:
|
|
||||||
print "trying std", self.formatpair, "on", x, "==", hex(x)
|
|
||||||
|
|
||||||
# Try signed.
|
# Try signed.
|
||||||
code = self.signed_code
|
code = self.signed_code
|
||||||
if self.signed_min <= x <= self.signed_max:
|
if self.signed_min <= x <= self.signed_max:
|
||||||
|
@ -267,7 +251,7 @@ class IntTester:
|
||||||
expected = long(x)
|
expected = long(x)
|
||||||
if x < 0:
|
if x < 0:
|
||||||
expected += 1L << self.bitsize
|
expected += 1L << self.bitsize
|
||||||
assert expected > 0
|
self.assert_(expected > 0)
|
||||||
expected = hex(expected)[2:-1] # chop "0x" and trailing 'L'
|
expected = hex(expected)[2:-1] # chop "0x" and trailing 'L'
|
||||||
if len(expected) & 1:
|
if len(expected) & 1:
|
||||||
expected = "0" + expected
|
expected = "0" + expected
|
||||||
|
@ -277,37 +261,30 @@ class IntTester:
|
||||||
# Pack work?
|
# Pack work?
|
||||||
format = ">" + code
|
format = ">" + code
|
||||||
got = pack(format, x)
|
got = pack(format, x)
|
||||||
verify(got == expected,
|
self.assertEqual(got, expected)
|
||||||
"'%s'-pack of %r gave %r, not %r" %
|
|
||||||
(format, x, got, expected))
|
|
||||||
|
|
||||||
# Unpack work?
|
# Unpack work?
|
||||||
retrieved = unpack(format, got)[0]
|
retrieved = unpack(format, got)[0]
|
||||||
verify(x == retrieved,
|
self.assertEqual(x, retrieved)
|
||||||
"'%s'-unpack of %r gave %r, not %r" %
|
|
||||||
(format, got, retrieved, x))
|
|
||||||
|
|
||||||
# Adding any byte should cause a "too big" error.
|
# Adding any byte should cause a "too big" error.
|
||||||
any_err(unpack, format, '\x01' + got)
|
self.assertRaises((struct.error, TypeError), unpack, format,
|
||||||
|
'\x01' + got)
|
||||||
# Try little-endian.
|
# Try little-endian.
|
||||||
format = "<" + code
|
format = "<" + code
|
||||||
expected = string_reverse(expected)
|
expected = string_reverse(expected)
|
||||||
|
|
||||||
# Pack work?
|
# Pack work?
|
||||||
got = pack(format, x)
|
got = pack(format, x)
|
||||||
verify(got == expected,
|
self.assertEqual(got, expected)
|
||||||
"'%s'-pack of %r gave %r, not %r" %
|
|
||||||
(format, x, got, expected))
|
|
||||||
|
|
||||||
# Unpack work?
|
# Unpack work?
|
||||||
retrieved = unpack(format, got)[0]
|
retrieved = unpack(format, got)[0]
|
||||||
verify(x == retrieved,
|
self.assertEqual(x, retrieved)
|
||||||
"'%s'-unpack of %r gave %r, not %r" %
|
|
||||||
(format, got, retrieved, x))
|
|
||||||
|
|
||||||
# Adding any byte should cause a "too big" error.
|
# Adding any byte should cause a "too big" error.
|
||||||
any_err(unpack, format, '\x01' + got)
|
self.assertRaises((struct.error, TypeError), unpack, format,
|
||||||
|
'\x01' + got)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# x is out of range -- verify pack realizes that.
|
# x is out of range -- verify pack realizes that.
|
||||||
|
@ -332,18 +309,15 @@ class IntTester:
|
||||||
|
|
||||||
# Pack work?
|
# Pack work?
|
||||||
got = pack(format, x)
|
got = pack(format, x)
|
||||||
verify(got == expected,
|
self.assertEqual(got, expected)
|
||||||
"'%s'-pack of %r gave %r, not %r" %
|
|
||||||
(format, x, got, expected))
|
|
||||||
|
|
||||||
# Unpack work?
|
# Unpack work?
|
||||||
retrieved = unpack(format, got)[0]
|
retrieved = unpack(format, got)[0]
|
||||||
verify(x == retrieved,
|
self.assertEqual(x, retrieved)
|
||||||
"'%s'-unpack of %r gave %r, not %r" %
|
|
||||||
(format, got, retrieved, x))
|
|
||||||
|
|
||||||
# Adding any byte should cause a "too big" error.
|
# Adding any byte should cause a "too big" error.
|
||||||
any_err(unpack, format, '\x01' + got)
|
self.assertRaises((struct.error, TypeError), unpack, format,
|
||||||
|
'\x01' + got)
|
||||||
|
|
||||||
# Try little-endian.
|
# Try little-endian.
|
||||||
format = "<" + code
|
format = "<" + code
|
||||||
|
@ -351,18 +325,15 @@ class IntTester:
|
||||||
|
|
||||||
# Pack work?
|
# Pack work?
|
||||||
got = pack(format, x)
|
got = pack(format, x)
|
||||||
verify(got == expected,
|
self.assertEqual(got, expected)
|
||||||
"'%s'-pack of %r gave %r, not %r" %
|
|
||||||
(format, x, got, expected))
|
|
||||||
|
|
||||||
# Unpack work?
|
# Unpack work?
|
||||||
retrieved = unpack(format, got)[0]
|
retrieved = unpack(format, got)[0]
|
||||||
verify(x == retrieved,
|
self.assertEqual(x, retrieved)
|
||||||
"'%s'-unpack of %r gave %r, not %r" %
|
|
||||||
(format, got, retrieved, x))
|
|
||||||
|
|
||||||
# Adding any byte should cause a "too big" error.
|
# Adding any byte should cause a "too big" error.
|
||||||
any_err(unpack, format, '\x01' + got)
|
self.assertRaises((struct.error, TypeError), unpack, format,
|
||||||
|
'\x01' + got)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# x is out of range -- verify pack realizes that.
|
# x is out of range -- verify pack realizes that.
|
||||||
|
@ -405,7 +376,9 @@ class IntTester:
|
||||||
for direction in "<>":
|
for direction in "<>":
|
||||||
for code in self.formatpair:
|
for code in self.formatpair:
|
||||||
for badobject in "a string", 3+42j, randrange:
|
for badobject in "a string", 3+42j, randrange:
|
||||||
any_err(struct.pack, direction + code, badobject)
|
self.assertRaises((struct.error, TypeError),
|
||||||
|
struct.pack, direction + code,
|
||||||
|
badobject)
|
||||||
|
|
||||||
for args in [("bB", 1),
|
for args in [("bB", 1),
|
||||||
("hH", 2),
|
("hH", 2),
|
||||||
|
@ -415,11 +388,8 @@ for args in [("bB", 1),
|
||||||
t = IntTester(*args)
|
t = IntTester(*args)
|
||||||
t.run()
|
t.run()
|
||||||
|
|
||||||
|
def test_p_code(self):
|
||||||
###########################################################################
|
# Test p ("Pascal string") code.
|
||||||
# The p ("Pascal string") code.
|
|
||||||
|
|
||||||
def test_p_code():
|
|
||||||
for code, input, expected, expectedback in [
|
for code, input, expected, expectedback in [
|
||||||
('p','abc', '\x00', ''),
|
('p','abc', '\x00', ''),
|
||||||
('1p', 'abc', '\x00', ''),
|
('1p', 'abc', '\x00', ''),
|
||||||
|
@ -430,23 +400,14 @@ def test_p_code():
|
||||||
('6p', 'abc', '\x03abc\x00\x00', 'abc'),
|
('6p', 'abc', '\x03abc\x00\x00', 'abc'),
|
||||||
('1000p', 'x'*1000, '\xff' + 'x'*999, 'x'*255)]:
|
('1000p', 'x'*1000, '\xff' + 'x'*999, 'x'*255)]:
|
||||||
got = struct.pack(code, input)
|
got = struct.pack(code, input)
|
||||||
if got != expected:
|
self.assertEqual(got, expected)
|
||||||
raise TestFailed("pack(%r, %r) == %r but expected %r" %
|
|
||||||
(code, input, got, expected))
|
|
||||||
(got,) = struct.unpack(code, got)
|
(got,) = struct.unpack(code, got)
|
||||||
if got != expectedback:
|
self.assertEqual(got, expectedback)
|
||||||
raise TestFailed("unpack(%r, %r) == %r but expected %r" %
|
|
||||||
(code, input, got, expectedback))
|
|
||||||
|
|
||||||
test_p_code()
|
def test_705836(self):
|
||||||
|
|
||||||
|
|
||||||
###########################################################################
|
|
||||||
# SF bug 705836. "<f" and ">f" had a severe rounding bug, where a carry
|
# 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
|
# from the low-order discarded bits could propagate into the exponent
|
||||||
# field, causing the result to be wrong by a factor of 2.
|
# field, causing the result to be wrong by a factor of 2.
|
||||||
|
|
||||||
def test_705836():
|
|
||||||
import math
|
import math
|
||||||
|
|
||||||
for base in range(1, 33):
|
for base in range(1, 33):
|
||||||
|
@ -460,36 +421,28 @@ def test_705836():
|
||||||
unpacked = struct.unpack("<f", packed)[0]
|
unpacked = struct.unpack("<f", packed)[0]
|
||||||
# This failed at base = 2, 4, and 32, with unpacked = 1, 2, and
|
# This failed at base = 2, 4, and 32, with unpacked = 1, 2, and
|
||||||
# 16, respectively.
|
# 16, respectively.
|
||||||
verify(base == unpacked)
|
self.assertEqual(base, unpacked)
|
||||||
bigpacked = struct.pack(">f", smaller)
|
bigpacked = struct.pack(">f", smaller)
|
||||||
verify(bigpacked == string_reverse(packed),
|
self.assertEqual(bigpacked, string_reverse(packed))
|
||||||
">f pack should be byte-reversal of <f pack")
|
|
||||||
unpacked = struct.unpack(">f", bigpacked)[0]
|
unpacked = struct.unpack(">f", bigpacked)[0]
|
||||||
verify(base == unpacked)
|
self.assertEqual(base, unpacked)
|
||||||
|
|
||||||
# Largest finite IEEE single.
|
# Largest finite IEEE single.
|
||||||
big = (1 << 24) - 1
|
big = (1 << 24) - 1
|
||||||
big = math.ldexp(big, 127 - 23)
|
big = math.ldexp(big, 127 - 23)
|
||||||
packed = struct.pack(">f", big)
|
packed = struct.pack(">f", big)
|
||||||
unpacked = struct.unpack(">f", packed)[0]
|
unpacked = struct.unpack(">f", packed)[0]
|
||||||
verify(big == unpacked)
|
self.assertEqual(big, unpacked)
|
||||||
|
|
||||||
# The same, but tack on a 1 bit so it rounds up to infinity.
|
# The same, but tack on a 1 bit so it rounds up to infinity.
|
||||||
big = (1 << 25) - 1
|
big = (1 << 25) - 1
|
||||||
big = math.ldexp(big, 127 - 24)
|
big = math.ldexp(big, 127 - 24)
|
||||||
try:
|
self.assertRaises(OverflowError, struct.pack, ">f", big)
|
||||||
packed = struct.pack(">f", big)
|
|
||||||
except OverflowError:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
raise TestFailed("expected OverflowError")
|
|
||||||
|
|
||||||
test_705836()
|
if PY_STRUCT_RANGE_CHECKING:
|
||||||
|
def test_1229380(self):
|
||||||
###########################################################################
|
# SF bug 1229380. No struct.pack exception for some out of
|
||||||
# SF bug 1229380. No struct.pack exception for some out of range integers
|
# range integers
|
||||||
|
|
||||||
def test_1229380():
|
|
||||||
import sys
|
import sys
|
||||||
for endian in ('', '>', '<'):
|
for endian in ('', '>', '<'):
|
||||||
for cls in (int, long):
|
for cls in (int, long):
|
||||||
|
@ -502,77 +455,38 @@ def test_1229380():
|
||||||
deprecated_err(struct.pack, endian + 'I', sys.maxint * 4L)
|
deprecated_err(struct.pack, endian + 'I', sys.maxint * 4L)
|
||||||
deprecated_err(struct.pack, endian + 'L', sys.maxint * 4L)
|
deprecated_err(struct.pack, endian + 'L', sys.maxint * 4L)
|
||||||
|
|
||||||
if PY_STRUCT_RANGE_CHECKING:
|
def XXXtest_1530559(self):
|
||||||
test_1229380()
|
# XXX This is broken: see the bug report
|
||||||
|
|
||||||
###########################################################################
|
|
||||||
# SF bug 1530559. struct.pack raises TypeError where it used to convert.
|
# SF bug 1530559. struct.pack raises TypeError where it used to convert.
|
||||||
|
|
||||||
def check_float_coerce(format, number):
|
|
||||||
if PY_STRUCT_FLOAT_COERCE == 2:
|
|
||||||
# Test for pre-2.5 struct module
|
|
||||||
packed = struct.pack(format, number)
|
|
||||||
floored = struct.unpack(format, packed)[0]
|
|
||||||
if floored != int(number):
|
|
||||||
raise TestFailed("did not correcly coerce float to int")
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
func(*args)
|
|
||||||
except (struct.error, TypeError):
|
|
||||||
if PY_STRUCT_FLOAT_COERCE:
|
|
||||||
raise TestFailed("expected DeprecationWarning for float coerce")
|
|
||||||
except DeprecationWarning:
|
|
||||||
if not PY_STRUCT_FLOAT_COERCE:
|
|
||||||
raise TestFailed("expected to raise struct.error for float coerce")
|
|
||||||
else:
|
|
||||||
raise TestFailed("did not raise error for float coerce")
|
|
||||||
|
|
||||||
check_float_coerce = with_warning_restore(deprecated_err)
|
|
||||||
|
|
||||||
def test_1530559():
|
|
||||||
for endian in ('', '>', '<'):
|
for endian in ('', '>', '<'):
|
||||||
for fmt in ('B', 'H', 'I', 'L', 'b', 'h', 'i', 'l'):
|
for fmt in ('B', 'H', 'I', 'L', 'b', 'h', 'i', 'l'):
|
||||||
check_float_coerce(endian + fmt, 1.0)
|
self.check_float_coerce(endian + fmt, 1.0)
|
||||||
check_float_coerce(endian + fmt, 1.5)
|
self.check_float_coerce(endian + fmt, 1.5)
|
||||||
|
|
||||||
test_1530559()
|
def test_unpack_from(self):
|
||||||
|
|
||||||
###########################################################################
|
|
||||||
# Packing and unpacking to/from buffers.
|
|
||||||
|
|
||||||
# Copied and modified from unittest.
|
|
||||||
def assertRaises(excClass, callableObj, *args, **kwargs):
|
|
||||||
try:
|
|
||||||
callableObj(*args, **kwargs)
|
|
||||||
except excClass:
|
|
||||||
return
|
|
||||||
else:
|
|
||||||
raise TestFailed("%s not raised." % excClass)
|
|
||||||
|
|
||||||
def test_unpack_from():
|
|
||||||
test_string = 'abcd01234'
|
test_string = 'abcd01234'
|
||||||
fmt = '4s'
|
fmt = '4s'
|
||||||
s = struct.Struct(fmt)
|
s = struct.Struct(fmt)
|
||||||
for cls in (str, buffer):
|
for cls in (str, buffer):
|
||||||
data = cls(test_string)
|
data = cls(test_string)
|
||||||
vereq(s.unpack_from(data), ('abcd',))
|
self.assertEqual(s.unpack_from(data), ('abcd',))
|
||||||
vereq(s.unpack_from(data, 2), ('cd01',))
|
self.assertEqual(s.unpack_from(data, 2), ('cd01',))
|
||||||
vereq(s.unpack_from(data, 4), ('0123',))
|
self.assertEqual(s.unpack_from(data, 4), ('0123',))
|
||||||
for i in xrange(6):
|
for i in xrange(6):
|
||||||
vereq(s.unpack_from(data, i), (data[i:i+4],))
|
self.assertEqual(s.unpack_from(data, i), (data[i:i+4],))
|
||||||
for i in xrange(6, len(test_string) + 1):
|
for i in xrange(6, len(test_string) + 1):
|
||||||
simple_err(s.unpack_from, data, i)
|
self.assertRaises(struct.error, s.unpack_from, data, i)
|
||||||
for cls in (str, buffer):
|
for cls in (str, buffer):
|
||||||
data = cls(test_string)
|
data = cls(test_string)
|
||||||
vereq(struct.unpack_from(fmt, data), ('abcd',))
|
self.assertEqual(struct.unpack_from(fmt, data), ('abcd',))
|
||||||
vereq(struct.unpack_from(fmt, data, 2), ('cd01',))
|
self.assertEqual(struct.unpack_from(fmt, data, 2), ('cd01',))
|
||||||
vereq(struct.unpack_from(fmt, data, 4), ('0123',))
|
self.assertEqual(struct.unpack_from(fmt, data, 4), ('0123',))
|
||||||
for i in xrange(6):
|
for i in xrange(6):
|
||||||
vereq(struct.unpack_from(fmt, data, i), (data[i:i+4],))
|
self.assertEqual(struct.unpack_from(fmt, data, i), (data[i:i+4],))
|
||||||
for i in xrange(6, len(test_string) + 1):
|
for i in xrange(6, len(test_string) + 1):
|
||||||
simple_err(struct.unpack_from, fmt, data, i)
|
self.assertRaises(struct.error, struct.unpack_from, fmt, data, i)
|
||||||
|
|
||||||
def test_pack_into():
|
def test_pack_into(self):
|
||||||
test_string = 'Reykjavik rocks, eow!'
|
test_string = 'Reykjavik rocks, eow!'
|
||||||
writable_buf = array.array('c', ' '*100)
|
writable_buf = array.array('c', ' '*100)
|
||||||
fmt = '21s'
|
fmt = '21s'
|
||||||
|
@ -581,19 +495,19 @@ def test_pack_into():
|
||||||
# Test without offset
|
# Test without offset
|
||||||
s.pack_into(writable_buf, 0, test_string)
|
s.pack_into(writable_buf, 0, test_string)
|
||||||
from_buf = writable_buf.tostring()[:len(test_string)]
|
from_buf = writable_buf.tostring()[:len(test_string)]
|
||||||
vereq(from_buf, test_string)
|
self.assertEqual(from_buf, test_string)
|
||||||
|
|
||||||
# Test with offset.
|
# Test with offset.
|
||||||
s.pack_into(writable_buf, 10, test_string)
|
s.pack_into(writable_buf, 10, test_string)
|
||||||
from_buf = writable_buf.tostring()[:len(test_string)+10]
|
from_buf = writable_buf.tostring()[:len(test_string)+10]
|
||||||
vereq(from_buf, test_string[:10] + test_string)
|
self.assertEqual(from_buf, test_string[:10] + test_string)
|
||||||
|
|
||||||
# Go beyond boundaries.
|
# Go beyond boundaries.
|
||||||
small_buf = array.array('c', ' '*10)
|
small_buf = array.array('c', ' '*10)
|
||||||
assertRaises(struct.error, s.pack_into, small_buf, 0, test_string)
|
self.assertRaises(struct.error, s.pack_into, small_buf, 0, test_string)
|
||||||
assertRaises(struct.error, s.pack_into, small_buf, 2, test_string)
|
self.assertRaises(struct.error, s.pack_into, small_buf, 2, test_string)
|
||||||
|
|
||||||
def test_pack_into_fn():
|
def test_pack_into_fn(self):
|
||||||
test_string = 'Reykjavik rocks, eow!'
|
test_string = 'Reykjavik rocks, eow!'
|
||||||
writable_buf = array.array('c', ' '*100)
|
writable_buf = array.array('c', ' '*100)
|
||||||
fmt = '21s'
|
fmt = '21s'
|
||||||
|
@ -602,75 +516,61 @@ def test_pack_into_fn():
|
||||||
# Test without offset.
|
# Test without offset.
|
||||||
pack_into(writable_buf, 0, test_string)
|
pack_into(writable_buf, 0, test_string)
|
||||||
from_buf = writable_buf.tostring()[:len(test_string)]
|
from_buf = writable_buf.tostring()[:len(test_string)]
|
||||||
vereq(from_buf, test_string)
|
self.assertEqual(from_buf, test_string)
|
||||||
|
|
||||||
# Test with offset.
|
# Test with offset.
|
||||||
pack_into(writable_buf, 10, test_string)
|
pack_into(writable_buf, 10, test_string)
|
||||||
from_buf = writable_buf.tostring()[:len(test_string)+10]
|
from_buf = writable_buf.tostring()[:len(test_string)+10]
|
||||||
vereq(from_buf, test_string[:10] + test_string)
|
self.assertEqual(from_buf, test_string[:10] + test_string)
|
||||||
|
|
||||||
# Go beyond boundaries.
|
# Go beyond boundaries.
|
||||||
small_buf = array.array('c', ' '*10)
|
small_buf = array.array('c', ' '*10)
|
||||||
assertRaises(struct.error, pack_into, small_buf, 0, test_string)
|
self.assertRaises(struct.error, pack_into, small_buf, 0, test_string)
|
||||||
assertRaises(struct.error, pack_into, small_buf, 2, test_string)
|
self.assertRaises(struct.error, pack_into, small_buf, 2, test_string)
|
||||||
|
|
||||||
def test_unpack_with_buffer():
|
def test_unpack_with_buffer(self):
|
||||||
# SF bug 1563759: struct.unpack doens't support buffer protocol objects
|
# SF bug 1563759: struct.unpack doens't support buffer protocol objects
|
||||||
data1 = array.array('B', '\x12\x34\x56\x78')
|
data1 = array.array('B', '\x12\x34\x56\x78')
|
||||||
data2 = buffer('......\x12\x34\x56\x78......', 6, 4)
|
data2 = buffer('......\x12\x34\x56\x78......', 6, 4)
|
||||||
for data in [data1, data2]:
|
for data in [data1, data2]:
|
||||||
value, = struct.unpack('>I', data)
|
value, = struct.unpack('>I', data)
|
||||||
vereq(value, 0x12345678)
|
self.assertEqual(value, 0x12345678)
|
||||||
|
|
||||||
# Test methods to pack and unpack from buffers rather than strings.
|
def test_bool(self):
|
||||||
test_unpack_from()
|
|
||||||
test_pack_into()
|
|
||||||
test_pack_into_fn()
|
|
||||||
test_unpack_with_buffer()
|
|
||||||
|
|
||||||
def test_bool():
|
|
||||||
for prefix in tuple("<>!=")+('',):
|
for prefix in tuple("<>!=")+('',):
|
||||||
false = (), [], [], '', 0
|
false = (), [], [], '', 0
|
||||||
true = [1], 'test', 5, -1, 0xffffffffL+1, 0xffffffff/2
|
true = [1], 'test', 5, -1, 0xffffffffL+1, 0xffffffff/2
|
||||||
|
|
||||||
falseFormat = prefix + '?' * len(false)
|
falseFormat = prefix + '?' * len(false)
|
||||||
if verbose:
|
|
||||||
print 'trying bool pack/unpack on', false, 'using format', falseFormat
|
|
||||||
packedFalse = struct.pack(falseFormat, *false)
|
packedFalse = struct.pack(falseFormat, *false)
|
||||||
unpackedFalse = struct.unpack(falseFormat, packedFalse)
|
unpackedFalse = struct.unpack(falseFormat, packedFalse)
|
||||||
|
|
||||||
trueFormat = prefix + '?' * len(true)
|
trueFormat = prefix + '?' * len(true)
|
||||||
if verbose:
|
|
||||||
print 'trying bool pack/unpack on', true, 'using format', trueFormat
|
|
||||||
packedTrue = struct.pack(trueFormat, *true)
|
packedTrue = struct.pack(trueFormat, *true)
|
||||||
unpackedTrue = struct.unpack(trueFormat, packedTrue)
|
unpackedTrue = struct.unpack(trueFormat, packedTrue)
|
||||||
|
|
||||||
if len(true) != len(unpackedTrue):
|
self.assertEqual(len(true), len(unpackedTrue))
|
||||||
raise TestFailed('unpacked true array is not of same size as input')
|
self.assertEqual(len(false), len(unpackedFalse))
|
||||||
if len(false) != len(unpackedFalse):
|
|
||||||
raise TestFailed('unpacked false array is not of same size as input')
|
|
||||||
|
|
||||||
for t in unpackedFalse:
|
for t in unpackedFalse:
|
||||||
if t is not False:
|
self.assertFalse(t)
|
||||||
raise TestFailed('%r did not unpack as False' % t)
|
|
||||||
for t in unpackedTrue:
|
for t in unpackedTrue:
|
||||||
if t is not True:
|
self.assertTrue(t)
|
||||||
raise TestFailed('%r did not unpack as false' % t)
|
|
||||||
|
|
||||||
if prefix and verbose:
|
|
||||||
print 'trying size of bool with format %r' % (prefix+'?')
|
|
||||||
packed = struct.pack(prefix+'?', 1)
|
packed = struct.pack(prefix+'?', 1)
|
||||||
|
|
||||||
if len(packed) != struct.calcsize(prefix+'?'):
|
self.assertEqual(len(packed), struct.calcsize(prefix+'?'))
|
||||||
raise TestFailed('packed length is not equal to calculated size')
|
|
||||||
|
|
||||||
if len(packed) != 1 and prefix:
|
if len(packed) != 1:
|
||||||
raise TestFailed('encoded bool is not one byte: %r' % packed)
|
self.assertFalse(prefix, msg='encoded bool is not one byte: %r'
|
||||||
elif not prefix and verbose:
|
%packed)
|
||||||
print 'size of bool in native format is %i' % (len(packed))
|
|
||||||
|
|
||||||
for c in '\x01\x7f\xff\x0f\xf0':
|
for c in '\x01\x7f\xff\x0f\xf0':
|
||||||
if struct.unpack('>?', c)[0] is not True:
|
self.assertTrue(struct.unpack('>?', c)[0])
|
||||||
raise TestFailed('%c did not unpack as True' % c)
|
|
||||||
|
|
||||||
test_bool()
|
|
||||||
|
def test_main():
|
||||||
|
run_unittest(StructTest)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_main()
|
||||||
|
|
Loading…
Reference in New Issue