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