mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-28 18:59:04 +08:00
* mmap: guard move() against dest/src past the mapping size
An offset larger than the mapping made `size - dest` underflow, producing
an out-of-range slice index panic. Check the high side first, as write() does.
Assisted-by: Claude
* exceptions: keep ImportError name/path/name_from out of an empty instance dict
ImportError.__reduce__ unwrapped get_arg(0), which is None when the exception
was constructed with no positional argument, aborting on pickle.dumps(ImportError()).
Fall back to the full args tuple there, and expose name/path/name_from as class
attributes defaulting to None so a bare ImportError() reduces to (cls, ()).
Assisted-by: Claude
* asyncio: stop unwrapping the _current_tasks downcast in current_task()
_asyncio._current_tasks is a reassignable module attribute; the three sibling
functions already degrade gracefully when it is not a dict, current_task() did not.
Assisted-by: Claude
* asyncio: raise TypeError when FutureIter.throw()'s exception class returns a non-exception
exc_type.call() goes through a Python-controlled __new__, so its result can be
any object; the downcast was unwrapped. Report it as a TypeError instead.
Assisted-by: Claude
* sequence: use a fallible reservation for sequence repetition
The guard only rejects a repeat whose per-element size crosses MAX_MEMORY_SIZE,
so (1,) * (10**12) still reached Vec::with_capacity and aborted in the allocator.
Reserve fallibly and surface a MemoryError.
Assisted-by: Claude
* collections: reject an oversized deque repetition with MemoryError
deque * sys.maxsize reached the allocator and aborted with a capacity overflow.
Apply the MAX_MEMORY_SIZE guard the other sequences already carry.
Assisted-by: Claude
* itertools: raise OverflowError for an out-of-range r argument
combinations/combinations_with_replacement/permutations narrowed r with
to_usize().unwrap(), so r=2**64 panicked instead of raising.
Assisted-by: Claude
* math: stream the generic sumprod path instead of collecting both iterables
The big-int path collected each argument into a Vec before multiplying, so an
unbounded iterable exhausted memory. Advance both iterators in lockstep and
accumulate, reporting a length mismatch when only one is exhausted.
Assisted-by: Claude
* _imp: raise TypeError for a second positional argument to find_frozen
withdata is keyword-only and unimplemented; passing it positionally hit an
unimplemented!() and aborted.
Assisted-by: Claude
* _typing: check _idfunc arity before indexing args
_typing._idfunc() with no argument indexed args[0] out of bounds.
Assisted-by: Claude
* exceptions: require a sequence for the ExceptionGroup excs argument
The argument was collected before being validated, so an unbounded iterable
such as itertools.count() exhausted memory. Reject a non-sequence up front.
Assisted-by: Claude
* mmap: treat an inverted find/rfind range as empty
find(b"x", 5, 2) built a slice whose start exceeded its end and panicked.
Assisted-by: Claude
* collections: give deque and defaultdict a GC traverse
Neither type opted into traversal, so a reference cycle through a deque or a
defaultdict was never collected.
Assisted-by: Claude
* itertools: opt the iterator types into GC traverse
cycle and its siblings hold Python references but declared no traverse, so a
cycle built through one of them leaked.
Assisted-by: Claude
* _ctypes: mask an out-of-range int instead of panicking
c_char_p(2**64) and pointer item assignment called .expect() on the narrowing
conversion. Wrap the value to the target width, which is what the C
implementation stores.
Assisted-by: Claude
* hashlib: import _hashlib when a hash module is loaded
The hash object type is a static type owned by _hashlib; calling _md5.md5()
without _hashlib imported hit an uninitialized static type and panicked.
Assisted-by: Claude
* _csv: fall back to the built-in dialect defaults when none is registered
The dialect table is empty until csv.py registers 'excel', so _csv.reader([])
unwrapped a missing entry and panicked.
Assisted-by: Claude
* builtins: reject surrogates in compile()/eval() source instead of panicking
expect_str() panics on a str containing surrogates; convert with try_as_utf8
so eval(chr(0xd800)) raises.
Assisted-by: Claude
* _suggestions: require a list for _generate_suggestions candidates
The argument was collected before validation, so an unbounded iterable
exhausted memory.
Assisted-by: Claude
* lzma: size the filter chain before consuming it
filters= was collected into a Vec before the length check, so an unbounded
iterable exhausted memory. Take the length through the sequence protocol first.
Assisted-by: Claude
* classmethod: opt into GC traverse
staticmethod already declares traverse; classmethod did not, so a cycle through
the wrapped callable leaked.
Assisted-by: Claude
* posix: reject unbounded iterables in posix_spawn and setgroups
argv, setsigdef, setsigmask and setgroups bound an ArgIterable and collected it
before validating, so an infinite generator exhausted memory. Require a
list/tuple for argv, validate signals while streaming, and take setgroups
through the sequence protocol.
Assisted-by: Claude
* _ctypes: size Array slice assignment and _argtypes_ before collecting
Both eagerly collected their argument, so an unbounded iterable exhausted
memory before the length check ran.
Assisted-by: Claude
* sys: propagate the breakpointhook warning failure
warn() was unwrapped, so an unimportable $PYTHONBREAKPOINT under
-W error panicked instead of raising.
Assisted-by: Claude
* structseq: require the sequence argument when constructing a struct sequence
A no-argument construction produced an empty backing tuple, and reading any
named field then indexed out of bounds.
Assisted-by: Claude
* Guard the hash slot dispatch against unbounded recursion
`PyObject::hash` invoked the type's hash slot directly, so an element-wise
`__hash__` following a deeply nested object graph recursed one native frame
per level and overflowed the stack. Wrap the dispatch in `with_recursion`,
matching the repr and rich-compare dispatches in the same file, so
`hash(x)` on a nested tuple/GenericAlias/slice raises `RecursionError`.
Assisted-by: Claude
* genericalias: guard the __parameters__ walk against unbounded recursion
`make_parameters_from_slice` recursed into every list/tuple argument with
nothing counting the frames, so `list[L]` for a self-referential or deeply
nested `L` overflowed the native stack at subscript time. Wrap the descent
in `with_recursion`, which makes the walk fallible; `PyGenericAlias::new`,
`from_args` and `make_parameters` now return `PyResult` and every caller
propagates.
Assisted-by: Claude
* Fix the type confusion in PyAtomicRef's Debug impl
`PyAtomicRef<T>` stores a pointer to a `Py<T>`, as `Deref`, `load_raw`,
`swap` and `Drop` all read it, but `Debug` cast it to a bare `T` and
formatted the object header as payload bytes. For `PyFunction`, whose
`code: PyAtomicRef<PyCode>` has a pointer-chasing `Debug`, that
dereferenced header words and segfaulted.
Cast to `PyObject` instead, which is what `Drop` already does and which
also covers the `PyAtomicRef<PyObject>` and `PyAtomicRef<Option<T>>`
instantiations that have no `Py<T>`.
`_asyncio._enter_task` reached this through `{:?}` in its "Cannot enter
into task" message; format the two tasks with their Python repr, which is
what the message is meant to show.
Assisted-by: Claude
* _sre: disallow instantiating Match
`Match` inherited `object.__new__`, so `M.__new__(M)` produced an instance
whose `regs`/`string`/`pattern` were never filled in by a match run; the
mapping subscript path read them and dereferenced garbage. The type has no
public constructor, so mark it `DISALLOW_INSTANTIATION`, which makes
`M.__new__(M)` raise `TypeError: cannot create 're.Match' instances`.
Assisted-by: Claude
* utils: return the empty repr instead of asserting a non-empty collection
`collection_repr` took the first element with an `.expect()` justified by the
caller's preceding non-empty check. Another thread clearing the collection
between that check and the iteration made the iterator yield nothing and
panicked the worker. Fall back to the caller-supplied empty form, which is
the text those callers already produce for an empty collection.
Assisted-by: Claude
* itertools: advance cycle's index atomically
`cycle.__next__` did `fetch_add(1)` and then reset the index to 0 in a
separate store, so two threads replaying the saved items could both read an
index past the end of `saved` and panic on the slice access. Do the advance
and the wrap in one `fetch_update`.
Assisted-by: Claude
* _ctypes: reject a float argument to a foreign call without argtypes
`conv_param`, the conversion used when `argtypes` is not set, converted its
argument with `try_int`, which goes through `__int__` and so accepts a
float. `libc.strlen(1.5)` therefore passed 1 where the callee expects a
`char *` and the callee dereferenced it. Match `ConvParam`, which does a
`PyLong_Check` and converts nothing: take the branch only for an `int` (or
a subclass, so `True` still converts), and let a float fall through to
"Don't know how to convert parameter".
The branch below it converted a float to a C double, but `try_int` claimed
every float before it could run, so it was dead; `CArgValue::Double`
existed only for that branch and both go. Typed doubles are unaffected —
they travel as `CArgValue::Typed` with code 'd'.
Assisted-by: Claude
* Report the iterator itself from PyIter's traverse
`Traverse for PyIter<O>` delegated to the inherent `PyObject::traverse` of
the object it wraps, so it reported that iterator's referents instead of
the iterator. The iterator's own reference to those referents was then
never subtracted during the collector's reference-subtraction pass, the
referents kept a non-zero gc_refs, and every object reachable from them
was classified as a root.
Any cycle running through a type with a `PyIter` field therefore survived
collection: `map`, `filter`, `zip`, `enumerate`, `reversed` and the
`itertools` iterators all leaked, while the same cycle through a `list`,
`tuple` or `list_iterator` collected. Report the wrapped object, as the
`PyObjectRef`, `PyRef<T>` and `PyStackRef` impls do.
`itertools.tee` still leaks: its shared buffer is a `PyRc<PyItertoolsTeeData>`
rather than a Python object, so the collector cannot see through it.
Assisted-by: Claude
* Remove the obsolete expectedFailure on test_code_module.test_unicode_error
Compiling a source string containing a lone surrogate now raises
UnicodeEncodeError, so the test passes.
Assisted-by: Claude
* itertools: reserve the combination indices fallibly
`combinations` and `combinations_with_replacement` built their index vector
with an infallible allocation, so an `r` that passes the ssize_t check but
does not fit in memory aborted the process instead of raising MemoryError.
Assisted-by: Claude
* Apply the struct sequence constructor's dict argument
`structseq(sequence, dict)` discarded its second argument, so the hidden
fields past `n_sequence_fields` — `tm_zone`, `st_atime` and friends — were
always None when constructed directly or restored from a `(sequence, dict)`
pickle, and a non-dict second argument was accepted silently.
Take the dict, require it to be a dict, and fill the hidden slots the
sequence did not cover from it. A key that names a field the sequence
already supplied, or no field at all, is now a
"got duplicate or unexpected field name(s)" TypeError instead of being
dropped. Both arguments are bindable by name, as `sequence` and `dict`.
`os.stat_result` and `os.statvfs_result` did not accept a second argument
at all; they and `time.struct_time` now share the parsing.
Assisted-by: Claude
* _imp: report the argument count in find_frozen's arity error
Assisted-by: Claude
* Add regression tests for the reproduced crashers
One case per catalog entry, each asserting the behavior the fix produces:
recursion guards, the memory-unsafety sites, the overflow and unbounded
allocation guards, the eager-collection rejections, the unwrap sites, and
the cycles the collector now breaks. Every expected value was checked
against CPython 3.14.
Assisted-by: Claude
* Tolerate a changed-size RuntimeError in the set repr stress test
The mutator and reader threads race on purpose; a "changed size during
iteration" RuntimeError is a valid outcome of that race and should not fail
the test. The panic it guards against is not.
Assisted-by: Claude
* Move the crash regression tests into per-module snippets
crash_regressions.py collected every reproduced crasher in one file. Split it
into the snippet for the module each case exercises, and add stdlib_gc.py,
stdlib_asyncio.py, stdlib_lzma.py, stdlib_threading_set_repr.py and
stdlib_threading_itertools_cycle.py for the cases with no existing home.
The suite runs every snippet under the host CPython too, so the checks only
RustPython raises are guarded by sys.implementation.name: the hash and
__parameters__ recursion depth, and the deque repeat overflow. The float
ctypes argument accepts either TypeError or ctypes.ArgumentError.
Assisted-by: Claude
371 lines
15 KiB
Python
Vendored
371 lines
15 KiB
Python
Vendored
import copy
|
|
import gc
|
|
import os
|
|
import pickle
|
|
import re
|
|
import textwrap
|
|
import time
|
|
import unittest
|
|
from test.support import script_helper
|
|
|
|
|
|
class StructSeqTest(unittest.TestCase):
|
|
|
|
def test_tuple(self):
|
|
t = time.gmtime()
|
|
self.assertIsInstance(t, tuple)
|
|
astuple = tuple(t)
|
|
self.assertEqual(len(t), len(astuple))
|
|
self.assertEqual(t, astuple)
|
|
|
|
# Check that slicing works the same way; at one point, slicing t[i:j] with
|
|
# 0 < i < j could produce NULLs in the result.
|
|
for i in range(-len(t), len(t)):
|
|
self.assertEqual(t[i:], astuple[i:])
|
|
for j in range(-len(t), len(t)):
|
|
self.assertEqual(t[i:j], astuple[i:j])
|
|
|
|
for j in range(-len(t), len(t)):
|
|
self.assertEqual(t[:j], astuple[:j])
|
|
|
|
self.assertRaises(IndexError, t.__getitem__, -len(t)-1)
|
|
self.assertRaises(IndexError, t.__getitem__, len(t))
|
|
for i in range(-len(t), len(t)-1):
|
|
self.assertEqual(t[i], astuple[i])
|
|
|
|
def test_repr(self):
|
|
t = time.gmtime()
|
|
self.assertTrue(repr(t))
|
|
t = time.gmtime(0)
|
|
self.assertEqual(repr(t),
|
|
"time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, "
|
|
"tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)")
|
|
# os.stat() gives a complicated struct sequence.
|
|
st = os.stat(__file__)
|
|
rep = repr(st)
|
|
self.assertStartsWith(rep, "os.stat_result")
|
|
self.assertIn("st_mode=", rep)
|
|
self.assertIn("st_ino=", rep)
|
|
self.assertIn("st_dev=", rep)
|
|
|
|
def test_concat(self):
|
|
t1 = time.gmtime()
|
|
t2 = t1 + tuple(t1)
|
|
for i in range(len(t1)):
|
|
self.assertEqual(t2[i], t2[i+len(t1)])
|
|
|
|
def test_repeat(self):
|
|
t1 = time.gmtime()
|
|
t2 = 3 * t1
|
|
for i in range(len(t1)):
|
|
self.assertEqual(t2[i], t2[i+len(t1)])
|
|
self.assertEqual(t2[i], t2[i+2*len(t1)])
|
|
|
|
def test_contains(self):
|
|
t1 = time.gmtime()
|
|
for item in t1:
|
|
self.assertIn(item, t1)
|
|
self.assertNotIn(-42, t1)
|
|
|
|
def test_hash(self):
|
|
t1 = time.gmtime()
|
|
self.assertEqual(hash(t1), hash(tuple(t1)))
|
|
|
|
def test_cmp(self):
|
|
t1 = time.gmtime()
|
|
t2 = type(t1)(t1)
|
|
self.assertEqual(t1, t2)
|
|
self.assertTrue(not (t1 < t2))
|
|
self.assertTrue(t1 <= t2)
|
|
self.assertTrue(not (t1 > t2))
|
|
self.assertTrue(t1 >= t2)
|
|
self.assertTrue(not (t1 != t2))
|
|
|
|
def test_fields(self):
|
|
t = time.gmtime()
|
|
self.assertEqual(len(t), t.n_sequence_fields)
|
|
self.assertEqual(t.n_unnamed_fields, 0)
|
|
self.assertEqual(t.n_fields, time._STRUCT_TM_ITEMS)
|
|
|
|
def test_constructor(self):
|
|
t = time.struct_time
|
|
|
|
self.assertRaises(TypeError, t)
|
|
self.assertRaises(TypeError, t, None)
|
|
self.assertRaises(TypeError, t, "123")
|
|
self.assertRaises(TypeError, t, "123", dict={})
|
|
self.assertRaises(TypeError, t, "123456789", dict=None)
|
|
self.assertRaises(TypeError, t, seq="123456789", dict={})
|
|
|
|
self.assertEqual(t("123456789"), tuple("123456789"))
|
|
self.assertEqual(t("123456789", {}), tuple("123456789"))
|
|
self.assertEqual(t("123456789", dict={}), tuple("123456789"))
|
|
self.assertEqual(t(sequence="123456789", dict={}), tuple("123456789"))
|
|
|
|
self.assertEqual(t("1234567890"), tuple("123456789"))
|
|
self.assertEqual(t("1234567890").tm_zone, "0")
|
|
self.assertEqual(t("123456789", {"tm_zone": "some zone"}), tuple("123456789"))
|
|
self.assertEqual(t("123456789", {"tm_zone": "some zone"}).tm_zone, "some zone")
|
|
|
|
s = "123456789"
|
|
self.assertEqual("".join(t(s)), s)
|
|
|
|
def test_constructor_with_duplicate_fields(self):
|
|
t = time.struct_time
|
|
|
|
error_message = re.escape("got duplicate or unexpected field name(s)")
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
t("1234567890", dict={"tm_zone": "some zone"})
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
t("1234567890", dict={"tm_zone": "some zone", "tm_mon": 1})
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
t("1234567890", dict={"error": 0, "tm_zone": "some zone"})
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
t("1234567890", dict={"error": 0, "tm_zone": "some zone", "tm_mon": 1})
|
|
|
|
def test_constructor_with_duplicate_unnamed_fields(self):
|
|
assert os.stat_result.n_unnamed_fields > 0
|
|
n_visible_fields = os.stat_result.n_sequence_fields
|
|
|
|
r = os.stat_result(range(n_visible_fields), {'st_atime': -1.0})
|
|
self.assertEqual(r.st_atime, -1.0)
|
|
self.assertEqual(r, tuple(range(n_visible_fields)))
|
|
|
|
r = os.stat_result((*range(n_visible_fields), -1.0))
|
|
self.assertEqual(r.st_atime, -1.0)
|
|
self.assertEqual(r, tuple(range(n_visible_fields)))
|
|
|
|
with self.assertRaisesRegex(TypeError,
|
|
re.escape("got duplicate or unexpected field name(s)")):
|
|
os.stat_result((*range(n_visible_fields), -1.0), {'st_atime': -1.0})
|
|
|
|
def test_constructor_with_unknown_fields(self):
|
|
t = time.struct_time
|
|
|
|
error_message = re.escape("got duplicate or unexpected field name(s)")
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
t("123456789", dict={"tm_year": 0})
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
t("123456789", dict={"tm_year": 0, "tm_mon": 1})
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
t("123456789", dict={"tm_zone": "some zone", "tm_mon": 1})
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
t("123456789", dict={"tm_zone": "some zone", "error": 0})
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
t("123456789", dict={"error": 0, "tm_zone": "some zone", "tm_mon": 1})
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
t("123456789", dict={"error": 0})
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
t("123456789", dict={"tm_zone": "some zone", "error": 0})
|
|
|
|
def test_eviltuple(self):
|
|
class Exc(Exception):
|
|
pass
|
|
|
|
# Devious code could crash structseqs' constructors
|
|
class C:
|
|
def __getitem__(self, i):
|
|
raise Exc
|
|
def __len__(self):
|
|
return 9
|
|
|
|
self.assertRaises(Exc, time.struct_time, C())
|
|
|
|
def test_pickling(self):
|
|
t = time.gmtime()
|
|
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
|
|
p = pickle.dumps(t, proto)
|
|
t2 = pickle.loads(p)
|
|
self.assertEqual(t2.__class__, t.__class__)
|
|
self.assertEqual(t2, t)
|
|
self.assertEqual(t2.tm_year, t.tm_year)
|
|
self.assertEqual(t2.tm_zone, t.tm_zone)
|
|
|
|
def test_pickling_with_unnamed_fields(self):
|
|
assert os.stat_result.n_unnamed_fields > 0
|
|
|
|
r = os.stat_result(range(os.stat_result.n_sequence_fields),
|
|
{'st_atime': 1.0, 'st_atime_ns': 2.0})
|
|
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
|
|
p = pickle.dumps(r, proto)
|
|
r2 = pickle.loads(p)
|
|
self.assertEqual(r2.__class__, r.__class__)
|
|
self.assertEqual(r2, r)
|
|
self.assertEqual(r2.st_mode, r.st_mode)
|
|
self.assertEqual(r2.st_atime, r.st_atime)
|
|
self.assertEqual(r2.st_atime_ns, r.st_atime_ns)
|
|
|
|
def test_copying(self):
|
|
n_fields = time.struct_time.n_fields
|
|
t = time.struct_time([[i] for i in range(n_fields)])
|
|
|
|
t2 = copy.copy(t)
|
|
self.assertEqual(t2.__class__, t.__class__)
|
|
self.assertEqual(t2, t)
|
|
self.assertEqual(t2.tm_year, t.tm_year)
|
|
self.assertEqual(t2.tm_zone, t.tm_zone)
|
|
self.assertIs(t2[0], t[0])
|
|
self.assertIs(t2.tm_year, t.tm_year)
|
|
|
|
t3 = copy.deepcopy(t)
|
|
self.assertEqual(t3.__class__, t.__class__)
|
|
self.assertEqual(t3, t)
|
|
self.assertEqual(t3.tm_year, t.tm_year)
|
|
self.assertEqual(t3.tm_zone, t.tm_zone)
|
|
self.assertIsNot(t3[0], t[0])
|
|
self.assertIsNot(t3.tm_year, t.tm_year)
|
|
|
|
def test_copying_with_unnamed_fields(self):
|
|
assert os.stat_result.n_unnamed_fields > 0
|
|
|
|
n_sequence_fields = os.stat_result.n_sequence_fields
|
|
r = os.stat_result([[i] for i in range(n_sequence_fields)],
|
|
{'st_atime': [1.0], 'st_atime_ns': [2.0]})
|
|
|
|
r2 = copy.copy(r)
|
|
self.assertEqual(r2.__class__, r.__class__)
|
|
self.assertEqual(r2, r)
|
|
self.assertEqual(r2.st_mode, r.st_mode)
|
|
self.assertEqual(r2.st_atime, r.st_atime)
|
|
self.assertEqual(r2.st_atime_ns, r.st_atime_ns)
|
|
self.assertIs(r2[0], r[0])
|
|
self.assertIs(r2.st_mode, r.st_mode)
|
|
self.assertIs(r2.st_atime, r.st_atime)
|
|
self.assertIs(r2.st_atime_ns, r.st_atime_ns)
|
|
|
|
r3 = copy.deepcopy(r)
|
|
self.assertEqual(r3.__class__, r.__class__)
|
|
self.assertEqual(r3, r)
|
|
self.assertEqual(r3.st_mode, r.st_mode)
|
|
self.assertEqual(r3.st_atime, r.st_atime)
|
|
self.assertEqual(r3.st_atime_ns, r.st_atime_ns)
|
|
self.assertIsNot(r3[0], r[0])
|
|
self.assertIsNot(r3.st_mode, r.st_mode)
|
|
self.assertIsNot(r3.st_atime, r.st_atime)
|
|
self.assertIsNot(r3.st_atime_ns, r.st_atime_ns)
|
|
|
|
def test_extended_getslice(self):
|
|
# Test extended slicing by comparing with list slicing.
|
|
t = time.gmtime()
|
|
L = list(t)
|
|
indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
|
|
for start in indices:
|
|
for stop in indices:
|
|
# Skip step 0 (invalid)
|
|
for step in indices[1:]:
|
|
self.assertEqual(list(t[start:stop:step]),
|
|
L[start:stop:step])
|
|
|
|
def test_match_args(self):
|
|
expected_args = ('tm_year', 'tm_mon', 'tm_mday', 'tm_hour', 'tm_min',
|
|
'tm_sec', 'tm_wday', 'tm_yday', 'tm_isdst')
|
|
self.assertEqual(time.struct_time.__match_args__, expected_args)
|
|
|
|
def test_match_args_with_unnamed_fields(self):
|
|
expected_args = ('st_mode', 'st_ino', 'st_dev', 'st_nlink', 'st_uid',
|
|
'st_gid', 'st_size')
|
|
self.assertEqual(os.stat_result.n_unnamed_fields, 3)
|
|
self.assertEqual(os.stat_result.__match_args__, expected_args)
|
|
|
|
def test_copy_replace_all_fields_visible(self):
|
|
assert os.times_result.n_unnamed_fields == 0
|
|
assert os.times_result.n_sequence_fields == os.times_result.n_fields
|
|
|
|
t = os.times()
|
|
|
|
# visible fields
|
|
self.assertEqual(copy.replace(t), t)
|
|
self.assertIsInstance(copy.replace(t), os.times_result)
|
|
self.assertEqual(copy.replace(t, user=1.5), (1.5, *t[1:]))
|
|
self.assertEqual(copy.replace(t, system=2.5), (t[0], 2.5, *t[2:]))
|
|
self.assertEqual(copy.replace(t, user=1.5, system=2.5), (1.5, 2.5, *t[2:]))
|
|
|
|
# unknown fields
|
|
with self.assertRaisesRegex(TypeError, 'unexpected field name'):
|
|
copy.replace(t, error=-1)
|
|
with self.assertRaisesRegex(TypeError, 'unexpected field name'):
|
|
copy.replace(t, user=1, error=-1)
|
|
|
|
@unittest.expectedFailure # TODO: RUSTPYTHON; Wrong error message
|
|
def test_copy_replace_with_invisible_fields(self):
|
|
assert time.struct_time.n_unnamed_fields == 0
|
|
assert time.struct_time.n_sequence_fields < time.struct_time.n_fields
|
|
|
|
t = time.gmtime(0)
|
|
|
|
# visible fields
|
|
t2 = copy.replace(t)
|
|
self.assertEqual(t2, (1970, 1, 1, 0, 0, 0, 3, 1, 0))
|
|
self.assertIsInstance(t2, time.struct_time)
|
|
t3 = copy.replace(t, tm_year=2000)
|
|
self.assertEqual(t3, (2000, 1, 1, 0, 0, 0, 3, 1, 0))
|
|
self.assertEqual(t3.tm_year, 2000)
|
|
t4 = copy.replace(t, tm_mon=2)
|
|
self.assertEqual(t4, (1970, 2, 1, 0, 0, 0, 3, 1, 0))
|
|
self.assertEqual(t4.tm_mon, 2)
|
|
t5 = copy.replace(t, tm_year=2000, tm_mon=2)
|
|
self.assertEqual(t5, (2000, 2, 1, 0, 0, 0, 3, 1, 0))
|
|
self.assertEqual(t5.tm_year, 2000)
|
|
self.assertEqual(t5.tm_mon, 2)
|
|
|
|
# named invisible fields
|
|
self.assertHasAttr(t, 'tm_zone')
|
|
with self.assertRaisesRegex(AttributeError, 'readonly attribute'):
|
|
t.tm_zone = 'some other zone'
|
|
self.assertEqual(t2.tm_zone, t.tm_zone)
|
|
self.assertEqual(t3.tm_zone, t.tm_zone)
|
|
self.assertEqual(t4.tm_zone, t.tm_zone)
|
|
t6 = copy.replace(t, tm_zone='some other zone')
|
|
self.assertEqual(t, t6)
|
|
self.assertEqual(t6.tm_zone, 'some other zone')
|
|
t7 = copy.replace(t, tm_year=2000, tm_zone='some other zone')
|
|
self.assertEqual(t7, (2000, 1, 1, 0, 0, 0, 3, 1, 0))
|
|
self.assertEqual(t7.tm_year, 2000)
|
|
self.assertEqual(t7.tm_zone, 'some other zone')
|
|
|
|
# unknown fields
|
|
with self.assertRaisesRegex(TypeError, 'unexpected field name'):
|
|
copy.replace(t, error=2)
|
|
with self.assertRaisesRegex(TypeError, 'unexpected field name'):
|
|
copy.replace(t, tm_year=2000, error=2)
|
|
with self.assertRaisesRegex(TypeError, 'unexpected field name'):
|
|
copy.replace(t, tm_zone='some other zone', error=2)
|
|
|
|
def test_copy_replace_with_unnamed_fields(self):
|
|
assert os.stat_result.n_unnamed_fields > 0
|
|
|
|
r = os.stat_result(range(os.stat_result.n_sequence_fields))
|
|
|
|
error_message = re.escape('__replace__() is not supported')
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
copy.replace(r)
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
copy.replace(r, st_mode=1)
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
copy.replace(r, error=2)
|
|
with self.assertRaisesRegex(TypeError, error_message):
|
|
copy.replace(r, st_mode=1, error=2)
|
|
|
|
def test_reference_cycle(self):
|
|
# gh-122527: Check that a structseq that's part of a reference cycle
|
|
# with its own type doesn't crash. Previously, if the type's dictionary
|
|
# was cleared first, the structseq instance would crash in the
|
|
# destructor.
|
|
script_helper.assert_python_ok("-c", textwrap.dedent(r"""
|
|
import time
|
|
t = time.gmtime()
|
|
type(t).refcyle = t
|
|
"""))
|
|
|
|
def test_replace_gc_tracked(self):
|
|
# Verify that __replace__ results are properly GC-tracked
|
|
time_struct = time.gmtime(0)
|
|
lst = []
|
|
replaced_struct = time_struct.__replace__(tm_year=lst)
|
|
lst.append(replaced_struct)
|
|
|
|
self.assertTrue(gc.is_tracked(replaced_struct))
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|