From 81971eafbef55f635413ed530beb4a6651c68549 Mon Sep 17 00:00:00 2001 From: Benjamin Peterson Date: Thu, 14 May 2009 22:01:31 +0000 Subject: [PATCH] correctly handle invalid operations on streams (like writing on a non-writable one) --- Lib/test/test_io.py | 13 +++++++++++++ Modules/_io/textio.c | 7 ++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py index 98dc71197b7..08e0f1396f4 100644 --- a/Lib/test/test_io.py +++ b/Lib/test/test_io.py @@ -290,6 +290,19 @@ class IOTest(unittest.TestCase): self.assertEqual(f.seek(-1, 2), self.LARGE) self.assertEqual(f.read(2), b"x") + def test_invalid_operations(self): + # Try writing on a file opened in read mode and vice-versa. + for mode in ("w", "wb"): + with open(support.TESTFN, mode) as fp: + self.assertRaises(IOError, fp.read) + self.assertRaises(IOError, fp.readline) + with open(support.TESTFN, "rb") as fp: + self.assertRaises(IOError, fp.write, b"blah") + self.assertRaises(IOError, fp.writelines, [b"blah\n"]) + with open(support.TESTFN, "r") as fp: + self.assertRaises(IOError, fp.write, "blah") + self.assertRaises(IOError, fp.writelines, ["blah\n"]) + def test_raw_file_io(self): with self.open(support.TESTFN, "wb", buffering=0) as f: self.assertEqual(f.readable(), False) diff --git a/Modules/_io/textio.c b/Modules/_io/textio.c index 8d2a686d80a..b78256e2ed6 100644 --- a/Modules/_io/textio.c +++ b/Modules/_io/textio.c @@ -1228,6 +1228,11 @@ TextIOWrapper_write(PyTextIOWrapperObject *self, PyObject *args) CHECK_CLOSED(self); + if (self->encoder == NULL) { + PyErr_SetString(PyExc_IOError, "not writable"); + return NULL; + } + Py_INCREF(text); textlen = PyUnicode_GetSize(text); @@ -1363,7 +1368,7 @@ TextIOWrapper_read_chunk(PyTextIOWrapperObject *self) */ if (self->decoder == NULL) { - PyErr_SetString(PyExc_ValueError, "no decoder"); + PyErr_SetString(PyExc_IOError, "not readable"); return -1; }