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

Skip to content

Commit d6fba02

Browse files
committed
[3.6] bpo-31271: Fix an assertion failure in io.TextIOWrapper.write. (pythonGH-3201)
(cherry picked from commit a5b4ea1)
1 parent cb7fdf6 commit d6fba02

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
@@ -1321,6 +1321,13 @@ _io_TextIOWrapper_write_impl(textio *self, PyObject *text)
13211321
Py_DECREF(text);
13221322
if (b == NULL)
13231323
return NULL;
1324+
if (!PyBytes_Check(b)) {
1325+
PyErr_Format(PyExc_TypeError,
1326+
"encoder should return a bytes object, not '%.200s'",
1327+
Py_TYPE(b)->tp_name);
1328+
Py_DECREF(b);
1329+
return NULL;
1330+
}
13241331

13251332
if (self->pending_bytes == NULL) {
13261333
self->pending_bytes = PyList_New(0);

0 commit comments

Comments
 (0)
0