| 1 |
# encoding: utf-8 |
| 2 |
"""Tests for the IPython tab-completion machinery.""" |
| 3 |
|
| 4 |
# Copyright (c) IPython Development Team. |
| 5 |
# Distributed under the terms of the Modified BSD License. |
| 6 |
|
| 7 |
import os |
| 8 |
import pytest |
| 9 |
import sys |
| 10 |
import textwrap |
| 11 |
import types |
| 12 |
import unittest |
| 13 |
import random |
| 14 |
|
| 15 |
from importlib.metadata import version |
| 16 |
|
| 17 |
from contextlib import contextmanager |
| 18 |
|
| 19 |
from traitlets.config.loader import Config |
| 20 |
from IPython import get_ipython |
| 21 |
from IPython.core import completer |
| 22 |
from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory |
| 23 |
from IPython.utils.generics import complete_object |
| 24 |
from IPython.testing import decorators as dec |
| 25 |
from IPython.core.latex_symbols import latex_symbols |
| 26 |
|
| 27 |
from IPython.core.completer import ( |
| 28 |
Completion, |
| 29 |
provisionalcompleter, |
| 30 |
match_dict_keys, |
| 31 |
_deduplicate_completions, |
| 32 |
_match_number_in_dict_key_prefix, |
| 33 |
completion_matcher, |
| 34 |
SimpleCompletion, |
| 35 |
CompletionContext, |
| 36 |
_unicode_name_compute, |
| 37 |
_UNICODE_RANGES, |
| 38 |
) |
| 39 |
|
| 40 |
from packaging.version import parse |
| 41 |
|
| 42 |
|
| 43 |
@contextmanager |
| 44 |
def jedi_status(status: bool): |
| 45 |
completer = get_ipython().Completer |
| 46 |
try: |
| 47 |
old = completer.use_jedi |
| 48 |
completer.use_jedi = status |
| 49 |
yield |
| 50 |
finally: |
| 51 |
completer.use_jedi = old |
| 52 |
|
| 53 |
|
| 54 |
# ----------------------------------------------------------------------------- |
| 55 |
# Test functions |
| 56 |
# ----------------------------------------------------------------------------- |
| 57 |
|
| 58 |
|
| 59 |
def recompute_unicode_ranges(): |
| 60 |
""" |
| 61 |
utility to recompute the largest unicode range without any characters |
| 62 |
|
| 63 |
use to recompute the gap in the global _UNICODE_RANGES of completer.py |
| 64 |
""" |
| 65 |
import itertools |
| 66 |
import unicodedata |
| 67 |
|
| 68 |
valid = [] |
| 69 |
for c in range(0, 0x10FFFF + 1): |
| 70 |
try: |
| 71 |
unicodedata.name(chr(c)) |
| 72 |
except ValueError: |
| 73 |
continue |
| 74 |
valid.append(c) |
| 75 |
|
| 76 |
def ranges(i): |
| 77 |
for a, b in itertools.groupby(enumerate(i), lambda pair: pair[1] - pair[0]): |
| 78 |
b = list(b) |
| 79 |
yield b[0][1], b[-1][1] |
| 80 |
|
| 81 |
rg = list(ranges(valid)) |
| 82 |
lens = [] |
| 83 |
gap_lens = [] |
| 84 |
_pstart, pstop = 0, 0 |
| 85 |
for start, stop in rg: |
| 86 |
lens.append(stop - start) |
| 87 |
gap_lens.append( |
| 88 |
( |
| 89 |
start - pstop, |
| 90 |
hex(pstop + 1), |
| 91 |
hex(start), |
| 92 |
f"{round((start - pstop)/0xe01f0*100)}%", |
| 93 |
) |
| 94 |
) |
| 95 |
_pstart, pstop = start, stop |
| 96 |
|
| 97 |
return sorted(gap_lens)[-1] |
| 98 |
|
| 99 |
|
| 100 |
def test_unicode_range(): |
| 101 |
""" |
| 102 |
Test that the ranges we test for unicode names give the same number of |
| 103 |
results than testing the full length. |
| 104 |
""" |
| 105 |
|
| 106 |
expected_list = _unicode_name_compute([(0, 0x110000)]) |
| 107 |
test = _unicode_name_compute(_UNICODE_RANGES) |
| 108 |
len_exp = len(expected_list) |
| 109 |
len_test = len(test) |
| 110 |
|
| 111 |
# do not inline the len() or on error pytest will try to print the 130 000 + |
| 112 |
# elements. |
| 113 |
message = None |
| 114 |
if len_exp != len_test or len_exp > 131808: |
| 115 |
size, start, stop, prct = recompute_unicode_ranges() |
| 116 |
message = f"""_UNICODE_RANGES likely wrong and need updating. This is |
| 117 |
likely due to a new release of Python. We've find that the biggest gap |
| 118 |
in unicode characters has reduces in size to be {size} characters |
| 119 |
({prct}), from {start}, to {stop}. In completer.py likely update to |
| 120 |
|
| 121 |
_UNICODE_RANGES = [(32, {start}), ({stop}, 0xe01f0)] |
| 122 |
|
| 123 |
And update the assertion below to use |
| 124 |
|
| 125 |
len_exp <= {len_exp} |
| 126 |
""" |
| 127 |
assert len_exp == len_test, message |
| 128 |
|
| 129 |
# fail if new unicode symbols have been added. |
| 130 |
assert len_exp <= 153626, message |
| 131 |
|
| 132 |
|
| 133 |
@contextmanager |
| 134 |
def greedy_completion(): |
| 135 |
ip = get_ipython() |
| 136 |
greedy_original = ip.Completer.greedy |
| 137 |
try: |
| 138 |
ip.Completer.greedy = True |
| 139 |
yield |
| 140 |
finally: |
| 141 |
ip.Completer.greedy = greedy_original |
| 142 |
|
| 143 |
|
| 144 |
@contextmanager |
| 145 |
def evaluation_policy(evaluation: str, **overrides): |
| 146 |
ip = get_ipython() |
| 147 |
evaluation_original = ip.Completer.evaluation |
| 148 |
overrides_original = ip.Completer.policy_overrides |
| 149 |
try: |
| 150 |
ip.Completer.evaluation = evaluation |
| 151 |
ip.Completer.policy_overrides = overrides |
| 152 |
yield |
| 153 |
finally: |
| 154 |
ip.Completer.evaluation = evaluation_original |
| 155 |
ip.Completer.policy_overrides = overrides_original |
| 156 |
|
| 157 |
|
| 158 |
@contextmanager |
| 159 |
def custom_matchers(matchers): |
| 160 |
ip = get_ipython() |
| 161 |
try: |
| 162 |
ip.Completer.custom_matchers.extend(matchers) |
| 163 |
yield |
| 164 |
finally: |
| 165 |
ip.Completer.custom_matchers.clear() |
| 166 |
|
| 167 |
|
| 168 |
if sys.platform == "win32": |
| 169 |
pairs = [ |
| 170 |
("abc", "abc"), |
| 171 |
(" abc", '" abc"'), |
| 172 |
("a bc", '"a bc"'), |
| 173 |
("a bc", '"a bc"'), |
| 174 |
(" bc", '" bc"'), |
| 175 |
] |
| 176 |
else: |
| 177 |
pairs = [ |
| 178 |
("abc", "abc"), |
| 179 |
(" abc", r"\ abc"), |
| 180 |
("a bc", r"a\ bc"), |
| 181 |
("a bc", r"a\ \ bc"), |
| 182 |
(" bc", r"\ \ bc"), |
| 183 |
# On posix, we also protect parens and other special characters. |
| 184 |
("a(bc", r"a\(bc"), |
| 185 |
("a)bc", r"a\)bc"), |
| 186 |
("a( )bc", r"a\(\ \)bc"), |
| 187 |
("a[1]bc", r"a\[1\]bc"), |
| 188 |
("a{1}bc", r"a\{1\}bc"), |
| 189 |
("a#bc", r"a\#bc"), |
| 190 |
("a?bc", r"a\?bc"), |
| 191 |
("a=bc", r"a\=bc"), |
| 192 |
("a\\bc", r"a\\bc"), |
| 193 |
("a|bc", r"a\|bc"), |
| 194 |
("a;bc", r"a\;bc"), |
| 195 |
("a:bc", r"a\:bc"), |
| 196 |
("a'bc", r"a\'bc"), |
| 197 |
("a*bc", r"a\*bc"), |
| 198 |
('a"bc', r"a\"bc"), |
| 199 |
("a^bc", r"a\^bc"), |
| 200 |
("a&bc", r"a\&bc"), |
| 201 |
] |
| 202 |
|
| 203 |
|
| 204 |
@pytest.mark.parametrize("s1,expected", pairs) |
| 205 |
def test_protect_filename(s1, expected): |
| 206 |
assert completer.protect_filename(s1) == expected |
| 207 |
|
| 208 |
|
| 209 |
def check_line_split(splitter, test_specs): |
| 210 |
for part1, part2, split in test_specs: |
| 211 |
cursor_pos = len(part1) |
| 212 |
line = part1 + part2 |
| 213 |
out = splitter.split_line(line, cursor_pos) |
| 214 |
assert out == split |
| 215 |
|
| 216 |
|
| 217 |
def test_line_split(): |
| 218 |
"""Basic line splitter test with default specs.""" |
| 219 |
sp = completer.CompletionSplitter() |
| 220 |
# The format of the test specs is: part1, part2, expected answer. Parts 1 |
| 221 |
# and 2 are joined into the 'line' sent to the splitter, as if the cursor |
| 222 |
# was at the end of part1. So an empty part2 represents someone hitting |
| 223 |
# tab at the end of the line, the most common case. |
| 224 |
t = [ |
| 225 |
("run some/script", "", "some/script"), |
| 226 |
("run scripts/er", "ror.py foo", "scripts/er"), |
| 227 |
("echo $HOM", "", "HOM"), |
| 228 |
("print sys.pa", "", "sys.pa"), |
| 229 |
("print(sys.pa", "", "sys.pa"), |
| 230 |
("execfile('scripts/er", "", "scripts/er"), |
| 231 |
("a[x.", "", "x."), |
| 232 |
("a[x.", "y", "x."), |
| 233 |
('cd "some_file/', "", "some_file/"), |
| 234 |
] |
| 235 |
check_line_split(sp, t) |
| 236 |
# Ensure splitting works OK with unicode by re-running the tests with |
| 237 |
# all inputs turned into unicode |
| 238 |
check_line_split(sp, [map(str, p) for p in t]) |
| 239 |
|
| 240 |
|
| 241 |
class NamedInstanceClass: |
| 242 |
instances = {} |
| 243 |
|
| 244 |
def __init__(self, name): |
| 245 |
self.instances[name] = self |
| 246 |
|
| 247 |
@classmethod |
| 248 |
def _ipython_key_completions_(cls): |
| 249 |
return cls.instances.keys() |
| 250 |
|
| 251 |
|
| 252 |
class KeyCompletable: |
| 253 |
def __init__(self, things=()): |
| 254 |
self.things = things |
| 255 |
|
| 256 |
def _ipython_key_completions_(self): |
| 257 |
return list(self.things) |
| 258 |
|
| 259 |
|
| 260 |
class TestCompleter(unittest.TestCase): |
| 261 |
def setUp(self): |
| 262 |
""" |
| 263 |
We want to silence all PendingDeprecationWarning when testing the completer |
| 264 |
""" |
| 265 |
self._assertwarns = self.assertWarns(PendingDeprecationWarning) |
| 266 |
self._assertwarns.__enter__() |
| 267 |
|
| 268 |
def tearDown(self): |
| 269 |
try: |
| 270 |
self._assertwarns.__exit__(None, None, None) |
| 271 |
except AssertionError: |
| 272 |
pass |
| 273 |
|
| 274 |
def test_custom_completion_error(self): |
| 275 |
"""Test that errors from custom attribute completers are silenced.""" |
| 276 |
ip = get_ipython() |
| 277 |
|
| 278 |
class A: |
| 279 |
pass |
| 280 |
|
| 281 |
ip.user_ns["x"] = A() |
| 282 |
|
| 283 |
@complete_object.register(A) |
| 284 |
def complete_A(a, existing_completions): |
| 285 |
raise TypeError("this should be silenced") |
| 286 |
|
| 287 |
ip.complete("x.") |
| 288 |
|
| 289 |
def test_custom_completion_ordering(self): |
| 290 |
"""Test that errors from custom attribute completers are silenced.""" |
| 291 |
ip = get_ipython() |
| 292 |
|
| 293 |
_, matches = ip.complete("in") |
| 294 |
assert matches.index("input") < matches.index("int") |
| 295 |
|
| 296 |
def complete_example(a): |
| 297 |
return ["example2", "example1"] |
| 298 |
|
| 299 |
ip.Completer.custom_completers.add_re("ex*", complete_example) |
| 300 |
_, matches = ip.complete("ex") |
| 301 |
assert matches.index("example2") < matches.index("example1") |
| 302 |
|
| 303 |
def test_unicode_completions(self): |
| 304 |
ip = get_ipython() |
| 305 |
# Some strings that trigger different types of completion. Check them both |
| 306 |
# in str and unicode forms |
| 307 |
s = ["ru", "%ru", "cd /", "floa", "float(x)/"] |
| 308 |
for t in s + list(map(str, s)): |
| 309 |
# We don't need to check exact completion values (they may change |
| 310 |
# depending on the state of the namespace, but at least no exceptions |
| 311 |
# should be thrown and the return value should be a pair of text, list |
| 312 |
# values. |
| 313 |
text, matches = ip.complete(t) |
| 314 |
self.assertIsInstance(text, str) |
| 315 |
self.assertIsInstance(matches, list) |
| 316 |
|
| 317 |
def test_latex_completions(self): |
| 318 |
ip = get_ipython() |
| 319 |
# Test some random unicode symbols |
| 320 |
keys = random.sample(sorted(latex_symbols), 10) |
| 321 |
for k in keys: |
| 322 |
text, matches = ip.complete(k) |
| 323 |
self.assertEqual(text, k) |
| 324 |
self.assertEqual(matches, [latex_symbols[k]]) |
| 325 |
# Test a more complex line |
| 326 |
text, matches = ip.complete("print(\\alpha") |
| 327 |
self.assertEqual(text, "\\alpha") |
| 328 |
self.assertEqual(matches[0], latex_symbols["\\alpha"]) |
| 329 |
# Test multiple matching latex symbols |
| 330 |
text, matches = ip.complete("\\al") |
| 331 |
self.assertIn("\\alpha", matches) |
| 332 |
self.assertIn("\\aleph", matches) |
| 333 |
|
| 334 |
def test_latex_no_results(self): |
| 335 |
""" |
| 336 |
forward latex should really return nothing in either field if nothing is found. |
| 337 |
""" |
| 338 |
ip = get_ipython() |
| 339 |
text, matches = ip.Completer.latex_matches("\\really_i_should_match_nothing") |
| 340 |
self.assertEqual(text, "") |
| 341 |
self.assertEqual(matches, ()) |
| 342 |
|
| 343 |
def test_back_latex_completion(self): |
| 344 |
ip = get_ipython() |
| 345 |
|
| 346 |
# do not return more than 1 matches for \beta, only the latex one. |
| 347 |
name, matches = ip.complete("\\β") |
| 348 |
self.assertEqual(matches, ["\\beta"]) |
| 349 |
|
| 350 |
def test_back_unicode_completion(self): |
| 351 |
ip = get_ipython() |
| 352 |
|
| 353 |
name, matches = ip.complete("\\Ⅴ") |
| 354 |
self.assertEqual(matches, ["\\ROMAN NUMERAL FIVE"]) |
| 355 |
|
| 356 |
def test_forward_unicode_completion(self): |
| 357 |
ip = get_ipython() |
| 358 |
|
| 359 |
name, matches = ip.complete("\\ROMAN NUMERAL FIVE") |
| 360 |
self.assertEqual(matches, ["Ⅴ"]) # This is not a V |
| 361 |
self.assertEqual(matches, ["\u2164"]) # same as above but explicit. |
| 362 |
|
| 363 |
def test_delim_setting(self): |
| 364 |
sp = completer.CompletionSplitter() |
| 365 |
sp.delims = " " |
| 366 |
self.assertEqual(sp.delims, " ") |
| 367 |
self.assertEqual(sp._delim_expr, r"[\ ]") |
| 368 |
|
| 369 |
def test_spaces(self): |
| 370 |
"""Test with only spaces as split chars.""" |
| 371 |
sp = completer.CompletionSplitter() |
| 372 |
sp.delims = " " |
| 373 |
t = [("foo", "", "foo"), ("run foo", "", "foo"), ("run foo", "bar", "foo")] |
| 374 |
check_line_split(sp, t) |
| 375 |
|
| 376 |
def test_has_open_quotes1(self): |
| 377 |
for s in ["'", "'''", "'hi' '"]: |
| 378 |
self.assertEqual(completer.has_open_quotes(s), "'") |
| 379 |
|
| 380 |
def test_has_open_quotes2(self): |
| 381 |
for s in ['"', '"""', '"hi" "']: |
| 382 |
self.assertEqual(completer.has_open_quotes(s), '"') |
| 383 |
|
| 384 |
def test_has_open_quotes3(self): |
| 385 |
for s in ["''", "''' '''", "'hi' 'ipython'"]: |
| 386 |
self.assertFalse(completer.has_open_quotes(s)) |
| 387 |
|
| 388 |
def test_has_open_quotes4(self): |
| 389 |
for s in ['""', '""" """', '"hi" "ipython"']: |
| 390 |
self.assertFalse(completer.has_open_quotes(s)) |
| 391 |
|
| 392 |
@pytest.mark.xfail( |
| 393 |
sys.platform == "win32", reason="abspath completions fail on Windows" |
| 394 |
) |
| 395 |
def test_abspath_file_completions(self): |
| 396 |
ip = get_ipython() |
| 397 |
with TemporaryDirectory() as tmpdir: |
| 398 |
prefix = os.path.join(tmpdir, "foo") |
| 399 |
suffixes = ["1", "2"] |
| 400 |
names = [prefix + s for s in suffixes] |
| 401 |
for n in names: |
| 402 |
open(n, "w", encoding="utf-8").close() |
| 403 |
|
| 404 |
# Check simple completion |
| 405 |
c = ip.complete(prefix)[1] |
| 406 |
self.assertEqual(c, names) |
| 407 |
|
| 408 |
# Now check with a function call |
| 409 |
cmd = 'a = f("%s' % prefix |
| 410 |
c = ip.complete(prefix, cmd)[1] |
| 411 |
comp = [prefix + s for s in suffixes] |
| 412 |
self.assertEqual(c, comp) |
| 413 |
|
| 414 |
def test_local_file_completions(self): |
| 415 |
ip = get_ipython() |
| 416 |
with TemporaryWorkingDirectory(): |
| 417 |
prefix = "./foo" |
| 418 |
suffixes = ["1", "2"] |
| 419 |
names = [prefix + s for s in suffixes] |
| 420 |
for n in names: |
| 421 |
open(n, "w", encoding="utf-8").close() |
| 422 |
|
| 423 |
# Check simple completion |
| 424 |
c = ip.complete(prefix)[1] |
| 425 |
self.assertEqual(c, names) |
| 426 |
|
| 427 |
test_cases = { |
| 428 |
"function call": 'a = f("', |
| 429 |
"shell bang": "!ls ", |
| 430 |
"ls magic": r"%ls ", |
| 431 |
"alias ls": "ls ", |
| 432 |
} |
| 433 |
for name, code in test_cases.items(): |
| 434 |
cmd = f"{code}{prefix}" |
| 435 |
c = ip.complete(prefix, cmd)[1] |
| 436 |
comp = {prefix + s for s in suffixes} |
| 437 |
self.assertTrue(comp.issubset(set(c)), msg=f"completes in {name}") |
| 438 |
|
| 439 |
def test_quoted_file_completions(self): |
| 440 |
ip = get_ipython() |
| 441 |
|
| 442 |
def _(text): |
| 443 |
return ip.Completer._complete( |
| 444 |
cursor_line=0, cursor_pos=len(text), full_text=text |
| 445 |
)["IPCompleter.file_matcher"]["completions"] |
| 446 |
|
| 447 |
with TemporaryWorkingDirectory(): |
| 448 |
name = "foo'bar" |
| 449 |
open(name, "w", encoding="utf-8").close() |
| 450 |
|
| 451 |
# Don't escape Windows |
| 452 |
escaped = name if sys.platform == "win32" else "foo\\'bar" |
| 453 |
|
| 454 |
# Single quote matches embedded single quote |
| 455 |
c = _("open('foo")[0] |
| 456 |
self.assertEqual(c.text, escaped) |
| 457 |
|
| 458 |
# Double quote requires no escape |
| 459 |
c = _('open("foo')[0] |
| 460 |
self.assertEqual(c.text, name) |
| 461 |
|
| 462 |
# No quote requires an escape |
| 463 |
c = _("%ls foo")[0] |
| 464 |
self.assertEqual(c.text, escaped) |
| 465 |
|
| 466 |
@pytest.mark.xfail( |
| 467 |
sys.version_info.releaselevel in ("alpha",), |
| 468 |
reason="Parso does not yet parse 3.13", |
| 469 |
) |
| 470 |
def test_all_completions_dups(self): |
| 471 |
""" |
| 472 |
Make sure the output of `IPCompleter.all_completions` does not have |
| 473 |
duplicated prefixes. |
| 474 |
""" |
| 475 |
ip = get_ipython() |
| 476 |
c = ip.Completer |
| 477 |
ip.ex("class TestClass():\n\ta=1\n\ta1=2") |
| 478 |
for jedi_status in [True, False]: |
| 479 |
with provisionalcompleter(): |
| 480 |
ip.Completer.use_jedi = jedi_status |
| 481 |
matches = c.all_completions("TestCl") |
| 482 |
assert matches == ["TestClass"], (jedi_status, matches) |
| 483 |
matches = c.all_completions("TestClass.") |
| 484 |
assert len(matches) > 2, (jedi_status, matches) |
| 485 |
matches = c.all_completions("TestClass.a") |
| 486 |
if jedi_status: |
| 487 |
assert matches == ["TestClass.a", "TestClass.a1"], jedi_status |
| 488 |
else: |
| 489 |
assert matches == [".a", ".a1"], jedi_status |
| 490 |
|
| 491 |
@pytest.mark.xfail( |
| 492 |
sys.version_info.releaselevel in ("alpha",), |
| 493 |
reason="Parso does not yet parse 3.13", |
| 494 |
) |
| 495 |
def test_jedi(self): |
| 496 |
""" |
| 497 |
A couple of issue we had with Jedi |
| 498 |
""" |
| 499 |
ip = get_ipython() |
| 500 |
|
| 501 |
def _test_complete(reason, s, comp, start=None, end=None): |
| 502 |
l = len(s) |
| 503 |
start = start if start is not None else l |
| 504 |
end = end if end is not None else l |
| 505 |
with provisionalcompleter(): |
| 506 |
ip.Completer.use_jedi = True |
| 507 |
completions = set(ip.Completer.completions(s, l)) |
| 508 |
ip.Completer.use_jedi = False |
| 509 |
assert Completion(start, end, comp) in completions, reason |
| 510 |
|
| 511 |
def _test_not_complete(reason, s, comp): |
| 512 |
l = len(s) |
| 513 |
with provisionalcompleter(): |
| 514 |
ip.Completer.use_jedi = True |
| 515 |
completions = set(ip.Completer.completions(s, l)) |
| 516 |
ip.Completer.use_jedi = False |
| 517 |
assert Completion(l, l, comp) not in completions, reason |
| 518 |
|
| 519 |
import jedi |
| 520 |
|
| 521 |
jedi_version = tuple(int(i) for i in jedi.__version__.split(".")[:3]) |
| 522 |
if jedi_version > (0, 10): |
| 523 |
_test_complete("jedi >0.9 should complete and not crash", "a=1;a.", "real") |
| 524 |
_test_complete("can infer first argument", 'a=(1,"foo");a[0].', "real") |
| 525 |
_test_complete("can infer second argument", 'a=(1,"foo");a[1].', "capitalize") |
| 526 |
_test_complete("cover duplicate completions", "im", "import", 0, 2) |
| 527 |
|
| 528 |
_test_not_complete("does not mix types", 'a=(1,"foo");a[0].', "capitalize") |
| 529 |
|
| 530 |
@pytest.mark.xfail( |
| 531 |
sys.version_info.releaselevel in ("alpha",), |
| 532 |
reason="Parso does not yet parse 3.13", |
| 533 |
) |
| 534 |
def test_completion_have_signature(self): |
| 535 |
""" |
| 536 |
Lets make sure jedi is capable of pulling out the signature of the function we are completing. |
| 537 |
""" |
| 538 |
ip = get_ipython() |
| 539 |
with provisionalcompleter(): |
| 540 |
ip.Completer.use_jedi = True |
| 541 |
completions = ip.Completer.completions("ope", 3) |
| 542 |
c = next(completions) # should be `open` |
| 543 |
ip.Completer.use_jedi = False |
| 544 |
assert "file" in c.signature, "Signature of function was not found by completer" |
| 545 |
assert ( |
| 546 |
"encoding" in c.signature |
| 547 |
), "Signature of function was not found by completer" |
| 548 |
|
| 549 |
@pytest.mark.xfail( |
| 550 |
sys.version_info.releaselevel in ("alpha",), |
| 551 |
reason="Parso does not yet parse 3.13", |
| 552 |
) |
| 553 |
def test_completions_have_type(self): |
| 554 |
""" |
| 555 |
Lets make sure matchers provide completion type. |
| 556 |
""" |
| 557 |
ip = get_ipython() |
| 558 |
with provisionalcompleter(): |
| 559 |
ip.Completer.use_jedi = False |
| 560 |
completions = ip.Completer.completions("%tim", 3) |
| 561 |
c = next(completions) # should be `%time` or similar |
| 562 |
assert c.type == "magic", "Type of magic was not assigned by completer" |
| 563 |
|
| 564 |
@pytest.mark.xfail( |
| 565 |
parse(version("jedi")) <= parse("0.18.0"), |
| 566 |
reason="Known failure on jedi<=0.18.0", |
| 567 |
strict=True, |
| 568 |
) |
| 569 |
def test_deduplicate_completions(self): |
| 570 |
""" |
| 571 |
Test that completions are correctly deduplicated (even if ranges are not the same) |
| 572 |
""" |
| 573 |
ip = get_ipython() |
| 574 |
ip.ex( |
| 575 |
textwrap.dedent( |
| 576 |
""" |
| 577 |
class Z: |
| 578 |
zoo = 1 |
| 579 |
""" |
| 580 |
) |
| 581 |
) |
| 582 |
with provisionalcompleter(): |
| 583 |
ip.Completer.use_jedi = True |
| 584 |
l = list( |
| 585 |
_deduplicate_completions("Z.z", ip.Completer.completions("Z.z", 3)) |
| 586 |
) |
| 587 |
ip.Completer.use_jedi = False |
| 588 |
|
| 589 |
assert len(l) == 1, "Completions (Z.z<tab>) correctly deduplicate: %s " % l |
| 590 |
assert l[0].text == "zoo" # and not `it.accumulate` |
| 591 |
|
| 592 |
@pytest.mark.xfail( |
| 593 |
sys.version_info.releaselevel in ("alpha",), |
| 594 |
reason="Parso does not yet parse 3.13", |
| 595 |
) |
| 596 |
def test_greedy_completions(self): |
| 597 |
""" |
| 598 |
Test the capability of the Greedy completer. |
| 599 |
|
| 600 |
Most of the test here does not really show off the greedy completer, for proof |
| 601 |
each of the text below now pass with Jedi. The greedy completer is capable of more. |
| 602 |
|
| 603 |
See the :any:`test_dict_key_completion_contexts` |
| 604 |
|
| 605 |
""" |
| 606 |
ip = get_ipython() |
| 607 |
ip.ex("a=list(range(5))") |
| 608 |
ip.ex("b,c = 1, 1.2") |
| 609 |
ip.ex("d = {'a b': str}") |
| 610 |
ip.ex("x=y='a'") |
| 611 |
_, c = ip.complete(".", line="a[0].") |
| 612 |
self.assertFalse(".real" in c, "Shouldn't have completed on a[0]: %s" % c) |
| 613 |
|
| 614 |
def _(line, cursor_pos, expect, message, completion): |
| 615 |
with greedy_completion(), provisionalcompleter(): |
| 616 |
ip.Completer.use_jedi = False |
| 617 |
_, c = ip.complete(".", line=line, cursor_pos=cursor_pos) |
| 618 |
self.assertIn(expect, c, message % c) |
| 619 |
|
| 620 |
ip.Completer.use_jedi = True |
| 621 |
with provisionalcompleter(): |
| 622 |
completions = ip.Completer.completions(line, cursor_pos) |
| 623 |
self.assertIn(completion, list(completions)) |
| 624 |
|
| 625 |
with provisionalcompleter(): |
| 626 |
_( |
| 627 |
"a[0].", |
| 628 |
5, |
| 629 |
".real", |
| 630 |
"Should have completed on a[0].: %s", |
| 631 |
Completion(5, 5, "real"), |
| 632 |
) |
| 633 |
_( |
| 634 |
"a[0].r", |
| 635 |
6, |
| 636 |
".real", |
| 637 |
"Should have completed on a[0].r: %s", |
| 638 |
Completion(5, 6, "real"), |
| 639 |
) |
| 640 |
_( |
| 641 |
"a[0].from_", |
| 642 |
10, |
| 643 |
".from_bytes", |
| 644 |
"Should have completed on a[0].from_: %s", |
| 645 |
Completion(5, 10, "from_bytes"), |
| 646 |
) |
| 647 |
_( |
| 648 |
"assert str.star", |
| 649 |
14, |
| 650 |
".startswith", |
| 651 |
"Should have completed on `assert str.star`: %s", |
| 652 |
Completion(11, 14, "startswith"), |
| 653 |
) |
| 654 |
_( |
| 655 |
"d['a b'].str", |
| 656 |
12, |
| 657 |
".strip", |
| 658 |
"Should have completed on `d['a b'].str`: %s", |
| 659 |
Completion(9, 12, "strip"), |
| 660 |
) |
| 661 |
_( |
| 662 |
"a.app", |
| 663 |
4, |
| 664 |
".append", |
| 665 |
"Should have completed on `a.app`: %s", |
| 666 |
Completion(2, 4, "append"), |
| 667 |
) |
| 668 |
_( |
| 669 |
"x.upper() == y.", |
| 670 |
15, |
| 671 |
".upper", |
| 672 |
"Should have completed on `x.upper() == y.`: %s", |
| 673 |
Completion(15, 15, "upper"), |
| 674 |
) |
| 675 |
_( |
| 676 |
"(x.upper() == y.", |
| 677 |
16, |
| 678 |
".upper", |
| 679 |
"Should have completed on `(x.upper() == y.`: %s", |
| 680 |
Completion(16, 16, "upper"), |
| 681 |
) |
| 682 |
_( |
| 683 |
"(x.upper() == y).", |
| 684 |
17, |
| 685 |
".bit_length", |
| 686 |
"Should have completed on `(x.upper() == y).`: %s", |
| 687 |
Completion(17, 17, "bit_length"), |
| 688 |
) |
| 689 |
_( |
| 690 |
"{'==', 'abc'}.", |
| 691 |
14, |
| 692 |
".add", |
| 693 |
"Should have completed on `{'==', 'abc'}.`: %s", |
| 694 |
Completion(14, 14, "add"), |
| 695 |
) |
| 696 |
_( |
| 697 |
"b + c.", |
| 698 |
6, |
| 699 |
".hex", |
| 700 |
"Should have completed on `b + c.`: %s", |
| 701 |
Completion(6, 6, "hex"), |
| 702 |
) |
| 703 |
|
| 704 |
def test_omit__names(self): |
| 705 |
# also happens to test IPCompleter as a configurable |
| 706 |
ip = get_ipython() |
| 707 |
ip._hidden_attr = 1 |
| 708 |
ip._x = {} |
| 709 |
c = ip.Completer |
| 710 |
ip.ex("ip=get_ipython()") |
| 711 |
cfg = Config() |
| 712 |
cfg.IPCompleter.omit__names = 0 |
| 713 |
c.update_config(cfg) |
| 714 |
with provisionalcompleter(): |
| 715 |
c.use_jedi = False |
| 716 |
s, matches = c.complete("ip.") |
| 717 |
self.assertIn(".__str__", matches) |
| 718 |
self.assertIn("._hidden_attr", matches) |
| 719 |
|
| 720 |
# c.use_jedi = True |
| 721 |
# completions = set(c.completions('ip.', 3)) |
| 722 |
# self.assertIn(Completion(3, 3, '__str__'), completions) |
| 723 |
# self.assertIn(Completion(3,3, "_hidden_attr"), completions) |
| 724 |
|
| 725 |
cfg = Config() |
| 726 |
cfg.IPCompleter.omit__names = 1 |
| 727 |
c.update_config(cfg) |
| 728 |
with provisionalcompleter(): |
| 729 |
c.use_jedi = False |
| 730 |
s, matches = c.complete("ip.") |
| 731 |
self.assertNotIn(".__str__", matches) |
| 732 |
# self.assertIn('ip._hidden_attr', matches) |
| 733 |
|
| 734 |
# c.use_jedi = True |
| 735 |
# completions = set(c.completions('ip.', 3)) |
| 736 |
# self.assertNotIn(Completion(3,3,'__str__'), completions) |
| 737 |
# self.assertIn(Completion(3,3, "_hidden_attr"), completions) |
| 738 |
|
| 739 |
cfg = Config() |
| 740 |
cfg.IPCompleter.omit__names = 2 |
| 741 |
c.update_config(cfg) |
| 742 |
with provisionalcompleter(): |
| 743 |
c.use_jedi = False |
| 744 |
s, matches = c.complete("ip.") |
| 745 |
self.assertNotIn(".__str__", matches) |
| 746 |
self.assertNotIn("._hidden_attr", matches) |
| 747 |
|
| 748 |
# c.use_jedi = True |
| 749 |
# completions = set(c.completions('ip.', 3)) |
| 750 |
# self.assertNotIn(Completion(3,3,'__str__'), completions) |
| 751 |
# self.assertNotIn(Completion(3,3, "_hidden_attr"), completions) |
| 752 |
|
| 753 |
with provisionalcompleter(): |
| 754 |
c.use_jedi = False |
| 755 |
s, matches = c.complete("ip._x.") |
| 756 |
self.assertIn(".keys", matches) |
| 757 |
|
| 758 |
# c.use_jedi = True |
| 759 |
# completions = set(c.completions('ip._x.', 6)) |
| 760 |
# self.assertIn(Completion(6,6, "keys"), completions) |
| 761 |
|
| 762 |
del ip._hidden_attr |
| 763 |
del ip._x |
| 764 |
|
| 765 |
def test_limit_to__all__False_ok(self): |
| 766 |
""" |
| 767 |
Limit to all is deprecated, once we remove it this test can go away. |
| 768 |
""" |
| 769 |
ip = get_ipython() |
| 770 |
c = ip.Completer |
| 771 |
c.use_jedi = False |
| 772 |
ip.ex("class D: x=24") |
| 773 |
ip.ex("d=D()") |
| 774 |
cfg = Config() |
| 775 |
cfg.IPCompleter.limit_to__all__ = False |
| 776 |
c.update_config(cfg) |
| 777 |
s, matches = c.complete("d.") |
| 778 |
self.assertIn(".x", matches) |
| 779 |
|
| 780 |
def test_get__all__entries_ok(self): |
| 781 |
class A: |
| 782 |
__all__ = ["x", 1] |
| 783 |
|
| 784 |
words = completer.get__all__entries(A()) |
| 785 |
self.assertEqual(words, ["x"]) |
| 786 |
|
| 787 |
def test_get__all__entries_no__all__ok(self): |
| 788 |
class A: |
| 789 |
pass |
| 790 |
|
| 791 |
words = completer.get__all__entries(A()) |
| 792 |
self.assertEqual(words, []) |
| 793 |
|
| 794 |
def test_completes_globals_as_args_of_methods(self): |
| 795 |
ip = get_ipython() |
| 796 |
c = ip.Completer |
| 797 |
c.use_jedi = False |
| 798 |
ip.ex("long_variable_name = 1") |
| 799 |
ip.ex("a = []") |
| 800 |
s, matches = c.complete(None, "a.sort(lo") |
| 801 |
self.assertIn("long_variable_name", matches) |
| 802 |
|
| 803 |
def test_completes_attributes_in_fstring_expressions(self): |
| 804 |
ip = get_ipython() |
| 805 |
c = ip.Completer |
| 806 |
c.use_jedi = False |
| 807 |
|
| 808 |
class CustomClass: |
| 809 |
def method_one(self): |
| 810 |
pass |
| 811 |
|
| 812 |
ip.user_ns["custom_obj"] = CustomClass() |
| 813 |
|
| 814 |
# Test completion inside f-string expressions |
| 815 |
s, matches = c.complete(None, "f'{custom_obj.meth") |
| 816 |
self.assertIn(".method_one", matches) |
| 817 |
|
| 818 |
def test_completes_in_dict_expressions(self): |
| 819 |
ip = get_ipython() |
| 820 |
c = ip.Completer |
| 821 |
c.use_jedi = False |
| 822 |
ip.ex("class Test: pass") |
| 823 |
ip.ex("test_obj = Test()") |
| 824 |
ip.ex("test_obj.attribute = 'value'") |
| 825 |
|
| 826 |
# Test completion in dictionary expressions |
| 827 |
s, matches = c.complete(None, "d = {'key': test_obj.attr") |
| 828 |
self.assertIn(".attribute", matches) |
| 829 |
|
| 830 |
# Test global completion in dictionary expressions with dots |
| 831 |
s, matches = c.complete(None, "d = {'k.e.y': Te") |
| 832 |
self.assertIn("Test", matches) |
| 833 |
|
| 834 |
def test_func_kw_completions(self): |
| 835 |
ip = get_ipython() |
| 836 |
c = ip.Completer |
| 837 |
c.use_jedi = False |
| 838 |
ip.ex("def myfunc(a=1,b=2): return a+b") |
| 839 |
s, matches = c.complete(None, "myfunc(1,b") |
| 840 |
self.assertIn("b=", matches) |
| 841 |
# Simulate completing with cursor right after b (pos==10): |
| 842 |
s, matches = c.complete(None, "myfunc(1,b)", 10) |
| 843 |
self.assertIn("b=", matches) |
| 844 |
s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b') |
| 845 |
self.assertIn("b=", matches) |
| 846 |
# builtin function |
| 847 |
s, matches = c.complete(None, "min(k, k") |
| 848 |
self.assertIn("key=", matches) |
| 849 |
|
| 850 |
def test_default_arguments_from_docstring(self): |
| 851 |
ip = get_ipython() |
| 852 |
c = ip.Completer |
| 853 |
kwd = c._default_arguments_from_docstring("min(iterable[, key=func]) -> value") |
| 854 |
self.assertEqual(kwd, ["key"]) |
| 855 |
# with cython type etc |
| 856 |
kwd = c._default_arguments_from_docstring( |
| 857 |
"Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n" |
| 858 |
) |
| 859 |
self.assertEqual(kwd, ["ncall", "resume", "nsplit"]) |
| 860 |
# white spaces |
| 861 |
kwd = c._default_arguments_from_docstring( |
| 862 |
"\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n" |
| 863 |
) |
| 864 |
self.assertEqual(kwd, ["ncall", "resume", "nsplit"]) |
| 865 |
|
| 866 |
def test_line_magics(self): |
| 867 |
ip = get_ipython() |
| 868 |
c = ip.Completer |
| 869 |
s, matches = c.complete(None, "lsmag") |
| 870 |
self.assertIn("%lsmagic", matches) |
| 871 |
s, matches = c.complete(None, "%lsmag") |
| 872 |
self.assertIn("%lsmagic", matches) |
| 873 |
|
| 874 |
def test_cell_magics(self): |
| 875 |
from IPython.core.magic import register_cell_magic |
| 876 |
|
| 877 |
@register_cell_magic |
| 878 |
def _foo_cellm(line, cell): |
| 879 |
pass |
| 880 |
|
| 881 |
ip = get_ipython() |
| 882 |
c = ip.Completer |
| 883 |
|
| 884 |
s, matches = c.complete(None, "_foo_ce") |
| 885 |
self.assertIn("%%_foo_cellm", matches) |
| 886 |
s, matches = c.complete(None, "%%_foo_ce") |
| 887 |
self.assertIn("%%_foo_cellm", matches) |
| 888 |
|
| 889 |
def test_line_cell_magics(self): |
| 890 |
from IPython.core.magic import register_line_cell_magic |
| 891 |
|
| 892 |
@register_line_cell_magic |
| 893 |
def _bar_cellm(line, cell): |
| 894 |
pass |
| 895 |
|
| 896 |
ip = get_ipython() |
| 897 |
c = ip.Completer |
| 898 |
|
| 899 |
# The policy here is trickier, see comments in completion code. The |
| 900 |
# returned values depend on whether the user passes %% or not explicitly, |
| 901 |
# and this will show a difference if the same name is both a line and cell |
| 902 |
# magic. |
| 903 |
s, matches = c.complete(None, "_bar_ce") |
| 904 |
self.assertIn("%_bar_cellm", matches) |
| 905 |
self.assertIn("%%_bar_cellm", matches) |
| 906 |
s, matches = c.complete(None, "%_bar_ce") |
| 907 |
self.assertIn("%_bar_cellm", matches) |
| 908 |
self.assertIn("%%_bar_cellm", matches) |
| 909 |
s, matches = c.complete(None, "%%_bar_ce") |
| 910 |
self.assertNotIn("%_bar_cellm", matches) |
| 911 |
self.assertIn("%%_bar_cellm", matches) |
| 912 |
|
| 913 |
def test_line_magics_with_code_argument(self): |
| 914 |
ip = get_ipython() |
| 915 |
c = ip.Completer |
| 916 |
c.use_jedi = False |
| 917 |
|
| 918 |
# attribute completion |
| 919 |
text, matches = c.complete("%timeit -n 2 -r 1 float.as_integer") |
| 920 |
self.assertEqual(matches, [".as_integer_ratio"]) |
| 921 |
|
| 922 |
text, matches = c.complete("%debug --breakpoint test float.as_integer") |
| 923 |
self.assertEqual(matches, [".as_integer_ratio"]) |
| 924 |
|
| 925 |
text, matches = c.complete("%time --no-raise-error float.as_integer") |
| 926 |
self.assertEqual(matches, [".as_integer_ratio"]) |
| 927 |
|
| 928 |
text, matches = c.complete("%prun -l 0.5 -r float.as_integer") |
| 929 |
self.assertEqual(matches, [".as_integer_ratio"]) |
| 930 |
|
| 931 |
# implicit magics |
| 932 |
text, matches = c.complete("timeit -n 2 -r 1 float.as_integer") |
| 933 |
self.assertEqual(matches, [".as_integer_ratio"]) |
| 934 |
|
| 935 |
# built-ins completion |
| 936 |
text, matches = c.complete("%timeit -n 2 -r 1 flo") |
| 937 |
self.assertEqual(matches, ["float"]) |
| 938 |
|
| 939 |
# dict completion |
| 940 |
text, matches = c.complete("%timeit -n 2 -r 1 {'my_key': 1}['my") |
| 941 |
self.assertEqual(matches, ["my_key"]) |
| 942 |
|
| 943 |
# invalid arguments - should not throw |
| 944 |
text, matches = c.complete("%timeit -n 2 -r 1 -invalid float.as_integer") |
| 945 |
self.assertEqual(matches, []) |
| 946 |
|
| 947 |
text, matches = c.complete("%debug --invalid float.as_integer") |
| 948 |
self.assertEqual(matches, []) |
| 949 |
|
| 950 |
def test_line_magics_with_code_argument_shadowing(self): |
| 951 |
ip = get_ipython() |
| 952 |
c = ip.Completer |
| 953 |
c.use_jedi = False |
| 954 |
|
| 955 |
# shadow |
| 956 |
ip.run_cell("timeit = 1") |
| 957 |
|
| 958 |
# should not suggest on implict magic when shadowed |
| 959 |
text, matches = c.complete("timeit -n 2 -r 1 flo") |
| 960 |
self.assertEqual(matches, []) |
| 961 |
|
| 962 |
# should suggest on explicit magic |
| 963 |
text, matches = c.complete("%timeit -n 2 -r 1 flo") |
| 964 |
self.assertEqual(matches, ["float"]) |
| 965 |
|
| 966 |
# remove shadow |
| 967 |
del ip.user_ns["timeit"] |
| 968 |
|
| 969 |
# should suggest on implicit magic after shadow removal |
| 970 |
text, matches = c.complete("timeit -n 2 -r 1 flo") |
| 971 |
self.assertEqual(matches, ["float"]) |
| 972 |
|
| 973 |
def test_magic_completion_order(self): |
| 974 |
ip = get_ipython() |
| 975 |
c = ip.Completer |
| 976 |
|
| 977 |
# Test ordering of line and cell magics. |
| 978 |
text, matches = c.complete("timeit") |
| 979 |
self.assertEqual(matches, ["%timeit", "%%timeit"]) |
| 980 |
|
| 981 |
def test_magic_completion_shadowing(self): |
| 982 |
ip = get_ipython() |
| 983 |
c = ip.Completer |
| 984 |
c.use_jedi = False |
| 985 |
|
| 986 |
# Before importing matplotlib, %matplotlib magic should be the only option. |
| 987 |
text, matches = c.complete("mat") |
| 988 |
self.assertEqual(matches, ["%matplotlib"]) |
| 989 |
|
| 990 |
# The newly introduced name should shadow the magic. |
| 991 |
ip.run_cell("matplotlib = 1") |
| 992 |
text, matches = c.complete("mat") |
| 993 |
self.assertEqual(matches, ["matplotlib"]) |
| 994 |
|
| 995 |
# After removing matplotlib from namespace, the magic should again be |
| 996 |
# the only option. |
| 997 |
del ip.user_ns["matplotlib"] |
| 998 |
text, matches = c.complete("mat") |
| 999 |
self.assertEqual(matches, ["%matplotlib"]) |
| 1000 |
|
| 1001 |
def test_magic_completion_shadowing_explicit(self): |
| 1002 |
""" |
| 1003 |
If the user try to complete a shadowed magic, and explicit % start should |
| 1004 |
still return the completions. |
| 1005 |
""" |
| 1006 |
ip = get_ipython() |
| 1007 |
c = ip.Completer |
| 1008 |
|
| 1009 |
# Before importing matplotlib, %matplotlib magic should be the only option. |
| 1010 |
text, matches = c.complete("%mat") |
| 1011 |
self.assertEqual(matches, ["%matplotlib"]) |
| 1012 |
|
| 1013 |
ip.run_cell("matplotlib = 1") |
| 1014 |
|
| 1015 |
# After removing matplotlib from namespace, the magic should still be |
| 1016 |
# the only option. |
| 1017 |
text, matches = c.complete("%mat") |
| 1018 |
self.assertEqual(matches, ["%matplotlib"]) |
| 1019 |
|
| 1020 |
def test_magic_config(self): |
| 1021 |
ip = get_ipython() |
| 1022 |
c = ip.Completer |
| 1023 |
|
| 1024 |
s, matches = c.complete(None, "conf") |
| 1025 |
self.assertIn("%config", matches) |
| 1026 |
s, matches = c.complete(None, "conf") |
| 1027 |
self.assertNotIn("AliasManager", matches) |
| 1028 |
s, matches = c.complete(None, "config ") |
| 1029 |
self.assertIn("AliasManager", matches) |
| 1030 |
s, matches = c.complete(None, "%config ") |
| 1031 |
self.assertIn("AliasManager", matches) |
| 1032 |
s, matches = c.complete(None, "config Ali") |
| 1033 |
self.assertListEqual(["AliasManager"], matches) |
| 1034 |
s, matches = c.complete(None, "%config Ali") |
| 1035 |
self.assertListEqual(["AliasManager"], matches) |
| 1036 |
s, matches = c.complete(None, "config AliasManager") |
| 1037 |
self.assertListEqual(["AliasManager"], matches) |
| 1038 |
s, matches = c.complete(None, "%config AliasManager") |
| 1039 |
self.assertListEqual(["AliasManager"], matches) |
| 1040 |
s, matches = c.complete(None, "config AliasManager.") |
| 1041 |
self.assertIn("AliasManager.default_aliases", matches) |
| 1042 |
s, matches = c.complete(None, "%config AliasManager.") |
| 1043 |
self.assertIn("AliasManager.default_aliases", matches) |
| 1044 |
s, matches = c.complete(None, "config AliasManager.de") |
| 1045 |
self.assertListEqual(["AliasManager.default_aliases"], matches) |
| 1046 |
s, matches = c.complete(None, "config AliasManager.de") |
| 1047 |
self.assertListEqual(["AliasManager.default_aliases"], matches) |
| 1048 |
|
| 1049 |
def test_magic_color(self): |
| 1050 |
ip = get_ipython() |
| 1051 |
c = ip.Completer |
| 1052 |
|
| 1053 |
s, matches = c.complete(None, "colo") |
| 1054 |
assert "%colors" in matches |
| 1055 |
s, matches = c.complete(None, "colo") |
| 1056 |
assert "nocolor" not in matches |
| 1057 |
s, matches = c.complete(None, "%colors") # No trailing space |
| 1058 |
assert "nocolor" not in matches |
| 1059 |
s, matches = c.complete(None, "colors ") |
| 1060 |
assert "nocolor" in matches |
| 1061 |
s, matches = c.complete(None, "%colors ") |
| 1062 |
assert "nocolor" in matches |
| 1063 |
s, matches = c.complete(None, "colors noco") |
| 1064 |
assert ["nocolor"] == matches |
| 1065 |
s, matches = c.complete(None, "%colors noco") |
| 1066 |
assert ["nocolor"] == matches |
| 1067 |
|
| 1068 |
def test_match_dict_keys(self): |
| 1069 |
""" |
| 1070 |
Test that match_dict_keys works on a couple of use case does return what |
| 1071 |
expected, and does not crash |
| 1072 |
""" |
| 1073 |
delims = " \t\n`!@#$^&*()=+[{]}\\|;:'\",<>?" |
| 1074 |
|
| 1075 |
def match(*args, **kwargs): |
| 1076 |
quote, offset, matches = match_dict_keys(*args, delims=delims, **kwargs) |
| 1077 |
return quote, offset, list(matches) |
| 1078 |
|
| 1079 |
keys = ["foo", b"far"] |
| 1080 |
assert match(keys, "b'") == ("'", 2, ["far"]) |
| 1081 |
assert match(keys, "b'f") == ("'", 2, ["far"]) |
| 1082 |
assert match(keys, 'b"') == ('"', 2, ["far"]) |
| 1083 |
assert match(keys, 'b"f') == ('"', 2, ["far"]) |
| 1084 |
|
| 1085 |
assert match(keys, "'") == ("'", 1, ["foo"]) |
| 1086 |
assert match(keys, "'f") == ("'", 1, ["foo"]) |
| 1087 |
assert match(keys, '"') == ('"', 1, ["foo"]) |
| 1088 |
assert match(keys, '"f') == ('"', 1, ["foo"]) |
| 1089 |
|
| 1090 |
# Completion on first item of tuple |
| 1091 |
keys = [("foo", 1111), ("foo", 2222), (3333, "bar"), (3333, "test")] |
| 1092 |
assert match(keys, "'f") == ("'", 1, ["foo"]) |
| 1093 |
assert match(keys, "33") == ("", 0, ["3333"]) |
| 1094 |
|
| 1095 |
# Completion on numbers |
| 1096 |
keys = [ |
| 1097 |
0xDEADBEEF, |
| 1098 |
1111, |
| 1099 |
1234, |
| 1100 |
"1999", |
| 1101 |
0b10101, |
| 1102 |
22, |
| 1103 |
] # 0xDEADBEEF = 3735928559; 0b10101 = 21 |
| 1104 |
assert match(keys, "0xdead") == ("", 0, ["0xdeadbeef"]) |
| 1105 |
assert match(keys, "1") == ("", 0, ["1111", "1234"]) |
| 1106 |
assert match(keys, "2") == ("", 0, ["21", "22"]) |
| 1107 |
assert match(keys, "0b101") == ("", 0, ["0b10101", "0b10110"]) |
| 1108 |
|
| 1109 |
# Should yield on variables |
| 1110 |
assert match(keys, "a_variable") == ("", 0, []) |
| 1111 |
|
| 1112 |
# Should pass over invalid literals |
| 1113 |
assert match(keys, "'' ''") == ("", 0, []) |
| 1114 |
|
| 1115 |
def test_match_dict_keys_tuple(self): |
| 1116 |
""" |
| 1117 |
Test that match_dict_keys called with extra prefix works on a couple of use case, |
| 1118 |
does return what expected, and does not crash. |
| 1119 |
""" |
| 1120 |
delims = " \t\n`!@#$^&*()=+[{]}\\|;:'\",<>?" |
| 1121 |
|
| 1122 |
keys = [("foo", "bar"), ("foo", "oof"), ("foo", b"bar"), ("other", "test")] |
| 1123 |
|
| 1124 |
def match(*args, extra=None, **kwargs): |
| 1125 |
quote, offset, matches = match_dict_keys( |
| 1126 |
*args, delims=delims, extra_prefix=extra, **kwargs |
| 1127 |
) |
| 1128 |
return quote, offset, list(matches) |
| 1129 |
|
| 1130 |
# Completion on first key == "foo" |
| 1131 |
assert match(keys, "'", extra=("foo",)) == ("'", 1, ["bar", "oof"]) |
| 1132 |
assert match(keys, '"', extra=("foo",)) == ('"', 1, ["bar", "oof"]) |
| 1133 |
assert match(keys, "'o", extra=("foo",)) == ("'", 1, ["oof"]) |
| 1134 |
assert match(keys, '"o', extra=("foo",)) == ('"', 1, ["oof"]) |
| 1135 |
assert match(keys, "b'", extra=("foo",)) == ("'", 2, ["bar"]) |
| 1136 |
assert match(keys, 'b"', extra=("foo",)) == ('"', 2, ["bar"]) |
| 1137 |
assert match(keys, "b'b", extra=("foo",)) == ("'", 2, ["bar"]) |
| 1138 |
assert match(keys, 'b"b', extra=("foo",)) == ('"', 2, ["bar"]) |
| 1139 |
|
| 1140 |
# No Completion |
| 1141 |
assert match(keys, "'", extra=("no_foo",)) == ("'", 1, []) |
| 1142 |
assert match(keys, "'", extra=("fo",)) == ("'", 1, []) |
| 1143 |
|
| 1144 |
keys = [("foo1", "foo2", "foo3", "foo4"), ("foo1", "foo2", "bar", "foo4")] |
| 1145 |
assert match(keys, "'foo", extra=("foo1",)) == ("'", 1, ["foo2"]) |
| 1146 |
assert match(keys, "'foo", extra=("foo1", "foo2")) == ("'", 1, ["foo3"]) |
| 1147 |
assert match(keys, "'foo", extra=("foo1", "foo2", "foo3")) == ("'", 1, ["foo4"]) |
| 1148 |
assert match(keys, "'foo", extra=("foo1", "foo2", "foo3", "foo4")) == ( |
| 1149 |
"'", |
| 1150 |
1, |
| 1151 |
[], |
| 1152 |
) |
| 1153 |
|
| 1154 |
keys = [("foo", 1111), ("foo", "2222"), (3333, "bar"), (3333, 4444)] |
| 1155 |
assert match(keys, "'", extra=("foo",)) == ("'", 1, ["2222"]) |
| 1156 |
assert match(keys, "", extra=("foo",)) == ("", 0, ["1111", "'2222'"]) |
| 1157 |
assert match(keys, "'", extra=(3333,)) == ("'", 1, ["bar"]) |
| 1158 |
assert match(keys, "", extra=(3333,)) == ("", 0, ["'bar'", "4444"]) |
| 1159 |
assert match(keys, "'", extra=("3333",)) == ("'", 1, []) |
| 1160 |
assert match(keys, "33") == ("", 0, ["3333"]) |
| 1161 |
|
| 1162 |
def test_dict_key_completion_closures(self): |
| 1163 |
ip = get_ipython() |
| 1164 |
complete = ip.Completer.complete |
| 1165 |
ip.Completer.auto_close_dict_keys = True |
| 1166 |
|
| 1167 |
ip.user_ns["d"] = { |
| 1168 |
# tuple only |
| 1169 |
("aa", 11): None, |
| 1170 |
# tuple and non-tuple |
| 1171 |
("bb", 22): None, |
| 1172 |
"bb": None, |
| 1173 |
# non-tuple only |
| 1174 |
"cc": None, |
| 1175 |
# numeric tuple only |
| 1176 |
(77, "x"): None, |
| 1177 |
# numeric tuple and non-tuple |
| 1178 |
(88, "y"): None, |
| 1179 |
88: None, |
| 1180 |
# numeric non-tuple only |
| 1181 |
99: None, |
| 1182 |
} |
| 1183 |
|
| 1184 |
_, matches = complete(line_buffer="d[") |
| 1185 |
# should append `, ` if matches a tuple only |
| 1186 |
self.assertIn("'aa', ", matches) |
| 1187 |
# should not append anything if matches a tuple and an item |
| 1188 |
self.assertIn("'bb'", matches) |
| 1189 |
# should append `]` if matches and item only |
| 1190 |
self.assertIn("'cc']", matches) |
| 1191 |
|
| 1192 |
# should append `, ` if matches a tuple only |
| 1193 |
self.assertIn("77, ", matches) |
| 1194 |
# should not append anything if matches a tuple and an item |
| 1195 |
self.assertIn("88", matches) |
| 1196 |
# should append `]` if matches and item only |
| 1197 |
self.assertIn("99]", matches) |
| 1198 |
|
| 1199 |
_, matches = complete(line_buffer="d['aa', ") |
| 1200 |
# should restrict matches to those matching tuple prefix |
| 1201 |
self.assertIn("11]", matches) |
| 1202 |
self.assertNotIn("'bb'", matches) |
| 1203 |
self.assertNotIn("'bb', ", matches) |
| 1204 |
self.assertNotIn("'bb']", matches) |
| 1205 |
self.assertNotIn("'cc'", matches) |
| 1206 |
self.assertNotIn("'cc', ", matches) |
| 1207 |
self.assertNotIn("'cc']", matches) |
| 1208 |
ip.Completer.auto_close_dict_keys = False |
| 1209 |
|
| 1210 |
def test_dict_key_completion_string(self): |
| 1211 |
"""Test dictionary key completion for string keys""" |
| 1212 |
ip = get_ipython() |
| 1213 |
complete = ip.Completer.complete |
| 1214 |
|
| 1215 |
ip.user_ns["d"] = {"abc": None} |
| 1216 |
|
| 1217 |
# check completion at different stages |
| 1218 |
_, matches = complete(line_buffer="d[") |
| 1219 |
self.assertIn("'abc'", matches) |
| 1220 |
self.assertNotIn("'abc']", matches) |
| 1221 |
|
| 1222 |
_, matches = complete(line_buffer="d['") |
| 1223 |
self.assertIn("abc", matches) |
| 1224 |
self.assertNotIn("abc']", matches) |
| 1225 |
|
| 1226 |
_, matches = complete(line_buffer="d['a") |
| 1227 |
self.assertIn("abc", matches) |
| 1228 |
self.assertNotIn("abc']", matches) |
| 1229 |
|
| 1230 |
# check use of different quoting |
| 1231 |
_, matches = complete(line_buffer='d["') |
| 1232 |
self.assertIn("abc", matches) |
| 1233 |
self.assertNotIn('abc"]', matches) |
| 1234 |
|
| 1235 |
_, matches = complete(line_buffer='d["a') |
| 1236 |
self.assertIn("abc", matches) |
| 1237 |
self.assertNotIn('abc"]', matches) |
| 1238 |
|
| 1239 |
# check sensitivity to following context |
| 1240 |
_, matches = complete(line_buffer="d[]", cursor_pos=2) |
| 1241 |
self.assertIn("'abc'", matches) |
| 1242 |
|
| 1243 |
_, matches = complete(line_buffer="d['']", cursor_pos=3) |
| 1244 |
self.assertIn("abc", matches) |
| 1245 |
self.assertNotIn("abc'", matches) |
| 1246 |
self.assertNotIn("abc']", matches) |
| 1247 |
|
| 1248 |
# check multiple solutions are correctly returned and that noise is not |
| 1249 |
ip.user_ns["d"] = { |
| 1250 |
"abc": None, |
| 1251 |
"abd": None, |
| 1252 |
"bad": None, |
| 1253 |
object(): None, |
| 1254 |
5: None, |
| 1255 |
("abe", None): None, |
| 1256 |
(None, "abf"): None, |
| 1257 |
} |
| 1258 |
|
| 1259 |
_, matches = complete(line_buffer="d['a") |
| 1260 |
self.assertIn("abc", matches) |
| 1261 |
self.assertIn("abd", matches) |
| 1262 |
self.assertNotIn("bad", matches) |
| 1263 |
self.assertNotIn("abe", matches) |
| 1264 |
self.assertNotIn("abf", matches) |
| 1265 |
assert not any(m.endswith(("]", '"', "'")) for m in matches), matches |
| 1266 |
|
| 1267 |
# check escaping and whitespace |
| 1268 |
ip.user_ns["d"] = {"a\nb": None, "a'b": None, 'a"b': None, "a word": None} |
| 1269 |
_, matches = complete(line_buffer="d['a") |
| 1270 |
self.assertIn("a\\nb", matches) |
| 1271 |
self.assertIn("a\\'b", matches) |
| 1272 |
self.assertIn('a"b', matches) |
| 1273 |
self.assertIn("a word", matches) |
| 1274 |
assert not any(m.endswith(("]", '"', "'")) for m in matches), matches |
| 1275 |
|
| 1276 |
# - can complete on non-initial word of the string |
| 1277 |
_, matches = complete(line_buffer="d['a w") |
| 1278 |
self.assertIn("word", matches) |
| 1279 |
|
| 1280 |
# - understands quote escaping |
| 1281 |
_, matches = complete(line_buffer="d['a\\'") |
| 1282 |
self.assertIn("b", matches) |
| 1283 |
|
| 1284 |
# - default quoting should work like repr |
| 1285 |
_, matches = complete(line_buffer="d[") |
| 1286 |
self.assertIn('"a\'b"', matches) |
| 1287 |
|
| 1288 |
# - when opening quote with ", possible to match with unescaped apostrophe |
| 1289 |
_, matches = complete(line_buffer="d[\"a'") |
| 1290 |
self.assertIn("b", matches) |
| 1291 |
|
| 1292 |
# need to not split at delims that readline won't split at |
| 1293 |
if "-" not in ip.Completer.splitter.delims: |
| 1294 |
ip.user_ns["d"] = {"before-after": None} |
| 1295 |
_, matches = complete(line_buffer="d['before-af") |
| 1296 |
self.assertIn("before-after", matches) |
| 1297 |
|
| 1298 |
# check completion on tuple-of-string keys at different stage - on first key |
| 1299 |
ip.user_ns["d"] = {("foo", "bar"): None} |
| 1300 |
_, matches = complete(line_buffer="d[") |
| 1301 |
self.assertIn("'foo'", matches) |
| 1302 |
self.assertNotIn("'foo']", matches) |
| 1303 |
self.assertNotIn("'bar'", matches) |
| 1304 |
self.assertNotIn("foo", matches) |
| 1305 |
self.assertNotIn("bar", matches) |
| 1306 |
|
| 1307 |
# - match the prefix |
| 1308 |
_, matches = complete(line_buffer="d['f") |
| 1309 |
self.assertIn("foo", matches) |
| 1310 |
self.assertNotIn("foo']", matches) |
| 1311 |
self.assertNotIn('foo"]', matches) |
| 1312 |
_, matches = complete(line_buffer="d['foo") |
| 1313 |
self.assertIn("foo", matches) |
| 1314 |
|
| 1315 |
# - can complete on second key |
| 1316 |
_, matches = complete(line_buffer="d['foo', ") |
| 1317 |
self.assertIn("'bar'", matches) |
| 1318 |
_, matches = complete(line_buffer="d['foo', 'b") |
| 1319 |
self.assertIn("bar", matches) |
| 1320 |
self.assertNotIn("foo", matches) |
| 1321 |
|
| 1322 |
# - does not propose missing keys |
| 1323 |
_, matches = complete(line_buffer="d['foo', 'f") |
| 1324 |
self.assertNotIn("bar", matches) |
| 1325 |
self.assertNotIn("foo", matches) |
| 1326 |
|
| 1327 |
# check sensitivity to following context |
| 1328 |
_, matches = complete(line_buffer="d['foo',]", cursor_pos=8) |
| 1329 |
self.assertIn("'bar'", matches) |
| 1330 |
self.assertNotIn("bar", matches) |
| 1331 |
self.assertNotIn("'foo'", matches) |
| 1332 |
self.assertNotIn("foo", matches) |
| 1333 |
|
| 1334 |
_, matches = complete(line_buffer="d['']", cursor_pos=3) |
| 1335 |
self.assertIn("foo", matches) |
| 1336 |
assert not any(m.endswith(("]", '"', "'")) for m in matches), matches |
| 1337 |
|
| 1338 |
_, matches = complete(line_buffer='d[""]', cursor_pos=3) |
| 1339 |
self.assertIn("foo", matches) |
| 1340 |
assert not any(m.endswith(("]", '"', "'")) for m in matches), matches |
| 1341 |
|
| 1342 |
_, matches = complete(line_buffer='d["foo","]', cursor_pos=9) |
| 1343 |
self.assertIn("bar", matches) |
| 1344 |
assert not any(m.endswith(("]", '"', "'")) for m in matches), matches |
| 1345 |
|
| 1346 |
_, matches = complete(line_buffer='d["foo",]', cursor_pos=8) |
| 1347 |
self.assertIn("'bar'", matches) |
| 1348 |
self.assertNotIn("bar", matches) |
| 1349 |
|
| 1350 |
# Can complete with longer tuple keys |
| 1351 |
ip.user_ns["d"] = {("foo", "bar", "foobar"): None} |
| 1352 |
|
| 1353 |
# - can complete second key |
| 1354 |
_, matches = complete(line_buffer="d['foo', 'b") |
| 1355 |
self.assertIn("bar", matches) |
| 1356 |
self.assertNotIn("foo", matches) |
| 1357 |
self.assertNotIn("foobar", matches) |
| 1358 |
|
| 1359 |
# - can complete third key |
| 1360 |
_, matches = complete(line_buffer="d['foo', 'bar', 'fo") |
| 1361 |
self.assertIn("foobar", matches) |
| 1362 |
self.assertNotIn("foo", matches) |
| 1363 |
self.assertNotIn("bar", matches) |
| 1364 |
|
| 1365 |
def test_dict_key_completion_numbers(self): |
| 1366 |
ip = get_ipython() |
| 1367 |
complete = ip.Completer.complete |
| 1368 |
|
| 1369 |
ip.user_ns["d"] = { |
| 1370 |
0xDEADBEEF: None, # 3735928559 |
| 1371 |
1111: None, |
| 1372 |
1234: None, |
| 1373 |
"1999": None, |
| 1374 |
0b10101: None, # 21 |
| 1375 |
22: None, |
| 1376 |
} |
| 1377 |
_, matches = complete(line_buffer="d[1") |
| 1378 |
self.assertIn("1111", matches) |
| 1379 |
self.assertIn("1234", matches) |
| 1380 |
self.assertNotIn("1999", matches) |
| 1381 |
self.assertNotIn("'1999'", matches) |
| 1382 |
|
| 1383 |
_, matches = complete(line_buffer="d[0xdead") |
| 1384 |
self.assertIn("0xdeadbeef", matches) |
| 1385 |
|
| 1386 |
_, matches = complete(line_buffer="d[2") |
| 1387 |
self.assertIn("21", matches) |
| 1388 |
self.assertIn("22", matches) |
| 1389 |
|
| 1390 |
_, matches = complete(line_buffer="d[0b101") |
| 1391 |
self.assertIn("0b10101", matches) |
| 1392 |
self.assertIn("0b10110", matches) |
| 1393 |
|
| 1394 |
def test_dict_key_completion_contexts(self): |
| 1395 |
"""Test expression contexts in which dict key completion occurs""" |
| 1396 |
ip = get_ipython() |
| 1397 |
complete = ip.Completer.complete |
| 1398 |
d = {"abc": None} |
| 1399 |
ip.user_ns["d"] = d |
| 1400 |
|
| 1401 |
class C: |
| 1402 |
data = d |
| 1403 |
|
| 1404 |
ip.user_ns["C"] = C |
| 1405 |
ip.user_ns["get"] = lambda: d |
| 1406 |
ip.user_ns["nested"] = {"x": d} |
| 1407 |
|
| 1408 |
def assert_no_completion(**kwargs): |
| 1409 |
_, matches = complete(**kwargs) |
| 1410 |
self.assertNotIn("abc", matches) |
| 1411 |
self.assertNotIn("abc'", matches) |
| 1412 |
self.assertNotIn("abc']", matches) |
| 1413 |
self.assertNotIn("'abc'", matches) |
| 1414 |
self.assertNotIn("'abc']", matches) |
| 1415 |
|
| 1416 |
def assert_completion(**kwargs): |
| 1417 |
_, matches = complete(**kwargs) |
| 1418 |
self.assertIn("'abc'", matches) |
| 1419 |
self.assertNotIn("'abc']", matches) |
| 1420 |
|
| 1421 |
# no completion after string closed, even if reopened |
| 1422 |
assert_no_completion(line_buffer="d['a'") |
| 1423 |
assert_no_completion(line_buffer='d["a"') |
| 1424 |
assert_no_completion(line_buffer="d['a' + ") |
| 1425 |
assert_no_completion(line_buffer="d['a' + '") |
| 1426 |
|
| 1427 |
# completion in non-trivial expressions |
| 1428 |
assert_completion(line_buffer="+ d[") |
| 1429 |
assert_completion(line_buffer="(d[") |
| 1430 |
assert_completion(line_buffer="C.data[") |
| 1431 |
|
| 1432 |
# nested dict completion |
| 1433 |
assert_completion(line_buffer="nested['x'][") |
| 1434 |
|
| 1435 |
with evaluation_policy("minimal"): |
| 1436 |
with pytest.raises(AssertionError): |
| 1437 |
assert_completion(line_buffer="nested['x'][") |
| 1438 |
|
| 1439 |
# greedy flag |
| 1440 |
def assert_completion(**kwargs): |
| 1441 |
_, matches = complete(**kwargs) |
| 1442 |
self.assertIn("get()['abc']", matches) |
| 1443 |
|
| 1444 |
assert_no_completion(line_buffer="get()[") |
| 1445 |
with greedy_completion(): |
| 1446 |
assert_completion(line_buffer="get()[") |
| 1447 |
assert_completion(line_buffer="get()['") |
| 1448 |
assert_completion(line_buffer="get()['a") |
| 1449 |
assert_completion(line_buffer="get()['ab") |
| 1450 |
assert_completion(line_buffer="get()['abc") |
| 1451 |
|
| 1452 |
def test_completion_autoimport(self): |
| 1453 |
ip = get_ipython() |
| 1454 |
complete = ip.Completer.complete |
| 1455 |
with ( |
| 1456 |
evaluation_policy("limited", allow_auto_import=True), |
| 1457 |
jedi_status(False), |
| 1458 |
): |
| 1459 |
_, matches = complete(line_buffer="math.") |
| 1460 |
self.assertIn(".pi", matches) |
| 1461 |
|
| 1462 |
def test_completion_no_autoimport(self): |
| 1463 |
ip = get_ipython() |
| 1464 |
complete = ip.Completer.complete |
| 1465 |
with ( |
| 1466 |
evaluation_policy("limited", allow_auto_import=False), |
| 1467 |
jedi_status(False), |
| 1468 |
): |
| 1469 |
_, matches = complete(line_buffer="math.") |
| 1470 |
self.assertNotIn(".pi", matches) |
| 1471 |
|
| 1472 |
def test_completion_allow_custom_getattr_per_module(self): |
| 1473 |
factory_code = textwrap.dedent( |
| 1474 |
""" |
| 1475 |
class ListFactory: |
| 1476 |
def __getattr__(self, attr): |
| 1477 |
return [] |
| 1478 |
""" |
| 1479 |
) |
| 1480 |
|
| 1481 |
safe_lib = types.ModuleType("my.safe.lib") |
| 1482 |
sys.modules["my.safe.lib"] = safe_lib |
| 1483 |
exec(factory_code, safe_lib.__dict__) |
| 1484 |
|
| 1485 |
unsafe_lib = types.ModuleType("my.unsafe.lib") |
| 1486 |
sys.modules["my.unsafe.lib"] = unsafe_lib |
| 1487 |
exec(factory_code, unsafe_lib.__dict__) |
| 1488 |
|
| 1489 |
fake_safe_lib = types.ModuleType("my_fake_lib") |
| 1490 |
sys.modules["my_fake_lib"] = fake_safe_lib |
| 1491 |
exec(factory_code, fake_safe_lib.__dict__) |
| 1492 |
|
| 1493 |
ip = get_ipython() |
| 1494 |
ip.user_ns["safe_list_factory"] = safe_lib.ListFactory() |
| 1495 |
ip.user_ns["unsafe_list_factory"] = unsafe_lib.ListFactory() |
| 1496 |
ip.user_ns["fake_safe_factory"] = fake_safe_lib.ListFactory() |
| 1497 |
complete = ip.Completer.complete |
| 1498 |
with ( |
| 1499 |
evaluation_policy("limited", allowed_getattr_external={"my.safe.lib"}), |
| 1500 |
jedi_status(False), |
| 1501 |
): |
| 1502 |
_, matches = complete(line_buffer="safe_list_factory.example.") |
| 1503 |
self.assertIn(".append", matches) |
| 1504 |
# this also checks against https://github.com/ipython/ipython/issues/14916 |
| 1505 |
# because removing "un" would cause this test to incorrectly pass |
| 1506 |
_, matches = complete(line_buffer="unsafe_list_factory.example.") |
| 1507 |
self.assertNotIn(".append", matches) |
| 1508 |
|
| 1509 |
sys.modules["my"] = types.ModuleType("my") |
| 1510 |
|
| 1511 |
with ( |
| 1512 |
evaluation_policy("limited", allowed_getattr_external={"my"}), |
| 1513 |
jedi_status(False), |
| 1514 |
): |
| 1515 |
_, matches = complete(line_buffer="safe_list_factory.example.") |
| 1516 |
self.assertIn(".append", matches) |
| 1517 |
_, matches = complete(line_buffer="unsafe_list_factory.example.") |
| 1518 |
self.assertIn(".append", matches) |
| 1519 |
_, matches = complete(line_buffer="fake_safe_factory.example.") |
| 1520 |
self.assertNotIn(".append", matches) |
| 1521 |
|
| 1522 |
with ( |
| 1523 |
evaluation_policy("limited"), |
| 1524 |
jedi_status(False), |
| 1525 |
): |
| 1526 |
_, matches = complete(line_buffer="safe_list_factory.example.") |
| 1527 |
self.assertNotIn(".append", matches) |
| 1528 |
_, matches = complete(line_buffer="unsafe_list_factory.example.") |
| 1529 |
self.assertNotIn(".append", matches) |
| 1530 |
|
| 1531 |
def test_completion_allow_subclass_of_trusted_module(self): |
| 1532 |
factory_code = textwrap.dedent( |
| 1533 |
""" |
| 1534 |
class ListFactory: |
| 1535 |
def __getattr__(self, attr): |
| 1536 |
return [] |
| 1537 |
""" |
| 1538 |
) |
| 1539 |
trusted_lib = types.ModuleType("my.trusted.lib") |
| 1540 |
sys.modules["my.trusted.lib"] = trusted_lib |
| 1541 |
exec(factory_code, trusted_lib.__dict__) |
| 1542 |
|
| 1543 |
ip = get_ipython() |
| 1544 |
# Create a subclass in __main__ (untrusted namespace) |
| 1545 |
subclass_code = textwrap.dedent( |
| 1546 |
""" |
| 1547 |
class SubclassFactory(trusted_lib.ListFactory): |
| 1548 |
pass |
| 1549 |
""" |
| 1550 |
) |
| 1551 |
ip.user_ns["trusted_lib"] = trusted_lib |
| 1552 |
exec(subclass_code, ip.user_ns) |
| 1553 |
ip.user_ns["subclass_factory"] = ip.user_ns["SubclassFactory"]() |
| 1554 |
complete = ip.Completer.complete |
| 1555 |
with ( |
| 1556 |
evaluation_policy("limited", allowed_getattr_external={"my.trusted.lib"}), |
| 1557 |
jedi_status(False), |
| 1558 |
): |
| 1559 |
_, matches = complete(line_buffer="subclass_factory.example.") |
| 1560 |
self.assertIn(".append", matches) |
| 1561 |
|
| 1562 |
# Test that overriding __getattr__ in subclass in untrusted namespace prevents completion |
| 1563 |
overriding_subclass_code = textwrap.dedent( |
| 1564 |
""" |
| 1565 |
class OverridingSubclass(trusted_lib.ListFactory): |
| 1566 |
def __getattr__(self, attr): |
| 1567 |
return {} |
| 1568 |
""" |
| 1569 |
) |
| 1570 |
exec(overriding_subclass_code, ip.user_ns) |
| 1571 |
ip.user_ns["overriding_factory"] = ip.user_ns["OverridingSubclass"]() |
| 1572 |
|
| 1573 |
with ( |
| 1574 |
evaluation_policy("limited", allowed_getattr_external={"my.trusted.lib"}), |
| 1575 |
jedi_status(False), |
| 1576 |
): |
| 1577 |
_, matches = complete(line_buffer="overriding_factory.example.") |
| 1578 |
self.assertNotIn(".append", matches) |
| 1579 |
self.assertNotIn(".keys", matches) |
| 1580 |
|
| 1581 |
def test_completion_fallback_to_annotation_for_attribute(self): |
| 1582 |
code = textwrap.dedent( |
| 1583 |
""" |
| 1584 |
class StringMethods: |
| 1585 |
def a(): |
| 1586 |
pass |
| 1587 |
|
| 1588 |
class Test: |
| 1589 |
str: StringMethods |
| 1590 |
def __init__(self): |
| 1591 |
self.str = StringMethods() |
| 1592 |
def __getattr__(self, name): |
| 1593 |
raise AttributeError(f"{name} not found") |
| 1594 |
""" |
| 1595 |
) |
| 1596 |
|
| 1597 |
repro = types.ModuleType("repro") |
| 1598 |
sys.modules["repro"] = repro |
| 1599 |
exec(code, repro.__dict__) |
| 1600 |
|
| 1601 |
ip = get_ipython() |
| 1602 |
ip.user_ns["repro"] = repro |
| 1603 |
exec("r = repro.Test()", ip.user_ns) |
| 1604 |
|
| 1605 |
complete = ip.Completer.complete |
| 1606 |
try: |
| 1607 |
with evaluation_policy("limited"), jedi_status(False): |
| 1608 |
_, matches = complete(line_buffer="r.str.") |
| 1609 |
self.assertIn(".a", matches) |
| 1610 |
finally: |
| 1611 |
sys.modules.pop("repro", None) |
| 1612 |
ip.user_ns.pop("r", None) |
| 1613 |
|
| 1614 |
def test_policy_warnings(self): |
| 1615 |
with self.assertWarns( |
| 1616 |
UserWarning, |
| 1617 |
msg="Override 'allowed_getattr_external' is not valid with 'unsafe' evaluation policy", |
| 1618 |
): |
| 1619 |
with evaluation_policy("unsafe", allowed_getattr_external=[]): |
| 1620 |
pass |
| 1621 |
|
| 1622 |
with self.assertWarns( |
| 1623 |
UserWarning, |
| 1624 |
msg="Override 'test' is not valid with 'limited' evaluation policy", |
| 1625 |
): |
| 1626 |
with evaluation_policy("limited", test=[]): |
| 1627 |
pass |
| 1628 |
|
| 1629 |
def test_dict_key_completion_bytes(self): |
| 1630 |
"""Test handling of bytes in dict key completion""" |
| 1631 |
ip = get_ipython() |
| 1632 |
complete = ip.Completer.complete |
| 1633 |
|
| 1634 |
ip.user_ns["d"] = {"abc": None, b"abd": None} |
| 1635 |
|
| 1636 |
_, matches = complete(line_buffer="d[") |
| 1637 |
self.assertIn("'abc'", matches) |
| 1638 |
self.assertIn("b'abd'", matches) |
| 1639 |
|
| 1640 |
if False: # not currently implemented |
| 1641 |
_, matches = complete(line_buffer="d[b") |
| 1642 |
self.assertIn("b'abd'", matches) |
| 1643 |
self.assertNotIn("b'abc'", matches) |
| 1644 |
|
| 1645 |
_, matches = complete(line_buffer="d[b'") |
| 1646 |
self.assertIn("abd", matches) |
| 1647 |
self.assertNotIn("abc", matches) |
| 1648 |
|
| 1649 |
_, matches = complete(line_buffer="d[B'") |
| 1650 |
self.assertIn("abd", matches) |
| 1651 |
self.assertNotIn("abc", matches) |
| 1652 |
|
| 1653 |
_, matches = complete(line_buffer="d['") |
| 1654 |
self.assertIn("abc", matches) |
| 1655 |
self.assertNotIn("abd", matches) |
| 1656 |
|
| 1657 |
def test_dict_key_completion_unicode_py3(self): |
| 1658 |
"""Test handling of unicode in dict key completion""" |
| 1659 |
ip = get_ipython() |
| 1660 |
complete = ip.Completer.complete |
| 1661 |
|
| 1662 |
ip.user_ns["d"] = {"a\u05d0": None} |
| 1663 |
|
| 1664 |
# query using escape |
| 1665 |
if sys.platform != "win32": |
| 1666 |
# Known failure on Windows |
| 1667 |
_, matches = complete(line_buffer="d['a\\u05d0") |
| 1668 |
self.assertIn("u05d0", matches) # tokenized after \\ |
| 1669 |
|
| 1670 |
# query using character |
| 1671 |
_, matches = complete(line_buffer="d['a\u05d0") |
| 1672 |
self.assertIn("a\u05d0", matches) |
| 1673 |
|
| 1674 |
with greedy_completion(): |
| 1675 |
# query using escape |
| 1676 |
_, matches = complete(line_buffer="d['a\\u05d0") |
| 1677 |
self.assertIn("d['a\\u05d0']", matches) # tokenized after \\ |
| 1678 |
|
| 1679 |
# query using character |
| 1680 |
_, matches = complete(line_buffer="d['a\u05d0") |
| 1681 |
self.assertIn("d['a\u05d0']", matches) |
| 1682 |
|
| 1683 |
@dec.skip_without("numpy") |
| 1684 |
def test_struct_array_key_completion(self): |
| 1685 |
"""Test dict key completion applies to numpy struct arrays""" |
| 1686 |
import numpy |
| 1687 |
|
| 1688 |
ip = get_ipython() |
| 1689 |
complete = ip.Completer.complete |
| 1690 |
ip.user_ns["d"] = numpy.array([], dtype=[("hello", "f"), ("world", "f")]) |
| 1691 |
_, matches = complete(line_buffer="d['") |
| 1692 |
self.assertIn("hello", matches) |
| 1693 |
self.assertIn("world", matches) |
| 1694 |
# complete on the numpy struct itself |
| 1695 |
dt = numpy.dtype( |
| 1696 |
[("my_head", [("my_dt", ">u4"), ("my_df", ">u4")]), ("my_data", ">f4", 5)] |
| 1697 |
) |
| 1698 |
x = numpy.zeros(2, dtype=dt) |
| 1699 |
ip.user_ns["d"] = x[1] |
| 1700 |
_, matches = complete(line_buffer="d['") |
| 1701 |
self.assertIn("my_head", matches) |
| 1702 |
self.assertIn("my_data", matches) |
| 1703 |
|
| 1704 |
def completes_on_nested(): |
| 1705 |
ip.user_ns["d"] = numpy.zeros(2, dtype=dt) |
| 1706 |
_, matches = complete(line_buffer="d[1]['my_head']['") |
| 1707 |
self.assertTrue(any(["my_dt" in m for m in matches])) |
| 1708 |
self.assertTrue(any(["my_df" in m for m in matches])) |
| 1709 |
|
| 1710 |
# complete on a nested level |
| 1711 |
with greedy_completion(): |
| 1712 |
completes_on_nested() |
| 1713 |
|
| 1714 |
with evaluation_policy("limited"): |
| 1715 |
completes_on_nested() |
| 1716 |
|
| 1717 |
with evaluation_policy("minimal"): |
| 1718 |
with pytest.raises(AssertionError): |
| 1719 |
completes_on_nested() |
| 1720 |
|
| 1721 |
@dec.skip_without("pandas") |
| 1722 |
def test_dataframe_key_completion(self): |
| 1723 |
"""Test dict key completion applies to pandas DataFrames""" |
| 1724 |
import pandas |
| 1725 |
|
| 1726 |
ip = get_ipython() |
| 1727 |
complete = ip.Completer.complete |
| 1728 |
ip.user_ns["d"] = pandas.DataFrame({"hello": [1], "world": [2]}) |
| 1729 |
_, matches = complete(line_buffer="d['") |
| 1730 |
self.assertIn("hello", matches) |
| 1731 |
self.assertIn("world", matches) |
| 1732 |
_, matches = complete(line_buffer="d.loc[:, '") |
| 1733 |
self.assertIn("hello", matches) |
| 1734 |
self.assertIn("world", matches) |
| 1735 |
_, matches = complete(line_buffer="d.loc[1:, '") |
| 1736 |
self.assertIn("hello", matches) |
| 1737 |
_, matches = complete(line_buffer="d.loc[1:1, '") |
| 1738 |
self.assertIn("hello", matches) |
| 1739 |
_, matches = complete(line_buffer="d.loc[1:1:-1, '") |
| 1740 |
self.assertIn("hello", matches) |
| 1741 |
_, matches = complete(line_buffer="d.loc[::, '") |
| 1742 |
self.assertIn("hello", matches) |
| 1743 |
|
| 1744 |
def test_dict_key_completion_invalids(self): |
| 1745 |
"""Smoke test cases dict key completion can't handle""" |
| 1746 |
ip = get_ipython() |
| 1747 |
complete = ip.Completer.complete |
| 1748 |
|
| 1749 |
ip.user_ns["no_getitem"] = None |
| 1750 |
ip.user_ns["no_keys"] = [] |
| 1751 |
ip.user_ns["cant_call_keys"] = dict |
| 1752 |
ip.user_ns["empty"] = {} |
| 1753 |
ip.user_ns["d"] = {"abc": 5} |
| 1754 |
|
| 1755 |
_, matches = complete(line_buffer="no_getitem['") |
| 1756 |
_, matches = complete(line_buffer="no_keys['") |
| 1757 |
_, matches = complete(line_buffer="cant_call_keys['") |
| 1758 |
_, matches = complete(line_buffer="empty['") |
| 1759 |
_, matches = complete(line_buffer="name_error['") |
| 1760 |
_, matches = complete(line_buffer="d['\\") # incomplete escape |
| 1761 |
|
| 1762 |
def test_object_key_completion(self): |
| 1763 |
ip = get_ipython() |
| 1764 |
ip.user_ns["key_completable"] = KeyCompletable(["qwerty", "qwick"]) |
| 1765 |
|
| 1766 |
_, matches = ip.Completer.complete(line_buffer="key_completable['qw") |
| 1767 |
self.assertIn("qwerty", matches) |
| 1768 |
self.assertIn("qwick", matches) |
| 1769 |
|
| 1770 |
def test_class_key_completion(self): |
| 1771 |
ip = get_ipython() |
| 1772 |
NamedInstanceClass("qwerty") |
| 1773 |
NamedInstanceClass("qwick") |
| 1774 |
ip.user_ns["named_instance_class"] = NamedInstanceClass |
| 1775 |
|
| 1776 |
_, matches = ip.Completer.complete(line_buffer="named_instance_class['qw") |
| 1777 |
self.assertIn("qwerty", matches) |
| 1778 |
self.assertIn("qwick", matches) |
| 1779 |
|
| 1780 |
def test_tryimport(self): |
| 1781 |
""" |
| 1782 |
Test that try-import don't crash on trailing dot, and import modules before |
| 1783 |
""" |
| 1784 |
from IPython.core.completerlib import try_import |
| 1785 |
|
| 1786 |
assert try_import("IPython.") |
| 1787 |
|
| 1788 |
def test_aimport_module_completer(self): |
| 1789 |
ip = get_ipython() |
| 1790 |
_, matches = ip.complete("i", "%aimport i") |
| 1791 |
self.assertIn("io", matches) |
| 1792 |
self.assertNotIn("int", matches) |
| 1793 |
|
| 1794 |
def test_nested_import_module_completer(self): |
| 1795 |
ip = get_ipython() |
| 1796 |
_, matches = ip.complete(None, "import IPython.co", 17) |
| 1797 |
self.assertIn("IPython.core", matches) |
| 1798 |
self.assertNotIn("import IPython.core", matches) |
| 1799 |
self.assertNotIn("IPython.display", matches) |
| 1800 |
|
| 1801 |
def test_import_module_completer(self): |
| 1802 |
ip = get_ipython() |
| 1803 |
_, matches = ip.complete("i", "import i") |
| 1804 |
self.assertIn("io", matches) |
| 1805 |
self.assertNotIn("int", matches) |
| 1806 |
|
| 1807 |
def test_from_module_completer(self): |
| 1808 |
ip = get_ipython() |
| 1809 |
_, matches = ip.complete("B", "from io import B", 16) |
| 1810 |
self.assertIn("BytesIO", matches) |
| 1811 |
self.assertNotIn("BaseException", matches) |
| 1812 |
|
| 1813 |
def test_snake_case_completion(self): |
| 1814 |
ip = get_ipython() |
| 1815 |
ip.Completer.use_jedi = False |
| 1816 |
ip.user_ns["some_three"] = 3 |
| 1817 |
ip.user_ns["some_four"] = 4 |
| 1818 |
_, matches = ip.complete("s_", "print(s_f") |
| 1819 |
self.assertIn("some_three", matches) |
| 1820 |
self.assertIn("some_four", matches) |
| 1821 |
|
| 1822 |
def test_mix_terms(self): |
| 1823 |
ip = get_ipython() |
| 1824 |
from textwrap import dedent |
| 1825 |
|
| 1826 |
ip.Completer.use_jedi = False |
| 1827 |
ip.ex( |
| 1828 |
dedent( |
| 1829 |
""" |
| 1830 |
class Test: |
| 1831 |
def meth(self, meth_arg1): |
| 1832 |
print("meth") |
| 1833 |
|
| 1834 |
def meth_1(self, meth1_arg1, meth1_arg2): |
| 1835 |
print("meth1") |
| 1836 |
|
| 1837 |
def meth_2(self, meth2_arg1, meth2_arg2): |
| 1838 |
print("meth2") |
| 1839 |
test = Test() |
| 1840 |
""" |
| 1841 |
) |
| 1842 |
) |
| 1843 |
_, matches = ip.complete(None, "test.meth(") |
| 1844 |
self.assertIn("meth_arg1=", matches) |
| 1845 |
self.assertNotIn("meth2_arg1=", matches) |
| 1846 |
|
| 1847 |
def test_percent_symbol_restrict_to_magic_completions(self): |
| 1848 |
ip = get_ipython() |
| 1849 |
completer = ip.Completer |
| 1850 |
text = "%a" |
| 1851 |
|
| 1852 |
with provisionalcompleter(): |
| 1853 |
completer.use_jedi = True |
| 1854 |
completions = completer.completions(text, len(text)) |
| 1855 |
for c in completions: |
| 1856 |
self.assertEqual(c.text[0], "%") |
| 1857 |
|
| 1858 |
def test_fwd_unicode_restricts(self): |
| 1859 |
ip = get_ipython() |
| 1860 |
completer = ip.Completer |
| 1861 |
text = "\\ROMAN NUMERAL FIVE" |
| 1862 |
|
| 1863 |
with provisionalcompleter(): |
| 1864 |
completer.use_jedi = True |
| 1865 |
completions = [ |
| 1866 |
completion.text for completion in completer.completions(text, len(text)) |
| 1867 |
] |
| 1868 |
self.assertEqual(completions, ["\u2164"]) |
| 1869 |
|
| 1870 |
def test_dict_key_restrict_to_dicts(self): |
| 1871 |
"""Test that dict key suppresses non-dict completion items""" |
| 1872 |
ip = get_ipython() |
| 1873 |
c = ip.Completer |
| 1874 |
d = {"abc": None} |
| 1875 |
ip.user_ns["d"] = d |
| 1876 |
|
| 1877 |
text = 'd["a' |
| 1878 |
|
| 1879 |
def _(): |
| 1880 |
with provisionalcompleter(): |
| 1881 |
c.use_jedi = True |
| 1882 |
return [ |
| 1883 |
completion.text for completion in c.completions(text, len(text)) |
| 1884 |
] |
| 1885 |
|
| 1886 |
completions = _() |
| 1887 |
self.assertEqual(completions, ["abc"]) |
| 1888 |
|
| 1889 |
# check that it can be disabled in granular manner: |
| 1890 |
cfg = Config() |
| 1891 |
cfg.IPCompleter.suppress_competing_matchers = { |
| 1892 |
"IPCompleter.dict_key_matcher": False |
| 1893 |
} |
| 1894 |
c.update_config(cfg) |
| 1895 |
|
| 1896 |
completions = _() |
| 1897 |
self.assertIn("abc", completions) |
| 1898 |
self.assertGreater(len(completions), 1) |
| 1899 |
|
| 1900 |
def test_matcher_suppression(self): |
| 1901 |
@completion_matcher(identifier="a_matcher") |
| 1902 |
def a_matcher(text): |
| 1903 |
return ["completion_a"] |
| 1904 |
|
| 1905 |
@completion_matcher(identifier="b_matcher", api_version=2) |
| 1906 |
def b_matcher(context: CompletionContext): |
| 1907 |
text = context.token |
| 1908 |
result = {"completions": [SimpleCompletion("completion_b")]} |
| 1909 |
|
| 1910 |
if text == "suppress c": |
| 1911 |
result["suppress"] = {"c_matcher"} |
| 1912 |
|
| 1913 |
if text.startswith("suppress all"): |
| 1914 |
result["suppress"] = True |
| 1915 |
if text == "suppress all but c": |
| 1916 |
result["do_not_suppress"] = {"c_matcher"} |
| 1917 |
if text == "suppress all but a": |
| 1918 |
result["do_not_suppress"] = {"a_matcher"} |
| 1919 |
|
| 1920 |
return result |
| 1921 |
|
| 1922 |
@completion_matcher(identifier="c_matcher") |
| 1923 |
def c_matcher(text): |
| 1924 |
return ["completion_c"] |
| 1925 |
|
| 1926 |
with custom_matchers([a_matcher, b_matcher, c_matcher]): |
| 1927 |
ip = get_ipython() |
| 1928 |
c = ip.Completer |
| 1929 |
|
| 1930 |
def _(text, expected): |
| 1931 |
c.use_jedi = False |
| 1932 |
s, matches = c.complete(text) |
| 1933 |
self.assertEqual(expected, matches) |
| 1934 |
|
| 1935 |
_("do not suppress", ["completion_a", "completion_b", "completion_c"]) |
| 1936 |
_("suppress all", ["completion_b"]) |
| 1937 |
_("suppress all but a", ["completion_a", "completion_b"]) |
| 1938 |
_("suppress all but c", ["completion_b", "completion_c"]) |
| 1939 |
|
| 1940 |
def configure(suppression_config): |
| 1941 |
cfg = Config() |
| 1942 |
cfg.IPCompleter.suppress_competing_matchers = suppression_config |
| 1943 |
c.update_config(cfg) |
| 1944 |
|
| 1945 |
# test that configuration takes priority over the run-time decisions |
| 1946 |
|
| 1947 |
configure(False) |
| 1948 |
_("suppress all", ["completion_a", "completion_b", "completion_c"]) |
| 1949 |
|
| 1950 |
configure({"b_matcher": False}) |
| 1951 |
_("suppress all", ["completion_a", "completion_b", "completion_c"]) |
| 1952 |
|
| 1953 |
configure({"a_matcher": False}) |
| 1954 |
_("suppress all", ["completion_b"]) |
| 1955 |
|
| 1956 |
configure({"b_matcher": True}) |
| 1957 |
_("do not suppress", ["completion_b"]) |
| 1958 |
|
| 1959 |
configure(True) |
| 1960 |
_("do not suppress", ["completion_a"]) |
| 1961 |
|
| 1962 |
def test_matcher_suppression_with_iterator(self): |
| 1963 |
@completion_matcher(identifier="matcher_returning_iterator") |
| 1964 |
def matcher_returning_iterator(text): |
| 1965 |
return iter(["completion_iter"]) |
| 1966 |
|
| 1967 |
@completion_matcher(identifier="matcher_returning_list") |
| 1968 |
def matcher_returning_list(text): |
| 1969 |
return ["completion_list"] |
| 1970 |
|
| 1971 |
with custom_matchers([matcher_returning_iterator, matcher_returning_list]): |
| 1972 |
ip = get_ipython() |
| 1973 |
c = ip.Completer |
| 1974 |
|
| 1975 |
def _(text, expected): |
| 1976 |
c.use_jedi = False |
| 1977 |
s, matches = c.complete(text) |
| 1978 |
self.assertEqual(expected, matches) |
| 1979 |
|
| 1980 |
def configure(suppression_config): |
| 1981 |
cfg = Config() |
| 1982 |
cfg.IPCompleter.suppress_competing_matchers = suppression_config |
| 1983 |
c.update_config(cfg) |
| 1984 |
|
| 1985 |
configure(False) |
| 1986 |
_("---", ["completion_iter", "completion_list"]) |
| 1987 |
|
| 1988 |
configure(True) |
| 1989 |
_("---", ["completion_iter"]) |
| 1990 |
|
| 1991 |
configure(None) |
| 1992 |
_("--", ["completion_iter", "completion_list"]) |
| 1993 |
|
| 1994 |
@pytest.mark.xfail( |
| 1995 |
sys.version_info.releaselevel in ("alpha",), |
| 1996 |
reason="Parso does not yet parse 3.13", |
| 1997 |
) |
| 1998 |
def test_matcher_suppression_with_jedi(self): |
| 1999 |
ip = get_ipython() |
| 2000 |
c = ip.Completer |
| 2001 |
c.use_jedi = True |
| 2002 |
|
| 2003 |
def configure(suppression_config): |
| 2004 |
cfg = Config() |
| 2005 |
cfg.IPCompleter.suppress_competing_matchers = suppression_config |
| 2006 |
c.update_config(cfg) |
| 2007 |
|
| 2008 |
def _(): |
| 2009 |
with provisionalcompleter(): |
| 2010 |
matches = [completion.text for completion in c.completions("dict.", 5)] |
| 2011 |
self.assertIn("keys", matches) |
| 2012 |
|
| 2013 |
configure(False) |
| 2014 |
_() |
| 2015 |
|
| 2016 |
configure(True) |
| 2017 |
_() |
| 2018 |
|
| 2019 |
configure(None) |
| 2020 |
_() |
| 2021 |
|
| 2022 |
def test_matcher_disabling(self): |
| 2023 |
@completion_matcher(identifier="a_matcher") |
| 2024 |
def a_matcher(text): |
| 2025 |
return ["completion_a"] |
| 2026 |
|
| 2027 |
@completion_matcher(identifier="b_matcher") |
| 2028 |
def b_matcher(text): |
| 2029 |
return ["completion_b"] |
| 2030 |
|
| 2031 |
def _(expected): |
| 2032 |
s, matches = c.complete("completion_") |
| 2033 |
self.assertEqual(expected, matches) |
| 2034 |
|
| 2035 |
with custom_matchers([a_matcher, b_matcher]): |
| 2036 |
ip = get_ipython() |
| 2037 |
c = ip.Completer |
| 2038 |
|
| 2039 |
_(["completion_a", "completion_b"]) |
| 2040 |
|
| 2041 |
cfg = Config() |
| 2042 |
cfg.IPCompleter.disable_matchers = ["b_matcher"] |
| 2043 |
c.update_config(cfg) |
| 2044 |
|
| 2045 |
_(["completion_a"]) |
| 2046 |
|
| 2047 |
cfg.IPCompleter.disable_matchers = [] |
| 2048 |
c.update_config(cfg) |
| 2049 |
|
| 2050 |
def test_matcher_priority(self): |
| 2051 |
@completion_matcher(identifier="a_matcher", priority=0, api_version=2) |
| 2052 |
def a_matcher(text): |
| 2053 |
return {"completions": [SimpleCompletion("completion_a")], "suppress": True} |
| 2054 |
|
| 2055 |
@completion_matcher(identifier="b_matcher", priority=2, api_version=2) |
| 2056 |
def b_matcher(text): |
| 2057 |
return {"completions": [SimpleCompletion("completion_b")], "suppress": True} |
| 2058 |
|
| 2059 |
def _(expected): |
| 2060 |
s, matches = c.complete("completion_") |
| 2061 |
self.assertEqual(expected, matches) |
| 2062 |
|
| 2063 |
with custom_matchers([a_matcher, b_matcher]): |
| 2064 |
ip = get_ipython() |
| 2065 |
c = ip.Completer |
| 2066 |
|
| 2067 |
_(["completion_b"]) |
| 2068 |
a_matcher.matcher_priority = 3 |
| 2069 |
_(["completion_a"]) |
| 2070 |
|
| 2071 |
def test_private_attr_completions(self): |
| 2072 |
ip = get_ipython() |
| 2073 |
ip.user_ns["Test"] = type("Test", (), {"_test1": 1, "__test2": 2}) |
| 2074 |
ip.user_ns["t"] = ip.user_ns["Test"]() |
| 2075 |
ip.Completer.use_jedi = False |
| 2076 |
|
| 2077 |
try: |
| 2078 |
with provisionalcompleter(): |
| 2079 |
completions = list(ip.Completer.completions(text="t._", offset=3)) |
| 2080 |
completion_texts = [c.text for c in completions] |
| 2081 |
|
| 2082 |
assert ( |
| 2083 |
"._test1" in completion_texts |
| 2084 |
), f"_test1 not found in {completion_texts}" |
| 2085 |
assert ( |
| 2086 |
".__test2" in completion_texts |
| 2087 |
), f"__test2 not found in {completion_texts}" |
| 2088 |
finally: |
| 2089 |
del ip.user_ns["Test"] |
| 2090 |
del ip.user_ns["t"] |
| 2091 |
|
| 2092 |
|
| 2093 |
@pytest.mark.parametrize( |
| 2094 |
"use_jedi,evaluation", |
| 2095 |
[ |
| 2096 |
[True, "minimal"], |
| 2097 |
[False, "limited"], |
| 2098 |
], |
| 2099 |
) |
| 2100 |
@pytest.mark.parametrize( |
| 2101 |
"code,insert_text", |
| 2102 |
[ |
| 2103 |
[ |
| 2104 |
"\n".join( |
| 2105 |
[ |
| 2106 |
"class NotYetDefined:", |
| 2107 |
" def my_method(self) -> str:", |
| 2108 |
" return 1", |
| 2109 |
"my_instance = NotYetDefined()", |
| 2110 |
"my_insta", |
| 2111 |
] |
| 2112 |
), |
| 2113 |
"my_instance", |
| 2114 |
], |
| 2115 |
[ |
| 2116 |
"\n".join( |
| 2117 |
[ |
| 2118 |
"class NotYetDefined:", |
| 2119 |
" def my_method(self) -> str:", |
| 2120 |
" return 1", |
| 2121 |
"instance = NotYetDefined()", |
| 2122 |
"instance.", |
| 2123 |
] |
| 2124 |
), |
| 2125 |
"my_method", |
| 2126 |
], |
| 2127 |
[ |
| 2128 |
"\n".join( |
| 2129 |
[ |
| 2130 |
"class NotYetDefined:", |
| 2131 |
" def my_method(self) -> str:", |
| 2132 |
" return 1", |
| 2133 |
"my_instance = NotYetDefined()", |
| 2134 |
"my_instance.my_method().", |
| 2135 |
] |
| 2136 |
), |
| 2137 |
"capitalize", |
| 2138 |
], |
| 2139 |
[ |
| 2140 |
"\n".join( |
| 2141 |
[ |
| 2142 |
"class NotYetDefined:", |
| 2143 |
" def my_method(self):", |
| 2144 |
" return []", |
| 2145 |
"my_instance = NotYetDefined()", |
| 2146 |
"my_instance.my_method().", |
| 2147 |
] |
| 2148 |
), |
| 2149 |
"append", |
| 2150 |
], |
| 2151 |
[ |
| 2152 |
"\n".join( |
| 2153 |
[ |
| 2154 |
"class NotYetDefined:", |
| 2155 |
" @property", |
| 2156 |
" def my_property(self):", |
| 2157 |
" return 1.1", |
| 2158 |
"my_instance = NotYetDefined()", |
| 2159 |
"my_instance.my_property.", |
| 2160 |
] |
| 2161 |
), |
| 2162 |
"as_integer_ratio", |
| 2163 |
], |
| 2164 |
[ |
| 2165 |
"\n".join( |
| 2166 |
[ |
| 2167 |
"my_instance = 1.1", |
| 2168 |
"assert my_instance.", |
| 2169 |
] |
| 2170 |
), |
| 2171 |
"as_integer_ratio", |
| 2172 |
], |
| 2173 |
[ |
| 2174 |
"\n".join( |
| 2175 |
[ |
| 2176 |
"def my_test() -> float:", |
| 2177 |
" pass", |
| 2178 |
"my_test().", |
| 2179 |
] |
| 2180 |
), |
| 2181 |
"as_integer_ratio", |
| 2182 |
], |
| 2183 |
[ |
| 2184 |
"\n".join( |
| 2185 |
[ |
| 2186 |
"def my_test():", |
| 2187 |
" return {}", |
| 2188 |
"my_test().", |
| 2189 |
] |
| 2190 |
), |
| 2191 |
"keys", |
| 2192 |
], |
| 2193 |
[ |
| 2194 |
"\n".join( |
| 2195 |
[ |
| 2196 |
"l = []", |
| 2197 |
"def my_test():", |
| 2198 |
" return l", |
| 2199 |
"my_test().", |
| 2200 |
] |
| 2201 |
), |
| 2202 |
"append", |
| 2203 |
], |
| 2204 |
[ |
| 2205 |
"\n".join( |
| 2206 |
[ |
| 2207 |
"num = {1: 'one'}", |
| 2208 |
"num[2] = 'two'", |
| 2209 |
"num.", |
| 2210 |
] |
| 2211 |
), |
| 2212 |
"keys", |
| 2213 |
], |
| 2214 |
[ |
| 2215 |
"\n".join( |
| 2216 |
[ |
| 2217 |
"num = {1: 'one'}", |
| 2218 |
"num[2] = ['two']", |
| 2219 |
"num[2].", |
| 2220 |
] |
| 2221 |
), |
| 2222 |
"append", |
| 2223 |
], |
| 2224 |
[ |
| 2225 |
"\n".join( |
| 2226 |
[ |
| 2227 |
"l = []", |
| 2228 |
"class NotYetDefined:", |
| 2229 |
" def my_method(self):", |
| 2230 |
" return l", |
| 2231 |
"my_instance = NotYetDefined()", |
| 2232 |
"my_instance.my_method().", |
| 2233 |
] |
| 2234 |
), |
| 2235 |
"append", |
| 2236 |
], |
| 2237 |
[ |
| 2238 |
"\n".join( |
| 2239 |
[ |
| 2240 |
"def string_or_int(flag):", |
| 2241 |
" if flag:", |
| 2242 |
" return 'test'", |
| 2243 |
" return 1", |
| 2244 |
"string_or_int().", |
| 2245 |
] |
| 2246 |
), |
| 2247 |
["capitalize", "as_integer_ratio"], |
| 2248 |
], |
| 2249 |
[ |
| 2250 |
"\n".join( |
| 2251 |
[ |
| 2252 |
"def foo():", |
| 2253 |
" l = []", |
| 2254 |
" return l", |
| 2255 |
"foo().", |
| 2256 |
] |
| 2257 |
), |
| 2258 |
"append", |
| 2259 |
], |
| 2260 |
[ |
| 2261 |
"\n".join( |
| 2262 |
[ |
| 2263 |
"class NotYetDefined:", |
| 2264 |
" def __init__(self):", |
| 2265 |
" self.test = []", |
| 2266 |
"instance = NotYetDefined()", |
| 2267 |
"instance.", |
| 2268 |
] |
| 2269 |
), |
| 2270 |
"test", |
| 2271 |
], |
| 2272 |
[ |
| 2273 |
"\n".join( |
| 2274 |
[ |
| 2275 |
"class NotYetDefined:", |
| 2276 |
" def __init__(instance):", |
| 2277 |
" instance.test = []", |
| 2278 |
"instance = NotYetDefined()", |
| 2279 |
"instance.test.", |
| 2280 |
] |
| 2281 |
), |
| 2282 |
"append", |
| 2283 |
], |
| 2284 |
[ |
| 2285 |
"\n".join( |
| 2286 |
[ |
| 2287 |
"class NotYetDefined:", |
| 2288 |
" def __init__(this):", |
| 2289 |
" this.test:str = []", |
| 2290 |
"instance = NotYetDefined()", |
| 2291 |
"instance.test.", |
| 2292 |
] |
| 2293 |
), |
| 2294 |
"capitalize", |
| 2295 |
], |
| 2296 |
[ |
| 2297 |
"\n".join( |
| 2298 |
[ |
| 2299 |
"l = []", |
| 2300 |
"class NotYetDefined:", |
| 2301 |
" def __init__(me):", |
| 2302 |
" me.test = l", |
| 2303 |
"instance = NotYetDefined()", |
| 2304 |
"instance.test.", |
| 2305 |
] |
| 2306 |
), |
| 2307 |
"append", |
| 2308 |
], |
| 2309 |
[ |
| 2310 |
"\n".join( |
| 2311 |
[ |
| 2312 |
"class NotYetDefined:", |
| 2313 |
" def test(self):", |
| 2314 |
" self.l = []", |
| 2315 |
" return self.l", |
| 2316 |
"instance = NotYetDefined()", |
| 2317 |
"instance.test().", |
| 2318 |
] |
| 2319 |
), |
| 2320 |
"append", |
| 2321 |
], |
| 2322 |
[ |
| 2323 |
"\n".join( |
| 2324 |
[ |
| 2325 |
"class NotYetDefined:", |
| 2326 |
" def test():", |
| 2327 |
" return []", |
| 2328 |
"instance = NotYetDefined()", |
| 2329 |
"instance.test().", |
| 2330 |
] |
| 2331 |
), |
| 2332 |
"append", |
| 2333 |
], |
| 2334 |
[ |
| 2335 |
"\n".join( |
| 2336 |
[ |
| 2337 |
"def foo():", |
| 2338 |
" if some_condition:", |
| 2339 |
" return {'top':{'mid':{'leaf': 2}}}", |
| 2340 |
" return {'top': {'mid':[]}}", |
| 2341 |
"foo()['top']['mid'].", |
| 2342 |
] |
| 2343 |
), |
| 2344 |
["keys", "append"], |
| 2345 |
], |
| 2346 |
[ |
| 2347 |
"\n".join( |
| 2348 |
[ |
| 2349 |
"def foo():", |
| 2350 |
" if some_condition:", |
| 2351 |
" return {'top':{'mid':{'leaf': 2}}}", |
| 2352 |
" return {'top': {'mid':[]}}", |
| 2353 |
"foo()['top']['mid']['leaf'].", |
| 2354 |
] |
| 2355 |
), |
| 2356 |
"as_integer_ratio", |
| 2357 |
], |
| 2358 |
[ |
| 2359 |
"\n".join( |
| 2360 |
[ |
| 2361 |
"async def async_func():", |
| 2362 |
" return []", |
| 2363 |
"async_func().", |
| 2364 |
] |
| 2365 |
), |
| 2366 |
"cr_await", |
| 2367 |
], |
| 2368 |
[ |
| 2369 |
"\n".join( |
| 2370 |
[ |
| 2371 |
"async def async_func():", |
| 2372 |
" return []", |
| 2373 |
"(await async_func()).", |
| 2374 |
] |
| 2375 |
), |
| 2376 |
"append", |
| 2377 |
], |
| 2378 |
[ |
| 2379 |
"\n".join(["t = []", "if some_condition:", " t."]), |
| 2380 |
"append", |
| 2381 |
], |
| 2382 |
[ |
| 2383 |
"\n".join( |
| 2384 |
[ |
| 2385 |
"t = []", |
| 2386 |
"if some_condition:", |
| 2387 |
" t = 'string'", |
| 2388 |
"t.", |
| 2389 |
] |
| 2390 |
), |
| 2391 |
["append", "capitalize"], |
| 2392 |
], |
| 2393 |
[ |
| 2394 |
"\n".join( |
| 2395 |
[ |
| 2396 |
"t = []", |
| 2397 |
"if some_condition:", |
| 2398 |
" t = 'string'", |
| 2399 |
"else:", |
| 2400 |
" t.", |
| 2401 |
] |
| 2402 |
), |
| 2403 |
"append", |
| 2404 |
], |
| 2405 |
[ |
| 2406 |
"\n".join( |
| 2407 |
[ |
| 2408 |
"t = []", |
| 2409 |
"if some_condition:", |
| 2410 |
" t = 'string'", |
| 2411 |
"else:", |
| 2412 |
" t = 1", |
| 2413 |
"t.", |
| 2414 |
] |
| 2415 |
), |
| 2416 |
["append", "capitalize", "as_integer_ratio"], |
| 2417 |
], |
| 2418 |
[ |
| 2419 |
"\n".join( |
| 2420 |
[ |
| 2421 |
"t = []", |
| 2422 |
"if condition_1:", |
| 2423 |
" t = 'string'", |
| 2424 |
"elif condition_2:", |
| 2425 |
" t = 1", |
| 2426 |
"elif condition_3:", |
| 2427 |
" t.", |
| 2428 |
] |
| 2429 |
), |
| 2430 |
"append", |
| 2431 |
], |
| 2432 |
[ |
| 2433 |
"\n".join( |
| 2434 |
[ |
| 2435 |
"t = []", |
| 2436 |
"if condition_1:", |
| 2437 |
" t = 'string'", |
| 2438 |
"elif condition_2:", |
| 2439 |
" t = 1", |
| 2440 |
"elif condition_3:", |
| 2441 |
" t = {}", |
| 2442 |
"t.", |
| 2443 |
] |
| 2444 |
), |
| 2445 |
["append", "capitalize", "as_integer_ratio", "keys"], |
| 2446 |
], |
| 2447 |
[ |
| 2448 |
"\n".join( |
| 2449 |
[ |
| 2450 |
"t = []", |
| 2451 |
"if condition_1:", |
| 2452 |
" if condition_2:", |
| 2453 |
" t = 'nested'", |
| 2454 |
"t.", |
| 2455 |
] |
| 2456 |
), |
| 2457 |
["append", "capitalize"], |
| 2458 |
], |
| 2459 |
[ |
| 2460 |
"\n".join( |
| 2461 |
[ |
| 2462 |
"a = []", |
| 2463 |
"while condition:", |
| 2464 |
" a.", |
| 2465 |
] |
| 2466 |
), |
| 2467 |
"append", |
| 2468 |
], |
| 2469 |
[ |
| 2470 |
"\n".join( |
| 2471 |
[ |
| 2472 |
"t = []", |
| 2473 |
"while condition:", |
| 2474 |
" t = 'str'", |
| 2475 |
"t.", |
| 2476 |
] |
| 2477 |
), |
| 2478 |
["append", "capitalize"], |
| 2479 |
], |
| 2480 |
[ |
| 2481 |
"\n".join( |
| 2482 |
[ |
| 2483 |
"t = []", |
| 2484 |
"while condition_1:", |
| 2485 |
" while condition_2:", |
| 2486 |
" t = 'str'", |
| 2487 |
"t.", |
| 2488 |
] |
| 2489 |
), |
| 2490 |
["append", "capitalize"], |
| 2491 |
], |
| 2492 |
[ |
| 2493 |
"\n".join( |
| 2494 |
[ |
| 2495 |
"for i in range(10):", |
| 2496 |
" i.", |
| 2497 |
] |
| 2498 |
), |
| 2499 |
"bit_length", |
| 2500 |
], |
| 2501 |
[ |
| 2502 |
"\n".join( |
| 2503 |
[ |
| 2504 |
"for i in range(10):", |
| 2505 |
" if i % 2 == 0:", |
| 2506 |
" i.", |
| 2507 |
] |
| 2508 |
), |
| 2509 |
"bit_length", |
| 2510 |
], |
| 2511 |
[ |
| 2512 |
"\n".join( |
| 2513 |
[ |
| 2514 |
"for item in ['a', 'b', 'c']:", |
| 2515 |
" item.", |
| 2516 |
] |
| 2517 |
), |
| 2518 |
"capitalize", |
| 2519 |
], |
| 2520 |
[ |
| 2521 |
"\n".join( |
| 2522 |
[ |
| 2523 |
"for key, value in {'a': 1, 'b': 2}.items():", |
| 2524 |
" key.", |
| 2525 |
] |
| 2526 |
), |
| 2527 |
"capitalize", |
| 2528 |
], |
| 2529 |
[ |
| 2530 |
"\n".join( |
| 2531 |
[ |
| 2532 |
"for key, value in {'a': 1, 'b': 2}.items():", |
| 2533 |
" value.", |
| 2534 |
] |
| 2535 |
), |
| 2536 |
"bit_length", |
| 2537 |
], |
| 2538 |
[ |
| 2539 |
"\n".join( |
| 2540 |
[ |
| 2541 |
"for sublist in [[1, 2], [3, 4]]:", |
| 2542 |
" sublist.", |
| 2543 |
] |
| 2544 |
), |
| 2545 |
"append", |
| 2546 |
], |
| 2547 |
[ |
| 2548 |
"\n".join( |
| 2549 |
[ |
| 2550 |
"for sublist in [[1, 2], [3, 4]]:", |
| 2551 |
" for item in sublist:", |
| 2552 |
" item.", |
| 2553 |
] |
| 2554 |
), |
| 2555 |
"bit_length", |
| 2556 |
], |
| 2557 |
[ |
| 2558 |
"\n".join( |
| 2559 |
[ |
| 2560 |
"t: list[str]", |
| 2561 |
"t[0].", |
| 2562 |
] |
| 2563 |
), |
| 2564 |
["capitalize"], |
| 2565 |
], |
| 2566 |
], |
| 2567 |
) |
| 2568 |
def test_undefined_variables(use_jedi, evaluation, code, insert_text): |
| 2569 |
offset = len(code) |
| 2570 |
ip.Completer.use_jedi = use_jedi |
| 2571 |
ip.Completer.evaluation = evaluation |
| 2572 |
|
| 2573 |
with provisionalcompleter(): |
| 2574 |
completions = list(ip.Completer.completions(text=code, offset=offset)) |
| 2575 |
insert_texts = insert_text if isinstance(insert_text, list) else [insert_text] |
| 2576 |
for text in insert_texts: |
| 2577 |
match = [c for c in completions if c.text.lstrip(".") == text] |
| 2578 |
message_on_fail = f"{text} not found among {[c.text for c in completions]}" |
| 2579 |
assert len(match) == 1, message_on_fail |
| 2580 |
|
| 2581 |
|
| 2582 |
@pytest.mark.parametrize( |
| 2583 |
"code,insert_text", |
| 2584 |
[ |
| 2585 |
[ |
| 2586 |
"\n".join( |
| 2587 |
[ |
| 2588 |
"t: dict = {'a': []}", |
| 2589 |
"t['a'].", |
| 2590 |
] |
| 2591 |
), |
| 2592 |
["append"], |
| 2593 |
], |
| 2594 |
[ |
| 2595 |
"\n".join( |
| 2596 |
[ |
| 2597 |
"t: int | dict = {'a': []}", |
| 2598 |
"t.", |
| 2599 |
] |
| 2600 |
), |
| 2601 |
["keys", "bit_length"], |
| 2602 |
], |
| 2603 |
[ |
| 2604 |
"\n".join( |
| 2605 |
[ |
| 2606 |
"t: int | dict = {'a': []}", |
| 2607 |
"t['a'].", |
| 2608 |
] |
| 2609 |
), |
| 2610 |
"append", |
| 2611 |
], |
| 2612 |
# Test union types |
| 2613 |
[ |
| 2614 |
"\n".join( |
| 2615 |
[ |
| 2616 |
"t: int | str", |
| 2617 |
"t.", |
| 2618 |
] |
| 2619 |
), |
| 2620 |
["bit_length", "capitalize"], |
| 2621 |
], |
| 2622 |
[ |
| 2623 |
"\n".join( |
| 2624 |
[ |
| 2625 |
"def func() -> int | str: pass", |
| 2626 |
"func().", |
| 2627 |
] |
| 2628 |
), |
| 2629 |
["bit_length", "capitalize"], |
| 2630 |
], |
| 2631 |
[ |
| 2632 |
"\n".join( |
| 2633 |
[ |
| 2634 |
"t: list = ['test']", |
| 2635 |
"t[0].", |
| 2636 |
] |
| 2637 |
), |
| 2638 |
["capitalize"], |
| 2639 |
], |
| 2640 |
[ |
| 2641 |
"\n".join( |
| 2642 |
[ |
| 2643 |
"class T:", |
| 2644 |
" @property", |
| 2645 |
" def p(self) -> int | str: pass", |
| 2646 |
"t = T()", |
| 2647 |
"t.p.", |
| 2648 |
] |
| 2649 |
), |
| 2650 |
["bit_length", "capitalize"], |
| 2651 |
], |
| 2652 |
], |
| 2653 |
) |
| 2654 |
def test_undefined_variables_without_jedi(code, insert_text): |
| 2655 |
offset = len(code) |
| 2656 |
ip.Completer.use_jedi = False |
| 2657 |
ip.Completer.evaluation = "limited" |
| 2658 |
|
| 2659 |
with provisionalcompleter(): |
| 2660 |
completions = list(ip.Completer.completions(text=code, offset=offset)) |
| 2661 |
insert_texts = insert_text if isinstance(insert_text, list) else [insert_text] |
| 2662 |
for text in insert_texts: |
| 2663 |
match = [c for c in completions if c.text.lstrip(".") == text] |
| 2664 |
message_on_fail = f"{text} not found among {[c.text for c in completions]}" |
| 2665 |
assert len(match) == 1, message_on_fail |
| 2666 |
|
| 2667 |
|
| 2668 |
@pytest.mark.parametrize( |
| 2669 |
"code", |
| 2670 |
[ |
| 2671 |
"\n".join( |
| 2672 |
[ |
| 2673 |
"def my_test() -> float:", |
| 2674 |
" return 1.1", |
| 2675 |
"my_test().", |
| 2676 |
] |
| 2677 |
), |
| 2678 |
"\n".join( |
| 2679 |
[ |
| 2680 |
"class MyClass():", |
| 2681 |
" b: list[str]", |
| 2682 |
"x = MyClass()", |
| 2683 |
"x.b[0].", |
| 2684 |
] |
| 2685 |
), |
| 2686 |
"\n".join( |
| 2687 |
[ |
| 2688 |
"class MyClass():", |
| 2689 |
" b: list[str]", |
| 2690 |
"x = MyClass()", |
| 2691 |
"x.fake_attr().", |
| 2692 |
] |
| 2693 |
), |
| 2694 |
], |
| 2695 |
) |
| 2696 |
def test_no_file_completions_in_attr_access(code): |
| 2697 |
"""Test that files are not suggested during attribute/method completion.""" |
| 2698 |
with TemporaryWorkingDirectory(): |
| 2699 |
open(".hidden", "w", encoding="utf-8").close() |
| 2700 |
offset = len(code) |
| 2701 |
for use_jedi in (True, False): |
| 2702 |
with provisionalcompleter(), jedi_status(use_jedi): |
| 2703 |
completions = list(ip.Completer.completions(text=code, offset=offset)) |
| 2704 |
matches = [c for c in completions if c.text.lstrip(".") == "hidden"] |
| 2705 |
assert ( |
| 2706 |
len(matches) == 0 |
| 2707 |
), f"File '.hidden' should not appear in attribute completion" |
| 2708 |
|
| 2709 |
|
| 2710 |
@pytest.mark.parametrize( |
| 2711 |
"line,expected", |
| 2712 |
[ |
| 2713 |
# Basic test cases |
| 2714 |
("np.", "attribute"), |
| 2715 |
("np.ran", "attribute"), |
| 2716 |
("np.random.rand(np.random.ran", "attribute"), |
| 2717 |
("np.random.rand(n", "global"), |
| 2718 |
("d['k.e.y.'](ran", "global"), |
| 2719 |
("d[0].k", "attribute"), |
| 2720 |
("a = { 'a': np.ran", "attribute"), |
| 2721 |
("n", "global"), |
| 2722 |
("", "global"), |
| 2723 |
# Dots in string literals |
| 2724 |
('some_var = "this is a string with a dot.', "global"), |
| 2725 |
("text = 'another string with a dot.", "global"), |
| 2726 |
('f"greeting {user.na', "attribute"), # Cursor in f-string expression |
| 2727 |
('t"welcome {guest.na', "attribute"), # Cursor in t-string expression |
| 2728 |
('f"hello {name} worl', "global"), # Cursor in f-string outside expression |
| 2729 |
('f"hello {{a.', "global"), |
| 2730 |
('f"hello {{{a.', "attribute"), |
| 2731 |
# Backslash escapes in strings |
| 2732 |
('var = "string with \\"escaped quote and a dot.', "global"), |
| 2733 |
("escaped = 'single \\'quote\\' with a dot.", "global"), |
| 2734 |
# Multi-line strings |
| 2735 |
('multi = """This is line one\nwith a dot.', "global"), |
| 2736 |
("multi_single = '''Another\nmulti-line\nwith a dot.", "global"), |
| 2737 |
# Inline comments |
| 2738 |
("x = 5 # This is a comment", "global"), |
| 2739 |
("y = obj.method() # Comment after dot.method", "global"), |
| 2740 |
# Hash symbol within string literals should not be treated as comments |
| 2741 |
("d['#'] = np.", "attribute"), |
| 2742 |
# Nested parentheses with dots |
| 2743 |
("complex_expr = (func((obj.method(param.attr", "attribute"), |
| 2744 |
("multiple_nesting = {key: [value.attr", "attribute"), |
| 2745 |
# Numbers |
| 2746 |
("3.", "global"), |
| 2747 |
("3.14", "global"), |
| 2748 |
("-42.14", "global"), |
| 2749 |
("x = func(3.14", "global"), |
| 2750 |
("x = func(a3.", "attribute"), |
| 2751 |
("x = func(a3.12", "global"), |
| 2752 |
("3.1.", "attribute"), |
| 2753 |
("-3.1.", "attribute"), |
| 2754 |
("(3).", "attribute"), |
| 2755 |
# Additional cases |
| 2756 |
("", "global"), |
| 2757 |
('str_with_code = "x.attr', "global"), |
| 2758 |
('f"formatted {obj.attr', "attribute"), |
| 2759 |
('f"formatted {obj.attr}', "global"), |
| 2760 |
("dict_with_dots = {'key.with.dots': value.attr", "attribute"), |
| 2761 |
("d[f'{a}']['{a.", "global"), |
| 2762 |
("ls .", "global"), |
| 2763 |
("t._", "attribute"), |
| 2764 |
("t.__a", "attribute"), |
| 2765 |
], |
| 2766 |
) |
| 2767 |
def test_completion_context(line, expected): |
| 2768 |
"""Test completion context""" |
| 2769 |
ip = get_ipython() |
| 2770 |
get_context = ip.Completer._determine_completion_context |
| 2771 |
result = get_context(line) |
| 2772 |
assert result.value == expected, f"Failed on input: '{line}'" |
| 2773 |
|
| 2774 |
|
| 2775 |
@pytest.mark.parametrize( |
| 2776 |
"line,expected,expected_after_assignment", |
| 2777 |
[ |
| 2778 |
("test_alias file", True, False), # overshadowed by variable |
| 2779 |
("test_alias .", True, False), |
| 2780 |
("test_alias file.", True, False), |
| 2781 |
("%test_alias .file.ext", True, True), # magic, not affected by variable |
| 2782 |
("!test_alias file.", True, True), # bang, not affected by variable |
| 2783 |
], |
| 2784 |
) |
| 2785 |
def test_completion_in_cli_context(line, expected, expected_after_assignment): |
| 2786 |
"""Test completion context with and without variable overshadowing""" |
| 2787 |
ip = get_ipython() |
| 2788 |
ip.run_cell("alias test_alias echo test_alias") |
| 2789 |
get_context = ip.Completer._is_completing_in_cli_context |
| 2790 |
|
| 2791 |
# Normal case |
| 2792 |
result = get_context(line) |
| 2793 |
assert result == expected, f"Failed on input: '{line}'" |
| 2794 |
|
| 2795 |
# Test with alias assigned as a variable |
| 2796 |
try: |
| 2797 |
ip.user_ns["test_alias"] = "some_value" |
| 2798 |
result_after_assignment = get_context(line) |
| 2799 |
assert ( |
| 2800 |
result_after_assignment == expected_after_assignment |
| 2801 |
), f"Failed after assigning 'ls' as a variable for input: '{line}'" |
| 2802 |
finally: |
| 2803 |
ip.user_ns.pop("test_alias", None) |
| 2804 |
|
| 2805 |
|
| 2806 |
@pytest.mark.xfail(reason="Completion context not yet supported") |
| 2807 |
@pytest.mark.parametrize( |
| 2808 |
"line, expected", |
| 2809 |
[ |
| 2810 |
("f'{f'a.", "global"), # Nested f-string |
| 2811 |
("3a.", "global"), # names starting with numbers or other symbols |
| 2812 |
("$).", "global"), # random things with dot at end |
| 2813 |
], |
| 2814 |
) |
| 2815 |
def test_unsupported_completion_context(line, expected): |
| 2816 |
"""Test unsupported completion context""" |
| 2817 |
ip = get_ipython() |
| 2818 |
get_context = ip.Completer._determine_completion_context |
| 2819 |
result = get_context(line) |
| 2820 |
assert result.value == expected, f"Failed on input: '{line}'" |
| 2821 |
|
| 2822 |
|
| 2823 |
@pytest.mark.parametrize( |
| 2824 |
"setup,code,expected,not_expected", |
| 2825 |
[ |
| 2826 |
('a="str"; b=1', "(a, b.", [".bit_count", ".conjugate"], [".count"]), |
| 2827 |
('a="str"; b=1', "(a, b).", [".count"], [".bit_count", ".capitalize"]), |
| 2828 |
('x="str"; y=1', "x = {1, y.", [".bit_count"], [".count"]), |
| 2829 |
('x="str"; y=1', "x = [1, y.", [".bit_count"], [".count"]), |
| 2830 |
('x="str"; y=1; fun=lambda x:x', "x = fun(1, y.", [".bit_count"], [".count"]), |
| 2831 |
], |
| 2832 |
) |
| 2833 |
def test_misc_no_jedi_completions(setup, code, expected, not_expected): |
| 2834 |
ip = get_ipython() |
| 2835 |
c = ip.Completer |
| 2836 |
ip.ex(setup) |
| 2837 |
with provisionalcompleter(), jedi_status(False): |
| 2838 |
matches = c.all_completions(code) |
| 2839 |
assert set(expected) - set(matches) == set(), set(matches) |
| 2840 |
assert set(matches).intersection(set(not_expected)) == set() |
| 2841 |
|
| 2842 |
|
| 2843 |
@pytest.mark.parametrize( |
| 2844 |
"code,expected", |
| 2845 |
[ |
| 2846 |
(" (a, b", "b"), |
| 2847 |
("(a, b", "b"), |
| 2848 |
("(a, b)", ""), # trim always start by trimming |
| 2849 |
(" (a, b)", "(a, b)"), |
| 2850 |
(" [a, b]", "[a, b]"), |
| 2851 |
(" a, b", "b"), |
| 2852 |
("x = {1, y", "y"), |
| 2853 |
("x = [1, y", "y"), |
| 2854 |
("x = fun(1, y", "y"), |
| 2855 |
(" assert a", "a"), |
| 2856 |
], |
| 2857 |
) |
| 2858 |
def test_trim_expr(code, expected): |
| 2859 |
c = get_ipython().Completer |
| 2860 |
assert c._trim_expr(code) == expected |
| 2861 |
|
| 2862 |
|
| 2863 |
@pytest.mark.parametrize( |
| 2864 |
"input, expected", |
| 2865 |
[ |
| 2866 |
["1.234", "1.234"], |
| 2867 |
# should match signed numbers |
| 2868 |
["+1", "+1"], |
| 2869 |
["-1", "-1"], |
| 2870 |
["-1.0", "-1.0"], |
| 2871 |
["-1.", "-1."], |
| 2872 |
["+1.", "+1."], |
| 2873 |
[".1", ".1"], |
| 2874 |
# should not match non-numbers |
| 2875 |
["1..", None], |
| 2876 |
["..", None], |
| 2877 |
[".1.", None], |
| 2878 |
# should match after comma |
| 2879 |
[",1", "1"], |
| 2880 |
[", 1", "1"], |
| 2881 |
[", .1", ".1"], |
| 2882 |
[", +.1", "+.1"], |
| 2883 |
# should not match after trailing spaces |
| 2884 |
[".1 ", None], |
| 2885 |
# some complex cases |
| 2886 |
["0b_0011_1111_0100_1110", "0b_0011_1111_0100_1110"], |
| 2887 |
["0xdeadbeef", "0xdeadbeef"], |
| 2888 |
["0b_1110_0101", "0b_1110_0101"], |
| 2889 |
# should not match if in an operation |
| 2890 |
["1 + 1", None], |
| 2891 |
[", 1 + 1", None], |
| 2892 |
], |
| 2893 |
) |
| 2894 |
def test_match_numeric_literal_for_dict_key(input, expected): |
| 2895 |
assert _match_number_in_dict_key_prefix(input) == expected |