Skip to content

Commit 30c2cf8

Browse files
committed
Fix warn mode to work when warnings are configured as errors
Remove catch_warnings() workaround from production code and instead fix the root cause: tests were allowing sys.warnoptions to leak into the forkserver subprocess via _args_from_interpreter_flags(). When CI runs with -W error, the forkserver subprocess was inheriting this flag and converting our ImportWarning calls into exceptions, causing it to crash. Solution: Save and clear sys.warnoptions in test setUp, restore in tearDown. This gives the forkserver subprocess a clean warning state where warnings.warn() works as intended. Also remove unnecessary set_forkserver_preload([]) call from tearDown.
1 parent 6d4c521 commit 30c2cf8

File tree

2 files changed

+14
-15
lines changed

2 files changed

+14
-15
lines changed

Lib/multiprocessing/forkserver.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -244,13 +244,11 @@ def _handle_preload(preload, main_path=None, sys_path=None, on_error='ignore'):
244244
raise
245245
case 'warn':
246246
import warnings
247-
with warnings.catch_warnings():
248-
warnings.simplefilter('always', ImportWarning)
249-
warnings.warn(
250-
f"Failed to preload __main__ from {main_path!r}: {e}",
251-
ImportWarning,
252-
stacklevel=2
253-
)
247+
warnings.warn(
248+
f"Failed to preload __main__ from {main_path!r}: {e}",
249+
ImportWarning,
250+
stacklevel=2
251+
)
254252
case 'ignore':
255253
pass
256254
finally:
@@ -265,13 +263,11 @@ def _handle_preload(preload, main_path=None, sys_path=None, on_error='ignore'):
265263
raise
266264
case 'warn':
267265
import warnings
268-
with warnings.catch_warnings():
269-
warnings.simplefilter('always', ImportWarning)
270-
warnings.warn(
271-
f"Failed to preload module {modname!r}: {e}",
272-
ImportWarning,
273-
stacklevel=2
274-
)
266+
warnings.warn(
267+
f"Failed to preload module {modname!r}: {e}",
268+
ImportWarning,
269+
stacklevel=2
270+
)
275271
case 'ignore':
276272
pass
277273

Lib/test/test_multiprocessing_forkserver/test_preload.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Tests for forkserver preload functionality."""
22

33
import multiprocessing
4+
import sys
45
import tempfile
56
import unittest
67
from multiprocessing import forkserver
@@ -10,12 +11,14 @@ class TestForkserverPreload(unittest.TestCase):
1011
"""Tests for forkserver preload functionality."""
1112

1213
def setUp(self):
14+
self._saved_warnoptions = sys.warnoptions.copy()
15+
sys.warnoptions.clear()
1316
self.ctx = multiprocessing.get_context('forkserver')
1417
forkserver._forkserver._stop()
1518

1619
def tearDown(self):
20+
sys.warnoptions[:] = self._saved_warnoptions
1721
forkserver._forkserver._stop()
18-
self.ctx.set_forkserver_preload([])
1922

2023
@staticmethod
2124
def _send_value(conn, value):

0 commit comments

Comments
 (0)