##// END OF EJS Templates
Add failing test for #822, will be fixed next
Fernando Perez -
Show More
@@ -1,230 +1,237 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 from StringIO import StringIO
28 from StringIO import StringIO
29
29
30 from IPython.testing import decorators as dec
30 from IPython.testing import decorators as dec
31 from IPython.utils import io
31 from IPython.utils import io
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # Tests
34 # Tests
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36
36
37 class InteractiveShellTestCase(unittest.TestCase):
37 class InteractiveShellTestCase(unittest.TestCase):
38 def test_naked_string_cells(self):
38 def test_naked_string_cells(self):
39 """Test that cells with only naked strings are fully executed"""
39 """Test that cells with only naked strings are fully executed"""
40 ip = get_ipython()
40 ip = get_ipython()
41 # First, single-line inputs
41 # First, single-line inputs
42 ip.run_cell('"a"\n')
42 ip.run_cell('"a"\n')
43 self.assertEquals(ip.user_ns['_'], 'a')
43 self.assertEquals(ip.user_ns['_'], 'a')
44 # And also multi-line cells
44 # And also multi-line cells
45 ip.run_cell('"""a\nb"""\n')
45 ip.run_cell('"""a\nb"""\n')
46 self.assertEquals(ip.user_ns['_'], 'a\nb')
46 self.assertEquals(ip.user_ns['_'], 'a\nb')
47
47
48 def test_run_empty_cell(self):
48 def test_run_empty_cell(self):
49 """Just make sure we don't get a horrible error with a blank
49 """Just make sure we don't get a horrible error with a blank
50 cell of input. Yes, I did overlook that."""
50 cell of input. Yes, I did overlook that."""
51 ip = get_ipython()
51 ip = get_ipython()
52 old_xc = ip.execution_count
52 old_xc = ip.execution_count
53 ip.run_cell('')
53 ip.run_cell('')
54 self.assertEquals(ip.execution_count, old_xc)
54 self.assertEquals(ip.execution_count, old_xc)
55
55
56 def test_run_cell_multiline(self):
56 def test_run_cell_multiline(self):
57 """Multi-block, multi-line cells must execute correctly.
57 """Multi-block, multi-line cells must execute correctly.
58 """
58 """
59 ip = get_ipython()
59 ip = get_ipython()
60 src = '\n'.join(["x=1",
60 src = '\n'.join(["x=1",
61 "y=2",
61 "y=2",
62 "if 1:",
62 "if 1:",
63 " x += 1",
63 " x += 1",
64 " y += 1",])
64 " y += 1",])
65 ip.run_cell(src)
65 ip.run_cell(src)
66 self.assertEquals(ip.user_ns['x'], 2)
66 self.assertEquals(ip.user_ns['x'], 2)
67 self.assertEquals(ip.user_ns['y'], 3)
67 self.assertEquals(ip.user_ns['y'], 3)
68
68
69 def test_multiline_string_cells(self):
69 def test_multiline_string_cells(self):
70 "Code sprinkled with multiline strings should execute (GH-306)"
70 "Code sprinkled with multiline strings should execute (GH-306)"
71 ip = get_ipython()
71 ip = get_ipython()
72 ip.run_cell('tmp=0')
72 ip.run_cell('tmp=0')
73 self.assertEquals(ip.user_ns['tmp'], 0)
73 self.assertEquals(ip.user_ns['tmp'], 0)
74 ip.run_cell('tmp=1;"""a\nb"""\n')
74 ip.run_cell('tmp=1;"""a\nb"""\n')
75 self.assertEquals(ip.user_ns['tmp'], 1)
75 self.assertEquals(ip.user_ns['tmp'], 1)
76
76
77 def test_dont_cache_with_semicolon(self):
77 def test_dont_cache_with_semicolon(self):
78 "Ending a line with semicolon should not cache the returned object (GH-307)"
78 "Ending a line with semicolon should not cache the returned object (GH-307)"
79 ip = get_ipython()
79 ip = get_ipython()
80 oldlen = len(ip.user_ns['Out'])
80 oldlen = len(ip.user_ns['Out'])
81 a = ip.run_cell('1;', store_history=True)
81 a = ip.run_cell('1;', store_history=True)
82 newlen = len(ip.user_ns['Out'])
82 newlen = len(ip.user_ns['Out'])
83 self.assertEquals(oldlen, newlen)
83 self.assertEquals(oldlen, newlen)
84 #also test the default caching behavior
84 #also test the default caching behavior
85 ip.run_cell('1', store_history=True)
85 ip.run_cell('1', store_history=True)
86 newlen = len(ip.user_ns['Out'])
86 newlen = len(ip.user_ns['Out'])
87 self.assertEquals(oldlen+1, newlen)
87 self.assertEquals(oldlen+1, newlen)
88
88
89 def test_In_variable(self):
89 def test_In_variable(self):
90 "Verify that In variable grows with user input (GH-284)"
90 "Verify that In variable grows with user input (GH-284)"
91 ip = get_ipython()
91 ip = get_ipython()
92 oldlen = len(ip.user_ns['In'])
92 oldlen = len(ip.user_ns['In'])
93 ip.run_cell('1;', store_history=True)
93 ip.run_cell('1;', store_history=True)
94 newlen = len(ip.user_ns['In'])
94 newlen = len(ip.user_ns['In'])
95 self.assertEquals(oldlen+1, newlen)
95 self.assertEquals(oldlen+1, newlen)
96 self.assertEquals(ip.user_ns['In'][-1],'1;')
96 self.assertEquals(ip.user_ns['In'][-1],'1;')
97
97
98 def test_magic_names_in_string(self):
98 def test_magic_names_in_string(self):
99 ip = get_ipython()
99 ip = get_ipython()
100 ip.run_cell('a = """\n%exit\n"""')
100 ip.run_cell('a = """\n%exit\n"""')
101 self.assertEquals(ip.user_ns['a'], '\n%exit\n')
101 self.assertEquals(ip.user_ns['a'], '\n%exit\n')
102
102
103 def test_alias_crash(self):
103 def test_alias_crash(self):
104 """Errors in prefilter can't crash IPython"""
104 """Errors in prefilter can't crash IPython"""
105 ip = get_ipython()
105 ip = get_ipython()
106 ip.run_cell('%alias parts echo first %s second %s')
106 ip.run_cell('%alias parts echo first %s second %s')
107 # capture stderr:
107 # capture stderr:
108 save_err = io.stderr
108 save_err = io.stderr
109 io.stderr = StringIO()
109 io.stderr = StringIO()
110 ip.run_cell('parts 1')
110 ip.run_cell('parts 1')
111 err = io.stderr.getvalue()
111 err = io.stderr.getvalue()
112 io.stderr = save_err
112 io.stderr = save_err
113 self.assertEquals(err.split(':')[0], 'ERROR')
113 self.assertEquals(err.split(':')[0], 'ERROR')
114
114
115 def test_trailing_newline(self):
115 def test_trailing_newline(self):
116 """test that running !(command) does not raise a SyntaxError"""
116 """test that running !(command) does not raise a SyntaxError"""
117 ip = get_ipython()
117 ip = get_ipython()
118 ip.run_cell('!(true)\n', False)
118 ip.run_cell('!(true)\n', False)
119 ip.run_cell('!(true)\n\n\n', False)
119 ip.run_cell('!(true)\n\n\n', False)
120
120
121 def test_gh_597(self):
121 def test_gh_597(self):
122 """Pretty-printing lists of objects with non-ascii reprs may cause
122 """Pretty-printing lists of objects with non-ascii reprs may cause
123 problems."""
123 problems."""
124 class Spam(object):
124 class Spam(object):
125 def __repr__(self):
125 def __repr__(self):
126 return "\xe9"*50
126 return "\xe9"*50
127 import IPython.core.formatters
127 import IPython.core.formatters
128 f = IPython.core.formatters.PlainTextFormatter()
128 f = IPython.core.formatters.PlainTextFormatter()
129 f([Spam(),Spam()])
129 f([Spam(),Spam()])
130
130
131 def test_future_flags(self):
131 def test_future_flags(self):
132 """Check that future flags are used for parsing code (gh-777)"""
132 """Check that future flags are used for parsing code (gh-777)"""
133 ip = get_ipython()
133 ip = get_ipython()
134 ip.run_cell('from __future__ import print_function')
134 ip.run_cell('from __future__ import print_function')
135 try:
135 try:
136 ip.run_cell('prfunc_return_val = print(1,2, sep=" ")')
136 ip.run_cell('prfunc_return_val = print(1,2, sep=" ")')
137 assert 'prfunc_return_val' in ip.user_ns
137 assert 'prfunc_return_val' in ip.user_ns
138 finally:
138 finally:
139 # Reset compiler flags so we don't mess up other tests.
139 # Reset compiler flags so we don't mess up other tests.
140 ip.compile.reset_compiler_flags()
140 ip.compile.reset_compiler_flags()
141
141
142 def test_future_unicode(self):
142 def test_future_unicode(self):
143 """Check that unicode_literals is imported from __future__ (gh #786)"""
143 """Check that unicode_literals is imported from __future__ (gh #786)"""
144 ip = get_ipython()
144 ip = get_ipython()
145 try:
145 try:
146 ip.run_cell(u'byte_str = "a"')
146 ip.run_cell(u'byte_str = "a"')
147 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
147 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
148 ip.run_cell('from __future__ import unicode_literals')
148 ip.run_cell('from __future__ import unicode_literals')
149 ip.run_cell(u'unicode_str = "a"')
149 ip.run_cell(u'unicode_str = "a"')
150 assert isinstance(ip.user_ns['unicode_str'], unicode) # strings literals are now unicode
150 assert isinstance(ip.user_ns['unicode_str'], unicode) # strings literals are now unicode
151 finally:
151 finally:
152 # Reset compiler flags so we don't mess up other tests.
152 # Reset compiler flags so we don't mess up other tests.
153 ip.compile.reset_compiler_flags()
153 ip.compile.reset_compiler_flags()
154
154
155 def test_bad_custom_tb(self):
155 def test_bad_custom_tb(self):
156 """Check that InteractiveShell is protected from bad custom exception handlers"""
156 """Check that InteractiveShell is protected from bad custom exception handlers"""
157 ip = get_ipython()
157 ip = get_ipython()
158 from IPython.utils import io
158 from IPython.utils import io
159 save_stderr = io.stderr
159 save_stderr = io.stderr
160 try:
160 try:
161 # capture stderr
161 # capture stderr
162 io.stderr = StringIO()
162 io.stderr = StringIO()
163 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
163 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
164 self.assertEquals(ip.custom_exceptions, (IOError,))
164 self.assertEquals(ip.custom_exceptions, (IOError,))
165 ip.run_cell(u'raise IOError("foo")')
165 ip.run_cell(u'raise IOError("foo")')
166 self.assertEquals(ip.custom_exceptions, ())
166 self.assertEquals(ip.custom_exceptions, ())
167 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
167 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
168 finally:
168 finally:
169 io.stderr = save_stderr
169 io.stderr = save_stderr
170
170
171 def test_bad_custom_tb_return(self):
171 def test_bad_custom_tb_return(self):
172 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
172 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
173 ip = get_ipython()
173 ip = get_ipython()
174 from IPython.utils import io
174 from IPython.utils import io
175 save_stderr = io.stderr
175 save_stderr = io.stderr
176 try:
176 try:
177 # capture stderr
177 # capture stderr
178 io.stderr = StringIO()
178 io.stderr = StringIO()
179 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
179 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
180 self.assertEquals(ip.custom_exceptions, (NameError,))
180 self.assertEquals(ip.custom_exceptions, (NameError,))
181 ip.run_cell(u'a=abracadabra')
181 ip.run_cell(u'a=abracadabra')
182 self.assertEquals(ip.custom_exceptions, ())
182 self.assertEquals(ip.custom_exceptions, ())
183 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
183 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
184 finally:
184 finally:
185 io.stderr = save_stderr
185 io.stderr = save_stderr
186
186
187 def test_drop_by_id(self):
187 def test_drop_by_id(self):
188 ip = get_ipython()
188 ip = get_ipython()
189 myvars = {"a":object(), "b":object(), "c": object()}
189 myvars = {"a":object(), "b":object(), "c": object()}
190 ip.push(myvars, interactive=False)
190 ip.push(myvars, interactive=False)
191 for name in myvars:
191 for name in myvars:
192 assert name in ip.user_ns, name
192 assert name in ip.user_ns, name
193 assert name in ip.user_ns_hidden, name
193 assert name in ip.user_ns_hidden, name
194 ip.user_ns['b'] = 12
194 ip.user_ns['b'] = 12
195 ip.drop_by_id(myvars)
195 ip.drop_by_id(myvars)
196 for name in ["a", "c"]:
196 for name in ["a", "c"]:
197 assert name not in ip.user_ns, name
197 assert name not in ip.user_ns, name
198 assert name not in ip.user_ns_hidden, name
198 assert name not in ip.user_ns_hidden, name
199 assert ip.user_ns['b'] == 12
199 assert ip.user_ns['b'] == 12
200 ip.reset()
200 ip.reset()
201
201
202 def test_var_expand(self):
203 ip = get_ipython()
204 ip.user_ns['f'] = u'Ca\xc3\xb1o'
205 # This should not raise any exception:
206 ip.var_expand(u'echo $f')
207
208
202 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
209 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
203
210
204 def setUp(self):
211 def setUp(self):
205 self.BASETESTDIR = tempfile.mkdtemp()
212 self.BASETESTDIR = tempfile.mkdtemp()
206 self.TESTDIR = join(self.BASETESTDIR, u"åäö")
213 self.TESTDIR = join(self.BASETESTDIR, u"åäö")
207 os.mkdir(self.TESTDIR)
214 os.mkdir(self.TESTDIR)
208 with open(join(self.TESTDIR, u"åäötestscript.py"), "w") as sfile:
215 with open(join(self.TESTDIR, u"åäötestscript.py"), "w") as sfile:
209 sfile.write("pass\n")
216 sfile.write("pass\n")
210 self.oldpath = os.getcwdu()
217 self.oldpath = os.getcwdu()
211 os.chdir(self.TESTDIR)
218 os.chdir(self.TESTDIR)
212 self.fname = u"åäötestscript.py"
219 self.fname = u"åäötestscript.py"
213
220
214
221
215 def tearDown(self):
222 def tearDown(self):
216 os.chdir(self.oldpath)
223 os.chdir(self.oldpath)
217 shutil.rmtree(self.BASETESTDIR)
224 shutil.rmtree(self.BASETESTDIR)
218
225
219 def test_1(self):
226 def test_1(self):
220 """Test safe_execfile with non-ascii path
227 """Test safe_execfile with non-ascii path
221 """
228 """
222 _ip.shell.safe_execfile(self.fname, {}, raise_exceptions=True)
229 _ip.shell.safe_execfile(self.fname, {}, raise_exceptions=True)
223
230
224
231
225 class TestSystemRaw(unittest.TestCase):
232 class TestSystemRaw(unittest.TestCase):
226 def test_1(self):
233 def test_1(self):
227 """Test system_raw with non-ascii cmd
234 """Test system_raw with non-ascii cmd
228 """
235 """
229 cmd = ur'''python -c "'åäö'" '''
236 cmd = ur'''python -c "'åäö'" '''
230 _ip.shell.system_raw(cmd)
237 _ip.shell.system_raw(cmd)
General Comments 0
You need to be logged in to leave comments. Login now