##// END OF EJS Templates
remove another py2 only test
Paul Ivanov -
Show More
@@ -1,799 +1,739 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 unittest
10 10
11 11 from contextlib import contextmanager
12 12
13 13 import nose.tools as nt
14 14
15 15 from traitlets.config.loader import Config
16 16 from IPython import get_ipython
17 17 from IPython.core import completer
18 18 from IPython.external.decorators import knownfailureif
19 19 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
20 20 from IPython.utils.generics import complete_object
21 21 from IPython.utils.py3compat import string_types, unicode_type
22 22 from IPython.testing import decorators as dec
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Test functions
26 26 #-----------------------------------------------------------------------------
27 27
28 28 @contextmanager
29 29 def greedy_completion():
30 30 ip = get_ipython()
31 31 greedy_original = ip.Completer.greedy
32 32 try:
33 33 ip.Completer.greedy = True
34 34 yield
35 35 finally:
36 36 ip.Completer.greedy = greedy_original
37 37
38 38 def test_protect_filename():
39 39 if sys.platform == 'win32':
40 40 pairs = [('abc','abc'),
41 41 (' abc','" abc"'),
42 42 ('a bc','"a bc"'),
43 43 ('a bc','"a bc"'),
44 44 (' bc','" bc"'),
45 45 ]
46 46 else:
47 47 pairs = [('abc','abc'),
48 48 (' abc',r'\ abc'),
49 49 ('a bc',r'a\ bc'),
50 50 ('a bc',r'a\ \ bc'),
51 51 (' bc',r'\ \ bc'),
52 52 # On posix, we also protect parens and other special characters.
53 53 ('a(bc',r'a\(bc'),
54 54 ('a)bc',r'a\)bc'),
55 55 ('a( )bc',r'a\(\ \)bc'),
56 56 ('a[1]bc', r'a\[1\]bc'),
57 57 ('a{1}bc', r'a\{1\}bc'),
58 58 ('a#bc', r'a\#bc'),
59 59 ('a?bc', r'a\?bc'),
60 60 ('a=bc', r'a\=bc'),
61 61 ('a\\bc', r'a\\bc'),
62 62 ('a|bc', r'a\|bc'),
63 63 ('a;bc', r'a\;bc'),
64 64 ('a:bc', r'a\:bc'),
65 65 ("a'bc", r"a\'bc"),
66 66 ('a*bc', r'a\*bc'),
67 67 ('a"bc', r'a\"bc'),
68 68 ('a^bc', r'a\^bc'),
69 69 ('a&bc', r'a\&bc'),
70 70 ]
71 71 # run the actual tests
72 72 for s1, s2 in pairs:
73 73 s1p = completer.protect_filename(s1)
74 74 nt.assert_equal(s1p, s2)
75 75
76 76
77 77 def check_line_split(splitter, test_specs):
78 78 for part1, part2, split in test_specs:
79 79 cursor_pos = len(part1)
80 80 line = part1+part2
81 81 out = splitter.split_line(line, cursor_pos)
82 82 nt.assert_equal(out, split)
83 83
84 84
85 85 def test_line_split():
86 86 """Basic line splitter test with default specs."""
87 87 sp = completer.CompletionSplitter()
88 88 # The format of the test specs is: part1, part2, expected answer. Parts 1
89 89 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
90 90 # was at the end of part1. So an empty part2 represents someone hitting
91 91 # tab at the end of the line, the most common case.
92 92 t = [('run some/scrip', '', 'some/scrip'),
93 93 ('run scripts/er', 'ror.py foo', 'scripts/er'),
94 94 ('echo $HOM', '', 'HOM'),
95 95 ('print sys.pa', '', 'sys.pa'),
96 96 ('print(sys.pa', '', 'sys.pa'),
97 97 ("execfile('scripts/er", '', 'scripts/er'),
98 98 ('a[x.', '', 'x.'),
99 99 ('a[x.', 'y', 'x.'),
100 100 ('cd "some_file/', '', 'some_file/'),
101 101 ]
102 102 check_line_split(sp, t)
103 103 # Ensure splitting works OK with unicode by re-running the tests with
104 104 # all inputs turned into unicode
105 105 check_line_split(sp, [ map(unicode_type, p) for p in t] )
106 106
107 107
108 108 def test_custom_completion_error():
109 109 """Test that errors from custom attribute completers are silenced."""
110 110 ip = get_ipython()
111 111 class A(object): pass
112 112 ip.user_ns['a'] = A()
113 113
114 114 @complete_object.when_type(A)
115 115 def complete_A(a, existing_completions):
116 116 raise TypeError("this should be silenced")
117 117
118 118 ip.complete("a.")
119 119
120 120
121 121 def test_unicode_completions():
122 122 ip = get_ipython()
123 123 # Some strings that trigger different types of completion. Check them both
124 124 # in str and unicode forms
125 125 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
126 126 for t in s + list(map(unicode_type, s)):
127 127 # We don't need to check exact completion values (they may change
128 128 # depending on the state of the namespace, but at least no exceptions
129 129 # should be thrown and the return value should be a pair of text, list
130 130 # values.
131 131 text, matches = ip.complete(t)
132 132 nt.assert_true(isinstance(text, string_types))
133 133 nt.assert_true(isinstance(matches, list))
134 134
135 135 def test_latex_completions():
136 136 from IPython.core.latex_symbols import latex_symbols
137 137 import random
138 138 ip = get_ipython()
139 139 # Test some random unicode symbols
140 140 keys = random.sample(latex_symbols.keys(), 10)
141 141 for k in keys:
142 142 text, matches = ip.complete(k)
143 143 nt.assert_equal(len(matches),1)
144 144 nt.assert_equal(text, k)
145 145 nt.assert_equal(matches[0], latex_symbols[k])
146 146 # Test a more complex line
147 147 text, matches = ip.complete(u'print(\\alpha')
148 148 nt.assert_equals(text, u'\\alpha')
149 149 nt.assert_equals(matches[0], latex_symbols['\\alpha'])
150 150 # Test multiple matching latex symbols
151 151 text, matches = ip.complete(u'\\al')
152 152 nt.assert_in('\\alpha', matches)
153 153 nt.assert_in('\\aleph', matches)
154 154
155 155
156 156
157 157
158 158 def test_back_latex_completion():
159 159 ip = get_ipython()
160 160
161 161 # do not return more than 1 matches fro \beta, only the latex one.
162 162 name, matches = ip.complete('\\Ξ²')
163 163 nt.assert_equal(len(matches), 1)
164 164 nt.assert_equal(matches[0], '\\beta')
165 165
166 166 def test_back_unicode_completion():
167 167 ip = get_ipython()
168 168
169 169 name, matches = ip.complete('\\β…€')
170 170 nt.assert_equal(len(matches), 1)
171 171 nt.assert_equal(matches[0], '\\ROMAN NUMERAL FIVE')
172 172
173 173
174 174 def test_forward_unicode_completion():
175 175 ip = get_ipython()
176 176
177 177 name, matches = ip.complete('\\ROMAN NUMERAL FIVE')
178 178 nt.assert_equal(len(matches), 1)
179 179 nt.assert_equal(matches[0], 'β…€')
180 180
181 181 @dec.knownfailureif(sys.platform == 'win32', 'Fails if there is a C:\\j... path')
182 182 def test_no_ascii_back_completion():
183 183 ip = get_ipython()
184 184 with TemporaryWorkingDirectory(): # Avoid any filename completions
185 185 # single ascii letter that don't have yet completions
186 186 for letter in 'jJ' :
187 187 name, matches = ip.complete('\\'+letter)
188 188 nt.assert_equal(matches, [])
189 189
190 190
191 191
192 192
193 193 class CompletionSplitterTestCase(unittest.TestCase):
194 194 def setUp(self):
195 195 self.sp = completer.CompletionSplitter()
196 196
197 197 def test_delim_setting(self):
198 198 self.sp.delims = ' '
199 199 nt.assert_equal(self.sp.delims, ' ')
200 200 nt.assert_equal(self.sp._delim_expr, '[\ ]')
201 201
202 202 def test_spaces(self):
203 203 """Test with only spaces as split chars."""
204 204 self.sp.delims = ' '
205 205 t = [('foo', '', 'foo'),
206 206 ('run foo', '', 'foo'),
207 207 ('run foo', 'bar', 'foo'),
208 208 ]
209 209 check_line_split(self.sp, t)
210 210
211 211
212 212 def test_has_open_quotes1():
213 213 for s in ["'", "'''", "'hi' '"]:
214 214 nt.assert_equal(completer.has_open_quotes(s), "'")
215 215
216 216
217 217 def test_has_open_quotes2():
218 218 for s in ['"', '"""', '"hi" "']:
219 219 nt.assert_equal(completer.has_open_quotes(s), '"')
220 220
221 221
222 222 def test_has_open_quotes3():
223 223 for s in ["''", "''' '''", "'hi' 'ipython'"]:
224 224 nt.assert_false(completer.has_open_quotes(s))
225 225
226 226
227 227 def test_has_open_quotes4():
228 228 for s in ['""', '""" """', '"hi" "ipython"']:
229 229 nt.assert_false(completer.has_open_quotes(s))
230 230
231 231
232 232 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
233 233 def test_abspath_file_completions():
234 234 ip = get_ipython()
235 235 with TemporaryDirectory() as tmpdir:
236 236 prefix = os.path.join(tmpdir, 'foo')
237 237 suffixes = ['1', '2']
238 238 names = [prefix+s for s in suffixes]
239 239 for n in names:
240 240 open(n, 'w').close()
241 241
242 242 # Check simple completion
243 243 c = ip.complete(prefix)[1]
244 244 nt.assert_equal(c, names)
245 245
246 246 # Now check with a function call
247 247 cmd = 'a = f("%s' % prefix
248 248 c = ip.complete(prefix, cmd)[1]
249 249 comp = [prefix+s for s in suffixes]
250 250 nt.assert_equal(c, comp)
251 251
252 252
253 253 def test_local_file_completions():
254 254 ip = get_ipython()
255 255 with TemporaryWorkingDirectory():
256 256 prefix = './foo'
257 257 suffixes = ['1', '2']
258 258 names = [prefix+s for s in suffixes]
259 259 for n in names:
260 260 open(n, 'w').close()
261 261
262 262 # Check simple completion
263 263 c = ip.complete(prefix)[1]
264 264 nt.assert_equal(c, names)
265 265
266 266 # Now check with a function call
267 267 cmd = 'a = f("%s' % prefix
268 268 c = ip.complete(prefix, cmd)[1]
269 269 comp = set(prefix+s for s in suffixes)
270 270 nt.assert_true(comp.issubset(set(c)))
271 271
272 272
273 273 def test_greedy_completions():
274 274 ip = get_ipython()
275 275 ip.ex('a=list(range(5))')
276 276 _,c = ip.complete('.',line='a[0].')
277 277 nt.assert_false('.real' in c,
278 278 "Shouldn't have completed on a[0]: %s"%c)
279 279 with greedy_completion():
280 280 def _(line, cursor_pos, expect, message):
281 281 _,c = ip.complete('.', line=line, cursor_pos=cursor_pos)
282 282 nt.assert_in(expect, c, message%c)
283 283
284 284 yield _, 'a[0].', 5, 'a[0].real', "Should have completed on a[0].: %s"
285 285 yield _, 'a[0].r', 6, 'a[0].real', "Should have completed on a[0].r: %s"
286 286
287 287 if sys.version_info > (3,4):
288 288 yield _, 'a[0].from_', 10, 'a[0].from_bytes', "Should have completed on a[0].from_: %s"
289 289
290 290
291 291
292 292 def test_omit__names():
293 293 # also happens to test IPCompleter as a configurable
294 294 ip = get_ipython()
295 295 ip._hidden_attr = 1
296 296 ip._x = {}
297 297 c = ip.Completer
298 298 ip.ex('ip=get_ipython()')
299 299 cfg = Config()
300 300 cfg.IPCompleter.omit__names = 0
301 301 c.update_config(cfg)
302 302 s,matches = c.complete('ip.')
303 303 nt.assert_in('ip.__str__', matches)
304 304 nt.assert_in('ip._hidden_attr', matches)
305 305 cfg = Config()
306 306 cfg.IPCompleter.omit__names = 1
307 307 c.update_config(cfg)
308 308 s,matches = c.complete('ip.')
309 309 nt.assert_not_in('ip.__str__', matches)
310 310 nt.assert_in('ip._hidden_attr', matches)
311 311 cfg = Config()
312 312 cfg.IPCompleter.omit__names = 2
313 313 c.update_config(cfg)
314 314 s,matches = c.complete('ip.')
315 315 nt.assert_not_in('ip.__str__', matches)
316 316 nt.assert_not_in('ip._hidden_attr', matches)
317 317 s,matches = c.complete('ip._x.')
318 318 nt.assert_in('ip._x.keys', matches)
319 319 del ip._hidden_attr
320 320
321 321
322 322 def test_limit_to__all__False_ok():
323 323 ip = get_ipython()
324 324 c = ip.Completer
325 325 ip.ex('class D: x=24')
326 326 ip.ex('d=D()')
327 327 cfg = Config()
328 328 cfg.IPCompleter.limit_to__all__ = False
329 329 c.update_config(cfg)
330 330 s, matches = c.complete('d.')
331 331 nt.assert_in('d.x', matches)
332 332
333 333
334 334 def test_get__all__entries_ok():
335 335 class A(object):
336 336 __all__ = ['x', 1]
337 337 words = completer.get__all__entries(A())
338 338 nt.assert_equal(words, ['x'])
339 339
340 340
341 341 def test_get__all__entries_no__all__ok():
342 342 class A(object):
343 343 pass
344 344 words = completer.get__all__entries(A())
345 345 nt.assert_equal(words, [])
346 346
347 347
348 348 def test_func_kw_completions():
349 349 ip = get_ipython()
350 350 c = ip.Completer
351 351 ip.ex('def myfunc(a=1,b=2): return a+b')
352 352 s, matches = c.complete(None, 'myfunc(1,b')
353 353 nt.assert_in('b=', matches)
354 354 # Simulate completing with cursor right after b (pos==10):
355 355 s, matches = c.complete(None, 'myfunc(1,b)', 10)
356 356 nt.assert_in('b=', matches)
357 357 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
358 358 nt.assert_in('b=', matches)
359 359 #builtin function
360 360 s, matches = c.complete(None, 'min(k, k')
361 361 nt.assert_in('key=', matches)
362 362
363 363
364 364 def test_default_arguments_from_docstring():
365 365 ip = get_ipython()
366 366 c = ip.Completer
367 367 kwd = c._default_arguments_from_docstring(
368 368 'min(iterable[, key=func]) -> value')
369 369 nt.assert_equal(kwd, ['key'])
370 370 #with cython type etc
371 371 kwd = c._default_arguments_from_docstring(
372 372 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
373 373 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
374 374 #white spaces
375 375 kwd = c._default_arguments_from_docstring(
376 376 '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
377 377 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
378 378
379 379 def test_line_magics():
380 380 ip = get_ipython()
381 381 c = ip.Completer
382 382 s, matches = c.complete(None, 'lsmag')
383 383 nt.assert_in('%lsmagic', matches)
384 384 s, matches = c.complete(None, '%lsmag')
385 385 nt.assert_in('%lsmagic', matches)
386 386
387 387
388 388 def test_cell_magics():
389 389 from IPython.core.magic import register_cell_magic
390 390
391 391 @register_cell_magic
392 392 def _foo_cellm(line, cell):
393 393 pass
394 394
395 395 ip = get_ipython()
396 396 c = ip.Completer
397 397
398 398 s, matches = c.complete(None, '_foo_ce')
399 399 nt.assert_in('%%_foo_cellm', matches)
400 400 s, matches = c.complete(None, '%%_foo_ce')
401 401 nt.assert_in('%%_foo_cellm', matches)
402 402
403 403
404 404 def test_line_cell_magics():
405 405 from IPython.core.magic import register_line_cell_magic
406 406
407 407 @register_line_cell_magic
408 408 def _bar_cellm(line, cell):
409 409 pass
410 410
411 411 ip = get_ipython()
412 412 c = ip.Completer
413 413
414 414 # The policy here is trickier, see comments in completion code. The
415 415 # returned values depend on whether the user passes %% or not explicitly,
416 416 # and this will show a difference if the same name is both a line and cell
417 417 # magic.
418 418 s, matches = c.complete(None, '_bar_ce')
419 419 nt.assert_in('%_bar_cellm', matches)
420 420 nt.assert_in('%%_bar_cellm', matches)
421 421 s, matches = c.complete(None, '%_bar_ce')
422 422 nt.assert_in('%_bar_cellm', matches)
423 423 nt.assert_in('%%_bar_cellm', matches)
424 424 s, matches = c.complete(None, '%%_bar_ce')
425 425 nt.assert_not_in('%_bar_cellm', matches)
426 426 nt.assert_in('%%_bar_cellm', matches)
427 427
428 428
429 429 def test_magic_completion_order():
430 430
431 431 ip = get_ipython()
432 432 c = ip.Completer
433 433
434 434 # Test ordering of magics and non-magics with the same name
435 435 # We want the non-magic first
436 436
437 437 # Before importing matplotlib, there should only be one option:
438 438
439 439 text, matches = c.complete('mat')
440 440 nt.assert_equal(matches, ["%matplotlib"])
441 441
442 442
443 443 ip.run_cell("matplotlib = 1") # introduce name into namespace
444 444
445 445 # After the import, there should be two options, ordered like this:
446 446 text, matches = c.complete('mat')
447 447 nt.assert_equal(matches, ["matplotlib", "%matplotlib"])
448 448
449 449
450 450 ip.run_cell("timeit = 1") # define a user variable called 'timeit'
451 451
452 452 # Order of user variable and line and cell magics with same name:
453 453 text, matches = c.complete('timeit')
454 454 nt.assert_equal(matches, ["timeit", "%timeit","%%timeit"])
455 455
456 456
457 457 def test_dict_key_completion_string():
458 458 """Test dictionary key completion for string keys"""
459 459 ip = get_ipython()
460 460 complete = ip.Completer.complete
461 461
462 462 ip.user_ns['d'] = {'abc': None}
463 463
464 464 # check completion at different stages
465 465 _, matches = complete(line_buffer="d[")
466 466 nt.assert_in("'abc'", matches)
467 467 nt.assert_not_in("'abc']", matches)
468 468
469 469 _, matches = complete(line_buffer="d['")
470 470 nt.assert_in("abc", matches)
471 471 nt.assert_not_in("abc']", matches)
472 472
473 473 _, matches = complete(line_buffer="d['a")
474 474 nt.assert_in("abc", matches)
475 475 nt.assert_not_in("abc']", matches)
476 476
477 477 # check use of different quoting
478 478 _, matches = complete(line_buffer="d[\"")
479 479 nt.assert_in("abc", matches)
480 480 nt.assert_not_in('abc\"]', matches)
481 481
482 482 _, matches = complete(line_buffer="d[\"a")
483 483 nt.assert_in("abc", matches)
484 484 nt.assert_not_in('abc\"]', matches)
485 485
486 486 # check sensitivity to following context
487 487 _, matches = complete(line_buffer="d[]", cursor_pos=2)
488 488 nt.assert_in("'abc'", matches)
489 489
490 490 _, matches = complete(line_buffer="d['']", cursor_pos=3)
491 491 nt.assert_in("abc", matches)
492 492 nt.assert_not_in("abc'", matches)
493 493 nt.assert_not_in("abc']", matches)
494 494
495 495 # check multiple solutions are correctly returned and that noise is not
496 496 ip.user_ns['d'] = {'abc': None, 'abd': None, 'bad': None, object(): None,
497 497 5: None}
498 498
499 499 _, matches = complete(line_buffer="d['a")
500 500 nt.assert_in("abc", matches)
501 501 nt.assert_in("abd", matches)
502 502 nt.assert_not_in("bad", matches)
503 503 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
504 504
505 505 # check escaping and whitespace
506 506 ip.user_ns['d'] = {'a\nb': None, 'a\'b': None, 'a"b': None, 'a word': None}
507 507 _, matches = complete(line_buffer="d['a")
508 508 nt.assert_in("a\\nb", matches)
509 509 nt.assert_in("a\\'b", matches)
510 510 nt.assert_in("a\"b", matches)
511 511 nt.assert_in("a word", matches)
512 512 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
513 513
514 514 # - can complete on non-initial word of the string
515 515 _, matches = complete(line_buffer="d['a w")
516 516 nt.assert_in("word", matches)
517 517
518 518 # - understands quote escaping
519 519 _, matches = complete(line_buffer="d['a\\'")
520 520 nt.assert_in("b", matches)
521 521
522 522 # - default quoting should work like repr
523 523 _, matches = complete(line_buffer="d[")
524 524 nt.assert_in("\"a'b\"", matches)
525 525
526 526 # - when opening quote with ", possible to match with unescaped apostrophe
527 527 _, matches = complete(line_buffer="d[\"a'")
528 528 nt.assert_in("b", matches)
529 529
530 530 # need to not split at delims that readline won't split at
531 531 if '-' not in ip.Completer.splitter.delims:
532 532 ip.user_ns['d'] = {'before-after': None}
533 533 _, matches = complete(line_buffer="d['before-af")
534 534 nt.assert_in('before-after', matches)
535 535
536 536 def test_dict_key_completion_contexts():
537 537 """Test expression contexts in which dict key completion occurs"""
538 538 ip = get_ipython()
539 539 complete = ip.Completer.complete
540 540 d = {'abc': None}
541 541 ip.user_ns['d'] = d
542 542
543 543 class C:
544 544 data = d
545 545 ip.user_ns['C'] = C
546 546 ip.user_ns['get'] = lambda: d
547 547
548 548 def assert_no_completion(**kwargs):
549 549 _, matches = complete(**kwargs)
550 550 nt.assert_not_in('abc', matches)
551 551 nt.assert_not_in('abc\'', matches)
552 552 nt.assert_not_in('abc\']', matches)
553 553 nt.assert_not_in('\'abc\'', matches)
554 554 nt.assert_not_in('\'abc\']', matches)
555 555
556 556 def assert_completion(**kwargs):
557 557 _, matches = complete(**kwargs)
558 558 nt.assert_in("'abc'", matches)
559 559 nt.assert_not_in("'abc']", matches)
560 560
561 561 # no completion after string closed, even if reopened
562 562 assert_no_completion(line_buffer="d['a'")
563 563 assert_no_completion(line_buffer="d[\"a\"")
564 564 assert_no_completion(line_buffer="d['a' + ")
565 565 assert_no_completion(line_buffer="d['a' + '")
566 566
567 567 # completion in non-trivial expressions
568 568 assert_completion(line_buffer="+ d[")
569 569 assert_completion(line_buffer="(d[")
570 570 assert_completion(line_buffer="C.data[")
571 571
572 572 # greedy flag
573 573 def assert_completion(**kwargs):
574 574 _, matches = complete(**kwargs)
575 575 nt.assert_in("get()['abc']", matches)
576 576
577 577 assert_no_completion(line_buffer="get()[")
578 578 with greedy_completion():
579 579 assert_completion(line_buffer="get()[")
580 580 assert_completion(line_buffer="get()['")
581 581 assert_completion(line_buffer="get()['a")
582 582 assert_completion(line_buffer="get()['ab")
583 583 assert_completion(line_buffer="get()['abc")
584 584
585 585
586 586
587 587 def test_dict_key_completion_bytes():
588 588 """Test handling of bytes in dict key completion"""
589 589 ip = get_ipython()
590 590 complete = ip.Completer.complete
591 591
592 592 ip.user_ns['d'] = {'abc': None, b'abd': None}
593 593
594 594 _, matches = complete(line_buffer="d[")
595 595 nt.assert_in("'abc'", matches)
596 596 nt.assert_in("b'abd'", matches)
597 597
598 598 if False: # not currently implemented
599 599 _, matches = complete(line_buffer="d[b")
600 600 nt.assert_in("b'abd'", matches)
601 601 nt.assert_not_in("b'abc'", matches)
602 602
603 603 _, matches = complete(line_buffer="d[b'")
604 604 nt.assert_in("abd", matches)
605 605 nt.assert_not_in("abc", matches)
606 606
607 607 _, matches = complete(line_buffer="d[B'")
608 608 nt.assert_in("abd", matches)
609 609 nt.assert_not_in("abc", matches)
610 610
611 611 _, matches = complete(line_buffer="d['")
612 612 nt.assert_in("abc", matches)
613 613 nt.assert_not_in("abd", matches)
614 614
615 615
616 def test_dict_key_completion_unicode_py2():
617 """Test handling of unicode in dict key completion"""
618 ip = get_ipython()
619 complete = ip.Completer.complete
620
621 ip.user_ns['d'] = {u'abc': None,
622 u'a\u05d0b': None}
623
624 _, matches = complete(line_buffer="d[")
625 nt.assert_in("u'abc'", matches)
626 nt.assert_in("u'a\\u05d0b'", matches)
627
628 _, matches = complete(line_buffer="d['a")
629 nt.assert_in("abc", matches)
630 nt.assert_not_in("a\\u05d0b", matches)
631
632 _, matches = complete(line_buffer="d[u'a")
633 nt.assert_in("abc", matches)
634 nt.assert_in("a\\u05d0b", matches)
635
636 _, matches = complete(line_buffer="d[U'a")
637 nt.assert_in("abc", matches)
638 nt.assert_in("a\\u05d0b", matches)
639
640 # query using escape
641 if sys.platform != 'win32':
642 # Known failure on Windows
643 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
644 nt.assert_in("u05d0b", matches) # tokenized after \\
645
646 # query using character
647 _, matches = complete(line_buffer=u"d[u'a\u05d0")
648 nt.assert_in(u"a\u05d0b", matches)
649
650 with greedy_completion():
651 _, matches = complete(line_buffer="d[")
652 nt.assert_in("d[u'abc']", matches)
653 nt.assert_in("d[u'a\\u05d0b']", matches)
654
655 _, matches = complete(line_buffer="d['a")
656 nt.assert_in("d['abc']", matches)
657 nt.assert_not_in("d[u'a\\u05d0b']", matches)
658
659 _, matches = complete(line_buffer="d[u'a")
660 nt.assert_in("d[u'abc']", matches)
661 nt.assert_in("d[u'a\\u05d0b']", matches)
662
663 _, matches = complete(line_buffer="d[U'a")
664 nt.assert_in("d[U'abc']", matches)
665 nt.assert_in("d[U'a\\u05d0b']", matches)
666
667 # query using escape
668 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
669 nt.assert_in("d[u'a\\u05d0b']", matches) # tokenized after \\
670
671 # query using character
672 _, matches = complete(line_buffer=u"d[u'a\u05d0")
673 nt.assert_in(u"d[u'a\u05d0b']", matches)
674
675
676 616 def test_dict_key_completion_unicode_py3():
677 617 """Test handling of unicode in dict key completion"""
678 618 ip = get_ipython()
679 619 complete = ip.Completer.complete
680 620
681 621 ip.user_ns['d'] = {u'a\u05d0': None}
682 622
683 623 # query using escape
684 624 if sys.platform != 'win32':
685 625 # Known failure on Windows
686 626 _, matches = complete(line_buffer="d['a\\u05d0")
687 627 nt.assert_in("u05d0", matches) # tokenized after \\
688 628
689 629 # query using character
690 630 _, matches = complete(line_buffer="d['a\u05d0")
691 631 nt.assert_in(u"a\u05d0", matches)
692 632
693 633 with greedy_completion():
694 634 # query using escape
695 635 _, matches = complete(line_buffer="d['a\\u05d0")
696 636 nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\
697 637
698 638 # query using character
699 639 _, matches = complete(line_buffer="d['a\u05d0")
700 640 nt.assert_in(u"d['a\u05d0']", matches)
701 641
702 642
703 643
704 644 @dec.skip_without('numpy')
705 645 def test_struct_array_key_completion():
706 646 """Test dict key completion applies to numpy struct arrays"""
707 647 import numpy
708 648 ip = get_ipython()
709 649 complete = ip.Completer.complete
710 650 ip.user_ns['d'] = numpy.array([], dtype=[('hello', 'f'), ('world', 'f')])
711 651 _, matches = complete(line_buffer="d['")
712 652 nt.assert_in("hello", matches)
713 653 nt.assert_in("world", matches)
714 654 # complete on the numpy struct itself
715 655 dt = numpy.dtype([('my_head', [('my_dt', '>u4'), ('my_df', '>u4')]),
716 656 ('my_data', '>f4', 5)])
717 657 x = numpy.zeros(2, dtype=dt)
718 658 ip.user_ns['d'] = x[1]
719 659 _, matches = complete(line_buffer="d['")
720 660 nt.assert_in("my_head", matches)
721 661 nt.assert_in("my_data", matches)
722 662 # complete on a nested level
723 663 with greedy_completion():
724 664 ip.user_ns['d'] = numpy.zeros(2, dtype=dt)
725 665 _, matches = complete(line_buffer="d[1]['my_head']['")
726 666 nt.assert_true(any(["my_dt" in m for m in matches]))
727 667 nt.assert_true(any(["my_df" in m for m in matches]))
728 668
729 669
730 670 @dec.skip_without('pandas')
731 671 def test_dataframe_key_completion():
732 672 """Test dict key completion applies to pandas DataFrames"""
733 673 import pandas
734 674 ip = get_ipython()
735 675 complete = ip.Completer.complete
736 676 ip.user_ns['d'] = pandas.DataFrame({'hello': [1], 'world': [2]})
737 677 _, matches = complete(line_buffer="d['")
738 678 nt.assert_in("hello", matches)
739 679 nt.assert_in("world", matches)
740 680
741 681
742 682 def test_dict_key_completion_invalids():
743 683 """Smoke test cases dict key completion can't handle"""
744 684 ip = get_ipython()
745 685 complete = ip.Completer.complete
746 686
747 687 ip.user_ns['no_getitem'] = None
748 688 ip.user_ns['no_keys'] = []
749 689 ip.user_ns['cant_call_keys'] = dict
750 690 ip.user_ns['empty'] = {}
751 691 ip.user_ns['d'] = {'abc': 5}
752 692
753 693 _, matches = complete(line_buffer="no_getitem['")
754 694 _, matches = complete(line_buffer="no_keys['")
755 695 _, matches = complete(line_buffer="cant_call_keys['")
756 696 _, matches = complete(line_buffer="empty['")
757 697 _, matches = complete(line_buffer="name_error['")
758 698 _, matches = complete(line_buffer="d['\\") # incomplete escape
759 699
760 700 class KeyCompletable(object):
761 701 def __init__(self, things=()):
762 702 self.things = things
763 703
764 704 def _ipython_key_completions_(self):
765 705 return list(self.things)
766 706
767 707 def test_object_key_completion():
768 708 ip = get_ipython()
769 709 ip.user_ns['key_completable'] = KeyCompletable(['qwerty', 'qwick'])
770 710
771 711 _, matches = ip.Completer.complete(line_buffer="key_completable['qw")
772 712 nt.assert_in('qwerty', matches)
773 713 nt.assert_in('qwick', matches)
774 714
775 715
776 716 def test_aimport_module_completer():
777 717 ip = get_ipython()
778 718 _, matches = ip.complete('i', '%aimport i')
779 719 nt.assert_in('io', matches)
780 720 nt.assert_not_in('int', matches)
781 721
782 722 def test_nested_import_module_completer():
783 723 ip = get_ipython()
784 724 _, matches = ip.complete(None, 'import IPython.co', 17)
785 725 nt.assert_in('IPython.core', matches)
786 726 nt.assert_not_in('import IPython.core', matches)
787 727 nt.assert_not_in('IPython.display', matches)
788 728
789 729 def test_import_module_completer():
790 730 ip = get_ipython()
791 731 _, matches = ip.complete('i', 'import i')
792 732 nt.assert_in('io', matches)
793 733 nt.assert_not_in('int', matches)
794 734
795 735 def test_from_module_completer():
796 736 ip = get_ipython()
797 737 _, matches = ip.complete('B', 'from io import B', 16)
798 738 nt.assert_in('BytesIO', matches)
799 739 nt.assert_not_in('BaseException', matches)
General Comments 0
You need to be logged in to leave comments. Login now