Debian Codegraph @

test/test_api/test_completion.py

raw symbols SCIP
1 from os.path import join, sep as s, dirname, expanduser
2 import os
3 from textwrap import dedent
4 from itertools import count
5 from pathlib import Path
6 from typing import Any
7
8 import pytest
9
10 from ..helpers import root_dir
11 from jedi.api.helpers import _start_match, _fuzzy_match
12 from jedi.inference.imports import _load_python_module
13 from jedi.file_io import KnownContentFileIO
14 from jedi.inference.base_value import ValueSet
15
16
17 def test_in_whitespace(Script):
18 code = dedent('''
19 def x():
20 pass''')
21 assert len(Script(code).complete(column=2)) > 20
22
23
24 def test_empty_init(Script):
25 """This was actually an issue."""
26 code = dedent('''\
27 class X(object): pass
28 X(''')
29 assert not Script(code).complete()
30
31
32 def test_in_empty_space(Script):
33 code = dedent('''\
34 class X(object):
35 def __init__(self):
36 hello
37 ''')
38 comps = Script(code).complete(3, 7)
39 self, = [c for c in comps if c.name == 'self']
40 assert self.name == 'self'
41 def_, = self.infer()
42 assert def_.name == 'X'
43
44
45 def test_indent_value(Script):
46 """
47 If an INDENT is the next supposed token, we should still be able to
48 complete.
49 """
50 code = 'if 1:\nisinstanc'
51 comp, = Script(code).complete()
52 assert comp.name == 'isinstance'
53
54
55 def test_keyword_value(Script):
56 def get_names(*args, **kwargs):
57 return [d.name for d in Script(*args, **kwargs).complete()]
58
59 names = get_names('if 1:\n pass\n')
60 assert 'if' in names
61 assert 'elif' in names
62
63
64 def test_os_nowait(Script):
65 """ github issue #45 """
66 s = Script("import os; os.P_").complete()
67 assert 'P_NOWAIT' in [i.name for i in s]
68
69
70 def test_points_in_completion(Script):
71 """At some point, points were inserted into the completions, this
72 caused problems, sometimes.
73 """
74 c = Script("if IndentationErr").complete()
75 assert c[0].name == 'IndentationError'
76 assert c[0].complete == 'or'
77
78
79 def test_loading_unicode_files_with_bad_global_charset(Script, monkeypatch, tmpdir):
80 dirname = str(tmpdir.mkdir('jedi-test'))
81 filename1 = join(dirname, 'test1.py')
82 filename2 = join(dirname, 'test2.py')
83 data = "# coding: latin-1\nfoo = 'm\xf6p'\n".encode("latin-1")
84
85 with open(filename1, "wb") as f:
86 f.write(data)
87 s = Script("from test1 import foo\nfoo.", path=filename2)
88 s.complete(line=2, column=4)
89
90
91 def test_complete_expanduser(Script):
92 possibilities = os.scandir(expanduser('~'))
93 non_dots = [p for p in possibilities if not p.name.startswith('.') and len(p.name) > 1]
94 item = non_dots[0]
95 line = "'~%s%s'" % (os.sep, item.name)
96 s = Script(line)
97 expected_name = item.name
98 if item.is_dir():
99 expected_name += os.path.sep
100 assert expected_name in [c.name for c in s.complete(column=len(line)-1)]
101
102
103 def test_fake_subnodes(Script):
104 """
105 Test the number of subnodes of a fake object.
106
107 There was a bug where the number of child nodes would grow on every
108 call to :func:``jedi.inference.compiled.fake.get_faked``.
109
110 See Github PR#649 and isseu #591.
111 """
112 def get_str_completion(values):
113 for c in values:
114 if c.name == 'str':
115 return c
116 limit = None
117 for i in range(2):
118 completions = Script('').complete()
119 c = get_str_completion(completions)
120 str_value, = c._name.infer()
121 n = len(str_value.tree_node.children[-1].children)
122 if i == 0:
123 limit = n
124 else:
125 assert n == limit
126
127
128 def test_generator(Script):
129 # Did have some problems with the usage of generator completions this
130 # way.
131 s = "def abc():\n" \
132 " yield 1\n" \
133 "abc()."
134 assert Script(s).complete()
135
136
137 def test_in_comment(Script):
138 assert Script(" # Comment").complete()
139 # TODO this is a bit ugly, that the behaviors in comments are different.
140 assert not Script("max_attr_value = int(2) # Cast to int for spe").complete()
141
142
143 def test_in_comment_before_string(Script):
144 assert not Script(" # Foo\n'asdf'").complete(line=1)
145
146
147 def test_async(Script, environment):
148 code = dedent('''
149 foo = 3
150 async def x():
151 hey = 3
152 ho''')
153 comps = Script(code).complete(column=4)
154 names = [c.name for c in comps]
155 assert 'foo' in names
156 assert 'hey' in names
157
158
159 def test_with_stmt_error_recovery(Script):
160 assert Script('with open('') as foo: foo.\na').complete(line=1)
161
162
163 def test_function_param_usage(Script):
164 c, = Script('def func(foo_value):\n str(foo_valu').complete()
165 assert c.complete == 'e'
166 assert c.name == 'foo_value'
167
168 c1, c2 = Script('def func(foo_value):\n func(foo_valu').complete()
169 assert c1.complete == 'e'
170 assert c1.name == 'foo_value'
171 assert c2.complete == 'e='
172 assert c2.name == 'foo_value='
173
174
175 @pytest.mark.parametrize(
176 'code, has_keywords', (
177 ('', True),
178 ('x;', True),
179 ('1', False),
180 ('1 ', True),
181 ('1\t', True),
182 ('1\n', True),
183 ('1\\\n', True),
184 )
185 )
186 def test_keyword_completion(Script, code, has_keywords):
187 assert has_keywords == any(x.is_keyword for x in Script(code).complete())
188
189
190 f1 = join(root_dir, 'example.py')
191 f2 = join(root_dir, 'test', 'example.py')
192 os_path = 'from os.path import *\n'
193 # os.path.sep escaped
194 se = s * 2 if s == '\\' else s
195 current_dirname = os.path.basename(dirname(dirname(dirname(__file__))))
196
197
198 @pytest.mark.parametrize(
199 'file, code, column, expected', [
200 # General tests / relative paths
201 (None, '"comp', None, []), # No files like comp
202 (None, '"test', None, [s]),
203 (None, '"test', 4, ['t' + s]),
204 ('example.py', '"test%scomp' % s, None, ['letion' + s]),
205 ('example.py', 'r"comp"', None, []),
206 ('example.py', 'r"tes"', None, []),
207 ('example.py', '1 + r"tes"', None, []),
208 ('example.py', 'r"tes"', 5, ['t' + s]),
209 ('example.py', 'r" tes"', 6, []),
210 ('test%sexample.py' % se, 'r"tes"', 5, ['t' + s]),
211 ('test%sexample.py' % se, 'r"test%scomp"' % s, 5, ['t' + s]),
212 ('test%sexample.py' % se, 'r"test%scomp"' % s, 11, ['letion' + s]),
213 ('test%sexample.py' % se, '"%s"' % join('test', 'completion', 'basi'), 21, ['c.py']),
214 ('example.py', 'rb"' + join('..', current_dirname, 'tes'), None, ['t' + s]),
215
216 # Absolute paths
217 (None, f'"{root_dir.joinpath("test", "test_ca")}', None, ['che.py"']),
218 (None, f'"{root_dir.joinpath("test", "test_ca")}"', len(str(root_dir)) + 14, ['che.py']),
219
220 # Longer quotes
221 ('example.py', 'r"""test', None, [s]),
222 ('example.py', 'r"""\ntest', None, []),
223 ('example.py', 'u"""tes\n', (1, 7), ['t' + s]),
224 ('example.py', '"""test%stest_cache.p"""' % s, 20, ['y']),
225 ('example.py', '"""test%stest_cache.p"""' % s, 19, ['py"""']),
226
227 # Adding
228 ('example.py', '"test" + "%stest_cac' % se, None, ['he.py"']),
229 ('example.py', '"test" + "%s" + "test_cac' % se, None, ['he.py"']),
230 ('example.py', 'x = 1 + "test', None, []),
231 ('example.py', 'x = f("te" + "st)', 16, [s]),
232 ('example.py', 'x = f("te" + "st', 16, [s]),
233 ('example.py', 'x = f("te" + "st"', 16, [s]),
234 ('example.py', 'x = f("te" + "st")', 16, [s]),
235 ('example.py', 'x = f("t" + "est")', 16, [s]),
236 ('example.py', 'x = f(b"t" + "est")', 17, []),
237 ('example.py', '"test" + "', None, [s]),
238
239 # __file__
240 (f1, os_path + 'dirname(__file__) + "%stest' % s, None, [s]),
241 (f2, os_path + 'dirname(__file__) + "%stest_ca' % se, None, ['che.py"']),
242 (f2, os_path + 'dirname(abspath(__file__)) + sep + "test_ca', None, ['che.py"']),
243 (f2, os_path + 'join(dirname(__file__), "completion") + sep + "basi', None, ['c.py"']),
244 (f2, os_path + 'join("test", "completion") + sep + "basi', None, ['c.py"']),
245
246 # inside join
247 (f2, os_path + 'join(dirname(__file__), "completion", "basi', None, ['c.py"']),
248 (f2, os_path + 'join(dirname(__file__), "completion", "basi)', 43, ['c.py"']),
249 (f2, os_path + 'join(dirname(__file__), "completion", "basi")', 43, ['c.py']),
250 (f2, os_path + 'join(dirname(__file__), "completion", "basi)', 35, ['']),
251 (f2, os_path + 'join(dirname(__file__), "completion", "basi)', 33, ['on"']),
252 (f2, os_path + 'join(dirname(__file__), "completion", "basi")', 33, ['on"']),
253
254 # join with one argument. join will not get inferred and the result is
255 # that directories and in a slash. This is unfortunate, but doesn't
256 # really matter.
257 (f2, os_path + 'join("tes', 9, ['t"']),
258 (f2, os_path + 'join(\'tes)', 9, ["t'"]),
259 (f2, os_path + 'join(r"tes"', 10, ['t']),
260 (f2, os_path + 'join("""tes""")', 11, ['t']),
261
262 # Almost like join but not really
263 (f2, os_path + 'join["tes', 9, ['t' + s]),
264 (f2, os_path + 'join["tes"', 9, ['t' + s]),
265 (f2, os_path + 'join["tes"]', 9, ['t' + s]),
266 (f2, os_path + 'join[dirname(__file__), "completi', 33, []),
267 (f2, os_path + 'join[dirname(__file__), "completi"', 33, []),
268 (f2, os_path + 'join[dirname(__file__), "completi"]', 33, []),
269
270 # With full paths
271 (f2, 'import os\nos.path.join(os.path.dirname(__file__), "completi', 49, ['on"']),
272 (f2, 'import os\nos.path.join(os.path.dirname(__file__), "completi"', 49, ['on']),
273 (f2, 'import os\nos.path.join(os.path.dirname(__file__), "completi")', 49, ['on']),
274
275 # With alias
276 (f2, 'import os.path as p as p\np.join(p.dirname(__file__), "completi', None, ['on"']),
277 (f2, 'from os.path import dirname, join as j\nj(dirname(__file__), "completi',
278 None, ['on"']),
279
280 # Trying to break it
281 (f2, os_path + 'join(["tes', 10, ['t' + s]),
282 (f2, os_path + 'join(["tes"]', 10, ['t' + s]),
283 (f2, os_path + 'join(["tes"])', 10, ['t' + s]),
284 (f2, os_path + 'join("test", "test_cac" + x,', 22, ['he.py']),
285
286 # GH #1528
287 (f2, "'a' 'b'", 4, Ellipsis),
288 ]
289 )
290 def test_file_path_completions(Script, file, code, column, expected):
291 line = None
292 if isinstance(column, tuple):
293 line, column = column
294 comps = Script(code, path=file).complete(line=line, column=column)
295 if expected is Ellipsis:
296 assert len(comps) > 100 # This is basically global completions.
297 else:
298 assert [c.complete for c in comps] == expected
299
300
301 def test_file_path_should_have_completions(Script):
302 assert Script('r"').complete() # See GH #1503
303
304
305 _dict_keys_completion_tests: "list[tuple[str, int | None, list[str | Any]]]" = [
306 ('ints[', 5, ['1', '50', Ellipsis]),
307 ('ints[]', 5, ['1', '50', Ellipsis]),
308 ('ints[1]', 5, ['1', '50', Ellipsis]),
309 ('ints[1]', 6, ['']),
310 ('ints[1', 5, ['1', '50', Ellipsis]),
311 ('ints[1', 6, ['']),
312
313 ('ints[5]', 5, ['1', '50', Ellipsis]),
314 ('ints[5]', 6, ['0']),
315 ('ints[50', 5, ['1', '50', Ellipsis]),
316 ('ints[5', 6, ['0']),
317 ('ints[ 5', None, ['0']),
318 ('ints [ 5', None, ['0']),
319 ('ints[50', 6, ['0']),
320 ('ints[50', 7, ['']),
321
322 ('strs[', 5, ["'asdf'", "'fbar'", "'foo'", Ellipsis]),
323 ('strs[]', 5, ["'asdf'", "'fbar'", "'foo'", Ellipsis]),
324 ("strs['", 6, ["asdf'", "fbar'", "foo'"]),
325 ("strs[']", 6, ["asdf'", "fbar'", "foo'"]),
326 ('strs["]', 6, ['asdf"', 'fbar"', 'foo"']),
327 ('strs["""]', 6, ['asdf', 'fbar', 'foo']),
328 ('strs["""]', 8, ['asdf"""', 'fbar"""', 'foo"""']),
329 ('strs[b"]', 8, []),
330 ('strs[r"asd', 10, ['f"']),
331 ('strs[r"asd"', 10, ['f']),
332 ('strs[R"asd', 10, ['f"']),
333 ('strs[ R"asd', None, ['f"']),
334 ('strs[\tR"asd', None, ['f"']),
335 ('strs[\nR"asd', None, ['f"']),
336 ('strs[f"asd', 10, []),
337 ('strs[br"""asd', 13, ['f"""']),
338 ('strs[br"""asd"""', 13, ['f']),
339 ('strs[ \t"""asd"""', 13, ['f']),
340
341 ('strs["f', 7, ['bar"', 'oo"']),
342 ('strs["f"', 7, ['bar', 'oo']),
343 ('strs["f]', 7, ['bar"', 'oo"']),
344 ('strs["f"]', 7, ['bar', 'oo']),
345
346 ('mixed[', 6, [r"'a\\sdf'", '1', '1.1', "b'foo'", Ellipsis]),
347 ('mixed[1', 7, ['', '.1']),
348 ('mixed[Non', 9, ['e']),
349
350 ('casted["f', 9, ['3"', 'bar"', 'oo"']),
351 ('casted["f"', 9, ['3', 'bar', 'oo']),
352 ('casted["f3', 10, ['"']),
353 ('casted["f3"', 10, ['']),
354 ('casted_mod["f', 13, ['3"', 'bar"', 'oo"', 'ull"', 'uuu"']),
355
356 ('keywords["', None, ['a"']),
357 ('keywords[Non', None, ['e']),
358 ('keywords[Fa', None, ['lse']),
359 ('keywords[Tr', None, ['ue']),
360 ('keywords[str', None, ['', 's']),
361 ]
362
363
364 @pytest.mark.parametrize(
365 'added_code, column, expected', _dict_keys_completion_tests
366 )
367 def test_dict_keys_completions(Script, added_code, column, expected):
368 code = dedent(r'''
369 ints = {1: ''}
370 ints[50] = 3.0
371 strs = {'asdf': 1, u"""foo""": 2, r'fbar': 3}
372 mixed = {1: 2, 1.10: 4, None: 6, r'a\sdf': 8, b'foo': 9}
373 casted = dict(strs, f3=4, r'\\xyz')
374 casted_mod = dict(casted)
375 casted_mod["fuuu"] = 8
376 casted_mod["full"] = 8
377 keywords = {None: 1, False: 2, "a": 3}
378 ''')
379 comps = Script(code + added_code).complete(column=column)
380 if Ellipsis in expected:
381 # This means that global completions are part of this, so filter all of
382 # that out.
383 comps = [c for c in comps if not c._name.is_value_name and not c.is_keyword]
384 expected = [e for e in expected if e is not Ellipsis]
385
386 assert [c.complete for c in comps] == expected
387
388
389 def test_dict_keys_in_weird_case(Script):
390 assert Script('a[\n# foo\nx]').complete(line=2, column=0)
391
392
393 def test_start_match():
394 assert _start_match('Condition', 'C')
395
396
397 def test_fuzzy_match():
398 assert _fuzzy_match('Condition', 'i')
399 assert not _fuzzy_match('Condition', 'p')
400 assert _fuzzy_match('Condition', 'ii')
401 assert not _fuzzy_match('Condition', 'Ciito')
402 assert _fuzzy_match('Condition', 'Cdiio')
403
404
405 def test_ellipsis_completion(Script):
406 assert Script('...').complete() == []
407
408
409 @pytest.fixture
410 def module_injector():
411 counter = count()
412
413 def module_injector(inference_state, names, code):
414 assert isinstance(names, tuple)
415 file_io = KnownContentFileIO(
416 Path('foo/bar/module-injector-%s.py' % next(counter)).absolute(),
417 code
418 )
419 v = _load_python_module(inference_state, file_io, names)
420 inference_state.module_cache.add(names, ValueSet([v]))
421
422 return module_injector
423
424
425 def test_completion_cache(Script, module_injector):
426 """
427 For some modules like numpy, tensorflow or pandas we cache docstrings and
428 type to avoid them slowing us down, because they are huge.
429 """
430 script = Script('import numpy; numpy.foo')
431 module_injector(script._inference_state, ('numpy',), 'def foo(a): "doc"')
432 c, = script.complete()
433 assert c.name == 'foo'
434 assert c.type == 'function'
435 assert c.docstring() == 'foo(a)\n\ndoc'
436
437 code = dedent('''\
438 class foo:
439 'doc2'
440 def __init__(self):
441 pass
442 ''')
443 script = Script('import numpy; numpy.foo')
444 module_injector(script._inference_state, ('numpy',), code)
445 # The outpus should still be the same
446 c, = script.complete()
447 assert c.name == 'foo'
448 assert c.type == 'function'
449 assert c.docstring() == 'foo(a)\n\ndoc'
450 cls, = c.infer()
451 assert cls.type == 'class'
452 assert cls.docstring() == 'foo()\n\ndoc2'
453
454
455 @pytest.mark.parametrize('module', ['typing', 'os'])
456 def test_module_completions(Script, module):
457 for c in Script('import {module}; {module}.'.format(module=module)).complete():
458 # Just make sure that there are no errors
459 c.type
460 c.docstring()
461
462
463 def test_whitespace_at_end_after_dot(Script):
464 assert 'strip' in [c.name for c in Script('str. ').complete()]