1
0
forked from VimPlug/jedi

Don't use goto_definitions anymore, use infer

This commit is contained in:
Dave Halter
2019-12-20 19:02:18 +01:00
parent 4bbaec68e8
commit d7d9c9642a
30 changed files with 131 additions and 137 deletions

View File

@@ -118,7 +118,7 @@ def has_typing(environment):
return True return True
script = jedi.Script('import typing', environment=environment) script = jedi.Script('import typing', environment=environment)
return bool(script.goto_definitions()) return bool(script.infer())
@pytest.fixture(scope='session') @pytest.fixture(scope='session')

View File

@@ -45,7 +45,7 @@ def run(code, index, infer=False):
start = time.time() start = time.time()
script = jedi.Script(code) script = jedi.Script(code)
if infer: if infer:
result = script.goto_definitions() result = script.infer()
else: else:
result = script.complete() result = script.complete()
print('Used %ss for the %sth run.' % (time.time() - start, index + 1)) print('Used %ss for the %sth run.' % (time.time() - start, index + 1))

View File

@@ -130,12 +130,12 @@ def test_goto_assignments_on_non_name(Script, environment):
assert Script('True').goto_assignments() == [] assert Script('True').goto_assignments() == []
def test_goto_definitions_on_non_name(Script): def test_infer_on_non_name(Script):
assert Script('import x', column=0).goto_definitions() == [] assert Script('import x').infer(column=0) == []
def test_goto_definitions_on_generator(Script): def test_infer_on_generator(Script):
def_, = Script('def x(): yield 1\ny=x()\ny').goto_definitions() def_, = Script('def x(): yield 1\ny=x()\ny').infer()
assert def_.name == 'Generator' assert def_.name == 'Generator'
@@ -159,7 +159,7 @@ def test_goto_definition_not_multiple(Script):
else: else:
a = A(1) a = A(1)
a''') a''')
assert len(Script(s).goto_definitions()) == 1 assert len(Script(s).infer()) == 1
def test_usage_description(Script): def test_usage_description(Script):
@@ -264,7 +264,7 @@ def test_goto_definition_cursor(Script):
should2 = 8, 10 should2 = 8, 10
def get_def(pos): def get_def(pos):
return [d.description for d in Script(s, *pos).goto_definitions()] return [d.description for d in Script(s).infer(*pos)]
in_name = get_def(in_name) in_name = get_def(in_name)
under_score = get_def(under_score) under_score = get_def(under_score)
@@ -290,7 +290,7 @@ def test_no_statement_parent(Script):
pass pass
variable = f if random.choice([0, 1]) else C""") variable = f if random.choice([0, 1]) else C""")
defs = Script(source, column=3).goto_definitions() defs = Script(source).infer(column=3)
defs = sorted(defs, key=lambda d: d.line) defs = sorted(defs, key=lambda d: d.line)
assert [d.description for d in defs] == ['def f', 'class C'] assert [d.description for d in defs] == ['def f', 'class C']
@@ -303,7 +303,7 @@ def test_backslash_continuation_and_bracket(Script):
lines = code.splitlines() lines = code.splitlines()
column = lines[-1].index('(') column = lines[-1].index('(')
def_, = Script(code, line=len(lines), column=column).goto_definitions() def_, = Script(code).infer(line=len(lines), column=column)
assert def_.name == 'int' assert def_.name == 'int'
@@ -355,6 +355,6 @@ def test_file_fuzzy_completion(Script):
] ]
) )
def test_goto_on_string(Script, code, column): def test_goto_on_string(Script, code, column):
script = Script(code, column=column) script = Script(code)
assert not script.goto_definitions() assert not script.infer(column=column)
assert not script.goto_assignments() assert not script.goto(column=column)

View File

@@ -309,7 +309,7 @@ def test_signature_is_definition(Script):
""" """
s = """class Spam(): pass\nSpam""" s = """class Spam(): pass\nSpam"""
signature = Script(s + '(').call_signatures()[0] signature = Script(s + '(').call_signatures()[0]
definition = Script(s + '(', column=0).goto_definitions()[0] definition = Script(s + '(').infer(column=0)[0]
signature.line == 1 signature.line == 1
signature.column == 6 signature.column == 6

View File

@@ -14,7 +14,7 @@ from ..helpers import get_example_dir
def test_is_keyword(Script): def test_is_keyword(Script):
results = Script('str', 1, 1, None).goto_definitions() results = Script('str', path=None).infer(1, 1)
assert len(results) == 1 and results[0].is_keyword is False assert len(results) == 1 and results[0].is_keyword is False
@@ -48,8 +48,8 @@ def test_basedefinition_type(Script, names):
source += dedent(""" source += dedent("""
variable = sys or C or x or f or g or g() or h""") variable = sys or C or x or f or g or g() or h""")
lines = source.splitlines() lines = source.splitlines()
script = Script(source, len(lines), len('variable'), None) script = Script(source, path=None)
definitions += script.goto_definitions() definitions += script.infer(len(lines), len('variable'))
script2 = Script(source, 4, len('class C'), None) script2 = Script(source, 4, len('class C'), None)
definitions += script2.usages() definitions += script2.usages()
@@ -96,7 +96,7 @@ def test_function_call_signature_in_doc(Script):
defs = Script(""" defs = Script("""
def f(x, y=1, z='a'): def f(x, y=1, z='a'):
pass pass
f""").goto_definitions() f""").infer()
doc = defs[0].docstring() doc = defs[0].docstring()
assert "f(x, y=1, z='a')" in str(doc) assert "f(x, y=1, z='a')" in str(doc)
@@ -112,7 +112,7 @@ def test_class_call_signature(Script):
class Foo: class Foo:
def __init__(self, x, y=1, z='a'): def __init__(self, x, y=1, z='a'):
pass pass
Foo""").goto_definitions() Foo""").infer()
doc = defs[0].docstring() doc = defs[0].docstring()
assert doc == "Foo(x, y=1, z='a')" assert doc == "Foo(x, y=1, z='a')"
@@ -204,7 +204,7 @@ def test_signature_params(Script):
pass pass
foo''') foo''')
check(Script(s).goto_definitions()) check(Script(s).infer())
check(Script(s).goto_assignments()) check(Script(s).goto_assignments())
check(Script(s + '\nbar=foo\nbar').goto_assignments()) check(Script(s + '\nbar=foo\nbar').goto_assignments())
@@ -451,7 +451,7 @@ def test_builtin_module_with_path(Script):
a path or not. It shouldn't have a module_path, because that is just a path or not. It shouldn't have a module_path, because that is just
confusing. confusing.
""" """
semlock, = Script('from _multiprocessing import SemLock').goto_definitions() semlock, = Script('from _multiprocessing import SemLock').infer()
assert isinstance(semlock._name, CompiledValueName) assert isinstance(semlock._name, CompiledValueName)
assert semlock.module_path is None assert semlock.module_path is None
assert semlock.in_builtin_module() is True assert semlock.in_builtin_module() is True
@@ -491,7 +491,7 @@ def test_inheritance_module_path(Script, goto_assignment, code, name, file_name)
script = Script(code, path=whatever_path) script = Script(code, path=whatever_path)
if goto_assignment is None: if goto_assignment is None:
func, = script.goto_definitions() func, = script.infer()
else: else:
func, = script.goto_assignments(follow_imports=goto_assignment) func, = script.goto_assignments(follow_imports=goto_assignment)
assert func.type == 'function' assert func.type == 'function'

View File

@@ -66,13 +66,13 @@ def test_error_in_environment(inference_state, Script, environment):
with pytest.raises(jedi.InternalError): with pytest.raises(jedi.InternalError):
inference_state.compiled_subprocess._test_raise_error(KeyboardInterrupt) inference_state.compiled_subprocess._test_raise_error(KeyboardInterrupt)
# Jedi should still work. # Jedi should still work.
def_, = Script('str').goto_definitions() def_, = Script('str').infer()
assert def_.name == 'str' assert def_.name == 'str'
def test_stdout_in_subprocess(inference_state, Script): def test_stdout_in_subprocess(inference_state, Script):
inference_state.compiled_subprocess._test_print(stdout='.') inference_state.compiled_subprocess._test_print(stdout='.')
Script('1').goto_definitions() Script('1').infer()
def test_killed_subprocess(inference_state, Script, environment): def test_killed_subprocess(inference_state, Script, environment):
@@ -83,9 +83,9 @@ def test_killed_subprocess(inference_state, Script, environment):
# Since the process was terminated (and nobody knows about it) the first # Since the process was terminated (and nobody knows about it) the first
# Jedi call fails. # Jedi call fails.
with pytest.raises(jedi.InternalError): with pytest.raises(jedi.InternalError):
Script('str').goto_definitions() Script('str').infer()
def_, = Script('str').goto_definitions() def_, = Script('str').infer()
# Jedi should now work again. # Jedi should now work again.
assert def_.name == 'str' assert def_.name == 'str'

View File

@@ -43,7 +43,7 @@ class MixinTestFullName(object):
class TestFullNameWithGotoDefinitions(MixinTestFullName, TestCase): class TestFullNameWithGotoDefinitions(MixinTestFullName, TestCase):
operation = 'goto_definitions' operation = 'infer'
def test_tuple_mapping(self): def test_tuple_mapping(self):
if self.environment.version_info.major == 2: if self.environment.version_info.major == 2:
@@ -97,9 +97,9 @@ def test_sub_module(Script, jedi_path):
path. path.
""" """
sys_path = [jedi_path] sys_path = [jedi_path]
defs = Script('from jedi.api import classes; classes', sys_path=sys_path).goto_definitions() defs = Script('from jedi.api import classes; classes', sys_path=sys_path).infer()
assert [d.full_name for d in defs] == ['jedi.api.classes'] assert [d.full_name for d in defs] == ['jedi.api.classes']
defs = Script('import jedi.api; jedi.api', sys_path=sys_path).goto_definitions() defs = Script('import jedi.api; jedi.api', sys_path=sys_path).infer()
assert [d.full_name for d in defs] == ['jedi.api'] assert [d.full_name for d in defs] == ['jedi.api']

View File

@@ -298,7 +298,7 @@ def test_property_content():
return 1 return 1
foo = Foo3() foo = Foo3()
def_, = jedi.Interpreter('foo.bar', [locals()]).goto_definitions() def_, = jedi.Interpreter('foo.bar', [locals()]).infer()
assert def_.name == 'int' assert def_.name == 'int'
@@ -345,7 +345,7 @@ def test_completion_param_annotations():
assert [d.name for d in b.infer()] == ['str'] assert [d.name for d in b.infer()] == ['str']
assert {d.name for d in c.infer()} == {'int', 'float'} assert {d.name for d in c.infer()} == {'int', 'float'}
d, = jedi.Interpreter('foo()', [locals()]).goto_definitions() d, = jedi.Interpreter('foo()', [locals()]).infer()
assert d.name == 'bytes' assert d.name == 'bytes'
@@ -397,7 +397,7 @@ def test_repr_execution_issue():
er = ErrorRepr() er = ErrorRepr()
script = jedi.Interpreter('er', [locals()]) script = jedi.Interpreter('er', [locals()])
d, = script.goto_definitions() d, = script.infer()
assert d.name == 'ErrorRepr' assert d.name == 'ErrorRepr'
assert d.type == 'instance' assert d.type == 'instance'
@@ -452,7 +452,7 @@ def test_name_not_findable():
def test_stubs_working(): def test_stubs_working():
from multiprocessing import cpu_count from multiprocessing import cpu_count
defs = jedi.Interpreter("cpu_count()", [locals()]).goto_definitions() defs = jedi.Interpreter("cpu_count()", [locals()]).infer()
assert [d.name for d in defs] == ['int'] assert [d.name for d in defs] == ['int']
@@ -559,7 +559,7 @@ def test_type_var():
"""This was an issue before, see Github #1369""" """This was an issue before, see Github #1369"""
import typing import typing
x = typing.TypeVar('myvar') x = typing.TypeVar('myvar')
def_, = jedi.Interpreter('x', [locals()]).goto_definitions() def_, = jedi.Interpreter('x', [locals()]).infer()
assert def_.name == 'TypeVar' assert def_.name == 'TypeVar'

View File

@@ -16,7 +16,7 @@ def test_goto_assignments_keyword(Script):
def test_keyword(Script, environment): def test_keyword(Script, environment):
""" github jedi-vim issue #44 """ """ github jedi-vim issue #44 """
defs = Script("print").goto_definitions() defs = Script("print").infer()
if environment.version_info.major < 3: if environment.version_info.major < 3:
assert defs == [] assert defs == []
else: else:
@@ -26,7 +26,7 @@ def test_keyword(Script, environment):
completions = Script("import").complete(1, 1) completions = Script("import").complete(1, 1)
assert len(completions) > 10 and 'if' in [c.name for c in completions] assert len(completions) > 10 and 'if' in [c.name for c in completions]
assert Script("assert").goto_definitions() == [] assert Script("assert").infer() == []
def test_keyword_attributes(Script): def test_keyword_attributes(Script):

View File

@@ -18,7 +18,7 @@ def test_add_dynamic_mods(Script):
src2 = 'from .. import setup; setup.r(1)' src2 = 'from .. import setup; setup.r(1)'
script = Script(src1, path='../setup.py') script = Script(src1, path='../setup.py')
imports.load_module(script._inference_state, os.path.abspath(fname), src2) imports.load_module(script._inference_state, os.path.abspath(fname), src2)
result = script.goto_definitions() result = script.infer()
assert len(result) == 1 assert len(result) == 1
assert result[0].description == 'class int' assert result[0].description == 'class int'

View File

@@ -49,11 +49,11 @@ def test_multibyte_script(Script):
def test_goto_definition_at_zero(Script): def test_goto_definition_at_zero(Script):
"""At zero usually sometimes raises unicode issues.""" """At zero usually sometimes raises unicode issues."""
assert Script("a", 1, 1).goto_definitions() == [] assert Script("a").infer(1, 1) == []
s = Script("str", 1, 1).goto_definitions() s = Script("str").infer(1, 1)
assert len(s) == 1 assert len(s) == 1
assert list(s)[0].description == 'class str' assert list(s)[0].description == 'class str'
assert Script("", 1, 0).goto_definitions() == [] assert Script("").infer(1, 0) == []
def test_complete_at_zero(Script): def test_complete_at_zero(Script):

View File

@@ -18,7 +18,7 @@ def test_simple_annotations(Script, environment):
annot('')""") annot('')""")
assert [d.name for d in Script(source).goto_definitions()] == ['str'] assert [d.name for d in Script(source).infer()] == ['str']
source = dedent("""\ source = dedent("""\
@@ -26,7 +26,7 @@ def test_simple_annotations(Script, environment):
return a return a
annot_ret('')""") annot_ret('')""")
assert [d.name for d in Script(source).goto_definitions()] == ['str'] assert [d.name for d in Script(source).infer()] == ['str']
source = dedent("""\ source = dedent("""\
def annot(a:int): def annot(a:int):
@@ -34,7 +34,7 @@ def test_simple_annotations(Script, environment):
annot('')""") annot('')""")
assert [d.name for d in Script(source).goto_definitions()] == ['int'] assert [d.name for d in Script(source).infer()] == ['int']
@pytest.mark.parametrize('reference', [ @pytest.mark.parametrize('reference', [
@@ -50,7 +50,7 @@ def test_illegal_forward_references(Script, environment, reference):
source = 'def foo(bar: "%s"): bar' % reference source = 'def foo(bar: "%s"): bar' % reference
assert not Script(source).goto_definitions() assert not Script(source).infer()
def test_lambda_forward_references(Script, environment): def test_lambda_forward_references(Script, environment):
@@ -61,4 +61,4 @@ def test_lambda_forward_references(Script, environment):
# For now just receiving the 3 is ok. I'm doubting that this is what we # For now just receiving the 3 is ok. I'm doubting that this is what we
# want. We also execute functions. Should we only execute classes? # want. We also execute functions. Should we only execute classes?
assert Script(source).goto_definitions() assert Script(source).infer()

View File

@@ -61,7 +61,7 @@ def test_doc(inference_state):
def test_string_literals(Script, environment): def test_string_literals(Script, environment):
def typ(string): def typ(string):
d = Script("a = %s; a" % string).goto_definitions()[0] d = Script("a = %s; a" % string).infer()[0]
return d.name return d.name
assert typ('""') == 'str' assert typ('""') == 'str'
@@ -98,12 +98,12 @@ def test_dict_values(Script, environment):
if environment.version_info.major == 2: if environment.version_info.major == 2:
# It looks like typeshed for Python 2 returns Any. # It looks like typeshed for Python 2 returns Any.
pytest.skip() pytest.skip()
assert Script('import sys\nsys.modules["alshdb;lasdhf"]').goto_definitions() assert Script('import sys\nsys.modules["alshdb;lasdhf"]').infer()
def test_getitem_on_none(Script): def test_getitem_on_none(Script):
script = Script('None[1j]') script = Script('None[1j]')
assert not script.goto_definitions() assert not script.infer()
issue, = script._inference_state.analysis issue, = script._inference_state.analysis
assert issue.name == 'type-error-not-subscriptable' assert issue.name == 'type-error-not-subscriptable'

View File

@@ -11,11 +11,11 @@ def test_module_attributes(Script):
def test_module__file__(Script, environment): def test_module__file__(Script, environment):
assert not Script('__file__').goto_definitions() assert not Script('__file__').infer()
def_, = Script('__file__', path='example.py').goto_definitions() def_, = Script('__file__', path='example.py').infer()
value = force_unicode(def_._name._value.get_safe_value()) value = force_unicode(def_._name._value.get_safe_value())
assert value.endswith('example.py') assert value.endswith('example.py')
def_, = Script('import antigravity; antigravity.__file__').goto_definitions() def_, = Script('import antigravity; antigravity.__file__').infer()
value = force_unicode(def_._name._value.get_safe_value()) value = force_unicode(def_._name._value.get_safe_value())
assert value.endswith('.py') assert value.endswith('.py')

View File

@@ -32,7 +32,7 @@ def test_function_doc(Script):
defs = Script(""" defs = Script("""
def func(): def func():
'''Docstring of `func`.''' '''Docstring of `func`.'''
func""").goto_definitions() func""").infer()
assert defs[0].docstring() == 'func()\n\nDocstring of `func`.' assert defs[0].docstring() == 'func()\n\nDocstring of `func`.'
@@ -40,7 +40,7 @@ def test_class_doc(Script):
defs = Script(""" defs = Script("""
class TestClass(): class TestClass():
'''Docstring of `TestClass`.''' '''Docstring of `TestClass`.'''
TestClass""").goto_definitions() TestClass""").infer()
expected = 'Docstring of `TestClass`.' expected = 'Docstring of `TestClass`.'
assert defs[0].docstring(raw=True) == expected assert defs[0].docstring(raw=True) == expected
@@ -52,7 +52,7 @@ def test_class_doc_with_init(Script):
class TestClass(): class TestClass():
'''Docstring''' '''Docstring'''
def __init__(self, foo, bar=3): pass def __init__(self, foo, bar=3): pass
TestClass""").goto_definitions() TestClass""").infer()
assert d.docstring() == 'TestClass(foo, bar=3)\n\nDocstring' assert d.docstring() == 'TestClass(foo, bar=3)\n\nDocstring'
@@ -62,7 +62,7 @@ def test_instance_doc(Script):
class TestClass(): class TestClass():
'''Docstring of `TestClass`.''' '''Docstring of `TestClass`.'''
tc = TestClass() tc = TestClass()
tc""").goto_definitions() tc""").infer()
assert defs[0].docstring() == 'Docstring of `TestClass`.' assert defs[0].docstring() == 'Docstring of `TestClass`.'
@@ -71,7 +71,7 @@ def test_attribute_docstring(Script):
defs = Script(""" defs = Script("""
x = None x = None
'''Docstring of `x`.''' '''Docstring of `x`.'''
x""").goto_definitions() x""").infer()
assert defs[0].docstring() == 'Docstring of `x`.' assert defs[0].docstring() == 'Docstring of `x`.'
@@ -82,7 +82,7 @@ def test_multiple_docstrings(Script):
'''Original docstring.''' '''Original docstring.'''
x = func x = func
'''Docstring of `x`.''' '''Docstring of `x`.'''
x""").goto_definitions() x""").infer()
docs = [d.docstring() for d in defs] docs = [d.docstring() for d in defs]
assert docs == ['Original docstring.', 'Docstring of `x`.'] assert docs == ['Original docstring.', 'Docstring of `x`.']
@@ -167,7 +167,7 @@ def test_docstring_params_formatting(Script):
param2, param2,
param3): param3):
pass pass
func""").goto_definitions() func""").infer()
assert defs[0].docstring() == 'func(param1, param2, param3)' assert defs[0].docstring() == 'func(param1, param2, param3)'
@@ -412,7 +412,7 @@ def test_decorator(Script):
check_user''') check_user''')
d, = Script(code).goto_definitions() d, = Script(code).infer()
assert d.docstring(raw=True) == 'Nice docstring' assert d.docstring(raw=True) == 'Nice docstring'

View File

@@ -7,18 +7,18 @@ from jedi.inference.gradual.conversion import convert_names
def test_sqlite3_conversion(Script): def test_sqlite3_conversion(Script):
script1 = Script('import sqlite3; sqlite3.Connection') script1 = Script('import sqlite3; sqlite3.Connection')
d, = script1.goto_definitions() d, = script1.infer()
assert not d.module_path assert not d.module_path
assert d.full_name == 'sqlite3.Connection' assert d.full_name == 'sqlite3.Connection'
assert convert_names([d._name], only_stubs=True) assert convert_names([d._name], only_stubs=True)
d, = script1.goto_definitions(only_stubs=True) d, = script1.infer(only_stubs=True)
assert d.is_stub() assert d.is_stub()
assert d.full_name == 'sqlite3.dbapi2.Connection' assert d.full_name == 'sqlite3.dbapi2.Connection'
script2 = Script(path=d.module_path, line=d.line, column=d.column) script2 = Script(path=d.module_path)
d, = script2.goto_definitions() d, = script2.infer(line=d.line, column=d.column)
assert not d.is_stub() assert not d.is_stub()
assert d.full_name == 'sqlite3.Connection' assert d.full_name == 'sqlite3.Connection'
v, = d._name.infer() v, = d._name.infer()

View File

@@ -23,5 +23,5 @@ def ScriptInStubFolder(Script):
] ]
) )
def test_find_stubs_infer(ScriptInStubFolder, code, expected): def test_find_stubs_infer(ScriptInStubFolder, code, expected):
defs = ScriptInStubFolder(code).goto_definitions() defs = ScriptInStubFolder(code).infer()
assert [d.name for d in defs] == expected assert [d.name for d in defs] == expected

View File

@@ -66,7 +66,7 @@ def test_infer_and_goto(Script, code, full_name, has_stub, has_python, way,
if type_ == 'goto': if type_ == 'goto':
defs = s.goto_assignments(follow_imports=True, **kwargs) defs = s.goto_assignments(follow_imports=True, **kwargs)
else: else:
defs = s.goto_definitions(**kwargs) defs = s.infer(**kwargs)
else: else:
goto_defs = s.goto_assignments( goto_defs = s.goto_assignments(
# Prefering stubs when we want to go to python and vice versa # Prefering stubs when we want to go to python and vice versa

View File

@@ -46,21 +46,21 @@ def test_get_stub_files():
def test_function(Script, environment): def test_function(Script, environment):
code = 'import threading; threading.current_thread' code = 'import threading; threading.current_thread'
def_, = Script(code).goto_definitions() def_, = Script(code).infer()
value = def_._name._value value = def_._name._value
assert isinstance(value, FunctionValue), value assert isinstance(value, FunctionValue), value
def_, = Script(code + '()').goto_definitions() def_, = Script(code + '()').infer()
value = def_._name._value value = def_._name._value
assert isinstance(value, TreeInstance) assert isinstance(value, TreeInstance)
def_, = Script('import threading; threading.Thread').goto_definitions() def_, = Script('import threading; threading.Thread').infer()
assert isinstance(def_._name._value, ClassValue), def_ assert isinstance(def_._name._value, ClassValue), def_
def test_keywords_variable(Script): def test_keywords_variable(Script):
code = 'import keyword; keyword.kwlist' code = 'import keyword; keyword.kwlist'
for seq in Script(code).goto_definitions(): for seq in Script(code).infer():
assert seq.name == 'Sequence' assert seq.name == 'Sequence'
# This points towards the typeshed implementation # This points towards the typeshed implementation
stub_seq, = seq.goto(only_stubs=True) stub_seq, = seq.goto(only_stubs=True)
@@ -68,31 +68,31 @@ def test_keywords_variable(Script):
def test_class(Script): def test_class(Script):
def_, = Script('import threading; threading.Thread').goto_definitions() def_, = Script('import threading; threading.Thread').infer()
value = def_._name._value value = def_._name._value
assert isinstance(value, ClassValue), value assert isinstance(value, ClassValue), value
def test_instance(Script): def test_instance(Script):
def_, = Script('import threading; threading.Thread()').goto_definitions() def_, = Script('import threading; threading.Thread()').infer()
value = def_._name._value value = def_._name._value
assert isinstance(value, TreeInstance) assert isinstance(value, TreeInstance)
def test_class_function(Script): def test_class_function(Script):
def_, = Script('import threading; threading.Thread.getName').goto_definitions() def_, = Script('import threading; threading.Thread.getName').infer()
value = def_._name._value value = def_._name._value
assert isinstance(value, MethodValue), value assert isinstance(value, MethodValue), value
def test_method(Script): def test_method(Script):
code = 'import threading; threading.Thread().getName' code = 'import threading; threading.Thread().getName'
def_, = Script(code).goto_definitions() def_, = Script(code).infer()
value = def_._name._value value = def_._name._value
assert isinstance(value, BoundMethod), value assert isinstance(value, BoundMethod), value
assert isinstance(value._wrapped_value, MethodValue), value assert isinstance(value._wrapped_value, MethodValue), value
def_, = Script(code + '()').goto_definitions() def_, = Script(code + '()').infer()
value = def_._name._value value = def_._name._value
assert isinstance(value, TreeInstance) assert isinstance(value, TreeInstance)
assert value.class_value.py__name__() == 'str' assert value.class_value.py__name__() == 'str'
@@ -100,13 +100,13 @@ def test_method(Script):
def test_sys_exc_info(Script): def test_sys_exc_info(Script):
code = 'import sys; sys.exc_info()' code = 'import sys; sys.exc_info()'
none, def_ = Script(code + '[1]').goto_definitions() none, def_ = Script(code + '[1]').infer()
# It's an optional. # It's an optional.
assert def_.name == 'BaseException' assert def_.name == 'BaseException'
assert def_.type == 'instance' assert def_.type == 'instance'
assert none.name == 'NoneType' assert none.name == 'NoneType'
none, def_ = Script(code + '[0]').goto_definitions() none, def_ = Script(code + '[0]').infer()
assert def_.name == 'BaseException' assert def_.name == 'BaseException'
assert def_.type == 'class' assert def_.type == 'class'
@@ -114,7 +114,7 @@ def test_sys_exc_info(Script):
def test_sys_getwindowsversion(Script, environment): def test_sys_getwindowsversion(Script, environment):
# This should only exist on Windows, but type inference should happen # This should only exist on Windows, but type inference should happen
# everywhere. # everywhere.
definitions = Script('import sys; sys.getwindowsversion().major').goto_definitions() definitions = Script('import sys; sys.getwindowsversion().major').infer()
if environment.version_info.major == 2: if environment.version_info.major == 2:
assert not definitions assert not definitions
else: else:
@@ -127,19 +127,19 @@ def test_sys_hexversion(Script):
def_, = script.complete() def_, = script.complete()
assert isinstance(def_._name, stub_value._StubName), def_._name assert isinstance(def_._name, stub_value._StubName), def_._name
assert typeshed.TYPESHED_PATH in def_.module_path assert typeshed.TYPESHED_PATH in def_.module_path
def_, = script.goto_definitions() def_, = script.infer()
assert def_.name == 'int' assert def_.name == 'int'
def test_math(Script): def test_math(Script):
def_, = Script('import math; math.acos()').goto_definitions() def_, = Script('import math; math.acos()').infer()
assert def_.name == 'float' assert def_.name == 'float'
value = def_._name._value value = def_._name._value
assert value assert value
def test_type_var(Script): def test_type_var(Script):
def_, = Script('import typing; T = typing.TypeVar("T1")').goto_definitions() def_, = Script('import typing; T = typing.TypeVar("T1")').infer()
assert def_.name == 'TypeVar' assert def_.name == 'TypeVar'
assert def_.description == 'TypeVar = object()' assert def_.description == 'TypeVar = object()'
@@ -152,7 +152,7 @@ def test_type_var(Script):
) )
def test_math_is_stub(Script, code, full_name): def test_math_is_stub(Script, code, full_name):
s = Script(code) s = Script(code)
cos, = s.goto_definitions() cos, = s.infer()
wanted = os.path.join('typeshed', 'stdlib', '2and3', 'math.pyi') wanted = os.path.join('typeshed', 'stdlib', '2and3', 'math.pyi')
assert cos.module_path.endswith(wanted) assert cos.module_path.endswith(wanted)
assert cos.is_stub() is True assert cos.is_stub() is True
@@ -168,7 +168,7 @@ def test_math_is_stub(Script, code, full_name):
def test_goto_stubs(Script): def test_goto_stubs(Script):
s = Script('import os; os') s = Script('import os; os')
os_module, = s.goto_definitions() os_module, = s.infer()
assert os_module.full_name == 'os' assert os_module.full_name == 'os'
assert os_module.is_stub() is False assert os_module.is_stub() is False
stub, = os_module.goto(only_stubs=True) stub, = os_module.goto(only_stubs=True)
@@ -199,20 +199,16 @@ def test_goto_stubs_on_itself(Script, code, type_):
""" """
s = Script(code) s = Script(code)
if type_ == 'infer': if type_ == 'infer':
def_, = s.goto_definitions() def_, = s.infer()
else: else:
def_, = s.goto_assignments(follow_imports=True) def_, = s.goto_assignments(follow_imports=True)
stub, = def_.goto(only_stubs=True) stub, = def_.goto(only_stubs=True)
script_on_source = Script( script_on_source = Script(path=def_.module_path)
path=def_.module_path,
line=def_.line,
column=def_.column
)
if type_ == 'infer': if type_ == 'infer':
definition, = script_on_source.goto_definitions() definition, = script_on_source.infer(def_.line, def_.column)
else: else:
definition, = script_on_source.goto_assignments() definition, = script_on_source.goto(def_.line, def_.column)
same_stub, = definition.goto(only_stubs=True) same_stub, = definition.goto(only_stubs=True)
_assert_is_same(same_stub, stub) _assert_is_same(same_stub, stub)
_assert_is_same(definition, def_) _assert_is_same(definition, def_)
@@ -221,15 +217,13 @@ def test_goto_stubs_on_itself(Script, code, type_):
# And the reverse. # And the reverse.
script_on_stub = Script( script_on_stub = Script(
path=same_stub.module_path, path=same_stub.module_path,
line=same_stub.line,
column=same_stub.column
) )
if type_ == 'infer': if type_ == 'infer':
same_definition, = script_on_stub.goto_definitions() same_definition, = script_on_stub.infer(same_stub.line, same_stub.column)
same_definition2, = same_stub.infer() same_definition2, = same_stub.infer()
else: else:
same_definition, = script_on_stub.goto_assignments() same_definition, = script_on_stub.goto(same_stub.line, same_stub.column)
same_definition2, = same_stub.goto() same_definition2, = same_stub.goto()
_assert_is_same(same_definition, definition) _assert_is_same(same_definition, definition)

View File

@@ -17,9 +17,9 @@ def test_implicit_namespace_package(Script):
return Script(sys_path=sys_path, *args, **kwargs) return Script(sys_path=sys_path, *args, **kwargs)
# goto definition # goto definition
assert script_with_path('from pkg import ns1_file').goto_definitions() assert script_with_path('from pkg import ns1_file').infer()
assert script_with_path('from pkg import ns2_file').goto_definitions() assert script_with_path('from pkg import ns2_file').infer()
assert not script_with_path('from pkg import ns3_file').goto_definitions() assert not script_with_path('from pkg import ns3_file').infer()
# goto assignment # goto assignment
tests = { tests = {
@@ -57,11 +57,11 @@ def test_implicit_nested_namespace_package(Script):
script = Script(sys_path=sys_path, source=code, line=1, column=61) script = Script(sys_path=sys_path, source=code, line=1, column=61)
result = script.goto_definitions() result = script.infer()
assert len(result) == 1 assert len(result) == 1
implicit_pkg, = Script(code, column=10, sys_path=sys_path).goto_definitions() implicit_pkg, = Script(code, sys_path=sys_path).infer(column=10)
assert implicit_pkg.type == 'module' assert implicit_pkg.type == 'module'
assert implicit_pkg.module_path is None assert implicit_pkg.module_path is None
@@ -91,7 +91,7 @@ def test_namespace_package_in_multiple_directories_goto_definition(Script):
sys_path = [join(dirname(__file__), d) sys_path = [join(dirname(__file__), d)
for d in ['implicit_namespace_package/ns1', 'implicit_namespace_package/ns2']] for d in ['implicit_namespace_package/ns1', 'implicit_namespace_package/ns2']]
script = Script(sys_path=sys_path, source=CODE) script = Script(sys_path=sys_path, source=CODE)
result = script.goto_definitions() result = script.infer()
assert len(result) == 1 assert len(result) == 1

View File

@@ -87,7 +87,7 @@ def test_find_module_package_zipped(Script, inference_state, environment):
def test_correct_zip_package_behavior(Script, inference_state, environment, code, def test_correct_zip_package_behavior(Script, inference_state, environment, code,
file, package, path, skip_python2): file, package, path, skip_python2):
sys_path = environment.get_sys_path() + [pkg_zip_path] sys_path = environment.get_sys_path() + [pkg_zip_path]
pkg, = Script(code, sys_path=sys_path).goto_definitions() pkg, = Script(code, sys_path=sys_path).infer()
value, = pkg._name.infer() value, = pkg._name.infer()
assert value.py__file__() == os.path.join(pkg_zip_path, 'pkg', file) assert value.py__file__() == os.path.join(pkg_zip_path, 'pkg', file)
assert '.'.join(value.py__package__()) == package assert '.'.join(value.py__package__()) == package
@@ -118,12 +118,12 @@ def test_import_not_in_sys_path(Script):
This is in the end just a fallback. This is in the end just a fallback.
""" """
a = Script(path='module.py', line=5).goto_definitions() a = Script(path='module.py').infer(line=5)
assert a[0].name == 'int' assert a[0].name == 'int'
a = Script(path='module.py', line=6).goto_definitions() a = Script(path='module.py').infer(line=6)
assert a[0].name == 'str' assert a[0].name == 'str'
a = Script(path='module.py', line=7).goto_definitions() a = Script(path='module.py').infer(line=7)
assert a[0].name == 'str' assert a[0].name == 'str'
@@ -157,7 +157,7 @@ def test_not_importable_file(Script):
def test_import_unique(Script): def test_import_unique(Script):
src = "import os; os.path" src = "import os; os.path"
defs = Script(src, path='example.py').goto_definitions() defs = Script(src, path='example.py').infer()
parent_contexts = [d._name._value for d in defs] parent_contexts = [d._name._value for d in defs]
assert len(parent_contexts) == len(set(parent_contexts)) assert len(parent_contexts) == len(set(parent_contexts))
@@ -191,8 +191,8 @@ def test_import_completion_docstring(Script):
def test_goto_definition_on_import(Script): def test_goto_definition_on_import(Script):
assert Script("import sys_blabla", 1, 8).goto_definitions() == [] assert Script("import sys_blabla").infer(1, 8) == []
assert len(Script("import sys", 1, 8).goto_definitions()) == 1 assert len(Script("import sys").infer(1, 8)) == 1
@cwd_at('jedi') @cwd_at('jedi')
@@ -237,8 +237,8 @@ def test_imports_on_global_namespace_without_path(Script):
def test_named_import(Script): def test_named_import(Script):
"""named import - jedi-vim issue #8""" """named import - jedi-vim issue #8"""
s = "import time as dt" s = "import time as dt"
assert len(Script(s, 1, 15, '/').goto_definitions()) == 1 assert len(Script(s, path='/').infer(1, 15)) == 1
assert len(Script(s, 1, 10, '/').goto_definitions()) == 1 assert len(Script(s, path='/').infer(1, 10)) == 1
@pytest.mark.skipif('True', reason='The nested import stuff is still very messy.') @pytest.mark.skipif('True', reason='The nested import stuff is still very messy.')
@@ -300,7 +300,7 @@ def test_compiled_import_none(monkeypatch, Script):
""" """
script = Script('import sys') script = Script('import sys')
monkeypatch.setattr(compiled, 'load_module', lambda *args, **kwargs: None) monkeypatch.setattr(compiled, 'load_module', lambda *args, **kwargs: None)
def_, = script.goto_definitions() def_, = script.infer()
assert def_.type == 'module' assert def_.type == 'module'
value, = def_._name.infer() value, = def_._name.infer()
assert not _stub_to_python_value_set(value) assert not _stub_to_python_value_set(value)
@@ -403,7 +403,7 @@ def test_relative_import_out_of_file_system(Script):
assert import_.name == 'import' assert import_.name == 'import'
script = Script("from " + '.' * 100 + 'abc import ABCMeta') script = Script("from " + '.' * 100 + 'abc import ABCMeta')
assert not script.goto_definitions() assert not script.infer()
assert not script.complete() assert not script.complete()
@@ -456,7 +456,7 @@ def test_import_needed_modules_by_jedi(Script, environment, tmpdir, name):
path=tmpdir.join('something.py').strpath, path=tmpdir.join('something.py').strpath,
sys_path=[tmpdir.strpath] + environment.get_sys_path(), sys_path=[tmpdir.strpath] + environment.get_sys_path(),
) )
module, = script.goto_definitions() module, = script.infer()
assert module._inference_state.builtins_module.py__file__() != module_path assert module._inference_state.builtins_module.py__file__() != module_path
assert module._inference_state.typing_module.py__file__() != module_path assert module._inference_state.typing_module.py__file__() != module_path

View File

@@ -3,7 +3,7 @@ from jedi.inference.value import TreeInstance
def _infer_literal(Script, code, is_fstring=False): def _infer_literal(Script, code, is_fstring=False):
def_, = Script(code).goto_definitions() def_, = Script(code).infer()
if is_fstring: if is_fstring:
assert def_.name == 'str' assert def_.name == 'str'
assert isinstance(def_._name._value, TreeInstance) assert isinstance(def_._name._value, TreeInstance)

View File

@@ -14,7 +14,7 @@ def interpreter(code, namespace, *args, **kwargs):
def test_on_code(): def test_on_code():
from functools import wraps from functools import wraps
i = interpreter("wraps.__code__", {'wraps': wraps}) i = interpreter("wraps.__code__", {'wraps': wraps})
assert i.goto_definitions() assert i.infer()
@pytest.mark.skipif('sys.version_info < (3,5)') @pytest.mark.skipif('sys.version_info < (3,5)')

View File

@@ -15,9 +15,9 @@ def script_with_path(Script, *args, **kwargs):
def test_goto_definition(Script): def test_goto_definition(Script):
assert script_with_path(Script, 'from pkg import ns1_file').goto_definitions() assert script_with_path(Script, 'from pkg import ns1_file').infer()
assert script_with_path(Script, 'from pkg import ns2_file').goto_definitions() assert script_with_path(Script, 'from pkg import ns2_file').infer()
assert not script_with_path(Script, 'from pkg import ns3_file').goto_definitions() assert not script_with_path(Script, 'from pkg import ns3_file').infer()
@pytest.mark.parametrize( @pytest.mark.parametrize(
@@ -31,7 +31,7 @@ def test_goto_definition(Script):
] ]
) )
def test_goto_assignment(Script, source, solution): def test_goto_assignment(Script, source, solution):
ass = script_with_path(Script, source).goto_assignments() ass = script_with_path(Script, source).goto()
assert len(ass) == 1 assert len(ass) == 1
assert ass[0].description == "foo = '%s'" % solution assert ass[0].description == "foo = '%s'" % solution
@@ -70,9 +70,9 @@ def test_nested_namespace_package(Script):
sys_path = [dirname(__file__)] sys_path = [dirname(__file__)]
script = Script(sys_path=sys_path, source=code, line=1, column=45) script = Script(sys_path=sys_path, source=code)
result = script.goto_definitions() result = script.infer(line=1, column=45)
assert len(result) == 1 assert len(result) == 1
@@ -88,9 +88,9 @@ def test_relative_import(Script, environment, tmpdir):
# Need to copy the content in a directory where there's no __init__.py. # Need to copy the content in a directory where there's no __init__.py.
py.path.local(directory).copy(tmpdir) py.path.local(directory).copy(tmpdir)
file_path = join(tmpdir.strpath, "rel1.py") file_path = join(tmpdir.strpath, "rel1.py")
script = Script(path=file_path, line=1) script = Script(path=file_path)
d, = script.goto_definitions() d, = script.infer(line=1)
assert d.name == 'int' assert d.name == 'int'
d, = script.goto_assignments() d, = script.goto(line=1)
assert d.name == 'name' assert d.name == 'name'
assert d.module_name == 'rel2' assert d.module_name == 'rel2'

View File

@@ -2,7 +2,7 @@ from textwrap import dedent
def get_definition_and_inference_state(Script, source): def get_definition_and_inference_state(Script, source):
first, = Script(dedent(source)).goto_definitions() first, = Script(dedent(source)).infer()
return first._name._value, first._inference_state return first._name._value, first._inference_state

View File

@@ -32,7 +32,7 @@ def test_compiled_signature(Script, environment, code, sig, names, op, version):
if not op(environment.version_info, version): if not op(environment.version_info, version):
return # The test right next to it should take over. return # The test right next to it should take over.
d, = Script(code).goto_definitions() d, = Script(code).infer()
value, = d._name.infer() value, = d._name.infer()
compiled, = _stub_to_python_value_set(value) compiled, = _stub_to_python_value_set(value)
signature, = compiled.get_signatures() signature, = compiled.get_signatures()

View File

@@ -42,7 +42,7 @@ def test_namedtuple_content(Script):
""") """)
def d(source): def d(source):
x, = Script(source).goto_definitions() x, = Script(source).infer()
return x.name return x.name
assert d(source + 'unnamed.bar') == 'int' assert d(source + 'unnamed.bar') == 'int'
@@ -65,7 +65,7 @@ def test_nested_namedtuples(Script):
assert 'data' in [c.name for c in s.complete()] assert 'data' in [c.name for c in s.complete()]
def test_namedtuple_goto_definitions(Script): def test_namedtuple_infer(Script):
source = dedent(""" source = dedent("""
from collections import namedtuple from collections import namedtuple
@@ -74,7 +74,7 @@ def test_namedtuple_goto_definitions(Script):
from jedi.api import Script from jedi.api import Script
d1, = Script(source).goto_definitions() d1, = Script(source).infer()
assert d1.get_line_code() == "class Foo(tuple):\n" assert d1.get_line_code() == "class Foo(tuple):\n"
assert d1.module_path is None assert d1.module_path is None
@@ -86,7 +86,7 @@ def test_re_sub(Script, environment):
version differences. version differences.
""" """
def run(code): def run(code):
defs = Script(code).goto_definitions() defs = Script(code).infer()
return {d.name for d in defs} return {d.name for d in defs}
names = run("import re; re.sub('a', 'a', 'f')") names = run("import re; re.sub('a', 'a', 'f')")

View File

@@ -29,7 +29,7 @@ def test_if(Script):
# Two parsers needed, one for pass and one for the function. # Two parsers needed, one for pass and one for the function.
check_p(src) check_p(src)
assert [d.name for d in Script(src, 8, 6).goto_definitions()] == ['int'] assert [d.name for d in Script(src).infer(8, 6)] == ['int']
def test_class_and_if(Script): def test_class_and_if(Script):
@@ -47,7 +47,7 @@ def test_class_and_if(Script):
# COMMENT # COMMENT
a_func()""") a_func()""")
check_p(src) check_p(src)
assert [d.name for d in Script(src).goto_definitions()] == ['int'] assert [d.name for d in Script(src).infer()] == ['int']
def test_add_to_end(Script): def test_add_to_end(Script):
@@ -82,7 +82,7 @@ def test_add_to_end(Script):
def test_tokenizer_with_string_literal_backslash(Script): def test_tokenizer_with_string_literal_backslash(Script):
c = Script("statement = u'foo\\\n'; statement").goto_definitions() c = Script("statement = u'foo\\\n'; statement").infer()
assert c[0]._name._value.get_safe_value() == 'foo' assert c[0]._name._value.get_safe_value() == 'foo'
@@ -90,6 +90,6 @@ def test_ellipsis_without_getitem(Script, environment):
if environment.version_info.major == 2: if environment.version_info.major == 2:
pytest.skip('In 2.7 Ellipsis can only be used like x[...]') pytest.skip('In 2.7 Ellipsis can only be used like x[...]')
def_, = Script('x=...;x').goto_definitions() def_, = Script('x=...;x').infer()
assert def_.name == 'ellipsis' assert def_.name == 'ellipsis'

View File

@@ -12,14 +12,14 @@ def auto_import_json(monkeypatch):
def test_base_auto_import_modules(auto_import_json, Script): def test_base_auto_import_modules(auto_import_json, Script):
loads, = Script('import json; json.loads').goto_definitions() loads, = Script('import json; json.loads').infer()
assert isinstance(loads._name, ValueName) assert isinstance(loads._name, ValueName)
value, = loads._name.infer() value, = loads._name.infer()
assert isinstance(value.parent_context._value, StubModuleValue) assert isinstance(value.parent_context._value, StubModuleValue)
def test_auto_import_modules_imports(auto_import_json, Script): def test_auto_import_modules_imports(auto_import_json, Script):
main, = Script('from json import tool; tool.main').goto_definitions() main, = Script('from json import tool; tool.main').infer()
assert isinstance(main._name, CompiledValueName) assert isinstance(main._name, CompiledValueName)
@@ -47,5 +47,5 @@ def test_cropped_file_size(monkeypatch, names, Script):
# It should just not crash if we are outside of the cropped range. # It should just not crash if we are outside of the cropped range.
script = Script(code + code + 'Foo') script = Script(code + code + 'Foo')
assert not script.goto_definitions() assert not script.infer()
assert 'Foo' in [c.name for c in script.complete()] assert 'Foo' in [c.name for c in script.complete()]

View File

@@ -52,7 +52,7 @@ def test_precedence_slowdown(Script):
""" """
with open('speed/precedence.py') as f: with open('speed/precedence.py') as f:
line = len(f.read().splitlines()) line = len(f.read().splitlines())
assert Script(line=line, path='speed/precedence.py').goto_definitions() assert Script(path='speed/precedence.py').infer(line=line)
@_check_speed(0.1) @_check_speed(0.1)