##// END OF EJS Templates
test failure
Matthias Bussonnier -
Show More
@@ -1,1123 +1,1129 b''
1 1 # encoding: utf-8
2 2 """Tests for the IPython tab-completion machinery."""
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7 import os
8 8 import sys
9 9 import textwrap
10 10 import unittest
11 11
12 12 from contextlib import contextmanager
13 13
14 14 import nose.tools as nt
15 15
16 16 from traitlets.config.loader import Config
17 17 from IPython import get_ipython
18 18 from IPython.core import completer
19 19 from IPython.external import decorators
20 20 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
21 21 from IPython.utils.generics import complete_object
22 22 from IPython.testing import decorators as dec
23 23
24 24 from IPython.core.completer import (
25 25 Completion,
26 26 provisionalcompleter,
27 27 match_dict_keys,
28 28 _deduplicate_completions,
29 29 )
30 30 from nose.tools import assert_in, assert_not_in
31 31
32 32 # -----------------------------------------------------------------------------
33 33 # Test functions
34 34 # -----------------------------------------------------------------------------
35 35
36 36 def test_unicode_range():
37 37 """
38 38 Test that the ranges we test for unicode names give the same number of
39 39 results than testing the full length.
40 40 """
41 41 from IPython.core.completer import _unicode_name_compute, _UNICODE_RANGES
42 42
43 43 expected_list = _unicode_name_compute([(0, 0x110000)])
44 44 test = _unicode_name_compute(_UNICODE_RANGES)
45 len_exp = len(expected_list)
46 len_test = len(test)
45 47
46 assert len(expected_list) == len(test)
47 assert len(expected_list) == 131808
48 # do not inline the len() or on error pytest will try to print the 130 000 +
49 # elements.
50 assert len_exp == len_test
51
52 # fail if new unicode symbols have been added.
53 assert len_exp <= 131808
48 54
49 55
50 56 @contextmanager
51 57 def greedy_completion():
52 58 ip = get_ipython()
53 59 greedy_original = ip.Completer.greedy
54 60 try:
55 61 ip.Completer.greedy = True
56 62 yield
57 63 finally:
58 64 ip.Completer.greedy = greedy_original
59 65
60 66
61 67 def test_protect_filename():
62 68 if sys.platform == "win32":
63 69 pairs = [
64 70 ("abc", "abc"),
65 71 (" abc", '" abc"'),
66 72 ("a bc", '"a bc"'),
67 73 ("a bc", '"a bc"'),
68 74 (" bc", '" bc"'),
69 75 ]
70 76 else:
71 77 pairs = [
72 78 ("abc", "abc"),
73 79 (" abc", r"\ abc"),
74 80 ("a bc", r"a\ bc"),
75 81 ("a bc", r"a\ \ bc"),
76 82 (" bc", r"\ \ bc"),
77 83 # On posix, we also protect parens and other special characters.
78 84 ("a(bc", r"a\(bc"),
79 85 ("a)bc", r"a\)bc"),
80 86 ("a( )bc", r"a\(\ \)bc"),
81 87 ("a[1]bc", r"a\[1\]bc"),
82 88 ("a{1}bc", r"a\{1\}bc"),
83 89 ("a#bc", r"a\#bc"),
84 90 ("a?bc", r"a\?bc"),
85 91 ("a=bc", r"a\=bc"),
86 92 ("a\\bc", r"a\\bc"),
87 93 ("a|bc", r"a\|bc"),
88 94 ("a;bc", r"a\;bc"),
89 95 ("a:bc", r"a\:bc"),
90 96 ("a'bc", r"a\'bc"),
91 97 ("a*bc", r"a\*bc"),
92 98 ('a"bc', r"a\"bc"),
93 99 ("a^bc", r"a\^bc"),
94 100 ("a&bc", r"a\&bc"),
95 101 ]
96 102 # run the actual tests
97 103 for s1, s2 in pairs:
98 104 s1p = completer.protect_filename(s1)
99 105 nt.assert_equal(s1p, s2)
100 106
101 107
102 108 def check_line_split(splitter, test_specs):
103 109 for part1, part2, split in test_specs:
104 110 cursor_pos = len(part1)
105 111 line = part1 + part2
106 112 out = splitter.split_line(line, cursor_pos)
107 113 nt.assert_equal(out, split)
108 114
109 115
110 116 def test_line_split():
111 117 """Basic line splitter test with default specs."""
112 118 sp = completer.CompletionSplitter()
113 119 # The format of the test specs is: part1, part2, expected answer. Parts 1
114 120 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
115 121 # was at the end of part1. So an empty part2 represents someone hitting
116 122 # tab at the end of the line, the most common case.
117 123 t = [
118 124 ("run some/scrip", "", "some/scrip"),
119 125 ("run scripts/er", "ror.py foo", "scripts/er"),
120 126 ("echo $HOM", "", "HOM"),
121 127 ("print sys.pa", "", "sys.pa"),
122 128 ("print(sys.pa", "", "sys.pa"),
123 129 ("execfile('scripts/er", "", "scripts/er"),
124 130 ("a[x.", "", "x."),
125 131 ("a[x.", "y", "x."),
126 132 ('cd "some_file/', "", "some_file/"),
127 133 ]
128 134 check_line_split(sp, t)
129 135 # Ensure splitting works OK with unicode by re-running the tests with
130 136 # all inputs turned into unicode
131 137 check_line_split(sp, [map(str, p) for p in t])
132 138
133 139
134 140 class NamedInstanceMetaclass(type):
135 141 def __getitem__(cls, item):
136 142 return cls.get_instance(item)
137 143
138 144
139 145 class NamedInstanceClass(metaclass=NamedInstanceMetaclass):
140 146 def __init__(self, name):
141 147 if not hasattr(self.__class__, "instances"):
142 148 self.__class__.instances = {}
143 149 self.__class__.instances[name] = self
144 150
145 151 @classmethod
146 152 def _ipython_key_completions_(cls):
147 153 return cls.instances.keys()
148 154
149 155 @classmethod
150 156 def get_instance(cls, name):
151 157 return cls.instances[name]
152 158
153 159
154 160 class KeyCompletable:
155 161 def __init__(self, things=()):
156 162 self.things = things
157 163
158 164 def _ipython_key_completions_(self):
159 165 return list(self.things)
160 166
161 167
162 168 class TestCompleter(unittest.TestCase):
163 169 def setUp(self):
164 170 """
165 171 We want to silence all PendingDeprecationWarning when testing the completer
166 172 """
167 173 self._assertwarns = self.assertWarns(PendingDeprecationWarning)
168 174 self._assertwarns.__enter__()
169 175
170 176 def tearDown(self):
171 177 try:
172 178 self._assertwarns.__exit__(None, None, None)
173 179 except AssertionError:
174 180 pass
175 181
176 182 def test_custom_completion_error(self):
177 183 """Test that errors from custom attribute completers are silenced."""
178 184 ip = get_ipython()
179 185
180 186 class A:
181 187 pass
182 188
183 189 ip.user_ns["x"] = A()
184 190
185 191 @complete_object.register(A)
186 192 def complete_A(a, existing_completions):
187 193 raise TypeError("this should be silenced")
188 194
189 195 ip.complete("x.")
190 196
191 197 def test_custom_completion_ordering(self):
192 198 """Test that errors from custom attribute completers are silenced."""
193 199 ip = get_ipython()
194 200
195 201 _, matches = ip.complete('in')
196 202 assert matches.index('input') < matches.index('int')
197 203
198 204 def complete_example(a):
199 205 return ['example2', 'example1']
200 206
201 207 ip.Completer.custom_completers.add_re('ex*', complete_example)
202 208 _, matches = ip.complete('ex')
203 209 assert matches.index('example2') < matches.index('example1')
204 210
205 211 def test_unicode_completions(self):
206 212 ip = get_ipython()
207 213 # Some strings that trigger different types of completion. Check them both
208 214 # in str and unicode forms
209 215 s = ["ru", "%ru", "cd /", "floa", "float(x)/"]
210 216 for t in s + list(map(str, s)):
211 217 # We don't need to check exact completion values (they may change
212 218 # depending on the state of the namespace, but at least no exceptions
213 219 # should be thrown and the return value should be a pair of text, list
214 220 # values.
215 221 text, matches = ip.complete(t)
216 222 nt.assert_true(isinstance(text, str))
217 223 nt.assert_true(isinstance(matches, list))
218 224
219 225 def test_latex_completions(self):
220 226 from IPython.core.latex_symbols import latex_symbols
221 227 import random
222 228
223 229 ip = get_ipython()
224 230 # Test some random unicode symbols
225 231 keys = random.sample(latex_symbols.keys(), 10)
226 232 for k in keys:
227 233 text, matches = ip.complete(k)
228 234 nt.assert_equal(text, k)
229 235 nt.assert_equal(matches, [latex_symbols[k]])
230 236 # Test a more complex line
231 237 text, matches = ip.complete("print(\\alpha")
232 238 nt.assert_equal(text, "\\alpha")
233 239 nt.assert_equal(matches[0], latex_symbols["\\alpha"])
234 240 # Test multiple matching latex symbols
235 241 text, matches = ip.complete("\\al")
236 242 nt.assert_in("\\alpha", matches)
237 243 nt.assert_in("\\aleph", matches)
238 244
239 245 def test_latex_no_results(self):
240 246 """
241 247 forward latex should really return nothing in either field if nothing is found.
242 248 """
243 249 ip = get_ipython()
244 250 text, matches = ip.Completer.latex_matches("\\really_i_should_match_nothing")
245 251 nt.assert_equal(text, "")
246 252 nt.assert_equal(matches, ())
247 253
248 254 def test_back_latex_completion(self):
249 255 ip = get_ipython()
250 256
251 257 # do not return more than 1 matches fro \beta, only the latex one.
252 258 name, matches = ip.complete("\\Ξ²")
253 259 nt.assert_equal(matches, ['\\beta'])
254 260
255 261 def test_back_unicode_completion(self):
256 262 ip = get_ipython()
257 263
258 264 name, matches = ip.complete("\\β…€")
259 265 nt.assert_equal(matches, ("\\ROMAN NUMERAL FIVE",))
260 266
261 267 def test_forward_unicode_completion(self):
262 268 ip = get_ipython()
263 269
264 270 name, matches = ip.complete("\\ROMAN NUMERAL FIVE")
265 271 nt.assert_equal(matches, ["β…€"] ) # This is not a V
266 272 nt.assert_equal(matches, ["\u2164"] ) # same as above but explicit.
267 273
268 274 @nt.nottest # now we have a completion for \jmath
269 275 @decorators.knownfailureif(
270 276 sys.platform == "win32", "Fails if there is a C:\\j... path"
271 277 )
272 278 def test_no_ascii_back_completion(self):
273 279 ip = get_ipython()
274 280 with TemporaryWorkingDirectory(): # Avoid any filename completions
275 281 # single ascii letter that don't have yet completions
276 282 for letter in "jJ":
277 283 name, matches = ip.complete("\\" + letter)
278 284 nt.assert_equal(matches, [])
279 285
280 286 class CompletionSplitterTestCase(unittest.TestCase):
281 287 def setUp(self):
282 288 self.sp = completer.CompletionSplitter()
283 289
284 290 def test_delim_setting(self):
285 291 self.sp.delims = " "
286 292 nt.assert_equal(self.sp.delims, " ")
287 293 nt.assert_equal(self.sp._delim_expr, r"[\ ]")
288 294
289 295 def test_spaces(self):
290 296 """Test with only spaces as split chars."""
291 297 self.sp.delims = " "
292 298 t = [("foo", "", "foo"), ("run foo", "", "foo"), ("run foo", "bar", "foo")]
293 299 check_line_split(self.sp, t)
294 300
295 301 def test_has_open_quotes1(self):
296 302 for s in ["'", "'''", "'hi' '"]:
297 303 nt.assert_equal(completer.has_open_quotes(s), "'")
298 304
299 305 def test_has_open_quotes2(self):
300 306 for s in ['"', '"""', '"hi" "']:
301 307 nt.assert_equal(completer.has_open_quotes(s), '"')
302 308
303 309 def test_has_open_quotes3(self):
304 310 for s in ["''", "''' '''", "'hi' 'ipython'"]:
305 311 nt.assert_false(completer.has_open_quotes(s))
306 312
307 313 def test_has_open_quotes4(self):
308 314 for s in ['""', '""" """', '"hi" "ipython"']:
309 315 nt.assert_false(completer.has_open_quotes(s))
310 316
311 317 @decorators.knownfailureif(
312 318 sys.platform == "win32", "abspath completions fail on Windows"
313 319 )
314 320 def test_abspath_file_completions(self):
315 321 ip = get_ipython()
316 322 with TemporaryDirectory() as tmpdir:
317 323 prefix = os.path.join(tmpdir, "foo")
318 324 suffixes = ["1", "2"]
319 325 names = [prefix + s for s in suffixes]
320 326 for n in names:
321 327 open(n, "w").close()
322 328
323 329 # Check simple completion
324 330 c = ip.complete(prefix)[1]
325 331 nt.assert_equal(c, names)
326 332
327 333 # Now check with a function call
328 334 cmd = 'a = f("%s' % prefix
329 335 c = ip.complete(prefix, cmd)[1]
330 336 comp = [prefix + s for s in suffixes]
331 337 nt.assert_equal(c, comp)
332 338
333 339 def test_local_file_completions(self):
334 340 ip = get_ipython()
335 341 with TemporaryWorkingDirectory():
336 342 prefix = "./foo"
337 343 suffixes = ["1", "2"]
338 344 names = [prefix + s for s in suffixes]
339 345 for n in names:
340 346 open(n, "w").close()
341 347
342 348 # Check simple completion
343 349 c = ip.complete(prefix)[1]
344 350 nt.assert_equal(c, names)
345 351
346 352 # Now check with a function call
347 353 cmd = 'a = f("%s' % prefix
348 354 c = ip.complete(prefix, cmd)[1]
349 355 comp = {prefix + s for s in suffixes}
350 356 nt.assert_true(comp.issubset(set(c)))
351 357
352 358 def test_quoted_file_completions(self):
353 359 ip = get_ipython()
354 360 with TemporaryWorkingDirectory():
355 361 name = "foo'bar"
356 362 open(name, "w").close()
357 363
358 364 # Don't escape Windows
359 365 escaped = name if sys.platform == "win32" else "foo\\'bar"
360 366
361 367 # Single quote matches embedded single quote
362 368 text = "open('foo"
363 369 c = ip.Completer._complete(
364 370 cursor_line=0, cursor_pos=len(text), full_text=text
365 371 )[1]
366 372 nt.assert_equal(c, [escaped])
367 373
368 374 # Double quote requires no escape
369 375 text = 'open("foo'
370 376 c = ip.Completer._complete(
371 377 cursor_line=0, cursor_pos=len(text), full_text=text
372 378 )[1]
373 379 nt.assert_equal(c, [name])
374 380
375 381 # No quote requires an escape
376 382 text = "%ls foo"
377 383 c = ip.Completer._complete(
378 384 cursor_line=0, cursor_pos=len(text), full_text=text
379 385 )[1]
380 386 nt.assert_equal(c, [escaped])
381 387
382 388 def test_all_completions_dups(self):
383 389 """
384 390 Make sure the output of `IPCompleter.all_completions` does not have
385 391 duplicated prefixes.
386 392 """
387 393 ip = get_ipython()
388 394 c = ip.Completer
389 395 ip.ex("class TestClass():\n\ta=1\n\ta1=2")
390 396 for jedi_status in [True, False]:
391 397 with provisionalcompleter():
392 398 ip.Completer.use_jedi = jedi_status
393 399 matches = c.all_completions("TestCl")
394 400 assert matches == ['TestClass'], jedi_status
395 401 matches = c.all_completions("TestClass.")
396 402 assert len(matches) > 2, jedi_status
397 403 matches = c.all_completions("TestClass.a")
398 404 assert matches == ['TestClass.a', 'TestClass.a1'], jedi_status
399 405
400 406 def test_jedi(self):
401 407 """
402 408 A couple of issue we had with Jedi
403 409 """
404 410 ip = get_ipython()
405 411
406 412 def _test_complete(reason, s, comp, start=None, end=None):
407 413 l = len(s)
408 414 start = start if start is not None else l
409 415 end = end if end is not None else l
410 416 with provisionalcompleter():
411 417 ip.Completer.use_jedi = True
412 418 completions = set(ip.Completer.completions(s, l))
413 419 ip.Completer.use_jedi = False
414 420 assert_in(Completion(start, end, comp), completions, reason)
415 421
416 422 def _test_not_complete(reason, s, comp):
417 423 l = len(s)
418 424 with provisionalcompleter():
419 425 ip.Completer.use_jedi = True
420 426 completions = set(ip.Completer.completions(s, l))
421 427 ip.Completer.use_jedi = False
422 428 assert_not_in(Completion(l, l, comp), completions, reason)
423 429
424 430 import jedi
425 431
426 432 jedi_version = tuple(int(i) for i in jedi.__version__.split(".")[:3])
427 433 if jedi_version > (0, 10):
428 434 yield _test_complete, "jedi >0.9 should complete and not crash", "a=1;a.", "real"
429 435 yield _test_complete, "can infer first argument", 'a=(1,"foo");a[0].', "real"
430 436 yield _test_complete, "can infer second argument", 'a=(1,"foo");a[1].', "capitalize"
431 437 yield _test_complete, "cover duplicate completions", "im", "import", 0, 2
432 438
433 439 yield _test_not_complete, "does not mix types", 'a=(1,"foo");a[0].', "capitalize"
434 440
435 441 def test_completion_have_signature(self):
436 442 """
437 443 Lets make sure jedi is capable of pulling out the signature of the function we are completing.
438 444 """
439 445 ip = get_ipython()
440 446 with provisionalcompleter():
441 447 ip.Completer.use_jedi = True
442 448 completions = ip.Completer.completions("ope", 3)
443 449 c = next(completions) # should be `open`
444 450 ip.Completer.use_jedi = False
445 451 assert "file" in c.signature, "Signature of function was not found by completer"
446 452 assert (
447 453 "encoding" in c.signature
448 454 ), "Signature of function was not found by completer"
449 455
450 456 def test_deduplicate_completions(self):
451 457 """
452 458 Test that completions are correctly deduplicated (even if ranges are not the same)
453 459 """
454 460 ip = get_ipython()
455 461 ip.ex(
456 462 textwrap.dedent(
457 463 """
458 464 class Z:
459 465 zoo = 1
460 466 """
461 467 )
462 468 )
463 469 with provisionalcompleter():
464 470 ip.Completer.use_jedi = True
465 471 l = list(
466 472 _deduplicate_completions("Z.z", ip.Completer.completions("Z.z", 3))
467 473 )
468 474 ip.Completer.use_jedi = False
469 475
470 476 assert len(l) == 1, "Completions (Z.z<tab>) correctly deduplicate: %s " % l
471 477 assert l[0].text == "zoo" # and not `it.accumulate`
472 478
473 479 def test_greedy_completions(self):
474 480 """
475 481 Test the capability of the Greedy completer.
476 482
477 483 Most of the test here does not really show off the greedy completer, for proof
478 484 each of the text below now pass with Jedi. The greedy completer is capable of more.
479 485
480 486 See the :any:`test_dict_key_completion_contexts`
481 487
482 488 """
483 489 ip = get_ipython()
484 490 ip.ex("a=list(range(5))")
485 491 _, c = ip.complete(".", line="a[0].")
486 492 nt.assert_false(".real" in c, "Shouldn't have completed on a[0]: %s" % c)
487 493
488 494 def _(line, cursor_pos, expect, message, completion):
489 495 with greedy_completion(), provisionalcompleter():
490 496 ip.Completer.use_jedi = False
491 497 _, c = ip.complete(".", line=line, cursor_pos=cursor_pos)
492 498 nt.assert_in(expect, c, message % c)
493 499
494 500 ip.Completer.use_jedi = True
495 501 with provisionalcompleter():
496 502 completions = ip.Completer.completions(line, cursor_pos)
497 503 nt.assert_in(completion, completions)
498 504
499 505 with provisionalcompleter():
500 506 yield _, "a[0].", 5, "a[0].real", "Should have completed on a[0].: %s", Completion(
501 507 5, 5, "real"
502 508 )
503 509 yield _, "a[0].r", 6, "a[0].real", "Should have completed on a[0].r: %s", Completion(
504 510 5, 6, "real"
505 511 )
506 512
507 513 yield _, "a[0].from_", 10, "a[0].from_bytes", "Should have completed on a[0].from_: %s", Completion(
508 514 5, 10, "from_bytes"
509 515 )
510 516
511 517 def test_omit__names(self):
512 518 # also happens to test IPCompleter as a configurable
513 519 ip = get_ipython()
514 520 ip._hidden_attr = 1
515 521 ip._x = {}
516 522 c = ip.Completer
517 523 ip.ex("ip=get_ipython()")
518 524 cfg = Config()
519 525 cfg.IPCompleter.omit__names = 0
520 526 c.update_config(cfg)
521 527 with provisionalcompleter():
522 528 c.use_jedi = False
523 529 s, matches = c.complete("ip.")
524 530 nt.assert_in("ip.__str__", matches)
525 531 nt.assert_in("ip._hidden_attr", matches)
526 532
527 533 # c.use_jedi = True
528 534 # completions = set(c.completions('ip.', 3))
529 535 # nt.assert_in(Completion(3, 3, '__str__'), completions)
530 536 # nt.assert_in(Completion(3,3, "_hidden_attr"), completions)
531 537
532 538 cfg = Config()
533 539 cfg.IPCompleter.omit__names = 1
534 540 c.update_config(cfg)
535 541 with provisionalcompleter():
536 542 c.use_jedi = False
537 543 s, matches = c.complete("ip.")
538 544 nt.assert_not_in("ip.__str__", matches)
539 545 # nt.assert_in('ip._hidden_attr', matches)
540 546
541 547 # c.use_jedi = True
542 548 # completions = set(c.completions('ip.', 3))
543 549 # nt.assert_not_in(Completion(3,3,'__str__'), completions)
544 550 # nt.assert_in(Completion(3,3, "_hidden_attr"), completions)
545 551
546 552 cfg = Config()
547 553 cfg.IPCompleter.omit__names = 2
548 554 c.update_config(cfg)
549 555 with provisionalcompleter():
550 556 c.use_jedi = False
551 557 s, matches = c.complete("ip.")
552 558 nt.assert_not_in("ip.__str__", matches)
553 559 nt.assert_not_in("ip._hidden_attr", matches)
554 560
555 561 # c.use_jedi = True
556 562 # completions = set(c.completions('ip.', 3))
557 563 # nt.assert_not_in(Completion(3,3,'__str__'), completions)
558 564 # nt.assert_not_in(Completion(3,3, "_hidden_attr"), completions)
559 565
560 566 with provisionalcompleter():
561 567 c.use_jedi = False
562 568 s, matches = c.complete("ip._x.")
563 569 nt.assert_in("ip._x.keys", matches)
564 570
565 571 # c.use_jedi = True
566 572 # completions = set(c.completions('ip._x.', 6))
567 573 # nt.assert_in(Completion(6,6, "keys"), completions)
568 574
569 575 del ip._hidden_attr
570 576 del ip._x
571 577
572 578 def test_limit_to__all__False_ok(self):
573 579 """
574 580 Limit to all is deprecated, once we remove it this test can go away.
575 581 """
576 582 ip = get_ipython()
577 583 c = ip.Completer
578 584 c.use_jedi = False
579 585 ip.ex("class D: x=24")
580 586 ip.ex("d=D()")
581 587 cfg = Config()
582 588 cfg.IPCompleter.limit_to__all__ = False
583 589 c.update_config(cfg)
584 590 s, matches = c.complete("d.")
585 591 nt.assert_in("d.x", matches)
586 592
587 593 def test_get__all__entries_ok(self):
588 594 class A:
589 595 __all__ = ["x", 1]
590 596
591 597 words = completer.get__all__entries(A())
592 598 nt.assert_equal(words, ["x"])
593 599
594 600 def test_get__all__entries_no__all__ok(self):
595 601 class A:
596 602 pass
597 603
598 604 words = completer.get__all__entries(A())
599 605 nt.assert_equal(words, [])
600 606
601 607 def test_func_kw_completions(self):
602 608 ip = get_ipython()
603 609 c = ip.Completer
604 610 c.use_jedi = False
605 611 ip.ex("def myfunc(a=1,b=2): return a+b")
606 612 s, matches = c.complete(None, "myfunc(1,b")
607 613 nt.assert_in("b=", matches)
608 614 # Simulate completing with cursor right after b (pos==10):
609 615 s, matches = c.complete(None, "myfunc(1,b)", 10)
610 616 nt.assert_in("b=", matches)
611 617 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
612 618 nt.assert_in("b=", matches)
613 619 # builtin function
614 620 s, matches = c.complete(None, "min(k, k")
615 621 nt.assert_in("key=", matches)
616 622
617 623 def test_default_arguments_from_docstring(self):
618 624 ip = get_ipython()
619 625 c = ip.Completer
620 626 kwd = c._default_arguments_from_docstring("min(iterable[, key=func]) -> value")
621 627 nt.assert_equal(kwd, ["key"])
622 628 # with cython type etc
623 629 kwd = c._default_arguments_from_docstring(
624 630 "Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n"
625 631 )
626 632 nt.assert_equal(kwd, ["ncall", "resume", "nsplit"])
627 633 # white spaces
628 634 kwd = c._default_arguments_from_docstring(
629 635 "\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n"
630 636 )
631 637 nt.assert_equal(kwd, ["ncall", "resume", "nsplit"])
632 638
633 639 def test_line_magics(self):
634 640 ip = get_ipython()
635 641 c = ip.Completer
636 642 s, matches = c.complete(None, "lsmag")
637 643 nt.assert_in("%lsmagic", matches)
638 644 s, matches = c.complete(None, "%lsmag")
639 645 nt.assert_in("%lsmagic", matches)
640 646
641 647 def test_cell_magics(self):
642 648 from IPython.core.magic import register_cell_magic
643 649
644 650 @register_cell_magic
645 651 def _foo_cellm(line, cell):
646 652 pass
647 653
648 654 ip = get_ipython()
649 655 c = ip.Completer
650 656
651 657 s, matches = c.complete(None, "_foo_ce")
652 658 nt.assert_in("%%_foo_cellm", matches)
653 659 s, matches = c.complete(None, "%%_foo_ce")
654 660 nt.assert_in("%%_foo_cellm", matches)
655 661
656 662 def test_line_cell_magics(self):
657 663 from IPython.core.magic import register_line_cell_magic
658 664
659 665 @register_line_cell_magic
660 666 def _bar_cellm(line, cell):
661 667 pass
662 668
663 669 ip = get_ipython()
664 670 c = ip.Completer
665 671
666 672 # The policy here is trickier, see comments in completion code. The
667 673 # returned values depend on whether the user passes %% or not explicitly,
668 674 # and this will show a difference if the same name is both a line and cell
669 675 # magic.
670 676 s, matches = c.complete(None, "_bar_ce")
671 677 nt.assert_in("%_bar_cellm", matches)
672 678 nt.assert_in("%%_bar_cellm", matches)
673 679 s, matches = c.complete(None, "%_bar_ce")
674 680 nt.assert_in("%_bar_cellm", matches)
675 681 nt.assert_in("%%_bar_cellm", matches)
676 682 s, matches = c.complete(None, "%%_bar_ce")
677 683 nt.assert_not_in("%_bar_cellm", matches)
678 684 nt.assert_in("%%_bar_cellm", matches)
679 685
680 686 def test_magic_completion_order(self):
681 687 ip = get_ipython()
682 688 c = ip.Completer
683 689
684 690 # Test ordering of line and cell magics.
685 691 text, matches = c.complete("timeit")
686 692 nt.assert_equal(matches, ["%timeit", "%%timeit"])
687 693
688 694 def test_magic_completion_shadowing(self):
689 695 ip = get_ipython()
690 696 c = ip.Completer
691 697 c.use_jedi = False
692 698
693 699 # Before importing matplotlib, %matplotlib magic should be the only option.
694 700 text, matches = c.complete("mat")
695 701 nt.assert_equal(matches, ["%matplotlib"])
696 702
697 703 # The newly introduced name should shadow the magic.
698 704 ip.run_cell("matplotlib = 1")
699 705 text, matches = c.complete("mat")
700 706 nt.assert_equal(matches, ["matplotlib"])
701 707
702 708 # After removing matplotlib from namespace, the magic should again be
703 709 # the only option.
704 710 del ip.user_ns["matplotlib"]
705 711 text, matches = c.complete("mat")
706 712 nt.assert_equal(matches, ["%matplotlib"])
707 713
708 714 def test_magic_completion_shadowing_explicit(self):
709 715 """
710 716 If the user try to complete a shadowed magic, and explicit % start should
711 717 still return the completions.
712 718 """
713 719 ip = get_ipython()
714 720 c = ip.Completer
715 721
716 722 # Before importing matplotlib, %matplotlib magic should be the only option.
717 723 text, matches = c.complete("%mat")
718 724 nt.assert_equal(matches, ["%matplotlib"])
719 725
720 726 ip.run_cell("matplotlib = 1")
721 727
722 728 # After removing matplotlib from namespace, the magic should still be
723 729 # the only option.
724 730 text, matches = c.complete("%mat")
725 731 nt.assert_equal(matches, ["%matplotlib"])
726 732
727 733 def test_magic_config(self):
728 734 ip = get_ipython()
729 735 c = ip.Completer
730 736
731 737 s, matches = c.complete(None, "conf")
732 738 nt.assert_in("%config", matches)
733 739 s, matches = c.complete(None, "conf")
734 740 nt.assert_not_in("AliasManager", matches)
735 741 s, matches = c.complete(None, "config ")
736 742 nt.assert_in("AliasManager", matches)
737 743 s, matches = c.complete(None, "%config ")
738 744 nt.assert_in("AliasManager", matches)
739 745 s, matches = c.complete(None, "config Ali")
740 746 nt.assert_list_equal(["AliasManager"], matches)
741 747 s, matches = c.complete(None, "%config Ali")
742 748 nt.assert_list_equal(["AliasManager"], matches)
743 749 s, matches = c.complete(None, "config AliasManager")
744 750 nt.assert_list_equal(["AliasManager"], matches)
745 751 s, matches = c.complete(None, "%config AliasManager")
746 752 nt.assert_list_equal(["AliasManager"], matches)
747 753 s, matches = c.complete(None, "config AliasManager.")
748 754 nt.assert_in("AliasManager.default_aliases", matches)
749 755 s, matches = c.complete(None, "%config AliasManager.")
750 756 nt.assert_in("AliasManager.default_aliases", matches)
751 757 s, matches = c.complete(None, "config AliasManager.de")
752 758 nt.assert_list_equal(["AliasManager.default_aliases"], matches)
753 759 s, matches = c.complete(None, "config AliasManager.de")
754 760 nt.assert_list_equal(["AliasManager.default_aliases"], matches)
755 761
756 762 def test_magic_color(self):
757 763 ip = get_ipython()
758 764 c = ip.Completer
759 765
760 766 s, matches = c.complete(None, "colo")
761 767 nt.assert_in("%colors", matches)
762 768 s, matches = c.complete(None, "colo")
763 769 nt.assert_not_in("NoColor", matches)
764 770 s, matches = c.complete(None, "%colors") # No trailing space
765 771 nt.assert_not_in("NoColor", matches)
766 772 s, matches = c.complete(None, "colors ")
767 773 nt.assert_in("NoColor", matches)
768 774 s, matches = c.complete(None, "%colors ")
769 775 nt.assert_in("NoColor", matches)
770 776 s, matches = c.complete(None, "colors NoCo")
771 777 nt.assert_list_equal(["NoColor"], matches)
772 778 s, matches = c.complete(None, "%colors NoCo")
773 779 nt.assert_list_equal(["NoColor"], matches)
774 780
775 781 def test_match_dict_keys(self):
776 782 """
777 783 Test that match_dict_keys works on a couple of use case does return what
778 784 expected, and does not crash
779 785 """
780 786 delims = " \t\n`!@#$^&*()=+[{]}\\|;:'\",<>?"
781 787
782 788 keys = ["foo", b"far"]
783 789 assert match_dict_keys(keys, "b'", delims=delims) == ("'", 2, ["far"])
784 790 assert match_dict_keys(keys, "b'f", delims=delims) == ("'", 2, ["far"])
785 791 assert match_dict_keys(keys, 'b"', delims=delims) == ('"', 2, ["far"])
786 792 assert match_dict_keys(keys, 'b"f', delims=delims) == ('"', 2, ["far"])
787 793
788 794 assert match_dict_keys(keys, "'", delims=delims) == ("'", 1, ["foo"])
789 795 assert match_dict_keys(keys, "'f", delims=delims) == ("'", 1, ["foo"])
790 796 assert match_dict_keys(keys, '"', delims=delims) == ('"', 1, ["foo"])
791 797 assert match_dict_keys(keys, '"f', delims=delims) == ('"', 1, ["foo"])
792 798
793 799 match_dict_keys
794 800
795 801 def test_dict_key_completion_string(self):
796 802 """Test dictionary key completion for string keys"""
797 803 ip = get_ipython()
798 804 complete = ip.Completer.complete
799 805
800 806 ip.user_ns["d"] = {"abc": None}
801 807
802 808 # check completion at different stages
803 809 _, matches = complete(line_buffer="d[")
804 810 nt.assert_in("'abc'", matches)
805 811 nt.assert_not_in("'abc']", matches)
806 812
807 813 _, matches = complete(line_buffer="d['")
808 814 nt.assert_in("abc", matches)
809 815 nt.assert_not_in("abc']", matches)
810 816
811 817 _, matches = complete(line_buffer="d['a")
812 818 nt.assert_in("abc", matches)
813 819 nt.assert_not_in("abc']", matches)
814 820
815 821 # check use of different quoting
816 822 _, matches = complete(line_buffer='d["')
817 823 nt.assert_in("abc", matches)
818 824 nt.assert_not_in('abc"]', matches)
819 825
820 826 _, matches = complete(line_buffer='d["a')
821 827 nt.assert_in("abc", matches)
822 828 nt.assert_not_in('abc"]', matches)
823 829
824 830 # check sensitivity to following context
825 831 _, matches = complete(line_buffer="d[]", cursor_pos=2)
826 832 nt.assert_in("'abc'", matches)
827 833
828 834 _, matches = complete(line_buffer="d['']", cursor_pos=3)
829 835 nt.assert_in("abc", matches)
830 836 nt.assert_not_in("abc'", matches)
831 837 nt.assert_not_in("abc']", matches)
832 838
833 839 # check multiple solutions are correctly returned and that noise is not
834 840 ip.user_ns["d"] = {
835 841 "abc": None,
836 842 "abd": None,
837 843 "bad": None,
838 844 object(): None,
839 845 5: None,
840 846 }
841 847
842 848 _, matches = complete(line_buffer="d['a")
843 849 nt.assert_in("abc", matches)
844 850 nt.assert_in("abd", matches)
845 851 nt.assert_not_in("bad", matches)
846 852 assert not any(m.endswith(("]", '"', "'")) for m in matches), matches
847 853
848 854 # check escaping and whitespace
849 855 ip.user_ns["d"] = {"a\nb": None, "a'b": None, 'a"b': None, "a word": None}
850 856 _, matches = complete(line_buffer="d['a")
851 857 nt.assert_in("a\\nb", matches)
852 858 nt.assert_in("a\\'b", matches)
853 859 nt.assert_in('a"b', matches)
854 860 nt.assert_in("a word", matches)
855 861 assert not any(m.endswith(("]", '"', "'")) for m in matches), matches
856 862
857 863 # - can complete on non-initial word of the string
858 864 _, matches = complete(line_buffer="d['a w")
859 865 nt.assert_in("word", matches)
860 866
861 867 # - understands quote escaping
862 868 _, matches = complete(line_buffer="d['a\\'")
863 869 nt.assert_in("b", matches)
864 870
865 871 # - default quoting should work like repr
866 872 _, matches = complete(line_buffer="d[")
867 873 nt.assert_in('"a\'b"', matches)
868 874
869 875 # - when opening quote with ", possible to match with unescaped apostrophe
870 876 _, matches = complete(line_buffer="d[\"a'")
871 877 nt.assert_in("b", matches)
872 878
873 879 # need to not split at delims that readline won't split at
874 880 if "-" not in ip.Completer.splitter.delims:
875 881 ip.user_ns["d"] = {"before-after": None}
876 882 _, matches = complete(line_buffer="d['before-af")
877 883 nt.assert_in("before-after", matches)
878 884
879 885 def test_dict_key_completion_contexts(self):
880 886 """Test expression contexts in which dict key completion occurs"""
881 887 ip = get_ipython()
882 888 complete = ip.Completer.complete
883 889 d = {"abc": None}
884 890 ip.user_ns["d"] = d
885 891
886 892 class C:
887 893 data = d
888 894
889 895 ip.user_ns["C"] = C
890 896 ip.user_ns["get"] = lambda: d
891 897
892 898 def assert_no_completion(**kwargs):
893 899 _, matches = complete(**kwargs)
894 900 nt.assert_not_in("abc", matches)
895 901 nt.assert_not_in("abc'", matches)
896 902 nt.assert_not_in("abc']", matches)
897 903 nt.assert_not_in("'abc'", matches)
898 904 nt.assert_not_in("'abc']", matches)
899 905
900 906 def assert_completion(**kwargs):
901 907 _, matches = complete(**kwargs)
902 908 nt.assert_in("'abc'", matches)
903 909 nt.assert_not_in("'abc']", matches)
904 910
905 911 # no completion after string closed, even if reopened
906 912 assert_no_completion(line_buffer="d['a'")
907 913 assert_no_completion(line_buffer='d["a"')
908 914 assert_no_completion(line_buffer="d['a' + ")
909 915 assert_no_completion(line_buffer="d['a' + '")
910 916
911 917 # completion in non-trivial expressions
912 918 assert_completion(line_buffer="+ d[")
913 919 assert_completion(line_buffer="(d[")
914 920 assert_completion(line_buffer="C.data[")
915 921
916 922 # greedy flag
917 923 def assert_completion(**kwargs):
918 924 _, matches = complete(**kwargs)
919 925 nt.assert_in("get()['abc']", matches)
920 926
921 927 assert_no_completion(line_buffer="get()[")
922 928 with greedy_completion():
923 929 assert_completion(line_buffer="get()[")
924 930 assert_completion(line_buffer="get()['")
925 931 assert_completion(line_buffer="get()['a")
926 932 assert_completion(line_buffer="get()['ab")
927 933 assert_completion(line_buffer="get()['abc")
928 934
929 935 def test_dict_key_completion_bytes(self):
930 936 """Test handling of bytes in dict key completion"""
931 937 ip = get_ipython()
932 938 complete = ip.Completer.complete
933 939
934 940 ip.user_ns["d"] = {"abc": None, b"abd": None}
935 941
936 942 _, matches = complete(line_buffer="d[")
937 943 nt.assert_in("'abc'", matches)
938 944 nt.assert_in("b'abd'", matches)
939 945
940 946 if False: # not currently implemented
941 947 _, matches = complete(line_buffer="d[b")
942 948 nt.assert_in("b'abd'", matches)
943 949 nt.assert_not_in("b'abc'", matches)
944 950
945 951 _, matches = complete(line_buffer="d[b'")
946 952 nt.assert_in("abd", matches)
947 953 nt.assert_not_in("abc", matches)
948 954
949 955 _, matches = complete(line_buffer="d[B'")
950 956 nt.assert_in("abd", matches)
951 957 nt.assert_not_in("abc", matches)
952 958
953 959 _, matches = complete(line_buffer="d['")
954 960 nt.assert_in("abc", matches)
955 961 nt.assert_not_in("abd", matches)
956 962
957 963 def test_dict_key_completion_unicode_py3(self):
958 964 """Test handling of unicode in dict key completion"""
959 965 ip = get_ipython()
960 966 complete = ip.Completer.complete
961 967
962 968 ip.user_ns["d"] = {"a\u05d0": None}
963 969
964 970 # query using escape
965 971 if sys.platform != "win32":
966 972 # Known failure on Windows
967 973 _, matches = complete(line_buffer="d['a\\u05d0")
968 974 nt.assert_in("u05d0", matches) # tokenized after \\
969 975
970 976 # query using character
971 977 _, matches = complete(line_buffer="d['a\u05d0")
972 978 nt.assert_in("a\u05d0", matches)
973 979
974 980 with greedy_completion():
975 981 # query using escape
976 982 _, matches = complete(line_buffer="d['a\\u05d0")
977 983 nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\
978 984
979 985 # query using character
980 986 _, matches = complete(line_buffer="d['a\u05d0")
981 987 nt.assert_in("d['a\u05d0']", matches)
982 988
983 989 @dec.skip_without("numpy")
984 990 def test_struct_array_key_completion(self):
985 991 """Test dict key completion applies to numpy struct arrays"""
986 992 import numpy
987 993
988 994 ip = get_ipython()
989 995 complete = ip.Completer.complete
990 996 ip.user_ns["d"] = numpy.array([], dtype=[("hello", "f"), ("world", "f")])
991 997 _, matches = complete(line_buffer="d['")
992 998 nt.assert_in("hello", matches)
993 999 nt.assert_in("world", matches)
994 1000 # complete on the numpy struct itself
995 1001 dt = numpy.dtype(
996 1002 [("my_head", [("my_dt", ">u4"), ("my_df", ">u4")]), ("my_data", ">f4", 5)]
997 1003 )
998 1004 x = numpy.zeros(2, dtype=dt)
999 1005 ip.user_ns["d"] = x[1]
1000 1006 _, matches = complete(line_buffer="d['")
1001 1007 nt.assert_in("my_head", matches)
1002 1008 nt.assert_in("my_data", matches)
1003 1009 # complete on a nested level
1004 1010 with greedy_completion():
1005 1011 ip.user_ns["d"] = numpy.zeros(2, dtype=dt)
1006 1012 _, matches = complete(line_buffer="d[1]['my_head']['")
1007 1013 nt.assert_true(any(["my_dt" in m for m in matches]))
1008 1014 nt.assert_true(any(["my_df" in m for m in matches]))
1009 1015
1010 1016 @dec.skip_without("pandas")
1011 1017 def test_dataframe_key_completion(self):
1012 1018 """Test dict key completion applies to pandas DataFrames"""
1013 1019 import pandas
1014 1020
1015 1021 ip = get_ipython()
1016 1022 complete = ip.Completer.complete
1017 1023 ip.user_ns["d"] = pandas.DataFrame({"hello": [1], "world": [2]})
1018 1024 _, matches = complete(line_buffer="d['")
1019 1025 nt.assert_in("hello", matches)
1020 1026 nt.assert_in("world", matches)
1021 1027
1022 1028 def test_dict_key_completion_invalids(self):
1023 1029 """Smoke test cases dict key completion can't handle"""
1024 1030 ip = get_ipython()
1025 1031 complete = ip.Completer.complete
1026 1032
1027 1033 ip.user_ns["no_getitem"] = None
1028 1034 ip.user_ns["no_keys"] = []
1029 1035 ip.user_ns["cant_call_keys"] = dict
1030 1036 ip.user_ns["empty"] = {}
1031 1037 ip.user_ns["d"] = {"abc": 5}
1032 1038
1033 1039 _, matches = complete(line_buffer="no_getitem['")
1034 1040 _, matches = complete(line_buffer="no_keys['")
1035 1041 _, matches = complete(line_buffer="cant_call_keys['")
1036 1042 _, matches = complete(line_buffer="empty['")
1037 1043 _, matches = complete(line_buffer="name_error['")
1038 1044 _, matches = complete(line_buffer="d['\\") # incomplete escape
1039 1045
1040 1046 def test_object_key_completion(self):
1041 1047 ip = get_ipython()
1042 1048 ip.user_ns["key_completable"] = KeyCompletable(["qwerty", "qwick"])
1043 1049
1044 1050 _, matches = ip.Completer.complete(line_buffer="key_completable['qw")
1045 1051 nt.assert_in("qwerty", matches)
1046 1052 nt.assert_in("qwick", matches)
1047 1053
1048 1054 def test_class_key_completion(self):
1049 1055 ip = get_ipython()
1050 1056 NamedInstanceClass("qwerty")
1051 1057 NamedInstanceClass("qwick")
1052 1058 ip.user_ns["named_instance_class"] = NamedInstanceClass
1053 1059
1054 1060 _, matches = ip.Completer.complete(line_buffer="named_instance_class['qw")
1055 1061 nt.assert_in("qwerty", matches)
1056 1062 nt.assert_in("qwick", matches)
1057 1063
1058 1064 def test_tryimport(self):
1059 1065 """
1060 1066 Test that try-import don't crash on trailing dot, and import modules before
1061 1067 """
1062 1068 from IPython.core.completerlib import try_import
1063 1069
1064 1070 assert try_import("IPython.")
1065 1071
1066 1072 def test_aimport_module_completer(self):
1067 1073 ip = get_ipython()
1068 1074 _, matches = ip.complete("i", "%aimport i")
1069 1075 nt.assert_in("io", matches)
1070 1076 nt.assert_not_in("int", matches)
1071 1077
1072 1078 def test_nested_import_module_completer(self):
1073 1079 ip = get_ipython()
1074 1080 _, matches = ip.complete(None, "import IPython.co", 17)
1075 1081 nt.assert_in("IPython.core", matches)
1076 1082 nt.assert_not_in("import IPython.core", matches)
1077 1083 nt.assert_not_in("IPython.display", matches)
1078 1084
1079 1085 def test_import_module_completer(self):
1080 1086 ip = get_ipython()
1081 1087 _, matches = ip.complete("i", "import i")
1082 1088 nt.assert_in("io", matches)
1083 1089 nt.assert_not_in("int", matches)
1084 1090
1085 1091 def test_from_module_completer(self):
1086 1092 ip = get_ipython()
1087 1093 _, matches = ip.complete("B", "from io import B", 16)
1088 1094 nt.assert_in("BytesIO", matches)
1089 1095 nt.assert_not_in("BaseException", matches)
1090 1096
1091 1097 def test_snake_case_completion(self):
1092 1098 ip = get_ipython()
1093 1099 ip.Completer.use_jedi = False
1094 1100 ip.user_ns["some_three"] = 3
1095 1101 ip.user_ns["some_four"] = 4
1096 1102 _, matches = ip.complete("s_", "print(s_f")
1097 1103 nt.assert_in("some_three", matches)
1098 1104 nt.assert_in("some_four", matches)
1099 1105
1100 1106 def test_mix_terms(self):
1101 1107 ip = get_ipython()
1102 1108 from textwrap import dedent
1103 1109
1104 1110 ip.Completer.use_jedi = False
1105 1111 ip.ex(
1106 1112 dedent(
1107 1113 """
1108 1114 class Test:
1109 1115 def meth(self, meth_arg1):
1110 1116 print("meth")
1111 1117
1112 1118 def meth_1(self, meth1_arg1, meth1_arg2):
1113 1119 print("meth1")
1114 1120
1115 1121 def meth_2(self, meth2_arg1, meth2_arg2):
1116 1122 print("meth2")
1117 1123 test = Test()
1118 1124 """
1119 1125 )
1120 1126 )
1121 1127 _, matches = ip.complete(None, "test.meth(")
1122 1128 nt.assert_in("meth_arg1=", matches)
1123 1129 nt.assert_not_in("meth2_arg1=", matches)
General Comments 0
You need to be logged in to leave comments. Login now