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