Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Lib/test/test_memoryio.py
Original file line number Diff line number Diff line change
Expand Up @@ -860,6 +860,28 @@ class CBytesIOTest(PyBytesIOTest):
ioclass = io.BytesIO
UnsupportedOperation = io.UnsupportedOperation

def test_truncate_size_changes_stream(self):
class Size:
def __init__(self, action):
self.action = action

def __index__(self):
self.result = self.action()
return 0

stream = self.ioclass(b'abc')
with self.assertRaises(ValueError):
stream.truncate(Size(stream.close))

with self.ioclass(b'abc') as stream:
size = Size(stream.getbuffer)
try:
with self.assertRaises(BufferError):
stream.truncate(size)
self.assertEqual(stream.getvalue(), b'abc')
finally:
size.result.release()

def test_readinto_overlapping_buffer(self):
with self.ioclass(b'abcd') as stream:
with stream.getbuffer()[1:] as target:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix the ``truncate`` method on :class:`io.BytesIO` when converting its size argument closes the stream or exports its buffer.
2 changes: 2 additions & 0 deletions Modules/_io/bytesio.c
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,8 @@ _io_BytesIO_truncate_impl(bytesio *self, PyObject *size)
"negative size value %zd", new_size);
return NULL;
}
CHECK_CLOSED(self);
CHECK_EXPORTS(self);
}

if (new_size < self->string_size) {
Expand Down
Loading