Skip to content

Commit 97fe1b4

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 <vstinner@redhat.com>
1 parent 2bc1946 commit 97fe1b4

2 files changed

Lines changed: 21 additions & 8 deletions

File tree

‎Lib/test/support/__init__.py‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2741,10 +2741,19 @@ def fd_count():
27412741
if sys.platform.startswith(('linux', 'freebsd')):
27422742
try:
27432743
names = os.listdir("/proc/self/fd")
2744-
return len(names)
2744+
# Substract one because listdir() opens internally a file
2745+
# descriptor to list the content of the /proc/self/fd/ directory.
2746+
return len(names) - 1
27452747
except FileNotFoundError:
27462748
pass
27472749

2750+
MAXFD = 256
2751+
if hasattr(os, 'sysconf'):
2752+
try:
2753+
MAXFD = os.sysconf("SC_OPEN_MAX")
2754+
except OSError:
2755+
pass
2756+
27482757
old_modes = None
27492758
if sys.platform == 'win32':
27502759
# bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process
@@ -2762,13 +2771,6 @@ def fd_count():
27622771
msvcrt.CRT_ASSERT):
27632772
old_modes[report_type] = msvcrt.CrtSetReportMode(report_type, 0)
27642773

2765-
MAXFD = 256
2766-
if hasattr(os, 'sysconf'):
2767-
try:
2768-
MAXFD = os.sysconf("SC_OPEN_MAX")
2769-
except OSError:
2770-
pass
2771-
27722774
try:
27732775
count = 0
27742776
for fd in range(MAXFD):

‎Lib/test/test_support.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,6 +451,17 @@ def id(self):
451451
self.assertTrue(support.match_test(test_access))
452452
self.assertFalse(support.match_test(test_chdir))
453453

454+
def test_fd_count(self):
455+
# We cannot test the absolute value of fd_count(): on old Linux
456+
# kernel or glibc versions, os.urandom() keeps a FD open on
457+
# /dev/urandom device and Python has 4 FD opens instead of 3.
458+
start = support.fd_count()
459+
fd = os.open(__file__, os.O_RDONLY)
460+
try:
461+
more = support.fd_count()
462+
finally:
463+
os.close(fd)
464+
self.assertEqual(more - start, 1)
454465

455466
# XXX -follows a list of untested API
456467
# make_legacy_pyc

0 commit comments

Comments
 (0)