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