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