Пример #1
0
def test_relative_imports_with_multiple_similar_directories(Script, path, empty_sys_path):
    dir = get_example_dir('issue1209')
    if empty_sys_path:
        project = Project(dir, sys_path=(), smart_sys_path=False)
    else:
        project = Project(dir)
    script = Script(
        "from . ",
        path=os.path.join(dir, path),
        _project=project,
    )
    name, import_ = script.completions()
    assert import_.name == 'import'
    assert name.name == 'api_test1'
Пример #2
0
def test_flask_ext(Script, code, name):
    """flask.ext.foo is really imported from flaskext.foo or flask_foo.
    """
    path = get_example_dir('flask-site-packages')
    completions = Script(code, project=Project('.',
                                               sys_path=[path])).complete()
    assert name in [c.name for c in completions]
Пример #3
0
    def __init__(self, source, namespaces, **kwds):
        """
        Parse `source` and mixin interpreted Python objects from `namespaces`.

        :type source: str
        :arg  source: Code to parse.
        :type namespaces: list of dict
        :arg  namespaces: a list of namespace dictionaries such as the one
                          returned by :func:`locals`.

        Other optional arguments are same as the ones for :class:`Script`.
        If `line` and `column` are None, they are assumed be at the end of
        `source`.
        """
        try:
            namespaces = [dict(n) for n in namespaces]
        except Exception:
            raise TypeError("namespaces must be a non-empty list of dicts.")

        environment = kwds.get('environment', None)
        if environment is None:
            environment = InterpreterEnvironment()
        else:
            if not isinstance(environment, InterpreterEnvironment):
                raise TypeError(
                    "The environment needs to be an InterpreterEnvironment subclass."
                )

        super(Interpreter, self).__init__(source,
                                          environment=environment,
                                          _project=Project(os.getcwd()),
                                          **kwds)
        self.namespaces = namespaces
        self._inference_state.allow_descriptor_getattr = self._allow_descriptor_getattr_default
Пример #4
0
def getJediProject(force=False):
    """Provides a jedi project"""
    global jediProject

    if force or jediProject is None:
        project = GlobalData().project
        if project.isLoaded():
            jPath = project.getProjectDir()

            addedPaths = []
            for path in project.getImportDirsAsAbsolutePaths():
                if path not in addedPaths:
                    addedPaths.append(path)
            projectDir = project.getProjectDir()
            if projectDir not in addedPaths:
                addedPaths.append(projectDir)

        else:
            jPath = os.path.realpath(QDir.homePath())
            addedPaths = ()

        jediProject = Project(jPath,
                              sys_path=GlobalData().originalSysPath[:],
                              added_sys_path=addedPaths)

    return jediProject
Пример #5
0
    def __init__(self, code, namespaces, *, project=None, **kwds):
        try:
            namespaces = [dict(n) for n in namespaces]
        except Exception:
            raise TypeError("namespaces must be a non-empty list of dicts.")

        environment = kwds.get('environment', None)
        if environment is None:
            environment = InterpreterEnvironment()
        else:
            if not isinstance(environment, InterpreterEnvironment):
                raise TypeError(
                    "The environment needs to be an InterpreterEnvironment subclass."
                )

        if project is None:
            project = Project(Path.cwd())

        super().__init__(code,
                         environment=environment,
                         project=project,
                         **kwds)

        self.namespaces = namespaces
        self._inference_state.allow_descriptor_getattr = self._allow_descriptor_getattr_default
Пример #6
0
def test_infer_and_goto(Script, code, full_name, has_stub, has_python, way,
                        kwargs, type_, options, environment):
    if environment.version_info < (3, 5):
        # We just don't care about much of the detailed Python 2 failures
        # anymore, because its end-of-life soon. (same for 3.4)
        pytest.skip()

    if type_ == 'infer' and full_name == 'typing.Sequence' and environment.version_info >= (
            3, 7):
        # In Python 3.7+ there's not really a sequence definition, there's just
        # a name that leads nowhere.
        has_python = False

    project = Project(
        os.path.join(root_dir, 'test', 'completion', 'stub_folder'))
    s = Script(code, _project=project)
    prefer_stubs = kwargs['prefer_stubs']
    only_stubs = kwargs['only_stubs']

    if type_ == 'goto':
        full_name = options.get('goto_full_name', full_name)
        has_python = options.get('goto_has_python', has_python)

    if way == 'direct':
        if type_ == 'goto':
            defs = s.goto_assignments(follow_imports=True, **kwargs)
        else:
            defs = s.goto_definitions(**kwargs)
    else:
        goto_defs = s.goto_assignments(
            # Prefering stubs when we want to go to python and vice versa
            prefer_stubs=not (prefer_stubs or only_stubs),
            follow_imports=True,
        )
        if type_ == 'goto':
            defs = [
                d for goto_def in goto_defs
                for d in goto_def.goto_assignments(**kwargs)
            ]
        else:
            defs = [
                d for goto_def in goto_defs for d in goto_def.infer(**kwargs)
            ]

    if not has_stub and only_stubs:
        assert not defs
    else:
        assert defs

    for d in defs:
        if prefer_stubs and has_stub:
            assert d.is_stub()
        elif only_stubs:
            assert d.is_stub()
        else:
            assert has_python == (not d.is_stub())
        assert d.full_name == full_name

        assert d.is_stub() == d.module_path.endswith('.pyi')
Пример #7
0
def test_cache_works_with_sys_path_param(Script, tmpdir):
    foo_path = tmpdir.join('foo')
    bar_path = tmpdir.join('bar')
    foo_path.join('module.py').write('foo = 123', ensure=True)
    bar_path.join('module.py').write('bar = 123', ensure=True)
    foo_completions = Script(
        'import module; module.',
        project=Project('.', sys_path=[foo_path.strpath]),
    ).complete()
    bar_completions = Script(
        'import module; module.',
        project=Project('.', sys_path=[bar_path.strpath]),
    ).complete()
    assert 'foo' in [c.name for c in foo_completions]
    assert 'bar' not in [c.name for c in foo_completions]

    assert 'bar' in [c.name for c in bar_completions]
    assert 'foo' not in [c.name for c in bar_completions]
Пример #8
0
def test_correct_zip_package_behavior(Script, inference_state, environment,
                                      code, file, package, path):
    sys_path = environment.get_sys_path() + [str(pkg_zip_path)]
    pkg, = Script(code, project=Project('.', sys_path=sys_path)).infer()
    value, = pkg._name.infer()
    assert value.py__file__() == pkg_zip_path.joinpath('pkg', file)
    assert '.'.join(value.py__package__()) == package
    assert value.is_package() is (path is not None)
    if path is not None:
        assert value.py__path__() == [str(pkg_zip_path.joinpath(path))]
Пример #9
0
def test_relative_imports_without_path(Script):
    project = Project('.', sys_path=[], smart_sys_path=False)
    script = Script("from . ", _project=project)
    assert [c.name for c in script.completions()] == ['api_test1', 'import']

    script = Script("from .. ", _project=project)
    assert [c.name for c in script.completions()] == ['import', 'whatever']

    script = Script("from ... ", _project=project)
    assert [c.name for c in script.completions()] == ['api', 'import', 'whatever']
Пример #10
0
def test_find_module_not_package_zipped(Script, inference_state, environment):
    path = get_example_dir('zipped_imports', 'not_pkg.zip')
    sys_path = environment.get_sys_path() + [path]
    script = Script('import not_pkg; not_pkg.val',
                    project=Project('.', sys_path=sys_path))
    assert len(script.complete()) == 1

    file_io, is_package = inference_state.compiled_subprocess.get_module_info(
        sys_path=map(str, sys_path), string='not_pkg', full_name='not_pkg')
    assert file_io.path.parts[-2:] == ('not_pkg.zip', 'not_pkg.py')
    assert is_package is False
Пример #11
0
def test_relative_imports_without_path(Script):
    path = get_example_dir('issue1209', 'api', 'whatever')
    project = Project(path, sys_path=[], smart_sys_path=False)
    script = Script("from . ", project=project)
    assert [c.name for c in script.complete()] == ['api_test1', 'import']

    script = Script("from .. ", project=project)
    assert [c.name for c in script.complete()] == ['import', 'whatever']

    script = Script("from ... ", project=project)
    assert [c.name for c in script.complete()] == ['api', 'import', 'whatever']
Пример #12
0
def test_relative_imports_with_multiple_similar_directories(Script, path):
    dir = get_example_dir('issue1209')
    script = Script(
        "from .",
        path=os.path.join(dir, path)
    )
    # TODO pass this project to the script as a param once that's possible.
    script._evaluator.project = Project(dir)
    name, import_ = script.completions()
    assert import_.name == 'import'
    assert name.name == 'api_test1'
def test_import_needed_modules_by_jedi(Script, environment, tmpdir, name):
    module_path = tmpdir.join(name + '.py')
    module_path.write('int = ...')
    script = Script(
        'import ' + name,
        path=tmpdir.join('something.py').strpath,
        project=Project('.', sys_path=[tmpdir.strpath] + environment.get_sys_path()),
    )
    module, = script.infer()
    assert str(module._inference_state.builtins_module.py__file__()) != module_path
    assert str(module._inference_state.typing_module.py__file__()) != module_path
Пример #14
0
def test_conversion_of_stub_only(Script):
    project = Project(os.path.join(root_dir, 'test', 'completion', 'stub_folder'))
    code = 'import stub_only; stub_only.in_stub_only'
    d1, = Script(code, project=project).goto()
    assert d1.is_stub()

    script = Script(path=d1.module_path, project=project)
    d2, = script.goto(line=d1.line, column=d1.column)
    assert d2.is_stub()
    assert d2.module_path == d1.module_path
    assert d2.line == d1.line
    assert d2.column == d1.column
    assert d2.name == 'in_stub_only'
Пример #15
0
def test_find_module_package_zipped(Script, inference_state, environment):
    sys_path = environment.get_sys_path() + [str(pkg_zip_path)]

    project = Project('.', sys_path=sys_path)
    script = Script('import pkg; pkg.mod', project=project)
    assert len(script.complete()) == 1

    file_io, is_package = inference_state.compiled_subprocess.get_module_info(
        sys_path=sys_path, string='pkg', full_name='pkg')
    assert file_io is not None
    assert file_io.path.parts[-3:] == ('pkg.zip', 'pkg', '__init__.py')
    assert file_io._zip_path.name == 'pkg.zip'
    assert is_package is True
Пример #16
0
def test_goto_on_file(Script):
    project = Project(os.path.join(root_dir, 'test', 'completion', 'stub_folder'))
    script = Script('import stub_only; stub_only.Foo', project=project)
    d1, = script.goto()
    v, = d1._name.infer()
    foo, bar, obj = v.py__mro__()
    assert foo.py__name__() == 'Foo'
    assert bar.py__name__() == 'Bar'
    assert obj.py__name__() == 'object'

    # Make sure we go to Bar, because Foo is a bit before: `class Foo(Bar):`
    script = Script(path=d1.module_path, project=project)
    d2, = script.goto(line=d1.line, column=d1.column + 4)
    assert d2.name == 'Bar'
Пример #17
0
def test_get_modules_containing_name(inference_state, path, goal, is_package):
    inference_state.project = Project(test_dir)
    module = imports._load_python_module(
        inference_state,
        FileIO(path),
        import_names=('ok', 'lala', 'x'),
        is_package=is_package,
    )
    assert module
    module_context = module.as_context()
    input_module, found_module = get_module_contexts_containing_name(
        inference_state, [module_context], 'string_that_only_exists_here')
    assert input_module is module_context
    assert found_module.string_names == goal
Пример #18
0
def test_relative_imports_with_outside_paths(Script):
    dir = get_example_dir('issue1209')
    project = Project(dir, sys_path=[], smart_sys_path=False)
    script = Script(
        "from ...",
        path=os.path.join(dir, 'api/whatever/test_this.py'),
        _project=project,
    )
    assert [c.name for c in script.completions()] == ['api', 'import', 'whatever']

    script = Script(
        "from " + '.' * 100,
        path=os.path.join(dir, 'api/whatever/test_this.py'),
        _project=project,
    )
    assert [c.name for c in script.completions()] == ['import']
Пример #19
0
def test_infer_and_goto(Script, code, full_name, has_stub, has_python, way,
                        kwargs, type_, options, environment):
    if type_ == 'infer' and full_name == 'typing.Sequence' and environment.version_info >= (3, 7):
        # In Python 3.7+ there's not really a sequence definition, there's just
        # a name that leads nowhere.
        has_python = False

    project = Project(os.path.join(root_dir, 'test', 'completion', 'stub_folder'))
    s = Script(code, project=project)
    prefer_stubs = kwargs['prefer_stubs']
    only_stubs = kwargs['only_stubs']

    if type_ == 'goto':
        full_name = options.get('goto_full_name', full_name)
        has_python = options.get('goto_has_python', has_python)

    if way == 'direct':
        if type_ == 'goto':
            defs = s.goto(follow_imports=True, **kwargs)
        else:
            defs = s.infer(**kwargs)
    else:
        goto_defs = s.goto(
            # Prefering stubs when we want to go to python and vice versa
            prefer_stubs=not (prefer_stubs or only_stubs),
            follow_imports=True,
        )
        if type_ == 'goto':
            defs = [d for goto_def in goto_defs for d in goto_def.goto(**kwargs)]
        else:
            defs = [d for goto_def in goto_defs for d in goto_def.infer(**kwargs)]

    if not has_stub and only_stubs:
        assert not defs
    else:
        assert defs

    for d in defs:
        if prefer_stubs and has_stub:
            assert d.is_stub()
        elif only_stubs:
            assert d.is_stub()
        else:
            assert has_python == (not d.is_stub())
        assert d.full_name == full_name

        assert d.is_stub() == (d.module_path.suffix == '.pyi')
Пример #20
0
def test_import_not_in_sys_path(Script, environment):
    """
    non-direct imports (not in sys.path)

    This is in the end just a fallback.
    """
    path = get_example_dir()
    module_path = os.path.join(path, 'not_in_sys_path', 'pkg', 'module.py')
    # This project tests the smart path option of Project. The sys_path is
    # explicitly given to make sure that the path is just dumb and only
    # includes non-folder dependencies.
    project = Project(path, sys_path=environment.get_sys_path())
    a = Script(path=module_path, project=project).infer(line=5)
    assert a[0].name == 'int'

    a = Script(path=module_path, project=project).infer(line=6)
    assert a[0].name == 'str'
    a = Script(path=module_path, project=project).infer(line=7)
    assert a[0].name == 'str'
Пример #21
0
def test_references_scope(Script, code, places):
    if not code:
        code = '''import sys
from collections import defaultdict

print(sys.path)

def foo(bar):
    baz = defaultdict(int)
    return baz

def bar(foo):
    baz = defaultdict(int)
    return baz

foo()
'''
    from jedi.api.project import Project
    project = Project('', sys_path=[], smart_sys_path=False)
    script = Script(code, project=project)

    for place in places:
        assert places == [(n.line, n.column) for n in script.get_references(scope='file', *place)]
Пример #22
0
def test_infer_and_goto(Script, code, full_name, has_stub, has_python, way,
                        kwargs):
    project = Project(
        os.path.join(root_dir, 'test', 'completion', 'stub_folder'))
    s = Script(code, _project=project)
    if way == 'direct':
        defs = s.goto_definitions(**kwargs)
    else:
        goto_defs = s.goto_assignments()
        defs = [d for goto_def in goto_defs for d in goto_def.infer(**kwargs)]

    only_stubs = kwargs['only_stubs']
    prefer_stubs = kwargs['prefer_stubs']
    if not has_stub and only_stubs:
        assert not defs
    else:
        assert defs

    for d in defs:
        if prefer_stubs and has_stub:
            assert d.is_stub()
        if only_stubs:
            assert d.is_stub()
        assert d.full_name == full_name
Пример #23
0
def ScriptInStubFolder(Script):
    path = get_example_dir('stub_packages')
    project = Project(path, sys_path=[path], smart_sys_path=False)
    return partial(Script, _project=project)
Пример #24
0
 def get(include):
     from jedi.api.project import Project
     script = Script(source,
                     project=Project('', sys_path=[], smart_sys_path=False))
     references = script.get_references(column=8, include_builtins=include)
     return [(d.line, d.column) for d in references]
Пример #25
0
def test_zip_package_import_complete(Script, environment, code, names):
    sys_path = environment.get_sys_path() + [str(pkg_zip_path)]
    completions = Script(code, project=Project('.',
                                               sys_path=sys_path)).complete()
    assert names == {c.name for c in completions}