]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-102402: Fix logging test_relativeCreated_has_higher_precision() leak (#117985)
authorVictor Stinner <vstinner@python.org>
Thu, 18 Apr 2024 17:01:55 +0000 (19:01 +0200)
committerGitHub <noreply@github.com>
Thu, 18 Apr 2024 17:01:55 +0000 (19:01 +0200)
Fix a reference leak in test_relativeCreated_has_higher_precision()
of test_logging: don't reimport the logging the logging module.

Lib/test/test_logging.py

index 826b7381686dcb9dc9c6496db6f406d7571c7607..d8ae607d1d8d0141fa9d6cca166ca9bb8d36d6f0 100644 (file)
@@ -4598,27 +4598,25 @@ class FormatterTest(unittest.TestCase, AssertErrorMessage):
             self.assertEqual(record.msecs, want)
             self.assertEqual(record.created, ns / 1e9)
 
+    # The test overrides a private attribute
+    @support.cpython_only
     def test_relativeCreated_has_higher_precision(self):
         # See issue gh-102402
         ns = 1_677_903_920_000_998_503  # approx. 2023-03-04 04:25:20 UTC
         offsets_ns = (200, 500, 12_354, 99_999, 1_677_903_456_999_123_456)
-        orig_modules = import_helper._save_and_remove_modules(['logging'])
-        try:
-            with patch("time.time_ns") as patched_ns:
-                # mock for module import
-                patched_ns.return_value = ns
-                import logging
-                for offset_ns in offsets_ns:
-                    new_ns = ns + offset_ns
-                    # mock for log record creation
-                    patched_ns.return_value = new_ns
-                    record = logging.makeLogRecord({'msg': 'test'})
-                    self.assertAlmostEqual(record.created, new_ns / 1e9, places=6)
-                    # After PR gh-102412, precision (places) increases from 3 to 7
-                    self.assertAlmostEqual(record.relativeCreated, offset_ns / 1e6, places=7)
-        finally:
-            import_helper._save_and_remove_modules(['logging'])
-            sys.modules.update(orig_modules)
+
+        with (patch("time.time_ns") as time_ns_mock,
+              support.swap_attr(logging, '_startTime', ns)):
+            for offset_ns in offsets_ns:
+                # mock for log record creation
+                new_ns = ns + offset_ns
+                time_ns_mock.return_value = new_ns
+
+                record = logging.makeLogRecord({'msg': 'test'})
+                self.assertAlmostEqual(record.created, new_ns / 1e9, places=6)
+
+                # After PR gh-102412, precision (places) increases from 3 to 7
+                self.assertAlmostEqual(record.relativeCreated, offset_ns / 1e6, places=7)
 
 
 class TestBufferingFormatter(logging.BufferingFormatter):