8000 [3.6] bpo-31271: Fix an assertion failure in io.TextIOWrapper.write. … · python/cpython@9bcbc6c · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 9bcbc6c

Browse files
orenmnserhiy-storchaka
authored andcommitted
[3.6] bpo-31271: Fix an assertion failure in io.TextIOWrapper.write. (GH-3201) (#3209)
(cherry picked from commit a5b4ea1)
1 parent 8e67981 commit 9bcbc6c

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
@@ -3163,6 +3163,14 @@ def test_read_nonbytes(self):
31633163
t = self.TextIOWrapper(self.StringIO('a'))
31643164
self.assertRaises(TypeError, t.read)
31653165

3166+
def test_illegal_encoder(self):
3167+
# Issue 31271: Calling write() while the return value of encoder's
3168+
# encode() is invalid shouldn't cause an assertion failure.
3169+
rot13 = codecs.lookup("rot13")
3170+
with support.swap_attr(rot13, '_is_text_encoding', True):
3171+
t = io.TextIOWrapper(io.BytesIO(b'foo'), encoding="rot13")
3172+
self.assertRaises(TypeError, t.write, 'bar')
3173+
31663174
def test_illegal_decoder(self):
31673175
# Issue #17106
31683176
# 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
@@ -1331,6 +1331,13 @@ _io_TextIOWrapper_write_impl(textio *self, PyObject *text)
13311331
Py_DECREF(text);
13321332
if (b == NULL)
13331333
return NULL;
1334+
if (!PyBytes_Check(b)) {
1335+
PyErr_Format(PyExc_TypeError,
1336+
"encoder should return a bytes object, not '%.200s'",
1337+
Py_TYPE(b)->tp_name);
1338+
Py_DECREF(b);
1339+
return NULL;
1340+
}
13341341

13351342
if (self->pending_bytes == NULL) {
13361343
self->pending_bytes = PyList_New(0);

0 commit comments

Comments
 (0)
0