##// END OF EJS Templates
multifile selection
multifile selection

File last commit:

r6512:d6cfddab
r6839:f01957f4
Show More
test_completer.py
286 lines | 8.9 KiB | text/x-python | PythonLexer
Fernando Perez
Fix tab-completion for magics, other completion cleanup and fixes....
r2365 """Tests for the IPython tab-completion machinery.
"""
#-----------------------------------------------------------------------------
# Module imports
#-----------------------------------------------------------------------------
# stdlib
Fernando Perez
Fix bug in tab completion of filenames when quotes are present....
r3184 import os
Fernando Perez
Fix tab-completion for magics, other completion cleanup and fixes....
r2365 import sys
Fernando Perez
Add line splitting for text completion (like readline does internally)....
r2855 import unittest
Fernando Perez
Fix tab-completion for magics, other completion cleanup and fixes....
r2365
# third party
import nose.tools as nt
# our own packages
MinRK
move completer configurables to IPCompleter where they belong...
r5231 from IPython.config.loader import Config
Fernando Perez
Fix tab-completion for magics, other completion cleanup and fixes....
r2365 from IPython.core import completer
Min RK
fix various tests on Windows...
r4105 from IPython.external.decorators import knownfailureif
Fernando Perez
Fix bug in tab completion of filenames when quotes are present....
r3184 from IPython.utils.tempdir import TemporaryDirectory
Thomas Kluyver
Silence errors from custom attribute completer functions....
r5155 from IPython.utils.generics import complete_object
Fernando Perez
Fix tab-completion for magics, other completion cleanup and fixes....
r2365
#-----------------------------------------------------------------------------
# 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'),
]
Fernando Perez
Fix protection of special characters on tab completion....
r3176 # On posix, we also protect parens and other special characters
Fernando Perez
Fix tab-completion for magics, other completion cleanup and fixes....
r2365 if sys.platform != 'win32':
pairs.extend( [('a(bc',r'a\(bc'),
('a)bc',r'a\)bc'),
('a( )bc',r'a\(\ \)bc'),
Fernando Perez
Fix protection of special characters on tab completion....
r3176 ('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'),
Fernando Perez
Fix tab-completion for magics, other completion cleanup and fixes....
r2365 ] )
# run the actual tests
for s1, s2 in pairs:
s1p = completer.protect_filename(s1)
nt.assert_equals(s1p, s2)
Fernando Perez
Add line splitting for text completion (like readline does internally)....
r2855
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():
"""Basice 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)
Fernando Perez
Fix completer crash with certain unicode inputs....
r3074 # Ensure splitting works OK with unicode by re-running the tests with
# all inputs turned into unicode
check_line_split(sp, [ map(unicode, p) for p in t] )
Piti Ongmongkolkul
test function kw completer
r6511
Thomas Kluyver
Silence errors from custom attribute completer functions....
r5155 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.")
Fernando Perez
Fix completer crash with certain unicode inputs....
r3074
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 + map(unicode, 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, basestring))
nt.assert_true(isinstance(matches, list))
Fernando Perez
Add line splitting for text completion (like readline does internally)....
r2855
class CompletionSplitterTestCase(unittest.TestCase):
def setUp(self):
self.sp = completer.CompletionSplitter()
def test_delim_setting(self):
Fernando Perez
Improvements to tab completion in Qt GUI with new api....
r2857 self.sp.set_delims(' ')
nt.assert_equal(self.sp.get_delims(), ' ')
nt.assert_equal(self.sp._delim_expr, '[\ ]')
Fernando Perez
Add line splitting for text completion (like readline does internally)....
r2855
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)
Fernando Perez
Fix bug in tab completion of filenames when quotes are present....
r3184
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))
Piti Ongmongkolkul
test function kw completer
r6511
Min RK
fix various tests on Windows...
r4105 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
def test_abspath_file_completions():
Fernando Perez
Fix bug in tab completion of filenames when quotes are present....
r3184 ip = get_ipython()
with TemporaryDirectory() as tmpdir:
prefix = os.path.join(tmpdir, 'foo')
suffixes = map(str, [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)
Min RK
fix various tests on Windows...
r4105
Piti Ongmongkolkul
test function kw completer
r6511
Min RK
fix various tests on Windows...
r4105 def test_local_file_completions():
ip = get_ipython()
cwd = os.getcwdu()
try:
with TemporaryDirectory() as tmpdir:
os.chdir(tmpdir)
prefix = './foo'
suffixes = map(str, [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)
MinRK
make Completer.greedy configurable
r4825
Piti Ongmongkolkul
test function kw completer
r6511
MinRK
make Completer.greedy configurable
r4825 def test_greedy_completions():
ip = get_ipython()
ip.Completer.greedy = False
ip.ex('a=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)
Piti Ongmongkolkul
test function kw completer
r6511
MinRK
move completer configurables to IPCompleter where they belong...
r5231 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_true('ip.__str__' in matches)
nt.assert_true('ip._hidden_attr' in matches)
cfg.IPCompleter.omit__names = 1
c.update_config(cfg)
s,matches = c.complete('ip.')
nt.assert_false('ip.__str__' in matches)
nt.assert_true('ip._hidden_attr' in matches)
cfg.IPCompleter.omit__names = 2
c.update_config(cfg)
s,matches = c.complete('ip.')
nt.assert_false('ip.__str__' in matches)
nt.assert_false('ip._hidden_attr' in matches)
del ip._hidden_attr
Tim Couper
added __all__ to completer.py and added basic tests for test_dir2...
r6308
Tim Couper
added tests for limit_to__all__ for False and True cases
r6312
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_true('d.x' in matches)
Piti Ongmongkolkul
test function kw completer
r6511
Tim Couper
added tests for limit_to__all__ for False and True cases
r6312 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_true('d.z' in matches)
nt.assert_false('d.x' in matches)
Piti Ongmongkolkul
test function kw completer
r6511
Tim Couper
added __all__ to completer.py and added basic tests for test_dir2...
r6308 def test_get__all__entries_ok():
Piti Ongmongkolkul
test function kw completer
r6511 class A(object):
__all__ = ['x', 1]
words = completer.get__all__entries(A())
nt.assert_equal(words, ['x'])
Tim Couper
added __all__ to completer.py and added basic tests for test_dir2...
r6308
def test_get__all__entries_no__all__ok():
Piti Ongmongkolkul
test function kw completer
r6511 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_true('b=' in matches)
Piti Ongmongkolkul
add some comment
r6512 s, matches = c.complete(None,'myfunc(1,b)',10)#cursor is right after b
Piti Ongmongkolkul
test function kw completer
r6511 nt.assert_true('b=' in matches)