Skip to content

Commit 67b7158

Browse files
authored
bpo-33773: Fix test.support.fd_count() on Linux/FreBSD (GH-7421) (GH-7456)
Substract one because listdir() opens internally a file descriptor to list the content of the /proc/self/fd/ directory. Add test_support.test_fd_count(). Move also MAXFD code before msvcrt.CrtSetReportMode(), to make sure that the report mode is always restored on failure. (cherry picked from commit 492d642)
1 parent e5b79c5 commit 67b7158

File tree

2 files changed

+21
-8
lines changed

2 files changed

+21
-8
lines changed

‎Lib/test/support/__init__.py‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2068,11 +2068,20 @@ def fd_count():
20682068
if sys.platform.startswith(('linux', 'freebsd')):
20692069
try:
20702070
names = os.listdir("/proc/self/fd")
2071-
return len(names)
2071+
# Substract one because listdir() opens internally a file
2072+
# descriptor to list the content of the /proc/self/fd/ directory.
2073+
return len(names) - 1
20722074
except OSError as exc:
20732075
if exc.errno != errno.ENOENT:
20742076
raise
20752077

2078+
MAXFD = 256
2079+
if hasattr(os, 'sysconf'):
2080+
try:
2081+
MAXFD = os.sysconf("SC_OPEN_MAX")
2082+
except OSError:
2083+
pass
2084+
20762085
old_modes = None
20772086
if sys.platform == 'win32':
20782087
# bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process
@@ -2090,13 +2099,6 @@ def fd_count():
20902099
msvcrt.CRT_ASSERT):
20912100
old_modes[report_type] = msvcrt.CrtSetReportMode(report_type, 0)
20922101

2093-
MAXFD = 256
2094-
if hasattr(os, 'sysconf'):
2095-
try:
2096-
MAXFD = os.sysconf("SC_OPEN_MAX")
2097-
except OSError:
2098-
pass
2099-
21002102
try:
21012103
count = 0
21022104
for fd in range(MAXFD):

‎Lib/test/test_test_support.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,17 @@ def id(self):
417417
self.assertTrue(support.match_test(test_access))
418418
self.assertFalse(support.match_test(test_chdir))
419419

420+
def test_fd_count(self):
421+
# We cannot test the absolute value of fd_count(): on old Linux
422+
# kernel or glibc versions, os.urandom() keeps a FD open on
423+
# /dev/urandom device and Python has 4 FD opens instead of 3.
424+
start = support.fd_count()
425+
fd = os.open(__file__, os.O_RDONLY)
426+
try:
427+
more = support.fd_count()
428+
finally:
429+
os.close(fd)
430+
self.assertEqual(more - start, 1)
420431

421432
# XXX -follows a list of untested API
422433
# make_legacy_pyc

0 commit comments

Comments
 (0)