| 1 |
# -*- coding: utf-8 -*- |
| 2 |
"""Tests for the TerminalInteractiveShell and related pieces.""" |
| 3 |
# Copyright (c) IPython Development Team. |
| 4 |
# Distributed under the terms of the Modified BSD License. |
| 5 |
|
| 6 |
import sys |
| 7 |
import unittest |
| 8 |
import os |
| 9 |
|
| 10 |
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory |
| 11 |
|
| 12 |
|
| 13 |
from IPython.testing import tools as tt |
| 14 |
|
| 15 |
from IPython.terminal.ptutils import _elide, _adjust_completion_text_based_on_context |
| 16 |
from IPython.terminal.shortcuts.auto_suggest import NavigableAutoSuggestFromHistory |
| 17 |
|
| 18 |
|
| 19 |
class TestAutoSuggest(unittest.TestCase): |
| 20 |
def test_changing_provider(self): |
| 21 |
ip = get_ipython() |
| 22 |
ip.autosuggestions_provider = None |
| 23 |
self.assertEqual(ip.auto_suggest, None) |
| 24 |
ip.autosuggestions_provider = "AutoSuggestFromHistory" |
| 25 |
self.assertIsInstance(ip.auto_suggest, AutoSuggestFromHistory) |
| 26 |
ip.autosuggestions_provider = "NavigableAutoSuggestFromHistory" |
| 27 |
self.assertIsInstance(ip.auto_suggest, NavigableAutoSuggestFromHistory) |
| 28 |
|
| 29 |
|
| 30 |
def test_elide(): |
| 31 |
_elide("concatenate((a1, a2, ...), axis", "", min_elide=30) # do not raise |
| 32 |
_elide("concatenate((a1, a2, ..), . axis", "", min_elide=30) # do not raise |
| 33 |
assert ( |
| 34 |
_elide("aaaa.bbbb.ccccc.dddddd.eeeee.fffff.gggggg.hhhhhh", "", min_elide=30) |
| 35 |
== "aaaa.b…g.hhhhhh" |
| 36 |
) |
| 37 |
|
| 38 |
test_string = os.sep.join(["", 10 * "a", 10 * "b", 10 * "c", ""]) |
| 39 |
expect_string = os.sep + "a" + "\N{HORIZONTAL ELLIPSIS}" + "b" + os.sep + 10 * "c" |
| 40 |
assert _elide(test_string, "", min_elide=30) == expect_string |
| 41 |
|
| 42 |
|
| 43 |
def test_elide_typed_normal(): |
| 44 |
assert ( |
| 45 |
_elide( |
| 46 |
"the quick brown fox jumped over the lazy dog", |
| 47 |
"the quick brown fox", |
| 48 |
min_elide=10, |
| 49 |
) |
| 50 |
== "the…fox jumped over the lazy dog" |
| 51 |
) |
| 52 |
|
| 53 |
|
| 54 |
def test_elide_typed_short_match(): |
| 55 |
""" |
| 56 |
if the match is too short we don't elide. |
| 57 |
avoid the "the...the" |
| 58 |
""" |
| 59 |
assert ( |
| 60 |
_elide("the quick brown fox jumped over the lazy dog", "the", min_elide=10) |
| 61 |
== "the quick brown fox jumped over the lazy dog" |
| 62 |
) |
| 63 |
|
| 64 |
|
| 65 |
def test_elide_typed_no_match(): |
| 66 |
""" |
| 67 |
if the match is too short we don't elide. |
| 68 |
avoid the "the...the" |
| 69 |
""" |
| 70 |
# here we typed red instead of brown |
| 71 |
assert ( |
| 72 |
_elide( |
| 73 |
"the quick brown fox jumped over the lazy dog", |
| 74 |
"the quick red fox", |
| 75 |
min_elide=10, |
| 76 |
) |
| 77 |
== "the quick brown fox jumped over the lazy dog" |
| 78 |
) |
| 79 |
|
| 80 |
|
| 81 |
class TestContextAwareCompletion(unittest.TestCase): |
| 82 |
def test_adjust_completion_text_based_on_context(self): |
| 83 |
# Adjusted case |
| 84 |
self.assertEqual( |
| 85 |
_adjust_completion_text_based_on_context("arg1=", "func1(a=)", 7), "arg1" |
| 86 |
) |
| 87 |
|
| 88 |
# Untouched cases |
| 89 |
self.assertEqual( |
| 90 |
_adjust_completion_text_based_on_context("arg1=", "func1(a)", 7), "arg1=" |
| 91 |
) |
| 92 |
self.assertEqual( |
| 93 |
_adjust_completion_text_based_on_context("arg1=", "func1(a", 7), "arg1=" |
| 94 |
) |
| 95 |
self.assertEqual( |
| 96 |
_adjust_completion_text_based_on_context("%magic", "func1(a=)", 7), "%magic" |
| 97 |
) |
| 98 |
self.assertEqual( |
| 99 |
_adjust_completion_text_based_on_context("func2", "func1(a=)", 7), "func2" |
| 100 |
) |
| 101 |
|
| 102 |
|
| 103 |
# Decorator for interaction loop tests ----------------------------------------- |
| 104 |
|
| 105 |
|
| 106 |
class mock_input_helper(object): |
| 107 |
"""Machinery for tests of the main interact loop. |
| 108 |
|
| 109 |
Used by the mock_input decorator. |
| 110 |
""" |
| 111 |
|
| 112 |
def __init__(self, testgen): |
| 113 |
self.testgen = testgen |
| 114 |
self.exception = None |
| 115 |
self.ip = get_ipython() |
| 116 |
|
| 117 |
def __enter__(self): |
| 118 |
self.orig_prompt_for_code = self.ip.prompt_for_code |
| 119 |
self.ip.prompt_for_code = self.fake_input |
| 120 |
return self |
| 121 |
|
| 122 |
def __exit__(self, etype, value, tb): |
| 123 |
self.ip.prompt_for_code = self.orig_prompt_for_code |
| 124 |
|
| 125 |
def fake_input(self): |
| 126 |
try: |
| 127 |
return next(self.testgen) |
| 128 |
except StopIteration: |
| 129 |
self.ip.keep_running = False |
| 130 |
return "" |
| 131 |
except: |
| 132 |
self.exception = sys.exc_info() |
| 133 |
self.ip.keep_running = False |
| 134 |
return "" |
| 135 |
|
| 136 |
|
| 137 |
def mock_input(testfunc): |
| 138 |
"""Decorator for tests of the main interact loop. |
| 139 |
|
| 140 |
Write the test as a generator, yield-ing the input strings, which IPython |
| 141 |
will see as if they were typed in at the prompt. |
| 142 |
""" |
| 143 |
|
| 144 |
def test_method(self): |
| 145 |
testgen = testfunc(self) |
| 146 |
with mock_input_helper(testgen) as mih: |
| 147 |
mih.ip.interact() |
| 148 |
|
| 149 |
if mih.exception is not None: |
| 150 |
# Re-raise captured exception |
| 151 |
etype, value, tb = mih.exception |
| 152 |
import traceback |
| 153 |
|
| 154 |
traceback.print_tb(tb, file=sys.stdout) |
| 155 |
del tb # Avoid reference loop |
| 156 |
raise value |
| 157 |
|
| 158 |
return test_method |
| 159 |
|
| 160 |
|
| 161 |
# Test classes ----------------------------------------------------------------- |
| 162 |
|
| 163 |
|
| 164 |
class InteractiveShellTestCase(unittest.TestCase): |
| 165 |
def rl_hist_entries(self, rl, n): |
| 166 |
"""Get last n readline history entries as a list""" |
| 167 |
return [ |
| 168 |
rl.get_history_item(rl.get_current_history_length() - x) |
| 169 |
for x in range(n - 1, -1, -1) |
| 170 |
] |
| 171 |
|
| 172 |
@mock_input |
| 173 |
def test_inputtransformer_syntaxerror(self): |
| 174 |
ip = get_ipython() |
| 175 |
ip.input_transformers_post.append(syntax_error_transformer) |
| 176 |
|
| 177 |
try: |
| 178 |
# raise Exception |
| 179 |
with tt.AssertPrints("4", suppress=False): |
| 180 |
yield "print(2*2)" |
| 181 |
|
| 182 |
with tt.AssertPrints("SyntaxError: input contains", suppress=False): |
| 183 |
yield "print(2345) # syntaxerror" |
| 184 |
|
| 185 |
with tt.AssertPrints("16", suppress=False): |
| 186 |
yield "print(4*4)" |
| 187 |
|
| 188 |
finally: |
| 189 |
ip.input_transformers_post.remove(syntax_error_transformer) |
| 190 |
|
| 191 |
def test_repl_not_plain_text(self): |
| 192 |
ip = get_ipython() |
| 193 |
formatter = ip.display_formatter |
| 194 |
assert formatter.active_types == ["text/plain"] |
| 195 |
|
| 196 |
# terminal may have arbitrary mimetype handler to open external viewer |
| 197 |
# or inline images. |
| 198 |
assert formatter.ipython_display_formatter.enabled |
| 199 |
|
| 200 |
class Test(object): |
| 201 |
def __repr__(self): |
| 202 |
return "<Test %i>" % id(self) |
| 203 |
|
| 204 |
def _repr_html_(self): |
| 205 |
return "<html>" |
| 206 |
|
| 207 |
# verify that HTML repr isn't computed |
| 208 |
obj = Test() |
| 209 |
data, _ = formatter.format(obj) |
| 210 |
self.assertEqual(data, {"text/plain": repr(obj)}) |
| 211 |
|
| 212 |
class Test2(Test): |
| 213 |
def _ipython_display_(self): |
| 214 |
from IPython.display import display, HTML |
| 215 |
|
| 216 |
display(HTML("<custom>")) |
| 217 |
|
| 218 |
# verify that mimehandlers are called |
| 219 |
called = False |
| 220 |
|
| 221 |
def handler(data, metadata): |
| 222 |
print("Handler called") |
| 223 |
nonlocal called |
| 224 |
called = True |
| 225 |
|
| 226 |
ip.display_formatter.active_types.append("text/html") |
| 227 |
ip.display_formatter.formatters["text/html"].enabled = True |
| 228 |
ip.mime_renderers["text/html"] = handler |
| 229 |
try: |
| 230 |
obj = Test() |
| 231 |
display(obj) |
| 232 |
finally: |
| 233 |
ip.display_formatter.formatters["text/html"].enabled = False |
| 234 |
del ip.mime_renderers["text/html"] |
| 235 |
|
| 236 |
assert called == True |
| 237 |
|
| 238 |
|
| 239 |
def syntax_error_transformer(lines): |
| 240 |
"""Transformer that throws SyntaxError if 'syntaxerror' is in the code.""" |
| 241 |
for line in lines: |
| 242 |
pos = line.find("syntaxerror") |
| 243 |
if pos >= 0: |
| 244 |
e = SyntaxError('input contains "syntaxerror"') |
| 245 |
e.text = line |
| 246 |
e.offset = pos + 1 |
| 247 |
raise e |
| 248 |
return lines |
| 249 |
|
| 250 |
|
| 251 |
class TerminalMagicsTestCase(unittest.TestCase): |
| 252 |
def test_paste_magics_blankline(self): |
| 253 |
"""Test that code with a blank line doesn't get split (gh-3246).""" |
| 254 |
ip = get_ipython() |
| 255 |
s = "def pasted_func(a):\n" " b = a+1\n" "\n" " return b" |
| 256 |
|
| 257 |
tm = ip.magics_manager.registry["TerminalMagics"] |
| 258 |
tm.store_or_execute(s, name=None) |
| 259 |
|
| 260 |
self.assertEqual(ip.user_ns["pasted_func"](54), 55) |