Debian Codegraph @

tests/run/reimport_from_subinterpreter.srctree

raw
1 # mode: run
2 # tag: pep489, subinterpreter
3
4 UNSET CFLAGS
5 PYTHON setup.py build_ext --inplace
6 PYTHON -c "import subtest; subtest.run_main()"
7 PYTHON -c "import subtest; subtest.run_sub()"
8 PYTHON -c "import subtest; subtest.run_main(); subtest.run_sub()"
9
10 ######## setup.py ########
11
12 from Cython.Build.Dependencies import cythonize
13 from distutils.core import setup
14
15 setup(
16 ext_modules = cythonize("**/*.pyx"),
17 )
18
19 ######## subtest.pyx ########
20
21 cdef extern from *:
22 """
23 /* Copied from CPython's _testcapi.c module */
24 static PyObject *run_in_subinterpreter(const char *code) {
25 int r;
26 PyThreadState *substate, *mainstate;
27
28 mainstate = PyThreadState_Get();
29
30 PyThreadState_Swap(NULL);
31
32 substate = Py_NewInterpreter();
33 if (substate == NULL) {
34 /* Since no new thread state was created, there is no exception to
35 propagate; raise a fresh one after swapping in the old thread
36 state. */
37 PyThreadState_Swap(mainstate);
38 PyErr_SetString(PyExc_RuntimeError, "sub-interpreter creation failed");
39 return NULL;
40 }
41 r = PyRun_SimpleString(code);
42 Py_EndInterpreter(substate);
43
44 PyThreadState_Swap(mainstate);
45 return PyLong_FromLong(r);
46 }
47 """
48 object run_in_subinterpreter(const char *code)
49
50
51 MAIN_HAS_IMPORTED = False
52
53 def run_main():
54 global MAIN_HAS_IMPORTED
55 MAIN_HAS_IMPORTED = True
56 import package.subtest
57 from package import subtest
58
59 def run_sub():
60 assert 0 == run_in_subinterpreter(b'1+1')
61 assert 0 == run_in_subinterpreter(b'2+2')
62
63 # The subinterpreter does not add the current working directory to
64 # sys.path, so we need to add it manually.
65 pre = b'import sys; sys.path.insert(0, "."); '
66 assert 0 == run_in_subinterpreter(pre + b'import package')
67 assert 0 == run_in_subinterpreter(pre + b'import package')
68
69 result = run_in_subinterpreter(pre + b'import package.subtest')
70 if not MAIN_HAS_IMPORTED:
71 assert result == 0, result # imports only in subinterpreters are ok
72 else:
73 assert result == -1, result # re-import in a different subinterpreter fails in Py3.5+ (with PEP-489)
74
75
76 ######## package/__init__.py ########
77
78 ######## package/subtest.pyx ########
79
80 print("Module loaded: %s" % __name__)