]> granicus.if.org Git - python/commitdiff
bpo-33773: Fix test.support.fd_count() on Linux/FreBSD (GH-7421)
authorVictor Stinner <vstinner@redhat.com>
Wed, 6 Jun 2018 15:23:50 +0000 (17:23 +0200)
committerGitHub <noreply@github.com>
Wed, 6 Jun 2018 15:23:50 +0000 (17:23 +0200)
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.

Lib/test/support/__init__.py
Lib/test/test_support.py

index a3a42cd69d0eebd8b263b915fbecfd3206b578a5..d8dabd435895643eb86e67cae7b6c2eefbf2148e 100644 (file)
@@ -2768,10 +2768,19 @@ def fd_count():
     if sys.platform.startswith(('linux', 'freebsd')):
         try:
             names = os.listdir("/proc/self/fd")
-            return len(names)
+            # Substract one because listdir() opens internally a file
+            # descriptor to list the content of the /proc/self/fd/ directory.
+            return len(names) - 1
         except FileNotFoundError:
             pass
 
+    MAXFD = 256
+    if hasattr(os, 'sysconf'):
+        try:
+            MAXFD = os.sysconf("SC_OPEN_MAX")
+        except OSError:
+            pass
+
     old_modes = None
     if sys.platform == 'win32':
         # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process
@@ -2789,13 +2798,6 @@ def fd_count():
                                 msvcrt.CRT_ASSERT):
                 old_modes[report_type] = msvcrt.CrtSetReportMode(report_type, 0)
 
-    MAXFD = 256
-    if hasattr(os, 'sysconf'):
-        try:
-            MAXFD = os.sysconf("SC_OPEN_MAX")
-        except OSError:
-            pass
-
     try:
         count = 0
         for fd in range(MAXFD):
index 36d5f849e1ad838f0ad4314ea76ef8fe57d2d586..89f1fbfb6c2b5292223184b22d412c0b37c6a0c4 100644 (file)
@@ -569,6 +569,17 @@ class TestSupport(unittest.TestCase):
             self.assertTrue(support.match_test(test_access))
             self.assertFalse(support.match_test(test_chdir))
 
+    def test_fd_count(self):
+        # We cannot test the absolute value of fd_count(): on old Linux
+        # kernel or glibc versions, os.urandom() keeps a FD open on
+        # /dev/urandom device and Python has 4 FD opens instead of 3.
+        start = support.fd_count()
+        fd = os.open(__file__, os.O_RDONLY)
+        try:
+            more = support.fd_count()
+        finally:
+            os.close(fd)
+        self.assertEqual(more - start, 1)
 
     # XXX -follows a list of untested API
     # make_legacy_pyc