Skip to content
Closed
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
46 changes: 46 additions & 0 deletions Lib/test/test_capi/test_file.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import io
import os
import errno
import unittest
from test import support
from test.support import import_helper, os_helper, warnings_helper
Expand Down Expand Up @@ -33,6 +34,30 @@ def test_pyfile_fromfd(self):
finally:
obj.close()

# Default buffering in binary mode (-1): BufferedReader
Copy link
Member

Choose a reason for hiding this comment

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

Why you're checking this here?
There's already tests on BufferedReader and TextIOWrapper below in this function.
Also, it's strange to open fd2 and fd3 under already existing with section for fp.

I need to ask if this PR was generated by LLM?

fd2 = os.open(filename, os.O_RDONLY)
try:
obj = pyfile_fromfd(fd2, filename, "rb", -1, NULL, NULL, NULL, 0)
try:
self.assertIsInstance(obj, _io.BufferedReader)
self.assertEqual(obj.readline(), FIRST_LINE.encode())
finally:
obj.close()
finally:
os.close(fd2)

# Default buffering in text mode (-1): TextIOWrapper
fd3 = os.open(filename, os.O_RDONLY)
try:
obj = pyfile_fromfd(fd3, filename, "r", -1, NULL, NULL, NULL, 0)
try:
self.assertIsInstance(obj, _io.TextIOWrapper)
self.assertEqual(obj.readline(), FIRST_LINE_NORM)
finally:
obj.close()
finally:
os.close(fd3)

# BufferedReader
fp.seek(0)
obj = pyfile_fromfd(fd, filename, "rb", 1024, NULL, NULL, NULL, 0)
Expand All @@ -54,6 +79,27 @@ def test_pyfile_fromfd(self):
finally:
obj.close()

def test_pyfile_fromfd_closefd(self):
# closefd=True should close the underlying file descriptor when the
# returned object is closed
pyfile_fromfd = _testlimitedcapi.pyfile_fromfd
filename = __file__

fd = os.open(filename, os.O_RDONLY)
try:
obj = pyfile_fromfd(fd, filename, "rb", -1, NULL, NULL, NULL, 1)
obj.close()
with self.assertRaises(OSError) as cm:
os.close(fd)
# On POSIX, closing a closed fd raises EBADF
self.assertEqual(cm.exception.errno, errno.EBADF)
finally:
# If the above failed for any reason and fd is still open, close it
try:
os.close(fd)
except OSError:
pass

def test_pyfile_getline(self):
# Test PyFile_GetLine(file, n): call file.readline()
# and strip "\n" suffix if n < 0.
Expand Down
Loading