| 1 |
""" |
| 2 |
Tests of ``jedi.api.Interpreter``. |
| 3 |
""" |
| 4 |
import sys |
| 5 |
import warnings |
| 6 |
import typing |
| 7 |
|
| 8 |
import pytest |
| 9 |
|
| 10 |
import jedi |
| 11 |
import jedi.settings |
| 12 |
from jedi.inference.compiled import mixed |
| 13 |
from importlib import import_module |
| 14 |
|
| 15 |
|
| 16 |
class _GlobalNameSpace: |
| 17 |
class SideEffectContainer: |
| 18 |
pass |
| 19 |
|
| 20 |
|
| 21 |
def get_completion(source, namespace): |
| 22 |
i = jedi.Interpreter(source, [namespace]) |
| 23 |
completions = i.complete() |
| 24 |
assert len(completions) == 1 |
| 25 |
return completions[0] |
| 26 |
|
| 27 |
|
| 28 |
def test_builtin_details(): |
| 29 |
import keyword |
| 30 |
|
| 31 |
class EmptyClass: |
| 32 |
pass |
| 33 |
|
| 34 |
variable = EmptyClass() |
| 35 |
|
| 36 |
def func(): |
| 37 |
pass |
| 38 |
|
| 39 |
cls = get_completion('EmptyClass', locals()) |
| 40 |
var = get_completion('variable', locals()) |
| 41 |
f = get_completion('func', locals()) |
| 42 |
m = get_completion('keyword', locals()) |
| 43 |
assert cls.type == 'class' |
| 44 |
assert var.type == 'instance' |
| 45 |
assert f.type == 'function' |
| 46 |
assert m.type == 'module' |
| 47 |
|
| 48 |
|
| 49 |
def test_numpy_like_non_zero(): |
| 50 |
""" |
| 51 |
Numpy-like array can't be caster to bool and need to be compacre with |
| 52 |
`is`/`is not` and not `==`/`!=` |
| 53 |
""" |
| 54 |
|
| 55 |
class NumpyNonZero: |
| 56 |
def __zero__(self): |
| 57 |
raise ValueError('Numpy arrays would raise and tell you to use .any() or all()') |
| 58 |
|
| 59 |
def __bool__(self): |
| 60 |
raise ValueError('Numpy arrays would raise and tell you to use .any() or all()') |
| 61 |
|
| 62 |
class NumpyLike: |
| 63 |
|
| 64 |
def __eq__(self, other): |
| 65 |
return NumpyNonZero() |
| 66 |
|
| 67 |
def something(self): |
| 68 |
pass |
| 69 |
|
| 70 |
x = NumpyLike() |
| 71 |
d = {'a': x} |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
get_completion('d["a"].some', {'d': d}) |
| 76 |
get_completion('x.some', {'x': x}) |
| 77 |
|
| 78 |
|
| 79 |
def test_nested_resolve(): |
| 80 |
class XX: |
| 81 |
def x(): |
| 82 |
pass |
| 83 |
|
| 84 |
cls = get_completion('XX', locals()) |
| 85 |
func = get_completion('XX.x', locals()) |
| 86 |
assert (func.line, func.column) == (cls.line + 1, 12) |
| 87 |
|
| 88 |
|
| 89 |
def test_side_effect_completion(): |
| 90 |
""" |
| 91 |
In the repl it's possible to cause side effects that are not documented in |
| 92 |
Python code, however we want references to Python code as well. Therefore |
| 93 |
we need some mixed kind of magic for tests. |
| 94 |
""" |
| 95 |
_GlobalNameSpace.SideEffectContainer.foo = 1 |
| 96 |
side_effect = get_completion('SideEffectContainer', _GlobalNameSpace.__dict__) |
| 97 |
|
| 98 |
|
| 99 |
value, = side_effect._name.infer() |
| 100 |
assert isinstance(value, mixed.MixedObject) |
| 101 |
foo = get_completion('SideEffectContainer.foo', _GlobalNameSpace.__dict__) |
| 102 |
assert foo.name == 'foo' |
| 103 |
|
| 104 |
|
| 105 |
def _assert_interpreter_complete(source, namespace, completions, *, check_type=False, **kwds): |
| 106 |
script = jedi.Interpreter(source, [namespace], **kwds) |
| 107 |
cs = script.complete() |
| 108 |
actual = [c.name for c in cs] |
| 109 |
if check_type: |
| 110 |
for c in cs: |
| 111 |
c.type |
| 112 |
assert sorted(actual) == sorted(completions) |
| 113 |
|
| 114 |
|
| 115 |
def test_complete_raw_function(): |
| 116 |
from os.path import join |
| 117 |
_assert_interpreter_complete('join("").up', locals(), ['upper']) |
| 118 |
|
| 119 |
|
| 120 |
def test_complete_raw_function_different_name(): |
| 121 |
from os.path import join as pjoin |
| 122 |
_assert_interpreter_complete('pjoin("").up', locals(), ['upper']) |
| 123 |
|
| 124 |
|
| 125 |
def test_complete_raw_module(): |
| 126 |
import os |
| 127 |
_assert_interpreter_complete('os.path.join("a").up', locals(), ['upper']) |
| 128 |
|
| 129 |
|
| 130 |
def test_complete_raw_instance(): |
| 131 |
import datetime |
| 132 |
dt = datetime.datetime(2013, 1, 1) |
| 133 |
completions = ['time', 'timetz', 'timetuple', 'timestamp'] |
| 134 |
_assert_interpreter_complete('(dt - dt).ti', locals(), completions) |
| 135 |
|
| 136 |
|
| 137 |
def test_list(): |
| 138 |
array = ['haha', 1] |
| 139 |
_assert_interpreter_complete('array[0].uppe', locals(), ['upper']) |
| 140 |
_assert_interpreter_complete('array[0].real', locals(), []) |
| 141 |
|
| 142 |
|
| 143 |
_assert_interpreter_complete('array[int].real', locals(), ['real']) |
| 144 |
_assert_interpreter_complete('array[int()].real', locals(), ['real']) |
| 145 |
|
| 146 |
_assert_interpreter_complete('array[2].upper', locals(), ['upper']) |
| 147 |
|
| 148 |
|
| 149 |
def test_getattr(): |
| 150 |
class Foo1: |
| 151 |
bar = [] |
| 152 |
baz = 'bar' |
| 153 |
_assert_interpreter_complete('getattr(Foo1, baz).app', locals(), ['append']) |
| 154 |
|
| 155 |
|
| 156 |
def test_slice(): |
| 157 |
class Foo1: |
| 158 |
bar = [] |
| 159 |
baz = 'xbarx' |
| 160 |
_assert_interpreter_complete('getattr(Foo1, baz[1:-1]).append', locals(), ['append']) |
| 161 |
|
| 162 |
|
| 163 |
def test_getitem_side_effects(): |
| 164 |
class Foo2: |
| 165 |
def __getitem__(self, index): |
| 166 |
|
| 167 |
if True: |
| 168 |
raise NotImplementedError() |
| 169 |
return index |
| 170 |
|
| 171 |
foo = Foo2() |
| 172 |
_assert_interpreter_complete('foo["asdf"].upper', locals(), ['upper']) |
| 173 |
|
| 174 |
|
| 175 |
@pytest.mark.parametrize('stacklevel', [1, 2]) |
| 176 |
@pytest.mark.filterwarnings("error") |
| 177 |
def test_property_warnings(stacklevel, allow_unsafe_getattr): |
| 178 |
class Foo3: |
| 179 |
@property |
| 180 |
def prop(self): |
| 181 |
|
| 182 |
warnings.warn("foo", DeprecationWarning, stacklevel=stacklevel) |
| 183 |
return '' |
| 184 |
|
| 185 |
foo = Foo3() |
| 186 |
expected = ['upper'] if allow_unsafe_getattr else [] |
| 187 |
_assert_interpreter_complete('foo.prop.uppe', locals(), expected) |
| 188 |
|
| 189 |
|
| 190 |
@pytest.mark.parametrize('class_is_findable', [False, True]) |
| 191 |
def test__getattr__completions(allow_unsafe_getattr, class_is_findable): |
| 192 |
class CompleteGetattr(object): |
| 193 |
def __getattr__(self, name): |
| 194 |
if name == 'foo': |
| 195 |
return self |
| 196 |
if name == 'fbar': |
| 197 |
return '' |
| 198 |
raise AttributeError(name) |
| 199 |
|
| 200 |
def __dir__(self): |
| 201 |
return ['foo', 'fbar'] + object.__dir__(self) |
| 202 |
|
| 203 |
if not class_is_findable: |
| 204 |
CompleteGetattr.__name__ = "something_somewhere" |
| 205 |
namespace = {'c': CompleteGetattr()} |
| 206 |
expected = ['foo', 'fbar'] |
| 207 |
_assert_interpreter_complete('c.f', namespace, expected) |
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
if not allow_unsafe_getattr: |
| 214 |
expected = [] |
| 215 |
_assert_interpreter_complete('c.foo.f', namespace, expected) |
| 216 |
_assert_interpreter_complete('c.foo.foo.f', namespace, expected) |
| 217 |
_assert_interpreter_complete('c.foo.uppe', namespace, []) |
| 218 |
|
| 219 |
expected_int = ['upper'] if allow_unsafe_getattr or class_is_findable else [] |
| 220 |
_assert_interpreter_complete('c.foo.fbar.uppe', namespace, expected_int) |
| 221 |
|
| 222 |
|
| 223 |
@pytest.fixture(params=[False, True]) |
| 224 |
def allow_unsafe_getattr(request, monkeypatch): |
| 225 |
monkeypatch.setattr(jedi.settings, 'allow_unsafe_interpreter_executions', request.param) |
| 226 |
return request.param |
| 227 |
|
| 228 |
|
| 229 |
def test_property_error_oldstyle(allow_unsafe_getattr): |
| 230 |
lst = [] |
| 231 |
|
| 232 |
class Foo3: |
| 233 |
@property |
| 234 |
def bar(self): |
| 235 |
lst.append(1) |
| 236 |
raise ValueError |
| 237 |
|
| 238 |
foo = Foo3() |
| 239 |
_assert_interpreter_complete('foo.bar', locals(), ['bar']) |
| 240 |
_assert_interpreter_complete('foo.bar.baz', locals(), []) |
| 241 |
|
| 242 |
if allow_unsafe_getattr: |
| 243 |
assert lst == [1] |
| 244 |
else: |
| 245 |
|
| 246 |
assert lst == [] |
| 247 |
|
| 248 |
|
| 249 |
def test_property_error_newstyle(allow_unsafe_getattr): |
| 250 |
lst = [] |
| 251 |
|
| 252 |
class Foo3(object): |
| 253 |
@property |
| 254 |
def bar(self): |
| 255 |
lst.append(1) |
| 256 |
raise ValueError |
| 257 |
|
| 258 |
foo = Foo3() |
| 259 |
_assert_interpreter_complete('foo.bar', locals(), ['bar']) |
| 260 |
_assert_interpreter_complete('foo.bar.baz', locals(), []) |
| 261 |
|
| 262 |
if allow_unsafe_getattr: |
| 263 |
assert lst == [1] |
| 264 |
else: |
| 265 |
|
| 266 |
assert lst == [] |
| 267 |
|
| 268 |
|
| 269 |
def test_property_content(): |
| 270 |
class Foo3(object): |
| 271 |
@property |
| 272 |
def bar(self): |
| 273 |
return 1 |
| 274 |
|
| 275 |
foo = Foo3() |
| 276 |
def_, = jedi.Interpreter('foo.bar', [locals()]).infer() |
| 277 |
assert def_.name == 'int' |
| 278 |
|
| 279 |
|
| 280 |
def test_param_completion(): |
| 281 |
def foo(bar): |
| 282 |
pass |
| 283 |
|
| 284 |
lambd = lambda xyz: 3 |
| 285 |
|
| 286 |
_assert_interpreter_complete('foo(bar', locals(), ['bar=']) |
| 287 |
_assert_interpreter_complete('lambd(xyz', locals(), ['xyz=']) |
| 288 |
|
| 289 |
|
| 290 |
def test_endless_yield(): |
| 291 |
lst = [1] * 10000 |
| 292 |
|
| 293 |
|
| 294 |
_assert_interpreter_complete('list(lst)[9000].rea', locals(), ['real']) |
| 295 |
|
| 296 |
|
| 297 |
def test_completion_params(): |
| 298 |
foo = lambda a, b=3: None |
| 299 |
|
| 300 |
script = jedi.Interpreter('foo', [locals()]) |
| 301 |
c, = script.complete() |
| 302 |
sig, = c.get_signatures() |
| 303 |
assert [p.name for p in sig.params] == ['a', 'b'] |
| 304 |
assert sig.params[0].infer() == [] |
| 305 |
t, = sig.params[1].infer() |
| 306 |
assert t.name == 'int' |
| 307 |
|
| 308 |
|
| 309 |
def test_completion_param_annotations(): |
| 310 |
|
| 311 |
|
| 312 |
code = 'def foo(a: 1, b: str, c: int = 1.0) -> bytes: pass' |
| 313 |
exec_locals = {} |
| 314 |
exec(code, exec_locals) |
| 315 |
script = jedi.Interpreter('foo', [exec_locals]) |
| 316 |
c, = script.complete() |
| 317 |
sig, = c.get_signatures() |
| 318 |
a, b, c = sig.params |
| 319 |
assert a.infer() == [] |
| 320 |
assert [d.name for d in b.infer()] == ['str'] |
| 321 |
assert {d.name for d in c.infer()} == {'int', 'float'} |
| 322 |
|
| 323 |
assert a.description == 'param a: 1' |
| 324 |
assert b.description == 'param b: str' |
| 325 |
assert c.description == 'param c: int=1.0' |
| 326 |
|
| 327 |
d, = jedi.Interpreter('foo()', [exec_locals]).infer() |
| 328 |
assert d.name == 'bytes' |
| 329 |
|
| 330 |
|
| 331 |
def test_keyword_argument(): |
| 332 |
def f(some_keyword_argument): |
| 333 |
pass |
| 334 |
|
| 335 |
c, = jedi.Interpreter("f(some_keyw", [{'f': f}]).complete() |
| 336 |
assert c.name == 'some_keyword_argument=' |
| 337 |
assert c.complete == 'ord_argument=' |
| 338 |
|
| 339 |
|
| 340 |
f.__name__ = 'xSOMETHING' |
| 341 |
c, = jedi.Interpreter("x(some_keyw", [{'x': f}]).complete() |
| 342 |
assert c.name == 'some_keyword_argument=' |
| 343 |
|
| 344 |
|
| 345 |
def test_more_complex_instances(): |
| 346 |
class Something: |
| 347 |
def foo(self, other): |
| 348 |
return self |
| 349 |
|
| 350 |
class Base: |
| 351 |
def wow(self): |
| 352 |
return Something() |
| 353 |
|
| 354 |
script = jedi.Interpreter('Base().wow().foo', [locals()]) |
| 355 |
c, = script.complete() |
| 356 |
assert c.name == 'foo' |
| 357 |
|
| 358 |
x = Base() |
| 359 |
script = jedi.Interpreter('x.wow().foo', [locals()]) |
| 360 |
c, = script.complete() |
| 361 |
assert c.name == 'foo' |
| 362 |
|
| 363 |
|
| 364 |
def test_repr_execution_issue(): |
| 365 |
""" |
| 366 |
Anticipate inspect.getfile executing a __repr__ of all kinds of objects. |
| 367 |
See also #919. |
| 368 |
""" |
| 369 |
class ErrorRepr: |
| 370 |
def __repr__(self): |
| 371 |
raise Exception('xyz') |
| 372 |
|
| 373 |
er = ErrorRepr() |
| 374 |
|
| 375 |
script = jedi.Interpreter('er', [locals()]) |
| 376 |
d, = script.infer() |
| 377 |
assert d.name == 'ErrorRepr' |
| 378 |
assert d.type == 'instance' |
| 379 |
|
| 380 |
|
| 381 |
def test_dir_magic_method(allow_unsafe_getattr): |
| 382 |
class CompleteAttrs(object): |
| 383 |
def __getattr__(self, name): |
| 384 |
if name == 'foo': |
| 385 |
return 1 |
| 386 |
if name == 'bar': |
| 387 |
return 2 |
| 388 |
raise AttributeError(name) |
| 389 |
|
| 390 |
def __dir__(self): |
| 391 |
return ['foo', 'bar'] + object.__dir__(self) |
| 392 |
|
| 393 |
itp = jedi.Interpreter("ca.", [{'ca': CompleteAttrs()}]) |
| 394 |
completions = itp.complete() |
| 395 |
names = [c.name for c in completions] |
| 396 |
assert ('__dir__' in names) is True |
| 397 |
assert '__class__' in names |
| 398 |
assert 'foo' in names |
| 399 |
assert 'bar' in names |
| 400 |
|
| 401 |
foo = [c for c in completions if c.name == 'foo'][0] |
| 402 |
if allow_unsafe_getattr: |
| 403 |
inst, = foo.infer() |
| 404 |
assert inst.name == 'int' |
| 405 |
assert inst.type == 'instance' |
| 406 |
else: |
| 407 |
assert foo.infer() == [] |
| 408 |
|
| 409 |
|
| 410 |
def test_name_not_findable(): |
| 411 |
class X(): |
| 412 |
if 0: |
| 413 |
NOT_FINDABLE |
| 414 |
|
| 415 |
def hidden(self): |
| 416 |
return |
| 417 |
|
| 418 |
hidden.__name__ = 'NOT_FINDABLE' |
| 419 |
|
| 420 |
setattr(X, 'NOT_FINDABLE', X.hidden) |
| 421 |
|
| 422 |
assert jedi.Interpreter("X.NOT_FINDA", [locals()]).complete() |
| 423 |
|
| 424 |
|
| 425 |
def test_stubs_working(): |
| 426 |
from multiprocessing import cpu_count |
| 427 |
defs = jedi.Interpreter("cpu_count()", [locals()]).infer() |
| 428 |
assert [d.name for d in defs] == ['int'] |
| 429 |
|
| 430 |
|
| 431 |
def test_sys_path_docstring(): |
| 432 |
import jedi |
| 433 |
s = jedi.Interpreter("from sys import path\npath", namespaces=[locals()]) |
| 434 |
s.complete(line=2, column=4)[0].docstring() |
| 435 |
|
| 436 |
|
| 437 |
@pytest.mark.parametrize( |
| 438 |
'code, completions', [ |
| 439 |
('x[0].uppe', ['upper']), |
| 440 |
('x[1337].uppe', ['upper']), |
| 441 |
('x[""].uppe', ['upper']), |
| 442 |
('x.appen', ['append']), |
| 443 |
|
| 444 |
('y.add', ['add']), |
| 445 |
('y[0].', []), |
| 446 |
('list(y)[0].', []), |
| 447 |
|
| 448 |
('z[0].uppe', ['upper']), |
| 449 |
('z[0].append', ['append']), |
| 450 |
('z[1].uppe', ['upper']), |
| 451 |
('z[1].append', []), |
| 452 |
|
| 453 |
('collections.deque().app', ['append', 'appendleft']), |
| 454 |
('deq.app', ['append', 'appendleft']), |
| 455 |
('deq.pop', ['pop', 'popleft']), |
| 456 |
('deq.pop().', []), |
| 457 |
|
| 458 |
('collections.Counter("asdf").setdef', ['setdefault']), |
| 459 |
('collections.Counter("asdf").pop().imag', ['imag']), |
| 460 |
('list(collections.Counter("asdf").keys())[0].uppe', ['upper']), |
| 461 |
('counter.setdefa', ['setdefault']), |
| 462 |
('counter.pop().imag', []), |
| 463 |
('counter.keys())[0].uppe', []), |
| 464 |
|
| 465 |
('string.upper().uppe', ['upper']), |
| 466 |
('"".upper().uppe', ['upper']), |
| 467 |
] |
| 468 |
) |
| 469 |
def test_simple_completions(code, completions): |
| 470 |
x = [str] |
| 471 |
y = {1} |
| 472 |
z = {1: str, 2: list} |
| 473 |
import collections |
| 474 |
deq = collections.deque([1]) |
| 475 |
counter = collections.Counter(['asdf']) |
| 476 |
string = '' |
| 477 |
|
| 478 |
defs = jedi.Interpreter(code, [locals()]).complete() |
| 479 |
assert [d.name for d in defs] == completions |
| 480 |
|
| 481 |
|
| 482 |
def test__wrapped__(): |
| 483 |
from functools import lru_cache |
| 484 |
|
| 485 |
@lru_cache(maxsize=128) |
| 486 |
def syslogs_to_df(): |
| 487 |
pass |
| 488 |
|
| 489 |
c, = jedi.Interpreter('syslogs_to_df', [locals()]).complete() |
| 490 |
|
| 491 |
assert c.line == syslogs_to_df.__wrapped__.__code__.co_firstlineno + 1 |
| 492 |
|
| 493 |
|
| 494 |
def test_illegal_class_instance(): |
| 495 |
class X: |
| 496 |
__class__ = 1 |
| 497 |
X.__name__ = 'asdf' |
| 498 |
d, = jedi.Interpreter('foo', [{'foo': X()}]).infer() |
| 499 |
v, = d._name.infer() |
| 500 |
assert not v.is_instance() |
| 501 |
|
| 502 |
|
| 503 |
@pytest.mark.parametrize('module_name', ['sys', 'time', 'unittest.mock']) |
| 504 |
def test_core_module_completes(module_name): |
| 505 |
module = import_module(module_name) |
| 506 |
assert jedi.Interpreter('module.', [locals()]).complete() |
| 507 |
|
| 508 |
|
| 509 |
@pytest.mark.parametrize( |
| 510 |
'code, expected, index', [ |
| 511 |
('a(', ['a', 'b', 'c'], 0), |
| 512 |
('b(', ['b', 'c'], 0), |
| 513 |
|
| 514 |
|
| 515 |
('c(', ['b', 'c'], 0), |
| 516 |
] |
| 517 |
) |
| 518 |
def test_partial_signatures(code, expected, index): |
| 519 |
import functools |
| 520 |
|
| 521 |
def func(a, b, c): |
| 522 |
pass |
| 523 |
|
| 524 |
a = functools.partial(func) |
| 525 |
b = functools.partial(func, 1) |
| 526 |
c = functools.partial(func, 1, c=2) |
| 527 |
|
| 528 |
sig, = jedi.Interpreter(code, [locals()]).get_signatures() |
| 529 |
assert [p.name for p in sig.params] == expected |
| 530 |
assert index == sig.index |
| 531 |
|
| 532 |
if sys.version_info < (3, 13): |
| 533 |
|
| 534 |
|
| 535 |
assert sig.name == 'partial' |
| 536 |
|
| 537 |
|
| 538 |
def test_type_var(): |
| 539 |
"""This was an issue before, see Github #1369""" |
| 540 |
x = typing.TypeVar('myvar') |
| 541 |
def_, = jedi.Interpreter('x', [locals()]).infer() |
| 542 |
assert def_.name == 'TypeVar' |
| 543 |
|
| 544 |
|
| 545 |
@pytest.mark.parametrize('class_is_findable', [False, True]) |
| 546 |
def test_param_annotation_completion(class_is_findable): |
| 547 |
class Foo: |
| 548 |
bar = 3 |
| 549 |
|
| 550 |
if not class_is_findable: |
| 551 |
Foo.__name__ = 'asdf' |
| 552 |
|
| 553 |
code = 'def CallFoo(x: Foo):\n x.ba' |
| 554 |
def_, = jedi.Interpreter(code, [locals()]).complete() |
| 555 |
assert def_.name == 'bar' |
| 556 |
|
| 557 |
|
| 558 |
@pytest.mark.parametrize( |
| 559 |
'code, column, expected', [ |
| 560 |
('strs[', 5, ["'asdf'", "'fbar'", "'foo'", Ellipsis]), |
| 561 |
('strs[]', 5, ["'asdf'", "'fbar'", "'foo'", Ellipsis]), |
| 562 |
("strs['", 6, ["asdf'", "fbar'", "foo'"]), |
| 563 |
("strs[']", 6, ["asdf'", "fbar'", "foo'"]), |
| 564 |
('strs["]', 6, ['asdf"', 'fbar"', 'foo"']), |
| 565 |
|
| 566 |
('mixed[', 6, [r"'a\\sdf'", '1', '1.1', "b'foo'", Ellipsis]), |
| 567 |
('mixed[1', 7, ['', '.1']), |
| 568 |
('mixed[Non', 9, ['e']), |
| 569 |
|
| 570 |
('implicit[10', None, ['00']), |
| 571 |
|
| 572 |
('inherited["', None, ['blablu"']), |
| 573 |
] |
| 574 |
) |
| 575 |
def test_dict_completion(code, column, expected): |
| 576 |
strs = {'asdf': 1, """foo""": 2, r'fbar': 3} |
| 577 |
mixed = {1: 2, 1.10: 4, None: 6, r'a\sdf': 8, b'foo': 9} |
| 578 |
|
| 579 |
class Inherited(dict): |
| 580 |
pass |
| 581 |
inherited = Inherited(blablu=3) |
| 582 |
|
| 583 |
namespaces = [locals(), {'implicit': {1000: 3}}] |
| 584 |
comps = jedi.Interpreter(code, namespaces).complete(column=column) |
| 585 |
if Ellipsis in expected: |
| 586 |
|
| 587 |
|
| 588 |
comps = [c for c in comps if not c._name.is_value_name and not c.is_keyword] |
| 589 |
expected = [e for e in expected if e is not Ellipsis] |
| 590 |
|
| 591 |
assert [c.complete for c in comps] == expected |
| 592 |
|
| 593 |
|
| 594 |
@pytest.mark.parametrize( |
| 595 |
'code, types', [ |
| 596 |
('dct[1]', ['int']), |
| 597 |
('dct["asdf"]', ['float']), |
| 598 |
('dct[r"asdf"]', ['float']), |
| 599 |
('dct["a"]', ['float', 'int']), |
| 600 |
] |
| 601 |
) |
| 602 |
def test_dict_getitem(code, types): |
| 603 |
dct = {1: 2, "asdf": 1.0} |
| 604 |
|
| 605 |
comps = jedi.Interpreter(code, [locals()]).infer() |
| 606 |
assert [c.name for c in comps] == types |
| 607 |
|
| 608 |
|
| 609 |
@pytest.mark.parametrize('class_is_findable', [False, True]) |
| 610 |
@pytest.mark.parametrize( |
| 611 |
'code, expected', [ |
| 612 |
('DunderCls()[0]', 'int'), |
| 613 |
('dunder[0]', 'int'), |
| 614 |
('next(DunderCls())', 'float'), |
| 615 |
('next(dunder)', 'float'), |
| 616 |
('for x in DunderCls(): x', 'str'), |
| 617 |
|
| 618 |
] |
| 619 |
) |
| 620 |
def test_dunders(class_is_findable, code, expected, allow_unsafe_getattr): |
| 621 |
from typing import Iterator |
| 622 |
|
| 623 |
class DunderCls: |
| 624 |
def __getitem__(self, key) -> int: |
| 625 |
return 1 |
| 626 |
|
| 627 |
def __iter__(self, key) -> Iterator[str]: |
| 628 |
pass |
| 629 |
|
| 630 |
def __next__(self, key) -> float: |
| 631 |
pass |
| 632 |
|
| 633 |
if not class_is_findable: |
| 634 |
DunderCls.__name__ = 'asdf' |
| 635 |
|
| 636 |
dunder = DunderCls() |
| 637 |
|
| 638 |
n, = jedi.Interpreter(code, [locals()]).infer() |
| 639 |
assert n.name == expected |
| 640 |
|
| 641 |
|
| 642 |
def foo(): |
| 643 |
raise KeyError |
| 644 |
|
| 645 |
|
| 646 |
def bar(): |
| 647 |
return float |
| 648 |
|
| 649 |
|
| 650 |
@pytest.mark.parametrize( |
| 651 |
'annotations, result, code', [ |
| 652 |
({}, [], ''), |
| 653 |
(None, [], ''), |
| 654 |
({'asdf': 'str'}, [], ''), |
| 655 |
|
| 656 |
({'return': 'str'}, ['str'], ''), |
| 657 |
({'return': 'None'}, ['NoneType'], ''), |
| 658 |
({'return': 'str().upper'}, [], ''), |
| 659 |
({'return': 'foo()'}, [], ''), |
| 660 |
({'return': 'bar()'}, ['float'], ''), |
| 661 |
|
| 662 |
|
| 663 |
({'return': 'typing.Union[str, int]'}, ['int', 'str'], ''), |
| 664 |
({'return': 'typing.Union["str", int]'}, ['int', 'str'], ''), |
| 665 |
({'return': 'typing.Union["str", 1]'}, |
| 666 |
(['str'] if (3, 14) > sys.version_info >= (3, 11) else []), ''), |
| 667 |
({'return': 'typing.Optional[str]'}, ['NoneType', 'str'], ''), |
| 668 |
({'return': 'typing.Optional[str, int]'}, [], ''), |
| 669 |
({'return': 'typing.Any'}, |
| 670 |
['_AnyMeta'] if sys.version_info >= (3, 11) else [], ''), |
| 671 |
|
| 672 |
({'return': 'typing.Tuple[int, str]'}, ['tuple'], ''), |
| 673 |
({'return': 'typing.Tuple[int, str]'}, ['int'], 'x()[0]'), |
| 674 |
({'return': 'typing.Tuple[int, str]'}, ['str'], 'x()[1]'), |
| 675 |
({'return': 'typing.Tuple[int, str]'}, [], 'x()[2]'), |
| 676 |
|
| 677 |
({'return': 'typing.List'}, ['list'], 'list'), |
| 678 |
({'return': 'typing.List[int]'}, ['list'], 'list'), |
| 679 |
({'return': 'typing.List[int]'}, ['int'], 'x()[0]'), |
| 680 |
({'return': 'typing.List[int, str]'}, [], 'x()[0]'), |
| 681 |
|
| 682 |
({'return': 'typing.Iterator[int]'}, [], 'x()[0]'), |
| 683 |
({'return': 'typing.Iterator[int]'}, ['int'], 'next(x())'), |
| 684 |
({'return': 'typing.Iterable[float]'}, ['float'], 'list(x())[0]'), |
| 685 |
|
| 686 |
({'return': 'decimal.Decimal'}, [], ''), |
| 687 |
({'return': 'lalalalallalaa'}, [], ''), |
| 688 |
({'return': 'lalalalallalaa.lala'}, [], ''), |
| 689 |
] |
| 690 |
) |
| 691 |
def test_string_annotation(annotations, result, code): |
| 692 |
x = lambda foo: 1 |
| 693 |
x.__annotations__ = annotations |
| 694 |
defs = jedi.Interpreter(code or 'x()', [locals()]).infer() |
| 695 |
assert [d.name for d in defs] == result |
| 696 |
|
| 697 |
|
| 698 |
def test_name_not_inferred_properly(): |
| 699 |
""" |
| 700 |
In IPython notebook it is typical that some parts of the code that is |
| 701 |
provided was already executed. In that case if something is not properly |
| 702 |
inferred, it should still infer from the variables it already knows. |
| 703 |
""" |
| 704 |
x = 1 |
| 705 |
d, = jedi.Interpreter('x = UNDEFINED; x', [locals()]).infer() |
| 706 |
assert d.name == 'int' |
| 707 |
|
| 708 |
|
| 709 |
def test_variable_reuse(): |
| 710 |
x = 1 |
| 711 |
d, = jedi.Interpreter('y = x\ny', [locals()]).infer() |
| 712 |
assert d.name == 'int' |
| 713 |
|
| 714 |
|
| 715 |
def test_negate(): |
| 716 |
code = "x = -y" |
| 717 |
x, = jedi.Interpreter(code, [{'y': 3}]).infer(1, 0) |
| 718 |
assert x.name == 'int' |
| 719 |
value, = x._name.infer() |
| 720 |
assert value.get_safe_value() == -3 |
| 721 |
|
| 722 |
|
| 723 |
def test_complete_not_findable_class_source(): |
| 724 |
class TestClass(): |
| 725 |
ta = 1 |
| 726 |
ta1 = 2 |
| 727 |
|
| 728 |
|
| 729 |
|
| 730 |
|
| 731 |
TestClass.__module__ = "__main__" |
| 732 |
|
| 733 |
module = sys.modules.pop("__main__") |
| 734 |
try: |
| 735 |
interpreter = jedi.Interpreter("TestClass.", [locals()]) |
| 736 |
completions = interpreter.complete(column=10, line=1) |
| 737 |
finally: |
| 738 |
sys.modules["__main__"] = module |
| 739 |
|
| 740 |
assert "ta" in [c.name for c in completions] |
| 741 |
assert "ta1" in [c.name for c in completions] |
| 742 |
|
| 743 |
|
| 744 |
def test_param_infer_default(): |
| 745 |
abs_sig, = jedi.Interpreter('abs(', [{'abs': abs}]).get_signatures() |
| 746 |
param, = abs_sig.params |
| 747 |
|
| 748 |
assert param.name in ('x', 'number') |
| 749 |
assert param.infer_default() == [] |
| 750 |
|
| 751 |
|
| 752 |
@pytest.mark.parametrize( |
| 753 |
'code, expected', [ |
| 754 |
("random.triangular(", ['high=', 'low=', 'mode=']), |
| 755 |
("random.triangular(low=1, ", ['high=', 'mode=']), |
| 756 |
("random.triangular(high=1, ", ['low=', 'mode=']), |
| 757 |
("random.triangular(low=1, high=2, ", ['mode=']), |
| 758 |
("random.triangular(low=1, mode=2, ", ['high=']), |
| 759 |
], |
| 760 |
) |
| 761 |
def test_keyword_param_completion(code, expected): |
| 762 |
import random |
| 763 |
completions = jedi.Interpreter(code, [locals()]).complete() |
| 764 |
assert expected == [c.name for c in completions if c.name.endswith('=')] |
| 765 |
|
| 766 |
|
| 767 |
@pytest.mark.parametrize('class_is_findable', [False, True]) |
| 768 |
def test_avoid_descriptor_executions_if_not_necessary(class_is_findable): |
| 769 |
counter = 0 |
| 770 |
|
| 771 |
class AvoidDescriptor(object): |
| 772 |
@property |
| 773 |
def prop(self): |
| 774 |
nonlocal counter |
| 775 |
counter += 1 |
| 776 |
return self |
| 777 |
|
| 778 |
if not class_is_findable: |
| 779 |
AvoidDescriptor.__name__ = "something_somewhere" |
| 780 |
namespace = {'b': AvoidDescriptor()} |
| 781 |
expected = ['prop'] |
| 782 |
_assert_interpreter_complete('b.pro', namespace, expected, check_type=True) |
| 783 |
assert counter == 0 |
| 784 |
_assert_interpreter_complete('b.prop.pro', namespace, expected, check_type=True) |
| 785 |
assert counter == 1 |
| 786 |
|
| 787 |
|
| 788 |
class Hello: |
| 789 |
its_me = 1 |
| 790 |
|
| 791 |
|
| 792 |
@pytest.mark.parametrize('class_is_findable', [False, True]) |
| 793 |
def test_try_to_use_return_annotation_for_property(class_is_findable): |
| 794 |
class WithProperties(object): |
| 795 |
@property |
| 796 |
def with_annotation1(self) -> str: |
| 797 |
raise BaseException |
| 798 |
|
| 799 |
@property |
| 800 |
def with_annotation2(self) -> 'str': |
| 801 |
raise BaseException |
| 802 |
|
| 803 |
@property |
| 804 |
def with_annotation3(self) -> Hello: |
| 805 |
raise BaseException |
| 806 |
|
| 807 |
@property |
| 808 |
def with_annotation4(self) -> 'Hello': |
| 809 |
raise BaseException |
| 810 |
|
| 811 |
@property |
| 812 |
def with_annotation_garbage1(self) -> 'asldjflksjdfljdslkjfsl': |
| 813 |
return Hello() |
| 814 |
|
| 815 |
@property |
| 816 |
def with_annotation_garbage2(self) -> 'sdf & 8': |
| 817 |
return Hello() |
| 818 |
|
| 819 |
@property |
| 820 |
def without_annotation(self): |
| 821 |
return "" |
| 822 |
|
| 823 |
if not class_is_findable: |
| 824 |
WithProperties.__name__ = "something_somewhere" |
| 825 |
Hello.__name__ = "something_somewhere_else" |
| 826 |
|
| 827 |
namespace = {'p': WithProperties()} |
| 828 |
_assert_interpreter_complete('p.without_annotation.upp', namespace, ['upper']) |
| 829 |
_assert_interpreter_complete('p.with_annotation1.upp', namespace, ['upper']) |
| 830 |
_assert_interpreter_complete('p.with_annotation2.upp', namespace, ['upper']) |
| 831 |
_assert_interpreter_complete('p.with_annotation3.its', namespace, ['its_me']) |
| 832 |
_assert_interpreter_complete('p.with_annotation4.its', namespace, ['its_me']) |
| 833 |
|
| 834 |
_assert_interpreter_complete('p.with_annotation_garbage1.its', namespace, ['its_me']) |
| 835 |
_assert_interpreter_complete('p.with_annotation_garbage2.its', namespace, ['its_me']) |
| 836 |
|
| 837 |
|
| 838 |
def test_nested__getitem__(): |
| 839 |
d = {'foo': {'bar': 1}} |
| 840 |
_assert_interpreter_complete('d["fo', locals(), ['"foo"']) |
| 841 |
_assert_interpreter_complete('d["foo"]["ba', locals(), ['"bar"']) |
| 842 |
_assert_interpreter_complete('(d["foo"])["ba', locals(), ['"bar"']) |
| 843 |
_assert_interpreter_complete('((d["foo"]))["ba', locals(), ['"bar"']) |
| 844 |
|
| 845 |
|
| 846 |
@pytest.mark.parametrize('class_is_findable', [False, True]) |
| 847 |
def test_custom__getitem__(class_is_findable, allow_unsafe_getattr): |
| 848 |
class CustomGetItem: |
| 849 |
def __getitem__(self, x: int): |
| 850 |
return "asdf" |
| 851 |
|
| 852 |
if not class_is_findable: |
| 853 |
CustomGetItem.__name__ = "something_somewhere" |
| 854 |
|
| 855 |
namespace = {'c': CustomGetItem()} |
| 856 |
if not class_is_findable and not allow_unsafe_getattr: |
| 857 |
expected = [] |
| 858 |
else: |
| 859 |
expected = ['upper'] |
| 860 |
_assert_interpreter_complete('c["a"].up', namespace, expected) |
| 861 |
|
| 862 |
|
| 863 |
def test_star_import_completions(): |
| 864 |
|
| 865 |
completions = jedi.Interpreter("from json import *\ndum", []).complete(2, 3) |
| 866 |
names = [c.name for c in completions] |
| 867 |
|
| 868 |
assert 'dump' in names |
| 869 |
assert 'dumps' in names |
| 870 |
|
| 871 |
|
| 872 |
def test_whitespace_after_dot_completion(Script): |
| 873 |
|
| 874 |
completions = jedi.Interpreter("object. \n", []).complete(1, 8) |
| 875 |
assert "mro" in [c.name for c in completions] |