Show More
@@ -1,420 +1,432 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 sys |
|
25 | import sys | |
26 | import tempfile |
|
26 | import tempfile | |
27 | import unittest |
|
27 | import unittest | |
28 | from os.path import join |
|
28 | from os.path import join | |
29 | from StringIO import StringIO |
|
29 | from StringIO import StringIO | |
30 |
|
30 | |||
31 | # third-party |
|
31 | # third-party | |
32 | import nose.tools as nt |
|
32 | import nose.tools as nt | |
33 |
|
33 | |||
34 | # Our own |
|
34 | # Our own | |
35 | from IPython.testing.decorators import skipif |
|
35 | from IPython.testing.decorators import skipif | |
36 | from IPython.testing import tools as tt |
|
36 | from IPython.testing import tools as tt | |
37 | from IPython.utils import io |
|
37 | from IPython.utils import io | |
38 |
|
38 | |||
39 | #----------------------------------------------------------------------------- |
|
39 | #----------------------------------------------------------------------------- | |
40 | # Globals |
|
40 | # Globals | |
41 | #----------------------------------------------------------------------------- |
|
41 | #----------------------------------------------------------------------------- | |
42 | # This is used by every single test, no point repeating it ad nauseam |
|
42 | # This is used by every single test, no point repeating it ad nauseam | |
43 | ip = get_ipython() |
|
43 | ip = get_ipython() | |
44 |
|
44 | |||
45 | #----------------------------------------------------------------------------- |
|
45 | #----------------------------------------------------------------------------- | |
46 | # Tests |
|
46 | # Tests | |
47 | #----------------------------------------------------------------------------- |
|
47 | #----------------------------------------------------------------------------- | |
48 |
|
48 | |||
49 | class InteractiveShellTestCase(unittest.TestCase): |
|
49 | class InteractiveShellTestCase(unittest.TestCase): | |
50 | def test_naked_string_cells(self): |
|
50 | def test_naked_string_cells(self): | |
51 | """Test that cells with only naked strings are fully executed""" |
|
51 | """Test that cells with only naked strings are fully executed""" | |
52 | # First, single-line inputs |
|
52 | # First, single-line inputs | |
53 | ip.run_cell('"a"\n') |
|
53 | ip.run_cell('"a"\n') | |
54 | self.assertEqual(ip.user_ns['_'], 'a') |
|
54 | self.assertEqual(ip.user_ns['_'], 'a') | |
55 | # And also multi-line cells |
|
55 | # And also multi-line cells | |
56 | ip.run_cell('"""a\nb"""\n') |
|
56 | ip.run_cell('"""a\nb"""\n') | |
57 | self.assertEqual(ip.user_ns['_'], 'a\nb') |
|
57 | self.assertEqual(ip.user_ns['_'], 'a\nb') | |
58 |
|
58 | |||
59 | def test_run_empty_cell(self): |
|
59 | def test_run_empty_cell(self): | |
60 | """Just make sure we don't get a horrible error with a blank |
|
60 | """Just make sure we don't get a horrible error with a blank | |
61 | cell of input. Yes, I did overlook that.""" |
|
61 | cell of input. Yes, I did overlook that.""" | |
62 | old_xc = ip.execution_count |
|
62 | old_xc = ip.execution_count | |
63 | ip.run_cell('') |
|
63 | ip.run_cell('') | |
64 | self.assertEqual(ip.execution_count, old_xc) |
|
64 | self.assertEqual(ip.execution_count, old_xc) | |
65 |
|
65 | |||
66 | def test_run_cell_multiline(self): |
|
66 | def test_run_cell_multiline(self): | |
67 | """Multi-block, multi-line cells must execute correctly. |
|
67 | """Multi-block, multi-line cells must execute correctly. | |
68 | """ |
|
68 | """ | |
69 | src = '\n'.join(["x=1", |
|
69 | src = '\n'.join(["x=1", | |
70 | "y=2", |
|
70 | "y=2", | |
71 | "if 1:", |
|
71 | "if 1:", | |
72 | " x += 1", |
|
72 | " x += 1", | |
73 | " y += 1",]) |
|
73 | " y += 1",]) | |
74 | ip.run_cell(src) |
|
74 | ip.run_cell(src) | |
75 | self.assertEqual(ip.user_ns['x'], 2) |
|
75 | self.assertEqual(ip.user_ns['x'], 2) | |
76 | self.assertEqual(ip.user_ns['y'], 3) |
|
76 | self.assertEqual(ip.user_ns['y'], 3) | |
77 |
|
77 | |||
78 | def test_multiline_string_cells(self): |
|
78 | def test_multiline_string_cells(self): | |
79 | "Code sprinkled with multiline strings should execute (GH-306)" |
|
79 | "Code sprinkled with multiline strings should execute (GH-306)" | |
80 | ip.run_cell('tmp=0') |
|
80 | ip.run_cell('tmp=0') | |
81 | self.assertEqual(ip.user_ns['tmp'], 0) |
|
81 | self.assertEqual(ip.user_ns['tmp'], 0) | |
82 | ip.run_cell('tmp=1;"""a\nb"""\n') |
|
82 | ip.run_cell('tmp=1;"""a\nb"""\n') | |
83 | self.assertEqual(ip.user_ns['tmp'], 1) |
|
83 | self.assertEqual(ip.user_ns['tmp'], 1) | |
84 |
|
84 | |||
85 | def test_dont_cache_with_semicolon(self): |
|
85 | def test_dont_cache_with_semicolon(self): | |
86 | "Ending a line with semicolon should not cache the returned object (GH-307)" |
|
86 | "Ending a line with semicolon should not cache the returned object (GH-307)" | |
87 | oldlen = len(ip.user_ns['Out']) |
|
87 | oldlen = len(ip.user_ns['Out']) | |
88 | a = ip.run_cell('1;', store_history=True) |
|
88 | a = ip.run_cell('1;', store_history=True) | |
89 | newlen = len(ip.user_ns['Out']) |
|
89 | newlen = len(ip.user_ns['Out']) | |
90 | self.assertEqual(oldlen, newlen) |
|
90 | self.assertEqual(oldlen, newlen) | |
91 | #also test the default caching behavior |
|
91 | #also test the default caching behavior | |
92 | ip.run_cell('1', store_history=True) |
|
92 | ip.run_cell('1', store_history=True) | |
93 | newlen = len(ip.user_ns['Out']) |
|
93 | newlen = len(ip.user_ns['Out']) | |
94 | self.assertEqual(oldlen+1, newlen) |
|
94 | self.assertEqual(oldlen+1, newlen) | |
95 |
|
95 | |||
96 | def test_In_variable(self): |
|
96 | def test_In_variable(self): | |
97 | "Verify that In variable grows with user input (GH-284)" |
|
97 | "Verify that In variable grows with user input (GH-284)" | |
98 | oldlen = len(ip.user_ns['In']) |
|
98 | oldlen = len(ip.user_ns['In']) | |
99 | ip.run_cell('1;', store_history=True) |
|
99 | ip.run_cell('1;', store_history=True) | |
100 | newlen = len(ip.user_ns['In']) |
|
100 | newlen = len(ip.user_ns['In']) | |
101 | self.assertEqual(oldlen+1, newlen) |
|
101 | self.assertEqual(oldlen+1, newlen) | |
102 | self.assertEqual(ip.user_ns['In'][-1],'1;') |
|
102 | self.assertEqual(ip.user_ns['In'][-1],'1;') | |
103 |
|
103 | |||
104 | def test_magic_names_in_string(self): |
|
104 | def test_magic_names_in_string(self): | |
105 | ip.run_cell('a = """\n%exit\n"""') |
|
105 | ip.run_cell('a = """\n%exit\n"""') | |
106 | self.assertEqual(ip.user_ns['a'], '\n%exit\n') |
|
106 | self.assertEqual(ip.user_ns['a'], '\n%exit\n') | |
107 |
|
107 | |||
108 | def test_alias_crash(self): |
|
108 | def test_alias_crash(self): | |
109 | """Errors in prefilter can't crash IPython""" |
|
109 | """Errors in prefilter can't crash IPython""" | |
110 | ip.run_cell('%alias parts echo first %s second %s') |
|
110 | ip.run_cell('%alias parts echo first %s second %s') | |
111 | # capture stderr: |
|
111 | # capture stderr: | |
112 | save_err = io.stderr |
|
112 | save_err = io.stderr | |
113 | io.stderr = StringIO() |
|
113 | io.stderr = StringIO() | |
114 | ip.run_cell('parts 1') |
|
114 | ip.run_cell('parts 1') | |
115 | err = io.stderr.getvalue() |
|
115 | err = io.stderr.getvalue() | |
116 | io.stderr = save_err |
|
116 | io.stderr = save_err | |
117 | self.assertEqual(err.split(':')[0], 'ERROR') |
|
117 | self.assertEqual(err.split(':')[0], 'ERROR') | |
118 |
|
118 | |||
119 | def test_trailing_newline(self): |
|
119 | def test_trailing_newline(self): | |
120 | """test that running !(command) does not raise a SyntaxError""" |
|
120 | """test that running !(command) does not raise a SyntaxError""" | |
121 | ip.run_cell('!(true)\n', False) |
|
121 | ip.run_cell('!(true)\n', False) | |
122 | ip.run_cell('!(true)\n\n\n', False) |
|
122 | ip.run_cell('!(true)\n\n\n', False) | |
123 |
|
123 | |||
124 | def test_gh_597(self): |
|
124 | def test_gh_597(self): | |
125 | """Pretty-printing lists of objects with non-ascii reprs may cause |
|
125 | """Pretty-printing lists of objects with non-ascii reprs may cause | |
126 | problems.""" |
|
126 | problems.""" | |
127 | class Spam(object): |
|
127 | class Spam(object): | |
128 | def __repr__(self): |
|
128 | def __repr__(self): | |
129 | return "\xe9"*50 |
|
129 | return "\xe9"*50 | |
130 | import IPython.core.formatters |
|
130 | import IPython.core.formatters | |
131 | f = IPython.core.formatters.PlainTextFormatter() |
|
131 | f = IPython.core.formatters.PlainTextFormatter() | |
132 | f([Spam(),Spam()]) |
|
132 | f([Spam(),Spam()]) | |
133 |
|
133 | |||
134 |
|
134 | |||
135 | def test_future_flags(self): |
|
135 | def test_future_flags(self): | |
136 | """Check that future flags are used for parsing code (gh-777)""" |
|
136 | """Check that future flags are used for parsing code (gh-777)""" | |
137 | ip.run_cell('from __future__ import print_function') |
|
137 | ip.run_cell('from __future__ import print_function') | |
138 | try: |
|
138 | try: | |
139 | ip.run_cell('prfunc_return_val = print(1,2, sep=" ")') |
|
139 | ip.run_cell('prfunc_return_val = print(1,2, sep=" ")') | |
140 | assert 'prfunc_return_val' in ip.user_ns |
|
140 | assert 'prfunc_return_val' in ip.user_ns | |
141 | finally: |
|
141 | finally: | |
142 | # Reset compiler flags so we don't mess up other tests. |
|
142 | # Reset compiler flags so we don't mess up other tests. | |
143 | ip.compile.reset_compiler_flags() |
|
143 | ip.compile.reset_compiler_flags() | |
144 |
|
144 | |||
145 | def test_future_unicode(self): |
|
145 | def test_future_unicode(self): | |
146 | """Check that unicode_literals is imported from __future__ (gh #786)""" |
|
146 | """Check that unicode_literals is imported from __future__ (gh #786)""" | |
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 | from IPython.utils import io |
|
190 | from IPython.utils import io | |
191 | save_stderr = io.stderr |
|
191 | save_stderr = io.stderr | |
192 | try: |
|
192 | try: | |
193 | # capture stderr |
|
193 | # capture stderr | |
194 | io.stderr = StringIO() |
|
194 | io.stderr = StringIO() | |
195 | ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0) |
|
195 | ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0) | |
196 | self.assertEqual(ip.custom_exceptions, (IOError,)) |
|
196 | self.assertEqual(ip.custom_exceptions, (IOError,)) | |
197 | ip.run_cell(u'raise IOError("foo")') |
|
197 | ip.run_cell(u'raise IOError("foo")') | |
198 | self.assertEqual(ip.custom_exceptions, ()) |
|
198 | self.assertEqual(ip.custom_exceptions, ()) | |
199 | self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue()) |
|
199 | self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue()) | |
200 | finally: |
|
200 | finally: | |
201 | io.stderr = save_stderr |
|
201 | io.stderr = save_stderr | |
202 |
|
202 | |||
203 | def test_bad_custom_tb_return(self): |
|
203 | def test_bad_custom_tb_return(self): | |
204 | """Check that InteractiveShell is protected from bad return types in custom exception handlers""" |
|
204 | """Check that InteractiveShell is protected from bad return types in custom exception handlers""" | |
205 | from IPython.utils import io |
|
205 | from IPython.utils import io | |
206 | save_stderr = io.stderr |
|
206 | save_stderr = io.stderr | |
207 | try: |
|
207 | try: | |
208 | # capture stderr |
|
208 | # capture stderr | |
209 | io.stderr = StringIO() |
|
209 | io.stderr = StringIO() | |
210 | ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1) |
|
210 | ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1) | |
211 | self.assertEqual(ip.custom_exceptions, (NameError,)) |
|
211 | self.assertEqual(ip.custom_exceptions, (NameError,)) | |
212 | ip.run_cell(u'a=abracadabra') |
|
212 | ip.run_cell(u'a=abracadabra') | |
213 | self.assertEqual(ip.custom_exceptions, ()) |
|
213 | self.assertEqual(ip.custom_exceptions, ()) | |
214 | self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue()) |
|
214 | self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue()) | |
215 | finally: |
|
215 | finally: | |
216 | io.stderr = save_stderr |
|
216 | io.stderr = save_stderr | |
217 |
|
217 | |||
218 | def test_drop_by_id(self): |
|
218 | def test_drop_by_id(self): | |
219 | myvars = {"a":object(), "b":object(), "c": object()} |
|
219 | myvars = {"a":object(), "b":object(), "c": object()} | |
220 | ip.push(myvars, interactive=False) |
|
220 | ip.push(myvars, interactive=False) | |
221 | for name in myvars: |
|
221 | for name in myvars: | |
222 | assert name in ip.user_ns, name |
|
222 | assert name in ip.user_ns, name | |
223 | assert name in ip.user_ns_hidden, name |
|
223 | assert name in ip.user_ns_hidden, name | |
224 | ip.user_ns['b'] = 12 |
|
224 | ip.user_ns['b'] = 12 | |
225 | ip.drop_by_id(myvars) |
|
225 | ip.drop_by_id(myvars) | |
226 | for name in ["a", "c"]: |
|
226 | for name in ["a", "c"]: | |
227 | assert name not in ip.user_ns, name |
|
227 | assert name not in ip.user_ns, name | |
228 | assert name not in ip.user_ns_hidden, name |
|
228 | assert name not in ip.user_ns_hidden, name | |
229 | assert ip.user_ns['b'] == 12 |
|
229 | assert ip.user_ns['b'] == 12 | |
230 | ip.reset() |
|
230 | ip.reset() | |
231 |
|
231 | |||
232 | def test_var_expand(self): |
|
232 | def test_var_expand(self): | |
233 | ip.user_ns['f'] = u'Ca\xf1o' |
|
233 | ip.user_ns['f'] = u'Ca\xf1o' | |
234 | self.assertEqual(ip.var_expand(u'echo $f'), u'echo Ca\xf1o') |
|
234 | self.assertEqual(ip.var_expand(u'echo $f'), u'echo Ca\xf1o') | |
235 | self.assertEqual(ip.var_expand(u'echo {f}'), u'echo Ca\xf1o') |
|
235 | self.assertEqual(ip.var_expand(u'echo {f}'), u'echo Ca\xf1o') | |
236 | self.assertEqual(ip.var_expand(u'echo {f[:-1]}'), u'echo Ca\xf1') |
|
236 | self.assertEqual(ip.var_expand(u'echo {f[:-1]}'), u'echo Ca\xf1') | |
237 | self.assertEqual(ip.var_expand(u'echo {1*2}'), u'echo 2') |
|
237 | self.assertEqual(ip.var_expand(u'echo {1*2}'), u'echo 2') | |
238 |
|
238 | |||
239 | ip.user_ns['f'] = b'Ca\xc3\xb1o' |
|
239 | ip.user_ns['f'] = b'Ca\xc3\xb1o' | |
240 | # This should not raise any exception: |
|
240 | # This should not raise any exception: | |
241 | ip.var_expand(u'echo $f') |
|
241 | ip.var_expand(u'echo $f') | |
242 |
|
242 | |||
243 | def test_var_expand_local(self): |
|
243 | def test_var_expand_local(self): | |
244 | """Test local variable expansion in !system and %magic calls""" |
|
244 | """Test local variable expansion in !system and %magic calls""" | |
245 | # !system |
|
245 | # !system | |
246 | ip.run_cell('def test():\n' |
|
246 | ip.run_cell('def test():\n' | |
247 | ' lvar = "ttt"\n' |
|
247 | ' lvar = "ttt"\n' | |
248 | ' ret = !echo {lvar}\n' |
|
248 | ' ret = !echo {lvar}\n' | |
249 | ' return ret[0]\n') |
|
249 | ' return ret[0]\n') | |
250 | res = ip.user_ns['test']() |
|
250 | res = ip.user_ns['test']() | |
251 | nt.assert_in('ttt', res) |
|
251 | nt.assert_in('ttt', res) | |
252 |
|
252 | |||
253 | # %magic |
|
253 | # %magic | |
254 | ip.run_cell('def makemacro():\n' |
|
254 | ip.run_cell('def makemacro():\n' | |
255 | ' macroname = "macro_var_expand_locals"\n' |
|
255 | ' macroname = "macro_var_expand_locals"\n' | |
256 | ' %macro {macroname} codestr\n') |
|
256 | ' %macro {macroname} codestr\n') | |
257 | ip.user_ns['codestr'] = "str(12)" |
|
257 | ip.user_ns['codestr'] = "str(12)" | |
258 | ip.run_cell('makemacro()') |
|
258 | ip.run_cell('makemacro()') | |
259 | nt.assert_in('macro_var_expand_locals', ip.user_ns) |
|
259 | nt.assert_in('macro_var_expand_locals', ip.user_ns) | |
260 |
|
260 | |||
|
261 | def test_var_expand_self(self): | |||
|
262 | """Test variable expansion with the name 'self', which was failing. | |||
|
263 | ||||
|
264 | See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218 | |||
|
265 | """ | |||
|
266 | ip.run_cell('class cTest:\n' | |||
|
267 | ' classvar="see me"\n' | |||
|
268 | ' def test(self):\n' | |||
|
269 | ' res = !echo Variable: {self.classvar}\n' | |||
|
270 | ' return res\n') | |||
|
271 | nt.assert_in('see me', ip.user_ns['cTest']().test()) | |||
|
272 | ||||
261 | def test_bad_var_expand(self): |
|
273 | def test_bad_var_expand(self): | |
262 | """var_expand on invalid formats shouldn't raise""" |
|
274 | """var_expand on invalid formats shouldn't raise""" | |
263 | # SyntaxError |
|
275 | # SyntaxError | |
264 | self.assertEqual(ip.var_expand(u"{'a':5}"), u"{'a':5}") |
|
276 | self.assertEqual(ip.var_expand(u"{'a':5}"), u"{'a':5}") | |
265 | # NameError |
|
277 | # NameError | |
266 | self.assertEqual(ip.var_expand(u"{asdf}"), u"{asdf}") |
|
278 | self.assertEqual(ip.var_expand(u"{asdf}"), u"{asdf}") | |
267 | # ZeroDivisionError |
|
279 | # ZeroDivisionError | |
268 | self.assertEqual(ip.var_expand(u"{1/0}"), u"{1/0}") |
|
280 | self.assertEqual(ip.var_expand(u"{1/0}"), u"{1/0}") | |
269 |
|
281 | |||
270 | def test_silent_nopostexec(self): |
|
282 | def test_silent_nopostexec(self): | |
271 | """run_cell(silent=True) doesn't invoke post-exec funcs""" |
|
283 | """run_cell(silent=True) doesn't invoke post-exec funcs""" | |
272 | d = dict(called=False) |
|
284 | d = dict(called=False) | |
273 | def set_called(): |
|
285 | def set_called(): | |
274 | d['called'] = True |
|
286 | d['called'] = True | |
275 |
|
287 | |||
276 | ip.register_post_execute(set_called) |
|
288 | ip.register_post_execute(set_called) | |
277 | ip.run_cell("1", silent=True) |
|
289 | ip.run_cell("1", silent=True) | |
278 | self.assertFalse(d['called']) |
|
290 | self.assertFalse(d['called']) | |
279 | # double-check that non-silent exec did what we expected |
|
291 | # double-check that non-silent exec did what we expected | |
280 | # silent to avoid |
|
292 | # silent to avoid | |
281 | ip.run_cell("1") |
|
293 | ip.run_cell("1") | |
282 | self.assertTrue(d['called']) |
|
294 | self.assertTrue(d['called']) | |
283 | # remove post-exec |
|
295 | # remove post-exec | |
284 | ip._post_execute.pop(set_called) |
|
296 | ip._post_execute.pop(set_called) | |
285 |
|
297 | |||
286 | def test_silent_noadvance(self): |
|
298 | def test_silent_noadvance(self): | |
287 | """run_cell(silent=True) doesn't advance execution_count""" |
|
299 | """run_cell(silent=True) doesn't advance execution_count""" | |
288 | ec = ip.execution_count |
|
300 | ec = ip.execution_count | |
289 | # silent should force store_history=False |
|
301 | # silent should force store_history=False | |
290 | ip.run_cell("1", store_history=True, silent=True) |
|
302 | ip.run_cell("1", store_history=True, silent=True) | |
291 |
|
303 | |||
292 | self.assertEqual(ec, ip.execution_count) |
|
304 | self.assertEqual(ec, ip.execution_count) | |
293 | # double-check that non-silent exec did what we expected |
|
305 | # double-check that non-silent exec did what we expected | |
294 | # silent to avoid |
|
306 | # silent to avoid | |
295 | ip.run_cell("1", store_history=True) |
|
307 | ip.run_cell("1", store_history=True) | |
296 | self.assertEqual(ec+1, ip.execution_count) |
|
308 | self.assertEqual(ec+1, ip.execution_count) | |
297 |
|
309 | |||
298 | def test_silent_nodisplayhook(self): |
|
310 | def test_silent_nodisplayhook(self): | |
299 | """run_cell(silent=True) doesn't trigger displayhook""" |
|
311 | """run_cell(silent=True) doesn't trigger displayhook""" | |
300 | d = dict(called=False) |
|
312 | d = dict(called=False) | |
301 |
|
313 | |||
302 | trap = ip.display_trap |
|
314 | trap = ip.display_trap | |
303 | save_hook = trap.hook |
|
315 | save_hook = trap.hook | |
304 |
|
316 | |||
305 | def failing_hook(*args, **kwargs): |
|
317 | def failing_hook(*args, **kwargs): | |
306 | d['called'] = True |
|
318 | d['called'] = True | |
307 |
|
319 | |||
308 | try: |
|
320 | try: | |
309 | trap.hook = failing_hook |
|
321 | trap.hook = failing_hook | |
310 | ip.run_cell("1", silent=True) |
|
322 | ip.run_cell("1", silent=True) | |
311 | self.assertFalse(d['called']) |
|
323 | self.assertFalse(d['called']) | |
312 | # double-check that non-silent exec did what we expected |
|
324 | # double-check that non-silent exec did what we expected | |
313 | # silent to avoid |
|
325 | # silent to avoid | |
314 | ip.run_cell("1") |
|
326 | ip.run_cell("1") | |
315 | self.assertTrue(d['called']) |
|
327 | self.assertTrue(d['called']) | |
316 | finally: |
|
328 | finally: | |
317 | trap.hook = save_hook |
|
329 | trap.hook = save_hook | |
318 |
|
330 | |||
319 | @skipif(sys.version_info[0] >= 3, "softspace removed in py3") |
|
331 | @skipif(sys.version_info[0] >= 3, "softspace removed in py3") | |
320 | def test_print_softspace(self): |
|
332 | def test_print_softspace(self): | |
321 | """Verify that softspace is handled correctly when executing multiple |
|
333 | """Verify that softspace is handled correctly when executing multiple | |
322 | statements. |
|
334 | statements. | |
323 |
|
335 | |||
324 | In [1]: print 1; print 2 |
|
336 | In [1]: print 1; print 2 | |
325 | 1 |
|
337 | 1 | |
326 | 2 |
|
338 | 2 | |
327 |
|
339 | |||
328 | In [2]: print 1,; print 2 |
|
340 | In [2]: print 1,; print 2 | |
329 | 1 2 |
|
341 | 1 2 | |
330 | """ |
|
342 | """ | |
331 |
|
343 | |||
332 | def test_ofind_line_magic(self): |
|
344 | def test_ofind_line_magic(self): | |
333 | from IPython.core.magic import register_line_magic |
|
345 | from IPython.core.magic import register_line_magic | |
334 |
|
346 | |||
335 | @register_line_magic |
|
347 | @register_line_magic | |
336 | def lmagic(line): |
|
348 | def lmagic(line): | |
337 | "A line magic" |
|
349 | "A line magic" | |
338 |
|
350 | |||
339 | # Get info on line magic |
|
351 | # Get info on line magic | |
340 | lfind = ip._ofind('lmagic') |
|
352 | lfind = ip._ofind('lmagic') | |
341 | info = dict(found=True, isalias=False, ismagic=True, |
|
353 | info = dict(found=True, isalias=False, ismagic=True, | |
342 | namespace = 'IPython internal', obj= lmagic.__wrapped__, |
|
354 | namespace = 'IPython internal', obj= lmagic.__wrapped__, | |
343 | parent = None) |
|
355 | parent = None) | |
344 | nt.assert_equal(lfind, info) |
|
356 | nt.assert_equal(lfind, info) | |
345 |
|
357 | |||
346 | def test_ofind_cell_magic(self): |
|
358 | def test_ofind_cell_magic(self): | |
347 | from IPython.core.magic import register_cell_magic |
|
359 | from IPython.core.magic import register_cell_magic | |
348 |
|
360 | |||
349 | @register_cell_magic |
|
361 | @register_cell_magic | |
350 | def cmagic(line, cell): |
|
362 | def cmagic(line, cell): | |
351 | "A cell magic" |
|
363 | "A cell magic" | |
352 |
|
364 | |||
353 | # Get info on cell magic |
|
365 | # Get info on cell magic | |
354 | find = ip._ofind('cmagic') |
|
366 | find = ip._ofind('cmagic') | |
355 | info = dict(found=True, isalias=False, ismagic=True, |
|
367 | info = dict(found=True, isalias=False, ismagic=True, | |
356 | namespace = 'IPython internal', obj= cmagic.__wrapped__, |
|
368 | namespace = 'IPython internal', obj= cmagic.__wrapped__, | |
357 | parent = None) |
|
369 | parent = None) | |
358 | nt.assert_equal(find, info) |
|
370 | nt.assert_equal(find, info) | |
359 |
|
371 | |||
360 | def test_custom_exception(self): |
|
372 | def test_custom_exception(self): | |
361 | called = [] |
|
373 | called = [] | |
362 | def my_handler(shell, etype, value, tb, tb_offset=None): |
|
374 | def my_handler(shell, etype, value, tb, tb_offset=None): | |
363 | called.append(etype) |
|
375 | called.append(etype) | |
364 | shell.showtraceback((etype, value, tb), tb_offset=tb_offset) |
|
376 | shell.showtraceback((etype, value, tb), tb_offset=tb_offset) | |
365 |
|
377 | |||
366 | ip.set_custom_exc((ValueError,), my_handler) |
|
378 | ip.set_custom_exc((ValueError,), my_handler) | |
367 | try: |
|
379 | try: | |
368 | ip.run_cell("raise ValueError('test')") |
|
380 | ip.run_cell("raise ValueError('test')") | |
369 | # Check that this was called, and only once. |
|
381 | # Check that this was called, and only once. | |
370 | self.assertEqual(called, [ValueError]) |
|
382 | self.assertEqual(called, [ValueError]) | |
371 | finally: |
|
383 | finally: | |
372 | # Reset the custom exception hook |
|
384 | # Reset the custom exception hook | |
373 | ip.set_custom_exc((), None) |
|
385 | ip.set_custom_exc((), None) | |
374 |
|
386 | |||
375 |
|
387 | |||
376 | class TestSafeExecfileNonAsciiPath(unittest.TestCase): |
|
388 | class TestSafeExecfileNonAsciiPath(unittest.TestCase): | |
377 |
|
389 | |||
378 | def setUp(self): |
|
390 | def setUp(self): | |
379 | self.BASETESTDIR = tempfile.mkdtemp() |
|
391 | self.BASETESTDIR = tempfile.mkdtemp() | |
380 | self.TESTDIR = join(self.BASETESTDIR, u"åäö") |
|
392 | self.TESTDIR = join(self.BASETESTDIR, u"åäö") | |
381 | os.mkdir(self.TESTDIR) |
|
393 | os.mkdir(self.TESTDIR) | |
382 | with open(join(self.TESTDIR, u"åäötestscript.py"), "w") as sfile: |
|
394 | with open(join(self.TESTDIR, u"åäötestscript.py"), "w") as sfile: | |
383 | sfile.write("pass\n") |
|
395 | sfile.write("pass\n") | |
384 | self.oldpath = os.getcwdu() |
|
396 | self.oldpath = os.getcwdu() | |
385 | os.chdir(self.TESTDIR) |
|
397 | os.chdir(self.TESTDIR) | |
386 | self.fname = u"åäötestscript.py" |
|
398 | self.fname = u"åäötestscript.py" | |
387 |
|
399 | |||
388 | def tearDown(self): |
|
400 | def tearDown(self): | |
389 | os.chdir(self.oldpath) |
|
401 | os.chdir(self.oldpath) | |
390 | shutil.rmtree(self.BASETESTDIR) |
|
402 | shutil.rmtree(self.BASETESTDIR) | |
391 |
|
403 | |||
392 | def test_1(self): |
|
404 | def test_1(self): | |
393 | """Test safe_execfile with non-ascii path |
|
405 | """Test safe_execfile with non-ascii path | |
394 | """ |
|
406 | """ | |
395 | ip.safe_execfile(self.fname, {}, raise_exceptions=True) |
|
407 | ip.safe_execfile(self.fname, {}, raise_exceptions=True) | |
396 |
|
408 | |||
397 |
|
409 | |||
398 | class TestSystemRaw(unittest.TestCase): |
|
410 | class TestSystemRaw(unittest.TestCase): | |
399 | def test_1(self): |
|
411 | def test_1(self): | |
400 | """Test system_raw with non-ascii cmd |
|
412 | """Test system_raw with non-ascii cmd | |
401 | """ |
|
413 | """ | |
402 | cmd = ur'''python -c "'åäö'" ''' |
|
414 | cmd = ur'''python -c "'åäö'" ''' | |
403 | ip.system_raw(cmd) |
|
415 | ip.system_raw(cmd) | |
404 |
|
416 | |||
405 | class TestModules(unittest.TestCase, tt.TempFileMixin): |
|
417 | class TestModules(unittest.TestCase, tt.TempFileMixin): | |
406 | def test_extraneous_loads(self): |
|
418 | def test_extraneous_loads(self): | |
407 | """Test we're not loading modules on startup that we shouldn't. |
|
419 | """Test we're not loading modules on startup that we shouldn't. | |
408 | """ |
|
420 | """ | |
409 | self.mktmp("import sys\n" |
|
421 | self.mktmp("import sys\n" | |
410 | "print('numpy' in sys.modules)\n" |
|
422 | "print('numpy' in sys.modules)\n" | |
411 | "print('IPython.parallel' in sys.modules)\n" |
|
423 | "print('IPython.parallel' in sys.modules)\n" | |
412 | "print('IPython.zmq' in sys.modules)\n" |
|
424 | "print('IPython.zmq' in sys.modules)\n" | |
413 | ) |
|
425 | ) | |
414 | out = "False\nFalse\nFalse\n" |
|
426 | out = "False\nFalse\nFalse\n" | |
415 | tt.ipexec_validate(self.fname, out) |
|
427 | tt.ipexec_validate(self.fname, out) | |
416 |
|
428 | |||
417 |
|
429 | |||
418 | def test__IPYTHON__(): |
|
430 | def test__IPYTHON__(): | |
419 | # This shouldn't raise a NameError, that's all |
|
431 | # This shouldn't raise a NameError, that's all | |
420 | __IPYTHON__ |
|
432 | __IPYTHON__ |
General Comments 0
You need to be logged in to leave comments.
Login now