Skip to content

bpo-41352: Raise UnsupportedOperation for FileIO.readall() in "w" mode #21568

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Lib/test/test_fileio.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,22 @@ def testBlksize(self):
blksize = getattr(fst, 'st_blksize', blksize)
self.assertEqual(self.f._blksize, blksize)

def testReadWithWritingMode(self):
r, w = os.pipe()
with os.fdopen(w, "w") as w:
w.write("hello")
with io.FileIO(r, mode="w") as f:
with self.assertRaises(_io.UnsupportedOperation):
f.read()

def testReadallWithWritingMode(self):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These new test methods have too much duplicated code.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I (or @evanWang1409) can pull out the pipe setup into a separate method, if you would like. Otherwise I'm not sure what else is the right direction here. It's not clear what abstraction would make sense given that there are only two callers right now and this is a small test case.

r, w = os.pipe()
with os.fdopen(w, "w") as w:
w.write("hello")
with io.FileIO(r, mode="w") as f:
with self.assertRaises(_io.UnsupportedOperation):
f.readall()

# verify readinto
def testReadintoByteArray(self):
self.f.write(bytes([1, 2, 0, 255]))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix "FileIO.readall()" to check for "readable" and raise "UnsupportedOperation" for not readable file in "w" mode.
3 changes: 3 additions & 0 deletions Modules/_io/fileio.c
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,9 @@ _io_FileIO_readall_impl(fileio *self)

if (self->fd < 0)
return err_closed();
if (!self->readable) {
return err_mode("reading");
}

Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
Expand Down