[Python-checkins] r72649 - in python/branches/py3k: Lib/test/test_io.py Modules/_io/textio.c

benjamin.peterson python-checkins at python.org
Fri May 15 00:01:31 CEST 2009


Author: benjamin.peterson
Date: Fri May 15 00:01:31 2009
New Revision: 72649

Log:
correctly handle invalid operations on streams (like writing on a non-writable one)

Modified:
   python/branches/py3k/Lib/test/test_io.py
   python/branches/py3k/Modules/_io/textio.c

Modified: python/branches/py3k/Lib/test/test_io.py
==============================================================================
--- python/branches/py3k/Lib/test/test_io.py	(original)
+++ python/branches/py3k/Lib/test/test_io.py	Fri May 15 00:01:31 2009
@@ -290,6 +290,19 @@
         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)

Modified: python/branches/py3k/Modules/_io/textio.c
==============================================================================
--- python/branches/py3k/Modules/_io/textio.c	(original)
+++ python/branches/py3k/Modules/_io/textio.c	Fri May 15 00:01:31 2009
@@ -1228,6 +1228,11 @@
 
     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 @@
      */
 
     if (self->decoder == NULL) {
-        PyErr_SetString(PyExc_ValueError, "no decoder");
+        PyErr_SetString(PyExc_IOError, "not readable");
         return -1;
     }
 


More information about the Python-checkins mailing list