| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
import _imp as imp |
| 9 |
import os |
| 10 |
import importlib |
| 11 |
import sys |
| 12 |
import time |
| 13 |
import shutil |
| 14 |
import threading |
| 15 |
import unittest |
| 16 |
from unittest import mock |
| 17 |
from test.support import verbose, cpython_only |
| 18 |
from test.support.import_helper import forget |
| 19 |
from test.support.os_helper import (TESTFN, unlink, rmtree) |
| 20 |
from test.support import script_helper, threading_helper |
| 21 |
|
| 22 |
threading_helper.requires_working_threading(module=True) |
| 23 |
|
| 24 |
def task(N, done, done_tasks, errors): |
| 25 |
try: |
| 26 |
|
| 27 |
|
| 28 |
if len(done_tasks) % 2: |
| 29 |
import modulefinder |
| 30 |
import random |
| 31 |
else: |
| 32 |
import random |
| 33 |
import modulefinder |
| 34 |
|
| 35 |
x = random.randrange(1, 3) |
| 36 |
except Exception as e: |
| 37 |
errors.append(e.with_traceback(None)) |
| 38 |
finally: |
| 39 |
done_tasks.append(threading.get_ident()) |
| 40 |
finished = len(done_tasks) == N |
| 41 |
if finished: |
| 42 |
done.set() |
| 43 |
|
| 44 |
def mock_register_at_fork(func): |
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
return mock.patch('os.register_at_fork', create=True)(func) |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
circular_imports_modules = { |
| 54 |
'A': """if 1: |
| 55 |
import time |
| 56 |
time.sleep(%(delay)s) |
| 57 |
x = 'a' |
| 58 |
import C |
| 59 |
""", |
| 60 |
'B': """if 1: |
| 61 |
import time |
| 62 |
time.sleep(%(delay)s) |
| 63 |
x = 'b' |
| 64 |
import D |
| 65 |
""", |
| 66 |
'C': """import B""", |
| 67 |
'D': """import A""", |
| 68 |
} |
| 69 |
|
| 70 |
class Finder: |
| 71 |
"""A dummy finder to detect concurrent access to its find_spec() |
| 72 |
method.""" |
| 73 |
|
| 74 |
def __init__(self): |
| 75 |
self.numcalls = 0 |
| 76 |
self.x = 0 |
| 77 |
self.lock = threading.Lock() |
| 78 |
|
| 79 |
def find_spec(self, name, path=None, target=None): |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
assert imp.lock_held() |
| 84 |
with self.lock: |
| 85 |
self.numcalls += 1 |
| 86 |
x = self.x |
| 87 |
time.sleep(0.01) |
| 88 |
self.x = x + 1 |
| 89 |
|
| 90 |
class FlushingFinder: |
| 91 |
"""A dummy finder which flushes sys.path_importer_cache when it gets |
| 92 |
called.""" |
| 93 |
|
| 94 |
def find_spec(self, name, path=None, target=None): |
| 95 |
sys.path_importer_cache.clear() |
| 96 |
|
| 97 |
|
| 98 |
class ThreadedImportTests(unittest.TestCase): |
| 99 |
|
| 100 |
def setUp(self): |
| 101 |
self.old_random = sys.modules.pop('random', None) |
| 102 |
|
| 103 |
def tearDown(self): |
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
if self.old_random is not None: |
| 108 |
sys.modules['random'] = self.old_random |
| 109 |
|
| 110 |
@mock_register_at_fork |
| 111 |
def check_parallel_module_init(self, mock_os): |
| 112 |
if imp.lock_held(): |
| 113 |
|
| 114 |
raise unittest.SkipTest("can't run when import lock is held") |
| 115 |
|
| 116 |
done = threading.Event() |
| 117 |
for N in (20, 50) * 3: |
| 118 |
if verbose: |
| 119 |
print("Trying", N, "threads ...", end=' ') |
| 120 |
|
| 121 |
for modname in ['random', 'modulefinder']: |
| 122 |
try: |
| 123 |
del sys.modules[modname] |
| 124 |
except KeyError: |
| 125 |
pass |
| 126 |
errors = [] |
| 127 |
done_tasks = [] |
| 128 |
done.clear() |
| 129 |
t0 = time.monotonic() |
| 130 |
with threading_helper.start_threads( |
| 131 |
threading.Thread(target=task, args=(N, done, done_tasks, errors,)) |
| 132 |
for i in range(N)): |
| 133 |
pass |
| 134 |
completed = done.wait(10 * 60) |
| 135 |
dt = time.monotonic() - t0 |
| 136 |
if verbose: |
| 137 |
print("%.1f ms" % (dt*1e3), flush=True, end=" ") |
| 138 |
dbg_info = 'done: %s/%s' % (len(done_tasks), N) |
| 139 |
self.assertFalse(errors, dbg_info) |
| 140 |
self.assertTrue(completed, dbg_info) |
| 141 |
if verbose: |
| 142 |
print("OK.") |
| 143 |
|
| 144 |
def test_parallel_module_init(self): |
| 145 |
self.check_parallel_module_init() |
| 146 |
|
| 147 |
def test_parallel_meta_path(self): |
| 148 |
finder = Finder() |
| 149 |
sys.meta_path.insert(0, finder) |
| 150 |
try: |
| 151 |
self.check_parallel_module_init() |
| 152 |
self.assertGreater(finder.numcalls, 0) |
| 153 |
self.assertEqual(finder.x, finder.numcalls) |
| 154 |
finally: |
| 155 |
sys.meta_path.remove(finder) |
| 156 |
|
| 157 |
def test_parallel_path_hooks(self): |
| 158 |
|
| 159 |
|
| 160 |
finder = Finder() |
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
flushing_finder = FlushingFinder() |
| 165 |
def path_hook(path): |
| 166 |
finder.find_spec('') |
| 167 |
raise ImportError |
| 168 |
sys.path_hooks.insert(0, path_hook) |
| 169 |
sys.meta_path.append(flushing_finder) |
| 170 |
try: |
| 171 |
|
| 172 |
flushing_finder.find_spec('') |
| 173 |
numtests = self.check_parallel_module_init() |
| 174 |
self.assertGreater(finder.numcalls, 0) |
| 175 |
self.assertEqual(finder.x, finder.numcalls) |
| 176 |
finally: |
| 177 |
sys.meta_path.remove(flushing_finder) |
| 178 |
sys.path_hooks.remove(path_hook) |
| 179 |
|
| 180 |
def test_import_hangers(self): |
| 181 |
|
| 182 |
|
| 183 |
try: |
| 184 |
del sys.modules['test.test_importlib.threaded_import_hangers'] |
| 185 |
except KeyError: |
| 186 |
pass |
| 187 |
import test.test_importlib.threaded_import_hangers |
| 188 |
self.assertFalse(test.test_importlib.threaded_import_hangers.errors) |
| 189 |
|
| 190 |
@cpython_only |
| 191 |
def test_circular_imports(self): |
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
delay = 0.5 |
| 205 |
os.mkdir(TESTFN) |
| 206 |
self.addCleanup(shutil.rmtree, TESTFN) |
| 207 |
sys.path.insert(0, TESTFN) |
| 208 |
self.addCleanup(sys.path.remove, TESTFN) |
| 209 |
for name, contents in circular_imports_modules.items(): |
| 210 |
contents = contents % {'delay': delay} |
| 211 |
with open(os.path.join(TESTFN, name + ".py"), "wb") as f: |
| 212 |
f.write(contents.encode('utf-8')) |
| 213 |
self.addCleanup(forget, name) |
| 214 |
|
| 215 |
importlib.invalidate_caches() |
| 216 |
results = [] |
| 217 |
def import_ab(): |
| 218 |
import A |
| 219 |
results.append(getattr(A, 'x', None)) |
| 220 |
def import_ba(): |
| 221 |
import B |
| 222 |
results.append(getattr(B, 'x', None)) |
| 223 |
t1 = threading.Thread(target=import_ab) |
| 224 |
t2 = threading.Thread(target=import_ba) |
| 225 |
t1.start() |
| 226 |
t2.start() |
| 227 |
t1.join() |
| 228 |
t2.join() |
| 229 |
self.assertEqual(set(results), {'a', 'b'}) |
| 230 |
|
| 231 |
@mock_register_at_fork |
| 232 |
def test_side_effect_import(self, mock_os): |
| 233 |
code = """if 1: |
| 234 |
import threading |
| 235 |
def target(): |
| 236 |
import random |
| 237 |
t = threading.Thread(target=target) |
| 238 |
t.start() |
| 239 |
t.join() |
| 240 |
t = None""" |
| 241 |
sys.path.insert(0, os.curdir) |
| 242 |
self.addCleanup(sys.path.remove, os.curdir) |
| 243 |
filename = TESTFN + ".py" |
| 244 |
with open(filename, "wb") as f: |
| 245 |
f.write(code.encode('utf-8')) |
| 246 |
self.addCleanup(unlink, filename) |
| 247 |
self.addCleanup(forget, TESTFN) |
| 248 |
self.addCleanup(rmtree, '__pycache__') |
| 249 |
importlib.invalidate_caches() |
| 250 |
with threading_helper.wait_threads_exit(): |
| 251 |
__import__(TESTFN) |
| 252 |
del sys.modules[TESTFN] |
| 253 |
|
| 254 |
def test_concurrent_futures_circular_import(self): |
| 255 |
|
| 256 |
fn = os.path.join(os.path.dirname(__file__), |
| 257 |
'partial', 'cfimport.py') |
| 258 |
script_helper.assert_python_ok(fn) |
| 259 |
|
| 260 |
def test_multiprocessing_pool_circular_import(self): |
| 261 |
|
| 262 |
fn = os.path.join(os.path.dirname(__file__), |
| 263 |
'partial', 'pool_in_threads.py') |
| 264 |
script_helper.assert_python_ok(fn) |
| 265 |
|
| 266 |
|
| 267 |
def setUpModule(): |
| 268 |
thread_info = threading_helper.threading_setup() |
| 269 |
unittest.addModuleCleanup(threading_helper.threading_cleanup, *thread_info) |
| 270 |
try: |
| 271 |
old_switchinterval = sys.getswitchinterval() |
| 272 |
unittest.addModuleCleanup(sys.setswitchinterval, old_switchinterval) |
| 273 |
sys.setswitchinterval(1e-5) |
| 274 |
except AttributeError: |
| 275 |
pass |
| 276 |
|
| 277 |
|
| 278 |
if __name__ == "__main__": |
| 279 |
unittest.main() |