Beispiel #1
0
 def testOpendir(self):
     # Issue 3703: opening a directory should fill the errno
     # Windows always returns "[Errno 13]: Permission denied
     # Unix calls dircheck() and returns "[Errno 21]: Is a directory"
     try:
         _FileIO('.', 'r')
     except IOError as e:
         self.assertNotEqual(e.errno, 0)
         self.assertEqual(e.filename, ".")
     else:
         self.fail("Should have raised IOError")
Beispiel #2
0
    def testErrors(self):
        f = self.f
        self.assertTrue(not f.isatty())
        self.assertTrue(not f.closed)
        #self.assertEqual(f.name, TESTFN)
        self.assertRaises(ValueError, f.read, 10) # Open for writing
        f.close()
        self.assertTrue(f.closed)
        f = self.f = _FileIO(TESTFN, 'r')
        self.assertRaises(TypeError, f.readinto, "")
        self.assertTrue(not f.closed)
        f.close()
        self.assertTrue(f.closed)

        # These methods all accept a call with 0 arguments
        methods = ['fileno', 'isatty', 'read', 
                   'tell', 'truncate', 'seekable',
                   'readable', 'writable']
        if sys.platform.startswith('atheos'):
            methods.remove('truncate')

        self.f.close()
        self.assertTrue(self.f.closed)

        for methodname in methods:
            method = getattr(self.f, methodname)
            # should raise on closed file
            self.assertRaises(ValueError, method)

        # These other methods should be tested using a specific call
        # in case the test for number of arguments comes first.
        b = bytearray()
        self.assertRaises(ValueError, self.f.readinto, b )
        self.assertRaises(ValueError, self.f.seek, 0)
        self.assertRaises(ValueError, self.f.write, b )
Beispiel #3
0
 def testWritelinesUserList(self):
     l = UserList([b"123", b"456"])
     self.f.writelines(l)
     self.f.close()
     self.f = _FileIO(TESTFN, "rb")
     buf = self.f.read()
     self.assertEqual(buf, b"123456")
Beispiel #4
0
 def testWritelinesUserList(self):
     l = UserList([b'123', b'456'])
     self.f.writelines(l)
     self.f.close()
     self.f = _FileIO(TESTFN, 'rb')
     buf = self.f.read()
     self.assertEqual(buf, b'123456')
Beispiel #5
0
 def testReadinto(self):
     # verify readinto
     self.f.write(b"\x01\x02")
     self.f.close()
     a = array(b"b", b"x" * 10)
     self.f = _FileIO(TESTFN, "r")
     n = self.f.readinto(a)
     self.assertEqual(array(b"b", [1, 2]), a[:n])
Beispiel #6
0
 def ReopenForRead(self):
     try:
         self.f.close()
     except IOError:
         pass
     self.f = _FileIO(TESTFN, 'r')
     os.close(self.f.fileno())
     return self.f
Beispiel #7
0
 def testReadinto(self):
     # verify readinto
     self.f.write(b"\x01\x02")
     self.f.close()
     a = array(b'b', b'x'*10)
     self.f = _FileIO(TESTFN, 'r')
     n = self.f.readinto(a)
     self.assertEqual(array(b'b', [1, 2]), a[:n])
Beispiel #8
0
    def testAbles(self):

        f = self.f = _FileIO(TESTFN, "w")
        self.assertEqual(f.readable(), False)
        self.assertEqual(f.writable(), True)
        self.assertEqual(f.seekable(), True)
        f.close()

        f = self.f = _FileIO(TESTFN, "r")
        self.assertEqual(f.readable(), True)
        self.assertEqual(f.writable(), False)
        self.assertEqual(f.seekable(), True)
        f.close()

        f = self.f = _FileIO(TESTFN, "a+")
        self.assertEqual(f.readable(), True)
        self.assertEqual(f.writable(), True)
        self.assertEqual(f.seekable(), True)
        self.assertEqual(f.isatty(), False)
        f.close()

        # Jython specific issues:
        # On OSX, FileIO("/dev/tty", "w").isatty() is False
        # On Ubuntu, FileIO("/dev/tty", "w").isatty() throws IOError: Illegal seek
        #
        # Much like we see on other platforms, we cannot reliably
        # determine it is not seekable (or special).
        #
        # Related bug: http://bugs.jython.org/issue1945
        if sys.platform != "win32" and not is_jython:
            try:
                f = self.f = _FileIO("/dev/tty", "a")
            except EnvironmentError:
                # When run in a cron job there just aren't any
                # ttys, so skip the test.  This also handles other
                # OS'es that don't support /dev/tty.
                pass
            else:
                self.assertEqual(f.readable(), False)
                self.assertEqual(f.writable(), True)
                if sys.platform != "darwin" and \
                   'bsd' not in sys.platform and \
                   not sys.platform.startswith('sunos'):
                    # Somehow /dev/tty appears seekable on some BSDs
                    self.assertEqual(f.seekable(), False)
                self.assertEqual(f.isatty(), True)
Beispiel #9
0
 def test_none_args(self):
     self.f.write(b"hi\nbye\nabc")
     self.f.close()
     self.f = _FileIO(TESTFN, 'r')
     self.assertEqual(self.f.read(None), b"hi\nbye\nabc")
     self.f.seek(0)
     self.assertEqual(self.f.readline(None), b"hi\n")
     self.assertEqual(self.f.readlines(None), [b"bye\n", b"abc"])
Beispiel #10
0
 def testModeStrings(self):
     # check invalid mode strings
     for mode in ("", "aU", "wU+", "rw", "rt"):
         try:
             f = self.f = _FileIO(TESTFN, mode)
         except ValueError:
             pass
         else:
             self.fail('%r is an invalid file mode' % mode)
 def testReprNoCloseFD(self):
     fd = os.open(TESTFN, os.O_RDONLY)
     try:
         with _FileIO(fd, 'r', closefd=False) as f:
             self.assertEqual(repr(f),
                              "<_io.FileIO name=%r mode=%r closefd=False>"
                              % (f.name, f.mode))
     finally:
         os.close(fd)
 def testTruncate(self):
     f = _FileIO(TESTFN, 'w')
     f.write(bytes(bytearray(range(10))))
     self.assertEqual(f.tell(), 10)
     f.truncate(5)
     self.assertEqual(f.tell(), 10)
     self.assertEqual(f.seek(0, os.SEEK_END), 5)
     f.truncate(15)
     self.assertEqual(f.tell(), 5)
     self.assertEqual(f.seek(0, os.SEEK_END), 15)
Beispiel #13
0
    def testAbles(self):
        try:
            f = _FileIO(TESTFN, "w")
            self.assertEquals(f.readable(), False)
            self.assertEquals(f.writable(), True)
            self.assertEquals(f.seekable(), True)
            f.close()

            f = _FileIO(TESTFN, "r")
            self.assertEquals(f.readable(), True)
            self.assertEquals(f.writable(), False)
            self.assertEquals(f.seekable(), True)
            f.close()

            f = _FileIO(TESTFN, "a+")
            self.assertEquals(f.readable(), True)
            self.assertEquals(f.writable(), True)
            self.assertEquals(f.seekable(), True)
            self.assertEquals(f.isatty(), False)
            f.close()

            if sys.platform != "win32":
                try:
                    f = _FileIO("/dev/tty", "a")
                except EnvironmentError:
                    # When run in a cron job there just aren't any
                    # ttys, so skip the test.  This also handles other
                    # OS'es that don't support /dev/tty.
                    pass
                else:
                    f = _FileIO("/dev/tty", "a")
                    self.assertEquals(f.readable(), False)
                    self.assertEquals(f.writable(), True)
                    if sys.platform != "darwin" and \
                       'bsd' not in sys.platform and \
                       not sys.platform.startswith('sunos'):
                        # Somehow /dev/tty appears seekable on some BSDs
                        self.assertEquals(f.seekable(), False)
                    self.assertEquals(f.isatty(), True)
                    f.close()
        finally:
            os.unlink(TESTFN)
Beispiel #14
0
 def testTruncate(self):
     f = self.f = _FileIO(TESTFN, 'w')
     f.write(bytes(bytearray(list(range(10)))))
     self.assertEqual(f.tell(), 10)
     f.truncate(5)
     self.assertEqual(f.tell(), 10)
     self.assertEqual(f.seek(0, os.SEEK_END), 5)
     f.truncate(15)
     self.assertEqual(f.tell(), 5)
     #XXX: next assert not working in Jython:
     #self.assertEqual(f.seek(0, os.SEEK_END), 15)
     f.close()
Beispiel #15
0
 def testErrors(self):
     f = self.f
     self.assertTrue(not f.isatty())
     self.assertTrue(not f.closed)
     #self.assertEqual(f.name, TESTFN)
     self.assertRaises(ValueError, f.read, 10) # Open for reading
     f.close()
     self.assertTrue(f.closed)
     f = _FileIO(TESTFN, 'r')
     self.assertRaises(TypeError, f.readinto, "")
     self.assertTrue(not f.closed)
     f.close()
     self.assertTrue(f.closed)
Beispiel #16
0
    def testAbles(self):
        try:
            f = _FileIO(TESTFN, "w")
            self.assertEqual(f.readable(), False)
            self.assertEqual(f.writable(), True)
            self.assertEqual(f.seekable(), True)
            f.close()

            f = _FileIO(TESTFN, "r")
            self.assertEqual(f.readable(), True)
            self.assertEqual(f.writable(), False)
            self.assertEqual(f.seekable(), True)
            f.close()

            f = _FileIO(TESTFN, "a+")
            self.assertEqual(f.readable(), True)
            self.assertEqual(f.writable(), True)
            self.assertEqual(f.seekable(), True)
            self.assertEqual(f.isatty(), False)
            f.close()
        finally:
            os.unlink(TESTFN)
Beispiel #17
0
        def bug801631():
            # SF bug <http://www.python.org/sf/801631>
            # "file.truncate fault on windows"
            f = _FileIO(TESTFN, 'w')
            f.write(bytes(range(11)))
            f.close()

            f = _FileIO(TESTFN,'r+')
            data = f.read(5)
            if data != bytes(range(5)):
                self.fail("Read on file opened for update failed %r" % data)
            if f.tell() != 5:
                self.fail("File pos after read wrong %d" % f.tell())

            f.truncate()
            if f.tell() != 5:
                self.fail("File pos after ftruncate wrong %d" % f.tell())

            f.close()
            size = os.path.getsize(TESTFN)
            if size != 5:
                self.fail("File size after ftruncate wrong %d" % size)
Beispiel #18
0
 def testBytesOpen(self):
     # Opening a bytes filename
     try:
         fn = TESTFN.encode("ascii")
     except UnicodeEncodeError:
         # Skip test
         return
     f = self.f = _FileIO(fn, "w")
     f.write(b"abc")
     f.close()
     with open(TESTFN, "rb") as f:
         self.f = f
         self.assertEqual(f.read(), b"abc")
Beispiel #19
0
 def testModeStrings(self):
     # test that the mode attribute is correct for various mode strings
     # given as init args
     try:
         for modes in [('w', 'wb'), ('wb', 'wb'), ('wb+', 'rb+'),
                       ('w+b', 'rb+'), ('a', 'ab'), ('ab', 'ab'),
                       ('ab+', 'ab+'), ('a+b', 'ab+'), ('r', 'rb'),
                       ('rb', 'rb'), ('rb+', 'rb+'), ('r+b', 'rb+')]:
             # read modes are last so that TESTFN will exist first
             with _FileIO(TESTFN, modes[0]) as f:
                 self.assertEqual(f.mode, modes[1])
     finally:
         if os.path.exists(TESTFN):
             os.unlink(TESTFN)
Beispiel #20
0
 def testBytesOpen(self):
     # Opening a bytes filename
     try:
         fn = TESTFN.encode("ascii")
     except UnicodeEncodeError:
         self.skipTest('could not encode %r to ascii' % TESTFN)
     f = _FileIO(fn, "w")
     try:
         f.write(b"abc")
         f.close()
         with open(TESTFN, "rb") as f:
             self.assertEqual(f.read(), b"abc")
     finally:
         os.unlink(TESTFN)
Beispiel #21
0
 def testBadModeArgument(self):
     # verify that we get a sensible error message for bad mode argument
     bad_mode = "qwerty"
     try:
         f = _FileIO(TESTFN, bad_mode)
     except ValueError as msg:
         if msg.args[0] != 0:
             s = str(msg)
             if TESTFN in s or bad_mode not in s:
                 self.fail("bad error message for invalid mode: %s" % s)
         # if msg.args[0] == 0, we're probably on Windows where there may be
         # no obvious way to discover why open() failed.
     else:
         f.close()
         self.fail("no error for invalid mode: %s" % bad_mode)
Beispiel #22
0
 def testAblesOnTTY(self):
     try:
         f = _FileIO("/dev/tty", "a")
     except EnvironmentError:
         # When run in a cron job there just aren't any
         # ttys, so skip the test.  This also handles other
         # OS'es that don't support /dev/tty.
         self.skipTest('need /dev/tty')
     else:
         self.assertEqual(f.readable(), False)
         self.assertEqual(f.writable(), True)
         if sys.platform != "darwin" and \
            'bsd' not in sys.platform and \
            not sys.platform.startswith('sunos'):
             # Somehow /dev/tty appears seekable on some BSDs
             self.assertEqual(f.seekable(), False)
         self.assertEqual(f.isatty(), True)
         f.close()
Beispiel #23
0
 def test_surrogates(self):
     # Issue #8438: try to open a filename containing surrogates.
     # It should either fail because the file doesn't exist or the filename
     # can't be represented using the filesystem encoding, but not because
     # of a LookupError for the error handler "surrogateescape".
     filename = u'\udc80.txt'
     try:
         with _FileIO(filename):
             pass
     except (UnicodeEncodeError, IOError):
         pass
     # Spawn a separate Python process with a different "file system
     # default encoding", to exercise this further.
     env = dict(os.environ)
     env[b'LC_CTYPE'] = b'C'
     _, out = run_python('-c', 'import _io; _io.FileIO(%r)' % filename, env=env)
     if ('UnicodeEncodeError' not in out and
         'IOError: [Errno 2] No such file or directory' not in out):
         self.fail('Bad output: %r' % out)
Beispiel #24
0
 def test_surrogates(self):
     # Issue #8438: try to open a filename containing surrogates.
     # It should either fail because the file doesn't exist or the filename
     # can't be represented using the filesystem encoding, but not because
     # of a LookupError for the error handler "surrogateescape".
     filename = u'\udc80.txt'
     try:
         with _FileIO(filename):
             pass
     except (UnicodeEncodeError, IOError):
         pass
     # Spawn a separate Python process with a different "file system
     # default encoding", to exercise this further.
     env = dict(os.environ)
     env[b'LC_CTYPE'] = b'C'
     _, out = run_python('-c', 'import _io; _io.FileIO(%r)' % filename, env=env)
     if ('UnicodeEncodeError' not in out and
         'IOError: [Errno 2] No such file or directory' not in out):
         self.fail('Bad output: %r' % out)
Beispiel #25
0
 def test_surrogates(self):
     # Issue #8438: try to open a filename containing surrogates.
     # It should either fail because the file doesn't exist or the filename
     # can't be represented using the filesystem encoding, but not because
     # of a LookupError for the error handler "surrogateescape".
     filename = "\udc80.txt"
     try:
         with _FileIO(filename):
             pass
     except (UnicodeEncodeError, IOError):
         pass
     # Spawn a separate Python process with a different "file system
     # default encoding", to exercise this further.
     env = dict(os.environ)
     env[b"LC_CTYPE"] = b"C"
     _, out = run_python("-c", "import _io; _io.FileIO(%r)" % filename, env=env)
     if "UnicodeEncodeError" not in out and not (
         ("IOError: [Errno 2] No such file or directory" in out) or ("IOError: [Errno 22] Invalid argument" in out)
     ):
         self.fail("Bad output: %r" % out)
Beispiel #26
0
    def testErrors(self):
        f = self.f
        self.assertTrue(not f.isatty())
        self.assertTrue(not f.closed)
        #self.assertEqual(f.name, TESTFN)
        self.assertRaises(ValueError, f.read, 10)  # Open for writing
        f.close()
        self.assertTrue(f.closed)
        f = self.f = _FileIO(TESTFN, 'r')
        self.assertRaises(TypeError, f.readinto, "")
        self.assertTrue(not f.closed)
        f.close()
        self.assertTrue(f.closed)

        # These methods all accept a call with 0 arguments
        methods = [
            'fileno', 'isatty', 'read', 'tell', 'truncate', 'seekable',
            'readable', 'writable'
        ]
        if sys.platform.startswith('atheos'):
            methods.remove('truncate')

        self.f.close()
        self.assertTrue(self.f.closed)

        for methodname in methods:
            method = getattr(self.f, methodname)
            # should raise on closed file
            self.assertRaises(ValueError, method)

        # These other methods should be tested using a specific call
        # in case the test for number of arguments comes first.
        b = bytearray()
        self.assertRaises(ValueError, self.f.readinto, b)
        self.assertRaises(ValueError, self.f.seek, 0)
        self.assertRaises(ValueError, self.f.write, b)
Beispiel #27
0
 def testUnicodeOpen(self):
     # verify repr works for unicode too
     f = self.f = _FileIO(str(TESTFN), "w")
Beispiel #28
0
 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)
Beispiel #29
0
 def testUnicodeOpen(self):
     # verify repr works for unicode too
     f = self.f = _FileIO(str(TESTFN), "w")
Beispiel #30
0
 def testUnicodeOpen(self):
     # verify repr works for unicode too
     f = _FileIO(str(TESTFN), "w")
     f.close()
     os.unlink(TESTFN)
Beispiel #31
0
 def setUp(self):
     self.f = _FileIO(TESTFN, 'w')
Beispiel #32
0
 def testUnicodeOpen(self):
     # verify repr works for unicode too
     f = _FileIO(str(TESTFN), "w")
     f.close()
     os.unlink(TESTFN)
Beispiel #33
0
 def setUp(self):
     self.f = _FileIO(TESTFN, 'w')
Beispiel #34
0
 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)