##// END OF EJS Templates
Tiny correction to test for interactiveshell scope.
Thomas Kluyver -
Show More
@@ -1,273 +1,273 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tests for the key interactiveshell module.
3 3
4 4 Historically the main classes in interactiveshell have been under-tested. This
5 5 module should grow as many single-method tests as possible to trap many of the
6 6 recurring bugs we seem to encounter with high-level interaction.
7 7
8 8 Authors
9 9 -------
10 10 * Fernando Perez
11 11 """
12 12 #-----------------------------------------------------------------------------
13 13 # Copyright (C) 2011 The IPython Development Team
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #-----------------------------------------------------------------------------
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Imports
21 21 #-----------------------------------------------------------------------------
22 22 # stdlib
23 23 import os
24 24 import shutil
25 25 import tempfile
26 26 import unittest
27 27 from os.path import join
28 28 import sys
29 29 from StringIO import StringIO
30 30
31 31 from IPython.testing import decorators as dec
32 32 from IPython.utils import io
33 33
34 34 #-----------------------------------------------------------------------------
35 35 # Tests
36 36 #-----------------------------------------------------------------------------
37 37
38 38 class InteractiveShellTestCase(unittest.TestCase):
39 39 def test_naked_string_cells(self):
40 40 """Test that cells with only naked strings are fully executed"""
41 41 ip = get_ipython()
42 42 # First, single-line inputs
43 43 ip.run_cell('"a"\n')
44 44 self.assertEquals(ip.user_ns['_'], 'a')
45 45 # And also multi-line cells
46 46 ip.run_cell('"""a\nb"""\n')
47 47 self.assertEquals(ip.user_ns['_'], 'a\nb')
48 48
49 49 def test_run_empty_cell(self):
50 50 """Just make sure we don't get a horrible error with a blank
51 51 cell of input. Yes, I did overlook that."""
52 52 ip = get_ipython()
53 53 old_xc = ip.execution_count
54 54 ip.run_cell('')
55 55 self.assertEquals(ip.execution_count, old_xc)
56 56
57 57 def test_run_cell_multiline(self):
58 58 """Multi-block, multi-line cells must execute correctly.
59 59 """
60 60 ip = get_ipython()
61 61 src = '\n'.join(["x=1",
62 62 "y=2",
63 63 "if 1:",
64 64 " x += 1",
65 65 " y += 1",])
66 66 ip.run_cell(src)
67 67 self.assertEquals(ip.user_ns['x'], 2)
68 68 self.assertEquals(ip.user_ns['y'], 3)
69 69
70 70 def test_multiline_string_cells(self):
71 71 "Code sprinkled with multiline strings should execute (GH-306)"
72 72 ip = get_ipython()
73 73 ip.run_cell('tmp=0')
74 74 self.assertEquals(ip.user_ns['tmp'], 0)
75 75 ip.run_cell('tmp=1;"""a\nb"""\n')
76 76 self.assertEquals(ip.user_ns['tmp'], 1)
77 77
78 78 def test_dont_cache_with_semicolon(self):
79 79 "Ending a line with semicolon should not cache the returned object (GH-307)"
80 80 ip = get_ipython()
81 81 oldlen = len(ip.user_ns['Out'])
82 82 a = ip.run_cell('1;', store_history=True)
83 83 newlen = len(ip.user_ns['Out'])
84 84 self.assertEquals(oldlen, newlen)
85 85 #also test the default caching behavior
86 86 ip.run_cell('1', store_history=True)
87 87 newlen = len(ip.user_ns['Out'])
88 88 self.assertEquals(oldlen+1, newlen)
89 89
90 90 def test_In_variable(self):
91 91 "Verify that In variable grows with user input (GH-284)"
92 92 ip = get_ipython()
93 93 oldlen = len(ip.user_ns['In'])
94 94 ip.run_cell('1;', store_history=True)
95 95 newlen = len(ip.user_ns['In'])
96 96 self.assertEquals(oldlen+1, newlen)
97 97 self.assertEquals(ip.user_ns['In'][-1],'1;')
98 98
99 99 def test_magic_names_in_string(self):
100 100 ip = get_ipython()
101 101 ip.run_cell('a = """\n%exit\n"""')
102 102 self.assertEquals(ip.user_ns['a'], '\n%exit\n')
103 103
104 104 def test_alias_crash(self):
105 105 """Errors in prefilter can't crash IPython"""
106 106 ip = get_ipython()
107 107 ip.run_cell('%alias parts echo first %s second %s')
108 108 # capture stderr:
109 109 save_err = io.stderr
110 110 io.stderr = StringIO()
111 111 ip.run_cell('parts 1')
112 112 err = io.stderr.getvalue()
113 113 io.stderr = save_err
114 114 self.assertEquals(err.split(':')[0], 'ERROR')
115 115
116 116 def test_trailing_newline(self):
117 117 """test that running !(command) does not raise a SyntaxError"""
118 118 ip = get_ipython()
119 119 ip.run_cell('!(true)\n', False)
120 120 ip.run_cell('!(true)\n\n\n', False)
121 121
122 122 def test_gh_597(self):
123 123 """Pretty-printing lists of objects with non-ascii reprs may cause
124 124 problems."""
125 125 class Spam(object):
126 126 def __repr__(self):
127 127 return "\xe9"*50
128 128 import IPython.core.formatters
129 129 f = IPython.core.formatters.PlainTextFormatter()
130 130 f([Spam(),Spam()])
131 131
132 132
133 133 def test_future_flags(self):
134 134 """Check that future flags are used for parsing code (gh-777)"""
135 135 ip = get_ipython()
136 136 ip.run_cell('from __future__ import print_function')
137 137 try:
138 138 ip.run_cell('prfunc_return_val = print(1,2, sep=" ")')
139 139 assert 'prfunc_return_val' in ip.user_ns
140 140 finally:
141 141 # Reset compiler flags so we don't mess up other tests.
142 142 ip.compile.reset_compiler_flags()
143 143
144 144 def test_future_unicode(self):
145 145 """Check that unicode_literals is imported from __future__ (gh #786)"""
146 146 ip = get_ipython()
147 147 try:
148 148 ip.run_cell(u'byte_str = "a"')
149 149 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
150 150 ip.run_cell('from __future__ import unicode_literals')
151 151 ip.run_cell(u'unicode_str = "a"')
152 152 assert isinstance(ip.user_ns['unicode_str'], unicode) # strings literals are now unicode
153 153 finally:
154 154 # Reset compiler flags so we don't mess up other tests.
155 155 ip.compile.reset_compiler_flags()
156 156
157 157 def test_can_pickle(self):
158 158 "Can we pickle objects defined interactively (GH-29)"
159 159 ip = get_ipython()
160 160 ip.reset()
161 161 ip.run_cell(("class Mylist(list):\n"
162 162 " def __init__(self,x=[]):\n"
163 163 " list.__init__(self,x)"))
164 164 ip.run_cell("w=Mylist([1,2,3])")
165 165
166 166 from cPickle import dumps
167 167
168 168 # We need to swap in our main module - this is only necessary
169 169 # inside the test framework, because IPython puts the interactive module
170 170 # in place (but the test framework undoes this).
171 171 _main = sys.modules['__main__']
172 172 sys.modules['__main__'] = ip.user_module
173 173 try:
174 174 res = dumps(ip.user_ns["w"])
175 175 finally:
176 176 sys.modules['__main__'] = _main
177 177 self.assertTrue(isinstance(res, bytes))
178 178
179 179 def test_global_ns(self):
180 180 "Code in functions must be able to access variables outside them."
181 181 ip = get_ipython()
182 182 ip.run_cell("a = 10")
183 ip.run_cell(("def f(x):"
183 ip.run_cell(("def f(x):\n"
184 184 " return x + a"))
185 185 ip.run_cell("b = f(12)")
186 186 self.assertEqual(ip.user_ns["b"], 22)
187 187
188 188 def test_bad_custom_tb(self):
189 189 """Check that InteractiveShell is protected from bad custom exception handlers"""
190 190 ip = get_ipython()
191 191 from IPython.utils import io
192 192 save_stderr = io.stderr
193 193 try:
194 194 # capture stderr
195 195 io.stderr = StringIO()
196 196 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
197 197 self.assertEquals(ip.custom_exceptions, (IOError,))
198 198 ip.run_cell(u'raise IOError("foo")')
199 199 self.assertEquals(ip.custom_exceptions, ())
200 200 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
201 201 finally:
202 202 io.stderr = save_stderr
203 203
204 204 def test_bad_custom_tb_return(self):
205 205 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
206 206 ip = get_ipython()
207 207 from IPython.utils import io
208 208 save_stderr = io.stderr
209 209 try:
210 210 # capture stderr
211 211 io.stderr = StringIO()
212 212 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
213 213 self.assertEquals(ip.custom_exceptions, (NameError,))
214 214 ip.run_cell(u'a=abracadabra')
215 215 self.assertEquals(ip.custom_exceptions, ())
216 216 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
217 217 finally:
218 218 io.stderr = save_stderr
219 219
220 220 def test_drop_by_id(self):
221 221 ip = get_ipython()
222 222 myvars = {"a":object(), "b":object(), "c": object()}
223 223 ip.push(myvars, interactive=False)
224 224 for name in myvars:
225 225 assert name in ip.user_ns, name
226 226 assert name in ip.user_ns_hidden, name
227 227 ip.user_ns['b'] = 12
228 228 ip.drop_by_id(myvars)
229 229 for name in ["a", "c"]:
230 230 assert name not in ip.user_ns, name
231 231 assert name not in ip.user_ns_hidden, name
232 232 assert ip.user_ns['b'] == 12
233 233 ip.reset()
234 234
235 235 def test_var_expand(self):
236 236 ip = get_ipython()
237 237 ip.user_ns['f'] = u'Ca\xf1o'
238 238 self.assertEqual(ip.var_expand(u'echo $f'), u'echo Ca\xf1o')
239 239
240 240 ip.user_ns['f'] = b'Ca\xc3\xb1o'
241 241 # This should not raise any exception:
242 242 ip.var_expand(u'echo $f')
243 243
244 244
245 245 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
246 246
247 247 def setUp(self):
248 248 self.BASETESTDIR = tempfile.mkdtemp()
249 249 self.TESTDIR = join(self.BASETESTDIR, u"åäö")
250 250 os.mkdir(self.TESTDIR)
251 251 with open(join(self.TESTDIR, u"åäötestscript.py"), "w") as sfile:
252 252 sfile.write("pass\n")
253 253 self.oldpath = os.getcwdu()
254 254 os.chdir(self.TESTDIR)
255 255 self.fname = u"åäötestscript.py"
256 256
257 257
258 258 def tearDown(self):
259 259 os.chdir(self.oldpath)
260 260 shutil.rmtree(self.BASETESTDIR)
261 261
262 262 def test_1(self):
263 263 """Test safe_execfile with non-ascii path
264 264 """
265 265 _ip.shell.safe_execfile(self.fname, {}, raise_exceptions=True)
266 266
267 267
268 268 class TestSystemRaw(unittest.TestCase):
269 269 def test_1(self):
270 270 """Test system_raw with non-ascii cmd
271 271 """
272 272 cmd = ur'''python -c "'åäö'" '''
273 273 _ip.shell.system_raw(cmd)
General Comments 0
You need to be logged in to leave comments. Login now