Debian Codegraph @

tests/test_magic_terminal.py

raw
1 """Tests for various magic functions specific to the terminal frontend."""
2
3 # -----------------------------------------------------------------------------
4 # Imports
5 # -----------------------------------------------------------------------------
6
7 import sys
8 from io import StringIO
9 from unittest import TestCase
10
11 from IPython.testing import tools as tt
12
13 # -----------------------------------------------------------------------------
14 # Test functions begin
15 # -----------------------------------------------------------------------------
16
17
18 MINIMAL_LAZY_MAGIC = """
19 from IPython.core.magic import (
20 Magics,
21 magics_class,
22 line_magic,
23 cell_magic,
24 )
25
26
27 @magics_class
28 class LazyMagics(Magics):
29 @line_magic
30 def lazy_line(self, line):
31 print("Lazy Line")
32
33 @cell_magic
34 def lazy_cell(self, line, cell):
35 print("Lazy Cell")
36
37
38 def load_ipython_extension(ipython):
39 ipython.register_magics(LazyMagics)
40 """
41
42
43 def check_cpaste(code, should_fail=False):
44 """Execute code via 'cpaste' and ensure it was executed, unless
45 should_fail is set.
46 """
47 ip.user_ns["code_ran"] = False
48
49 src = StringIO()
50 src.write(code)
51 src.write("\n--\n")
52 src.seek(0)
53
54 stdin_save = sys.stdin
55 sys.stdin = src
56
57 try:
58 context = tt.AssertPrints if should_fail else tt.AssertNotPrints
59 with context("Traceback (most recent call last)"):
60 ip.run_line_magic("cpaste", "")
61
62 if not should_fail:
63 assert ip.user_ns["code_ran"], "%r failed" % code
64 finally:
65 sys.stdin = stdin_save
66
67
68 def test_cpaste():
69 """Test cpaste magic"""
70
71 def runf():
72 """Marker function: sets a flag when executed."""
73 ip.user_ns["code_ran"] = True
74 return "runf" # return string so '+ runf()' doesn't result in success
75
76 tests = {
77 "pass": [
78 "runf()",
79 "In [1]: runf()",
80 "In [1]: if 1:\n ...: runf()",
81 "> > > runf()",
82 ">>> runf()",
83 " >>> runf()",
84 ],
85 "fail": [
86 "1 + runf()",
87 "++ runf()",
88 ],
89 }
90
91 ip.user_ns["runf"] = runf
92
93 for code in tests["pass"]:
94 check_cpaste(code)
95
96 for code in tests["fail"]:
97 check_cpaste(code, should_fail=True)
98
99
100 class PasteTestCase(TestCase):
101 """Multiple tests for clipboard pasting"""
102
103 def paste(self, txt, flags="-q"):
104 """Paste input text, by default in quiet mode"""
105 ip.hooks.clipboard_get = lambda: txt
106 ip.run_line_magic("paste", flags)
107
108 def setUp(self):
109 # Inject fake clipboard hook but save original so we can restore it later
110 self.original_clip = ip.hooks.clipboard_get
111
112 def tearDown(self):
113 # Restore original hook
114 ip.hooks.clipboard_get = self.original_clip
115
116 def test_paste(self):
117 ip.user_ns.pop("x", None)
118 self.paste("x = 1")
119 self.assertEqual(ip.user_ns["x"], 1)
120 ip.user_ns.pop("x")
121
122 def test_paste_pyprompt(self):
123 ip.user_ns.pop("x", None)
124 self.paste(">>> x=2")
125 self.assertEqual(ip.user_ns["x"], 2)
126 ip.user_ns.pop("x")
127
128 def test_paste_py_multi(self):
129 self.paste(
130 """
131 >>> x = [1,2,3]
132 >>> y = []
133 >>> for i in x:
134 ... y.append(i**2)
135 ...
136 """
137 )
138 self.assertEqual(ip.user_ns["x"], [1, 2, 3])
139 self.assertEqual(ip.user_ns["y"], [1, 4, 9])
140
141 def test_paste_py_multi_r(self):
142 "Now, test that self.paste -r works"
143 self.test_paste_py_multi()
144 self.assertEqual(ip.user_ns.pop("x"), [1, 2, 3])
145 self.assertEqual(ip.user_ns.pop("y"), [1, 4, 9])
146 self.assertFalse("x" in ip.user_ns)
147 ip.run_line_magic("paste", "-r")
148 self.assertEqual(ip.user_ns["x"], [1, 2, 3])
149 self.assertEqual(ip.user_ns["y"], [1, 4, 9])
150
151 def test_paste_email(self):
152 "Test pasting of email-quoted contents"
153 self.paste(
154 """\
155 >> def foo(x):
156 >> return x + 1
157 >> xx = foo(1.1)"""
158 )
159 self.assertEqual(ip.user_ns["xx"], 2.1)
160
161 def test_paste_email2(self):
162 "Email again; some programs add a space also at each quoting level"
163 self.paste(
164 """\
165 > > def foo(x):
166 > > return x + 1
167 > > yy = foo(2.1) """
168 )
169 self.assertEqual(ip.user_ns["yy"], 3.1)
170
171 def test_paste_email_py(self):
172 "Email quoting of interactive input"
173 self.paste(
174 """\
175 >> >>> def f(x):
176 >> ... return x+1
177 >> ...
178 >> >>> zz = f(2.5) """
179 )
180 self.assertEqual(ip.user_ns["zz"], 3.5)
181
182 def test_paste_echo(self):
183 "Also test self.paste echoing, by temporarily faking the writer"
184 w = StringIO()
185 old_write = sys.stdout.write
186 sys.stdout.write = w.write
187 code = """
188 a = 100
189 b = 200"""
190 try:
191 self.paste(code, "")
192 out = w.getvalue()
193 finally:
194 sys.stdout.write = old_write
195 self.assertEqual(ip.user_ns["a"], 100)
196 self.assertEqual(ip.user_ns["b"], 200)
197 assert out == code + "\n## -- End pasted text --\n"
198
199 def test_paste_leading_commas(self):
200 "Test multiline strings with leading commas"
201 tm = ip.magics_manager.registry["TerminalMagics"]
202 s = '''\
203 a = """
204 ,1,2,3
205 """'''
206 ip.user_ns.pop("foo", None)
207 tm.store_or_execute(s, "foo")
208 self.assertIn("foo", ip.user_ns)
209
210 def test_paste_trailing_question(self):
211 "Test pasting sources with trailing question marks"
212 tm = ip.magics_manager.registry["TerminalMagics"]
213 s = """\
214 def funcfoo():
215 if True: #am i true?
216 return 'fooresult'
217 """
218 ip.user_ns.pop("funcfoo", None)
219 self.paste(s)
220 self.assertEqual(ip.user_ns["funcfoo"](), "fooresult")