Skip to content

Commit c5179f6

Browse files
authored
bpo-30599: Fix test_threaded_import reference leak (python#2029)
Mock os.register_at_fork() when importing the random module, since this function doesn't allow to unregister callbacks and so leaked memory.
1 parent 1b7863c commit c5179f6

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

Lib/test/test_threaded_import.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import time
1313
import shutil
1414
import unittest
15+
from unittest import mock
1516
from test.support import (
1617
verbose, import_module, run_unittest, TESTFN, reap_threads,
1718
forget, unlink, rmtree, start_threads)
@@ -37,6 +38,12 @@ def task(N, done, done_tasks, errors):
3738
if finished:
3839
done.set()
3940

41+
def mock_register_at_fork(func):
42+
# bpo-30599: Mock os.register_at_fork() when importing the random module,
43+
# since this function doesn't allow to unregister callbacks and would leak
44+
# memory.
45+
return mock.patch('os.register_at_fork', create=True)(func)
46+
4047
# Create a circular import structure: A -> C -> B -> D -> A
4148
# NOTE: `time` is already loaded and therefore doesn't threaten to deadlock.
4249

@@ -97,7 +104,8 @@ def tearDown(self):
97104
if self.old_random is not None:
98105
sys.modules['random'] = self.old_random
99106

100-
def check_parallel_module_init(self):
107+
@mock_register_at_fork
108+
def check_parallel_module_init(self, mock_os):
101109
if imp.lock_held():
102110
# This triggers on, e.g., from test import autotest.
103111
raise unittest.SkipTest("can't run when import lock is held")
@@ -214,7 +222,8 @@ def import_ba():
214222
t2.join()
215223
self.assertEqual(set(results), {'a', 'b'})
216224

217-
def test_side_effect_import(self):
225+
@mock_register_at_fork
226+
def test_side_effect_import(self, mock_os):
218227
code = """if 1:
219228
import threading
220229
def target():

0 commit comments

Comments
 (0)