##// END OF EJS Templates
test function kw completer
Piti Ongmongkolkul -
Show More
@@ -1,268 +1,286
1 1 """Tests for the IPython tab-completion machinery.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Module imports
5 5 #-----------------------------------------------------------------------------
6 6
7 7 # stdlib
8 8 import os
9 9 import sys
10 10 import unittest
11 11
12 12 # third party
13 13 import nose.tools as nt
14 14
15 15 # our own packages
16 16 from IPython.config.loader import Config
17 17 from IPython.core import completer
18 18 from IPython.external.decorators import knownfailureif
19 19 from IPython.utils.tempdir import TemporaryDirectory
20 20 from IPython.utils.generics import complete_object
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Test functions
24 24 #-----------------------------------------------------------------------------
25 25 def test_protect_filename():
26 26 pairs = [ ('abc','abc'),
27 27 (' abc',r'\ abc'),
28 28 ('a bc',r'a\ bc'),
29 29 ('a bc',r'a\ \ bc'),
30 30 (' bc',r'\ \ bc'),
31 31 ]
32 32 # On posix, we also protect parens and other special characters
33 33 if sys.platform != 'win32':
34 34 pairs.extend( [('a(bc',r'a\(bc'),
35 35 ('a)bc',r'a\)bc'),
36 36 ('a( )bc',r'a\(\ \)bc'),
37 37 ('a[1]bc', r'a\[1\]bc'),
38 38 ('a{1}bc', r'a\{1\}bc'),
39 39 ('a#bc', r'a\#bc'),
40 40 ('a?bc', r'a\?bc'),
41 41 ('a=bc', r'a\=bc'),
42 42 ('a\\bc', r'a\\bc'),
43 43 ('a|bc', r'a\|bc'),
44 44 ('a;bc', r'a\;bc'),
45 45 ('a:bc', r'a\:bc'),
46 46 ("a'bc", r"a\'bc"),
47 47 ('a*bc', r'a\*bc'),
48 48 ('a"bc', r'a\"bc'),
49 49 ('a^bc', r'a\^bc'),
50 50 ('a&bc', r'a\&bc'),
51 51 ] )
52 52 # run the actual tests
53 53 for s1, s2 in pairs:
54 54 s1p = completer.protect_filename(s1)
55 55 nt.assert_equals(s1p, s2)
56 56
57 57
58 58 def check_line_split(splitter, test_specs):
59 59 for part1, part2, split in test_specs:
60 60 cursor_pos = len(part1)
61 61 line = part1+part2
62 62 out = splitter.split_line(line, cursor_pos)
63 63 nt.assert_equal(out, split)
64 64
65 65
66 66 def test_line_split():
67 67 """Basice line splitter test with default specs."""
68 68 sp = completer.CompletionSplitter()
69 69 # The format of the test specs is: part1, part2, expected answer. Parts 1
70 70 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
71 71 # was at the end of part1. So an empty part2 represents someone hitting
72 72 # tab at the end of the line, the most common case.
73 73 t = [('run some/scrip', '', 'some/scrip'),
74 74 ('run scripts/er', 'ror.py foo', 'scripts/er'),
75 75 ('echo $HOM', '', 'HOM'),
76 76 ('print sys.pa', '', 'sys.pa'),
77 77 ('print(sys.pa', '', 'sys.pa'),
78 78 ("execfile('scripts/er", '', 'scripts/er'),
79 79 ('a[x.', '', 'x.'),
80 80 ('a[x.', 'y', 'x.'),
81 81 ('cd "some_file/', '', 'some_file/'),
82 82 ]
83 83 check_line_split(sp, t)
84 84 # Ensure splitting works OK with unicode by re-running the tests with
85 85 # all inputs turned into unicode
86 86 check_line_split(sp, [ map(unicode, p) for p in t] )
87 87
88
88 89 def test_custom_completion_error():
89 90 """Test that errors from custom attribute completers are silenced."""
90 91 ip = get_ipython()
91 92 class A(object): pass
92 93 ip.user_ns['a'] = A()
93 94
94 95 @complete_object.when_type(A)
95 96 def complete_A(a, existing_completions):
96 97 raise TypeError("this should be silenced")
97 98
98 99 ip.complete("a.")
99 100
100 101
101 102 def test_unicode_completions():
102 103 ip = get_ipython()
103 104 # Some strings that trigger different types of completion. Check them both
104 105 # in str and unicode forms
105 106 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
106 107 for t in s + map(unicode, s):
107 108 # We don't need to check exact completion values (they may change
108 109 # depending on the state of the namespace, but at least no exceptions
109 110 # should be thrown and the return value should be a pair of text, list
110 111 # values.
111 112 text, matches = ip.complete(t)
112 113 nt.assert_true(isinstance(text, basestring))
113 114 nt.assert_true(isinstance(matches, list))
114 115
115 116
116 117 class CompletionSplitterTestCase(unittest.TestCase):
117 118 def setUp(self):
118 119 self.sp = completer.CompletionSplitter()
119 120
120 121 def test_delim_setting(self):
121 122 self.sp.set_delims(' ')
122 123 nt.assert_equal(self.sp.get_delims(), ' ')
123 124 nt.assert_equal(self.sp._delim_expr, '[\ ]')
124 125
125 126 def test_spaces(self):
126 127 """Test with only spaces as split chars."""
127 128 self.sp.delims = ' '
128 129 t = [('foo', '', 'foo'),
129 130 ('run foo', '', 'foo'),
130 131 ('run foo', 'bar', 'foo'),
131 132 ]
132 133 check_line_split(self.sp, t)
133 134
134 135
135 136 def test_has_open_quotes1():
136 137 for s in ["'", "'''", "'hi' '"]:
137 138 nt.assert_equal(completer.has_open_quotes(s), "'")
138 139
139 140
140 141 def test_has_open_quotes2():
141 142 for s in ['"', '"""', '"hi" "']:
142 143 nt.assert_equal(completer.has_open_quotes(s), '"')
143 144
144 145
145 146 def test_has_open_quotes3():
146 147 for s in ["''", "''' '''", "'hi' 'ipython'"]:
147 148 nt.assert_false(completer.has_open_quotes(s))
148 149
149 150
150 151 def test_has_open_quotes4():
151 152 for s in ['""', '""" """', '"hi" "ipython"']:
152 153 nt.assert_false(completer.has_open_quotes(s))
153 154
155
154 156 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
155 157 def test_abspath_file_completions():
156 158 ip = get_ipython()
157 159 with TemporaryDirectory() as tmpdir:
158 160 prefix = os.path.join(tmpdir, 'foo')
159 161 suffixes = map(str, [1,2])
160 162 names = [prefix+s for s in suffixes]
161 163 for n in names:
162 164 open(n, 'w').close()
163 165
164 166 # Check simple completion
165 167 c = ip.complete(prefix)[1]
166 168 nt.assert_equal(c, names)
167 169
168 170 # Now check with a function call
169 171 cmd = 'a = f("%s' % prefix
170 172 c = ip.complete(prefix, cmd)[1]
171 173 comp = [prefix+s for s in suffixes]
172 174 nt.assert_equal(c, comp)
173 175
176
174 177 def test_local_file_completions():
175 178 ip = get_ipython()
176 179 cwd = os.getcwdu()
177 180 try:
178 181 with TemporaryDirectory() as tmpdir:
179 182 os.chdir(tmpdir)
180 183 prefix = './foo'
181 184 suffixes = map(str, [1,2])
182 185 names = [prefix+s for s in suffixes]
183 186 for n in names:
184 187 open(n, 'w').close()
185 188
186 189 # Check simple completion
187 190 c = ip.complete(prefix)[1]
188 191 nt.assert_equal(c, names)
189 192
190 193 # Now check with a function call
191 194 cmd = 'a = f("%s' % prefix
192 195 c = ip.complete(prefix, cmd)[1]
193 196 comp = [prefix+s for s in suffixes]
194 197 nt.assert_equal(c, comp)
195 198 finally:
196 199 # prevent failures from making chdir stick
197 200 os.chdir(cwd)
198 201
202
199 203 def test_greedy_completions():
200 204 ip = get_ipython()
201 205 ip.Completer.greedy = False
202 206 ip.ex('a=range(5)')
203 207 _,c = ip.complete('.',line='a[0].')
204 208 nt.assert_false('a[0].real' in c, "Shouldn't have completed on a[0]: %s"%c)
205 209 ip.Completer.greedy = True
206 210 _,c = ip.complete('.',line='a[0].')
207 211 nt.assert_true('a[0].real' in c, "Should have completed on a[0]: %s"%c)
208 212
213
209 214 def test_omit__names():
210 215 # also happens to test IPCompleter as a configurable
211 216 ip = get_ipython()
212 217 ip._hidden_attr = 1
213 218 c = ip.Completer
214 219 ip.ex('ip=get_ipython()')
215 220 cfg = Config()
216 221 cfg.IPCompleter.omit__names = 0
217 222 c.update_config(cfg)
218 223 s,matches = c.complete('ip.')
219 224 nt.assert_true('ip.__str__' in matches)
220 225 nt.assert_true('ip._hidden_attr' in matches)
221 226 cfg.IPCompleter.omit__names = 1
222 227 c.update_config(cfg)
223 228 s,matches = c.complete('ip.')
224 229 nt.assert_false('ip.__str__' in matches)
225 230 nt.assert_true('ip._hidden_attr' in matches)
226 231 cfg.IPCompleter.omit__names = 2
227 232 c.update_config(cfg)
228 233 s,matches = c.complete('ip.')
229 234 nt.assert_false('ip.__str__' in matches)
230 235 nt.assert_false('ip._hidden_attr' in matches)
231 236 del ip._hidden_attr
232 237
233 238
234 239 def test_limit_to__all__False_ok():
235 240 ip = get_ipython()
236 241 c = ip.Completer
237 242 ip.ex('class D: x=24')
238 243 ip.ex('d=D()')
239 244 cfg = Config()
240 245 cfg.IPCompleter.limit_to__all__ = False
241 246 c.update_config(cfg)
242 247 s, matches = c.complete('d.')
243 248 nt.assert_true('d.x' in matches)
244 249
250
245 251 def test_limit_to__all__True_ok():
246 252 ip = get_ipython()
247 253 c = ip.Completer
248 254 ip.ex('class D: x=24')
249 255 ip.ex('d=D()')
250 256 ip.ex("d.__all__=['z']")
251 257 cfg = Config()
252 258 cfg.IPCompleter.limit_to__all__ = True
253 259 c.update_config(cfg)
254 260 s, matches = c.complete('d.')
255 261 nt.assert_true('d.z' in matches)
256 262 nt.assert_false('d.x' in matches)
257 263
264
258 265 def test_get__all__entries_ok():
259 266 class A(object):
260 267 __all__ = ['x', 1]
261 268 words = completer.get__all__entries(A())
262 269 nt.assert_equal(words, ['x'])
263 270
271
264 272 def test_get__all__entries_no__all__ok():
265 273 class A(object):
266 274 pass
267 275 words = completer.get__all__entries(A())
268 276 nt.assert_equal(words, [])
277
278
279 def test_func_kw_completions():
280 ip = get_ipython()
281 c = ip.Completer
282 ip.ex('def myfunc(a=1,b=2): return a+b')
283 s, matches = c.complete(None,'myfunc(1,b')
284 nt.assert_true('b=' in matches)
285 s, matches = c.complete(None,'myfunc(1,b)',10)
286 nt.assert_true('b=' in matches)
General Comments 0
You need to be logged in to leave comments. Login now