mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-28 10:44:36 +08:00
* _json: add native make_encoder (c_make_encoder)
json.encoder fell back to the pure-Python _make_iterencode because _json
had no make_encoder, making json.dumps ~25x slower than CPython. Implement
the C encoder semantics natively: str/None/bool/int/float/list/tuple/dict
ordering, key coercion and skipkeys, sort_keys via the VM's fallible sort
(comparison errors propagate instead of panicking), circular reference
detection, indent handling, allow_nan, default() fallback with recursion
guard, and CPython's add_note annotations. Removes the now-passing
expectedFailure markers in test_json.
Assisted-by: Claude Code:claude-fable-5-1
* pyexpat: add UseForeignDTD, fix silently swallowed handler exceptions
genshi's XML template loader (bm_genshi) called xmlparser.UseForeignDTD(),
which pyexpat.rs didn't implement, raising AttributeError. Add it as an
accepted no-op: the pyexpat module here wraps the pure-Rust xml-rs crate
(not real libexpat), which has no hook for splicing in a foreign DTD.
Root-causing the resulting bug also uncovered why genshi's template
generate()/render() produced empty output instead of erroring: do_parse's
invoke_handler swallowed every exception raised by a Python callback
(handler.call(...).ok()), and genshi's expat callbacks fail immediately
by reading `parser.CurrentLineNumber`/`CurrentColumnNumber`, which
pyexpat.rs never exposed. The AttributeError was silently discarded,
so no start/end/text events ever reached genshi's queue.
Fix both: propagate handler exceptions out of Parse()/ParseFile() (matching
libexpat/CPython semantics), and add CurrentLineNumber/CurrentColumnNumber/
CurrentByteIndex as read-only attributes backed by xml-rs's per-event
TextPosition (byte index is derived from it and is exact for ASCII
documents). This also fixes test_minidom's
testExceptionOnSpacesInXMLNSValue, previously an expected failure because
the ValueError from an invalid xmlns value was swallowed the same way.
PositionTest in test_pyexpat.py checks byte-exact expat semantics (token
*start* position) that xml-rs's *current parse cursor* position can't
reproduce exactly, so that one test is now marked an expected failure.
Assisted-by: Claude Code:claude-fable-5-1
* pyexpat: support multi-chunk Parse()/ParseFile() feeds
bm_xml_etree failed with AssertionError: missing end tags from
TreeBuilder.close(), because xml.etree.ElementTree reads and feeds large
documents to XMLParser.feed() in ~64KB chunks (and xml.sax's
IncrementalParser and ElementTree's XMLPullParser do the same). Each
Parse()/ParseFile() call built a brand-new xml-rs EventReader from only
the bytes passed in that call, discarding all parser state between calls.
When a chunk boundary fell in the middle of an element, the fragment
parsed by itself was invalid/incomplete XML, so xml-rs silently errored
out (matching this module's existing "ignore stricter xml-rs errors"
behavior) and the corresponding start/end events were dropped entirely
-- not just delayed.
xml-rs has no API to resume a parser across separate Read sources, so
instead each call now appends the new chunk to a persistent buffer and
re-parses the buffer as a whole, replaying only the events at or beyond
the count already dispatched in previous calls (dispatched_events). This
also makes position tracking (CurrentLineNumber/Column/ByteIndex) correct
regardless of how the input was chunked. Trade-off: each Parse() call is
now O(size fed so far), so a document delivered in many small chunks is
parsed several times over; acceptable for correctness but noticeably
slower than a true incremental parser for pathological chunk sizes.
This also fixes several previously-xfailed tests that depend on
incremental feeding: test_xml_etree.py's XMLPullParserTest (test_events,
test_feed_while_iterating, test_simple_xml, test_simple_xml_chunk_22,
test_simple_xml_with_ns) and ElementTreeTest.test_parseliteral, plus
test_sax.py's ExpatReaderTest (test_expat_entityresolver_default,
test_expat_incremental, test_expat_incremental_reset) -- their
expectedFailure markers are removed. test_simple_xml_chunk_1/_chunk_5
(1- and 5-byte chunks) still fail and remain xfail: at that granularity
xml-rs's stricter-than-expat tokenizer errors on some intermediate
prefixes that libexpat tolerates.
Assisted-by: Claude Code:claude-fable-5-1
* test: drop stale expectedFailure markers fixed by the pyexpat changes
test_plistlib's four invalid-document tests and test_xmlrpc's
test_loads_unsupported pass now that pyexpat no longer swallows
handler exceptions and keeps parser state across chunked feeds.
Assisted-by: Claude Code:claude-fable-5-1
* pyexpat: drive a single background EventReader for true incremental Parse()
8802451f3 fixed multi-chunk Parse()/ParseFile() feeds by accumulating every
fed byte and re-parsing the whole buffer from scratch on each call, which is
O(total bytes) per chunk -- quadratic in document size. xml-rs's EventReader
has no API to pause/resume across separate Read sources, so instead one
EventReader is now driven to completion on a dedicated background thread fed
through a condvar-backed queue (FeedBuffer/FeedReader); Parse()/ParseFile()
push their chunk, wake the thread, and drain (on the calling thread only)
whatever events that unblocks, stopping once the thread reports it is
blocked waiting for more input. Handlers always run on the calling thread.
A handler exception stops dispatch without tearing down the stream, so the
next Parse() resumes where it left off, mirroring libexpat. CurrentByteIndex
is now computed incrementally per line (with an amortized per-query cursor,
needed since real documents are often a single very long line) instead of
scanning the whole buffer. ParserCreate() never spawns a thread; one is
spawned lazily by the first Parse()/ParseFile() call, and dropping the
parser always stops and joins it.
Fixes test_xml_etree{,_c}'s test_events_comment, previously xfailed because
the old whole-buffer replay lost top-level comment events across feeds.
Measured (M4 Pro, release build):
- Scaling (ElementTree.parse, newline-separated doc): new backend 1/4/16 MB
= 0.15/0.61/2.35s (linear); CPython 3.14 same file = 0.015/0.055/0.23s.
- pyperformance's bm_xml_etree doc (156KB, effectively one line): old
backend single etree.parse() = 1.99s, single iterparse() = 3.53s; new
backend = 0.025s / 0.031s (~80-110x). Full bench_parse/iterparse/generate/
process (30/10/10/1 reps) now finish in ~1.5s/0.6s/0.4s/0.3s instead of
timing out past pyperformance's 400s limit.
- 10k ParserCreate() (never fed / partially fed / fully fed and dropped):
0.32s, no residual native threads, no RSS growth.
test -j4 test_pyexpat test_xml_etree test_xml_etree_c test_sax test_minidom
test_xml_dom_minicompat test_pulldom test_plistlib test_xmlrpc test_html
test_htmlparser test_threading: all pass (1350 tests, 89 skipped).
Assisted-by: Claude Code:claude-fable-5-1
* pyexpat: add a Sync fallback backend for targets without threads
2f58e9531 made pyexpat always drive its EventReader on a background
thread (ParserStream::spawn), panicking via .expect() if the thread
couldn't be spawned. pyexpat is registered unconditionally, including
on wasm32, where std::thread::spawn always fails at runtime, so the
first Parse() call panicked there.
Introduce a Backend enum: Backend::Threaded (the existing ParserStream)
on targets that can spawn threads, and a new Backend::Sync, the
accumulate-and-reparse implementation from 8802451f3, used on wasm32
and as a runtime fallback if spawning a thread ever fails. Both share
LineTracker for identical CurrentLineNumber/CurrentColumnNumber/
CurrentByteIndex and handler/error semantics.
Fixed two correctness bugs while porting the Sync backend forward:
marking the parser permanently "finished" as soon as a from-scratch
reparse happened to reach EndDocument (which can be a false positive
on a not-yet-complete buffer, e.g. right before epilog content
arrives) rather than only on the caller's real isfinal signal; and
counting that same EndDocument towards the dispatched-event index,
which could make a real event land on an index a later, longer reparse
had already skipped past. Verified by force-selecting Backend::Sync
under a test-only env var (removed) and diffing its output against
Backend::Threaded for the xml/sax/etree/plistlib/xmlrpc test suites
and a 2MB document fed in 1KB chunks.
Assisted-by: Claude Code:claude-fable-5-1
* _pickle: native Pickler, Unpickler and PickleBuffer
Adds `crates/stdlib/src/pickle.rs`, a native `_pickle` implementing
Pickler, Unpickler, PickleBuffer, PicklerMemoProxy/UnpicklerMemoProxy,
dump/dumps/load/loads and the PickleError family, so `Lib/pickle.py`
stops falling back to `_Pickler`/`_Unpickler`.
Protocols 0-5 are supported and produce byte-identical output to the
pure-Python pickler, including framing for protocol >= 4, memoization,
`fast` mode, dispatch_table, reducer_override, persistent_id /
persistent_load, find_class with `_compat_pickle` fix_imports, buffer
callbacks and out-of-band protocol 5 buffers. This also turns on
`pickle.PickleBuffer`, which RustPython did not have before.
Speedups over the pure-Python implementation (best of 5, us/op):
pickle 835 -> 21 (39x), pickle_list 525 -> 4.4 (119x),
pickle_dict 4018 -> 32 (125x), unpickle 630 -> 24 (26x),
unpickle_list 317 -> 5.0 (63x). CPython 3.14's C accelerator runs the
same workloads 1.5-2.9x faster than this.
test_pickle now runs 1008 tests (was 470) since the C-implementation
test classes are enabled; test_pickle, test_pickletools,
test_picklebuffer are green and 22 obsolete expectedFailure markers are
removed.
Assisted-by: Claude Code:claude-fable-5-1
* _pickle: raise the pickle.find_class audit event
Unpickler.find_class now raises `sys.audit('pickle.find_class', module,
name)` like CPython, so audit hooks can veto global lookups
(test_audit.test_pickle). Also drops four expectedFailure markers that
the native module makes pass: test_pydoc's builtin-method description
tests, test_memoryview.test_picklebuffer_reference_loop and
test_pyclbr.test_others.
Full suite: 456 test files / 42,648 tests green.
Assisted-by: Claude Code:claude-fable-5-1
* _pickle: avoid temporary buffers on the save fast paths
Opcode plus payload is now appended straight to the output buffer
(`write_pair`) instead of building a `Vec` per int, str, bytes and memo
opcode, `save_tuple` no longer copies the element slice, and the
`when serializing ...` note text is only formatted when an error is
actually raised.
bm_pickle "pickle" workload: 21.4 -> 17.0 us/op.
Assisted-by: Claude Code:claude-fable-5-1
* pyexpat: make the threaded backend fork-safe
fork() only keeps the calling thread. test_platform's
test_mac_ver_with_fork crashed the child with SIGTRAP: plistlib parses
a plist through pyexpat (spawning a background parser thread) before
os.fork(), then parses again in the child. Bisecting away every other
explanation (a plain threading.Thread survives the same fork fine,
since it goes through this VM's own fork-safe thread bookkeeping)
showed the crash is not from touching the *inherited* ParserStream
(already joined by refcounting before the fork in this repro) but from
spawning a *brand new* parser thread from the child, which reliably
crashed during the new thread's own startup.
Register a pthread_atfork child hook (lazily, the first time a parser
thread is spawned) that sets a permanent, process-wide flag the
instant this process is ever the child of a fork(). Once set:
- ParserStream::try_spawn refuses to spawn any further thread and
Backend::new falls back to Backend::Sync instead, exactly as on
targets that cannot spawn threads at all.
- Feeding an inherited Backend::Threaded raises a clear ExpatError
instead of touching its FeedBuffer/channel (whose mutex/condvar may
look held by a thread that no longer exists), and dropping it leaks
its JoinHandle/buffer/channel via ManuallyDrop rather than joining or
destroying them, since even destroying a POSIX mutex that looks held
is undefined behavior.
The parent is unaffected: the pthread_atfork hook only runs in the
child. Verified with a 200-iteration fork stress test (fresh parsers
and parsers forked mid-parse) and the full test_platform/xml/fork/
subprocess/multiprocessing_fork test modules.
Assisted-by: Claude Code:claude-fable-5-1
* pyexpat: implement name interning via self.intern, matching libexpat
self.intern (an always-present dict by default) was stored but never
consulted; every StartElement/EndElement/attribute name allocated a
fresh PyStr even when the same tag or attribute name repeated across
many sibling events. Wire it up the way libexpat does
(PyDict_SetDefault(self->intern, name, name)): element and attribute
*names* are now memoized so a repeated name reuses the same PyStr
object (and its cached hash) instead of reallocating and rehashing.
Attribute values are left out of the cache, same as libexpat.
This fixes test_pyexpat's previously-xfailed InterningTest.test, which
asserts object identity across repeated StartElementHandler/
EndElementHandler calls.
Measured on the pyperformance xml_etree parse/iterparse/generate/
process variants: no measurable wall-clock change (the dominant cost
there is Python-level TreeBuilder/Element bytecode execution and
thread hand-off, not name allocation), so this is a correctness/
feature-completion fix rather than a throughput win for that
benchmark; kept because it is a real, previously-inert compatibility
gap and is otherwise free.
Assisted-by: Claude Code:claude-fable-5-1
* _elementtree: native Element, SubElement and ParseError
Adds crates/stdlib/src/elementtree.rs providing the accelerator names
xml/etree/ElementTree.py picks up at import time. Element carries the
full API (tag/text/tail/attrib, indexing and slicing, find*/iter/
itertext, copy/deepcopy/pickle state) with CPython's lazily created
attrib dict and deferred text join, is subclassable, weak-referenceable
and GC-traversable, and drops every displaced object after releasing its
lock so a __del__ can re-enter safely.
xml_etree, best of 3 (s): parse 1.64 -> 1.14, iterparse 0.68 -> 0.54,
generate 0.44 -> 0.25, process 0.27 -> 0.16.
Assisted-by: Claude Code:claude-fable-5-1
* _elementtree: native TreeBuilder and XMLParser
TreeBuilder keeps CPython's element/data/tail bookkeeping in Rust,
including the pull-parser event hooks _setevents installs. XMLParser
drives a pyexpat parser whose handlers are this type's own native
methods, so a start or end tag reaches the builder without a Python
frame: the universal-name cache, attribute dict and TreeBuilder call all
happen in Rust when the target is our own builder, while foreign targets
still go through the documented start/end/data/comment/pi protocol.
ElementTree.parse() also picks up the _parse_whole fast path.
xml_etree, best of 3 (s): parse 1.14 -> 0.53, iterparse 0.54 -> 0.28,
generate 0.25 -> 0.24, process 0.16 -> 0.16. Against the pure-Python
baseline that is parse 3.1x, iterparse 2.4x, generate 1.8x, process
1.7x.
Assisted-by: Claude Code:claude-fable-5-1
* pyexpat: stop rescanning the whole line per position query
LineTracker converted a TextPosition column to a byte offset by
validating and decoding its entire buffered line tail on every query,
and appended fed bytes to that tail one at a time. On a document that is
one long line -- what xml.etree.tostring() writes, and what the
xml_etree benchmark parses -- the tail is the whole read-ahead, so a
per-event lookup became quadratic. Walk only the characters the query
actually asks for, over the deque's two halves in place, and record fed
bytes a line at a time. Byte indices are unchanged.
xml_etree, best of 3 (s): parse 0.52 -> 0.38, iterparse 0.28 -> 0.25.
Assisted-by: Claude Code:claude-fable-5-1
* _elementtree: charge Element.__deepcopy__ to the recursion budget
A chain of elements is copied by native recursion, so a deep enough tree
overflowed the real stack instead of raising. Wrap the copy in
with_recursion, as CPython does, and drop the skip on
test_deeply_nested_deepcopy for the accelerated run.
Assisted-by: Claude Code:claude-fable-5-1
* pyexpat: don't let a stale NeedMore end a Parse() early
The parser thread reports NeedMore when it finds the feed buffer empty
and parks. If it reached that point before the chunk Parse() was about
to push became visible -- which it does whenever the thread happens to
be scheduled first, so more often under load -- pump() consumed that
report as if it answered the new chunk and handed control back to Python
having dispatched nothing, silently losing the whole document.
Stamp each NeedMore with the push count observed when the buffer was
found empty and ignore reports older than the push being pumped. The
push notifies the condvar under the same mutex the report was sent
from, so the parser thread is guaranteed to wake and report again.
Fixes an intermittent failure of test_pyexpat's InterningTest under
parallel load (about 5 losses per 20000 parses before, none after).
Assisted-by: Claude Code:claude-fable-5-1
* Restore xml.etree test markers instead of skipTest in bodies
Assisted-by: Grok:4.6
* Clone state before try_to_bool in pickle load_build
try_to_bool takes the object by value, and load_build still needs the
state dict afterwards.
Assisted-by: Grok:4.6
* Drop decorative section-separator comments
Assisted-by: Grok:4.6
* Represent pickle opcodes as an enum
Assisted-by: Grok:4.6
* Use full paths for thread-only types in pyexpat
Assisted-by: Grok:4.6
---------
Co-authored-by: Lee Dogeon <dev.moreal@gmail.com>
836 lines
28 KiB
Python
Vendored
836 lines
28 KiB
Python
Vendored
"""Unit tests for the memoryview
|
|
|
|
Some tests are in test_bytes. Many tests that require _testbuffer.ndarray
|
|
are in test_buffer.
|
|
"""
|
|
|
|
import unittest
|
|
import test.support
|
|
import sys
|
|
import gc
|
|
import weakref
|
|
import array
|
|
import io
|
|
import copy
|
|
import pickle
|
|
import struct
|
|
|
|
from itertools import product
|
|
from test import support
|
|
from test.support import import_helper, threading_helper
|
|
|
|
|
|
class MyObject:
|
|
pass
|
|
|
|
|
|
class AbstractMemoryTests:
|
|
source_bytes = b"abcdef"
|
|
|
|
@property
|
|
def _source(self):
|
|
return self.source_bytes
|
|
|
|
@property
|
|
def _types(self):
|
|
return filter(None, [self.ro_type, self.rw_type])
|
|
|
|
def check_getitem_with_type(self, tp):
|
|
b = tp(self._source)
|
|
oldrefcount = sys.getrefcount(b)
|
|
m = self._view(b)
|
|
self.assertEqual(m[0], ord(b"a"))
|
|
self.assertIsInstance(m[0], int)
|
|
self.assertEqual(m[5], ord(b"f"))
|
|
self.assertEqual(m[-1], ord(b"f"))
|
|
self.assertEqual(m[-6], ord(b"a"))
|
|
# Bounds checking
|
|
self.assertRaises(IndexError, lambda: m[6])
|
|
self.assertRaises(IndexError, lambda: m[-7])
|
|
self.assertRaises(IndexError, lambda: m[sys.maxsize])
|
|
self.assertRaises(IndexError, lambda: m[-sys.maxsize])
|
|
# Type checking
|
|
self.assertRaises(TypeError, lambda: m[None])
|
|
self.assertRaises(TypeError, lambda: m[0.0])
|
|
self.assertRaises(TypeError, lambda: m["a"])
|
|
m = None
|
|
self.assertEqual(sys.getrefcount(b), oldrefcount)
|
|
|
|
def test_getitem(self):
|
|
for tp in self._types:
|
|
self.check_getitem_with_type(tp)
|
|
|
|
def test_index(self):
|
|
for tp in self._types:
|
|
b = tp(self._source)
|
|
m = self._view(b) # may be a sub-view
|
|
l = m.tolist()
|
|
k = 2 * len(self._source)
|
|
|
|
for chi in self._source:
|
|
if chi in l:
|
|
self.assertEqual(m.index(chi), l.index(chi))
|
|
else:
|
|
self.assertRaises(ValueError, m.index, chi)
|
|
|
|
for start, stop in product(range(-k, k), range(-k, k)):
|
|
index = -1
|
|
try:
|
|
index = l.index(chi, start, stop)
|
|
except ValueError:
|
|
pass
|
|
|
|
if index == -1:
|
|
self.assertRaises(ValueError, m.index, chi, start, stop)
|
|
else:
|
|
self.assertEqual(m.index(chi, start, stop), index)
|
|
|
|
def test_iter(self):
|
|
for tp in self._types:
|
|
b = tp(self._source)
|
|
m = self._view(b)
|
|
self.assertEqual(list(m), [m[i] for i in range(len(m))])
|
|
|
|
def test_count(self):
|
|
for tp in self._types:
|
|
b = tp(self._source)
|
|
m = self._view(b)
|
|
l = m.tolist()
|
|
for ch in list(m):
|
|
self.assertEqual(m.count(ch), l.count(ch))
|
|
|
|
b = tp((b'a' * 5) + (b'c' * 3))
|
|
m = self._view(b) # may be sliced
|
|
l = m.tolist()
|
|
with self.subTest('count', buffer=b):
|
|
self.assertEqual(m.count(ord('a')), l.count(ord('a')))
|
|
self.assertEqual(m.count(ord('b')), l.count(ord('b')))
|
|
self.assertEqual(m.count(ord('c')), l.count(ord('c')))
|
|
|
|
def test_setitem_readonly(self):
|
|
if not self.ro_type:
|
|
self.skipTest("no read-only type to test")
|
|
b = self.ro_type(self._source)
|
|
oldrefcount = sys.getrefcount(b)
|
|
m = self._view(b)
|
|
def setitem(value):
|
|
m[0] = value
|
|
self.assertRaises(TypeError, setitem, b"a")
|
|
self.assertRaises(TypeError, setitem, 65)
|
|
self.assertRaises(TypeError, setitem, memoryview(b"a"))
|
|
m = None
|
|
self.assertEqual(sys.getrefcount(b), oldrefcount)
|
|
|
|
def test_setitem_writable(self):
|
|
if not self.rw_type:
|
|
self.skipTest("no writable type to test")
|
|
tp = self.rw_type
|
|
b = self.rw_type(self._source)
|
|
oldrefcount = sys.getrefcount(b)
|
|
m = self._view(b)
|
|
m[0] = ord(b'1')
|
|
self._check_contents(tp, b, b"1bcdef")
|
|
m[0:1] = tp(b"0")
|
|
self._check_contents(tp, b, b"0bcdef")
|
|
m[1:3] = tp(b"12")
|
|
self._check_contents(tp, b, b"012def")
|
|
m[1:1] = tp(b"")
|
|
self._check_contents(tp, b, b"012def")
|
|
m[:] = tp(b"abcdef")
|
|
self._check_contents(tp, b, b"abcdef")
|
|
|
|
# Overlapping copies of a view into itself
|
|
m[0:3] = m[2:5]
|
|
self._check_contents(tp, b, b"cdedef")
|
|
m[:] = tp(b"abcdef")
|
|
m[2:5] = m[0:3]
|
|
self._check_contents(tp, b, b"ababcf")
|
|
|
|
def setitem(key, value):
|
|
m[key] = tp(value)
|
|
# Bounds checking
|
|
self.assertRaises(IndexError, setitem, 6, b"a")
|
|
self.assertRaises(IndexError, setitem, -7, b"a")
|
|
self.assertRaises(IndexError, setitem, sys.maxsize, b"a")
|
|
self.assertRaises(IndexError, setitem, -sys.maxsize, b"a")
|
|
# Wrong index/slice types
|
|
self.assertRaises(TypeError, setitem, 0.0, b"a")
|
|
self.assertRaises(TypeError, setitem, (0,), b"a")
|
|
self.assertRaises(TypeError, setitem, (slice(0,1,1), 0), b"a")
|
|
self.assertRaises(TypeError, setitem, (0, slice(0,1,1)), b"a")
|
|
self.assertRaises(TypeError, setitem, (0,), b"a")
|
|
self.assertRaises(TypeError, setitem, "a", b"a")
|
|
# Not implemented: multidimensional slices
|
|
slices = (slice(0,1,1), slice(0,1,2))
|
|
self.assertRaises(NotImplementedError, setitem, slices, b"a")
|
|
# Trying to resize the memory object
|
|
exc = ValueError if m.format == 'c' else TypeError
|
|
self.assertRaises(exc, setitem, 0, b"")
|
|
self.assertRaises(exc, setitem, 0, b"ab")
|
|
self.assertRaises(ValueError, setitem, slice(1,1), b"a")
|
|
self.assertRaises(ValueError, setitem, slice(0,2), b"a")
|
|
|
|
m = None
|
|
self.assertEqual(sys.getrefcount(b), oldrefcount)
|
|
|
|
def test_delitem(self):
|
|
for tp in self._types:
|
|
b = tp(self._source)
|
|
m = self._view(b)
|
|
with self.assertRaises(TypeError):
|
|
del m[1]
|
|
with self.assertRaises(TypeError):
|
|
del m[1:4]
|
|
|
|
def test_tobytes(self):
|
|
for tp in self._types:
|
|
m = self._view(tp(self._source))
|
|
b = m.tobytes()
|
|
# This calls self.getitem_type() on each separate byte of b"abcdef"
|
|
expected = b"".join(
|
|
self.getitem_type(bytes([c])) for c in b"abcdef")
|
|
self.assertEqual(b, expected)
|
|
self.assertIsInstance(b, bytes)
|
|
|
|
def test_tolist(self):
|
|
for tp in self._types:
|
|
m = self._view(tp(self._source))
|
|
l = m.tolist()
|
|
self.assertEqual(l, list(b"abcdef"))
|
|
|
|
def test_compare(self):
|
|
# memoryviews can compare for equality with other objects
|
|
# having the buffer interface.
|
|
for tp in self._types:
|
|
m = self._view(tp(self._source))
|
|
for tp_comp in self._types:
|
|
self.assertTrue(m == tp_comp(b"abcdef"))
|
|
self.assertFalse(m != tp_comp(b"abcdef"))
|
|
self.assertFalse(m == tp_comp(b"abcde"))
|
|
self.assertTrue(m != tp_comp(b"abcde"))
|
|
self.assertFalse(m == tp_comp(b"abcde1"))
|
|
self.assertTrue(m != tp_comp(b"abcde1"))
|
|
self.assertTrue(m == m)
|
|
self.assertTrue(m == m[:])
|
|
self.assertTrue(m[0:6] == m[:])
|
|
self.assertFalse(m[0:5] == m)
|
|
|
|
# Comparison with objects which don't support the buffer API
|
|
self.assertFalse(m == "abcdef")
|
|
self.assertTrue(m != "abcdef")
|
|
self.assertFalse("abcdef" == m)
|
|
self.assertTrue("abcdef" != m)
|
|
|
|
# Unordered comparisons
|
|
for c in (m, b"abcdef"):
|
|
self.assertRaises(TypeError, lambda: m < c)
|
|
self.assertRaises(TypeError, lambda: c <= m)
|
|
self.assertRaises(TypeError, lambda: m >= c)
|
|
self.assertRaises(TypeError, lambda: c > m)
|
|
|
|
def check_attributes_with_type(self, tp):
|
|
m = self._view(tp(self._source))
|
|
self.assertEqual(m.format, self.format)
|
|
self.assertEqual(m.itemsize, self.itemsize)
|
|
self.assertEqual(m.ndim, 1)
|
|
self.assertEqual(m.shape, (6,))
|
|
self.assertEqual(len(m), 6)
|
|
self.assertEqual(m.strides, (self.itemsize,))
|
|
self.assertEqual(m.suboffsets, ())
|
|
return m
|
|
|
|
def test_attributes_readonly(self):
|
|
if not self.ro_type:
|
|
self.skipTest("no read-only type to test")
|
|
m = self.check_attributes_with_type(self.ro_type)
|
|
self.assertEqual(m.readonly, True)
|
|
|
|
def test_attributes_writable(self):
|
|
if not self.rw_type:
|
|
self.skipTest("no writable type to test")
|
|
m = self.check_attributes_with_type(self.rw_type)
|
|
self.assertEqual(m.readonly, False)
|
|
|
|
def test_getbuffer(self):
|
|
# Test PyObject_GetBuffer() on a memoryview object.
|
|
for tp in self._types:
|
|
b = tp(self._source)
|
|
oldrefcount = sys.getrefcount(b)
|
|
m = self._view(b)
|
|
oldviewrefcount = sys.getrefcount(m)
|
|
s = str(m, "utf-8")
|
|
self._check_contents(tp, b, s.encode("utf-8"))
|
|
self.assertEqual(sys.getrefcount(m), oldviewrefcount)
|
|
m = None
|
|
self.assertEqual(sys.getrefcount(b), oldrefcount)
|
|
|
|
def test_gc(self):
|
|
for tp in self._types:
|
|
if not isinstance(tp, type):
|
|
# If tp is a factory rather than a plain type, skip
|
|
continue
|
|
|
|
class MyView():
|
|
def __init__(self, base):
|
|
self.m = memoryview(base)
|
|
class MySource(tp):
|
|
pass
|
|
|
|
# Create a reference cycle through a memoryview object.
|
|
# This exercises mbuf_clear().
|
|
b = MySource(tp(b'abc'))
|
|
m = self._view(b)
|
|
o = MyObject()
|
|
b.m = m
|
|
b.o = o
|
|
wr = weakref.ref(o)
|
|
b = m = o = None
|
|
# The cycle must be broken
|
|
gc.collect()
|
|
self.assertTrue(wr() is None, wr())
|
|
|
|
# This exercises memory_clear().
|
|
m = MyView(tp(b'abc'))
|
|
o = MyObject()
|
|
m.x = m
|
|
m.o = o
|
|
wr = weakref.ref(o)
|
|
m = o = None
|
|
# The cycle must be broken
|
|
gc.collect()
|
|
self.assertTrue(wr() is None, wr())
|
|
|
|
def _check_released(self, m, tp):
|
|
check = self.assertRaisesRegex(ValueError, "released")
|
|
with check: bytes(m)
|
|
with check: m.tobytes()
|
|
with check: m.tolist()
|
|
with check: m[0]
|
|
with check: m[0] = b'x'
|
|
with check: len(m)
|
|
with check: m.format
|
|
with check: m.itemsize
|
|
with check: m.ndim
|
|
with check: m.readonly
|
|
with check: m.shape
|
|
with check: m.strides
|
|
with check:
|
|
with m:
|
|
pass
|
|
# str() and repr() still function
|
|
self.assertIn("released memory", str(m))
|
|
self.assertIn("released memory", repr(m))
|
|
self.assertEqual(m, m)
|
|
self.assertNotEqual(m, memoryview(tp(self._source)))
|
|
self.assertNotEqual(m, tp(self._source))
|
|
|
|
def test_contextmanager(self):
|
|
for tp in self._types:
|
|
b = tp(self._source)
|
|
m = self._view(b)
|
|
with m as cm:
|
|
self.assertIs(cm, m)
|
|
self._check_released(m, tp)
|
|
m = self._view(b)
|
|
# Can release explicitly inside the context manager
|
|
with m:
|
|
m.release()
|
|
|
|
def test_release(self):
|
|
for tp in self._types:
|
|
b = tp(self._source)
|
|
m = self._view(b)
|
|
m.release()
|
|
self._check_released(m, tp)
|
|
# Can be called a second time (it's a no-op)
|
|
m.release()
|
|
self._check_released(m, tp)
|
|
|
|
def test_writable_readonly(self):
|
|
# Issue #10451: memoryview incorrectly exposes a readonly
|
|
# buffer as writable causing a segfault if using mmap
|
|
tp = self.ro_type
|
|
if tp is None:
|
|
self.skipTest("no read-only type to test")
|
|
b = tp(self._source)
|
|
m = self._view(b)
|
|
i = io.BytesIO(b'ZZZZ')
|
|
self.assertRaises(TypeError, i.readinto, m)
|
|
|
|
def test_getbuf_fail(self):
|
|
self.assertRaises(TypeError, self._view, {})
|
|
|
|
def test_hash(self):
|
|
# Memoryviews of readonly (hashable) types are hashable, and they
|
|
# hash as hash(obj.tobytes()).
|
|
tp = self.ro_type
|
|
if tp is None:
|
|
self.skipTest("no read-only type to test")
|
|
b = tp(self._source)
|
|
m = self._view(b)
|
|
self.assertEqual(hash(m), hash(b"abcdef"))
|
|
# Releasing the memoryview keeps the stored hash value (as with weakrefs)
|
|
m.release()
|
|
self.assertEqual(hash(m), hash(b"abcdef"))
|
|
# Hashing a memoryview for the first time after it is released
|
|
# results in an error (as with weakrefs).
|
|
m = self._view(b)
|
|
m.release()
|
|
self.assertRaises(ValueError, hash, m)
|
|
|
|
def test_hash_writable(self):
|
|
# Memoryviews of writable types are unhashable
|
|
tp = self.rw_type
|
|
if tp is None:
|
|
self.skipTest("no writable type to test")
|
|
b = tp(self._source)
|
|
m = self._view(b)
|
|
self.assertRaises(ValueError, hash, m)
|
|
|
|
def test_hash_use_after_free(self):
|
|
# Prevent crash in memoryview(v).__hash__ with re-entrant v.__hash__.
|
|
# Regression test for https://github.com/python/cpython/issues/142664.
|
|
class E(array.array):
|
|
def __hash__(self):
|
|
mv.release()
|
|
self.clear()
|
|
return 123
|
|
|
|
v = E('B', b'A' * 4096)
|
|
mv = memoryview(v).toreadonly() # must be read-only for hash()
|
|
self.assertRaises(BufferError, hash, mv)
|
|
self.assertRaises(BufferError, mv.__hash__)
|
|
|
|
def test_weakref(self):
|
|
# Check memoryviews are weakrefable
|
|
for tp in self._types:
|
|
b = tp(self._source)
|
|
m = self._view(b)
|
|
L = []
|
|
def callback(wr, b=b):
|
|
L.append(b)
|
|
wr = weakref.ref(m, callback)
|
|
self.assertIs(wr(), m)
|
|
del m
|
|
test.support.gc_collect()
|
|
self.assertIs(wr(), None)
|
|
self.assertIs(L[0], b)
|
|
|
|
def test_reversed(self):
|
|
for tp in self._types:
|
|
b = tp(self._source)
|
|
m = self._view(b)
|
|
aslist = list(reversed(m.tolist()))
|
|
self.assertEqual(list(reversed(m)), aslist)
|
|
self.assertEqual(list(reversed(m)), list(m[::-1]))
|
|
|
|
def test_toreadonly(self):
|
|
for tp in self._types:
|
|
b = tp(self._source)
|
|
m = self._view(b)
|
|
mm = m.toreadonly()
|
|
self.assertTrue(mm.readonly)
|
|
self.assertTrue(memoryview(mm).readonly)
|
|
self.assertEqual(mm.tolist(), m.tolist())
|
|
mm.release()
|
|
m.tolist()
|
|
|
|
def test_issue22668(self):
|
|
a = array.array('H', [256, 256, 256, 256])
|
|
x = memoryview(a)
|
|
m = x.cast('B')
|
|
b = m.cast('H')
|
|
c = b[0:2]
|
|
d = memoryview(b)
|
|
|
|
del b
|
|
|
|
self.assertEqual(c[0], 256)
|
|
self.assertEqual(d[0], 256)
|
|
self.assertEqual(c.format, "H")
|
|
self.assertEqual(d.format, "H")
|
|
|
|
_ = m.cast('I')
|
|
self.assertEqual(c[0], 256)
|
|
self.assertEqual(d[0], 256)
|
|
self.assertEqual(c.format, "H")
|
|
self.assertEqual(d.format, "H")
|
|
|
|
def test_hex_use_after_free(self):
|
|
# Prevent UAF in memoryview.hex(sep) with re-entrant sep.__len__.
|
|
# Regression test for https://github.com/python/cpython/issues/143195.
|
|
ba = bytearray(b'A' * 1024)
|
|
mv = memoryview(ba)
|
|
|
|
class S(bytes):
|
|
def __len__(self):
|
|
mv.release()
|
|
ba.clear()
|
|
return 1
|
|
|
|
self.assertRaises(BufferError, mv.hex, S(b':'))
|
|
|
|
|
|
# Variations on source objects for the buffer: bytes-like objects, then arrays
|
|
# with itemsize > 1.
|
|
# NOTE: support for multi-dimensional objects is unimplemented.
|
|
|
|
class BaseBytesMemoryTests(AbstractMemoryTests):
|
|
ro_type = bytes
|
|
rw_type = bytearray
|
|
getitem_type = bytes
|
|
itemsize = 1
|
|
format = 'B'
|
|
|
|
class BaseArrayMemoryTests(AbstractMemoryTests):
|
|
ro_type = None
|
|
rw_type = lambda self, b: array.array('i', list(b))
|
|
getitem_type = lambda self, b: array.array('i', list(b)).tobytes()
|
|
itemsize = array.array('i').itemsize
|
|
format = 'i'
|
|
|
|
@unittest.skip('XXX test should be adapted for non-byte buffers')
|
|
def test_getbuffer(self):
|
|
pass
|
|
|
|
@unittest.skip('XXX NotImplementedError: tolist() only supports byte views')
|
|
def test_tolist(self):
|
|
pass
|
|
|
|
|
|
# Variations on indirection levels: memoryview, slice of memoryview,
|
|
# slice of slice of memoryview.
|
|
# This is important to test allocation subtleties.
|
|
|
|
class BaseMemoryviewTests:
|
|
def _view(self, obj):
|
|
return memoryview(obj)
|
|
|
|
def _check_contents(self, tp, obj, contents):
|
|
self.assertEqual(obj, tp(contents))
|
|
|
|
def test_count(self):
|
|
super().test_count()
|
|
for tp in self._types:
|
|
b = tp((b'a' * 5) + (b'c' * 3))
|
|
m = self._view(b) # should not be sliced
|
|
self.assertEqual(len(b), len(m))
|
|
with self.subTest('count', buffer=b):
|
|
self.assertEqual(m.count(ord('a')), 5)
|
|
self.assertEqual(m.count(ord('b')), 0)
|
|
self.assertEqual(m.count(ord('c')), 3)
|
|
|
|
|
|
class BaseMemorySliceTests:
|
|
source_bytes = b"XabcdefY"
|
|
|
|
def _view(self, obj):
|
|
m = memoryview(obj)
|
|
return m[1:7]
|
|
|
|
def _check_contents(self, tp, obj, contents):
|
|
self.assertEqual(obj[1:7], tp(contents))
|
|
|
|
def test_refs(self):
|
|
for tp in self._types:
|
|
m = memoryview(tp(self._source))
|
|
oldrefcount = sys.getrefcount(m)
|
|
m[1:2]
|
|
self.assertEqual(sys.getrefcount(m), oldrefcount)
|
|
|
|
class BaseMemorySliceSliceTests:
|
|
source_bytes = b"XabcdefY"
|
|
|
|
def _view(self, obj):
|
|
m = memoryview(obj)
|
|
return m[:7][1:]
|
|
|
|
def _check_contents(self, tp, obj, contents):
|
|
self.assertEqual(obj[1:7], tp(contents))
|
|
|
|
|
|
# Concrete test classes
|
|
|
|
class BytesMemoryviewTest(unittest.TestCase,
|
|
BaseMemoryviewTests, BaseBytesMemoryTests):
|
|
|
|
def test_constructor(self):
|
|
for tp in self._types:
|
|
ob = tp(self._source)
|
|
self.assertTrue(memoryview(ob))
|
|
self.assertTrue(memoryview(object=ob))
|
|
self.assertRaises(TypeError, memoryview)
|
|
self.assertRaises(TypeError, memoryview, ob, ob)
|
|
self.assertRaises(TypeError, memoryview, argument=ob)
|
|
self.assertRaises(TypeError, memoryview, ob, argument=True)
|
|
|
|
class ArrayMemoryviewTest(unittest.TestCase,
|
|
BaseMemoryviewTests, BaseArrayMemoryTests):
|
|
|
|
def test_array_assign(self):
|
|
# Issue #4569: segfault when mutating a memoryview with itemsize != 1
|
|
a = array.array('i', range(10))
|
|
m = memoryview(a)
|
|
new_a = array.array('i', range(9, -1, -1))
|
|
m[:] = new_a
|
|
self.assertEqual(a, new_a)
|
|
|
|
def test_boolean_format(self):
|
|
# Test '?' format (keep all the checks below for UBSan)
|
|
# See github.com/python/cpython/issues/148390.
|
|
|
|
# m1a and m1b are equivalent to [False, True, False]
|
|
m1a = memoryview(b'\0\2\0').cast('?')
|
|
self.assertEqual(m1a.tolist(), [False, True, False])
|
|
m1b = memoryview(b'\0\4\0').cast('?')
|
|
self.assertEqual(m1b.tolist(), [False, True, False])
|
|
self.assertEqual(m1a, m1b)
|
|
|
|
# m2a and m2b are equivalent to [True, True, True]
|
|
m2a = memoryview(b'\1\3\5').cast('?')
|
|
self.assertEqual(m2a.tolist(), [True, True, True])
|
|
m2b = memoryview(b'\2\4\6').cast('?')
|
|
self.assertEqual(m2b.tolist(), [True, True, True])
|
|
self.assertEqual(m2a, m2b)
|
|
|
|
allbytes = bytes(range(256))
|
|
allbytes = memoryview(allbytes).cast('?')
|
|
self.assertEqual(allbytes.tolist(), [False] + [True] * 255)
|
|
|
|
|
|
class BytesMemorySliceTest(unittest.TestCase,
|
|
BaseMemorySliceTests, BaseBytesMemoryTests):
|
|
pass
|
|
|
|
class ArrayMemorySliceTest(unittest.TestCase,
|
|
BaseMemorySliceTests, BaseArrayMemoryTests):
|
|
pass
|
|
|
|
class BytesMemorySliceSliceTest(unittest.TestCase,
|
|
BaseMemorySliceSliceTests, BaseBytesMemoryTests):
|
|
pass
|
|
|
|
class ArrayMemorySliceSliceTest(unittest.TestCase,
|
|
BaseMemorySliceSliceTests, BaseArrayMemoryTests):
|
|
pass
|
|
|
|
|
|
class OtherTest(unittest.TestCase):
|
|
def test_ctypes_cast(self):
|
|
# Issue 15944: Allow all source formats when casting to bytes.
|
|
ctypes = import_helper.import_module("ctypes")
|
|
p6 = bytes(ctypes.c_double(0.6))
|
|
|
|
d = ctypes.c_double()
|
|
m = memoryview(d).cast("B")
|
|
m[:2] = p6[:2]
|
|
m[2:] = p6[2:]
|
|
self.assertEqual(d.value, 0.6)
|
|
|
|
for format in "Bbc":
|
|
with self.subTest(format):
|
|
d = ctypes.c_double()
|
|
m = memoryview(d).cast(format)
|
|
m[:2] = memoryview(p6).cast(format)[:2]
|
|
m[2:] = memoryview(p6).cast(format)[2:]
|
|
self.assertEqual(d.value, 0.6)
|
|
|
|
def test_half_float(self):
|
|
half_data = struct.pack('eee', 0.0, -1.5, 1.5)
|
|
float_data = struct.pack('fff', 0.0, -1.5, 1.5)
|
|
half_view = memoryview(half_data).cast('e')
|
|
float_view = memoryview(float_data).cast('f')
|
|
self.assertEqual(half_view.nbytes * 2, float_view.nbytes)
|
|
self.assertListEqual(half_view.tolist(), float_view.tolist())
|
|
|
|
def test_memoryview_hex(self):
|
|
# Issue #9951: memoryview.hex() segfaults with non-contiguous buffers.
|
|
x = b'0' * 200000
|
|
m1 = memoryview(x)
|
|
m2 = m1[::-1]
|
|
self.assertEqual(m2.hex(), '30' * 200000)
|
|
|
|
def test_memoryview_hex_separator(self):
|
|
x = bytes(range(97, 102))
|
|
m1 = memoryview(x)
|
|
m2 = m1[::-1]
|
|
self.assertEqual(m2.hex(':'), '65:64:63:62:61')
|
|
self.assertEqual(m2.hex(':', 2), '65:6463:6261')
|
|
self.assertEqual(m2.hex(':', -2), '6564:6362:61')
|
|
self.assertEqual(m2.hex(sep=':', bytes_per_sep=2), '65:6463:6261')
|
|
self.assertEqual(m2.hex(sep=':', bytes_per_sep=-2), '6564:6362:61')
|
|
for bytes_per_sep in 5, -5, 2**31-1, -(2**31-1):
|
|
with self.subTest(bytes_per_sep=bytes_per_sep):
|
|
self.assertEqual(m2.hex(':', bytes_per_sep), '6564636261')
|
|
for bytes_per_sep in 2**31, -2**31, 2**1000, -2**1000:
|
|
with self.subTest(bytes_per_sep=bytes_per_sep):
|
|
try:
|
|
self.assertEqual(m2.hex(':', bytes_per_sep), '6564636261')
|
|
except OverflowError:
|
|
pass
|
|
|
|
def test_copy(self):
|
|
m = memoryview(b'abc')
|
|
with self.assertRaises(TypeError):
|
|
copy.copy(m)
|
|
|
|
def test_pickle(self):
|
|
m = memoryview(b'abc')
|
|
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
|
|
with self.assertRaises(TypeError):
|
|
pickle.dumps(m, proto)
|
|
|
|
def test_use_released_memory(self):
|
|
# gh-92888: Previously it was possible to use a memoryview even after
|
|
# backing buffer is freed in certain cases. This tests that those
|
|
# cases raise an exception.
|
|
size = 128
|
|
def release():
|
|
m.release()
|
|
nonlocal ba
|
|
ba = bytearray(size)
|
|
class MyIndex:
|
|
def __index__(self):
|
|
release()
|
|
return 4
|
|
class MyFloat:
|
|
def __float__(self):
|
|
release()
|
|
return 4.25
|
|
class MyBool:
|
|
def __bool__(self):
|
|
release()
|
|
return True
|
|
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size))
|
|
with self.assertRaises(ValueError):
|
|
m[MyIndex()]
|
|
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size))
|
|
self.assertEqual(list(m[:MyIndex()]), [255] * 4)
|
|
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size))
|
|
self.assertEqual(list(m[MyIndex():8]), [255] * 4)
|
|
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size)).cast('B', (64, 2))
|
|
with self.assertRaisesRegex(ValueError, "operation forbidden"):
|
|
m[MyIndex(), 0]
|
|
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size)).cast('B', (2, 64))
|
|
with self.assertRaisesRegex(ValueError, "operation forbidden"):
|
|
m[0, MyIndex()]
|
|
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size))
|
|
with self.assertRaisesRegex(ValueError, "operation forbidden"):
|
|
m[MyIndex()] = 42
|
|
self.assertEqual(ba[:8], b'\0'*8)
|
|
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size))
|
|
with self.assertRaisesRegex(ValueError, "operation forbidden"):
|
|
m[:MyIndex()] = b'spam'
|
|
self.assertEqual(ba[:8], b'\0'*8)
|
|
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size))
|
|
with self.assertRaisesRegex(ValueError, "operation forbidden"):
|
|
m[MyIndex():8] = b'spam'
|
|
self.assertEqual(ba[:8], b'\0'*8)
|
|
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size)).cast('B', (64, 2))
|
|
with self.assertRaisesRegex(ValueError, "operation forbidden"):
|
|
m[MyIndex(), 0] = 42
|
|
self.assertEqual(ba[8:16], b'\0'*8)
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size)).cast('B', (2, 64))
|
|
with self.assertRaisesRegex(ValueError, "operation forbidden"):
|
|
m[0, MyIndex()] = 42
|
|
self.assertEqual(ba[:8], b'\0'*8)
|
|
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size))
|
|
with self.assertRaisesRegex(ValueError, "operation forbidden"):
|
|
m[0] = MyIndex()
|
|
self.assertEqual(ba[:8], b'\0'*8)
|
|
|
|
for fmt in 'bhilqnBHILQN':
|
|
with self.subTest(fmt=fmt):
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size)).cast(fmt)
|
|
with self.assertRaisesRegex(ValueError, "operation forbidden"):
|
|
m[0] = MyIndex()
|
|
self.assertEqual(ba[:8], b'\0'*8)
|
|
|
|
for fmt in 'fd':
|
|
with self.subTest(fmt=fmt):
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size)).cast(fmt)
|
|
with self.assertRaisesRegex(ValueError, "operation forbidden"):
|
|
m[0] = MyFloat()
|
|
self.assertEqual(ba[:8], b'\0'*8)
|
|
|
|
ba = None
|
|
m = memoryview(bytearray(b'\xff'*size)).cast('?')
|
|
with self.assertRaisesRegex(ValueError, "operation forbidden"):
|
|
m[0] = MyBool()
|
|
self.assertEqual(ba[:8], b'\0'*8)
|
|
|
|
def test_buffer_reference_loop(self):
|
|
m = memoryview(b'abc').__buffer__(0)
|
|
o = MyObject()
|
|
o.m = m
|
|
o.o = o
|
|
wr = weakref.ref(o)
|
|
del m, o
|
|
gc.collect()
|
|
self.assertIsNone(wr())
|
|
|
|
def test_picklebuffer_reference_loop(self):
|
|
pb = pickle.PickleBuffer(memoryview(b'abc'))
|
|
o = MyObject()
|
|
o.pb = pb
|
|
o.o = o
|
|
wr = weakref.ref(o)
|
|
del pb, o
|
|
gc.collect()
|
|
self.assertIsNone(wr())
|
|
|
|
|
|
@threading_helper.requires_working_threading()
|
|
@support.requires_resource("cpu")
|
|
class RacingTest(unittest.TestCase):
|
|
def test_racing_getbuf_and_releasebuf(self):
|
|
"""Repeatly access the memoryview for racing."""
|
|
try:
|
|
from multiprocessing.managers import SharedMemoryManager
|
|
except ImportError:
|
|
self.skipTest("Test requires multiprocessing")
|
|
from threading import Thread, Event
|
|
|
|
start = Event()
|
|
with SharedMemoryManager() as smm:
|
|
obj = smm.ShareableList(range(100))
|
|
def test():
|
|
# Issue gh-127085, the `ShareableList.count` is just a
|
|
# convenient way to mess the `exports` counter of `memoryview`,
|
|
# this issue has no direct relation with `ShareableList`.
|
|
start.wait(support.SHORT_TIMEOUT)
|
|
for i in range(10):
|
|
obj.count(1)
|
|
threads = [Thread(target=test) for _ in range(10)]
|
|
with threading_helper.start_threads(threads):
|
|
start.set()
|
|
|
|
del obj
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|