def test_generator(self): # Did have some problems with the usage of generator completions this # way. s = "def abc():\n" \ " yield 1\n" \ "abc()." assert Script(s).completions()
def test_unicode_script(): """ normally no unicode objects are being used. (<=2.7) """ s = unicode("import datetime; datetime.timedelta") completions = Script(s).completions() assert len(completions) assert type(completions[0].description) is unicode s = u("author='öä'; author") completions = Script(s).completions() x = completions[0].description assert type(x) is unicode s = u("#-*- coding: iso-8859-1 -*-\nauthor='öä'; author") s = s.encode('latin-1') completions = Script(s).completions() assert type(completions[0].description) is unicode
def goto_definition(event): if not control_is_pressed(event.state): return assert isinstance(event.widget, tk.Text) text = event.widget source = text.get("1.0", "end") index = text.index("insert") index_parts = index.split(".") line, column = int(index_parts[0]), int(index_parts[1]) # TODO: find current editor filename from jedi import Script script = Script(source, line=line, column=column, path="") defs = script.goto_definitions() if len(defs) > 0: module_path = defs[0].module_path module_name = defs[0].module_name line = defs[0].line if module_path and line is not None: get_workbench().get_editor_notebook().show_file(module_path, line) elif module_name == "" and line is not None: # current editor get_workbench().get_editor_notebook().get_current_editor( ).select_range(line)
def test_param_endings(): """ Params should be represented without the comma and whitespace they have around them. """ sig = Script('def x(a, b=5, c=""): pass\n x(').call_signatures()[0] assert [p.description for p in sig.params] == ['a', 'b=5', 'c=""']
def test_complex(self): s = """ def abc(a,b): pass def a(self): abc( if 1: pass """ assert_signature(s, 'abc', 0, line=6, column=24) s = """ import re def huhu(it): re.compile( return it * 2 """ assert_signature(s, 'compile', 0, line=4, column=31) # jedi-vim #70 s = """def foo(""" assert Script(s).call_signatures() == [] # jedi-vim #116 s = """import itertools; test = getattr(itertools, 'chain'); test(""" assert_signature(s, 'chain', 0)
def test_goto_assignments_keyword(): """ Bug: goto assignments on ``in`` used to raise AttributeError:: 'unicode' object has no attribute 'generate_call_path' """ Script('in').goto_assignments()
def test_function_definitions_should_break(self): """ Function definitions (and other tokens that cannot exist within call signatures) should break and not be able to return a call signature. """ assert_signature('str(\ndef x', 'str', 0) assert not Script('str(\ndef x(): pass').call_signatures()
def test_function_definition_complex(self): s = """ def abc(a,b): pass def a(self): abc( if 1: pass """ self._run(s, 'abc', 0, line=6, column=24) s = """ import re def huhu(it): re.compile( return it * 2 """ self._run(s, 'compile', 0, line=4, column=31) # jedi-vim #70 s = """def foo(""" assert Script(s).call_signatures() == [] # jedi-vim #116 s = """import functools; test = getattr(functools, 'partial'); test(""" self._run(s, 'partial', 0)
def test_function_call_signature_in_doc(): defs = Script(""" def f(x, y=1, z='a'): pass f""").goto_definitions() doc = defs[0].doc assert "f(x, y=1, z='a')" in str(doc)
def test_wrong_encoding(cwd_tmpdir): x = cwd_tmpdir.join('x.py') # Use both latin-1 and utf-8 (a really broken file). x.write_binary(u'foobar = 1\nä'.encode('latin-1') + u'ä'.encode('utf-8')) c, = Script('import x; x.foo', sys_path=['.']).completions() assert c.name == 'foobar'
def _get_positions_correct_but_using_private_parts(self): from jedi import Script tree = jedi_utils.import_tree() locs = [] def process_scope(scope): if isinstance(scope, tree.Function): # process all children after name node, # (otherwise name of global function will be marked as local def) local_names = set() global_names = set() for child in scope.children[2:]: process_node(child, local_names, global_names) else: for child in scope.subscopes: process_scope(child) def process_node(node, local_names, global_names): if isinstance(node, tree.GlobalStmt): global_names.update([n.value for n in node.get_global_names()]) elif isinstance(node, tree.Name): if node.value in global_names: return if node.is_definition(): # local def locs.append(node) local_names.add(node.value) elif node.value in local_names: # use of local locs.append(node) elif isinstance(node, tree.BaseNode): # ref: jedi/parser/grammar*.txt if node.type == "trailer" and node.children[0].value == ".": # this is attribute return if isinstance(node, tree.Function): global_names = set( ) # outer global statement doesn't have effect anymore for child in node.children: process_node(child, local_names, global_names) source = self.text.get('1.0', 'end') script = Script(source + ")") # https://github.com/davidhalter/jedi/issues/897 module = jedi_utils.get_module_node(script) for child in module.children: if isinstance(child, tree.BaseNode) and jedi_utils.is_scope(child): process_scope(child) loc_pos = set( ("%d.%d" % (usage.start_pos[0], usage.start_pos[1]), "%d.%d" % (usage.start_pos[0], usage.start_pos[1] + len(usage.value))) for usage in locs) return loc_pos
def get_positions(self): index = self.text.index("insert") # ignore if cursor in STRING_OPEN if self.text.tag_prevrange("STRING_OPEN", index): return set() index_parts = index.split('.') l, c = int(index_parts[0]), int(index_parts[1]) script = Script(self.text.get('1.0', 'end') + ")", l, c) name = None stmt = NameHighlighter.get_statement_for_position( script._parser.module(), script._pos) if isinstance(stmt, tree.Name): name = stmt elif isinstance(stmt, tree.BaseNode): name = stmt.name_for_position(script._pos) if not name: return set() # format usage positions as tkinter text widget indices return set( ("%d.%d" % (usage.start_pos[0], usage.start_pos[1]), "%d.%d" % (usage.start_pos[0], usage.start_pos[1] + len(name.value))) for usage in NameHighlighter.find_usages(name, stmt, script._parser.module()))
def show_completion(self, tab): """Method shows code completion window Args: tab (obj): tab reference Returns: void """ if (self._win is not None): self._win.destroy() suffix = tab.path.split('.')[-1] if (suffix in ['py', 'jedi', 'padawan']): self._tab = tab row, col = tab.text.index(tk.INSERT).split('.') try: script = Script(tab.text.get('1.0', 'end-1c'), int(row), int(col)) completions = script.completions() except ValueError: return cnt = len(completions) if (cnt == 0): return if (cnt == 1): self._complete(completion=completions[0]) else: self._set_gui(completions)
def test_points_in_completion(self): """At some point, points were inserted into the completions, this caused problems, sometimes. """ c = Script("if IndentationErr").completions() assert c[0].name == 'IndentationError' self.assertEqual(c[0].complete, 'or')
def test_type_II(): """ GitHub Issue #833, `keyword`s are seen as `module`s """ for c in Script('f').completions(): if c.name == 'for': assert c.type == 'keyword'
def test_indent_context(): """ If an INDENT is the next supposed token, we should still be able to complete. """ code = 'if 1:\nisinstanc' comp, = Script(code).completions() assert comp.name == 'isinstance'
def test_class_call_signature(): defs = Script(""" class Foo: def __init__(self, x, y=1, z='a'): pass Foo""").goto_definitions() doc = defs[0].doc assert "Foo(self, x, y=1, z='a')" in str(doc)
def run(rest_source): source = dedent(""" def foo(bar, baz): pass """) results = Script(source + rest_source).completions() assert len(results) == 1 return results[0]
def test_lambda_params(): code = dedent('''\ my_lambda = lambda x: x+1 my_lambda(1)''') sig, = Script(code, column=11).call_signatures() assert sig.index == 0 assert sig.name == '<lambda>' assert [p.name for p in sig.params] == ['x']
def test_sys_path_with_modifications(): code = dedent(""" import os """) path = os.path.abspath(os.path.join(os.curdir, 'module_name.py')) paths = Script(code, path=path)._evaluator.project.sys_path assert '/tmp/.buildout/eggs/important_package.egg' in paths
def __init__(self, area, *args, **kwargs): source = area.get('1.0', 'end') source = area.get('1.0', 'end') line, col = area.indcur() script = Script(source, line, col, area.filename) completions = script.completions() CompletionWindow.__init__(self, area, completions, *args, **kwargs) self.bind('<F1>', lambda event: sys.stdout.write('%s\n%s\n' % ('#' * 80, self.box.selection_docs())))
def test_follow_definition(): """ github issue #45 """ c = Script("from datetime import timedelta; timedelta").completions() # type can also point to import, but there will be additional # attributes objs = itertools.chain.from_iterable(r.follow_definition() for r in c) types = [o.type for o in objs] assert 'import' not in types and 'class' in types
def do_complete(self, data): file_ = self.db.get_file(self.current_file) file_ = to_unicode(file_) lines = file_.splitlines() lno = self.current['lno'] line_before = '' if len(lines) >= lno: line_before = lines[lno - 1] indent = len(line_before) - len(line_before.lstrip()) segments = data.splitlines() for segment in reversed(segments): line = u(' ') * indent + segment lines.insert(lno - 1, line) script = Script( u('\n').join(lines), lno - 1 + len(segments), len(segments[-1]) + indent, '') try: completions = script.completions() except: self.db.send('Suggest') self.notify_exc('Completion failed for %s' % ('\n'.join(reversed(segments)))) return try: funs = script.call_signatures() or [] except: self.db.send('Suggest') self.notify_exc('Completion of function failed for %s' % ('\n'.join(reversed(segments)))) return try: suggest_obj = { 'params': [{ 'params': [p.get_code().replace('\n', '') for p in fun.params], 'index': fun.index, 'module': fun.module.path, 'call_name': fun.call_name } for fun in funs], 'completions': [{ 'base': comp.name[:len(comp.name) - len(comp.complete)], 'complete': comp.complete, 'description': comp.description } for comp in completions if comp.name.endswith(comp.complete)] } self.db.send('Suggest|%s' % dump(suggest_obj)) except: self.db.send('Suggest') self.notify_exc('Completion generation failed for %s' % ('\n'.join(reversed(segments))))
def test_namedtuple_list(): source = dedent("""\ import collections Cat = collections.namedtuple('Person', ['legs', u'length', 'large']) garfield = Cat(4, '85cm', True) garfield.l""") result = Script(source).completions() completions = set(r.name for r in result) assert completions == {'legs', 'length', 'large'}
def do_completion(self): source = self.area.get('1.0', 'end') line = self.area.indcur()[0] size = len(self.area.get('insert linestart', 'insert')) script = Script(source, line, size, self.area.filename) completions = script.completions() for ind in completions: self.insert('end', ind.name)
def test_namedtuple_str(letter, expected): source = dedent("""\ import collections Person = collections.namedtuple('Person', 'name smart') dave = Person('Dave', False) dave.%s""") % letter result = Script(source).completions() completions = set(r.name for r in result) assert completions == set(expected)
def test_multiple_signatures(self): s = dedent("""\ if x: def f(a, b): pass else: def f(a, b): pass f(""") assert len(Script(s).call_signatures()) == 2
def get_script(ls: LanguageServer, uri: str, update: bool = False) -> Script: result = None if update else scripts.get(uri) if not result: document = ls.workspace.get_document(uri) result = Script(code=document.source, path=document.path, environment=jediEnvironment, project=jediProject) scripts[uri] = result return result
def script(workspace: Workspace, uri: str) -> Script: """Simplifies getting jedi Script""" project_ = project(workspace) document = workspace.get_document(uri) return Script( code=document.source, path=document.path, project=project_, environment=get_cached_default_environment(), )
def test_multibyte_script(): """ `jedi.Script` must accept multi-byte string source. """ try: code = u("import datetime; datetime.d") comment = u("# multi-byte comment あいうえおä") s = (u('%s\n%s') % (code, comment)).encode('utf-8') except NameError: pass # python 3 has no unicode method else: assert len(Script(s, 1, len(code)).completions())