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