Ejemplo n.º 1
0
def test_back_latex_completion():
    ip = get_ipython()

    # do not return more than 1 matches fro \beta, only the latex one.
    name, matches = ip.complete('\\β')
    nt.assert_equal(len(matches), 1)
    nt.assert_equal(matches[0], '\\beta')
Ejemplo n.º 2
0
def page(data, start=0, screen_lines=0, pager_cmd=None):
    """Display content in a pager, piping through a pager after a certain length.
    
    data can be a mime-bundle dict, supplying multiple representations,
    keyed by mime-type, or text.
    
    Pager is dispatched via the `show_in_pager` yap_ipython hook.
    If no hook is registered, `pager_page` will be used.
    """
    # Some routines may auto-compute start offsets incorrectly and pass a
    # negative value.  Offset to 0 for robustness.
    start = max(0, start)

    # first, try the hook
    ip = get_ipython()
    if ip:
        try:
            ip.hooks.show_in_pager(data,
                                   start=start,
                                   screen_lines=screen_lines)
            return
        except TryNext:
            pass

    # fallback on default pager
    return pager_page(data, start, screen_lines, pager_cmd)
Ejemplo n.º 3
0
def test_no_ascii_back_completion():
    ip = get_ipython()
    with TemporaryWorkingDirectory():  # Avoid any filename completions
        # single ascii letter that don't have yet completions
        for letter in 'jJ' :
            name, matches = ip.complete('\\'+letter)
            nt.assert_equal(matches, [])
Ejemplo n.º 4
0
def test_ipython_display_formatter():
    """Objects with _ipython_display_ defined bypass other formatters"""
    f = get_ipython().display_formatter
    catcher = []

    class SelfDisplaying(object):
        def _ipython_display_(self):
            catcher.append(self)

    class NotSelfDisplaying(object):
        def __repr__(self):
            return "NotSelfDisplaying"

        def _ipython_display_(self):
            raise NotImplementedError

    save_enabled = f.ipython_display_formatter.enabled
    f.ipython_display_formatter.enabled = True

    yes = SelfDisplaying()
    no = NotSelfDisplaying()

    d, md = f.format(no)
    nt.assert_equal(d, {'text/plain': repr(no)})
    nt.assert_equal(md, {})
    nt.assert_equal(catcher, [])

    d, md = f.format(yes)
    nt.assert_equal(d, {})
    nt.assert_equal(md, {})
    nt.assert_equal(catcher, [yes])

    f.ipython_display_formatter.enabled = save_enabled
Ejemplo n.º 5
0
def test_quoted_file_completions():
    ip = get_ipython()
    with TemporaryWorkingDirectory():
        name = "foo'bar"
        open(name, 'w').close()

        # Don't escape Windows
        escaped = name if sys.platform == "win32" else "foo\\'bar"

        # Single quote matches embedded single quote
        text = "open('foo"
        c = ip.Completer._complete(cursor_line=0,
                                   cursor_pos=len(text),
                                   full_text=text)[1]
        nt.assert_equal(c, [escaped])

        # Double quote requires no escape
        text = 'open("foo'
        c = ip.Completer._complete(cursor_line=0,
                                   cursor_pos=len(text),
                                   full_text=text)[1]
        nt.assert_equal(c, [name])

        # No quote requires an escape
        text = '%ls foo'
        c = ip.Completer._complete(cursor_line=0,
                                   cursor_pos=len(text),
                                   full_text=text)[1]
        nt.assert_equal(c, [escaped])
Ejemplo n.º 6
0
def test_back_latex_completion():
    ip = get_ipython()

    # do not return more than 1 matches fro \beta, only the latex one.
    name, matches = ip.complete('\\β')
    nt.assert_equal(len(matches), 1)
    nt.assert_equal(matches[0], '\\beta')
Ejemplo n.º 7
0
def test_no_ascii_back_completion():
    ip = get_ipython()
    with TemporaryWorkingDirectory():  # Avoid any filename completions
        # single ascii letter that don't have yet completions
        for letter in 'jJ':
            name, matches = ip.complete('\\' + letter)
            nt.assert_equal(matches, [])
Ejemplo n.º 8
0
def test_alias_magic():
    """Test %alias_magic."""
    ip = get_ipython()
    mm = ip.magics_manager

    # Basic operation: both cell and line magics are created, if possible.
    ip.run_line_magic('alias_magic', 'timeit_alias timeit')
    nt.assert_in('timeit_alias', mm.magics['line'])
    nt.assert_in('timeit_alias', mm.magics['cell'])

    # --cell is specified, line magic not created.
    ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
    nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
    nt.assert_in('timeit_cell_alias', mm.magics['cell'])

    # Test that line alias is created successfully.
    ip.run_line_magic('alias_magic', '--line env_alias env')
    nt.assert_equal(ip.run_line_magic('env', ''),
                    ip.run_line_magic('env_alias', ''))

    # Test that line alias with parameters passed in is created successfully.
    ip.run_line_magic(
        'alias_magic',
        '--line history_alias history --params ' + shlex.quote('3'))
    nt.assert_in('history_alias', mm.magics['line'])
Ejemplo n.º 9
0
def test_snake_case_completion():
    ip = get_ipython()
    ip.user_ns['some_three'] = 3
    ip.user_ns['some_four'] = 4
    _, matches = ip.complete("s_", "print(s_f")
    nt.assert_in('some_three', matches)
    nt.assert_in('some_four', matches)
Ejemplo n.º 10
0
def test_dict_key_completion_bytes():
    """Test handling of bytes in dict key completion"""
    ip = get_ipython()
    complete = ip.Completer.complete

    ip.user_ns['d'] = {'abc': None, b'abd': None}

    _, matches = complete(line_buffer="d[")
    nt.assert_in("'abc'", matches)
    nt.assert_in("b'abd'", matches)

    if False:  # not currently implemented
        _, matches = complete(line_buffer="d[b")
        nt.assert_in("b'abd'", matches)
        nt.assert_not_in("b'abc'", matches)

        _, matches = complete(line_buffer="d[b'")
        nt.assert_in("abd", matches)
        nt.assert_not_in("abc", matches)

        _, matches = complete(line_buffer="d[B'")
        nt.assert_in("abd", matches)
        nt.assert_not_in("abc", matches)

        _, matches = complete(line_buffer="d['")
        nt.assert_in("abc", matches)
        nt.assert_not_in("abd", matches)
Ejemplo n.º 11
0
def test_magic_config():
    ip = get_ipython()
    c = ip.Completer

    s, matches = c.complete(None, 'conf')
    nt.assert_in('%config', matches)
    s, matches = c.complete(None, 'conf')
    nt.assert_not_in('AliasManager', matches)
    s, matches = c.complete(None, 'config ')
    nt.assert_in('AliasManager', matches)
    s, matches = c.complete(None, '%config ')
    nt.assert_in('AliasManager', matches)
    s, matches = c.complete(None, 'config Ali')
    nt.assert_list_equal(['AliasManager'], matches)
    s, matches = c.complete(None, '%config Ali')
    nt.assert_list_equal(['AliasManager'], matches)
    s, matches = c.complete(None, 'config AliasManager')
    nt.assert_list_equal(['AliasManager'], matches)
    s, matches = c.complete(None, '%config AliasManager')
    nt.assert_list_equal(['AliasManager'], matches)
    s, matches = c.complete(None, 'config AliasManager.')
    nt.assert_in('AliasManager.default_aliases', matches)
    s, matches = c.complete(None, '%config AliasManager.')
    nt.assert_in('AliasManager.default_aliases', matches)
    s, matches = c.complete(None, 'config AliasManager.de')
    nt.assert_list_equal(['AliasManager.default_aliases'], matches)
    s, matches = c.complete(None, 'config AliasManager.de')
    nt.assert_list_equal(['AliasManager.default_aliases'], matches)
Ejemplo n.º 12
0
def test_dict_key_completion_unicode_py3():
    """Test handling of unicode in dict key completion"""
    ip = get_ipython()
    complete = ip.Completer.complete

    ip.user_ns['d'] = {u'a\u05d0': None}

    # query using escape
    if sys.platform != 'win32':
        # Known failure on Windows
        _, matches = complete(line_buffer="d['a\\u05d0")
        nt.assert_in("u05d0", matches)  # tokenized after \\

    # query using character
    _, matches = complete(line_buffer="d['a\u05d0")
    nt.assert_in(u"a\u05d0", matches)
    
    with greedy_completion():
        # query using escape
        _, matches = complete(line_buffer="d['a\\u05d0")
        nt.assert_in("d['a\\u05d0']", matches)  # tokenized after \\

        # query using character
        _, matches = complete(line_buffer="d['a\u05d0")
        nt.assert_in(u"d['a\u05d0']", matches)
Ejemplo n.º 13
0
def test_time3():
    """Erroneous magic function calls, issue gh-3334"""
    ip = get_ipython()
    ip.user_ns.pop('run', None)

    with tt.AssertNotPrints("not found", channel='stderr'):
        ip.run_cell("%%time\n" "run = 0\n" "run += 1")
Ejemplo n.º 14
0
def test_object_key_completion():
    ip = get_ipython()
    ip.user_ns['key_completable'] = KeyCompletable(['qwerty', 'qwick'])

    _, matches = ip.Completer.complete(line_buffer="key_completable['qw")
    nt.assert_in('qwerty', matches)
    nt.assert_in('qwick', matches)
Ejemplo n.º 15
0
def test_jedi():
    """
    A couple of issue we had with Jedi
    """
    ip = get_ipython()

    def _test_complete(reason, s, comp, start=None, end=None):
        l = len(s)
        start = start if start is not None else l
        end = end if end is not None else l
        with provisionalcompleter():
            completions = set(ip.Completer.completions(s, l))
            assert_in(Completion(start, end, comp), completions, reason)

    def _test_not_complete(reason, s, comp):
        l = len(s)
        with provisionalcompleter():
            completions = set(ip.Completer.completions(s, l))
            assert_not_in(Completion(l, l, comp), completions, reason)

    import jedi
    jedi_version = tuple(int(i) for i in jedi.__version__.split('.')[:3])
    if jedi_version > (0, 10):
        yield _test_complete, 'jedi >0.9 should complete and not crash', 'a=1;a.', 'real'
    yield _test_complete, 'can infer first argument', 'a=(1,"foo");a[0].', 'real'
    yield _test_complete, 'can infer second argument', 'a=(1,"foo");a[1].', 'capitalize'
    yield _test_complete, 'cover duplicate completions', 'im', 'import', 0, 2

    yield _test_not_complete, 'does not mix types', 'a=(1,"foo");a[0].', 'capitalize'
Ejemplo n.º 16
0
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)
Ejemplo n.º 17
0
def test_greedy_completions():
    """
    Test the capability of the Greedy completer. 

    Most of the test here do not really show off the greedy completer, for proof
    each of the text bellow now pass with Jedi. The greedy completer is capable of more. 

    See the :any:`test_dict_key_completion_contexts`

    """
    ip = get_ipython()
    ip.ex('a=list(range(5))')
    _,c = ip.complete('.',line='a[0].')
    nt.assert_false('.real' in c,
                    "Shouldn't have completed on a[0]: %s"%c)
    with greedy_completion(), provisionalcompleter():
        def _(line, cursor_pos, expect, message, completion):
            _,c = ip.complete('.', line=line, cursor_pos=cursor_pos)
            with provisionalcompleter():
                completions = ip.Completer.completions(line, cursor_pos)
            nt.assert_in(expect, c, message%c)
            nt.assert_in(completion, completions)

        yield _, 'a[0].', 5, 'a[0].real', "Should have completed on a[0].: %s", Completion(5,5, 'real')
        yield _, 'a[0].r', 6, 'a[0].real', "Should have completed on a[0].r: %s", Completion(5,6, 'real')

        if sys.version_info > (3, 4):
            yield _, 'a[0].from_', 10, 'a[0].from_bytes', "Should have completed on a[0].from_: %s", Completion(5, 10, 'from_bytes')
Ejemplo n.º 18
0
def test_greedy_completions():
    """
    Test the capability of the Greedy completer. 

    Most of the test here do not really show off the greedy completer, for proof
    each of the text bellow now pass with Jedi. The greedy completer is capable of more. 

    See the :any:`test_dict_key_completion_contexts`

    """
    ip = get_ipython()
    ip.ex('a=list(range(5))')
    _, c = ip.complete('.', line='a[0].')
    nt.assert_false('.real' in c, "Shouldn't have completed on a[0]: %s" % c)
    with greedy_completion(), provisionalcompleter():

        def _(line, cursor_pos, expect, message, completion):
            _, c = ip.complete('.', line=line, cursor_pos=cursor_pos)
            with provisionalcompleter():
                completions = ip.Completer.completions(line, cursor_pos)
            nt.assert_in(expect, c, message % c)
            nt.assert_in(completion, completions)

        yield _, 'a[0].', 5, 'a[0].real', "Should have completed on a[0].: %s", Completion(
            5, 5, 'real')
        yield _, 'a[0].r', 6, 'a[0].real', "Should have completed on a[0].r: %s", Completion(
            5, 6, 'real')

        if sys.version_info > (3, 4):
            yield _, 'a[0].from_', 10, 'a[0].from_bytes', "Should have completed on a[0].from_: %s", Completion(
                5, 10, 'from_bytes')
Ejemplo n.º 19
0
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)
Ejemplo n.º 20
0
def test_quoted_file_completions():
    ip = get_ipython()
    with TemporaryWorkingDirectory():
        name = "foo'bar"
        open(name, 'w').close()

        # Don't escape Windows
        escaped = name if sys.platform == "win32" else "foo\\'bar"

        # Single quote matches embedded single quote
        text = "open('foo"
        c = ip.Completer._complete(cursor_line=0,
                                   cursor_pos=len(text),
                                   full_text=text)[1]
        nt.assert_equal(c, [escaped])

        # Double quote requires no escape
        text = 'open("foo'
        c = ip.Completer._complete(cursor_line=0,
                                   cursor_pos=len(text),
                                   full_text=text)[1]
        nt.assert_equal(c, [name])

        # No quote requires an escape
        text = '%ls foo'
        c = ip.Completer._complete(cursor_line=0,
                                   cursor_pos=len(text),
                                   full_text=text)[1]
        nt.assert_equal(c, [escaped])
Ejemplo n.º 21
0
def test_jedi():
    """
    A couple of issue we had with Jedi
    """
    ip = get_ipython()

    def _test_complete(reason, s, comp, start=None, end=None):
        l = len(s)
        start = start if start is not None else l
        end = end if end is not None else l
        with provisionalcompleter():
            completions = set(ip.Completer.completions(s, l))
            assert_in(Completion(start, end, comp), completions, reason)

    def _test_not_complete(reason, s, comp):
        l = len(s)
        with provisionalcompleter():
            completions = set(ip.Completer.completions(s, l))
            assert_not_in(Completion(l, l, comp), completions, reason)

    import jedi
    jedi_version = tuple(int(i) for i in jedi.__version__.split('.')[:3])
    if jedi_version > (0, 10):
        yield _test_complete, 'jedi >0.9 should complete and not crash', 'a=1;a.', 'real'
    yield _test_complete, 'can infer first argument', 'a=(1,"foo");a[0].', 'real'
    yield _test_complete, 'can infer second argument', 'a=(1,"foo");a[1].', 'capitalize'
    yield _test_complete, 'cover duplicate completions', 'im', 'import', 0, 2

    yield _test_not_complete, 'does not mix types', 'a=(1,"foo");a[0].', 'capitalize'
Ejemplo n.º 22
0
def test_snake_case_completion():
    ip = get_ipython()
    ip.user_ns['some_three'] = 3
    ip.user_ns['some_four'] = 4
    _, matches = ip.complete("s_", "print(s_f")
    nt.assert_in('some_three', matches)
    nt.assert_in('some_four', matches)
Ejemplo n.º 23
0
def test_pass_correct_include_exclude():
    class Tester(object):
        def __init__(self, include=None, exclude=None):
            self.include = include
            self.exclude = exclude

        def _repr_mimebundle_(self, include, exclude, **kwargs):
            if include and (include != self.include):
                raise ValueError(
                    'include got modified: display() may be broken.')
            if exclude and (exclude != self.exclude):
                raise ValueError(
                    'exclude got modified: display() may be broken.')

            return None

    include = {'a', 'b', 'c'}
    exclude = {'c', 'e', 'f'}

    f = get_ipython().display_formatter
    f.format(Tester(include=include, exclude=exclude),
             include=include,
             exclude=exclude)
    f.format(Tester(exclude=exclude), exclude=exclude)
    f.format(Tester(include=include), include=include)
Ejemplo n.º 24
0
def test_repr_mime():
    class HasReprMime(object):
        def _repr_mimebundle_(self, include=None, exclude=None):
            return {
                'application/json+test.v2': {
                    'x': 'y'
                },
                'plain/text' : '<HasReprMime>',
                'image/png' : 'i-overwrite'
            }

        def _repr_png_(self):
            return 'should-be-overwritten'
        def _repr_html_(self):
            return '<b>hi!</b>'
    
    f = get_ipython().display_formatter
    html_f = f.formatters['text/html']
    save_enabled = html_f.enabled
    html_f.enabled = True
    obj = HasReprMime()
    d, md = f.format(obj)
    html_f.enabled = save_enabled
    
    nt.assert_equal(sorted(d), ['application/json+test.v2',
                                'image/png',
                                'plain/text',
                                'text/html',
                                'text/plain'])
    nt.assert_equal(md, {})

    d, md = f.format(obj, include={'image/png'})
    nt.assert_equal(list(d.keys()), ['image/png'],
                    'Include should filter out even things from repr_mimebundle')
    nt.assert_equal(d['image/png'], 'i-overwrite', '_repr_mimebundle_ take precedence')
Ejemplo n.º 25
0
def test_magic_completion_order():
    ip = get_ipython()
    c = ip.Completer

    # Test ordering of line and cell magics.
    text, matches = c.complete("timeit")
    nt.assert_equal(matches, ["%timeit", "%%timeit"])
Ejemplo n.º 26
0
def test_magic_completion_order():
    ip = get_ipython()
    c = ip.Completer

    # Test ordering of line and cell magics.
    text, matches = c.complete("timeit")
    nt.assert_equal(matches, ["%timeit", "%%timeit"])
Ejemplo n.º 27
0
def test_object_key_completion():
    ip = get_ipython()
    ip.user_ns['key_completable'] = KeyCompletable(['qwerty', 'qwick'])

    _, matches = ip.Completer.complete(line_buffer="key_completable['qw")
    nt.assert_in('qwerty', matches)
    nt.assert_in('qwick', matches)
Ejemplo n.º 28
0
def test_dict_key_completion_unicode_py3():
    """Test handling of unicode in dict key completion"""
    ip = get_ipython()
    complete = ip.Completer.complete

    ip.user_ns['d'] = {u'a\u05d0': None}

    # query using escape
    if sys.platform != 'win32':
        # Known failure on Windows
        _, matches = complete(line_buffer="d['a\\u05d0")
        nt.assert_in("u05d0", matches)  # tokenized after \\

    # query using character
    _, matches = complete(line_buffer="d['a\u05d0")
    nt.assert_in(u"a\u05d0", matches)

    with greedy_completion():
        # query using escape
        _, matches = complete(line_buffer="d['a\\u05d0")
        nt.assert_in("d['a\\u05d0']", matches)  # tokenized after \\

        # query using character
        _, matches = complete(line_buffer="d['a\u05d0")
        nt.assert_in(u"d['a\u05d0']", matches)
Ejemplo n.º 29
0
def test_dict_key_completion_bytes():
    """Test handling of bytes in dict key completion"""
    ip = get_ipython()
    complete = ip.Completer.complete

    ip.user_ns['d'] = {'abc': None, b'abd': None}

    _, matches = complete(line_buffer="d[")
    nt.assert_in("'abc'", matches)
    nt.assert_in("b'abd'", matches)

    if False:  # not currently implemented
        _, matches = complete(line_buffer="d[b")
        nt.assert_in("b'abd'", matches)
        nt.assert_not_in("b'abc'", matches)

        _, matches = complete(line_buffer="d[b'")
        nt.assert_in("abd", matches)
        nt.assert_not_in("abc", matches)

        _, matches = complete(line_buffer="d[B'")
        nt.assert_in("abd", matches)
        nt.assert_not_in("abc", matches)

        _, matches = complete(line_buffer="d['")
        nt.assert_in("abc", matches)
        nt.assert_not_in("abd", matches)
Ejemplo n.º 30
0
def test_magic_config():
    ip = get_ipython()
    c = ip.Completer

    s, matches = c.complete(None, 'conf')
    nt.assert_in('%config', matches)
    s, matches = c.complete(None, 'conf')
    nt.assert_not_in('AliasManager', matches)
    s, matches = c.complete(None, 'config ')
    nt.assert_in('AliasManager', matches)
    s, matches = c.complete(None, '%config ')
    nt.assert_in('AliasManager', matches)
    s, matches = c.complete(None, 'config Ali')
    nt.assert_list_equal(['AliasManager'], matches)
    s, matches = c.complete(None, '%config Ali')
    nt.assert_list_equal(['AliasManager'], matches)
    s, matches = c.complete(None, 'config AliasManager')
    nt.assert_list_equal(['AliasManager'], matches)
    s, matches = c.complete(None, '%config AliasManager')
    nt.assert_list_equal(['AliasManager'], matches)
    s, matches = c.complete(None, 'config AliasManager.')
    nt.assert_in('AliasManager.default_aliases', matches)
    s, matches = c.complete(None, '%config AliasManager.')
    nt.assert_in('AliasManager.default_aliases', matches)
    s, matches = c.complete(None, 'config AliasManager.de')
    nt.assert_list_equal(['AliasManager.default_aliases'], matches)
    s, matches = c.complete(None, 'config AliasManager.de')
    nt.assert_list_equal(['AliasManager.default_aliases'], matches)
Ejemplo n.º 31
0
def test_ipython_display_formatter():
    """Objects with _ipython_display_ defined bypass other formatters"""
    f = get_ipython().display_formatter
    catcher = []
    class SelfDisplaying(object):
        def _ipython_display_(self):
            catcher.append(self)

    class NotSelfDisplaying(object):
        def __repr__(self):
            return "NotSelfDisplaying"
        
        def _ipython_display_(self):
            raise NotImplementedError
    
    save_enabled = f.ipython_display_formatter.enabled
    f.ipython_display_formatter.enabled = True
    
    yes = SelfDisplaying()
    no = NotSelfDisplaying()
    
    d, md = f.format(no)
    nt.assert_equal(d, {'text/plain': repr(no)})
    nt.assert_equal(md, {})
    nt.assert_equal(catcher, [])
    
    d, md = f.format(yes)
    nt.assert_equal(d, {})
    nt.assert_equal(md, {})
    nt.assert_equal(catcher, [yes])

    f.ipython_display_formatter.enabled = save_enabled
Ejemplo n.º 32
0
    def _init(self):
        """Common initialization for all BackgroundJob objects"""

        for attr in ['call', 'strform']:
            assert hasattr(self, attr), "Missing attribute <%s>" % attr

        # The num tag can be set by an external job manager
        self.num = None

        self.status = BackgroundJobBase.stat_created
        self.stat_code = BackgroundJobBase.stat_created_c
        self.finished = False
        self.result = '<BackgroundJob has not completed>'

        # reuse the ipython traceback handler if we can get to it, otherwise
        # make a new one
        try:
            make_tb = get_ipython().InteractiveTB.text
        except:
            make_tb = AutoFormattedTB(mode='Context',
                                      color_scheme='NoColor',
                                      tb_offset=1).text
        # Note that the actual API for text() requires the three args to be
        # passed in, so we wrap it in a simple lambda.
        self._make_tb = lambda: make_tb(None, None, None)

        # Hold a formatted traceback if one is generated.
        self._tb = None

        threading.Thread.__init__(self)
Ejemplo n.º 33
0
def greedy_completion():
    ip = get_ipython()
    greedy_original = ip.Completer.greedy
    try:
        ip.Completer.greedy = True
        yield
    finally:
        ip.Completer.greedy = greedy_original
Ejemplo n.º 34
0
def test_magic_parse_long_options():
    """Magic.parse_options can handle --foo=bar long options"""
    ip = get_ipython()
    m = DummyMagics(ip)
    opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
    nt.assert_in('foo', opts)
    nt.assert_in('bar', opts)
    nt.assert_equal(opts['bar'], "bubble")
Ejemplo n.º 35
0
def test_edit_cell():
    """%edit [cell id]"""
    ip = get_ipython()

    ip.run_cell(u"def foo(): return 1", store_history=True)

    # test
    _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
Ejemplo n.º 36
0
def greedy_completion():
    ip = get_ipython()
    greedy_original = ip.Completer.greedy
    try:
        ip.Completer.greedy = True
        yield
    finally:
        ip.Completer.greedy = greedy_original
Ejemplo n.º 37
0
def test_magic_parse_long_options():
    """Magic.parse_options can handle --foo=bar long options"""
    ip = get_ipython()
    m = DummyMagics(ip)
    opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
    nt.assert_in('foo', opts)
    nt.assert_in('bar', opts)
    nt.assert_equal(opts['bar'], "bubble")
Ejemplo n.º 38
0
def test_edit_cell():
    """%edit [cell id]"""
    ip = get_ipython()
    
    ip.run_cell(u"def foo(): return 1", store_history=True)
    
    # test
    _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
Ejemplo n.º 39
0
def test_class_key_completion():
    ip = get_ipython()
    NamedInstanceClass('qwerty')
    NamedInstanceClass('qwick')
    ip.user_ns['named_instance_class'] = NamedInstanceClass

    _, matches = ip.Completer.complete(line_buffer="named_instance_class['qw")
    nt.assert_in('qwerty', matches)
    nt.assert_in('qwick', matches)
Ejemplo n.º 40
0
def test_dataframe_key_completion():
    """Test dict key completion applies to pandas DataFrames"""
    import pandas
    ip = get_ipython()
    complete = ip.Completer.complete
    ip.user_ns['d'] = pandas.DataFrame({'hello': [1], 'world': [2]})
    _, matches = complete(line_buffer="d['")
    nt.assert_in("hello", matches)
    nt.assert_in("world", matches)
Ejemplo n.º 41
0
def test_dataframe_key_completion():
    """Test dict key completion applies to pandas DataFrames"""
    import pandas
    ip = get_ipython()
    complete = ip.Completer.complete
    ip.user_ns['d'] = pandas.DataFrame({'hello': [1], 'world': [2]})
    _, matches = complete(line_buffer="d['")
    nt.assert_in("hello", matches)
    nt.assert_in("world", matches)
Ejemplo n.º 42
0
def test_hist_pof():
    ip = get_ipython()
    ip.run_cell(u"1+2", store_history=True)
    #raise Exception(ip.history_manager.session_number)
    #raise Exception(list(ip.history_manager._get_range_session()))
    with TemporaryDirectory() as td:
        tf = os.path.join(td, 'hist.py')
        ip.run_line_magic('history', '-pof %s' % tf)
        assert os.path.isfile(tf)
Ejemplo n.º 43
0
def test_notebook_export_json():
    _ip = get_ipython()
    _ip.history_manager.reset()  # Clear any existing history.
    cmds = [u"a=1", u"def b():\n  return a**2", u"print('noël, été', b())"]
    for i, cmd in enumerate(cmds, start=1):
        _ip.history_manager.store_inputs(i, cmd)
    with TemporaryDirectory() as td:
        outfile = os.path.join(td, "nb.ipynb")
        _ip.magic("notebook -e %s" % outfile)
Ejemplo n.º 44
0
def test_script_defaults():
    ip = get_ipython()
    for cmd in ['sh', 'bash', 'perl', 'ruby']:
        try:
            find_cmd(cmd)
        except Exception:
            pass
        else:
            nt.assert_in(cmd, ip.magics_manager.magics['cell'])
Ejemplo n.º 45
0
def test_multiple_magics():
    ip = get_ipython()
    foo1 = FooFoo(ip)
    foo2 = FooFoo(ip)
    mm = ip.magics_manager
    mm.register(foo1)
    nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
    mm.register(foo2)
    nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
Ejemplo n.º 46
0
def test_ls_magic():
    ip = get_ipython()
    json_formatter = ip.display_formatter.formatters['application/json']
    json_formatter.enabled = True
    lsmagic = ip.magic('lsmagic')
    with warnings.catch_warnings(record=True) as w:
        j = json_formatter(lsmagic)
    nt.assert_equal(sorted(j), ['cell', 'line'])
    nt.assert_equal(w, []) # no warnings
Ejemplo n.º 47
0
def test_class_key_completion():
    ip = get_ipython()
    NamedInstanceClass('qwerty')
    NamedInstanceClass('qwick')
    ip.user_ns['named_instance_class'] = NamedInstanceClass

    _, matches = ip.Completer.complete(line_buffer="named_instance_class['qw")
    nt.assert_in('qwerty', matches)
    nt.assert_in('qwick', matches)
Ejemplo n.º 48
0
def test_repr_mime_failure():
    class BadReprMime(object):
        def _repr_mimebundle_(self, include=None, exclude=None):
            raise RuntimeError

    f = get_ipython().display_formatter
    obj = BadReprMime()
    d, md = f.format(obj)
    nt.assert_in('text/plain', d)
Ejemplo n.º 49
0
def test_ls_magic():
    ip = get_ipython()
    json_formatter = ip.display_formatter.formatters['application/json']
    json_formatter.enabled = True
    lsmagic = ip.magic('lsmagic')
    with warnings.catch_warnings(record=True) as w:
        j = json_formatter(lsmagic)
    nt.assert_equal(sorted(j), ['cell', 'line'])
    nt.assert_equal(w, [])  # no warnings
Ejemplo n.º 50
0
def test_multiple_magics():
    ip = get_ipython()
    foo1 = FooFoo(ip)
    foo2 = FooFoo(ip)
    mm = ip.magics_manager
    mm.register(foo1)
    nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
    mm.register(foo2)
    nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
Ejemplo n.º 51
0
def test_repr_mime_failure():
    class BadReprMime(object):
        def _repr_mimebundle_(self, include=None, exclude=None):
            raise RuntimeError

    f = get_ipython().display_formatter
    obj = BadReprMime()
    d, md = f.format(obj)
    nt.assert_in('text/plain', d)
Ejemplo n.º 52
0
def test_notebook_export_json():
    _ip = get_ipython()
    _ip.history_manager.reset()   # Clear any existing history.
    cmds = [u"a=1", u"def b():\n  return a**2", u"print('noël, été', b())"]
    for i, cmd in enumerate(cmds, start=1):
        _ip.history_manager.store_inputs(i, cmd)
    with TemporaryDirectory() as td:
        outfile = os.path.join(td, "nb.ipynb")
        _ip.magic("notebook -e %s" % outfile)
Ejemplo n.º 53
0
def test_script_defaults():
    ip = get_ipython()
    for cmd in ['sh', 'bash', 'perl', 'ruby']:
        try:
            find_cmd(cmd)
        except Exception:
            pass
        else:
            nt.assert_in(cmd, ip.magics_manager.magics['cell'])
Ejemplo n.º 54
0
def test_time3():
    """Erroneous magic function calls, issue gh-3334"""
    ip = get_ipython()
    ip.user_ns.pop('run', None)
    
    with tt.AssertNotPrints("not found", channel='stderr'):
        ip.run_cell("%%time\n"
                    "run = 0\n"
                    "run += 1")
Ejemplo n.º 55
0
def test_hist_pof():
    ip = get_ipython()
    ip.run_cell(u"1+2", store_history=True)
    #raise Exception(ip.history_manager.session_number)
    #raise Exception(list(ip.history_manager._get_range_session()))
    with TemporaryDirectory() as td:
        tf = os.path.join(td, 'hist.py')
        ip.run_line_magic('history', '-pof %s' % tf)
        assert os.path.isfile(tf)
Ejemplo n.º 56
0
def test_omit__names():
    # also happens to test IPCompleter as a configurable
    ip = get_ipython()
    ip._hidden_attr = 1
    ip._x = {}
    c = ip.Completer
    ip.ex('ip=get_ipython()')
    cfg = Config()
    cfg.IPCompleter.omit__names = 0
    c.update_config(cfg)
    with provisionalcompleter():
        s,matches = c.complete('ip.')
        completions = set(c.completions('ip.', 3))

        nt.assert_in('ip.__str__', matches)
        nt.assert_in(Completion(3, 3, '__str__'), completions)
        
        nt.assert_in('ip._hidden_attr', matches)
        nt.assert_in(Completion(3,3, "_hidden_attr"), completions)


    cfg = Config()
    cfg.IPCompleter.omit__names = 1
    c.update_config(cfg)
    with provisionalcompleter():
        s,matches = c.complete('ip.')
        completions = set(c.completions('ip.', 3))

        nt.assert_not_in('ip.__str__', matches)
        nt.assert_not_in(Completion(3,3,'__str__'), completions)

        # nt.assert_in('ip._hidden_attr', matches)
        nt.assert_in(Completion(3,3, "_hidden_attr"), completions)

    cfg = Config()
    cfg.IPCompleter.omit__names = 2
    c.update_config(cfg)
    with provisionalcompleter():
        s,matches = c.complete('ip.')
        completions = set(c.completions('ip.', 3))

        nt.assert_not_in('ip.__str__', matches)
        nt.assert_not_in(Completion(3,3,'__str__'), completions)

        nt.assert_not_in('ip._hidden_attr', matches)
        nt.assert_not_in(Completion(3,3, "_hidden_attr"), completions)

    with provisionalcompleter():
        s,matches = c.complete('ip._x.')
        completions = set(c.completions('ip._x.', 6))

        nt.assert_in('ip._x.keys', matches)
        nt.assert_in(Completion(6,6, "keys"), completions)

    del ip._hidden_attr
    del ip._x
Ejemplo n.º 57
0
def test_completion_have_signature():
    """
    Lets make sure jedi is capable of pulling out the signature of the function we are completing.
    """
    ip = get_ipython()
    with provisionalcompleter():
        completions = ip.Completer.completions('ope', 3)
        c = next(completions)  # should be `open`
    assert 'file' in c.signature, "Signature of function was not found by completer"
    assert 'encoding' in c.signature, "Signature of function was not found by completer"
Ejemplo n.º 58
0
def test_completion_have_signature():
    """
    Lets make sure jedi is capable of pulling out the signature of the function we are completing.
    """
    ip = get_ipython()
    with provisionalcompleter():
        completions = ip.Completer.completions('ope', 3)
        c = next(completions)  # should be `open`
    assert 'file' in c.signature, "Signature of function was not found by completer"
    assert 'encoding' in c.signature, "Signature of function was not found by completer"
Ejemplo n.º 59
0
def test_magic_magic():
    """Test %magic"""
    ip = get_ipython()
    with capture_output() as captured:
        ip.magic("magic")
    
    stdout = captured.stdout
    nt.assert_in('%magic', stdout)
    nt.assert_in('yap_ipython', stdout)
    nt.assert_in('Available', stdout)
Ejemplo n.º 60
0
def test_macro():
    ip = get_ipython()
    ip.history_manager.reset()   # Clear any existing history.
    cmds = ["a=1", "def b():\n  return a**2", "print(a,b())"]
    for i, cmd in enumerate(cmds, start=1):
        ip.history_manager.store_inputs(i, cmd)
    ip.magic("macro test 1-3")
    nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
    
    # List macros
    nt.assert_in("test", ip.magic("macro"))