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