Debian Codegraph @

test/run.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """
3 |jedi| is mostly being tested by what I would call "integration tests". These
4 tests are testing type inference with the public API. This makes a
5 lot of sense for |jedi|. Also, it is hard to write doctests/unittests for
6 the internal data structures.
7
8 There are different kinds of tests:
9
10 - completions / inference ``#?``
11 - goto: ``#!``
12 - references: ``#<``
13
14 How to run tests?
15 +++++++++++++++++
16
17 Jedi uses pytest_ to run unit and integration tests. To run tests,
18 simply run ``pytest``.
19
20 .. _pytest: http://pytest.org
21
22 Most integration test cases are located in the ``test/completion`` directory
23 and each test case starts with one of these comments:
24
25 - ``#?`` (completions / inference)
26 - ``#!`` (goto)
27 - ``#<`` (references)
28
29 There is also support for third party libraries. In a normal test run they are
30 not being executed, you have to provide a ``--thirdparty`` option.
31
32 In addition to pytest's ``-k`` and ``-m`` options, you can use the
33 ``-T`` (``--test-files`) option to specify which test cases should run.
34 It takes the format of ``FILE_NAME[:LINE[,LINE[,...]]]`` where
35 ``FILE_NAME`` is a file in ``test/completion`` and ``LINE`` is a line
36 number of the test comment. Here are some examples:
37
38 Run tests only in ``completion/basic.py`` and ``completion/imports.py``::
39
40 pytest test/test_integration.py -T basic.py -T imports.py
41
42 Run test at line 4, 6, and 8 in ``completion/basic.py``::
43
44 pytest test/test_integration.py -T basic.py:4,6,8
45
46 See ``pytest --help`` for more information.
47
48 If you want to debug a test, just use the ``--pdb`` option.
49
50 Alternate Test Runner
51 +++++++++++++++++++++
52
53 If you don't like the output of ``pytest``, there's an alternate test runner
54 that you can start by running ``./run.py``. The above example could be run by::
55
56 ./run.py basic 4 6 8 50-80
57
58 The advantage of this runner is simplicity and more customized error reports.
59
60 Auto-Completion Tests
61 +++++++++++++++++++++
62
63 Uses a comment to specify a test on the next line. The comment defines the
64 expected completions. The comment always begins with `#?`. The last row
65 symbolizes the cursor. For example::
66
67 #? ['upper']
68 a = 'foo'; a.upp
69
70 Inference Tests
71 +++++++++++++++
72
73 Inference tests look very simliar. The difference is that inference tests don't
74 use brackets::
75
76 #? int()
77 ab = 3; ab
78
79 Goto Tests
80 ++++++++++
81
82 Goto Tests look like this::
83
84 abc = 1
85 #! ['abc=1']
86 abc
87
88 Additionally it is possible to specify the column by adding a number, which
89 describes the position of the test (otherwise it's just the end of line)::
90
91 #! 2 ['abc=1']
92 abc
93
94 Reference Tests
95 +++++++++++++++
96
97 Tests look like this::
98
99 abc = 1
100 #< (1,0), (3,0)
101 abc
102 """
103 import os
104 import re
105 import sys
106 import operator
107 from ast import literal_eval
108 from io import StringIO
109 from functools import reduce
110 from unittest.mock import ANY
111 from pathlib import Path
112
113 import parso
114 from _pytest.outcomes import Skipped
115 import pytest
116
117 import jedi
118 from jedi import debug
119 from jedi.api.classes import Name
120 from jedi.api.completion import get_user_context
121 from jedi import parser_utils
122 from jedi.api.environment import get_default_environment, get_system_environment
123 from jedi.inference.gradual.conversion import convert_values
124 from jedi.inference.analysis import Warning
125
126 test_dir = Path(__file__).absolute().parent
127
128 TEST_COMPLETIONS = 0
129 TEST_INFERENCE = 1
130 TEST_GOTO = 2
131 TEST_REFERENCES = 3
132
133
134 grammar313 = parso.load_grammar(version='3.13')
135
136
137 class BaseTestCase(object):
138 def __init__(self, skip_version_info=None):
139 self._skip_version_info = skip_version_info
140 self._skip = None
141
142 def set_skip(self, reason):
143 self._skip = reason
144
145 def get_skip_reason(self, environment):
146 if self._skip is not None:
147 return self._skip
148
149 if self._skip_version_info is None:
150 return
151
152 comp_map = {
153 '==': 'eq',
154 '<=': 'le',
155 '>=': 'ge',
156 '<': 'lt',
157 '>': 'gt',
158 }
159 min_version, operator_ = self._skip_version_info
160 operation = getattr(operator, comp_map[operator_])
161 if not operation(environment.version_info[:2], min_version):
162 return "Python version %s %s.%s" % (
163 operator_, min_version[0], min_version[1]
164 )
165
166
167 class IntegrationTestCase(BaseTestCase):
168 source: str # Defined as a side effect
169
170 def __init__(self, test_type, correct, line_nr, column, start, line,
171 path=None, skip_version_info=None):
172 super().__init__(skip_version_info)
173 self.test_type = test_type
174 self.correct = correct
175 self.line_nr = line_nr
176 self.column = column
177 self.start = start
178 self.line = line
179 self.path = path
180 self._project = jedi.Project(test_dir)
181
182 @property
183 def module_name(self):
184 return os.path.splitext(os.path.basename(self.path))[0]
185
186 @property
187 def line_nr_test(self):
188 """The test is always defined on the line before."""
189 return self.line_nr - 1
190
191 def __repr__(self):
192 return '<%s: %s:%s %r>' % (self.__class__.__name__, self.path,
193 self.line_nr_test, self.line.rstrip())
194
195 def script(self, environment):
196 return jedi.Script(
197 self.source,
198 path=self.path,
199 environment=environment,
200 project=self._project
201 )
202
203 def run(self, compare_cb, environment=None):
204 testers = {
205 TEST_COMPLETIONS: self.run_completion,
206 TEST_INFERENCE: self.run_inference,
207 TEST_GOTO: self.run_goto,
208 TEST_REFERENCES: self.run_get_references,
209 }
210 if (self.path.endswith('pytest.py') or self.path.endswith('conftest.py')) \
211 and os.path.realpath(environment.executable) != os.path.realpath(sys.executable):
212 # It's not guarantueed that pytest is installed in test
213 # environments, if we're not running in the same environment that
214 # we're already in, so just skip that case.
215 pytest.skip()
216 return testers[self.test_type](compare_cb, environment)
217
218 def run_completion(self, compare_cb, environment):
219 completions = self.script(environment).complete(self.line_nr, self.column)
220 # import cProfile; cProfile.run('...')
221
222 comp_str = {c.name for c in completions}
223 for r in completions:
224 # Test if this access raises an error
225 assert isinstance(r.type, str)
226 return compare_cb(self, comp_str, set(literal_eval(self.correct)))
227
228 def run_inference(self, compare_cb, environment):
229 script = self.script(environment)
230 inference_state = script._inference_state
231
232 def comparison(definition):
233 suffix = '()' if definition.type == 'instance' else ''
234 return definition.full_name + suffix
235
236 def definition(correct, correct_start, path):
237 should_be = set()
238 for match in re.finditer('(?:[^ ]+)', correct):
239 string = match.group(0)
240 parser = grammar313.parse(string, start_symbol='eval_input', error_recovery=False)
241 parser_utils.move(parser.get_root_node(), self.line_nr)
242 node = parser.get_root_node()
243 module_context = script._get_module_context()
244 user_context = get_user_context(module_context, (self.line_nr, 0))
245 node.parent = user_context.tree_node
246 results = convert_values(user_context.infer_node(node))
247 if not results:
248 raise Exception('Could not resolve %s on line %s'
249 % (match.string, self.line_nr - 1))
250
251 should_be |= set(Name(inference_state, r.name) for r in results)
252 debug.dbg('Finished getting types', color='YELLOW')
253
254 # Because the objects have different ids, `repr`, then compare.
255 should = set(comparison(r) for r in should_be)
256 return should
257
258 should = definition(self.correct, self.start, script.path)
259 result = script.infer(self.line_nr, self.column)
260 is_str = set(comparison(r) for r in result)
261 for r in result:
262 # Test if this access raises an error
263 assert isinstance(r.type, str)
264 return compare_cb(self, is_str, should)
265
266 def run_goto(self, compare_cb, environment):
267 result = self.script(environment).goto(self.line_nr, self.column)
268 comp_str = str(sorted(str(r.description) for r in result))
269 return compare_cb(self, comp_str, self.correct)
270
271 def run_get_references(self, compare_cb, environment):
272 result = self.script(environment).get_references(self.line_nr, self.column)
273 self.correct = self.correct.strip()
274 compare = sorted(
275 (('stub:' if r.is_stub() else '')
276 + re.sub(r'^completion\.', '', r.module_name),
277 r.line,
278 r.column)
279 for r in result
280 )
281 wanted = []
282 if not self.correct:
283 positions = []
284 else:
285 positions = literal_eval(self.correct)
286 for pos_tup in positions:
287 if type(pos_tup[0]) == str:
288 # this means that there is a module specified
289 if pos_tup[1] == ...:
290 pos_tup = pos_tup[0], ANY, pos_tup[2]
291 wanted.append(pos_tup)
292 else:
293 line = pos_tup[0]
294 if pos_tup[0] is not None:
295 line += self.line_nr
296 wanted.append((self.module_name, line, pos_tup[1]))
297
298 return compare_cb(self, compare, sorted(wanted))
299
300
301 class StaticAnalysisCase(BaseTestCase):
302 """
303 Static Analysis cases lie in the static_analysis folder.
304 The tests also start with `#!`, like the inference tests.
305 """
306 def __init__(self, path):
307 self._path = path
308 self.name = os.path.basename(path)
309 with open(path) as f:
310 self._source = f.read()
311
312 skip_version_info = None
313 for line in self._source.splitlines():
314 skip_version_info = skip_python_version(line) or skip_version_info
315
316 super().__init__(skip_version_info)
317
318 def collect_comparison(self):
319 cases = []
320 for line_nr, line in enumerate(self._source.splitlines(), 1):
321 match = re.match(r'(\s*)#! (\d+ )?(.*)$', line)
322 if match is not None:
323 column = int(match.group(2) or 0) + len(match.group(1))
324 cases.append((line_nr + 1, column, match.group(3)))
325 return cases
326
327 def run(self, compare_cb, environment):
328 def typ_str(inst):
329 return 'warning ' if isinstance(inst, Warning) else ''
330
331 analysis = jedi.Script(
332 self._source,
333 path=self._path,
334 environment=environment,
335 )._analysis()
336 analysis = [(r.line, r.column, typ_str(r) + r.name)
337 for r in analysis]
338 compare_cb(self, analysis, self.collect_comparison())
339
340 def __repr__(self):
341 return "<%s: %s>" % (self.__class__.__name__, os.path.basename(self._path))
342
343
344 def skip_python_version(line):
345 # check for python minimal version number
346 match = re.match(r" *# *python *([<>]=?|==) *(\d+(?:\.\d+)?)$", line)
347 if match:
348 minimal_python_version = tuple(map(int, match.group(2).split(".")))
349 return minimal_python_version, match.group(1)
350 return None
351
352
353 def collect_file_tests(path, lines, lines_to_execute):
354 def makecase(t):
355 return IntegrationTestCase(t, correct, line_nr, column,
356 start, line, path=path,
357 skip_version_info=skip_version_info)
358
359 start = None
360 correct = None
361 test_type = None
362 skip_version_info = None
363 for line_nr, line in enumerate(lines, 1):
364 if correct is not None:
365 r = re.match(r'^(\d+)\s*(.*)$', correct)
366 if r:
367 column = int(r.group(1))
368 correct = r.group(2)
369 start += r.regs[2][0] # second group, start index
370 else:
371 column = len(line) - 1 # -1 for the \n
372 if test_type == '!':
373 yield makecase(TEST_GOTO)
374 elif test_type == '<':
375 yield makecase(TEST_REFERENCES)
376 elif correct.startswith('['):
377 yield makecase(TEST_COMPLETIONS)
378 else:
379 yield makecase(TEST_INFERENCE)
380 correct = None
381 else:
382 skip_version_info = skip_python_version(line) or skip_version_info
383 try:
384 r = re.search(r'(?:^|(?<=\s))#([?!<])\s*([^\n]*)', line)
385 # test_type is ? for completion and ! for goto
386 test_type = r.group(1)
387 correct = r.group(2)
388 # Quick hack to make everything work (not quite a bloody unicorn hack though).
389 if correct == '':
390 correct = ' '
391 start = r.start()
392 except AttributeError:
393 correct = None
394 else:
395 # Skip the test, if this is not specified test.
396 for l in lines_to_execute:
397 if isinstance(l, tuple) and l[0] <= line_nr <= l[1] \
398 or line_nr == l:
399 break
400 else:
401 if lines_to_execute:
402 correct = None
403
404
405 def collect_dir_tests(base_dir, test_files, check_thirdparty=False):
406 for f_name in os.listdir(base_dir):
407 files_to_execute = [a for a in test_files.items() if f_name.startswith(a[0])]
408 lines_to_execute = reduce(lambda x, y: x + y[1], files_to_execute, [])
409 if f_name.endswith(".py") and (not test_files or files_to_execute):
410 skip = None
411 if check_thirdparty:
412 lib = f_name.replace('_.py', '')
413 try:
414 # there is always an underline at the end.
415 # It looks like: completion/thirdparty/pylab_.py
416 __import__(lib)
417 except ImportError:
418 skip = 'Thirdparty-Library %s not found.' % lib
419
420 path = os.path.join(base_dir, f_name)
421
422 with open(path, newline='') as f:
423 source = f.read()
424
425 for case in collect_file_tests(path, StringIO(source),
426 lines_to_execute):
427 case.source = source
428 if skip:
429 case.set_skip(skip)
430 yield case
431
432
433 docoptstr = """
434 Using run.py to make debugging easier with integration tests.
435
436 An alternative testing format, which is much more hacky, but very nice to
437 work with.
438
439 Usage:
440 run.py [--pdb] [--debug] [--thirdparty] [--env <dotted>] [<rest>...]
441 run.py --help
442
443 Options:
444 -h --help Show this screen.
445 --pdb Enable pdb debugging on fail.
446 -d, --debug Enable text output debugging (please install ``colorama``).
447 --thirdparty Also run thirdparty tests (in ``completion/thirdparty``).
448 --env <dotted> A Python version, like 3.14, 3.13, etc.
449 """
450 if __name__ == '__main__':
451 import docopt
452 arguments = docopt.docopt(docoptstr)
453
454 import time
455 t_start = time.time()
456
457 if arguments['--debug']:
458 jedi.set_debug_function()
459
460 # get test list, that should be executed
461 test_files = {}
462 last = None
463 for arg in arguments['<rest>']:
464 match = re.match(r'(\d+)-(\d+)', arg)
465 if match:
466 start, end = match.groups()
467 test_files[last].append((int(start), int(end)))
468 elif arg.isdigit():
469 if last is None:
470 continue
471 test_files[last].append(int(arg))
472 else:
473 test_files[arg] = []
474 last = arg
475
476 # completion tests:
477 dir_ = os.path.dirname(os.path.realpath(__file__))
478 completion_test_dir = os.path.join(dir_, '../test/completion')
479 completion_test_dir = os.path.abspath(completion_test_dir)
480 tests_fail = 0
481
482 # execute tests
483 cases = list(collect_dir_tests(completion_test_dir, test_files))
484 if test_files or arguments['--thirdparty']:
485 completion_test_dir += '/thirdparty'
486 cases += collect_dir_tests(completion_test_dir, test_files, True)
487
488 def file_change(current, tests, fails):
489 if current is None:
490 current = ''
491 else:
492 current = os.path.basename(current)
493 print('{:25} {} tests and {} fails.'.format(current, tests, fails))
494
495 def report(case, actual, desired):
496 if actual == desired:
497 return 0
498 else:
499 print("\ttest fail @%d, actual = %s, desired = %s"
500 % (case.line_nr - 1, actual, desired))
501 return 1
502
503 if arguments['--env']:
504 environment = get_system_environment(arguments['--env'])
505 else:
506 # Will be 3.13.
507 environment = get_default_environment()
508
509 import traceback
510 current = cases[0].path if cases else None
511 count = fails = 0
512 for c in cases:
513 if c.get_skip_reason(environment):
514 continue
515 if current != c.path:
516 file_change(current, count, fails)
517 current = c.path
518 count = fails = 0
519
520 try:
521 if c.run(report, environment):
522 tests_fail += 1
523 fails += 1
524 except Exception:
525 traceback.print_exc()
526 print("\ttest fail @%d" % (c.line_nr - 1))
527 tests_fail += 1
528 fails += 1
529 if arguments['--pdb']:
530 import pdb
531 pdb.post_mortem()
532 except Skipped:
533 pass
534
535 count += 1
536
537 file_change(current, count, fails)
538
539 print('\nSummary: (%s fails of %s tests) in %.3fs'
540 % (tests_fail, len(cases), time.time() - t_start))
541
542 exit_code = 1 if tests_fail else 0
543 sys.exit(exit_code)