Skip to content

Commit a5b4ea1

Browse files
orenmnserhiy-storchaka
authored andcommitted
bpo-31271: Fix an assertion failure in io.TextIOWrapper.write. (#3201)
1 parent dce6502 commit a5b4ea1

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed

Lib/test/test_io.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3225,6 +3225,14 @@ def test_read_nonbytes(self):
32253225
t = self.TextIOWrapper(self.StringIO('a'))
32263226
self.assertRaises(TypeError, t.read)
32273227

3228+
def test_illegal_encoder(self):
3229+
# Issue 31271: Calling write() while the return value of encoder's
3230+
# encode() is invalid shouldn't cause an assertion failure.
3231+
rot13 = codecs.lookup("rot13")
3232+
with support.swap_attr(rot13, '_is_text_encoding', True):
3233+
t = io.TextIOWrapper(io.BytesIO(b'foo'), encoding="rot13")
3234+
self.assertRaises(TypeError, t.write, 'bar')
3235+
32283236
def test_illegal_decoder(self):
32293237
# Issue #17106
32303238
# Bypass the early encoding check added in issue 20404
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix an assertion failure in the write() method of `io.TextIOWrapper`, when
2+
the encoder doesn't return a bytes object. Patch by Oren Milman.

Modules/_io/textio.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1387,6 +1387,13 @@ _io_TextIOWrapper_write_impl(textio *self, PyObject *text)
13871387
Py_DECREF(text);
13881388
if (b == NULL)
13891389
return NULL;
1390+
if (!PyBytes_Check(b)) {
1391+
PyErr_Format(PyExc_TypeError,
1392+
"encoder should return a bytes object, not '%.200s'",
1393+
Py_TYPE(b)->tp_name);
1394+
Py_DECREF(b);
1395+
return NULL;
1396+
}
13901397

13911398
if (self->pending_bytes == NULL) {
13921399
self->pending_bytes = PyList_New(0);

0 commit comments

Comments
 (0)