File: test_completer.py

package info (click to toggle)
ipython 2.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 28,032 kB
  • ctags: 15,433
  • sloc: python: 73,792; makefile: 428; sh: 297
file content (394 lines) | stat: -rw-r--r-- 12,562 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
"""Tests for the IPython tab-completion machinery.
"""
#-----------------------------------------------------------------------------
# Module imports
#-----------------------------------------------------------------------------

# stdlib
import os
import sys
import unittest

# third party
import nose.tools as nt

# our own packages
from IPython.config.loader import Config
from IPython.core import completer
from IPython.external.decorators import knownfailureif
from IPython.utils.tempdir import TemporaryDirectory
from IPython.utils.generics import complete_object
from IPython.utils import py3compat
from IPython.utils.py3compat import string_types, unicode_type

#-----------------------------------------------------------------------------
# Test functions
#-----------------------------------------------------------------------------
def test_protect_filename():
    pairs = [ ('abc','abc'),
              (' abc',r'\ abc'),
              ('a bc',r'a\ bc'),
              ('a  bc',r'a\ \ bc'),
              ('  bc',r'\ \ bc'),
              ]
    # On posix, we also protect parens and other special characters
    if sys.platform != 'win32':
        pairs.extend( [('a(bc',r'a\(bc'),
                       ('a)bc',r'a\)bc'),
                       ('a( )bc',r'a\(\ \)bc'),
                       ('a[1]bc', r'a\[1\]bc'),
                       ('a{1}bc', r'a\{1\}bc'),
                       ('a#bc', r'a\#bc'),
                       ('a?bc', r'a\?bc'),
                       ('a=bc', r'a\=bc'),
                       ('a\\bc', r'a\\bc'),
                       ('a|bc', r'a\|bc'),
                       ('a;bc', r'a\;bc'),
                       ('a:bc', r'a\:bc'),
                       ("a'bc", r"a\'bc"),
                       ('a*bc', r'a\*bc'),
                       ('a"bc', r'a\"bc'),
                       ('a^bc', r'a\^bc'),
                       ('a&bc', r'a\&bc'),
                       ] )
    # run the actual tests
    for s1, s2 in pairs:
        s1p = completer.protect_filename(s1)
        nt.assert_equal(s1p, s2)


def check_line_split(splitter, test_specs):
    for part1, part2, split in test_specs:
        cursor_pos = len(part1)
        line = part1+part2
        out = splitter.split_line(line, cursor_pos)
        nt.assert_equal(out, split)


def test_line_split():
    """Basic line splitter test with default specs."""
    sp = completer.CompletionSplitter()
    # The format of the test specs is: part1, part2, expected answer.  Parts 1
    # and 2 are joined into the 'line' sent to the splitter, as if the cursor
    # was at the end of part1.  So an empty part2 represents someone hitting
    # tab at the end of the line, the most common case.
    t = [('run some/scrip', '', 'some/scrip'),
         ('run scripts/er', 'ror.py foo', 'scripts/er'),
         ('echo $HOM', '', 'HOM'),
         ('print sys.pa', '', 'sys.pa'),
         ('print(sys.pa', '', 'sys.pa'),
         ("execfile('scripts/er", '', 'scripts/er'),
         ('a[x.', '', 'x.'),
         ('a[x.', 'y', 'x.'),
         ('cd "some_file/', '', 'some_file/'),
         ]
    check_line_split(sp, t)
    # Ensure splitting works OK with unicode by re-running the tests with
    # all inputs turned into unicode
    check_line_split(sp, [ map(unicode_type, p) for p in t] )


def test_custom_completion_error():
    """Test that errors from custom attribute completers are silenced."""
    ip = get_ipython()
    class A(object): pass
    ip.user_ns['a'] = A()
    
    @complete_object.when_type(A)
    def complete_A(a, existing_completions):
        raise TypeError("this should be silenced")
    
    ip.complete("a.")


def test_unicode_completions():
    ip = get_ipython()
    # Some strings that trigger different types of completion.  Check them both
    # in str and unicode forms
    s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
    for t in s + list(map(unicode_type, s)):
        # We don't need to check exact completion values (they may change
        # depending on the state of the namespace, but at least no exceptions
        # should be thrown and the return value should be a pair of text, list
        # values.
        text, matches = ip.complete(t)
        nt.assert_true(isinstance(text, string_types))
        nt.assert_true(isinstance(matches, list))


class CompletionSplitterTestCase(unittest.TestCase):
    def setUp(self):
        self.sp = completer.CompletionSplitter()

    def test_delim_setting(self):
        self.sp.delims = ' '
        nt.assert_equal(self.sp.delims, ' ')
        nt.assert_equal(self.sp._delim_expr, '[\ ]')

    def test_spaces(self):
        """Test with only spaces as split chars."""
        self.sp.delims = ' '
        t = [('foo', '', 'foo'),
             ('run foo', '', 'foo'),
             ('run foo', 'bar', 'foo'),
             ]
        check_line_split(self.sp, t)


def test_has_open_quotes1():
    for s in ["'", "'''", "'hi' '"]:
        nt.assert_equal(completer.has_open_quotes(s), "'")


def test_has_open_quotes2():
    for s in ['"', '"""', '"hi" "']:
        nt.assert_equal(completer.has_open_quotes(s), '"')


def test_has_open_quotes3():
    for s in ["''", "''' '''", "'hi' 'ipython'"]:
        nt.assert_false(completer.has_open_quotes(s))


def test_has_open_quotes4():
    for s in ['""', '""" """', '"hi" "ipython"']:
        nt.assert_false(completer.has_open_quotes(s))


@knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
def test_abspath_file_completions():
    ip = get_ipython()
    with TemporaryDirectory() as tmpdir:
        prefix = os.path.join(tmpdir, 'foo')
        suffixes = ['1', '2']
        names = [prefix+s for s in suffixes]
        for n in names:
            open(n, 'w').close()

        # Check simple completion
        c = ip.complete(prefix)[1]
        nt.assert_equal(c, names)

        # Now check with a function call
        cmd = 'a = f("%s' % prefix
        c = ip.complete(prefix, cmd)[1]
        comp = [prefix+s for s in suffixes]
        nt.assert_equal(c, comp)


def test_local_file_completions():
    ip = get_ipython()
    cwd = py3compat.getcwd()
    try:
        with TemporaryDirectory() as tmpdir:
            os.chdir(tmpdir)
            prefix = './foo'
            suffixes = ['1', '2']
            names = [prefix+s for s in suffixes]
            for n in names:
                open(n, 'w').close()

            # Check simple completion
            c = ip.complete(prefix)[1]
            nt.assert_equal(c, names)

            # Now check with a function call
            cmd = 'a = f("%s' % prefix
            c = ip.complete(prefix, cmd)[1]
            comp = [prefix+s for s in suffixes]
            nt.assert_equal(c, comp)
    finally:
        # prevent failures from making chdir stick
        os.chdir(cwd)


def test_greedy_completions():
    ip = get_ipython()
    greedy_original = ip.Completer.greedy
    try:
        ip.Completer.greedy = False
        ip.ex('a=list(range(5))')
        _,c = ip.complete('.',line='a[0].')
        nt.assert_false('a[0].real' in c,
                        "Shouldn't have completed on a[0]: %s"%c)
        ip.Completer.greedy = True
        _,c = ip.complete('.',line='a[0].')
        nt.assert_true('a[0].real' in c, "Should have completed on a[0]: %s"%c)
    finally:
        ip.Completer.greedy = greedy_original


def test_omit__names():
    # also happens to test IPCompleter as a configurable
    ip = get_ipython()
    ip._hidden_attr = 1
    c = ip.Completer
    ip.ex('ip=get_ipython()')
    cfg = Config()
    cfg.IPCompleter.omit__names = 0
    c.update_config(cfg)
    s,matches = c.complete('ip.')
    nt.assert_in('ip.__str__', matches)
    nt.assert_in('ip._hidden_attr', matches)
    cfg.IPCompleter.omit__names = 1
    c.update_config(cfg)
    s,matches = c.complete('ip.')
    nt.assert_not_in('ip.__str__', matches)
    nt.assert_in('ip._hidden_attr', matches)
    cfg.IPCompleter.omit__names = 2
    c.update_config(cfg)
    s,matches = c.complete('ip.')
    nt.assert_not_in('ip.__str__', matches)
    nt.assert_not_in('ip._hidden_attr', matches)
    del ip._hidden_attr


def test_limit_to__all__False_ok():
    ip = get_ipython()
    c = ip.Completer
    ip.ex('class D: x=24')
    ip.ex('d=D()')
    cfg = Config()
    cfg.IPCompleter.limit_to__all__ = False
    c.update_config(cfg)
    s, matches = c.complete('d.')
    nt.assert_in('d.x', matches)


def test_limit_to__all__True_ok():
    ip = get_ipython()
    c = ip.Completer
    ip.ex('class D: x=24')
    ip.ex('d=D()')
    ip.ex("d.__all__=['z']")
    cfg = Config()
    cfg.IPCompleter.limit_to__all__ = True
    c.update_config(cfg)
    s, matches = c.complete('d.')
    nt.assert_in('d.z', matches)
    nt.assert_not_in('d.x', matches)


def test_get__all__entries_ok():
    class A(object):
        __all__ = ['x', 1]
    words = completer.get__all__entries(A())
    nt.assert_equal(words, ['x'])


def test_get__all__entries_no__all__ok():
    class A(object):
        pass
    words = completer.get__all__entries(A())
    nt.assert_equal(words, [])


def test_func_kw_completions():
    ip = get_ipython()
    c = ip.Completer
    ip.ex('def myfunc(a=1,b=2): return a+b')
    s, matches = c.complete(None, 'myfunc(1,b')
    nt.assert_in('b=', matches)
    # Simulate completing with cursor right after b (pos==10):
    s, matches = c.complete(None, 'myfunc(1,b)', 10)
    nt.assert_in('b=', matches)
    s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
    nt.assert_in('b=', matches)
    #builtin function
    s, matches = c.complete(None, 'min(k, k')
    nt.assert_in('key=', matches)


def test_default_arguments_from_docstring():
    doc = min.__doc__
    ip = get_ipython()
    c = ip.Completer
    kwd = c._default_arguments_from_docstring(
        'min(iterable[, key=func]) -> value')
    nt.assert_equal(kwd, ['key'])
    #with cython type etc
    kwd = c._default_arguments_from_docstring(
        'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
    nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
    #white spaces
    kwd = c._default_arguments_from_docstring(
        '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
    nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])

def test_line_magics():
    ip = get_ipython()
    c = ip.Completer
    s, matches = c.complete(None, 'lsmag')
    nt.assert_in('%lsmagic', matches)
    s, matches = c.complete(None, '%lsmag')
    nt.assert_in('%lsmagic', matches)


def test_cell_magics():
    from IPython.core.magic import register_cell_magic

    @register_cell_magic
    def _foo_cellm(line, cell):
        pass
    
    ip = get_ipython()
    c = ip.Completer

    s, matches = c.complete(None, '_foo_ce')
    nt.assert_in('%%_foo_cellm', matches)
    s, matches = c.complete(None, '%%_foo_ce')
    nt.assert_in('%%_foo_cellm', matches)


def test_line_cell_magics():
    from IPython.core.magic import register_line_cell_magic

    @register_line_cell_magic
    def _bar_cellm(line, cell):
        pass
    
    ip = get_ipython()
    c = ip.Completer

    # The policy here is trickier, see comments in completion code.  The
    # returned values depend on whether the user passes %% or not explicitly,
    # and this will show a difference if the same name is both a line and cell
    # magic.
    s, matches = c.complete(None, '_bar_ce')
    nt.assert_in('%_bar_cellm', matches)
    nt.assert_in('%%_bar_cellm', matches)
    s, matches = c.complete(None, '%_bar_ce')
    nt.assert_in('%_bar_cellm', matches)
    nt.assert_in('%%_bar_cellm', matches)
    s, matches = c.complete(None, '%%_bar_ce')
    nt.assert_not_in('%_bar_cellm', matches)
    nt.assert_in('%%_bar_cellm', matches)


def test_magic_completion_order():

    ip = get_ipython()
    c = ip.Completer

    # Test ordering of magics and non-magics with the same name
    # We want the non-magic first

    # Before importing matplotlib, there should only be one option:

    text, matches = c.complete('mat')
    nt.assert_equal(matches, ["%matplotlib"])


    ip.run_cell("matplotlib = 1")  # introduce name into namespace

    # After the import, there should be two options, ordered like this:
    text, matches = c.complete('mat')
    nt.assert_equal(matches, ["matplotlib", "%matplotlib"])


    ip.run_cell("timeit = 1")  # define a user variable called 'timeit'

    # Order of user variable and line and cell magics with same name:
    text, matches = c.complete('timeit')
    nt.assert_equal(matches, ["timeit", "%timeit","%%timeit"])