Debian Codegraph @

test/conftest.py

raw symbols SCIP
1 import os
2 import sys
3 import subprocess
4
5 import pytest
6
7 from . import helpers
8 from . import run
9 from . import refactor
10 from jedi import InterpreterEnvironment, get_system_environment
11 from jedi.inference.compiled.value import create_from_access_path
12 from jedi.api.interpreter import MixedModuleContext
13
14 # For interpreter tests sometimes the path of this directory is in the sys
15 # path, which we definitely don't want. So just remove it globally.
16 try:
17 sys.path.remove(str(helpers.test_dir))
18 except ValueError:
19 pass
20
21
22 def pytest_addoption(parser):
23 parser.addoption(
24 "--integration-case-dir",
25 default=os.path.join(helpers.test_dir, 'completion'),
26 help="Directory in which integration test case files locate.")
27 parser.addoption(
28 "--refactor-case-dir",
29 default=os.path.join(helpers.test_dir, 'refactor'),
30 help="Directory in which refactoring test case files locate.")
31 parser.addoption(
32 "--test-files", "-T", default=[], action='append',
33 help=(
34 "Specify test files using FILE_NAME[:LINE[,LINE[,...]]]. "
35 "For example: -T generators.py:10,13,19. "
36 "Note that you can use -m to specify the test case by id."))
37 parser.addoption(
38 "--thirdparty", action='store_true',
39 help="Include integration tests that requires third party modules.")
40
41
42 def parse_test_files_option(opt):
43 """
44 Parse option passed to --test-files into a key-value pair.
45
46 >>> parse_test_files_option('generators.py:10,13,19')
47 ('generators.py', [10, 13, 19])
48 """
49 opt = str(opt)
50 if ':' in opt:
51 (f_name, rest) = opt.split(':', 1)
52 return f_name, list(map(int, rest.split(',')))
53 else:
54 return opt, []
55
56
57 def pytest_generate_tests(metafunc):
58 """
59 :type metafunc: _pytest.python.Metafunc
60 """
61 test_files = dict(map(parse_test_files_option,
62 metafunc.config.option.test_files))
63 if 'case' in metafunc.fixturenames:
64 base_dir = metafunc.config.option.integration_case_dir
65 thirdparty = metafunc.config.option.thirdparty
66 cases = list(run.collect_dir_tests(base_dir, test_files))
67 if thirdparty:
68 cases.extend(run.collect_dir_tests(
69 os.path.join(base_dir, 'thirdparty'), test_files, True))
70 ids = ["%s:%s" % (c.module_name, c.line_nr_test) for c in cases]
71 metafunc.parametrize('case', cases, ids=ids)
72
73 if 'refactor_case' in metafunc.fixturenames:
74 base_dir = metafunc.config.option.refactor_case_dir
75 cases = list(refactor.collect_dir_tests(base_dir, test_files))
76 metafunc.parametrize(
77 'refactor_case', cases,
78 ids=[c.refactor_type + '-' + c.name for c in cases]
79 )
80
81 if 'static_analysis_case' in metafunc.fixturenames:
82 base_dir = os.path.join(os.path.dirname(__file__), 'static_analysis')
83 cases = list(collect_static_analysis_tests(base_dir, test_files))
84 metafunc.parametrize(
85 'static_analysis_case',
86 cases,
87 ids=[c.name for c in cases]
88 )
89
90
91 def collect_static_analysis_tests(base_dir, test_files):
92 for f_name in os.listdir(base_dir):
93 files_to_execute = [a for a in test_files.items() if a[0] in f_name]
94 if f_name.endswith(".py") and (not test_files or files_to_execute):
95 path = os.path.join(base_dir, f_name)
96 yield run.StaticAnalysisCase(path)
97
98
99 @pytest.fixture(scope='session')
100 def venv_path(tmpdir_factory, environment):
101 if isinstance(environment, InterpreterEnvironment):
102 # The environment can be a tox virtualenv environment which we don't
103 # want, so use the system environment.
104 environment = get_system_environment(
105 '.'.join(str(x) for x in environment.version_info[:2])
106 )
107
108 tmpdir = tmpdir_factory.mktemp('venv_path')
109 dirname = os.path.join(tmpdir.strpath, 'venv')
110
111 # We cannot use the Python from tox because tox creates virtualenvs and
112 # they have different site.py files that work differently than the default
113 # ones. Instead, we find the real Python executable by printing the value
114 # of sys.base_prefix or sys.real_prefix if we are in a virtualenv.
115 output = subprocess.check_output([
116 environment.executable, "-c",
117 "import sys; "
118 "print(sys.real_prefix if hasattr(sys, 'real_prefix') else sys.base_prefix)"
119 ])
120 prefix = output.rstrip().decode('utf8')
121 if os.name == 'nt':
122 executable_path = os.path.join(prefix, 'python')
123 else:
124 executable_name = os.path.basename(environment.executable)
125 executable_path = os.path.join(prefix, 'bin', executable_name)
126
127 return_code = subprocess.call([executable_path, '-m', 'venv', dirname])
128 assert return_code == 0, return_code
129 return dirname
130
131
132 @pytest.fixture()
133 def cwd_tmpdir(monkeypatch, tmpdir):
134 with helpers.set_cwd(tmpdir.strpath):
135 yield tmpdir
136
137
138 @pytest.fixture
139 def inference_state(Script):
140 return Script('')._inference_state
141
142
143 @pytest.fixture
144 def same_process_inference_state(Script):
145 return Script('', environment=InterpreterEnvironment())._inference_state
146
147
148 @pytest.fixture
149 def disable_typeshed(monkeypatch):
150 from jedi.inference.gradual import typeshed
151 monkeypatch.setattr(typeshed, '_load_from_typeshed', lambda *args, **kwargs: None)
152
153
154 @pytest.fixture
155 def create_compiled_object(inference_state):
156 return lambda obj: create_from_access_path(
157 inference_state,
158 inference_state.compiled_subprocess.create_simple_object(obj)
159 )
160
161
162 @pytest.fixture(params=[False, True])
163 def class_findable(monkeypatch, request):
164 if not request.param:
165 monkeypatch.setattr(
166 MixedModuleContext,
167 '_get_mixed_object',
168 lambda self, compiled_object: compiled_object.as_context()
169 )
170 return request.param