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