| 1 |
from test import support |
| 2 |
from test.support import is_apple_mobile, os_helper, requires_debug_ranges |
| 3 |
from test.support.script_helper import assert_python_ok |
| 4 |
import array |
| 5 |
import io |
| 6 |
import marshal |
| 7 |
import sys |
| 8 |
import unittest |
| 9 |
import os |
| 10 |
import types |
| 11 |
import textwrap |
| 12 |
|
| 13 |
try: |
| 14 |
import _testcapi |
| 15 |
except ImportError: |
| 16 |
_testcapi = None |
| 17 |
|
| 18 |
class HelperMixin: |
| 19 |
def helper(self, sample, *extra): |
| 20 |
new = marshal.loads(marshal.dumps(sample, *extra)) |
| 21 |
self.assertEqual(sample, new) |
| 22 |
try: |
| 23 |
with open(os_helper.TESTFN, "wb") as f: |
| 24 |
marshal.dump(sample, f, *extra) |
| 25 |
with open(os_helper.TESTFN, "rb") as f: |
| 26 |
new = marshal.load(f) |
| 27 |
self.assertEqual(sample, new) |
| 28 |
finally: |
| 29 |
os_helper.unlink(os_helper.TESTFN) |
| 30 |
|
| 31 |
class IntTestCase(unittest.TestCase, HelperMixin): |
| 32 |
def test_ints(self): |
| 33 |
# Test a range of Python ints larger than the machine word size. |
| 34 |
n = sys.maxsize ** 2 |
| 35 |
while n: |
| 36 |
for expected in (-n, n): |
| 37 |
self.helper(expected) |
| 38 |
n = n >> 1 |
| 39 |
n = 1 << 100 |
| 40 |
while n: |
| 41 |
for expected in (-n, -n+1, n-1, n): |
| 42 |
self.helper(expected) |
| 43 |
n = n >> 1 |
| 44 |
|
| 45 |
def test_int64(self): |
| 46 |
# Simulate int marshaling with TYPE_INT64. |
| 47 |
maxint64 = (1 << 63) - 1 |
| 48 |
minint64 = -maxint64-1 |
| 49 |
for base in maxint64, minint64, -maxint64, -(minint64 >> 1): |
| 50 |
while base: |
| 51 |
s = b'I' + int.to_bytes(base, 8, 'little', signed=True) |
| 52 |
got = marshal.loads(s) |
| 53 |
self.assertEqual(base, got) |
| 54 |
if base == -1: # a fixed-point for shifting right 1 |
| 55 |
base = 0 |
| 56 |
else: |
| 57 |
base >>= 1 |
| 58 |
|
| 59 |
got = marshal.loads(b'I\xfe\xdc\xba\x98\x76\x54\x32\x10') |
| 60 |
self.assertEqual(got, 0x1032547698badcfe) |
| 61 |
got = marshal.loads(b'I\x01\x23\x45\x67\x89\xab\xcd\xef') |
| 62 |
self.assertEqual(got, -0x1032547698badcff) |
| 63 |
got = marshal.loads(b'I\x08\x19\x2a\x3b\x4c\x5d\x6e\x7f') |
| 64 |
self.assertEqual(got, 0x7f6e5d4c3b2a1908) |
| 65 |
got = marshal.loads(b'I\xf7\xe6\xd5\xc4\xb3\xa2\x91\x80') |
| 66 |
self.assertEqual(got, -0x7f6e5d4c3b2a1909) |
| 67 |
|
| 68 |
def test_bool(self): |
| 69 |
for b in (True, False): |
| 70 |
self.helper(b) |
| 71 |
|
| 72 |
class FloatTestCase(unittest.TestCase, HelperMixin): |
| 73 |
def test_floats(self): |
| 74 |
# Test a few floats |
| 75 |
small = 1e-25 |
| 76 |
n = sys.maxsize * 3.7e250 |
| 77 |
while n > small: |
| 78 |
for expected in (-n, n): |
| 79 |
self.helper(float(expected)) |
| 80 |
n /= 123.4567 |
| 81 |
|
| 82 |
f = 0.0 |
| 83 |
s = marshal.dumps(f, 2) |
| 84 |
got = marshal.loads(s) |
| 85 |
self.assertEqual(f, got) |
| 86 |
# and with version <= 1 (floats marshalled differently then) |
| 87 |
s = marshal.dumps(f, 1) |
| 88 |
got = marshal.loads(s) |
| 89 |
self.assertEqual(f, got) |
| 90 |
|
| 91 |
n = sys.maxsize * 3.7e-250 |
| 92 |
while n < small: |
| 93 |
for expected in (-n, n): |
| 94 |
f = float(expected) |
| 95 |
self.helper(f) |
| 96 |
self.helper(f, 1) |
| 97 |
n *= 123.4567 |
| 98 |
|
| 99 |
class StringTestCase(unittest.TestCase, HelperMixin): |
| 100 |
def test_unicode(self): |
| 101 |
for s in ["", "Andr\xe8 Previn", "abc", " "*10000]: |
| 102 |
self.helper(marshal.loads(marshal.dumps(s))) |
| 103 |
|
| 104 |
def test_string(self): |
| 105 |
for s in ["", "Andr\xe8 Previn", "abc", " "*10000]: |
| 106 |
self.helper(s) |
| 107 |
|
| 108 |
def test_bytes(self): |
| 109 |
for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]: |
| 110 |
self.helper(s) |
| 111 |
|
| 112 |
class ExceptionTestCase(unittest.TestCase): |
| 113 |
def test_exceptions(self): |
| 114 |
new = marshal.loads(marshal.dumps(StopIteration)) |
| 115 |
self.assertEqual(StopIteration, new) |
| 116 |
|
| 117 |
class CodeTestCase(unittest.TestCase): |
| 118 |
def test_code(self): |
| 119 |
co = ExceptionTestCase.test_exceptions.__code__ |
| 120 |
new = marshal.loads(marshal.dumps(co)) |
| 121 |
self.assertEqual(co, new) |
| 122 |
|
| 123 |
def test_many_codeobjects(self): |
| 124 |
# Issue2957: bad recursion count on code objects |
| 125 |
# more than MAX_MARSHAL_STACK_DEPTH |
| 126 |
count = support.exceeds_recursion_limit() |
| 127 |
codes = (ExceptionTestCase.test_exceptions.__code__,) * count |
| 128 |
marshal.loads(marshal.dumps(codes)) |
| 129 |
|
| 130 |
def test_different_filenames(self): |
| 131 |
co1 = compile("x", "f1", "exec") |
| 132 |
co2 = compile("y", "f2", "exec") |
| 133 |
co1, co2 = marshal.loads(marshal.dumps((co1, co2))) |
| 134 |
self.assertEqual(co1.co_filename, "f1") |
| 135 |
self.assertEqual(co2.co_filename, "f2") |
| 136 |
|
| 137 |
def test_no_allow_code(self): |
| 138 |
data = {'a': [({0},)]} |
| 139 |
dump = marshal.dumps(data, allow_code=False) |
| 140 |
self.assertEqual(marshal.loads(dump, allow_code=False), data) |
| 141 |
|
| 142 |
f = io.BytesIO() |
| 143 |
marshal.dump(data, f, allow_code=False) |
| 144 |
f.seek(0) |
| 145 |
self.assertEqual(marshal.load(f, allow_code=False), data) |
| 146 |
|
| 147 |
co = ExceptionTestCase.test_exceptions.__code__ |
| 148 |
data = {'a': [({co, 0},)]} |
| 149 |
dump = marshal.dumps(data, allow_code=True) |
| 150 |
self.assertEqual(marshal.loads(dump, allow_code=True), data) |
| 151 |
with self.assertRaises(ValueError): |
| 152 |
marshal.dumps(data, allow_code=False) |
| 153 |
with self.assertRaises(ValueError): |
| 154 |
marshal.loads(dump, allow_code=False) |
| 155 |
|
| 156 |
marshal.dump(data, io.BytesIO(), allow_code=True) |
| 157 |
self.assertEqual(marshal.load(io.BytesIO(dump), allow_code=True), data) |
| 158 |
with self.assertRaises(ValueError): |
| 159 |
marshal.dump(data, io.BytesIO(), allow_code=False) |
| 160 |
with self.assertRaises(ValueError): |
| 161 |
marshal.load(io.BytesIO(dump), allow_code=False) |
| 162 |
|
| 163 |
@requires_debug_ranges() |
| 164 |
def test_minimal_linetable_with_no_debug_ranges(self): |
| 165 |
# Make sure when demarshalling objects with `-X no_debug_ranges` |
| 166 |
# that the columns are None. |
| 167 |
co = ExceptionTestCase.test_exceptions.__code__ |
| 168 |
code = textwrap.dedent(""" |
| 169 |
import sys |
| 170 |
import marshal |
| 171 |
with open(sys.argv[1], 'rb') as f: |
| 172 |
co = marshal.load(f) |
| 173 |
positions = list(co.co_positions()) |
| 174 |
assert positions[0][2] is None |
| 175 |
assert positions[0][3] is None |
| 176 |
""") |
| 177 |
|
| 178 |
try: |
| 179 |
with open(os_helper.TESTFN, 'wb') as f: |
| 180 |
marshal.dump(co, f) |
| 181 |
|
| 182 |
assert_python_ok('-X', 'no_debug_ranges', |
| 183 |
'-c', code, os_helper.TESTFN) |
| 184 |
finally: |
| 185 |
os_helper.unlink(os_helper.TESTFN) |
| 186 |
|
| 187 |
@support.cpython_only |
| 188 |
def test_same_filename_used(self): |
| 189 |
s = """def f(): pass\ndef g(): pass""" |
| 190 |
co = compile(s, "myfile", "exec") |
| 191 |
co = marshal.loads(marshal.dumps(co)) |
| 192 |
for obj in co.co_consts: |
| 193 |
if isinstance(obj, types.CodeType): |
| 194 |
self.assertIs(co.co_filename, obj.co_filename) |
| 195 |
|
| 196 |
class ContainerTestCase(unittest.TestCase, HelperMixin): |
| 197 |
d = {'astring': '[email protected]', |
| 198 |
'afloat': 7283.43, |
| 199 |
'anint': 2**20, |
| 200 |
'ashortlong': 2, |
| 201 |
'alist': ['.zyx.41'], |
| 202 |
'atuple': ('.zyx.41',)*10, |
| 203 |
'aboolean': False, |
| 204 |
'aunicode': "Andr\xe8 Previn" |
| 205 |
} |
| 206 |
|
| 207 |
def test_dict(self): |
| 208 |
self.helper(self.d) |
| 209 |
|
| 210 |
def test_list(self): |
| 211 |
self.helper(list(self.d.items())) |
| 212 |
|
| 213 |
def test_tuple(self): |
| 214 |
self.helper(tuple(self.d.keys())) |
| 215 |
|
| 216 |
def test_sets(self): |
| 217 |
for constructor in (set, frozenset): |
| 218 |
self.helper(constructor(self.d.keys())) |
| 219 |
|
| 220 |
|
| 221 |
class BufferTestCase(unittest.TestCase, HelperMixin): |
| 222 |
|
| 223 |
def test_bytearray(self): |
| 224 |
b = bytearray(b"abc") |
| 225 |
self.helper(b) |
| 226 |
new = marshal.loads(marshal.dumps(b)) |
| 227 |
self.assertEqual(type(new), bytes) |
| 228 |
|
| 229 |
def test_memoryview(self): |
| 230 |
b = memoryview(b"abc") |
| 231 |
self.helper(b) |
| 232 |
new = marshal.loads(marshal.dumps(b)) |
| 233 |
self.assertEqual(type(new), bytes) |
| 234 |
|
| 235 |
def test_array(self): |
| 236 |
a = array.array('B', b"abc") |
| 237 |
new = marshal.loads(marshal.dumps(a)) |
| 238 |
self.assertEqual(new, b"abc") |
| 239 |
|
| 240 |
|
| 241 |
class BugsTestCase(unittest.TestCase): |
| 242 |
def test_bug_5888452(self): |
| 243 |
# Simple-minded check for SF 588452: Debug build crashes |
| 244 |
marshal.dumps([128] * 1000) |
| 245 |
|
| 246 |
def test_patch_873224(self): |
| 247 |
self.assertRaises(Exception, marshal.loads, b'0') |
| 248 |
self.assertRaises(Exception, marshal.loads, b'f') |
| 249 |
self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1]) |
| 250 |
|
| 251 |
def test_version_argument(self): |
| 252 |
# Python 2.4.0 crashes for any call to marshal.dumps(x, y) |
| 253 |
self.assertEqual(marshal.loads(marshal.dumps(5, 0)), 5) |
| 254 |
self.assertEqual(marshal.loads(marshal.dumps(5, 1)), 5) |
| 255 |
|
| 256 |
def test_fuzz(self): |
| 257 |
# simple test that it's at least not *totally* trivial to |
| 258 |
# crash from bad marshal data |
| 259 |
for i in range(256): |
| 260 |
c = bytes([i]) |
| 261 |
try: |
| 262 |
marshal.loads(c) |
| 263 |
except Exception: |
| 264 |
pass |
| 265 |
|
| 266 |
def test_loads_recursion(self): |
| 267 |
def run_tests(N, check): |
| 268 |
# (((...None...),),) |
| 269 |
check(b')\x01' * N + b'N') |
| 270 |
check(b'(\x01\x00\x00\x00' * N + b'N') |
| 271 |
# [[[...None...]]] |
| 272 |
check(b'[\x01\x00\x00\x00' * N + b'N') |
| 273 |
# {None: {None: {None: ...None...}}} |
| 274 |
check(b'{N' * N + b'N' + b'0' * N) |
| 275 |
# frozenset([frozenset([frozenset([...None...])])]) |
| 276 |
check(b'>\x01\x00\x00\x00' * N + b'N') |
| 277 |
# Check that the generated marshal data is valid and marshal.loads() |
| 278 |
# works for moderately deep nesting |
| 279 |
run_tests(100, marshal.loads) |
| 280 |
# Very deeply nested structure shouldn't blow the stack |
| 281 |
def check(s): |
| 282 |
self.assertRaises(ValueError, marshal.loads, s) |
| 283 |
run_tests(2**20, check) |
| 284 |
|
| 285 |
def test_recursion_limit(self): |
| 286 |
# Create a deeply nested structure. |
| 287 |
head = last = [] |
| 288 |
# The max stack depth should match the value in Python/marshal.c. |
| 289 |
# BUG: https://bugs.python.org/issue33720 |
| 290 |
# Windows always limits the maximum depth on release and debug builds |
| 291 |
#if os.name == 'nt' and support.Py_DEBUG: |
| 292 |
if os.name == 'nt': |
| 293 |
MAX_MARSHAL_STACK_DEPTH = 1000 |
| 294 |
elif sys.platform == 'wasi' or is_apple_mobile: |
| 295 |
MAX_MARSHAL_STACK_DEPTH = 1500 |
| 296 |
else: |
| 297 |
MAX_MARSHAL_STACK_DEPTH = 2000 |
| 298 |
for i in range(MAX_MARSHAL_STACK_DEPTH - 2): |
| 299 |
last.append([0]) |
| 300 |
last = last[-1] |
| 301 |
|
| 302 |
# Verify we don't blow out the stack with dumps/load. |
| 303 |
data = marshal.dumps(head) |
| 304 |
new_head = marshal.loads(data) |
| 305 |
# Don't use == to compare objects, it can exceed the recursion limit. |
| 306 |
self.assertEqual(len(new_head), len(head)) |
| 307 |
self.assertEqual(len(new_head[0]), len(head[0])) |
| 308 |
self.assertEqual(len(new_head[-1]), len(head[-1])) |
| 309 |
|
| 310 |
last.append([0]) |
| 311 |
self.assertRaises(ValueError, marshal.dumps, head) |
| 312 |
|
| 313 |
def test_exact_type_match(self): |
| 314 |
# Former bug: |
| 315 |
# >>> class Int(int): pass |
| 316 |
# >>> type(loads(dumps(Int()))) |
| 317 |
# <type 'int'> |
| 318 |
for typ in (int, float, complex, tuple, list, dict, set, frozenset): |
| 319 |
# Note: str subclasses are not tested because they get handled |
| 320 |
# by marshal's routines for objects supporting the buffer API. |
| 321 |
subtyp = type('subtyp', (typ,), {}) |
| 322 |
self.assertRaises(ValueError, marshal.dumps, subtyp()) |
| 323 |
|
| 324 |
# Issue #1792 introduced a change in how marshal increases the size of its |
| 325 |
# internal buffer; this test ensures that the new code is exercised. |
| 326 |
def test_large_marshal(self): |
| 327 |
size = int(1e6) |
| 328 |
testString = 'abc' * size |
| 329 |
marshal.dumps(testString) |
| 330 |
|
| 331 |
def test_invalid_longs(self): |
| 332 |
# Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs |
| 333 |
invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00' |
| 334 |
self.assertRaises(ValueError, marshal.loads, invalid_string) |
| 335 |
|
| 336 |
def test_multiple_dumps_and_loads(self): |
| 337 |
# Issue 12291: marshal.load() should be callable multiple times |
| 338 |
# with interleaved data written by non-marshal code |
| 339 |
# Adapted from a patch by Engelbert Gruber. |
| 340 |
data = (1, 'abc', b'def', 1.0, (2, 'a', ['b', b'c'])) |
| 341 |
for interleaved in (b'', b'0123'): |
| 342 |
ilen = len(interleaved) |
| 343 |
positions = [] |
| 344 |
try: |
| 345 |
with open(os_helper.TESTFN, 'wb') as f: |
| 346 |
for d in data: |
| 347 |
marshal.dump(d, f) |
| 348 |
if ilen: |
| 349 |
f.write(interleaved) |
| 350 |
positions.append(f.tell()) |
| 351 |
with open(os_helper.TESTFN, 'rb') as f: |
| 352 |
for i, d in enumerate(data): |
| 353 |
self.assertEqual(d, marshal.load(f)) |
| 354 |
if ilen: |
| 355 |
f.read(ilen) |
| 356 |
self.assertEqual(positions[i], f.tell()) |
| 357 |
finally: |
| 358 |
os_helper.unlink(os_helper.TESTFN) |
| 359 |
|
| 360 |
def test_loads_reject_unicode_strings(self): |
| 361 |
# Issue #14177: marshal.loads() should not accept unicode strings |
| 362 |
unicode_string = 'T' |
| 363 |
self.assertRaises(TypeError, marshal.loads, unicode_string) |
| 364 |
|
| 365 |
def test_bad_reader(self): |
| 366 |
class BadReader(io.BytesIO): |
| 367 |
def readinto(self, buf): |
| 368 |
n = super().readinto(buf) |
| 369 |
if n is not None and n > 4: |
| 370 |
n += 10**6 |
| 371 |
return n |
| 372 |
for value in (1.0, 1j, b'0123456789', '0123456789'): |
| 373 |
self.assertRaises(ValueError, marshal.load, |
| 374 |
BadReader(marshal.dumps(value))) |
| 375 |
|
| 376 |
def test_eof(self): |
| 377 |
data = marshal.dumps(("hello", "dolly", None)) |
| 378 |
for i in range(len(data)): |
| 379 |
self.assertRaises(EOFError, marshal.loads, data[0: i]) |
| 380 |
|
| 381 |
def test_deterministic_sets(self): |
| 382 |
# bpo-37596: To support reproducible builds, sets and frozensets need to |
| 383 |
# have their elements serialized in a consistent order (even when they |
| 384 |
# have been scrambled by hash randomization): |
| 385 |
for kind in ("set", "frozenset"): |
| 386 |
for elements in ( |
| 387 |
"float('nan'), b'a', b'b', b'c', 'x', 'y', 'z'", |
| 388 |
# Also test for bad interactions with backreferencing: |
| 389 |
"('Spam', 0), ('Spam', 1), ('Spam', 2), ('Spam', 3), ('Spam', 4), ('Spam', 5)", |
| 390 |
): |
| 391 |
s = f"{kind}([{elements}])" |
| 392 |
with self.subTest(s): |
| 393 |
# First, make sure that our test case still has different |
| 394 |
# orders under hash seeds 0 and 1. If this check fails, we |
| 395 |
# need to update this test with different elements. Skip |
| 396 |
# this part if we are configured to use any other hash |
| 397 |
# algorithm (for example, using Py_HASH_EXTERNAL): |
| 398 |
if sys.hash_info.algorithm in {"fnv", "siphash24"}: |
| 399 |
args = ["-c", f"print({s})"] |
| 400 |
_, repr_0, _ = assert_python_ok(*args, PYTHONHASHSEED="0") |
| 401 |
_, repr_1, _ = assert_python_ok(*args, PYTHONHASHSEED="1") |
| 402 |
self.assertNotEqual(repr_0, repr_1) |
| 403 |
# Then, perform the actual test: |
| 404 |
args = ["-c", f"import marshal; print(marshal.dumps({s}))"] |
| 405 |
_, dump_0, _ = assert_python_ok(*args, PYTHONHASHSEED="0") |
| 406 |
_, dump_1, _ = assert_python_ok(*args, PYTHONHASHSEED="1") |
| 407 |
self.assertEqual(dump_0, dump_1) |
| 408 |
|
| 409 |
def test_unmarshallable(self): |
| 410 |
# Check no crash after encountering unmarshallable objects. |
| 411 |
# See https://github.com/python/cpython/issues/106287. |
| 412 |
fset = frozenset([int]) |
| 413 |
code = compile("a = 1", "<string>", "exec") |
| 414 |
code = code.replace(co_consts=(1, fset, None)) |
| 415 |
cases = (('tuple', (fset,)), |
| 416 |
('list', [fset]), |
| 417 |
('set', fset), |
| 418 |
('dict key', {fset: 'x'}), |
| 419 |
('dict value', {'x': fset}), |
| 420 |
('dict key & value', {fset: fset}), |
| 421 |
('slice', slice(fset, fset)), |
| 422 |
('code', code)) |
| 423 |
for name, arg in cases: |
| 424 |
with self.subTest(name, arg=arg): |
| 425 |
with self.assertRaisesRegex(ValueError, "unmarshallable object"): |
| 426 |
marshal.dumps((arg, memoryview(b''))) |
| 427 |
|
| 428 |
|
| 429 |
LARGE_SIZE = 2**31 |
| 430 |
pointer_size = 8 if sys.maxsize > 0xFFFFFFFF else 4 |
| 431 |
|
| 432 |
class NullWriter: |
| 433 |
def write(self, s): |
| 434 |
pass |
| 435 |
|
| 436 |
@unittest.skipIf(LARGE_SIZE > sys.maxsize, "test cannot run on 32-bit systems") |
| 437 |
class LargeValuesTestCase(unittest.TestCase): |
| 438 |
def check_unmarshallable(self, data): |
| 439 |
self.assertRaises(ValueError, marshal.dump, data, NullWriter()) |
| 440 |
|
| 441 |
@support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False) |
| 442 |
def test_bytes(self, size): |
| 443 |
self.check_unmarshallable(b'x' * size) |
| 444 |
|
| 445 |
@support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False) |
| 446 |
def test_str(self, size): |
| 447 |
self.check_unmarshallable('x' * size) |
| 448 |
|
| 449 |
@support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False) |
| 450 |
def test_tuple(self, size): |
| 451 |
self.check_unmarshallable((None,) * size) |
| 452 |
|
| 453 |
@support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False) |
| 454 |
def test_list(self, size): |
| 455 |
self.check_unmarshallable([None] * size) |
| 456 |
|
| 457 |
@support.bigmemtest(size=LARGE_SIZE, |
| 458 |
memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1), |
| 459 |
dry_run=False) |
| 460 |
def test_set(self, size): |
| 461 |
self.check_unmarshallable(set(range(size))) |
| 462 |
|
| 463 |
@support.bigmemtest(size=LARGE_SIZE, |
| 464 |
memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1), |
| 465 |
dry_run=False) |
| 466 |
def test_frozenset(self, size): |
| 467 |
self.check_unmarshallable(frozenset(range(size))) |
| 468 |
|
| 469 |
@support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False) |
| 470 |
def test_bytearray(self, size): |
| 471 |
self.check_unmarshallable(bytearray(size)) |
| 472 |
|
| 473 |
def CollectObjectIDs(ids, obj): |
| 474 |
"""Collect object ids seen in a structure""" |
| 475 |
if id(obj) in ids: |
| 476 |
return |
| 477 |
ids.add(id(obj)) |
| 478 |
if isinstance(obj, (list, tuple, set, frozenset)): |
| 479 |
for e in obj: |
| 480 |
CollectObjectIDs(ids, e) |
| 481 |
elif isinstance(obj, dict): |
| 482 |
for k, v in obj.items(): |
| 483 |
CollectObjectIDs(ids, k) |
| 484 |
CollectObjectIDs(ids, v) |
| 485 |
return len(ids) |
| 486 |
|
| 487 |
class InstancingTestCase(unittest.TestCase, HelperMixin): |
| 488 |
keys = (123, 1.2345, 'abc', (123, 'abc'), frozenset({123, 'abc'})) |
| 489 |
|
| 490 |
def helper3(self, rsample, recursive=False, simple=False): |
| 491 |
#we have two instances |
| 492 |
sample = (rsample, rsample) |
| 493 |
|
| 494 |
n0 = CollectObjectIDs(set(), sample) |
| 495 |
|
| 496 |
for v in range(3, marshal.version + 1): |
| 497 |
s3 = marshal.dumps(sample, v) |
| 498 |
n3 = CollectObjectIDs(set(), marshal.loads(s3)) |
| 499 |
|
| 500 |
#same number of instances generated |
| 501 |
self.assertEqual(n3, n0) |
| 502 |
|
| 503 |
if not recursive: |
| 504 |
#can compare with version 2 |
| 505 |
s2 = marshal.dumps(sample, 2) |
| 506 |
n2 = CollectObjectIDs(set(), marshal.loads(s2)) |
| 507 |
#old format generated more instances |
| 508 |
self.assertGreater(n2, n0) |
| 509 |
|
| 510 |
#if complex objects are in there, old format is larger |
| 511 |
if not simple: |
| 512 |
self.assertGreater(len(s2), len(s3)) |
| 513 |
else: |
| 514 |
self.assertGreaterEqual(len(s2), len(s3)) |
| 515 |
|
| 516 |
def testInt(self): |
| 517 |
intobj = 123321 |
| 518 |
self.helper(intobj) |
| 519 |
self.helper3(intobj, simple=True) |
| 520 |
|
| 521 |
def testFloat(self): |
| 522 |
floatobj = 1.2345 |
| 523 |
self.helper(floatobj) |
| 524 |
self.helper3(floatobj) |
| 525 |
|
| 526 |
def testStr(self): |
| 527 |
strobj = "abcde"*3 |
| 528 |
self.helper(strobj) |
| 529 |
self.helper3(strobj) |
| 530 |
|
| 531 |
def testBytes(self): |
| 532 |
bytesobj = b"abcde"*3 |
| 533 |
self.helper(bytesobj) |
| 534 |
self.helper3(bytesobj) |
| 535 |
|
| 536 |
def testList(self): |
| 537 |
for obj in self.keys: |
| 538 |
listobj = [obj, obj] |
| 539 |
self.helper(listobj) |
| 540 |
self.helper3(listobj) |
| 541 |
|
| 542 |
def testTuple(self): |
| 543 |
for obj in self.keys: |
| 544 |
tupleobj = (obj, obj) |
| 545 |
self.helper(tupleobj) |
| 546 |
self.helper3(tupleobj) |
| 547 |
|
| 548 |
def testSet(self): |
| 549 |
for obj in self.keys: |
| 550 |
setobj = {(obj, 1), (obj, 2)} |
| 551 |
self.helper(setobj) |
| 552 |
self.helper3(setobj) |
| 553 |
|
| 554 |
def testFrozenSet(self): |
| 555 |
for obj in self.keys: |
| 556 |
frozensetobj = frozenset({(obj, 1), (obj, 2)}) |
| 557 |
self.helper(frozensetobj) |
| 558 |
self.helper3(frozensetobj) |
| 559 |
|
| 560 |
def testDict(self): |
| 561 |
for obj in self.keys: |
| 562 |
dictobj = {"hello": obj, "goodbye": obj, obj: "hello"} |
| 563 |
self.helper(dictobj) |
| 564 |
self.helper3(dictobj) |
| 565 |
|
| 566 |
def testModule(self): |
| 567 |
with open(__file__, "rb") as f: |
| 568 |
code = f.read() |
| 569 |
if __file__.endswith(".py"): |
| 570 |
code = compile(code, __file__, "exec") |
| 571 |
self.helper(code) |
| 572 |
self.helper3(code) |
| 573 |
|
| 574 |
def testRecursion(self): |
| 575 |
obj = 1.2345 |
| 576 |
d = {"hello": obj, "goodbye": obj, obj: "hello"} |
| 577 |
d["self"] = d |
| 578 |
self.helper3(d, recursive=True) |
| 579 |
l = [obj, obj] |
| 580 |
l.append(l) |
| 581 |
self.helper3(l, recursive=True) |
| 582 |
|
| 583 |
class CompatibilityTestCase(unittest.TestCase): |
| 584 |
def _test(self, version): |
| 585 |
with open(__file__, "rb") as f: |
| 586 |
code = f.read() |
| 587 |
if __file__.endswith(".py"): |
| 588 |
code = compile(code, __file__, "exec") |
| 589 |
data = marshal.dumps(code, version) |
| 590 |
marshal.loads(data) |
| 591 |
|
| 592 |
def test0To3(self): |
| 593 |
self._test(0) |
| 594 |
|
| 595 |
def test1To3(self): |
| 596 |
self._test(1) |
| 597 |
|
| 598 |
def test2To3(self): |
| 599 |
self._test(2) |
| 600 |
|
| 601 |
def test3To3(self): |
| 602 |
self._test(3) |
| 603 |
|
| 604 |
class InterningTestCase(unittest.TestCase, HelperMixin): |
| 605 |
strobj = "this is an interned string" |
| 606 |
strobj = sys.intern(strobj) |
| 607 |
|
| 608 |
def testIntern(self): |
| 609 |
s = marshal.loads(marshal.dumps(self.strobj)) |
| 610 |
self.assertEqual(s, self.strobj) |
| 611 |
self.assertEqual(id(s), id(self.strobj)) |
| 612 |
s2 = sys.intern(s) |
| 613 |
self.assertEqual(id(s2), id(s)) |
| 614 |
|
| 615 |
def testNoIntern(self): |
| 616 |
s = marshal.loads(marshal.dumps(self.strobj, 2)) |
| 617 |
self.assertEqual(s, self.strobj) |
| 618 |
self.assertNotEqual(id(s), id(self.strobj)) |
| 619 |
s2 = sys.intern(s) |
| 620 |
self.assertNotEqual(id(s2), id(s)) |
| 621 |
|
| 622 |
@support.cpython_only |
| 623 |
@unittest.skipUnless(_testcapi, 'requires _testcapi') |
| 624 |
class CAPI_TestCase(unittest.TestCase, HelperMixin): |
| 625 |
|
| 626 |
def test_write_long_to_file(self): |
| 627 |
for v in range(marshal.version + 1): |
| 628 |
_testcapi.pymarshal_write_long_to_file(0x12345678, os_helper.TESTFN, v) |
| 629 |
with open(os_helper.TESTFN, 'rb') as f: |
| 630 |
data = f.read() |
| 631 |
os_helper.unlink(os_helper.TESTFN) |
| 632 |
self.assertEqual(data, b'\x78\x56\x34\x12') |
| 633 |
|
| 634 |
def test_write_object_to_file(self): |
| 635 |
obj = ('\u20ac', b'abc', 123, 45.6, 7+8j, 'long line '*1000) |
| 636 |
for v in range(marshal.version + 1): |
| 637 |
_testcapi.pymarshal_write_object_to_file(obj, os_helper.TESTFN, v) |
| 638 |
with open(os_helper.TESTFN, 'rb') as f: |
| 639 |
data = f.read() |
| 640 |
os_helper.unlink(os_helper.TESTFN) |
| 641 |
self.assertEqual(marshal.loads(data), obj) |
| 642 |
|
| 643 |
def test_read_short_from_file(self): |
| 644 |
with open(os_helper.TESTFN, 'wb') as f: |
| 645 |
f.write(b'\x34\x12xxxx') |
| 646 |
r, p = _testcapi.pymarshal_read_short_from_file(os_helper.TESTFN) |
| 647 |
os_helper.unlink(os_helper.TESTFN) |
| 648 |
self.assertEqual(r, 0x1234) |
| 649 |
self.assertEqual(p, 2) |
| 650 |
|
| 651 |
with open(os_helper.TESTFN, 'wb') as f: |
| 652 |
f.write(b'\x12') |
| 653 |
with self.assertRaises(EOFError): |
| 654 |
_testcapi.pymarshal_read_short_from_file(os_helper.TESTFN) |
| 655 |
os_helper.unlink(os_helper.TESTFN) |
| 656 |
|
| 657 |
def test_read_long_from_file(self): |
| 658 |
with open(os_helper.TESTFN, 'wb') as f: |
| 659 |
f.write(b'\x78\x56\x34\x12xxxx') |
| 660 |
r, p = _testcapi.pymarshal_read_long_from_file(os_helper.TESTFN) |
| 661 |
os_helper.unlink(os_helper.TESTFN) |
| 662 |
self.assertEqual(r, 0x12345678) |
| 663 |
self.assertEqual(p, 4) |
| 664 |
|
| 665 |
with open(os_helper.TESTFN, 'wb') as f: |
| 666 |
f.write(b'\x56\x34\x12') |
| 667 |
with self.assertRaises(EOFError): |
| 668 |
_testcapi.pymarshal_read_long_from_file(os_helper.TESTFN) |
| 669 |
os_helper.unlink(os_helper.TESTFN) |
| 670 |
|
| 671 |
def test_read_last_object_from_file(self): |
| 672 |
obj = ('\u20ac', b'abc', 123, 45.6, 7+8j) |
| 673 |
for v in range(marshal.version + 1): |
| 674 |
data = marshal.dumps(obj, v) |
| 675 |
with open(os_helper.TESTFN, 'wb') as f: |
| 676 |
f.write(data + b'xxxx') |
| 677 |
r, p = _testcapi.pymarshal_read_last_object_from_file(os_helper.TESTFN) |
| 678 |
os_helper.unlink(os_helper.TESTFN) |
| 679 |
self.assertEqual(r, obj) |
| 680 |
|
| 681 |
with open(os_helper.TESTFN, 'wb') as f: |
| 682 |
f.write(data[:1]) |
| 683 |
with self.assertRaises(EOFError): |
| 684 |
_testcapi.pymarshal_read_last_object_from_file(os_helper.TESTFN) |
| 685 |
os_helper.unlink(os_helper.TESTFN) |
| 686 |
|
| 687 |
def test_read_object_from_file(self): |
| 688 |
obj = ('\u20ac', b'abc', 123, 45.6, 7+8j) |
| 689 |
for v in range(marshal.version + 1): |
| 690 |
data = marshal.dumps(obj, v) |
| 691 |
with open(os_helper.TESTFN, 'wb') as f: |
| 692 |
f.write(data + b'xxxx') |
| 693 |
r, p = _testcapi.pymarshal_read_object_from_file(os_helper.TESTFN) |
| 694 |
os_helper.unlink(os_helper.TESTFN) |
| 695 |
self.assertEqual(r, obj) |
| 696 |
self.assertEqual(p, len(data)) |
| 697 |
|
| 698 |
with open(os_helper.TESTFN, 'wb') as f: |
| 699 |
f.write(data[:1]) |
| 700 |
with self.assertRaises(EOFError): |
| 701 |
_testcapi.pymarshal_read_object_from_file(os_helper.TESTFN) |
| 702 |
os_helper.unlink(os_helper.TESTFN) |
| 703 |
|
| 704 |
|
| 705 |
if __name__ == "__main__": |
| 706 |
unittest.main() |