##// END OF EJS Templates
Adding tests and limiting CM mode to python 3.
Brian E. Granger -
Show More
@@ -1,677 +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 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
130 def test_latex_completions():
131 from IPython.core.latex_symbols import latex_symbols
132 import random
133 ip = get_ipython()
134 # Test some random unicode symbols
135 keys = random.sample(latex_symbols.keys(), 10)
136 for k in keys:
137 text, matches = ip.complete(k)
138 nt.assert_equal(len(matches),1)
139 nt.assert_equal(text, k)
140 mt.assert_equal(matches[0], latex_symbols[k])
141 # Test a more complex line
142 text, matches = ip.complete(u'print(\\alpha')
143 nt.assert_equals(text, u'\\alpha')
144 nt.assert_equals(matches[0], latex_symbols['\\alpha'])
145 # Test multiple matching latex symbols
146 text, matches = ip.complete(u'\\al')
147 nt.assert_in('\\alpha', matches)
148 nt.assert_in('\\aleph', matches)
149
129 150
130 151 class CompletionSplitterTestCase(unittest.TestCase):
131 152 def setUp(self):
132 153 self.sp = completer.CompletionSplitter()
133 154
134 155 def test_delim_setting(self):
135 156 self.sp.delims = ' '
136 157 nt.assert_equal(self.sp.delims, ' ')
137 158 nt.assert_equal(self.sp._delim_expr, '[\ ]')
138 159
139 160 def test_spaces(self):
140 161 """Test with only spaces as split chars."""
141 162 self.sp.delims = ' '
142 163 t = [('foo', '', 'foo'),
143 164 ('run foo', '', 'foo'),
144 165 ('run foo', 'bar', 'foo'),
145 166 ]
146 167 check_line_split(self.sp, t)
147 168
148 169
149 170 def test_has_open_quotes1():
150 171 for s in ["'", "'''", "'hi' '"]:
151 172 nt.assert_equal(completer.has_open_quotes(s), "'")
152 173
153 174
154 175 def test_has_open_quotes2():
155 176 for s in ['"', '"""', '"hi" "']:
156 177 nt.assert_equal(completer.has_open_quotes(s), '"')
157 178
158 179
159 180 def test_has_open_quotes3():
160 181 for s in ["''", "''' '''", "'hi' 'ipython'"]:
161 182 nt.assert_false(completer.has_open_quotes(s))
162 183
163 184
164 185 def test_has_open_quotes4():
165 186 for s in ['""', '""" """', '"hi" "ipython"']:
166 187 nt.assert_false(completer.has_open_quotes(s))
167 188
168 189
169 190 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
170 191 def test_abspath_file_completions():
171 192 ip = get_ipython()
172 193 with TemporaryDirectory() as tmpdir:
173 194 prefix = os.path.join(tmpdir, 'foo')
174 195 suffixes = ['1', '2']
175 196 names = [prefix+s for s in suffixes]
176 197 for n in names:
177 198 open(n, 'w').close()
178 199
179 200 # Check simple completion
180 201 c = ip.complete(prefix)[1]
181 202 nt.assert_equal(c, names)
182 203
183 204 # Now check with a function call
184 205 cmd = 'a = f("%s' % prefix
185 206 c = ip.complete(prefix, cmd)[1]
186 207 comp = [prefix+s for s in suffixes]
187 208 nt.assert_equal(c, comp)
188 209
189 210
190 211 def test_local_file_completions():
191 212 ip = get_ipython()
192 213 with TemporaryWorkingDirectory():
193 214 prefix = './foo'
194 215 suffixes = ['1', '2']
195 216 names = [prefix+s for s in suffixes]
196 217 for n in names:
197 218 open(n, 'w').close()
198 219
199 220 # Check simple completion
200 221 c = ip.complete(prefix)[1]
201 222 nt.assert_equal(c, names)
202 223
203 224 # Now check with a function call
204 225 cmd = 'a = f("%s' % prefix
205 226 c = ip.complete(prefix, cmd)[1]
206 227 comp = [prefix+s for s in suffixes]
207 228 nt.assert_equal(c, comp)
208 229
209 230
210 231 def test_greedy_completions():
211 232 ip = get_ipython()
212 233 ip.ex('a=list(range(5))')
213 234 _,c = ip.complete('.',line='a[0].')
214 235 nt.assert_false('a[0].real' in c,
215 236 "Shouldn't have completed on a[0]: %s"%c)
216 237 with greedy_completion():
217 238 _,c = ip.complete('.',line='a[0].')
218 239 nt.assert_true('a[0].real' in c, "Should have completed on a[0]: %s"%c)
219 240
220 241
221 242 def test_omit__names():
222 243 # also happens to test IPCompleter as a configurable
223 244 ip = get_ipython()
224 245 ip._hidden_attr = 1
225 246 c = ip.Completer
226 247 ip.ex('ip=get_ipython()')
227 248 cfg = Config()
228 249 cfg.IPCompleter.omit__names = 0
229 250 c.update_config(cfg)
230 251 s,matches = c.complete('ip.')
231 252 nt.assert_in('ip.__str__', matches)
232 253 nt.assert_in('ip._hidden_attr', matches)
233 254 cfg.IPCompleter.omit__names = 1
234 255 c.update_config(cfg)
235 256 s,matches = c.complete('ip.')
236 257 nt.assert_not_in('ip.__str__', matches)
237 258 nt.assert_in('ip._hidden_attr', matches)
238 259 cfg.IPCompleter.omit__names = 2
239 260 c.update_config(cfg)
240 261 s,matches = c.complete('ip.')
241 262 nt.assert_not_in('ip.__str__', matches)
242 263 nt.assert_not_in('ip._hidden_attr', matches)
243 264 del ip._hidden_attr
244 265
245 266
246 267 def test_limit_to__all__False_ok():
247 268 ip = get_ipython()
248 269 c = ip.Completer
249 270 ip.ex('class D: x=24')
250 271 ip.ex('d=D()')
251 272 cfg = Config()
252 273 cfg.IPCompleter.limit_to__all__ = False
253 274 c.update_config(cfg)
254 275 s, matches = c.complete('d.')
255 276 nt.assert_in('d.x', matches)
256 277
257 278
258 279 def test_limit_to__all__True_ok():
259 280 ip = get_ipython()
260 281 c = ip.Completer
261 282 ip.ex('class D: x=24')
262 283 ip.ex('d=D()')
263 284 ip.ex("d.__all__=['z']")
264 285 cfg = Config()
265 286 cfg.IPCompleter.limit_to__all__ = True
266 287 c.update_config(cfg)
267 288 s, matches = c.complete('d.')
268 289 nt.assert_in('d.z', matches)
269 290 nt.assert_not_in('d.x', matches)
270 291
271 292
272 293 def test_get__all__entries_ok():
273 294 class A(object):
274 295 __all__ = ['x', 1]
275 296 words = completer.get__all__entries(A())
276 297 nt.assert_equal(words, ['x'])
277 298
278 299
279 300 def test_get__all__entries_no__all__ok():
280 301 class A(object):
281 302 pass
282 303 words = completer.get__all__entries(A())
283 304 nt.assert_equal(words, [])
284 305
285 306
286 307 def test_func_kw_completions():
287 308 ip = get_ipython()
288 309 c = ip.Completer
289 310 ip.ex('def myfunc(a=1,b=2): return a+b')
290 311 s, matches = c.complete(None, 'myfunc(1,b')
291 312 nt.assert_in('b=', matches)
292 313 # Simulate completing with cursor right after b (pos==10):
293 314 s, matches = c.complete(None, 'myfunc(1,b)', 10)
294 315 nt.assert_in('b=', matches)
295 316 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
296 317 nt.assert_in('b=', matches)
297 318 #builtin function
298 319 s, matches = c.complete(None, 'min(k, k')
299 320 nt.assert_in('key=', matches)
300 321
301 322
302 323 def test_default_arguments_from_docstring():
303 324 doc = min.__doc__
304 325 ip = get_ipython()
305 326 c = ip.Completer
306 327 kwd = c._default_arguments_from_docstring(
307 328 'min(iterable[, key=func]) -> value')
308 329 nt.assert_equal(kwd, ['key'])
309 330 #with cython type etc
310 331 kwd = c._default_arguments_from_docstring(
311 332 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
312 333 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
313 334 #white spaces
314 335 kwd = c._default_arguments_from_docstring(
315 336 '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
316 337 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
317 338
318 339 def test_line_magics():
319 340 ip = get_ipython()
320 341 c = ip.Completer
321 342 s, matches = c.complete(None, 'lsmag')
322 343 nt.assert_in('%lsmagic', matches)
323 344 s, matches = c.complete(None, '%lsmag')
324 345 nt.assert_in('%lsmagic', matches)
325 346
326 347
327 348 def test_cell_magics():
328 349 from IPython.core.magic import register_cell_magic
329 350
330 351 @register_cell_magic
331 352 def _foo_cellm(line, cell):
332 353 pass
333 354
334 355 ip = get_ipython()
335 356 c = ip.Completer
336 357
337 358 s, matches = c.complete(None, '_foo_ce')
338 359 nt.assert_in('%%_foo_cellm', matches)
339 360 s, matches = c.complete(None, '%%_foo_ce')
340 361 nt.assert_in('%%_foo_cellm', matches)
341 362
342 363
343 364 def test_line_cell_magics():
344 365 from IPython.core.magic import register_line_cell_magic
345 366
346 367 @register_line_cell_magic
347 368 def _bar_cellm(line, cell):
348 369 pass
349 370
350 371 ip = get_ipython()
351 372 c = ip.Completer
352 373
353 374 # The policy here is trickier, see comments in completion code. The
354 375 # returned values depend on whether the user passes %% or not explicitly,
355 376 # and this will show a difference if the same name is both a line and cell
356 377 # magic.
357 378 s, matches = c.complete(None, '_bar_ce')
358 379 nt.assert_in('%_bar_cellm', matches)
359 380 nt.assert_in('%%_bar_cellm', matches)
360 381 s, matches = c.complete(None, '%_bar_ce')
361 382 nt.assert_in('%_bar_cellm', matches)
362 383 nt.assert_in('%%_bar_cellm', matches)
363 384 s, matches = c.complete(None, '%%_bar_ce')
364 385 nt.assert_not_in('%_bar_cellm', matches)
365 386 nt.assert_in('%%_bar_cellm', matches)
366 387
367 388
368 389 def test_magic_completion_order():
369 390
370 391 ip = get_ipython()
371 392 c = ip.Completer
372 393
373 394 # Test ordering of magics and non-magics with the same name
374 395 # We want the non-magic first
375 396
376 397 # Before importing matplotlib, there should only be one option:
377 398
378 399 text, matches = c.complete('mat')
379 400 nt.assert_equal(matches, ["%matplotlib"])
380 401
381 402
382 403 ip.run_cell("matplotlib = 1") # introduce name into namespace
383 404
384 405 # After the import, there should be two options, ordered like this:
385 406 text, matches = c.complete('mat')
386 407 nt.assert_equal(matches, ["matplotlib", "%matplotlib"])
387 408
388 409
389 410 ip.run_cell("timeit = 1") # define a user variable called 'timeit'
390 411
391 412 # Order of user variable and line and cell magics with same name:
392 413 text, matches = c.complete('timeit')
393 414 nt.assert_equal(matches, ["timeit", "%timeit","%%timeit"])
394 415
395 416
396 417 def test_dict_key_completion_string():
397 418 """Test dictionary key completion for string keys"""
398 419 ip = get_ipython()
399 420 complete = ip.Completer.complete
400 421
401 422 ip.user_ns['d'] = {'abc': None}
402 423
403 424 # check completion at different stages
404 425 _, matches = complete(line_buffer="d[")
405 426 nt.assert_in("'abc'", matches)
406 427 nt.assert_not_in("'abc']", matches)
407 428
408 429 _, matches = complete(line_buffer="d['")
409 430 nt.assert_in("abc", matches)
410 431 nt.assert_not_in("abc']", matches)
411 432
412 433 _, matches = complete(line_buffer="d['a")
413 434 nt.assert_in("abc", matches)
414 435 nt.assert_not_in("abc']", matches)
415 436
416 437 # check use of different quoting
417 438 _, matches = complete(line_buffer="d[\"")
418 439 nt.assert_in("abc", matches)
419 440 nt.assert_not_in('abc\"]', matches)
420 441
421 442 _, matches = complete(line_buffer="d[\"a")
422 443 nt.assert_in("abc", matches)
423 444 nt.assert_not_in('abc\"]', matches)
424 445
425 446 # check sensitivity to following context
426 447 _, matches = complete(line_buffer="d[]", cursor_pos=2)
427 448 nt.assert_in("'abc'", matches)
428 449
429 450 _, matches = complete(line_buffer="d['']", cursor_pos=3)
430 451 nt.assert_in("abc", matches)
431 452 nt.assert_not_in("abc'", matches)
432 453 nt.assert_not_in("abc']", matches)
433 454
434 455 # check multiple solutions are correctly returned and that noise is not
435 456 ip.user_ns['d'] = {'abc': None, 'abd': None, 'bad': None, object(): None,
436 457 5: None}
437 458
438 459 _, matches = complete(line_buffer="d['a")
439 460 nt.assert_in("abc", matches)
440 461 nt.assert_in("abd", matches)
441 462 nt.assert_not_in("bad", matches)
442 463 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
443 464
444 465 # check escaping and whitespace
445 466 ip.user_ns['d'] = {'a\nb': None, 'a\'b': None, 'a"b': None, 'a word': None}
446 467 _, matches = complete(line_buffer="d['a")
447 468 nt.assert_in("a\\nb", matches)
448 469 nt.assert_in("a\\'b", matches)
449 470 nt.assert_in("a\"b", matches)
450 471 nt.assert_in("a word", matches)
451 472 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
452 473
453 474 # - can complete on non-initial word of the string
454 475 _, matches = complete(line_buffer="d['a w")
455 476 nt.assert_in("word", matches)
456 477
457 478 # - understands quote escaping
458 479 _, matches = complete(line_buffer="d['a\\'")
459 480 nt.assert_in("b", matches)
460 481
461 482 # - default quoting should work like repr
462 483 _, matches = complete(line_buffer="d[")
463 484 nt.assert_in("\"a'b\"", matches)
464 485
465 486 # - when opening quote with ", possible to match with unescaped apostrophe
466 487 _, matches = complete(line_buffer="d[\"a'")
467 488 nt.assert_in("b", matches)
468 489
469 490
470 491 def test_dict_key_completion_contexts():
471 492 """Test expression contexts in which dict key completion occurs"""
472 493 ip = get_ipython()
473 494 complete = ip.Completer.complete
474 495 d = {'abc': None}
475 496 ip.user_ns['d'] = d
476 497
477 498 class C:
478 499 data = d
479 500 ip.user_ns['C'] = C
480 501 ip.user_ns['get'] = lambda: d
481 502
482 503 def assert_no_completion(**kwargs):
483 504 _, matches = complete(**kwargs)
484 505 nt.assert_not_in('abc', matches)
485 506 nt.assert_not_in('abc\'', matches)
486 507 nt.assert_not_in('abc\']', matches)
487 508 nt.assert_not_in('\'abc\'', matches)
488 509 nt.assert_not_in('\'abc\']', matches)
489 510
490 511 def assert_completion(**kwargs):
491 512 _, matches = complete(**kwargs)
492 513 nt.assert_in("'abc'", matches)
493 514 nt.assert_not_in("'abc']", matches)
494 515
495 516 # no completion after string closed, even if reopened
496 517 assert_no_completion(line_buffer="d['a'")
497 518 assert_no_completion(line_buffer="d[\"a\"")
498 519 assert_no_completion(line_buffer="d['a' + ")
499 520 assert_no_completion(line_buffer="d['a' + '")
500 521
501 522 # completion in non-trivial expressions
502 523 assert_completion(line_buffer="+ d[")
503 524 assert_completion(line_buffer="(d[")
504 525 assert_completion(line_buffer="C.data[")
505 526
506 527 # greedy flag
507 528 def assert_completion(**kwargs):
508 529 _, matches = complete(**kwargs)
509 530 nt.assert_in("get()['abc']", matches)
510 531
511 532 assert_no_completion(line_buffer="get()[")
512 533 with greedy_completion():
513 534 assert_completion(line_buffer="get()[")
514 535 assert_completion(line_buffer="get()['")
515 536 assert_completion(line_buffer="get()['a")
516 537 assert_completion(line_buffer="get()['ab")
517 538 assert_completion(line_buffer="get()['abc")
518 539
519 540
520 541
521 542 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
522 543 def test_dict_key_completion_bytes():
523 544 """Test handling of bytes in dict key completion"""
524 545 ip = get_ipython()
525 546 complete = ip.Completer.complete
526 547
527 548 ip.user_ns['d'] = {'abc': None, b'abd': None}
528 549
529 550 _, matches = complete(line_buffer="d[")
530 551 nt.assert_in("'abc'", matches)
531 552 nt.assert_in("b'abd'", matches)
532 553
533 554 if False: # not currently implemented
534 555 _, matches = complete(line_buffer="d[b")
535 556 nt.assert_in("b'abd'", matches)
536 557 nt.assert_not_in("b'abc'", matches)
537 558
538 559 _, matches = complete(line_buffer="d[b'")
539 560 nt.assert_in("abd", matches)
540 561 nt.assert_not_in("abc", matches)
541 562
542 563 _, matches = complete(line_buffer="d[B'")
543 564 nt.assert_in("abd", matches)
544 565 nt.assert_not_in("abc", matches)
545 566
546 567 _, matches = complete(line_buffer="d['")
547 568 nt.assert_in("abc", matches)
548 569 nt.assert_not_in("abd", matches)
549 570
550 571
551 572 @dec.onlyif(sys.version_info[0] < 3, 'This test only applies in Py<3')
552 573 def test_dict_key_completion_unicode_py2():
553 574 """Test handling of unicode in dict key completion"""
554 575 ip = get_ipython()
555 576 complete = ip.Completer.complete
556 577
557 578 ip.user_ns['d'] = {u'abc': None,
558 579 u'a\u05d0b': None}
559 580
560 581 _, matches = complete(line_buffer="d[")
561 582 nt.assert_in("u'abc'", matches)
562 583 nt.assert_in("u'a\\u05d0b'", matches)
563 584
564 585 _, matches = complete(line_buffer="d['a")
565 586 nt.assert_in("abc", matches)
566 587 nt.assert_not_in("a\\u05d0b", matches)
567 588
568 589 _, matches = complete(line_buffer="d[u'a")
569 590 nt.assert_in("abc", matches)
570 591 nt.assert_in("a\\u05d0b", matches)
571 592
572 593 _, matches = complete(line_buffer="d[U'a")
573 594 nt.assert_in("abc", matches)
574 595 nt.assert_in("a\\u05d0b", matches)
575 596
576 597 # query using escape
577 598 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
578 599 nt.assert_in("u05d0b", matches) # tokenized after \\
579 600
580 601 # query using character
581 602 _, matches = complete(line_buffer=u"d[u'a\u05d0")
582 603 nt.assert_in(u"a\u05d0b", matches)
583 604
584 605 with greedy_completion():
585 606 _, matches = complete(line_buffer="d[")
586 607 nt.assert_in("d[u'abc']", matches)
587 608 nt.assert_in("d[u'a\\u05d0b']", matches)
588 609
589 610 _, matches = complete(line_buffer="d['a")
590 611 nt.assert_in("d['abc']", matches)
591 612 nt.assert_not_in("d[u'a\\u05d0b']", matches)
592 613
593 614 _, matches = complete(line_buffer="d[u'a")
594 615 nt.assert_in("d[u'abc']", matches)
595 616 nt.assert_in("d[u'a\\u05d0b']", matches)
596 617
597 618 _, matches = complete(line_buffer="d[U'a")
598 619 nt.assert_in("d[U'abc']", matches)
599 620 nt.assert_in("d[U'a\\u05d0b']", matches)
600 621
601 622 # query using escape
602 623 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
603 624 nt.assert_in("d[u'a\\u05d0b']", matches) # tokenized after \\
604 625
605 626 # query using character
606 627 _, matches = complete(line_buffer=u"d[u'a\u05d0")
607 628 nt.assert_in(u"d[u'a\u05d0b']", matches)
608 629
609 630
610 631 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
611 632 def test_dict_key_completion_unicode_py3():
612 633 """Test handling of unicode in dict key completion"""
613 634 ip = get_ipython()
614 635 complete = ip.Completer.complete
615 636
616 637 ip.user_ns['d'] = {u'a\u05d0': None}
617 638
618 639 # query using escape
619 640 _, matches = complete(line_buffer="d['a\\u05d0")
620 641 nt.assert_in("u05d0", matches) # tokenized after \\
621 642
622 643 # query using character
623 644 _, matches = complete(line_buffer="d['a\u05d0")
624 645 nt.assert_in(u"a\u05d0", matches)
625 646
626 647 with greedy_completion():
627 648 # query using escape
628 649 _, matches = complete(line_buffer="d['a\\u05d0")
629 650 nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\
630 651
631 652 # query using character
632 653 _, matches = complete(line_buffer="d['a\u05d0")
633 654 nt.assert_in(u"d['a\u05d0']", matches)
634 655
635 656
636 657
637 658 @dec.skip_without('numpy')
638 659 def test_struct_array_key_completion():
639 660 """Test dict key completion applies to numpy struct arrays"""
640 661 import numpy
641 662 ip = get_ipython()
642 663 complete = ip.Completer.complete
643 664 ip.user_ns['d'] = numpy.array([], dtype=[('hello', 'f'), ('world', 'f')])
644 665 _, matches = complete(line_buffer="d['")
645 666 nt.assert_in("hello", matches)
646 667 nt.assert_in("world", matches)
647 668
648 669
649 670 @dec.skip_without('pandas')
650 671 def test_dataframe_key_completion():
651 672 """Test dict key completion applies to pandas DataFrames"""
652 673 import pandas
653 674 ip = get_ipython()
654 675 complete = ip.Completer.complete
655 676 ip.user_ns['d'] = pandas.DataFrame({'hello': [1], 'world': [2]})
656 677 _, matches = complete(line_buffer="d['")
657 678 nt.assert_in("hello", matches)
658 679 nt.assert_in("world", matches)
659 680
660 681
661 682 def test_dict_key_completion_invalids():
662 683 """Smoke test cases dict key completion can't handle"""
663 684 ip = get_ipython()
664 685 complete = ip.Completer.complete
665 686
666 687 ip.user_ns['no_getitem'] = None
667 688 ip.user_ns['no_keys'] = []
668 689 ip.user_ns['cant_call_keys'] = dict
669 690 ip.user_ns['empty'] = {}
670 691 ip.user_ns['d'] = {'abc': 5}
671 692
672 693 _, matches = complete(line_buffer="no_getitem['")
673 694 _, matches = complete(line_buffer="no_keys['")
674 695 _, matches = complete(line_buffer="cant_call_keys['")
675 696 _, matches = complete(line_buffer="empty['")
676 697 _, matches = complete(line_buffer="name_error['")
677 698 _, matches = complete(line_buffer="d['\\") # incomplete escape
@@ -1,23 +1,28 b''
1 1 // IPython mode is just a slightly altered Python Mode with `?` beeing a extra
2 2 // single operator. Here we define `ipython` mode in the require `python`
3 3 // callback to auto-load python mode, which is more likely not the best things
4 4 // to do, but at least the simple one for now.
5 5
6 6 CodeMirror.requireMode('python',function(){
7 7 "use strict";
8 8
9 9 CodeMirror.defineMode("ipython", function(conf, parserConf) {
10 10 var pythonConf = {};
11 11 for (var prop in parserConf) {
12 12 if (parserConf.hasOwnProperty(prop)) {
13 13 pythonConf[prop] = parserConf[prop];
14 14 }
15 15 }
16 16 pythonConf.name = 'python';
17 17 pythonConf.singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!\\?]");
18 if (pythonConf.version === 3) {
19 console.log('setting up for python 3');
18 20 pythonConf.identifiers = new RegExp("^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*");
21 } else if (pythonConf.version === 2) {
22 pythonConf.identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
23 }
19 24 return CodeMirror.getMode(conf, pythonConf);
20 25 }, 'python');
21 26
22 27 CodeMirror.defineMIME("text/x-ipython", "ipython");
23 28 })
General Comments 0
You need to be logged in to leave comments. Login now