Skip to content

Commit 016aff7

Browse files
bpo-33773: Fix test.support.fd_count() on Linux/FreBSD (GH-7421)
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) Co-authored-by: Victor Stinner <[email protected]>
1 parent 5c022f1 commit 016aff7

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
@@ -2767,10 +2767,19 @@ def fd_count():
27672767
if sys.platform.startswith(('linux', 'freebsd')):
27682768
try:
27692769
names = os.listdir("/proc/self/fd")
2770-
return len(names)
2770+
# Substract one because listdir() opens internally a file
2771+
# descriptor to list the content of the /proc/self/fd/ directory.
2772+
return len(names) - 1
27712773
except FileNotFoundError:
27722774
pass
27732775

2776+
MAXFD = 256
2777+
if hasattr(os, 'sysconf'):
2778+
try:
2779+
MAXFD = os.sysconf("SC_OPEN_MAX")
2780+
except OSError:
2781+
pass
2782+
27742783
old_modes = None
27752784
if sys.platform == 'win32':
27762785
# bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process
@@ -2788,13 +2797,6 @@ def fd_count():
27882797
msvcrt.CRT_ASSERT):
27892798
old_modes[report_type] = msvcrt.CrtSetReportMode(report_type, 0)
27902799

2791-
MAXFD = 256
2792-
if hasattr(os, 'sysconf'):
2793-
try:
2794-
MAXFD = os.sysconf("SC_OPEN_MAX")
2795-
except OSError:
2796-
pass
2797-
27982800
try:
27992801
count = 0
28002802
for fd in range(MAXFD):

Lib/test/test_support.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -569,6 +569,17 @@ def id(self):
569569
self.assertTrue(support.match_test(test_access))
570570
self.assertFalse(support.match_test(test_chdir))
571571

572+
def test_fd_count(self):
573+
# We cannot test the absolute value of fd_count(): on old Linux
574+
# kernel or glibc versions, os.urandom() keeps a FD open on
575+
# /dev/urandom device and Python has 4 FD opens instead of 3.
576+
start = support.fd_count()
577+
fd = os.open(__file__, os.O_RDONLY)
578+
try:
579+
more = support.fd_count()
580+
finally:
581+
os.close(fd)
582+
self.assertEqual(more - start, 1)
572583

573584
# XXX -follows a list of untested API
574585
# make_legacy_pyc

0 commit comments

Comments
 (0)