Skip to content

Commit 6b97452

Browse files
authored
gh-157710: Add MemoryError tests to PyUnicodeWriter (#157853)
Add a test changing the buffer kind multiple times. Add assertions to _PyUnicodeWriter_InitWithBuffer().
1 parent 5962fc2 commit 6b97452

2 files changed

Lines changed: 36 additions & 0 deletions

File tree

‎Lib/test/test_capi/test_unicode.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2075,6 +2075,39 @@ def test_detect_overflow(self):
20752075
# strategy which depends on the operating system
20762076
self.assertIn(f'at position '.encode(), proc.err)
20772077

2078+
@support.nomemtest
2079+
def test_memory_error(self):
2080+
# Inject MemoryError in PyUnicodeWriter_WriteStr()
2081+
writer = self.create_writer(0)
2082+
writer.write_str("start")
2083+
with self.assertRaises(MemoryError):
2084+
with support.inject_memory_error_cm():
2085+
# Resize the internal str object
2086+
writer.write_str("s" * 1024)
2087+
writer.write_str(" end")
2088+
self.assertEqual(writer.finish(), "start end")
2089+
2090+
# Inject MemoryError in PyUnicodeWriter_Finish()
2091+
writer = self.create_writer(1024)
2092+
writer.write_str("abc")
2093+
with self.assertRaises(MemoryError):
2094+
with support.inject_memory_error_cm():
2095+
# Need to truncate the internal str object
2096+
writer.finish()
2097+
2098+
def test_change_kind(self):
2099+
writer = self.create_writer(0)
2100+
# Create an ASCII buffer
2101+
writer.write_str('ascii ')
2102+
# Change the buffer to UCS1
2103+
writer.write_str('latin1:\xe9 ')
2104+
# Change the buffer to UCS2
2105+
writer.write_str('ucs2:\u20ac ')
2106+
# Change the buffer to UCS4
2107+
writer.write_str('ucs4:\U0010ffff')
2108+
self.assertEqual(writer.finish(),
2109+
'ascii latin1:\xe9 ucs2:\u20ac ucs4:\U0010ffff')
2110+
20782111

20792112
# Test PyUnicodeWriter_Format()
20802113
@unittest.skipIf(ctypes is None, 'need ctypes')

‎Objects/unicode_writer.c‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,10 +199,13 @@ void PyUnicodeWriter_Discard(PyUnicodeWriter *writer)
199199
void
200200
_PyUnicodeWriter_InitWithBuffer(_PyUnicodeWriter *writer, PyObject *buffer)
201201
{
202+
assert(PyUnstable_Object_IsUniquelyReferenced(buffer));
203+
202204
memset(writer, 0, sizeof(*writer));
203205
writer->buffer = buffer;
204206
_PyUnicodeWriter_Update(writer);
205207
writer->min_length = writer->size;
208+
assert(_PyUnicodeWriter_CanWrite(writer));
206209
}
207210

208211

0 commit comments

Comments
 (0)