diff options
Diffstat (limited to 'Lib/test/test_threaded_import.py')
-rw-r--r-- | Lib/test/test_threaded_import.py | 256 |
1 files changed, 195 insertions, 61 deletions
diff --git a/Lib/test/test_threaded_import.py b/Lib/test/test_threaded_import.py index b31fdf1363a..7791935fdf1 100644 --- a/Lib/test/test_threaded_import.py +++ b/Lib/test/test_threaded_import.py @@ -5,72 +5,206 @@ # complains several times about module random having no attribute # randrange, and then Python hangs. +import os +import imp +import sys +import time +import shutil import unittest -from test.test_support import verbose, TestFailed, import_module -thread = import_module('thread') - -critical_section = thread.allocate_lock() -done = thread.allocate_lock() - -def task(): - global N, critical_section, done - import random - x = random.randrange(1, 3) - critical_section.acquire() - N -= 1 - # Must release critical_section before releasing done, else the main - # thread can exit and set critical_section to None as part of global - # teardown; then critical_section.release() raises AttributeError. - finished = N == 0 - critical_section.release() - if finished: - done.release() - -def test_import_hangers(): - import sys - if verbose: - print "testing import hangers ...", - - import test.threaded_import_hangers +from test.support import verbose, import_module, run_unittest, TESTFN +thread = import_module('_thread') +threading = import_module('threading') + +def task(N, done, done_tasks, errors): try: - if test.threaded_import_hangers.errors: - raise TestFailed(test.threaded_import_hangers.errors) - elif verbose: - print "OK." + # We don't use modulefinder but still import it in order to stress + # importing of different modules from several threads. + if len(done_tasks) % 2: + import modulefinder + import random + else: + import random + import modulefinder + # This will fail if random is not completely initialized + x = random.randrange(1, 3) + except Exception as e: + errors.append(e.with_traceback(None)) finally: + done_tasks.append(thread.get_ident()) + finished = len(done_tasks) == N + if finished: + done.set() + +# Create a circular import structure: A -> C -> B -> D -> A +# NOTE: `time` is already loaded and therefore doesn't threaten to deadlock. + +circular_imports_modules = { + 'A': """if 1: + import time + time.sleep(%(delay)s) + x = 'a' + import C + """, + 'B': """if 1: + import time + time.sleep(%(delay)s) + x = 'b' + import D + """, + 'C': """import B""", + 'D': """import A""", +} + +class Finder: + """A dummy finder to detect concurrent access to its find_module() + method.""" + + def __init__(self): + self.numcalls = 0 + self.x = 0 + self.lock = thread.allocate_lock() + + def find_module(self, name, path=None): + # Simulate some thread-unsafe behaviour. If calls to find_module() + # are properly serialized, `x` will end up the same as `numcalls`. + # Otherwise not. + with self.lock: + self.numcalls += 1 + x = self.x + time.sleep(0.1) + self.x = x + 1 + +class FlushingFinder: + """A dummy finder which flushes sys.path_importer_cache when it gets + called.""" + + def find_module(self, name, path=None): + sys.path_importer_cache.clear() + + +class ThreadedImportTests(unittest.TestCase): + + def setUp(self): + self.old_random = sys.modules.pop('random', None) + + def tearDown(self): + # If the `random` module was already initialized, we restore the + # old module at the end so that pickling tests don't fail. + # See http://bugs.python.org/issue3657#msg110461 + if self.old_random is not None: + sys.modules['random'] = self.old_random + + def check_parallel_module_init(self): + if imp.lock_held(): + # This triggers on, e.g., from test import autotest. + raise unittest.SkipTest("can't run when import lock is held") + + done = threading.Event() + for N in (20, 50) * 3: + if verbose: + print("Trying", N, "threads ...", end=' ') + # Make sure that random and modulefinder get reimported freshly + for modname in ['random', 'modulefinder']: + try: + del sys.modules[modname] + except KeyError: + pass + errors = [] + done_tasks = [] + done.clear() + for i in range(N): + thread.start_new_thread(task, (N, done, done_tasks, errors,)) + done.wait(60) + self.assertFalse(errors) + if verbose: + print("OK.") + + def test_parallel_module_init(self): + self.check_parallel_module_init() + + def test_parallel_meta_path(self): + finder = Finder() + sys.meta_path.append(finder) + try: + self.check_parallel_module_init() + self.assertGreater(finder.numcalls, 0) + self.assertEqual(finder.x, finder.numcalls) + finally: + sys.meta_path.remove(finder) + + def test_parallel_path_hooks(self): + # Here the Finder instance is only used to check concurrent calls + # to path_hook(). + finder = Finder() + # In order for our path hook to be called at each import, we need + # to flush the path_importer_cache, which we do by registering a + # dedicated meta_path entry. + flushing_finder = FlushingFinder() + def path_hook(path): + finder.find_module('') + raise ImportError + sys.path_hooks.append(path_hook) + sys.meta_path.append(flushing_finder) + try: + # Flush the cache a first time + flushing_finder.find_module('') + numtests = self.check_parallel_module_init() + self.assertGreater(finder.numcalls, 0) + self.assertEqual(finder.x, finder.numcalls) + finally: + sys.meta_path.remove(flushing_finder) + sys.path_hooks.remove(path_hook) + + def test_import_hangers(self): # In case this test is run again, make sure the helper module # gets loaded from scratch again. - del sys.modules['test.threaded_import_hangers'] - -# Tricky: When regrtest imports this module, the thread running regrtest -# grabs the import lock and won't let go of it until this module returns. -# All other threads attempting an import hang for the duration. Since -# this test spawns threads that do little *but* import, we can't do that -# successfully until after this module finishes importing and regrtest -# regains control. To make this work, a special case was added to -# regrtest to invoke a module's "test_main" function (if any) after -# importing it. - -def test_main(): # magic name! see above - global N, done - - import imp - if imp.lock_held(): - # This triggers on, e.g., from test import autotest. - raise unittest.SkipTest("can't run when import lock is held") - - done.acquire() - for N in (20, 50) * 3: - if verbose: - print "Trying", N, "threads ...", - for i in range(N): - thread.start_new_thread(task, ()) - done.acquire() - if verbose: - print "OK." - done.release() - - test_import_hangers() + try: + del sys.modules['test.threaded_import_hangers'] + except KeyError: + pass + import test.threaded_import_hangers + self.assertFalse(test.threaded_import_hangers.errors) + + def test_circular_imports(self): + # The goal of this test is to exercise implementations of the import + # lock which use a per-module lock, rather than a global lock. + # In these implementations, there is a possible deadlock with + # circular imports, for example: + # - thread 1 imports A (grabbing the lock for A) which imports B + # - thread 2 imports B (grabbing the lock for B) which imports A + # Such implementations should be able to detect such situations and + # resolve them one way or the other, without freezing. + # NOTE: our test constructs a slightly less trivial import cycle, + # in order to better stress the deadlock avoidance mechanism. + delay = 0.5 + os.mkdir(TESTFN) + self.addCleanup(shutil.rmtree, TESTFN) + sys.path.insert(0, TESTFN) + self.addCleanup(sys.path.remove, TESTFN) + for name, contents in circular_imports_modules.items(): + contents = contents % {'delay': delay} + with open(os.path.join(TESTFN, name + ".py"), "wb") as f: + f.write(contents.encode('utf-8')) + self.addCleanup(sys.modules.pop, name, None) + + results = [] + def import_ab(): + import A + results.append(getattr(A, 'x', None)) + def import_ba(): + import B + results.append(getattr(B, 'x', None)) + t1 = threading.Thread(target=import_ab) + t2 = threading.Thread(target=import_ba) + t1.start() + t2.start() + t1.join() + t2.join() + self.assertEqual(set(results), {'a', 'b'}) + + +def test_main(): + run_unittest(ThreadedImportTests) if __name__ == "__main__": test_main() |