test_completer.py
1749 lines
| 60.3 KiB
| text/x-python
|
PythonLexer
|
r16564 | # encoding: utf-8 | ||
"""Tests for the IPython tab-completion machinery.""" | ||||
# Copyright (c) IPython Development Team. | ||||
# Distributed under the terms of the Modified BSD License. | ||||
|
r2365 | |||
|
r3184 | import os | ||
|
r27042 | import pytest | ||
|
r2365 | import sys | ||
|
r23358 | import textwrap | ||
|
r2855 | import unittest | ||
|
r2365 | |||
|
r16564 | from contextlib import contextmanager | ||
|
r21253 | from traitlets.config.loader import Config | ||
|
r21718 | from IPython import get_ipython | ||
|
r2365 | from IPython.core import completer | ||
|
r16767 | from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory | ||
|
r5155 | from IPython.utils.generics import complete_object | ||
|
r15766 | from IPython.testing import decorators as dec | ||
|
r2365 | |||
|
r23358 | from IPython.core.completer import ( | ||
|
r25101 | Completion, | ||
provisionalcompleter, | ||||
match_dict_keys, | ||||
_deduplicate_completions, | ||||
|
r27912 | _match_number_in_dict_key_prefix, | ||
|
r27775 | completion_matcher, | ||
SimpleCompletion, | ||||
CompletionContext, | ||||
|
r25101 | ) | ||
|
r23284 | |||
|
r25101 | # ----------------------------------------------------------------------------- | ||
|
r2365 | # Test functions | ||
|
r25101 | # ----------------------------------------------------------------------------- | ||
|
r28561 | |||
|
r25729 | def recompute_unicode_ranges(): | ||
""" | ||||
utility to recompute the largest unicode range without any characters | ||||
use to recompute the gap in the global _UNICODE_RANGES of completer.py | ||||
""" | ||||
import itertools | ||||
import unicodedata | ||||
|
r28561 | |||
|
r25729 | valid = [] | ||
|
r28561 | for c in range(0, 0x10FFFF + 1): | ||
|
r25729 | try: | ||
unicodedata.name(chr(c)) | ||||
except ValueError: | ||||
continue | ||||
valid.append(c) | ||||
def ranges(i): | ||||
for a, b in itertools.groupby(enumerate(i), lambda pair: pair[1] - pair[0]): | ||||
b = list(b) | ||||
yield b[0][1], b[-1][1] | ||||
rg = list(ranges(valid)) | ||||
lens = [] | ||||
gap_lens = [] | ||||
|
r28561 | pstart, pstop = 0, 0 | ||
|
r25729 | for start, stop in rg: | ||
|
r28561 | lens.append(stop - start) | ||
gap_lens.append( | ||||
( | ||||
start - pstop, | ||||
hex(pstop + 1), | ||||
hex(start), | ||||
f"{round((start - pstop)/0xe01f0*100)}%", | ||||
) | ||||
) | ||||
|
r25729 | pstart, pstop = start, stop | ||
return sorted(gap_lens)[-1] | ||||
|
r25711 | def test_unicode_range(): | ||
""" | ||||
Test that the ranges we test for unicode names give the same number of | ||||
results than testing the full length. | ||||
""" | ||||
|
r28561 | from IPython.core.completer import _unicode_name_compute, _UNICODE_RANGES | ||
|
r25711 | |||
expected_list = _unicode_name_compute([(0, 0x110000)]) | ||||
test = _unicode_name_compute(_UNICODE_RANGES) | ||||
|
r25712 | len_exp = len(expected_list) | ||
len_test = len(test) | ||||
|
r25711 | |||
|
r25712 | # do not inline the len() or on error pytest will try to print the 130 000 + | ||
# elements. | ||||
|
r25729 | message = None | ||
if len_exp != len_test or len_exp > 131808: | ||||
size, start, stop, prct = recompute_unicode_ranges() | ||||
message = f"""_UNICODE_RANGES likely wrong and need updating. This is | ||||
likely due to a new release of Python. We've find that the biggest gap | ||||
|
r26875 | in unicode characters has reduces in size to be {size} characters | ||
|
r25729 | ({prct}), from {start}, to {stop}. In completer.py likely update to | ||
_UNICODE_RANGES = [(32, {start}), ({stop}, 0xe01f0)] | ||||
And update the assertion below to use | ||||
len_exp <= {len_exp} | ||||
""" | ||||
assert len_exp == len_test, message | ||||
|
r25712 | |||
|
r28561 | # fail if new unicode symbols have been added. | ||
|
r28560 | assert len_exp <= 143668, message | ||
|
r25711 | |||
|
r16564 | |||
@contextmanager | ||||
def greedy_completion(): | ||||
ip = get_ipython() | ||||
greedy_original = ip.Completer.greedy | ||||
try: | ||||
ip.Completer.greedy = True | ||||
yield | ||||
finally: | ||||
ip.Completer.greedy = greedy_original | ||||
|
r25101 | |||
|
r27775 | @contextmanager | ||
|
r27915 | def evaluation_policy(evaluation: str): | ||
|
r27906 | ip = get_ipython() | ||
evaluation_original = ip.Completer.evaluation | ||||
try: | ||||
ip.Completer.evaluation = evaluation | ||||
yield | ||||
finally: | ||||
ip.Completer.evaluation = evaluation_original | ||||
@contextmanager | ||||
|
r27775 | def custom_matchers(matchers): | ||
ip = get_ipython() | ||||
try: | ||||
ip.Completer.custom_matchers.extend(matchers) | ||||
yield | ||||
finally: | ||||
ip.Completer.custom_matchers.clear() | ||||
|
r2365 | def test_protect_filename(): | ||
|
r25101 | if sys.platform == "win32": | ||
pairs = [ | ||||
("abc", "abc"), | ||||
(" abc", '" abc"'), | ||||
("a bc", '"a bc"'), | ||||
("a bc", '"a bc"'), | ||||
(" bc", '" bc"'), | ||||
] | ||||
|
r22418 | else: | ||
|
r25101 | pairs = [ | ||
("abc", "abc"), | ||||
(" abc", r"\ abc"), | ||||
("a bc", r"a\ bc"), | ||||
("a bc", r"a\ \ bc"), | ||||
(" bc", r"\ \ bc"), | ||||
# On posix, we also protect parens and other special characters. | ||||
("a(bc", r"a\(bc"), | ||||
("a)bc", r"a\)bc"), | ||||
("a( )bc", r"a\(\ \)bc"), | ||||
("a[1]bc", r"a\[1\]bc"), | ||||
("a{1}bc", r"a\{1\}bc"), | ||||
("a#bc", r"a\#bc"), | ||||
("a?bc", r"a\?bc"), | ||||
("a=bc", r"a\=bc"), | ||||
("a\\bc", r"a\\bc"), | ||||
("a|bc", r"a\|bc"), | ||||
("a;bc", r"a\;bc"), | ||||
("a:bc", r"a\:bc"), | ||||
("a'bc", r"a\'bc"), | ||||
("a*bc", r"a\*bc"), | ||||
('a"bc', r"a\"bc"), | ||||
("a^bc", r"a\^bc"), | ||||
("a&bc", r"a\&bc"), | ||||
] | ||||
|
r2365 | # run the actual tests | ||
for s1, s2 in pairs: | ||||
s1p = completer.protect_filename(s1) | ||||
|
r26888 | assert s1p == s2 | ||
|
r2855 | |||
def check_line_split(splitter, test_specs): | ||||
for part1, part2, split in test_specs: | ||||
cursor_pos = len(part1) | ||||
|
r25101 | line = part1 + part2 | ||
|
r2855 | out = splitter.split_line(line, cursor_pos) | ||
|
r26888 | assert out == split | ||
|
r2855 | |||
def test_line_split(): | ||||
|
r13375 | """Basic line splitter test with default specs.""" | ||
|
r2855 | sp = completer.CompletionSplitter() | ||
# The format of the test specs is: part1, part2, expected answer. Parts 1 | ||||
# and 2 are joined into the 'line' sent to the splitter, as if the cursor | ||||
# was at the end of part1. So an empty part2 represents someone hitting | ||||
# tab at the end of the line, the most common case. | ||||
|
r25101 | t = [ | ||
("run some/scrip", "", "some/scrip"), | ||||
("run scripts/er", "ror.py foo", "scripts/er"), | ||||
("echo $HOM", "", "HOM"), | ||||
("print sys.pa", "", "sys.pa"), | ||||
("print(sys.pa", "", "sys.pa"), | ||||
("execfile('scripts/er", "", "scripts/er"), | ||||
("a[x.", "", "x."), | ||||
("a[x.", "y", "x."), | ||||
('cd "some_file/', "", "some_file/"), | ||||
] | ||||
|
r2855 | check_line_split(sp, t) | ||
|
r3074 | # Ensure splitting works OK with unicode by re-running the tests with | ||
# all inputs turned into unicode | ||||
|
r25101 | check_line_split(sp, [map(str, p) for p in t]) | ||
|
r6511 | |||
|
r3074 | |||
|
r27127 | class NamedInstanceClass: | ||
instances = {} | ||||
|
r21103 | |||
|
r25099 | def __init__(self, name): | ||
|
r27127 | self.instances[name] = self | ||
|
r21103 | |||
|
r25099 | @classmethod | ||
def _ipython_key_completions_(cls): | ||||
return cls.instances.keys() | ||||
|
r21103 | |||
|
r25101 | |||
|
r25100 | class KeyCompletable: | ||
|
r25099 | def __init__(self, things=()): | ||
self.things = things | ||||
|
r21103 | |||
|
r25099 | def _ipython_key_completions_(self): | ||
return list(self.things) | ||||
|
r21103 | |||
|
r25099 | class TestCompleter(unittest.TestCase): | ||
|
r2855 | def setUp(self): | ||
|
r25099 | """ | ||
We want to silence all PendingDeprecationWarning when testing the completer | ||||
""" | ||||
self._assertwarns = self.assertWarns(PendingDeprecationWarning) | ||||
self._assertwarns.__enter__() | ||||
def tearDown(self): | ||||
try: | ||||
self._assertwarns.__exit__(None, None, None) | ||||
except AssertionError: | ||||
pass | ||||
def test_custom_completion_error(self): | ||||
"""Test that errors from custom attribute completers are silenced.""" | ||||
ip = get_ipython() | ||||
|
r25101 | |||
class A: | ||||
pass | ||||
ip.user_ns["x"] = A() | ||||
|
r25099 | @complete_object.register(A) | ||
def complete_A(a, existing_completions): | ||||
raise TypeError("this should be silenced") | ||||
|
r25101 | |||
|
r25099 | ip.complete("x.") | ||
|
r25168 | def test_custom_completion_ordering(self): | ||
"""Test that errors from custom attribute completers are silenced.""" | ||||
ip = get_ipython() | ||||
_, matches = ip.complete('in') | ||||
assert matches.index('input') < matches.index('int') | ||||
def complete_example(a): | ||||
return ['example2', 'example1'] | ||||
ip.Completer.custom_completers.add_re('ex*', complete_example) | ||||
_, matches = ip.complete('ex') | ||||
assert matches.index('example2') < matches.index('example1') | ||||
|
r25099 | def test_unicode_completions(self): | ||
ip = get_ipython() | ||||
# Some strings that trigger different types of completion. Check them both | ||||
# in str and unicode forms | ||||
|
r25101 | s = ["ru", "%ru", "cd /", "floa", "float(x)/"] | ||
|
r25099 | for t in s + list(map(str, s)): | ||
# We don't need to check exact completion values (they may change | ||||
# depending on the state of the namespace, but at least no exceptions | ||||
# should be thrown and the return value should be a pair of text, list | ||||
# values. | ||||
text, matches = ip.complete(t) | ||||
|
r26888 | self.assertIsInstance(text, str) | ||
self.assertIsInstance(matches, list) | ||||
|
r25099 | |||
def test_latex_completions(self): | ||||
from IPython.core.latex_symbols import latex_symbols | ||||
import random | ||||
|
r25101 | |||
|
r25099 | ip = get_ipython() | ||
# Test some random unicode symbols | ||||
|
r27105 | keys = random.sample(sorted(latex_symbols), 10) | ||
|
r25099 | for k in keys: | ||
text, matches = ip.complete(k) | ||||
|
r26888 | self.assertEqual(text, k) | ||
self.assertEqual(matches, [latex_symbols[k]]) | ||||
|
r25099 | # Test a more complex line | ||
|
r25101 | text, matches = ip.complete("print(\\alpha") | ||
|
r26888 | self.assertEqual(text, "\\alpha") | ||
self.assertEqual(matches[0], latex_symbols["\\alpha"]) | ||||
|
r25099 | # Test multiple matching latex symbols | ||
|
r25101 | text, matches = ip.complete("\\al") | ||
|
r26888 | self.assertIn("\\alpha", matches) | ||
self.assertIn("\\aleph", matches) | ||||
|
r25099 | |||
|
r25686 | def test_latex_no_results(self): | ||
""" | ||||
forward latex should really return nothing in either field if nothing is found. | ||||
""" | ||||
ip = get_ipython() | ||||
text, matches = ip.Completer.latex_matches("\\really_i_should_match_nothing") | ||||
|
r26888 | self.assertEqual(text, "") | ||
self.assertEqual(matches, ()) | ||||
|
r25686 | |||
|
r25099 | def test_back_latex_completion(self): | ||
ip = get_ipython() | ||||
|
r26875 | # do not return more than 1 matches for \beta, only the latex one. | ||
|
r25101 | name, matches = ip.complete("\\β") | ||
|
r26888 | self.assertEqual(matches, ["\\beta"]) | ||
|
r25099 | |||
def test_back_unicode_completion(self): | ||||
ip = get_ipython() | ||||
|
r16767 | |||
|
r25101 | name, matches = ip.complete("\\â…¤") | ||
|
r27768 | self.assertEqual(matches, ["\\ROMAN NUMERAL FIVE"]) | ||
|
r16767 | |||
|
r25099 | def test_forward_unicode_completion(self): | ||
ip = get_ipython() | ||||
|
r25101 | |||
name, matches = ip.complete("\\ROMAN NUMERAL FIVE") | ||||
|
r26888 | self.assertEqual(matches, ["â…¤"]) # This is not a V | ||
self.assertEqual(matches, ["\u2164"]) # same as above but explicit. | ||||
|
r25099 | |||
|
r26989 | def test_delim_setting(self): | ||
sp = completer.CompletionSplitter() | ||||
sp.delims = " " | ||||
self.assertEqual(sp.delims, " ") | ||||
self.assertEqual(sp._delim_expr, r"[\ ]") | ||||
def test_spaces(self): | ||||
"""Test with only spaces as split chars.""" | ||||
sp = completer.CompletionSplitter() | ||||
sp.delims = " " | ||||
t = [("foo", "", "foo"), ("run foo", "", "foo"), ("run foo", "bar", "foo")] | ||||
check_line_split(sp, t) | ||||
|
r4825 | |||
|
r25099 | def test_has_open_quotes1(self): | ||
for s in ["'", "'''", "'hi' '"]: | ||||
|
r26888 | self.assertEqual(completer.has_open_quotes(s), "'") | ||
|
r25099 | |||
def test_has_open_quotes2(self): | ||||
for s in ['"', '"""', '"hi" "']: | ||||
|
r26888 | self.assertEqual(completer.has_open_quotes(s), '"') | ||
|
r25099 | |||
def test_has_open_quotes3(self): | ||||
for s in ["''", "''' '''", "'hi' 'ipython'"]: | ||||
|
r26888 | self.assertFalse(completer.has_open_quotes(s)) | ||
|
r25099 | |||
def test_has_open_quotes4(self): | ||||
for s in ['""', '""" """', '"hi" "ipython"']: | ||||
|
r26888 | self.assertFalse(completer.has_open_quotes(s)) | ||
|
r25099 | |||
|
r27042 | @pytest.mark.xfail( | ||
sys.platform == "win32", reason="abspath completions fail on Windows" | ||||
|
r25101 | ) | ||
|
r25099 | def test_abspath_file_completions(self): | ||
ip = get_ipython() | ||||
with TemporaryDirectory() as tmpdir: | ||||
|
r25101 | prefix = os.path.join(tmpdir, "foo") | ||
suffixes = ["1", "2"] | ||||
names = [prefix + s for s in suffixes] | ||||
|
r25099 | for n in names: | ||
|
r27495 | open(n, "w", encoding="utf-8").close() | ||
|
r25099 | |||
# Check simple completion | ||||
c = ip.complete(prefix)[1] | ||||
|
r26888 | self.assertEqual(c, names) | ||
|
r25099 | |||
# Now check with a function call | ||||
cmd = 'a = f("%s' % prefix | ||||
c = ip.complete(prefix, cmd)[1] | ||||
|
r25101 | comp = [prefix + s for s in suffixes] | ||
|
r26888 | self.assertEqual(c, comp) | ||
|
r25099 | |||
def test_local_file_completions(self): | ||||
ip = get_ipython() | ||||
with TemporaryWorkingDirectory(): | ||||
|
r25101 | prefix = "./foo" | ||
suffixes = ["1", "2"] | ||||
names = [prefix + s for s in suffixes] | ||||
|
r25099 | for n in names: | ||
|
r27495 | open(n, "w", encoding="utf-8").close() | ||
|
r25099 | |||
# Check simple completion | ||||
c = ip.complete(prefix)[1] | ||||
|
r26888 | self.assertEqual(c, names) | ||
|
r25099 | |||
# Now check with a function call | ||||
cmd = 'a = f("%s' % prefix | ||||
c = ip.complete(prefix, cmd)[1] | ||||
|
r25101 | comp = {prefix + s for s in suffixes} | ||
|
r26888 | self.assertTrue(comp.issubset(set(c))) | ||
|
r25099 | |||
def test_quoted_file_completions(self): | ||||
ip = get_ipython() | ||||
|
r27768 | |||
def _(text): | ||||
return ip.Completer._complete( | ||||
cursor_line=0, cursor_pos=len(text), full_text=text | ||||
)["IPCompleter.file_matcher"]["completions"] | ||||
|
r25099 | with TemporaryWorkingDirectory(): | ||
name = "foo'bar" | ||||
|
r27495 | open(name, "w", encoding="utf-8").close() | ||
|
r25099 | |||
# Don't escape Windows | ||||
escaped = name if sys.platform == "win32" else "foo\\'bar" | ||||
# Single quote matches embedded single quote | ||||
|
r27768 | c = _("open('foo")[0] | ||
self.assertEqual(c.text, escaped) | ||||
|
r25099 | |||
# Double quote requires no escape | ||||
|
r27768 | c = _('open("foo')[0] | ||
self.assertEqual(c.text, name) | ||||
|
r25099 | |||
# No quote requires an escape | ||||
|
r27768 | c = _("%ls foo")[0] | ||
self.assertEqual(c.text, escaped) | ||||
|
r25099 | |||
|
r28561 | @pytest.mark.xfail( | ||
sys.version_info.releaselevel in ("alpha",), | ||||
reason="Parso does not yet parse 3.13", | ||||
) | ||||
|
r25122 | def test_all_completions_dups(self): | ||
""" | ||||
Make sure the output of `IPCompleter.all_completions` does not have | ||||
duplicated prefixes. | ||||
""" | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
ip.ex("class TestClass():\n\ta=1\n\ta1=2") | ||||
for jedi_status in [True, False]: | ||||
with provisionalcompleter(): | ||||
ip.Completer.use_jedi = jedi_status | ||||
matches = c.all_completions("TestCl") | ||||
|
r27356 | assert matches == ["TestClass"], (jedi_status, matches) | ||
|
r25122 | matches = c.all_completions("TestClass.") | ||
|
r27356 | assert len(matches) > 2, (jedi_status, matches) | ||
|
r25122 | matches = c.all_completions("TestClass.a") | ||
assert matches == ['TestClass.a', 'TestClass.a1'], jedi_status | ||||
|
r28561 | @pytest.mark.xfail( | ||
sys.version_info.releaselevel in ("alpha",), | ||||
reason="Parso does not yet parse 3.13", | ||||
) | ||||
|
r25099 | def test_jedi(self): | ||
""" | ||||
A couple of issue we had with Jedi | ||||
""" | ||||
ip = get_ipython() | ||||
def _test_complete(reason, s, comp, start=None, end=None): | ||||
l = len(s) | ||||
start = start if start is not None else l | ||||
end = end if end is not None else l | ||||
with provisionalcompleter(): | ||||
ip.Completer.use_jedi = True | ||||
completions = set(ip.Completer.completions(s, l)) | ||||
ip.Completer.use_jedi = False | ||||
|
r26989 | assert Completion(start, end, comp) in completions, reason | ||
|
r23284 | |||
|
r25099 | def _test_not_complete(reason, s, comp): | ||
l = len(s) | ||||
with provisionalcompleter(): | ||||
ip.Completer.use_jedi = True | ||||
completions = set(ip.Completer.completions(s, l)) | ||||
ip.Completer.use_jedi = False | ||||
|
r26989 | assert Completion(l, l, comp) not in completions, reason | ||
|
r25099 | |||
import jedi | ||||
|
r25101 | |||
jedi_version = tuple(int(i) for i in jedi.__version__.split(".")[:3]) | ||||
|
r25099 | if jedi_version > (0, 10): | ||
|
r26989 | _test_complete("jedi >0.9 should complete and not crash", "a=1;a.", "real") | ||
_test_complete("can infer first argument", 'a=(1,"foo");a[0].', "real") | ||||
_test_complete("can infer second argument", 'a=(1,"foo");a[1].', "capitalize") | ||||
_test_complete("cover duplicate completions", "im", "import", 0, 2) | ||||
|
r25099 | |||
|
r26989 | _test_not_complete("does not mix types", 'a=(1,"foo");a[0].', "capitalize") | ||
|
r25099 | |||
|
r28561 | @pytest.mark.xfail( | ||
sys.version_info.releaselevel in ("alpha",), | ||||
reason="Parso does not yet parse 3.13", | ||||
) | ||||
|
r25099 | def test_completion_have_signature(self): | ||
""" | ||||
Lets make sure jedi is capable of pulling out the signature of the function we are completing. | ||||
""" | ||||
ip = get_ipython() | ||||
|
r23284 | with provisionalcompleter(): | ||
|
r24281 | ip.Completer.use_jedi = True | ||
|
r25101 | completions = ip.Completer.completions("ope", 3) | ||
|
r25099 | c = next(completions) # should be `open` | ||
|
r24281 | ip.Completer.use_jedi = False | ||
|
r25101 | assert "file" in c.signature, "Signature of function was not found by completer" | ||
assert ( | ||||
"encoding" in c.signature | ||||
), "Signature of function was not found by completer" | ||||
|
r25099 | |||
|
r28561 | @pytest.mark.xfail( | ||
sys.version_info.releaselevel in ("alpha",), | ||||
reason="Parso does not yet parse 3.13", | ||||
) | ||||
|
r27768 | def test_completions_have_type(self): | ||
""" | ||||
Lets make sure matchers provide completion type. | ||||
""" | ||||
ip = get_ipython() | ||||
with provisionalcompleter(): | ||||
ip.Completer.use_jedi = False | ||||
completions = ip.Completer.completions("%tim", 3) | ||||
c = next(completions) # should be `%time` or similar | ||||
assert c.type == "magic", "Type of magic was not assigned by completer" | ||||
|
r27487 | @pytest.mark.xfail(reason="Known failure on jedi<=0.18.0") | ||
|
r25099 | def test_deduplicate_completions(self): | ||
""" | ||||
Test that completions are correctly deduplicated (even if ranges are not the same) | ||||
""" | ||||
ip = get_ipython() | ||||
|
r25101 | ip.ex( | ||
textwrap.dedent( | ||||
""" | ||||
|
r25099 | class Z: | ||
zoo = 1 | ||||
|
r25101 | """ | ||
) | ||||
) | ||||
|
r23284 | with provisionalcompleter(): | ||
|
r24281 | ip.Completer.use_jedi = True | ||
|
r25101 | l = list( | ||
_deduplicate_completions("Z.z", ip.Completer.completions("Z.z", 3)) | ||||
) | ||||
|
r24281 | ip.Completer.use_jedi = False | ||
|
r23753 | |||
|
r25101 | assert len(l) == 1, "Completions (Z.z<tab>) correctly deduplicate: %s " % l | ||
assert l[0].text == "zoo" # and not `it.accumulate` | ||||
|
r23358 | |||
|
r28561 | @pytest.mark.xfail( | ||
sys.version_info.releaselevel in ("alpha",), | ||||
reason="Parso does not yet parse 3.13", | ||||
) | ||||
|
r25099 | def test_greedy_completions(self): | ||
""" | ||||
|
r27906 | Test the capability of the Greedy completer. | ||
|
r23358 | |||
|
r25099 | Most of the test here does not really show off the greedy completer, for proof | ||
|
r27906 | each of the text below now pass with Jedi. The greedy completer is capable of more. | ||
|
r23284 | |||
|
r25099 | See the :any:`test_dict_key_completion_contexts` | ||
|
r23284 | |||
|
r25099 | """ | ||
ip = get_ipython() | ||||
|
r25101 | ip.ex("a=list(range(5))") | ||
|
r28112 | ip.ex("d = {'a b': str}") | ||
|
r25101 | _, c = ip.complete(".", line="a[0].") | ||
|
r26888 | self.assertFalse(".real" in c, "Shouldn't have completed on a[0]: %s" % c) | ||
|
r25101 | |||
|
r25099 | def _(line, cursor_pos, expect, message, completion): | ||
with greedy_completion(), provisionalcompleter(): | ||||
ip.Completer.use_jedi = False | ||||
|
r25101 | _, c = ip.complete(".", line=line, cursor_pos=cursor_pos) | ||
|
r26888 | self.assertIn(expect, c, message % c) | ||
|
r23284 | |||
|
r25099 | ip.Completer.use_jedi = True | ||
with provisionalcompleter(): | ||||
completions = ip.Completer.completions(line, cursor_pos) | ||||
|
r26888 | self.assertIn(completion, completions) | ||
|
r23284 | |||
|
r25099 | with provisionalcompleter(): | ||
|
r26989 | _( | ||
"a[0].", | ||||
5, | ||||
|
r28112 | ".real", | ||
|
r26989 | "Should have completed on a[0].: %s", | ||
Completion(5, 5, "real"), | ||||
|
r25101 | ) | ||
|
r26989 | _( | ||
"a[0].r", | ||||
6, | ||||
|
r28112 | ".real", | ||
|
r26989 | "Should have completed on a[0].r: %s", | ||
Completion(5, 6, "real"), | ||||
|
r25101 | ) | ||
|
r25099 | |||
|
r26989 | _( | ||
"a[0].from_", | ||||
10, | ||||
|
r28112 | ".from_bytes", | ||
|
r26989 | "Should have completed on a[0].from_: %s", | ||
Completion(5, 10, "from_bytes"), | ||||
|
r25246 | ) | ||
|
r28112 | _( | ||
"assert str.star", | ||||
14, | ||||
"str.startswith", | ||||
"Should have completed on `assert str.star`: %s", | ||||
Completion(11, 14, "startswith"), | ||||
) | ||||
_( | ||||
"d['a b'].str", | ||||
12, | ||||
".strip", | ||||
"Should have completed on `d['a b'].str`: %s", | ||||
Completion(9, 12, "strip"), | ||||
) | ||||
|
r25099 | |||
def test_omit__names(self): | ||||
# also happens to test IPCompleter as a configurable | ||||
ip = get_ipython() | ||||
ip._hidden_attr = 1 | ||||
ip._x = {} | ||||
c = ip.Completer | ||||
|
r25101 | ip.ex("ip=get_ipython()") | ||
|
r25099 | cfg = Config() | ||
cfg.IPCompleter.omit__names = 0 | ||||
c.update_config(cfg) | ||||
with provisionalcompleter(): | ||||
c.use_jedi = False | ||||
|
r25101 | s, matches = c.complete("ip.") | ||
|
r26888 | self.assertIn("ip.__str__", matches) | ||
self.assertIn("ip._hidden_attr", matches) | ||||
|
r22292 | |||
|
r25099 | # c.use_jedi = True | ||
# completions = set(c.completions('ip.', 3)) | ||||
|
r26888 | # self.assertIn(Completion(3, 3, '__str__'), completions) | ||
# self.assertIn(Completion(3,3, "_hidden_attr"), completions) | ||||
|
r22292 | |||
|
r25099 | cfg = Config() | ||
cfg.IPCompleter.omit__names = 1 | ||||
c.update_config(cfg) | ||||
with provisionalcompleter(): | ||||
c.use_jedi = False | ||||
|
r25101 | s, matches = c.complete("ip.") | ||
|
r26888 | self.assertNotIn("ip.__str__", matches) | ||
# self.assertIn('ip._hidden_attr', matches) | ||||
|
r25099 | |||
# c.use_jedi = True | ||||
# completions = set(c.completions('ip.', 3)) | ||||
|
r26888 | # self.assertNotIn(Completion(3,3,'__str__'), completions) | ||
# self.assertIn(Completion(3,3, "_hidden_attr"), completions) | ||||
|
r25099 | |||
cfg = Config() | ||||
cfg.IPCompleter.omit__names = 2 | ||||
c.update_config(cfg) | ||||
with provisionalcompleter(): | ||||
c.use_jedi = False | ||||
|
r25101 | s, matches = c.complete("ip.") | ||
|
r26888 | self.assertNotIn("ip.__str__", matches) | ||
self.assertNotIn("ip._hidden_attr", matches) | ||||
|
r6511 | |||
|
r25099 | # c.use_jedi = True | ||
# completions = set(c.completions('ip.', 3)) | ||||
|
r26888 | # self.assertNotIn(Completion(3,3,'__str__'), completions) | ||
# self.assertNotIn(Completion(3,3, "_hidden_attr"), completions) | ||||
|
r24128 | |||
|
r25099 | with provisionalcompleter(): | ||
c.use_jedi = False | ||||
|
r25101 | s, matches = c.complete("ip._x.") | ||
|
r26888 | self.assertIn("ip._x.keys", matches) | ||
|
r23284 | |||
|
r25099 | # c.use_jedi = True | ||
# completions = set(c.completions('ip._x.', 6)) | ||||
|
r26888 | # self.assertIn(Completion(6,6, "keys"), completions) | ||
|
r23284 | |||
|
r25099 | del ip._hidden_attr | ||
del ip._x | ||||
|
r24128 | |||
|
r25099 | def test_limit_to__all__False_ok(self): | ||
""" | ||||
Limit to all is deprecated, once we remove it this test can go away. | ||||
""" | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
|
r24128 | c.use_jedi = False | ||
|
r25101 | ip.ex("class D: x=24") | ||
ip.ex("d=D()") | ||||
|
r25099 | cfg = Config() | ||
cfg.IPCompleter.limit_to__all__ = False | ||||
c.update_config(cfg) | ||||
|
r25101 | s, matches = c.complete("d.") | ||
|
r26888 | self.assertIn("d.x", matches) | ||
|
r23284 | |||
|
r25099 | def test_get__all__entries_ok(self): | ||
|
r25100 | class A: | ||
|
r25101 | __all__ = ["x", 1] | ||
|
r6308 | |||
|
r25101 | words = completer.get__all__entries(A()) | ||
|
r26888 | self.assertEqual(words, ["x"]) | ||
|
r6312 | |||
|
r25099 | def test_get__all__entries_no__all__ok(self): | ||
|
r25100 | class A: | ||
|
r25099 | pass | ||
|
r25101 | |||
|
r25099 | words = completer.get__all__entries(A()) | ||
|
r26888 | self.assertEqual(words, []) | ||
|
r6312 | |||
|
r25099 | def test_func_kw_completions(self): | ||
ip = get_ipython() | ||||
c = ip.Completer | ||||
c.use_jedi = False | ||||
|
r25101 | ip.ex("def myfunc(a=1,b=2): return a+b") | ||
s, matches = c.complete(None, "myfunc(1,b") | ||||
|
r26888 | self.assertIn("b=", matches) | ||
|
r25099 | # Simulate completing with cursor right after b (pos==10): | ||
|
r25101 | s, matches = c.complete(None, "myfunc(1,b)", 10) | ||
|
r26888 | self.assertIn("b=", matches) | ||
|
r25099 | s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b') | ||
|
r26888 | self.assertIn("b=", matches) | ||
|
r25101 | # builtin function | ||
s, matches = c.complete(None, "min(k, k") | ||||
|
r26888 | self.assertIn("key=", matches) | ||
|
r25099 | |||
def test_default_arguments_from_docstring(self): | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
|
r25101 | kwd = c._default_arguments_from_docstring("min(iterable[, key=func]) -> value") | ||
|
r26888 | self.assertEqual(kwd, ["key"]) | ||
|
r25101 | # with cython type etc | ||
|
r25099 | kwd = c._default_arguments_from_docstring( | ||
|
r25101 | "Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n" | ||
) | ||||
|
r26888 | self.assertEqual(kwd, ["ncall", "resume", "nsplit"]) | ||
|
r25101 | # white spaces | ||
|
r25099 | kwd = c._default_arguments_from_docstring( | ||
|
r25101 | "\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n" | ||
) | ||||
|
r26888 | self.assertEqual(kwd, ["ncall", "resume", "nsplit"]) | ||
|
r25099 | |||
def test_line_magics(self): | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
|
r25101 | s, matches = c.complete(None, "lsmag") | ||
|
r26888 | self.assertIn("%lsmagic", matches) | ||
|
r25101 | s, matches = c.complete(None, "%lsmag") | ||
|
r26888 | self.assertIn("%lsmagic", matches) | ||
|
r25099 | |||
def test_cell_magics(self): | ||||
from IPython.core.magic import register_cell_magic | ||||
@register_cell_magic | ||||
def _foo_cellm(line, cell): | ||||
pass | ||||
|
r25101 | |||
|
r25099 | ip = get_ipython() | ||
c = ip.Completer | ||||
|
r6511 | |||
|
r25101 | s, matches = c.complete(None, "_foo_ce") | ||
|
r26888 | self.assertIn("%%_foo_cellm", matches) | ||
|
r25101 | s, matches = c.complete(None, "%%_foo_ce") | ||
|
r26888 | self.assertIn("%%_foo_cellm", matches) | ||
|
r6511 | |||
|
r25099 | def test_line_cell_magics(self): | ||
from IPython.core.magic import register_line_cell_magic | ||||
|
r6511 | |||
|
r25099 | @register_line_cell_magic | ||
def _bar_cellm(line, cell): | ||||
pass | ||||
|
r25101 | |||
|
r25099 | ip = get_ipython() | ||
c = ip.Completer | ||||
# The policy here is trickier, see comments in completion code. The | ||||
# returned values depend on whether the user passes %% or not explicitly, | ||||
# and this will show a difference if the same name is both a line and cell | ||||
# magic. | ||||
|
r25101 | s, matches = c.complete(None, "_bar_ce") | ||
|
r26888 | self.assertIn("%_bar_cellm", matches) | ||
self.assertIn("%%_bar_cellm", matches) | ||||
|
r25101 | s, matches = c.complete(None, "%_bar_ce") | ||
|
r26888 | self.assertIn("%_bar_cellm", matches) | ||
self.assertIn("%%_bar_cellm", matches) | ||||
|
r25101 | s, matches = c.complete(None, "%%_bar_ce") | ||
|
r26888 | self.assertNotIn("%_bar_cellm", matches) | ||
self.assertIn("%%_bar_cellm", matches) | ||||
|
r25099 | |||
def test_magic_completion_order(self): | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
# Test ordering of line and cell magics. | ||||
text, matches = c.complete("timeit") | ||||
|
r26888 | self.assertEqual(matches, ["%timeit", "%%timeit"]) | ||
|
r25099 | |||
def test_magic_completion_shadowing(self): | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
c.use_jedi = False | ||||
|
r6991 | |||
|
r25099 | # Before importing matplotlib, %matplotlib magic should be the only option. | ||
text, matches = c.complete("mat") | ||||
|
r26888 | self.assertEqual(matches, ["%matplotlib"]) | ||
|
r25099 | |||
# The newly introduced name should shadow the magic. | ||||
ip.run_cell("matplotlib = 1") | ||||
text, matches = c.complete("mat") | ||||
|
r26888 | self.assertEqual(matches, ["matplotlib"]) | ||
|
r25099 | |||
# After removing matplotlib from namespace, the magic should again be | ||||
# the only option. | ||||
del ip.user_ns["matplotlib"] | ||||
text, matches = c.complete("mat") | ||||
|
r26888 | self.assertEqual(matches, ["%matplotlib"]) | ||
|
r25099 | |||
def test_magic_completion_shadowing_explicit(self): | ||||
""" | ||||
If the user try to complete a shadowed magic, and explicit % start should | ||||
still return the completions. | ||||
""" | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
# Before importing matplotlib, %matplotlib magic should be the only option. | ||||
text, matches = c.complete("%mat") | ||||
|
r26888 | self.assertEqual(matches, ["%matplotlib"]) | ||
|
r25099 | |||
ip.run_cell("matplotlib = 1") | ||||
# After removing matplotlib from namespace, the magic should still be | ||||
# the only option. | ||||
text, matches = c.complete("%mat") | ||||
|
r26888 | self.assertEqual(matches, ["%matplotlib"]) | ||
|
r25099 | |||
def test_magic_config(self): | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
|
r25101 | s, matches = c.complete(None, "conf") | ||
|
r26888 | self.assertIn("%config", matches) | ||
|
r25101 | s, matches = c.complete(None, "conf") | ||
|
r26888 | self.assertNotIn("AliasManager", matches) | ||
|
r25101 | s, matches = c.complete(None, "config ") | ||
|
r26888 | self.assertIn("AliasManager", matches) | ||
|
r25101 | s, matches = c.complete(None, "%config ") | ||
|
r26888 | self.assertIn("AliasManager", matches) | ||
|
r25101 | s, matches = c.complete(None, "config Ali") | ||
|
r26888 | self.assertListEqual(["AliasManager"], matches) | ||
|
r25101 | s, matches = c.complete(None, "%config Ali") | ||
|
r26888 | self.assertListEqual(["AliasManager"], matches) | ||
|
r25101 | s, matches = c.complete(None, "config AliasManager") | ||
|
r26888 | self.assertListEqual(["AliasManager"], matches) | ||
|
r25101 | s, matches = c.complete(None, "%config AliasManager") | ||
|
r26888 | self.assertListEqual(["AliasManager"], matches) | ||
|
r25101 | s, matches = c.complete(None, "config AliasManager.") | ||
|
r26888 | self.assertIn("AliasManager.default_aliases", matches) | ||
|
r25101 | s, matches = c.complete(None, "%config AliasManager.") | ||
|
r26888 | self.assertIn("AliasManager.default_aliases", matches) | ||
|
r25101 | s, matches = c.complete(None, "config AliasManager.de") | ||
|
r26888 | self.assertListEqual(["AliasManager.default_aliases"], matches) | ||
|
r25101 | s, matches = c.complete(None, "config AliasManager.de") | ||
|
r26888 | self.assertListEqual(["AliasManager.default_aliases"], matches) | ||
|
r25099 | |||
def test_magic_color(self): | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
|
r25101 | s, matches = c.complete(None, "colo") | ||
|
r26888 | self.assertIn("%colors", matches) | ||
|
r25101 | s, matches = c.complete(None, "colo") | ||
|
r26888 | self.assertNotIn("NoColor", matches) | ||
|
r25101 | s, matches = c.complete(None, "%colors") # No trailing space | ||
|
r26888 | self.assertNotIn("NoColor", matches) | ||
|
r25101 | s, matches = c.complete(None, "colors ") | ||
|
r26888 | self.assertIn("NoColor", matches) | ||
|
r25101 | s, matches = c.complete(None, "%colors ") | ||
|
r26888 | self.assertIn("NoColor", matches) | ||
|
r25101 | s, matches = c.complete(None, "colors NoCo") | ||
|
r26888 | self.assertListEqual(["NoColor"], matches) | ||
|
r25101 | s, matches = c.complete(None, "%colors NoCo") | ||
|
r26888 | self.assertListEqual(["NoColor"], matches) | ||
|
r25099 | |||
def test_match_dict_keys(self): | ||||
""" | ||||
Test that match_dict_keys works on a couple of use case does return what | ||||
expected, and does not crash | ||||
""" | ||||
|
r25101 | delims = " \t\n`!@#$^&*()=+[{]}\\|;:'\",<>?" | ||
|
r25099 | |||
|
r27912 | def match(*args, **kwargs): | ||
|
r27916 | quote, offset, matches = match_dict_keys(*args, delims=delims, **kwargs) | ||
|
r27912 | return quote, offset, list(matches) | ||
|
r25101 | keys = ["foo", b"far"] | ||
|
r27916 | assert match(keys, "b'") == ("'", 2, ["far"]) | ||
assert match(keys, "b'f") == ("'", 2, ["far"]) | ||||
assert match(keys, 'b"') == ('"', 2, ["far"]) | ||||
assert match(keys, 'b"f') == ('"', 2, ["far"]) | ||||
|
r25099 | |||
|
r27916 | assert match(keys, "'") == ("'", 1, ["foo"]) | ||
assert match(keys, "'f") == ("'", 1, ["foo"]) | ||||
assert match(keys, '"') == ('"', 1, ["foo"]) | ||||
assert match(keys, '"f') == ('"', 1, ["foo"]) | ||||
|
r27912 | |||
# Completion on first item of tuple | ||||
|
r27913 | keys = [("foo", 1111), ("foo", 2222), (3333, "bar"), (3333, "test")] | ||
|
r27916 | assert match(keys, "'f") == ("'", 1, ["foo"]) | ||
assert match(keys, "33") == ("", 0, ["3333"]) | ||||
|
r27912 | |||
# Completion on numbers | ||||
|
r27916 | keys = [ | ||
0xDEADBEEF, | ||||
1111, | ||||
1234, | ||||
"1999", | ||||
0b10101, | ||||
22, | ||||
] # 0xDEADBEEF = 3735928559; 0b10101 = 21 | ||||
assert match(keys, "0xdead") == ("", 0, ["0xdeadbeef"]) | ||||
assert match(keys, "1") == ("", 0, ["1111", "1234"]) | ||||
assert match(keys, "2") == ("", 0, ["21", "22"]) | ||||
assert match(keys, "0b101") == ("", 0, ["0b10101", "0b10110"]) | ||||
|
r25099 | |||
|
r27927 | # Should yield on variables | ||
assert match(keys, "a_variable") == ("", 0, []) | ||||
# Should pass over invalid literals | ||||
assert match(keys, "'' ''") == ("", 0, []) | ||||
|
r25851 | def test_match_dict_keys_tuple(self): | ||
""" | ||||
Test that match_dict_keys called with extra prefix works on a couple of use case, | ||||
does return what expected, and does not crash. | ||||
""" | ||||
delims = " \t\n`!@#$^&*()=+[{]}\\|;:'\",<>?" | ||||
|
r27906 | |||
|
r25851 | keys = [("foo", "bar"), ("foo", "oof"), ("foo", b"bar"), ('other', 'test')] | ||
|
r27916 | def match(*args, extra=None, **kwargs): | ||
quote, offset, matches = match_dict_keys( | ||||
*args, delims=delims, extra_prefix=extra, **kwargs | ||||
) | ||||
|
r27912 | return quote, offset, list(matches) | ||
|
r25851 | # Completion on first key == "foo" | ||
|
r27916 | assert match(keys, "'", extra=("foo",)) == ("'", 1, ["bar", "oof"]) | ||
assert match(keys, '"', extra=("foo",)) == ('"', 1, ["bar", "oof"]) | ||||
assert match(keys, "'o", extra=("foo",)) == ("'", 1, ["oof"]) | ||||
assert match(keys, '"o', extra=("foo",)) == ('"', 1, ["oof"]) | ||||
assert match(keys, "b'", extra=("foo",)) == ("'", 2, ["bar"]) | ||||
assert match(keys, 'b"', extra=("foo",)) == ('"', 2, ["bar"]) | ||||
assert match(keys, "b'b", extra=("foo",)) == ("'", 2, ["bar"]) | ||||
assert match(keys, 'b"b', extra=("foo",)) == ('"', 2, ["bar"]) | ||||
|
r25851 | |||
# No Completion | ||||
|
r27916 | assert match(keys, "'", extra=("no_foo",)) == ("'", 1, []) | ||
assert match(keys, "'", extra=("fo",)) == ("'", 1, []) | ||||
|
r25851 | |||
|
r27913 | keys = [("foo1", "foo2", "foo3", "foo4"), ("foo1", "foo2", "bar", "foo4")] | ||
|
r27916 | assert match(keys, "'foo", extra=("foo1",)) == ("'", 1, ["foo2"]) | ||
assert match(keys, "'foo", extra=("foo1", "foo2")) == ("'", 1, ["foo3"]) | ||||
assert match(keys, "'foo", extra=("foo1", "foo2", "foo3")) == ("'", 1, ["foo4"]) | ||||
assert match(keys, "'foo", extra=("foo1", "foo2", "foo3", "foo4")) == ( | ||||
|
r27913 | "'", | ||
1, | ||||
|
r27916 | [], | ||
|
r27913 | ) | ||
|
r27912 | |||
keys = [("foo", 1111), ("foo", "2222"), (3333, "bar"), (3333, 4444)] | ||||
|
r27916 | assert match(keys, "'", extra=("foo",)) == ("'", 1, ["2222"]) | ||
assert match(keys, "", extra=("foo",)) == ("", 0, ["1111", "'2222'"]) | ||||
assert match(keys, "'", extra=(3333,)) == ("'", 1, ["bar"]) | ||||
assert match(keys, "", extra=(3333,)) == ("", 0, ["'bar'", "4444"]) | ||||
assert match(keys, "'", extra=("3333",)) == ("'", 1, []) | ||||
assert match(keys, "33") == ("", 0, ["3333"]) | ||||
|
r27912 | |||
def test_dict_key_completion_closures(self): | ||||
ip = get_ipython() | ||||
complete = ip.Completer.complete | ||||
ip.Completer.auto_close_dict_keys = True | ||||
|
r25851 | |||
|
r27912 | ip.user_ns["d"] = { | ||
# tuple only | ||||
|
r27913 | ("aa", 11): None, | ||
|
r27912 | # tuple and non-tuple | ||
|
r27913 | ("bb", 22): None, | ||
"bb": None, | ||||
|
r27912 | # non-tuple only | ||
|
r27913 | "cc": None, | ||
|
r27912 | # numeric tuple only | ||
|
r27913 | (77, "x"): None, | ||
|
r27912 | # numeric tuple and non-tuple | ||
|
r27913 | (88, "y"): None, | ||
|
r27912 | 88: None, | ||
# numeric non-tuple only | ||||
99: None, | ||||
} | ||||
_, matches = complete(line_buffer="d[") | ||||
# should append `, ` if matches a tuple only | ||||
self.assertIn("'aa', ", matches) | ||||
# should not append anything if matches a tuple and an item | ||||
self.assertIn("'bb'", matches) | ||||
# should append `]` if matches and item only | ||||
self.assertIn("'cc']", matches) | ||||
# should append `, ` if matches a tuple only | ||||
self.assertIn("77, ", matches) | ||||
# should not append anything if matches a tuple and an item | ||||
self.assertIn("88", matches) | ||||
# should append `]` if matches and item only | ||||
self.assertIn("99]", matches) | ||||
_, matches = complete(line_buffer="d['aa', ") | ||||
# should restrict matches to those matching tuple prefix | ||||
self.assertIn("11]", matches) | ||||
self.assertNotIn("'bb'", matches) | ||||
self.assertNotIn("'bb', ", matches) | ||||
self.assertNotIn("'bb']", matches) | ||||
self.assertNotIn("'cc'", matches) | ||||
self.assertNotIn("'cc', ", matches) | ||||
self.assertNotIn("'cc']", matches) | ||||
ip.Completer.auto_close_dict_keys = False | ||||
|
r27906 | |||
|
r25099 | def test_dict_key_completion_string(self): | ||
"""Test dictionary key completion for string keys""" | ||||
ip = get_ipython() | ||||
complete = ip.Completer.complete | ||||
|
r6991 | |||
|
r25101 | ip.user_ns["d"] = {"abc": None} | ||
|
r6991 | |||
|
r25099 | # check completion at different stages | ||
_, matches = complete(line_buffer="d[") | ||||
|
r26888 | self.assertIn("'abc'", matches) | ||
self.assertNotIn("'abc']", matches) | ||||
|
r6991 | |||
|
r25099 | _, matches = complete(line_buffer="d['") | ||
|
r26888 | self.assertIn("abc", matches) | ||
self.assertNotIn("abc']", matches) | ||||
|
r6991 | |||
|
r25099 | _, matches = complete(line_buffer="d['a") | ||
|
r26888 | self.assertIn("abc", matches) | ||
self.assertNotIn("abc']", matches) | ||||
|
r13344 | |||
|
r25099 | # check use of different quoting | ||
|
r25101 | _, matches = complete(line_buffer='d["') | ||
|
r26888 | self.assertIn("abc", matches) | ||
self.assertNotIn('abc"]', matches) | ||||
|
r13344 | |||
|
r25101 | _, matches = complete(line_buffer='d["a') | ||
|
r26888 | self.assertIn("abc", matches) | ||
self.assertNotIn('abc"]', matches) | ||||
|
r13344 | |||
|
r25099 | # check sensitivity to following context | ||
_, matches = complete(line_buffer="d[]", cursor_pos=2) | ||||
|
r26888 | self.assertIn("'abc'", matches) | ||
|
r23898 | |||
|
r25099 | _, matches = complete(line_buffer="d['']", cursor_pos=3) | ||
|
r26888 | self.assertIn("abc", matches) | ||
self.assertNotIn("abc'", matches) | ||||
self.assertNotIn("abc']", matches) | ||||
|
r23898 | |||
|
r25099 | # check multiple solutions are correctly returned and that noise is not | ||
|
r25101 | ip.user_ns["d"] = { | ||
"abc": None, | ||||
"abd": None, | ||||
"bad": None, | ||||
object(): None, | ||||
5: None, | ||||
|
r25852 | ("abe", None): None, | ||
(None, "abf"): None | ||||
|
r25101 | } | ||
|
r23898 | |||
|
r25099 | _, matches = complete(line_buffer="d['a") | ||
|
r26888 | self.assertIn("abc", matches) | ||
self.assertIn("abd", matches) | ||||
self.assertNotIn("bad", matches) | ||||
self.assertNotIn("abe", matches) | ||||
self.assertNotIn("abf", matches) | ||||
|
r25101 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches | ||
|
r25099 | |||
# check escaping and whitespace | ||||
|
r25101 | ip.user_ns["d"] = {"a\nb": None, "a'b": None, 'a"b': None, "a word": None} | ||
|
r25099 | _, matches = complete(line_buffer="d['a") | ||
|
r26888 | self.assertIn("a\\nb", matches) | ||
self.assertIn("a\\'b", matches) | ||||
self.assertIn('a"b', matches) | ||||
self.assertIn("a word", matches) | ||||
|
r25101 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches | ||
|
r25099 | |||
# - can complete on non-initial word of the string | ||||
_, matches = complete(line_buffer="d['a w") | ||||
|
r26888 | self.assertIn("word", matches) | ||
|
r25099 | |||
# - understands quote escaping | ||||
_, matches = complete(line_buffer="d['a\\'") | ||||
|
r26888 | self.assertIn("b", matches) | ||
|
r25099 | |||
# - default quoting should work like repr | ||||
_, matches = complete(line_buffer="d[") | ||||
|
r26888 | self.assertIn('"a\'b"', matches) | ||
|
r25099 | |||
# - when opening quote with ", possible to match with unescaped apostrophe | ||||
_, matches = complete(line_buffer="d[\"a'") | ||||
|
r26888 | self.assertIn("b", matches) | ||
|
r25099 | |||
# need to not split at delims that readline won't split at | ||||
|
r25101 | if "-" not in ip.Completer.splitter.delims: | ||
ip.user_ns["d"] = {"before-after": None} | ||||
|
r25099 | _, matches = complete(line_buffer="d['before-af") | ||
|
r26888 | self.assertIn("before-after", matches) | ||
|
r25099 | |||
|
r25853 | # check completion on tuple-of-string keys at different stage - on first key | ||
ip.user_ns["d"] = {('foo', 'bar'): None} | ||||
_, matches = complete(line_buffer="d[") | ||||
|
r26888 | self.assertIn("'foo'", matches) | ||
self.assertNotIn("'foo']", matches) | ||||
self.assertNotIn("'bar'", matches) | ||||
self.assertNotIn("foo", matches) | ||||
self.assertNotIn("bar", matches) | ||||
|
r25853 | |||
# - match the prefix | ||||
_, matches = complete(line_buffer="d['f") | ||||
|
r26888 | self.assertIn("foo", matches) | ||
self.assertNotIn("foo']", matches) | ||||
self.assertNotIn('foo"]', matches) | ||||
|
r25853 | _, matches = complete(line_buffer="d['foo") | ||
|
r26888 | self.assertIn("foo", matches) | ||
|
r25853 | |||
# - can complete on second key | ||||
_, matches = complete(line_buffer="d['foo', ") | ||||
|
r26888 | self.assertIn("'bar'", matches) | ||
|
r25853 | _, matches = complete(line_buffer="d['foo', 'b") | ||
|
r26888 | self.assertIn("bar", matches) | ||
self.assertNotIn("foo", matches) | ||||
|
r25853 | |||
# - does not propose missing keys | ||||
_, matches = complete(line_buffer="d['foo', 'f") | ||||
|
r26888 | self.assertNotIn("bar", matches) | ||
self.assertNotIn("foo", matches) | ||||
|
r25853 | |||
# check sensitivity to following context | ||||
_, matches = complete(line_buffer="d['foo',]", cursor_pos=8) | ||||
|
r26888 | self.assertIn("'bar'", matches) | ||
self.assertNotIn("bar", matches) | ||||
self.assertNotIn("'foo'", matches) | ||||
self.assertNotIn("foo", matches) | ||||
|
r25853 | |||
_, matches = complete(line_buffer="d['']", cursor_pos=3) | ||||
|
r26888 | self.assertIn("foo", matches) | ||
|
r25853 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches | ||
_, matches = complete(line_buffer='d[""]', cursor_pos=3) | ||||
|
r26888 | self.assertIn("foo", matches) | ||
|
r25853 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches | ||
_, matches = complete(line_buffer='d["foo","]', cursor_pos=9) | ||||
|
r26888 | self.assertIn("bar", matches) | ||
|
r25853 | assert not any(m.endswith(("]", '"', "'")) for m in matches), matches | ||
_, matches = complete(line_buffer='d["foo",]', cursor_pos=8) | ||||
|
r26888 | self.assertIn("'bar'", matches) | ||
self.assertNotIn("bar", matches) | ||||
|
r25853 | |||
# Can complete with longer tuple keys | ||||
ip.user_ns["d"] = {('foo', 'bar', 'foobar'): None} | ||||
# - can complete second key | ||||
_, matches = complete(line_buffer="d['foo', 'b") | ||||
|
r26888 | self.assertIn("bar", matches) | ||
self.assertNotIn("foo", matches) | ||||
self.assertNotIn("foobar", matches) | ||||
|
r25853 | |||
# - can complete third key | ||||
_, matches = complete(line_buffer="d['foo', 'bar', 'fo") | ||||
|
r26888 | self.assertIn("foobar", matches) | ||
self.assertNotIn("foo", matches) | ||||
self.assertNotIn("bar", matches) | ||||
|
r25853 | |||
|
r27912 | def test_dict_key_completion_numbers(self): | ||
ip = get_ipython() | ||||
complete = ip.Completer.complete | ||||
ip.user_ns["d"] = { | ||||
|
r27913 | 0xDEADBEEF: None, # 3735928559 | ||
|
r27912 | 1111: None, | ||
1234: None, | ||||
"1999": None, | ||||
|
r27913 | 0b10101: None, # 21 | ||
22: None, | ||||
|
r27912 | } | ||
_, matches = complete(line_buffer="d[1") | ||||
self.assertIn("1111", matches) | ||||
self.assertIn("1234", matches) | ||||
self.assertNotIn("1999", matches) | ||||
self.assertNotIn("'1999'", matches) | ||||
_, matches = complete(line_buffer="d[0xdead") | ||||
self.assertIn("0xdeadbeef", matches) | ||||
_, matches = complete(line_buffer="d[2") | ||||
self.assertIn("21", matches) | ||||
self.assertIn("22", matches) | ||||
_, matches = complete(line_buffer="d[0b101") | ||||
self.assertIn("0b10101", matches) | ||||
self.assertIn("0b10110", matches) | ||||
|
r25099 | def test_dict_key_completion_contexts(self): | ||
"""Test expression contexts in which dict key completion occurs""" | ||||
ip = get_ipython() | ||||
complete = ip.Completer.complete | ||||
|
r25101 | d = {"abc": None} | ||
ip.user_ns["d"] = d | ||||
|
r25099 | |||
class C: | ||||
data = d | ||||
|
r25101 | |||
ip.user_ns["C"] = C | ||||
ip.user_ns["get"] = lambda: d | ||||
|
r27913 | ip.user_ns["nested"] = {"x": d} | ||
|
r25099 | |||
def assert_no_completion(**kwargs): | ||||
_, matches = complete(**kwargs) | ||||
|
r26888 | self.assertNotIn("abc", matches) | ||
self.assertNotIn("abc'", matches) | ||||
self.assertNotIn("abc']", matches) | ||||
self.assertNotIn("'abc'", matches) | ||||
self.assertNotIn("'abc']", matches) | ||||
|
r25099 | |||
def assert_completion(**kwargs): | ||||
_, matches = complete(**kwargs) | ||||
|
r26888 | self.assertIn("'abc'", matches) | ||
self.assertNotIn("'abc']", matches) | ||||
|
r25099 | |||
# no completion after string closed, even if reopened | ||||
assert_no_completion(line_buffer="d['a'") | ||||
|
r25101 | assert_no_completion(line_buffer='d["a"') | ||
|
r25099 | assert_no_completion(line_buffer="d['a' + ") | ||
assert_no_completion(line_buffer="d['a' + '") | ||||
# completion in non-trivial expressions | ||||
assert_completion(line_buffer="+ d[") | ||||
assert_completion(line_buffer="(d[") | ||||
assert_completion(line_buffer="C.data[") | ||||
|
r27906 | # nested dict completion | ||
assert_completion(line_buffer="nested['x'][") | ||||
|
r27915 | with evaluation_policy("minimal"): | ||
|
r27906 | with pytest.raises(AssertionError): | ||
assert_completion(line_buffer="nested['x'][") | ||||
|
r25099 | # greedy flag | ||
def assert_completion(**kwargs): | ||||
_, matches = complete(**kwargs) | ||||
|
r26888 | self.assertIn("get()['abc']", matches) | ||
|
r25101 | |||
|
r25099 | assert_no_completion(line_buffer="get()[") | ||
with greedy_completion(): | ||||
assert_completion(line_buffer="get()[") | ||||
assert_completion(line_buffer="get()['") | ||||
assert_completion(line_buffer="get()['a") | ||||
assert_completion(line_buffer="get()['ab") | ||||
assert_completion(line_buffer="get()['abc") | ||||
|
r23322 | |||
|
r25099 | def test_dict_key_completion_bytes(self): | ||
"""Test handling of bytes in dict key completion""" | ||||
ip = get_ipython() | ||||
complete = ip.Completer.complete | ||||
|
r15766 | |||
|
r25101 | ip.user_ns["d"] = {"abc": None, b"abd": None} | ||
|
r15766 | |||
|
r25099 | _, matches = complete(line_buffer="d[") | ||
|
r26888 | self.assertIn("'abc'", matches) | ||
self.assertIn("b'abd'", matches) | ||||
|
r15766 | |||
|
r25099 | if False: # not currently implemented | ||
_, matches = complete(line_buffer="d[b") | ||||
|
r26888 | self.assertIn("b'abd'", matches) | ||
self.assertNotIn("b'abc'", matches) | ||||
|
r15766 | |||
|
r25099 | _, matches = complete(line_buffer="d[b'") | ||
|
r26888 | self.assertIn("abd", matches) | ||
self.assertNotIn("abc", matches) | ||||
|
r15766 | |||
|
r25099 | _, matches = complete(line_buffer="d[B'") | ||
|
r26888 | self.assertIn("abd", matches) | ||
self.assertNotIn("abc", matches) | ||||
|
r15766 | |||
|
r25099 | _, matches = complete(line_buffer="d['") | ||
|
r26888 | self.assertIn("abc", matches) | ||
self.assertNotIn("abd", matches) | ||||
|
r15766 | |||
|
r25099 | def test_dict_key_completion_unicode_py3(self): | ||
"""Test handling of unicode in dict key completion""" | ||||
ip = get_ipython() | ||||
complete = ip.Completer.complete | ||||
|
r15773 | |||
|
r25101 | ip.user_ns["d"] = {"a\u05d0": None} | ||
|
r15773 | |||
|
r16564 | # query using escape | ||
|
r25101 | if sys.platform != "win32": | ||
|
r25099 | # Known failure on Windows | ||
_, matches = complete(line_buffer="d['a\\u05d0") | ||||
|
r26888 | self.assertIn("u05d0", matches) # tokenized after \\ | ||
|
r16564 | |||
# query using character | ||||
_, matches = complete(line_buffer="d['a\u05d0") | ||||
|
r26888 | self.assertIn("a\u05d0", matches) | ||
|
r25101 | |||
|
r25099 | with greedy_completion(): | ||
# query using escape | ||||
_, matches = complete(line_buffer="d['a\\u05d0") | ||||
|
r26888 | self.assertIn("d['a\\u05d0']", matches) # tokenized after \\ | ||
|
r25099 | |||
# query using character | ||||
_, matches = complete(line_buffer="d['a\u05d0") | ||||
|
r26888 | self.assertIn("d['a\u05d0']", matches) | ||
|
r25099 | |||
|
r25101 | @dec.skip_without("numpy") | ||
|
r25099 | def test_struct_array_key_completion(self): | ||
"""Test dict key completion applies to numpy struct arrays""" | ||||
import numpy | ||||
|
r25101 | |||
|
r25099 | ip = get_ipython() | ||
complete = ip.Completer.complete | ||||
|
r25101 | ip.user_ns["d"] = numpy.array([], dtype=[("hello", "f"), ("world", "f")]) | ||
|
r25099 | _, matches = complete(line_buffer="d['") | ||
|
r26888 | self.assertIn("hello", matches) | ||
self.assertIn("world", matches) | ||||
|
r25099 | # complete on the numpy struct itself | ||
|
r25101 | dt = numpy.dtype( | ||
[("my_head", [("my_dt", ">u4"), ("my_df", ">u4")]), ("my_data", ">f4", 5)] | ||||
) | ||||
|
r25099 | x = numpy.zeros(2, dtype=dt) | ||
|
r25101 | ip.user_ns["d"] = x[1] | ||
|
r25099 | _, matches = complete(line_buffer="d['") | ||
|
r26888 | self.assertIn("my_head", matches) | ||
self.assertIn("my_data", matches) | ||||
|
r27913 | |||
|
r27906 | def completes_on_nested(): | ||
|
r25101 | ip.user_ns["d"] = numpy.zeros(2, dtype=dt) | ||
|
r25099 | _, matches = complete(line_buffer="d[1]['my_head']['") | ||
|
r26888 | self.assertTrue(any(["my_dt" in m for m in matches])) | ||
self.assertTrue(any(["my_df" in m for m in matches])) | ||||
|
r27906 | # complete on a nested level | ||
with greedy_completion(): | ||||
completes_on_nested() | ||||
|
r27915 | with evaluation_policy("limited"): | ||
|
r27906 | completes_on_nested() | ||
|
r27915 | with evaluation_policy("minimal"): | ||
|
r27906 | with pytest.raises(AssertionError): | ||
completes_on_nested() | ||||
|
r25099 | |||
|
r25101 | @dec.skip_without("pandas") | ||
|
r25099 | def test_dataframe_key_completion(self): | ||
"""Test dict key completion applies to pandas DataFrames""" | ||||
import pandas | ||||
|
r25101 | |||
|
r25099 | ip = get_ipython() | ||
complete = ip.Completer.complete | ||||
|
r25101 | ip.user_ns["d"] = pandas.DataFrame({"hello": [1], "world": [2]}) | ||
|
r25099 | _, matches = complete(line_buffer="d['") | ||
|
r26888 | self.assertIn("hello", matches) | ||
self.assertIn("world", matches) | ||||
|
r27906 | _, matches = complete(line_buffer="d.loc[:, '") | ||
self.assertIn("hello", matches) | ||||
self.assertIn("world", matches) | ||||
_, matches = complete(line_buffer="d.loc[1:, '") | ||||
self.assertIn("hello", matches) | ||||
_, matches = complete(line_buffer="d.loc[1:1, '") | ||||
self.assertIn("hello", matches) | ||||
_, matches = complete(line_buffer="d.loc[1:1:-1, '") | ||||
self.assertIn("hello", matches) | ||||
_, matches = complete(line_buffer="d.loc[::, '") | ||||
self.assertIn("hello", matches) | ||||
|
r25099 | |||
def test_dict_key_completion_invalids(self): | ||||
"""Smoke test cases dict key completion can't handle""" | ||||
ip = get_ipython() | ||||
complete = ip.Completer.complete | ||||
|
r25101 | ip.user_ns["no_getitem"] = None | ||
ip.user_ns["no_keys"] = [] | ||||
ip.user_ns["cant_call_keys"] = dict | ||||
ip.user_ns["empty"] = {} | ||||
ip.user_ns["d"] = {"abc": 5} | ||||
|
r25099 | |||
_, matches = complete(line_buffer="no_getitem['") | ||||
_, matches = complete(line_buffer="no_keys['") | ||||
_, matches = complete(line_buffer="cant_call_keys['") | ||||
_, matches = complete(line_buffer="empty['") | ||||
_, matches = complete(line_buffer="name_error['") | ||||
_, matches = complete(line_buffer="d['\\") # incomplete escape | ||||
def test_object_key_completion(self): | ||||
ip = get_ipython() | ||||
|
r25101 | ip.user_ns["key_completable"] = KeyCompletable(["qwerty", "qwick"]) | ||
|
r25099 | |||
_, matches = ip.Completer.complete(line_buffer="key_completable['qw") | ||||
|
r26888 | self.assertIn("qwerty", matches) | ||
self.assertIn("qwick", matches) | ||||
|
r25099 | |||
def test_class_key_completion(self): | ||||
ip = get_ipython() | ||||
|
r25101 | NamedInstanceClass("qwerty") | ||
NamedInstanceClass("qwick") | ||||
ip.user_ns["named_instance_class"] = NamedInstanceClass | ||||
|
r25099 | |||
_, matches = ip.Completer.complete(line_buffer="named_instance_class['qw") | ||||
|
r26888 | self.assertIn("qwerty", matches) | ||
self.assertIn("qwick", matches) | ||||
|
r25099 | |||
def test_tryimport(self): | ||||
""" | ||||
Test that try-import don't crash on trailing dot, and import modules before | ||||
""" | ||||
from IPython.core.completerlib import try_import | ||||
|
r25101 | assert try_import("IPython.") | ||
|
r25099 | |||
def test_aimport_module_completer(self): | ||||
ip = get_ipython() | ||||
|
r25101 | _, matches = ip.complete("i", "%aimport i") | ||
|
r26888 | self.assertIn("io", matches) | ||
self.assertNotIn("int", matches) | ||||
|
r25099 | |||
def test_nested_import_module_completer(self): | ||||
ip = get_ipython() | ||||
|
r25101 | _, matches = ip.complete(None, "import IPython.co", 17) | ||
|
r26888 | self.assertIn("IPython.core", matches) | ||
self.assertNotIn("import IPython.core", matches) | ||||
self.assertNotIn("IPython.display", matches) | ||||
|
r25099 | |||
def test_import_module_completer(self): | ||||
ip = get_ipython() | ||||
|
r25101 | _, matches = ip.complete("i", "import i") | ||
|
r26888 | self.assertIn("io", matches) | ||
self.assertNotIn("int", matches) | ||||
|
r25099 | |||
def test_from_module_completer(self): | ||||
ip = get_ipython() | ||||
|
r25101 | _, matches = ip.complete("B", "from io import B", 16) | ||
|
r26888 | self.assertIn("BytesIO", matches) | ||
self.assertNotIn("BaseException", matches) | ||||
|
r25099 | |||
def test_snake_case_completion(self): | ||||
ip = get_ipython() | ||||
ip.Completer.use_jedi = False | ||||
|
r25101 | ip.user_ns["some_three"] = 3 | ||
ip.user_ns["some_four"] = 4 | ||||
|
r25099 | _, matches = ip.complete("s_", "print(s_f") | ||
|
r26888 | self.assertIn("some_three", matches) | ||
self.assertIn("some_four", matches) | ||||
|
r25099 | |||
def test_mix_terms(self): | ||||
ip = get_ipython() | ||||
from textwrap import dedent | ||||
|
r25101 | |||
|
r25099 | ip.Completer.use_jedi = False | ||
|
r25101 | ip.ex( | ||
dedent( | ||||
""" | ||||
|
r25099 | class Test: | ||
def meth(self, meth_arg1): | ||||
print("meth") | ||||
def meth_1(self, meth1_arg1, meth1_arg2): | ||||
print("meth1") | ||||
def meth_2(self, meth2_arg1, meth2_arg2): | ||||
print("meth2") | ||||
test = Test() | ||||
|
r25101 | """ | ||
) | ||||
) | ||||
|
r25099 | _, matches = ip.complete(None, "test.meth(") | ||
|
r26888 | self.assertIn("meth_arg1=", matches) | ||
self.assertNotIn("meth2_arg1=", matches) | ||||
|
r27541 | |||
def test_percent_symbol_restrict_to_magic_completions(self): | ||||
ip = get_ipython() | ||||
completer = ip.Completer | ||||
text = "%a" | ||||
with provisionalcompleter(): | ||||
completer.use_jedi = True | ||||
completions = completer.completions(text, len(text)) | ||||
for c in completions: | ||||
self.assertEqual(c.text[0], "%") | ||||
|
r27775 | |||
|
r27786 | def test_fwd_unicode_restricts(self): | ||
ip = get_ipython() | ||||
completer = ip.Completer | ||||
text = "\\ROMAN NUMERAL FIVE" | ||||
with provisionalcompleter(): | ||||
completer.use_jedi = True | ||||
completions = [ | ||||
completion.text for completion in completer.completions(text, len(text)) | ||||
] | ||||
self.assertEqual(completions, ["\u2164"]) | ||||
|
r27776 | def test_dict_key_restrict_to_dicts(self): | ||
"""Test that dict key suppresses non-dict completion items""" | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
d = {"abc": None} | ||||
ip.user_ns["d"] = d | ||||
text = 'd["a' | ||||
def _(): | ||||
with provisionalcompleter(): | ||||
c.use_jedi = True | ||||
return [ | ||||
completion.text for completion in c.completions(text, len(text)) | ||||
] | ||||
completions = _() | ||||
self.assertEqual(completions, ["abc"]) | ||||
# check that it can be disabled in granular manner: | ||||
cfg = Config() | ||||
cfg.IPCompleter.suppress_competing_matchers = { | ||||
"IPCompleter.dict_key_matcher": False | ||||
} | ||||
c.update_config(cfg) | ||||
completions = _() | ||||
self.assertIn("abc", completions) | ||||
self.assertGreater(len(completions), 1) | ||||
|
r27775 | def test_matcher_suppression(self): | ||
@completion_matcher(identifier="a_matcher") | ||||
def a_matcher(text): | ||||
return ["completion_a"] | ||||
@completion_matcher(identifier="b_matcher", api_version=2) | ||||
def b_matcher(context: CompletionContext): | ||||
text = context.token | ||||
result = {"completions": [SimpleCompletion("completion_b")]} | ||||
if text == "suppress c": | ||||
result["suppress"] = {"c_matcher"} | ||||
if text.startswith("suppress all"): | ||||
result["suppress"] = True | ||||
if text == "suppress all but c": | ||||
result["do_not_suppress"] = {"c_matcher"} | ||||
if text == "suppress all but a": | ||||
result["do_not_suppress"] = {"a_matcher"} | ||||
return result | ||||
@completion_matcher(identifier="c_matcher") | ||||
def c_matcher(text): | ||||
return ["completion_c"] | ||||
with custom_matchers([a_matcher, b_matcher, c_matcher]): | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
def _(text, expected): | ||||
|
r27776 | c.use_jedi = False | ||
s, matches = c.complete(text) | ||||
self.assertEqual(expected, matches) | ||||
|
r27775 | |||
_("do not suppress", ["completion_a", "completion_b", "completion_c"]) | ||||
_("suppress all", ["completion_b"]) | ||||
_("suppress all but a", ["completion_a", "completion_b"]) | ||||
_("suppress all but c", ["completion_b", "completion_c"]) | ||||
|
r27776 | def configure(suppression_config): | ||
cfg = Config() | ||||
cfg.IPCompleter.suppress_competing_matchers = suppression_config | ||||
c.update_config(cfg) | ||||
# test that configuration takes priority over the run-time decisions | ||||
configure(False) | ||||
_("suppress all", ["completion_a", "completion_b", "completion_c"]) | ||||
configure({"b_matcher": False}) | ||||
_("suppress all", ["completion_a", "completion_b", "completion_c"]) | ||||
configure({"a_matcher": False}) | ||||
_("suppress all", ["completion_b"]) | ||||
configure({"b_matcher": True}) | ||||
_("do not suppress", ["completion_b"]) | ||||
|
r27877 | configure(True) | ||
_("do not suppress", ["completion_a"]) | ||||
def test_matcher_suppression_with_iterator(self): | ||||
@completion_matcher(identifier="matcher_returning_iterator") | ||||
def matcher_returning_iterator(text): | ||||
return iter(["completion_iter"]) | ||||
@completion_matcher(identifier="matcher_returning_list") | ||||
def matcher_returning_list(text): | ||||
return ["completion_list"] | ||||
with custom_matchers([matcher_returning_iterator, matcher_returning_list]): | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
def _(text, expected): | ||||
c.use_jedi = False | ||||
s, matches = c.complete(text) | ||||
self.assertEqual(expected, matches) | ||||
def configure(suppression_config): | ||||
cfg = Config() | ||||
cfg.IPCompleter.suppress_competing_matchers = suppression_config | ||||
c.update_config(cfg) | ||||
configure(False) | ||||
_("---", ["completion_iter", "completion_list"]) | ||||
configure(True) | ||||
_("---", ["completion_iter"]) | ||||
configure(None) | ||||
_("--", ["completion_iter", "completion_list"]) | ||||
|
r28561 | @pytest.mark.xfail( | ||
sys.version_info.releaselevel in ("alpha",), | ||||
reason="Parso does not yet parse 3.13", | ||||
) | ||||
|
r27877 | def test_matcher_suppression_with_jedi(self): | ||
ip = get_ipython() | ||||
c = ip.Completer | ||||
c.use_jedi = True | ||||
def configure(suppression_config): | ||||
cfg = Config() | ||||
cfg.IPCompleter.suppress_competing_matchers = suppression_config | ||||
c.update_config(cfg) | ||||
def _(): | ||||
with provisionalcompleter(): | ||||
matches = [completion.text for completion in c.completions("dict.", 5)] | ||||
self.assertIn("keys", matches) | ||||
configure(False) | ||||
_() | ||||
configure(True) | ||||
_() | ||||
configure(None) | ||||
_() | ||||
|
r27775 | def test_matcher_disabling(self): | ||
@completion_matcher(identifier="a_matcher") | ||||
def a_matcher(text): | ||||
return ["completion_a"] | ||||
@completion_matcher(identifier="b_matcher") | ||||
def b_matcher(text): | ||||
return ["completion_b"] | ||||
def _(expected): | ||||
|
r27776 | s, matches = c.complete("completion_") | ||
self.assertEqual(expected, matches) | ||||
|
r27775 | |||
with custom_matchers([a_matcher, b_matcher]): | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
_(["completion_a", "completion_b"]) | ||||
cfg = Config() | ||||
cfg.IPCompleter.disable_matchers = ["b_matcher"] | ||||
c.update_config(cfg) | ||||
_(["completion_a"]) | ||||
cfg.IPCompleter.disable_matchers = [] | ||||
c.update_config(cfg) | ||||
def test_matcher_priority(self): | ||||
@completion_matcher(identifier="a_matcher", priority=0, api_version=2) | ||||
def a_matcher(text): | ||||
return {"completions": [SimpleCompletion("completion_a")], "suppress": True} | ||||
@completion_matcher(identifier="b_matcher", priority=2, api_version=2) | ||||
def b_matcher(text): | ||||
return {"completions": [SimpleCompletion("completion_b")], "suppress": True} | ||||
def _(expected): | ||||
|
r27776 | s, matches = c.complete("completion_") | ||
self.assertEqual(expected, matches) | ||||
|
r27775 | |||
with custom_matchers([a_matcher, b_matcher]): | ||||
ip = get_ipython() | ||||
c = ip.Completer | ||||
_(["completion_b"]) | ||||
a_matcher.matcher_priority = 3 | ||||
_(["completion_a"]) | ||||
|
r27912 | |||
@pytest.mark.parametrize( | ||||
|
r27913 | "input, expected", | ||
|
r27912 | [ | ||
|
r27913 | ["1.234", "1.234"], | ||
|
r27912 | # should match signed numbers | ||
|
r27913 | ["+1", "+1"], | ||
["-1", "-1"], | ||||
["-1.0", "-1.0"], | ||||
["-1.", "-1."], | ||||
["+1.", "+1."], | ||||
[".1", ".1"], | ||||
|
r27912 | # should not match non-numbers | ||
|
r27913 | ["1..", None], | ||
["..", None], | ||||
[".1.", None], | ||||
|
r27912 | # should match after comma | ||
|
r27913 | [",1", "1"], | ||
[", 1", "1"], | ||||
[", .1", ".1"], | ||||
[", +.1", "+.1"], | ||||
|
r27912 | # should not match after trailing spaces | ||
|
r27913 | [".1 ", None], | ||
|
r27912 | # some complex cases | ||
|
r27913 | ["0b_0011_1111_0100_1110", "0b_0011_1111_0100_1110"], | ||
["0xdeadbeef", "0xdeadbeef"], | ||||
["0b_1110_0101", "0b_1110_0101"], | ||||
|
r27927 | # should not match if in an operation | ||
["1 + 1", None], | ||||
[", 1 + 1", None], | ||||
|
r27913 | ], | ||
|
r27912 | ) | ||
def test_match_numeric_literal_for_dict_key(input, expected): | ||||
assert _match_number_in_dict_key_prefix(input) == expected | ||||