| 1 | import pytest |
| 2 | import sys |
| 3 | import time |
| 4 | from _thread import start_new_thread |
| 5 | |
| 6 | @pytest.mark.xfail('__pypy__' not in sys.builtin_module_names, |
| 7 | reason='Fails on CPython') |
| 8 | def test_multithreaded_import(tmpdir): |
| 9 | tmpfile = tmpdir.join('multithreaded_import_test.py') |
| 10 | tmpfile.write('''if 1: |
| 11 | x = 666 |
| 12 | import time |
| 13 | for i in range(1000): time.sleep(0.001) |
| 14 | x = 42 |
| 15 | ''') |
| 16 | |
| 17 | oldpath = sys.path[:] |
| 18 | try: |
| 19 | sys.path.insert(0, str(tmpdir)) |
| 20 | got = [] |
| 21 | |
| 22 | def check(): |
| 23 | import multithreaded_import_test |
| 24 | got.append(getattr(multithreaded_import_test, 'x', '?')) |
| 25 | |
| 26 | for i in range(5): |
| 27 | start_new_thread(check, ()) |
| 28 | |
| 29 | for n in range(100): |
| 30 | for i in range(105): |
| 31 | time.sleep(0.001) |
| 32 | if len(got) == 5: |
| 33 | break |
| 34 | else: |
| 35 | raise AssertionError("got %r so far but still waiting" % |
| 36 | (got,)) |
| 37 | |
| 38 | assert got == [42] * 5 |
| 39 | |
| 40 | finally: |
| 41 | sys.path[:] = oldpath |