]> granicus.if.org Git - python/commitdiff
Issue #15247: FileIO now raises an error when given a file descriptor pointing to...
authorAntoine Pitrou <solipsis@pitrou.net>
Fri, 6 Jul 2012 16:48:24 +0000 (18:48 +0200)
committerAntoine Pitrou <solipsis@pitrou.net>
Fri, 6 Jul 2012 16:48:24 +0000 (18:48 +0200)
Lib/test/test_fileio.py
Misc/NEWS
Modules/_io/fileio.c

index 173ec2543752f4376a64070f1bbd76a092f38385..5504ea321b54ec7c577032ba82f529f6a7e7583e 100644 (file)
@@ -127,6 +127,14 @@ class AutoFileTests(unittest.TestCase):
         else:
             self.fail("Should have raised IOError")
 
+    @unittest.skipIf(os.name == 'nt', "test only works on a POSIX-like system")
+    def testOpenDirFD(self):
+        fd = os.open('.', os.O_RDONLY)
+        with self.assertRaises(IOError) as cm:
+            _FileIO(fd, 'r')
+        os.close(fd)
+        self.assertEqual(cm.exception.errno, errno.EISDIR)
+
     #A set of functions testing that we get expected behaviour if someone has
     #manually closed the internal file descriptor.  First, a decorator:
     def ClosedFD(func):
index 563a7f098af7323b2a690fe4487d0c86af4a6ce2..699b4fb18b98adcd7ce82e8145bc42aec10103af 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -87,6 +87,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #15247: FileIO now raises an error when given a file descriptor
+  pointing to a directory.
+
 - Issue #5346: Preserve permissions of mbox, MMDF and Babyl mailbox
   files on flush().
 
index a7fad360b18616e27a059c2243782d45a0822cb8..605ad51e355381c48739ff2967951038d53fee37 100644 (file)
@@ -166,22 +166,15 @@ fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    directories, so we need a check.  */
 
 static int
-dircheck(fileio* self, const char *name)
+dircheck(fileio* self, PyObject *nameobj)
 {
 #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
     struct stat buf;
     if (self->fd < 0)
         return 0;
     if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
-        char *msg = strerror(EISDIR);
-        PyObject *exc;
-        if (internal_close(self))
-            return -1;
-
-        exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
-                                    EISDIR, msg, name);
-        PyErr_SetObject(PyExc_IOError, exc);
-        Py_XDECREF(exc);
+        errno = EISDIR;
+        PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
         return -1;
     }
 #endif
@@ -373,9 +366,9 @@ fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
                 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
             goto error;
         }
-        if (dircheck(self, name) < 0)
-            goto error;
     }
+    if (dircheck(self, nameobj) < 0)
+        goto error;
 
 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
     /* don't translate newlines (\r\n <=> \n) */