##// END OF EJS Templates
Skip some tests if nbformat not importable...
Thomas Kluyver -
Show More
@@ -1,961 +1,968 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tests for various magic functions.
2 """Tests for various magic functions.
3
3
4 Needs to be run by nose (to make ipython session available).
4 Needs to be run by nose (to make ipython session available).
5 """
5 """
6 from __future__ import absolute_import
6 from __future__ import absolute_import
7
7
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9 # Imports
9 # Imports
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 import io
12 import io
13 import os
13 import os
14 import sys
14 import sys
15 from unittest import TestCase
15 from unittest import TestCase, skipIf
16
16
17 try:
17 try:
18 from importlib import invalidate_caches # Required from Python 3.3
18 from importlib import invalidate_caches # Required from Python 3.3
19 except ImportError:
19 except ImportError:
20 def invalidate_caches():
20 def invalidate_caches():
21 pass
21 pass
22
22
23 import nose.tools as nt
23 import nose.tools as nt
24
24
25 from IPython.core import magic
25 from IPython.core import magic
26 from IPython.core.magic import (Magics, magics_class, line_magic,
26 from IPython.core.magic import (Magics, magics_class, line_magic,
27 cell_magic, line_cell_magic,
27 cell_magic, line_cell_magic,
28 register_line_magic, register_cell_magic,
28 register_line_magic, register_cell_magic,
29 register_line_cell_magic)
29 register_line_cell_magic)
30 from IPython.core.magics import execution, script, code
30 from IPython.core.magics import execution, script, code
31 from IPython.nbformat.v3.tests.nbexamples import nb0
32 from IPython.nbformat import current
33 from IPython.testing import decorators as dec
31 from IPython.testing import decorators as dec
34 from IPython.testing import tools as tt
32 from IPython.testing import tools as tt
35 from IPython.utils import py3compat
33 from IPython.utils import py3compat
36 from IPython.utils.io import capture_output
34 from IPython.utils.io import capture_output
37 from IPython.utils.tempdir import TemporaryDirectory
35 from IPython.utils.tempdir import TemporaryDirectory
38 from IPython.utils.process import find_cmd
36 from IPython.utils.process import find_cmd
39
37
40 if py3compat.PY3:
38 if py3compat.PY3:
41 from io import StringIO
39 from io import StringIO
42 else:
40 else:
43 from StringIO import StringIO
41 from StringIO import StringIO
44
42
45 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
46 # Test functions begin
44 # Test functions begin
47 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
48
46
49 @magic.magics_class
47 @magic.magics_class
50 class DummyMagics(magic.Magics): pass
48 class DummyMagics(magic.Magics): pass
51
49
52 def test_extract_code_ranges():
50 def test_extract_code_ranges():
53 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
51 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
54 expected = [(0, 1),
52 expected = [(0, 1),
55 (2, 3),
53 (2, 3),
56 (4, 6),
54 (4, 6),
57 (6, 9),
55 (6, 9),
58 (9, 14),
56 (9, 14),
59 (16, None),
57 (16, None),
60 (None, 9),
58 (None, 9),
61 (9, None),
59 (9, None),
62 (None, 13),
60 (None, 13),
63 (None, None)]
61 (None, None)]
64 actual = list(code.extract_code_ranges(instr))
62 actual = list(code.extract_code_ranges(instr))
65 nt.assert_equal(actual, expected)
63 nt.assert_equal(actual, expected)
66
64
67 def test_extract_symbols():
65 def test_extract_symbols():
68 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
66 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
69 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
67 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
70 expected = [([], ['a']),
68 expected = [([], ['a']),
71 (["def b():\n return 42\n"], []),
69 (["def b():\n return 42\n"], []),
72 (["class A: pass\n"], []),
70 (["class A: pass\n"], []),
73 (["class A: pass\n", "def b():\n return 42\n"], []),
71 (["class A: pass\n", "def b():\n return 42\n"], []),
74 (["class A: pass\n"], ['a']),
72 (["class A: pass\n"], ['a']),
75 ([], ['z'])]
73 ([], ['z'])]
76 for symbols, exp in zip(symbols_args, expected):
74 for symbols, exp in zip(symbols_args, expected):
77 nt.assert_equal(code.extract_symbols(source, symbols), exp)
75 nt.assert_equal(code.extract_symbols(source, symbols), exp)
78
76
79
77
80 def test_extract_symbols_raises_exception_with_non_python_code():
78 def test_extract_symbols_raises_exception_with_non_python_code():
81 source = ("=begin A Ruby program :)=end\n"
79 source = ("=begin A Ruby program :)=end\n"
82 "def hello\n"
80 "def hello\n"
83 "puts 'Hello world'\n"
81 "puts 'Hello world'\n"
84 "end")
82 "end")
85 with nt.assert_raises(SyntaxError):
83 with nt.assert_raises(SyntaxError):
86 code.extract_symbols(source, "hello")
84 code.extract_symbols(source, "hello")
87
85
88 def test_config():
86 def test_config():
89 """ test that config magic does not raise
87 """ test that config magic does not raise
90 can happen if Configurable init is moved too early into
88 can happen if Configurable init is moved too early into
91 Magics.__init__ as then a Config object will be registerd as a
89 Magics.__init__ as then a Config object will be registerd as a
92 magic.
90 magic.
93 """
91 """
94 ## should not raise.
92 ## should not raise.
95 _ip.magic('config')
93 _ip.magic('config')
96
94
97 def test_rehashx():
95 def test_rehashx():
98 # clear up everything
96 # clear up everything
99 _ip = get_ipython()
97 _ip = get_ipython()
100 _ip.alias_manager.clear_aliases()
98 _ip.alias_manager.clear_aliases()
101 del _ip.db['syscmdlist']
99 del _ip.db['syscmdlist']
102
100
103 _ip.magic('rehashx')
101 _ip.magic('rehashx')
104 # Practically ALL ipython development systems will have more than 10 aliases
102 # Practically ALL ipython development systems will have more than 10 aliases
105
103
106 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
104 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
107 for name, cmd in _ip.alias_manager.aliases:
105 for name, cmd in _ip.alias_manager.aliases:
108 # we must strip dots from alias names
106 # we must strip dots from alias names
109 nt.assert_not_in('.', name)
107 nt.assert_not_in('.', name)
110
108
111 # rehashx must fill up syscmdlist
109 # rehashx must fill up syscmdlist
112 scoms = _ip.db['syscmdlist']
110 scoms = _ip.db['syscmdlist']
113 nt.assert_true(len(scoms) > 10)
111 nt.assert_true(len(scoms) > 10)
114
112
115
113
116 def test_magic_parse_options():
114 def test_magic_parse_options():
117 """Test that we don't mangle paths when parsing magic options."""
115 """Test that we don't mangle paths when parsing magic options."""
118 ip = get_ipython()
116 ip = get_ipython()
119 path = 'c:\\x'
117 path = 'c:\\x'
120 m = DummyMagics(ip)
118 m = DummyMagics(ip)
121 opts = m.parse_options('-f %s' % path,'f:')[0]
119 opts = m.parse_options('-f %s' % path,'f:')[0]
122 # argv splitting is os-dependent
120 # argv splitting is os-dependent
123 if os.name == 'posix':
121 if os.name == 'posix':
124 expected = 'c:x'
122 expected = 'c:x'
125 else:
123 else:
126 expected = path
124 expected = path
127 nt.assert_equal(opts['f'], expected)
125 nt.assert_equal(opts['f'], expected)
128
126
129 def test_magic_parse_long_options():
127 def test_magic_parse_long_options():
130 """Magic.parse_options can handle --foo=bar long options"""
128 """Magic.parse_options can handle --foo=bar long options"""
131 ip = get_ipython()
129 ip = get_ipython()
132 m = DummyMagics(ip)
130 m = DummyMagics(ip)
133 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
131 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
134 nt.assert_in('foo', opts)
132 nt.assert_in('foo', opts)
135 nt.assert_in('bar', opts)
133 nt.assert_in('bar', opts)
136 nt.assert_equal(opts['bar'], "bubble")
134 nt.assert_equal(opts['bar'], "bubble")
137
135
138
136
139 @dec.skip_without('sqlite3')
137 @dec.skip_without('sqlite3')
140 def doctest_hist_f():
138 def doctest_hist_f():
141 """Test %hist -f with temporary filename.
139 """Test %hist -f with temporary filename.
142
140
143 In [9]: import tempfile
141 In [9]: import tempfile
144
142
145 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
143 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
146
144
147 In [11]: %hist -nl -f $tfile 3
145 In [11]: %hist -nl -f $tfile 3
148
146
149 In [13]: import os; os.unlink(tfile)
147 In [13]: import os; os.unlink(tfile)
150 """
148 """
151
149
152
150
153 @dec.skip_without('sqlite3')
151 @dec.skip_without('sqlite3')
154 def doctest_hist_r():
152 def doctest_hist_r():
155 """Test %hist -r
153 """Test %hist -r
156
154
157 XXX - This test is not recording the output correctly. For some reason, in
155 XXX - This test is not recording the output correctly. For some reason, in
158 testing mode the raw history isn't getting populated. No idea why.
156 testing mode the raw history isn't getting populated. No idea why.
159 Disabling the output checking for now, though at least we do run it.
157 Disabling the output checking for now, though at least we do run it.
160
158
161 In [1]: 'hist' in _ip.lsmagic()
159 In [1]: 'hist' in _ip.lsmagic()
162 Out[1]: True
160 Out[1]: True
163
161
164 In [2]: x=1
162 In [2]: x=1
165
163
166 In [3]: %hist -rl 2
164 In [3]: %hist -rl 2
167 x=1 # random
165 x=1 # random
168 %hist -r 2
166 %hist -r 2
169 """
167 """
170
168
171
169
172 @dec.skip_without('sqlite3')
170 @dec.skip_without('sqlite3')
173 def doctest_hist_op():
171 def doctest_hist_op():
174 """Test %hist -op
172 """Test %hist -op
175
173
176 In [1]: class b(float):
174 In [1]: class b(float):
177 ...: pass
175 ...: pass
178 ...:
176 ...:
179
177
180 In [2]: class s(object):
178 In [2]: class s(object):
181 ...: def __str__(self):
179 ...: def __str__(self):
182 ...: return 's'
180 ...: return 's'
183 ...:
181 ...:
184
182
185 In [3]:
183 In [3]:
186
184
187 In [4]: class r(b):
185 In [4]: class r(b):
188 ...: def __repr__(self):
186 ...: def __repr__(self):
189 ...: return 'r'
187 ...: return 'r'
190 ...:
188 ...:
191
189
192 In [5]: class sr(s,r): pass
190 In [5]: class sr(s,r): pass
193 ...:
191 ...:
194
192
195 In [6]:
193 In [6]:
196
194
197 In [7]: bb=b()
195 In [7]: bb=b()
198
196
199 In [8]: ss=s()
197 In [8]: ss=s()
200
198
201 In [9]: rr=r()
199 In [9]: rr=r()
202
200
203 In [10]: ssrr=sr()
201 In [10]: ssrr=sr()
204
202
205 In [11]: 4.5
203 In [11]: 4.5
206 Out[11]: 4.5
204 Out[11]: 4.5
207
205
208 In [12]: str(ss)
206 In [12]: str(ss)
209 Out[12]: 's'
207 Out[12]: 's'
210
208
211 In [13]:
209 In [13]:
212
210
213 In [14]: %hist -op
211 In [14]: %hist -op
214 >>> class b:
212 >>> class b:
215 ... pass
213 ... pass
216 ...
214 ...
217 >>> class s(b):
215 >>> class s(b):
218 ... def __str__(self):
216 ... def __str__(self):
219 ... return 's'
217 ... return 's'
220 ...
218 ...
221 >>>
219 >>>
222 >>> class r(b):
220 >>> class r(b):
223 ... def __repr__(self):
221 ... def __repr__(self):
224 ... return 'r'
222 ... return 'r'
225 ...
223 ...
226 >>> class sr(s,r): pass
224 >>> class sr(s,r): pass
227 >>>
225 >>>
228 >>> bb=b()
226 >>> bb=b()
229 >>> ss=s()
227 >>> ss=s()
230 >>> rr=r()
228 >>> rr=r()
231 >>> ssrr=sr()
229 >>> ssrr=sr()
232 >>> 4.5
230 >>> 4.5
233 4.5
231 4.5
234 >>> str(ss)
232 >>> str(ss)
235 's'
233 's'
236 >>>
234 >>>
237 """
235 """
238
236
239 def test_hist_pof():
237 def test_hist_pof():
240 ip = get_ipython()
238 ip = get_ipython()
241 ip.run_cell(u"1+2", store_history=True)
239 ip.run_cell(u"1+2", store_history=True)
242 #raise Exception(ip.history_manager.session_number)
240 #raise Exception(ip.history_manager.session_number)
243 #raise Exception(list(ip.history_manager._get_range_session()))
241 #raise Exception(list(ip.history_manager._get_range_session()))
244 with TemporaryDirectory() as td:
242 with TemporaryDirectory() as td:
245 tf = os.path.join(td, 'hist.py')
243 tf = os.path.join(td, 'hist.py')
246 ip.run_line_magic('history', '-pof %s' % tf)
244 ip.run_line_magic('history', '-pof %s' % tf)
247 assert os.path.isfile(tf)
245 assert os.path.isfile(tf)
248
246
249
247
250 @dec.skip_without('sqlite3')
248 @dec.skip_without('sqlite3')
251 def test_macro():
249 def test_macro():
252 ip = get_ipython()
250 ip = get_ipython()
253 ip.history_manager.reset() # Clear any existing history.
251 ip.history_manager.reset() # Clear any existing history.
254 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
252 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
255 for i, cmd in enumerate(cmds, start=1):
253 for i, cmd in enumerate(cmds, start=1):
256 ip.history_manager.store_inputs(i, cmd)
254 ip.history_manager.store_inputs(i, cmd)
257 ip.magic("macro test 1-3")
255 ip.magic("macro test 1-3")
258 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
256 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
259
257
260 # List macros
258 # List macros
261 nt.assert_in("test", ip.magic("macro"))
259 nt.assert_in("test", ip.magic("macro"))
262
260
263
261
264 @dec.skip_without('sqlite3')
262 @dec.skip_without('sqlite3')
265 def test_macro_run():
263 def test_macro_run():
266 """Test that we can run a multi-line macro successfully."""
264 """Test that we can run a multi-line macro successfully."""
267 ip = get_ipython()
265 ip = get_ipython()
268 ip.history_manager.reset()
266 ip.history_manager.reset()
269 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
267 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
270 "%macro test 2-3"]
268 "%macro test 2-3"]
271 for cmd in cmds:
269 for cmd in cmds:
272 ip.run_cell(cmd, store_history=True)
270 ip.run_cell(cmd, store_history=True)
273 nt.assert_equal(ip.user_ns["test"].value,
271 nt.assert_equal(ip.user_ns["test"].value,
274 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
272 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
275 with tt.AssertPrints("12"):
273 with tt.AssertPrints("12"):
276 ip.run_cell("test")
274 ip.run_cell("test")
277 with tt.AssertPrints("13"):
275 with tt.AssertPrints("13"):
278 ip.run_cell("test")
276 ip.run_cell("test")
279
277
280
278
281 def test_magic_magic():
279 def test_magic_magic():
282 """Test %magic"""
280 """Test %magic"""
283 ip = get_ipython()
281 ip = get_ipython()
284 with capture_output() as captured:
282 with capture_output() as captured:
285 ip.magic("magic")
283 ip.magic("magic")
286
284
287 stdout = captured.stdout
285 stdout = captured.stdout
288 nt.assert_in('%magic', stdout)
286 nt.assert_in('%magic', stdout)
289 nt.assert_in('IPython', stdout)
287 nt.assert_in('IPython', stdout)
290 nt.assert_in('Available', stdout)
288 nt.assert_in('Available', stdout)
291
289
292
290
293 @dec.skipif_not_numpy
291 @dec.skipif_not_numpy
294 def test_numpy_reset_array_undec():
292 def test_numpy_reset_array_undec():
295 "Test '%reset array' functionality"
293 "Test '%reset array' functionality"
296 _ip.ex('import numpy as np')
294 _ip.ex('import numpy as np')
297 _ip.ex('a = np.empty(2)')
295 _ip.ex('a = np.empty(2)')
298 nt.assert_in('a', _ip.user_ns)
296 nt.assert_in('a', _ip.user_ns)
299 _ip.magic('reset -f array')
297 _ip.magic('reset -f array')
300 nt.assert_not_in('a', _ip.user_ns)
298 nt.assert_not_in('a', _ip.user_ns)
301
299
302 def test_reset_out():
300 def test_reset_out():
303 "Test '%reset out' magic"
301 "Test '%reset out' magic"
304 _ip.run_cell("parrot = 'dead'", store_history=True)
302 _ip.run_cell("parrot = 'dead'", store_history=True)
305 # test '%reset -f out', make an Out prompt
303 # test '%reset -f out', make an Out prompt
306 _ip.run_cell("parrot", store_history=True)
304 _ip.run_cell("parrot", store_history=True)
307 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
305 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
308 _ip.magic('reset -f out')
306 _ip.magic('reset -f out')
309 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
307 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
310 nt.assert_equal(len(_ip.user_ns['Out']), 0)
308 nt.assert_equal(len(_ip.user_ns['Out']), 0)
311
309
312 def test_reset_in():
310 def test_reset_in():
313 "Test '%reset in' magic"
311 "Test '%reset in' magic"
314 # test '%reset -f in'
312 # test '%reset -f in'
315 _ip.run_cell("parrot", store_history=True)
313 _ip.run_cell("parrot", store_history=True)
316 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
314 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
317 _ip.magic('%reset -f in')
315 _ip.magic('%reset -f in')
318 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
316 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
319 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
317 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
320
318
321 def test_reset_dhist():
319 def test_reset_dhist():
322 "Test '%reset dhist' magic"
320 "Test '%reset dhist' magic"
323 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
321 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
324 _ip.magic('cd ' + os.path.dirname(nt.__file__))
322 _ip.magic('cd ' + os.path.dirname(nt.__file__))
325 _ip.magic('cd -')
323 _ip.magic('cd -')
326 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
324 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
327 _ip.magic('reset -f dhist')
325 _ip.magic('reset -f dhist')
328 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
326 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
329 _ip.run_cell("_dh = [d for d in tmp]") #restore
327 _ip.run_cell("_dh = [d for d in tmp]") #restore
330
328
331 def test_reset_in_length():
329 def test_reset_in_length():
332 "Test that '%reset in' preserves In[] length"
330 "Test that '%reset in' preserves In[] length"
333 _ip.run_cell("print 'foo'")
331 _ip.run_cell("print 'foo'")
334 _ip.run_cell("reset -f in")
332 _ip.run_cell("reset -f in")
335 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
333 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
336
334
337 def test_tb_syntaxerror():
335 def test_tb_syntaxerror():
338 """test %tb after a SyntaxError"""
336 """test %tb after a SyntaxError"""
339 ip = get_ipython()
337 ip = get_ipython()
340 ip.run_cell("for")
338 ip.run_cell("for")
341
339
342 # trap and validate stdout
340 # trap and validate stdout
343 save_stdout = sys.stdout
341 save_stdout = sys.stdout
344 try:
342 try:
345 sys.stdout = StringIO()
343 sys.stdout = StringIO()
346 ip.run_cell("%tb")
344 ip.run_cell("%tb")
347 out = sys.stdout.getvalue()
345 out = sys.stdout.getvalue()
348 finally:
346 finally:
349 sys.stdout = save_stdout
347 sys.stdout = save_stdout
350 # trim output, and only check the last line
348 # trim output, and only check the last line
351 last_line = out.rstrip().splitlines()[-1].strip()
349 last_line = out.rstrip().splitlines()[-1].strip()
352 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
350 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
353
351
354
352
355 def test_time():
353 def test_time():
356 ip = get_ipython()
354 ip = get_ipython()
357
355
358 with tt.AssertPrints("Wall time: "):
356 with tt.AssertPrints("Wall time: "):
359 ip.run_cell("%time None")
357 ip.run_cell("%time None")
360
358
361 ip.run_cell("def f(kmjy):\n"
359 ip.run_cell("def f(kmjy):\n"
362 " %time print (2*kmjy)")
360 " %time print (2*kmjy)")
363
361
364 with tt.AssertPrints("Wall time: "):
362 with tt.AssertPrints("Wall time: "):
365 with tt.AssertPrints("hihi", suppress=False):
363 with tt.AssertPrints("hihi", suppress=False):
366 ip.run_cell("f('hi')")
364 ip.run_cell("f('hi')")
367
365
368
366
369 @dec.skip_win32
367 @dec.skip_win32
370 def test_time2():
368 def test_time2():
371 ip = get_ipython()
369 ip = get_ipython()
372
370
373 with tt.AssertPrints("CPU times: user "):
371 with tt.AssertPrints("CPU times: user "):
374 ip.run_cell("%time None")
372 ip.run_cell("%time None")
375
373
376 def test_time3():
374 def test_time3():
377 """Erroneous magic function calls, issue gh-3334"""
375 """Erroneous magic function calls, issue gh-3334"""
378 ip = get_ipython()
376 ip = get_ipython()
379 ip.user_ns.pop('run', None)
377 ip.user_ns.pop('run', None)
380
378
381 with tt.AssertNotPrints("not found", channel='stderr'):
379 with tt.AssertNotPrints("not found", channel='stderr'):
382 ip.run_cell("%%time\n"
380 ip.run_cell("%%time\n"
383 "run = 0\n"
381 "run = 0\n"
384 "run += 1")
382 "run += 1")
385
383
386 def test_doctest_mode():
384 def test_doctest_mode():
387 "Toggle doctest_mode twice, it should be a no-op and run without error"
385 "Toggle doctest_mode twice, it should be a no-op and run without error"
388 _ip.magic('doctest_mode')
386 _ip.magic('doctest_mode')
389 _ip.magic('doctest_mode')
387 _ip.magic('doctest_mode')
390
388
391
389
392 def test_parse_options():
390 def test_parse_options():
393 """Tests for basic options parsing in magics."""
391 """Tests for basic options parsing in magics."""
394 # These are only the most minimal of tests, more should be added later. At
392 # These are only the most minimal of tests, more should be added later. At
395 # the very least we check that basic text/unicode calls work OK.
393 # the very least we check that basic text/unicode calls work OK.
396 m = DummyMagics(_ip)
394 m = DummyMagics(_ip)
397 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
395 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
398 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
396 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
399
397
400
398
401 def test_dirops():
399 def test_dirops():
402 """Test various directory handling operations."""
400 """Test various directory handling operations."""
403 # curpath = lambda :os.path.splitdrive(py3compat.getcwd())[1].replace('\\','/')
401 # curpath = lambda :os.path.splitdrive(py3compat.getcwd())[1].replace('\\','/')
404 curpath = py3compat.getcwd
402 curpath = py3compat.getcwd
405 startdir = py3compat.getcwd()
403 startdir = py3compat.getcwd()
406 ipdir = os.path.realpath(_ip.ipython_dir)
404 ipdir = os.path.realpath(_ip.ipython_dir)
407 try:
405 try:
408 _ip.magic('cd "%s"' % ipdir)
406 _ip.magic('cd "%s"' % ipdir)
409 nt.assert_equal(curpath(), ipdir)
407 nt.assert_equal(curpath(), ipdir)
410 _ip.magic('cd -')
408 _ip.magic('cd -')
411 nt.assert_equal(curpath(), startdir)
409 nt.assert_equal(curpath(), startdir)
412 _ip.magic('pushd "%s"' % ipdir)
410 _ip.magic('pushd "%s"' % ipdir)
413 nt.assert_equal(curpath(), ipdir)
411 nt.assert_equal(curpath(), ipdir)
414 _ip.magic('popd')
412 _ip.magic('popd')
415 nt.assert_equal(curpath(), startdir)
413 nt.assert_equal(curpath(), startdir)
416 finally:
414 finally:
417 os.chdir(startdir)
415 os.chdir(startdir)
418
416
419
417
420 def test_xmode():
418 def test_xmode():
421 # Calling xmode three times should be a no-op
419 # Calling xmode three times should be a no-op
422 xmode = _ip.InteractiveTB.mode
420 xmode = _ip.InteractiveTB.mode
423 for i in range(3):
421 for i in range(3):
424 _ip.magic("xmode")
422 _ip.magic("xmode")
425 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
423 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
426
424
427 def test_reset_hard():
425 def test_reset_hard():
428 monitor = []
426 monitor = []
429 class A(object):
427 class A(object):
430 def __del__(self):
428 def __del__(self):
431 monitor.append(1)
429 monitor.append(1)
432 def __repr__(self):
430 def __repr__(self):
433 return "<A instance>"
431 return "<A instance>"
434
432
435 _ip.user_ns["a"] = A()
433 _ip.user_ns["a"] = A()
436 _ip.run_cell("a")
434 _ip.run_cell("a")
437
435
438 nt.assert_equal(monitor, [])
436 nt.assert_equal(monitor, [])
439 _ip.magic("reset -f")
437 _ip.magic("reset -f")
440 nt.assert_equal(monitor, [1])
438 nt.assert_equal(monitor, [1])
441
439
442 class TestXdel(tt.TempFileMixin):
440 class TestXdel(tt.TempFileMixin):
443 def test_xdel(self):
441 def test_xdel(self):
444 """Test that references from %run are cleared by xdel."""
442 """Test that references from %run are cleared by xdel."""
445 src = ("class A(object):\n"
443 src = ("class A(object):\n"
446 " monitor = []\n"
444 " monitor = []\n"
447 " def __del__(self):\n"
445 " def __del__(self):\n"
448 " self.monitor.append(1)\n"
446 " self.monitor.append(1)\n"
449 "a = A()\n")
447 "a = A()\n")
450 self.mktmp(src)
448 self.mktmp(src)
451 # %run creates some hidden references...
449 # %run creates some hidden references...
452 _ip.magic("run %s" % self.fname)
450 _ip.magic("run %s" % self.fname)
453 # ... as does the displayhook.
451 # ... as does the displayhook.
454 _ip.run_cell("a")
452 _ip.run_cell("a")
455
453
456 monitor = _ip.user_ns["A"].monitor
454 monitor = _ip.user_ns["A"].monitor
457 nt.assert_equal(monitor, [])
455 nt.assert_equal(monitor, [])
458
456
459 _ip.magic("xdel a")
457 _ip.magic("xdel a")
460
458
461 # Check that a's __del__ method has been called.
459 # Check that a's __del__ method has been called.
462 nt.assert_equal(monitor, [1])
460 nt.assert_equal(monitor, [1])
463
461
464 def doctest_who():
462 def doctest_who():
465 """doctest for %who
463 """doctest for %who
466
464
467 In [1]: %reset -f
465 In [1]: %reset -f
468
466
469 In [2]: alpha = 123
467 In [2]: alpha = 123
470
468
471 In [3]: beta = 'beta'
469 In [3]: beta = 'beta'
472
470
473 In [4]: %who int
471 In [4]: %who int
474 alpha
472 alpha
475
473
476 In [5]: %who str
474 In [5]: %who str
477 beta
475 beta
478
476
479 In [6]: %whos
477 In [6]: %whos
480 Variable Type Data/Info
478 Variable Type Data/Info
481 ----------------------------
479 ----------------------------
482 alpha int 123
480 alpha int 123
483 beta str beta
481 beta str beta
484
482
485 In [7]: %who_ls
483 In [7]: %who_ls
486 Out[7]: ['alpha', 'beta']
484 Out[7]: ['alpha', 'beta']
487 """
485 """
488
486
489 def test_whos():
487 def test_whos():
490 """Check that whos is protected against objects where repr() fails."""
488 """Check that whos is protected against objects where repr() fails."""
491 class A(object):
489 class A(object):
492 def __repr__(self):
490 def __repr__(self):
493 raise Exception()
491 raise Exception()
494 _ip.user_ns['a'] = A()
492 _ip.user_ns['a'] = A()
495 _ip.magic("whos")
493 _ip.magic("whos")
496
494
497 @py3compat.u_format
495 @py3compat.u_format
498 def doctest_precision():
496 def doctest_precision():
499 """doctest for %precision
497 """doctest for %precision
500
498
501 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
499 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
502
500
503 In [2]: %precision 5
501 In [2]: %precision 5
504 Out[2]: {u}'%.5f'
502 Out[2]: {u}'%.5f'
505
503
506 In [3]: f.float_format
504 In [3]: f.float_format
507 Out[3]: {u}'%.5f'
505 Out[3]: {u}'%.5f'
508
506
509 In [4]: %precision %e
507 In [4]: %precision %e
510 Out[4]: {u}'%e'
508 Out[4]: {u}'%e'
511
509
512 In [5]: f(3.1415927)
510 In [5]: f(3.1415927)
513 Out[5]: {u}'3.141593e+00'
511 Out[5]: {u}'3.141593e+00'
514 """
512 """
515
513
516 def test_psearch():
514 def test_psearch():
517 with tt.AssertPrints("dict.fromkeys"):
515 with tt.AssertPrints("dict.fromkeys"):
518 _ip.run_cell("dict.fr*?")
516 _ip.run_cell("dict.fr*?")
519
517
520 def test_timeit_shlex():
518 def test_timeit_shlex():
521 """test shlex issues with timeit (#1109)"""
519 """test shlex issues with timeit (#1109)"""
522 _ip.ex("def f(*a,**kw): pass")
520 _ip.ex("def f(*a,**kw): pass")
523 _ip.magic('timeit -n1 "this is a bug".count(" ")')
521 _ip.magic('timeit -n1 "this is a bug".count(" ")')
524 _ip.magic('timeit -r1 -n1 f(" ", 1)')
522 _ip.magic('timeit -r1 -n1 f(" ", 1)')
525 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
523 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
526 _ip.magic('timeit -r1 -n1 ("a " + "b")')
524 _ip.magic('timeit -r1 -n1 ("a " + "b")')
527 _ip.magic('timeit -r1 -n1 f("a " + "b")')
525 _ip.magic('timeit -r1 -n1 f("a " + "b")')
528 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
526 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
529
527
530
528
531 def test_timeit_arguments():
529 def test_timeit_arguments():
532 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
530 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
533 _ip.magic("timeit ('#')")
531 _ip.magic("timeit ('#')")
534
532
535
533
536 def test_timeit_special_syntax():
534 def test_timeit_special_syntax():
537 "Test %%timeit with IPython special syntax"
535 "Test %%timeit with IPython special syntax"
538 @register_line_magic
536 @register_line_magic
539 def lmagic(line):
537 def lmagic(line):
540 ip = get_ipython()
538 ip = get_ipython()
541 ip.user_ns['lmagic_out'] = line
539 ip.user_ns['lmagic_out'] = line
542
540
543 # line mode test
541 # line mode test
544 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
542 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
545 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
543 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
546 # cell mode test
544 # cell mode test
547 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
545 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
548 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
546 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
549
547
550 def test_timeit_return():
548 def test_timeit_return():
551 """
549 """
552 test wether timeit -o return object
550 test wether timeit -o return object
553 """
551 """
554
552
555 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
553 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
556 assert(res is not None)
554 assert(res is not None)
557
555
558 def test_timeit_quiet():
556 def test_timeit_quiet():
559 """
557 """
560 test quiet option of timeit magic
558 test quiet option of timeit magic
561 """
559 """
562 with tt.AssertNotPrints("loops"):
560 with tt.AssertNotPrints("loops"):
563 _ip.run_cell("%timeit -n1 -r1 -q 1")
561 _ip.run_cell("%timeit -n1 -r1 -q 1")
564
562
565 @dec.skipif(execution.profile is None)
563 @dec.skipif(execution.profile is None)
566 def test_prun_special_syntax():
564 def test_prun_special_syntax():
567 "Test %%prun with IPython special syntax"
565 "Test %%prun with IPython special syntax"
568 @register_line_magic
566 @register_line_magic
569 def lmagic(line):
567 def lmagic(line):
570 ip = get_ipython()
568 ip = get_ipython()
571 ip.user_ns['lmagic_out'] = line
569 ip.user_ns['lmagic_out'] = line
572
570
573 # line mode test
571 # line mode test
574 _ip.run_line_magic('prun', '-q %lmagic my line')
572 _ip.run_line_magic('prun', '-q %lmagic my line')
575 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
573 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
576 # cell mode test
574 # cell mode test
577 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
575 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
578 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
576 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
579
577
580 @dec.skipif(execution.profile is None)
578 @dec.skipif(execution.profile is None)
581 def test_prun_quotes():
579 def test_prun_quotes():
582 "Test that prun does not clobber string escapes (GH #1302)"
580 "Test that prun does not clobber string escapes (GH #1302)"
583 _ip.magic(r"prun -q x = '\t'")
581 _ip.magic(r"prun -q x = '\t'")
584 nt.assert_equal(_ip.user_ns['x'], '\t')
582 nt.assert_equal(_ip.user_ns['x'], '\t')
585
583
586 def test_extension():
584 def test_extension():
587 tmpdir = TemporaryDirectory()
585 tmpdir = TemporaryDirectory()
588 orig_ipython_dir = _ip.ipython_dir
586 orig_ipython_dir = _ip.ipython_dir
589 try:
587 try:
590 _ip.ipython_dir = tmpdir.name
588 _ip.ipython_dir = tmpdir.name
591 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
589 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
592 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
590 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
593 _ip.magic("install_ext %s" % url)
591 _ip.magic("install_ext %s" % url)
594 _ip.user_ns.pop('arq', None)
592 _ip.user_ns.pop('arq', None)
595 invalidate_caches() # Clear import caches
593 invalidate_caches() # Clear import caches
596 _ip.magic("load_ext daft_extension")
594 _ip.magic("load_ext daft_extension")
597 nt.assert_equal(_ip.user_ns['arq'], 185)
595 nt.assert_equal(_ip.user_ns['arq'], 185)
598 _ip.magic("unload_ext daft_extension")
596 _ip.magic("unload_ext daft_extension")
599 assert 'arq' not in _ip.user_ns
597 assert 'arq' not in _ip.user_ns
600 finally:
598 finally:
601 _ip.ipython_dir = orig_ipython_dir
599 _ip.ipython_dir = orig_ipython_dir
602 tmpdir.cleanup()
600 tmpdir.cleanup()
603
604 def test_notebook_export_json():
605 with TemporaryDirectory() as td:
606 outfile = os.path.join(td, "nb.ipynb")
607 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
608 _ip.magic("notebook -e %s" % outfile)
609
601
610 def test_notebook_export_py():
611 with TemporaryDirectory() as td:
612 outfile = os.path.join(td, "nb.py")
613 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
614 _ip.magic("notebook -e %s" % outfile)
615
602
616 def test_notebook_reformat_py():
603 # The nose skip decorator doesn't work on classes, so this uses unittest's skipIf
617 with TemporaryDirectory() as td:
604 @skipIf(dec.module_not_available('IPython.nbformat.current'), 'nbformat not importable')
618 infile = os.path.join(td, "nb.ipynb")
605 class NotebookExportMagicTests(TestCase):
619 with io.open(infile, 'w', encoding='utf-8') as f:
606 def test_notebook_export_json(self):
620 current.write(nb0, f, 'json')
607 with TemporaryDirectory() as td:
621
608 outfile = os.path.join(td, "nb.ipynb")
622 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
609 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
623 _ip.magic("notebook -f py %s" % infile)
610 _ip.magic("notebook -e %s" % outfile)
611
612 def test_notebook_export_py(self):
613 with TemporaryDirectory() as td:
614 outfile = os.path.join(td, "nb.py")
615 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
616 _ip.magic("notebook -e %s" % outfile)
617
618 def test_notebook_reformat_py(self):
619 from IPython.nbformat.v3.tests.nbexamples import nb0
620 from IPython.nbformat import current
621 with TemporaryDirectory() as td:
622 infile = os.path.join(td, "nb.ipynb")
623 with io.open(infile, 'w', encoding='utf-8') as f:
624 current.write(nb0, f, 'json')
625
626 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
627 _ip.magic("notebook -f py %s" % infile)
628
629 def test_notebook_reformat_json(self):
630 from IPython.nbformat.v3.tests.nbexamples import nb0
631 from IPython.nbformat import current
632 with TemporaryDirectory() as td:
633 infile = os.path.join(td, "nb.py")
634 with io.open(infile, 'w', encoding='utf-8') as f:
635 current.write(nb0, f, 'py')
636
637 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
638 _ip.magic("notebook -f ipynb %s" % infile)
639 _ip.magic("notebook -f json %s" % infile)
624
640
625 def test_notebook_reformat_json():
626 with TemporaryDirectory() as td:
627 infile = os.path.join(td, "nb.py")
628 with io.open(infile, 'w', encoding='utf-8') as f:
629 current.write(nb0, f, 'py')
630
631 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
632 _ip.magic("notebook -f ipynb %s" % infile)
633 _ip.magic("notebook -f json %s" % infile)
634
641
635 def test_env():
642 def test_env():
636 env = _ip.magic("env")
643 env = _ip.magic("env")
637 assert isinstance(env, dict), type(env)
644 assert isinstance(env, dict), type(env)
638
645
639
646
640 class CellMagicTestCase(TestCase):
647 class CellMagicTestCase(TestCase):
641
648
642 def check_ident(self, magic):
649 def check_ident(self, magic):
643 # Manually called, we get the result
650 # Manually called, we get the result
644 out = _ip.run_cell_magic(magic, 'a', 'b')
651 out = _ip.run_cell_magic(magic, 'a', 'b')
645 nt.assert_equal(out, ('a','b'))
652 nt.assert_equal(out, ('a','b'))
646 # Via run_cell, it goes into the user's namespace via displayhook
653 # Via run_cell, it goes into the user's namespace via displayhook
647 _ip.run_cell('%%' + magic +' c\nd')
654 _ip.run_cell('%%' + magic +' c\nd')
648 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
655 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
649
656
650 def test_cell_magic_func_deco(self):
657 def test_cell_magic_func_deco(self):
651 "Cell magic using simple decorator"
658 "Cell magic using simple decorator"
652 @register_cell_magic
659 @register_cell_magic
653 def cellm(line, cell):
660 def cellm(line, cell):
654 return line, cell
661 return line, cell
655
662
656 self.check_ident('cellm')
663 self.check_ident('cellm')
657
664
658 def test_cell_magic_reg(self):
665 def test_cell_magic_reg(self):
659 "Cell magic manually registered"
666 "Cell magic manually registered"
660 def cellm(line, cell):
667 def cellm(line, cell):
661 return line, cell
668 return line, cell
662
669
663 _ip.register_magic_function(cellm, 'cell', 'cellm2')
670 _ip.register_magic_function(cellm, 'cell', 'cellm2')
664 self.check_ident('cellm2')
671 self.check_ident('cellm2')
665
672
666 def test_cell_magic_class(self):
673 def test_cell_magic_class(self):
667 "Cell magics declared via a class"
674 "Cell magics declared via a class"
668 @magics_class
675 @magics_class
669 class MyMagics(Magics):
676 class MyMagics(Magics):
670
677
671 @cell_magic
678 @cell_magic
672 def cellm3(self, line, cell):
679 def cellm3(self, line, cell):
673 return line, cell
680 return line, cell
674
681
675 _ip.register_magics(MyMagics)
682 _ip.register_magics(MyMagics)
676 self.check_ident('cellm3')
683 self.check_ident('cellm3')
677
684
678 def test_cell_magic_class2(self):
685 def test_cell_magic_class2(self):
679 "Cell magics declared via a class, #2"
686 "Cell magics declared via a class, #2"
680 @magics_class
687 @magics_class
681 class MyMagics2(Magics):
688 class MyMagics2(Magics):
682
689
683 @cell_magic('cellm4')
690 @cell_magic('cellm4')
684 def cellm33(self, line, cell):
691 def cellm33(self, line, cell):
685 return line, cell
692 return line, cell
686
693
687 _ip.register_magics(MyMagics2)
694 _ip.register_magics(MyMagics2)
688 self.check_ident('cellm4')
695 self.check_ident('cellm4')
689 # Check that nothing is registered as 'cellm33'
696 # Check that nothing is registered as 'cellm33'
690 c33 = _ip.find_cell_magic('cellm33')
697 c33 = _ip.find_cell_magic('cellm33')
691 nt.assert_equal(c33, None)
698 nt.assert_equal(c33, None)
692
699
693 def test_file():
700 def test_file():
694 """Basic %%file"""
701 """Basic %%file"""
695 ip = get_ipython()
702 ip = get_ipython()
696 with TemporaryDirectory() as td:
703 with TemporaryDirectory() as td:
697 fname = os.path.join(td, 'file1')
704 fname = os.path.join(td, 'file1')
698 ip.run_cell_magic("file", fname, u'\n'.join([
705 ip.run_cell_magic("file", fname, u'\n'.join([
699 'line1',
706 'line1',
700 'line2',
707 'line2',
701 ]))
708 ]))
702 with open(fname) as f:
709 with open(fname) as f:
703 s = f.read()
710 s = f.read()
704 nt.assert_in('line1\n', s)
711 nt.assert_in('line1\n', s)
705 nt.assert_in('line2', s)
712 nt.assert_in('line2', s)
706
713
707 def test_file_var_expand():
714 def test_file_var_expand():
708 """%%file $filename"""
715 """%%file $filename"""
709 ip = get_ipython()
716 ip = get_ipython()
710 with TemporaryDirectory() as td:
717 with TemporaryDirectory() as td:
711 fname = os.path.join(td, 'file1')
718 fname = os.path.join(td, 'file1')
712 ip.user_ns['filename'] = fname
719 ip.user_ns['filename'] = fname
713 ip.run_cell_magic("file", '$filename', u'\n'.join([
720 ip.run_cell_magic("file", '$filename', u'\n'.join([
714 'line1',
721 'line1',
715 'line2',
722 'line2',
716 ]))
723 ]))
717 with open(fname) as f:
724 with open(fname) as f:
718 s = f.read()
725 s = f.read()
719 nt.assert_in('line1\n', s)
726 nt.assert_in('line1\n', s)
720 nt.assert_in('line2', s)
727 nt.assert_in('line2', s)
721
728
722 def test_file_unicode():
729 def test_file_unicode():
723 """%%file with unicode cell"""
730 """%%file with unicode cell"""
724 ip = get_ipython()
731 ip = get_ipython()
725 with TemporaryDirectory() as td:
732 with TemporaryDirectory() as td:
726 fname = os.path.join(td, 'file1')
733 fname = os.path.join(td, 'file1')
727 ip.run_cell_magic("file", fname, u'\n'.join([
734 ip.run_cell_magic("file", fname, u'\n'.join([
728 u'linΓ©1',
735 u'linΓ©1',
729 u'linΓ©2',
736 u'linΓ©2',
730 ]))
737 ]))
731 with io.open(fname, encoding='utf-8') as f:
738 with io.open(fname, encoding='utf-8') as f:
732 s = f.read()
739 s = f.read()
733 nt.assert_in(u'linΓ©1\n', s)
740 nt.assert_in(u'linΓ©1\n', s)
734 nt.assert_in(u'linΓ©2', s)
741 nt.assert_in(u'linΓ©2', s)
735
742
736 def test_file_amend():
743 def test_file_amend():
737 """%%file -a amends files"""
744 """%%file -a amends files"""
738 ip = get_ipython()
745 ip = get_ipython()
739 with TemporaryDirectory() as td:
746 with TemporaryDirectory() as td:
740 fname = os.path.join(td, 'file2')
747 fname = os.path.join(td, 'file2')
741 ip.run_cell_magic("file", fname, u'\n'.join([
748 ip.run_cell_magic("file", fname, u'\n'.join([
742 'line1',
749 'line1',
743 'line2',
750 'line2',
744 ]))
751 ]))
745 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
752 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
746 'line3',
753 'line3',
747 'line4',
754 'line4',
748 ]))
755 ]))
749 with open(fname) as f:
756 with open(fname) as f:
750 s = f.read()
757 s = f.read()
751 nt.assert_in('line1\n', s)
758 nt.assert_in('line1\n', s)
752 nt.assert_in('line3\n', s)
759 nt.assert_in('line3\n', s)
753
760
754
761
755 def test_script_config():
762 def test_script_config():
756 ip = get_ipython()
763 ip = get_ipython()
757 ip.config.ScriptMagics.script_magics = ['whoda']
764 ip.config.ScriptMagics.script_magics = ['whoda']
758 sm = script.ScriptMagics(shell=ip)
765 sm = script.ScriptMagics(shell=ip)
759 nt.assert_in('whoda', sm.magics['cell'])
766 nt.assert_in('whoda', sm.magics['cell'])
760
767
761 @dec.skip_win32
768 @dec.skip_win32
762 def test_script_out():
769 def test_script_out():
763 ip = get_ipython()
770 ip = get_ipython()
764 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
771 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
765 nt.assert_equal(ip.user_ns['output'], 'hi\n')
772 nt.assert_equal(ip.user_ns['output'], 'hi\n')
766
773
767 @dec.skip_win32
774 @dec.skip_win32
768 def test_script_err():
775 def test_script_err():
769 ip = get_ipython()
776 ip = get_ipython()
770 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
777 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
771 nt.assert_equal(ip.user_ns['error'], 'hello\n')
778 nt.assert_equal(ip.user_ns['error'], 'hello\n')
772
779
773 @dec.skip_win32
780 @dec.skip_win32
774 def test_script_out_err():
781 def test_script_out_err():
775 ip = get_ipython()
782 ip = get_ipython()
776 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
783 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
777 nt.assert_equal(ip.user_ns['output'], 'hi\n')
784 nt.assert_equal(ip.user_ns['output'], 'hi\n')
778 nt.assert_equal(ip.user_ns['error'], 'hello\n')
785 nt.assert_equal(ip.user_ns['error'], 'hello\n')
779
786
780 @dec.skip_win32
787 @dec.skip_win32
781 def test_script_bg_out():
788 def test_script_bg_out():
782 ip = get_ipython()
789 ip = get_ipython()
783 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
790 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
784 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
791 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
785
792
786 @dec.skip_win32
793 @dec.skip_win32
787 def test_script_bg_err():
794 def test_script_bg_err():
788 ip = get_ipython()
795 ip = get_ipython()
789 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
796 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
790 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
797 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
791
798
792 @dec.skip_win32
799 @dec.skip_win32
793 def test_script_bg_out_err():
800 def test_script_bg_out_err():
794 ip = get_ipython()
801 ip = get_ipython()
795 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
802 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
796 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
803 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
797 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
804 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
798
805
799 def test_script_defaults():
806 def test_script_defaults():
800 ip = get_ipython()
807 ip = get_ipython()
801 for cmd in ['sh', 'bash', 'perl', 'ruby']:
808 for cmd in ['sh', 'bash', 'perl', 'ruby']:
802 try:
809 try:
803 find_cmd(cmd)
810 find_cmd(cmd)
804 except Exception:
811 except Exception:
805 pass
812 pass
806 else:
813 else:
807 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
814 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
808
815
809
816
810 @magics_class
817 @magics_class
811 class FooFoo(Magics):
818 class FooFoo(Magics):
812 """class with both %foo and %%foo magics"""
819 """class with both %foo and %%foo magics"""
813 @line_magic('foo')
820 @line_magic('foo')
814 def line_foo(self, line):
821 def line_foo(self, line):
815 "I am line foo"
822 "I am line foo"
816 pass
823 pass
817
824
818 @cell_magic("foo")
825 @cell_magic("foo")
819 def cell_foo(self, line, cell):
826 def cell_foo(self, line, cell):
820 "I am cell foo, not line foo"
827 "I am cell foo, not line foo"
821 pass
828 pass
822
829
823 def test_line_cell_info():
830 def test_line_cell_info():
824 """%%foo and %foo magics are distinguishable to inspect"""
831 """%%foo and %foo magics are distinguishable to inspect"""
825 ip = get_ipython()
832 ip = get_ipython()
826 ip.magics_manager.register(FooFoo)
833 ip.magics_manager.register(FooFoo)
827 oinfo = ip.object_inspect('foo')
834 oinfo = ip.object_inspect('foo')
828 nt.assert_true(oinfo['found'])
835 nt.assert_true(oinfo['found'])
829 nt.assert_true(oinfo['ismagic'])
836 nt.assert_true(oinfo['ismagic'])
830
837
831 oinfo = ip.object_inspect('%%foo')
838 oinfo = ip.object_inspect('%%foo')
832 nt.assert_true(oinfo['found'])
839 nt.assert_true(oinfo['found'])
833 nt.assert_true(oinfo['ismagic'])
840 nt.assert_true(oinfo['ismagic'])
834 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
841 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
835
842
836 oinfo = ip.object_inspect('%foo')
843 oinfo = ip.object_inspect('%foo')
837 nt.assert_true(oinfo['found'])
844 nt.assert_true(oinfo['found'])
838 nt.assert_true(oinfo['ismagic'])
845 nt.assert_true(oinfo['ismagic'])
839 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
846 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
840
847
841 def test_multiple_magics():
848 def test_multiple_magics():
842 ip = get_ipython()
849 ip = get_ipython()
843 foo1 = FooFoo(ip)
850 foo1 = FooFoo(ip)
844 foo2 = FooFoo(ip)
851 foo2 = FooFoo(ip)
845 mm = ip.magics_manager
852 mm = ip.magics_manager
846 mm.register(foo1)
853 mm.register(foo1)
847 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
854 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
848 mm.register(foo2)
855 mm.register(foo2)
849 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
856 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
850
857
851 def test_alias_magic():
858 def test_alias_magic():
852 """Test %alias_magic."""
859 """Test %alias_magic."""
853 ip = get_ipython()
860 ip = get_ipython()
854 mm = ip.magics_manager
861 mm = ip.magics_manager
855
862
856 # Basic operation: both cell and line magics are created, if possible.
863 # Basic operation: both cell and line magics are created, if possible.
857 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
864 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
858 nt.assert_in('timeit_alias', mm.magics['line'])
865 nt.assert_in('timeit_alias', mm.magics['line'])
859 nt.assert_in('timeit_alias', mm.magics['cell'])
866 nt.assert_in('timeit_alias', mm.magics['cell'])
860
867
861 # --cell is specified, line magic not created.
868 # --cell is specified, line magic not created.
862 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
869 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
863 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
870 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
864 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
871 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
865
872
866 # Test that line alias is created successfully.
873 # Test that line alias is created successfully.
867 ip.run_line_magic('alias_magic', '--line env_alias env')
874 ip.run_line_magic('alias_magic', '--line env_alias env')
868 nt.assert_equal(ip.run_line_magic('env', ''),
875 nt.assert_equal(ip.run_line_magic('env', ''),
869 ip.run_line_magic('env_alias', ''))
876 ip.run_line_magic('env_alias', ''))
870
877
871 def test_save():
878 def test_save():
872 """Test %save."""
879 """Test %save."""
873 ip = get_ipython()
880 ip = get_ipython()
874 ip.history_manager.reset() # Clear any existing history.
881 ip.history_manager.reset() # Clear any existing history.
875 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
882 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
876 for i, cmd in enumerate(cmds, start=1):
883 for i, cmd in enumerate(cmds, start=1):
877 ip.history_manager.store_inputs(i, cmd)
884 ip.history_manager.store_inputs(i, cmd)
878 with TemporaryDirectory() as tmpdir:
885 with TemporaryDirectory() as tmpdir:
879 file = os.path.join(tmpdir, "testsave.py")
886 file = os.path.join(tmpdir, "testsave.py")
880 ip.run_line_magic("save", "%s 1-10" % file)
887 ip.run_line_magic("save", "%s 1-10" % file)
881 with open(file) as f:
888 with open(file) as f:
882 content = f.read()
889 content = f.read()
883 nt.assert_equal(content.count(cmds[0]), 1)
890 nt.assert_equal(content.count(cmds[0]), 1)
884 nt.assert_in('coding: utf-8', content)
891 nt.assert_in('coding: utf-8', content)
885 ip.run_line_magic("save", "-a %s 1-10" % file)
892 ip.run_line_magic("save", "-a %s 1-10" % file)
886 with open(file) as f:
893 with open(file) as f:
887 content = f.read()
894 content = f.read()
888 nt.assert_equal(content.count(cmds[0]), 2)
895 nt.assert_equal(content.count(cmds[0]), 2)
889 nt.assert_in('coding: utf-8', content)
896 nt.assert_in('coding: utf-8', content)
890
897
891
898
892 def test_store():
899 def test_store():
893 """Test %store."""
900 """Test %store."""
894 ip = get_ipython()
901 ip = get_ipython()
895 ip.run_line_magic('load_ext', 'storemagic')
902 ip.run_line_magic('load_ext', 'storemagic')
896
903
897 # make sure the storage is empty
904 # make sure the storage is empty
898 ip.run_line_magic('store', '-z')
905 ip.run_line_magic('store', '-z')
899 ip.user_ns['var'] = 42
906 ip.user_ns['var'] = 42
900 ip.run_line_magic('store', 'var')
907 ip.run_line_magic('store', 'var')
901 ip.user_ns['var'] = 39
908 ip.user_ns['var'] = 39
902 ip.run_line_magic('store', '-r')
909 ip.run_line_magic('store', '-r')
903 nt.assert_equal(ip.user_ns['var'], 42)
910 nt.assert_equal(ip.user_ns['var'], 42)
904
911
905 ip.run_line_magic('store', '-d var')
912 ip.run_line_magic('store', '-d var')
906 ip.user_ns['var'] = 39
913 ip.user_ns['var'] = 39
907 ip.run_line_magic('store' , '-r')
914 ip.run_line_magic('store' , '-r')
908 nt.assert_equal(ip.user_ns['var'], 39)
915 nt.assert_equal(ip.user_ns['var'], 39)
909
916
910
917
911 def _run_edit_test(arg_s, exp_filename=None,
918 def _run_edit_test(arg_s, exp_filename=None,
912 exp_lineno=-1,
919 exp_lineno=-1,
913 exp_contents=None,
920 exp_contents=None,
914 exp_is_temp=None):
921 exp_is_temp=None):
915 ip = get_ipython()
922 ip = get_ipython()
916 M = code.CodeMagics(ip)
923 M = code.CodeMagics(ip)
917 last_call = ['','']
924 last_call = ['','']
918 opts,args = M.parse_options(arg_s,'prxn:')
925 opts,args = M.parse_options(arg_s,'prxn:')
919 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
926 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
920
927
921 if exp_filename is not None:
928 if exp_filename is not None:
922 nt.assert_equal(exp_filename, filename)
929 nt.assert_equal(exp_filename, filename)
923 if exp_contents is not None:
930 if exp_contents is not None:
924 with io.open(filename, 'r', encoding='utf-8') as f:
931 with io.open(filename, 'r', encoding='utf-8') as f:
925 contents = f.read()
932 contents = f.read()
926 nt.assert_equal(exp_contents, contents)
933 nt.assert_equal(exp_contents, contents)
927 if exp_lineno != -1:
934 if exp_lineno != -1:
928 nt.assert_equal(exp_lineno, lineno)
935 nt.assert_equal(exp_lineno, lineno)
929 if exp_is_temp is not None:
936 if exp_is_temp is not None:
930 nt.assert_equal(exp_is_temp, is_temp)
937 nt.assert_equal(exp_is_temp, is_temp)
931
938
932
939
933 def test_edit_interactive():
940 def test_edit_interactive():
934 """%edit on interactively defined objects"""
941 """%edit on interactively defined objects"""
935 ip = get_ipython()
942 ip = get_ipython()
936 n = ip.execution_count
943 n = ip.execution_count
937 ip.run_cell(u"def foo(): return 1", store_history=True)
944 ip.run_cell(u"def foo(): return 1", store_history=True)
938
945
939 try:
946 try:
940 _run_edit_test("foo")
947 _run_edit_test("foo")
941 except code.InteractivelyDefined as e:
948 except code.InteractivelyDefined as e:
942 nt.assert_equal(e.index, n)
949 nt.assert_equal(e.index, n)
943 else:
950 else:
944 raise AssertionError("Should have raised InteractivelyDefined")
951 raise AssertionError("Should have raised InteractivelyDefined")
945
952
946
953
947 def test_edit_cell():
954 def test_edit_cell():
948 """%edit [cell id]"""
955 """%edit [cell id]"""
949 ip = get_ipython()
956 ip = get_ipython()
950
957
951 ip.run_cell(u"def foo(): return 1", store_history=True)
958 ip.run_cell(u"def foo(): return 1", store_history=True)
952
959
953 # test
960 # test
954 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
961 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
955
962
956 def test_bookmark():
963 def test_bookmark():
957 ip = get_ipython()
964 ip = get_ipython()
958 ip.run_line_magic('bookmark', 'bmname')
965 ip.run_line_magic('bookmark', 'bmname')
959 with tt.AssertPrints('bmname'):
966 with tt.AssertPrints('bmname'):
960 ip.run_line_magic('bookmark', '-l')
967 ip.run_line_magic('bookmark', '-l')
961 ip.run_line_magic('bookmark', '-d bmname')
968 ip.run_line_magic('bookmark', '-d bmname')
@@ -1,515 +1,516 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for code execution (%run and related), which is particularly tricky.
2 """Tests for code execution (%run and related), which is particularly tricky.
3
3
4 Because of how %run manages namespaces, and the fact that we are trying here to
4 Because of how %run manages namespaces, and the fact that we are trying here to
5 verify subtle object deletion and reference counting issues, the %run tests
5 verify subtle object deletion and reference counting issues, the %run tests
6 will be kept in this separate file. This makes it easier to aggregate in one
6 will be kept in this separate file. This makes it easier to aggregate in one
7 place the tricks needed to handle it; most other magics are much easier to test
7 place the tricks needed to handle it; most other magics are much easier to test
8 and we do so in a common test_magic file.
8 and we do so in a common test_magic file.
9 """
9 """
10 from __future__ import absolute_import
10 from __future__ import absolute_import
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 import functools
16 import functools
17 import os
17 import os
18 from os.path import join as pjoin
18 from os.path import join as pjoin
19 import random
19 import random
20 import sys
20 import sys
21 import tempfile
21 import tempfile
22 import textwrap
22 import textwrap
23 import unittest
23 import unittest
24
24
25 import nose.tools as nt
25 import nose.tools as nt
26 from nose import SkipTest
26 from nose import SkipTest
27
27
28 from IPython.testing import decorators as dec
28 from IPython.testing import decorators as dec
29 from IPython.testing import tools as tt
29 from IPython.testing import tools as tt
30 from IPython.utils import py3compat
30 from IPython.utils import py3compat
31 from IPython.utils.io import capture_output
31 from IPython.utils.io import capture_output
32 from IPython.utils.tempdir import TemporaryDirectory
32 from IPython.utils.tempdir import TemporaryDirectory
33 from IPython.core import debugger
33 from IPython.core import debugger
34
34
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36 # Test functions begin
36 # Test functions begin
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38
38
39 def doctest_refbug():
39 def doctest_refbug():
40 """Very nasty problem with references held by multiple runs of a script.
40 """Very nasty problem with references held by multiple runs of a script.
41 See: https://github.com/ipython/ipython/issues/141
41 See: https://github.com/ipython/ipython/issues/141
42
42
43 In [1]: _ip.clear_main_mod_cache()
43 In [1]: _ip.clear_main_mod_cache()
44 # random
44 # random
45
45
46 In [2]: %run refbug
46 In [2]: %run refbug
47
47
48 In [3]: call_f()
48 In [3]: call_f()
49 lowercased: hello
49 lowercased: hello
50
50
51 In [4]: %run refbug
51 In [4]: %run refbug
52
52
53 In [5]: call_f()
53 In [5]: call_f()
54 lowercased: hello
54 lowercased: hello
55 lowercased: hello
55 lowercased: hello
56 """
56 """
57
57
58
58
59 def doctest_run_builtins():
59 def doctest_run_builtins():
60 r"""Check that %run doesn't damage __builtins__.
60 r"""Check that %run doesn't damage __builtins__.
61
61
62 In [1]: import tempfile
62 In [1]: import tempfile
63
63
64 In [2]: bid1 = id(__builtins__)
64 In [2]: bid1 = id(__builtins__)
65
65
66 In [3]: fname = tempfile.mkstemp('.py')[1]
66 In [3]: fname = tempfile.mkstemp('.py')[1]
67
67
68 In [3]: f = open(fname,'w')
68 In [3]: f = open(fname,'w')
69
69
70 In [4]: dummy= f.write('pass\n')
70 In [4]: dummy= f.write('pass\n')
71
71
72 In [5]: f.flush()
72 In [5]: f.flush()
73
73
74 In [6]: t1 = type(__builtins__)
74 In [6]: t1 = type(__builtins__)
75
75
76 In [7]: %run $fname
76 In [7]: %run $fname
77
77
78 In [7]: f.close()
78 In [7]: f.close()
79
79
80 In [8]: bid2 = id(__builtins__)
80 In [8]: bid2 = id(__builtins__)
81
81
82 In [9]: t2 = type(__builtins__)
82 In [9]: t2 = type(__builtins__)
83
83
84 In [10]: t1 == t2
84 In [10]: t1 == t2
85 Out[10]: True
85 Out[10]: True
86
86
87 In [10]: bid1 == bid2
87 In [10]: bid1 == bid2
88 Out[10]: True
88 Out[10]: True
89
89
90 In [12]: try:
90 In [12]: try:
91 ....: os.unlink(fname)
91 ....: os.unlink(fname)
92 ....: except:
92 ....: except:
93 ....: pass
93 ....: pass
94 ....:
94 ....:
95 """
95 """
96
96
97
97
98 def doctest_run_option_parser():
98 def doctest_run_option_parser():
99 r"""Test option parser in %run.
99 r"""Test option parser in %run.
100
100
101 In [1]: %run print_argv.py
101 In [1]: %run print_argv.py
102 []
102 []
103
103
104 In [2]: %run print_argv.py print*.py
104 In [2]: %run print_argv.py print*.py
105 ['print_argv.py']
105 ['print_argv.py']
106
106
107 In [3]: %run -G print_argv.py print*.py
107 In [3]: %run -G print_argv.py print*.py
108 ['print*.py']
108 ['print*.py']
109
109
110 """
110 """
111
111
112
112
113 @dec.skip_win32
113 @dec.skip_win32
114 def doctest_run_option_parser_for_posix():
114 def doctest_run_option_parser_for_posix():
115 r"""Test option parser in %run (Linux/OSX specific).
115 r"""Test option parser in %run (Linux/OSX specific).
116
116
117 You need double quote to escape glob in POSIX systems:
117 You need double quote to escape glob in POSIX systems:
118
118
119 In [1]: %run print_argv.py print\\*.py
119 In [1]: %run print_argv.py print\\*.py
120 ['print*.py']
120 ['print*.py']
121
121
122 You can't use quote to escape glob in POSIX systems:
122 You can't use quote to escape glob in POSIX systems:
123
123
124 In [2]: %run print_argv.py 'print*.py'
124 In [2]: %run print_argv.py 'print*.py'
125 ['print_argv.py']
125 ['print_argv.py']
126
126
127 """
127 """
128
128
129
129
130 @dec.skip_if_not_win32
130 @dec.skip_if_not_win32
131 def doctest_run_option_parser_for_windows():
131 def doctest_run_option_parser_for_windows():
132 r"""Test option parser in %run (Windows specific).
132 r"""Test option parser in %run (Windows specific).
133
133
134 In Windows, you can't escape ``*` `by backslash:
134 In Windows, you can't escape ``*` `by backslash:
135
135
136 In [1]: %run print_argv.py print\\*.py
136 In [1]: %run print_argv.py print\\*.py
137 ['print\\*.py']
137 ['print\\*.py']
138
138
139 You can use quote to escape glob:
139 You can use quote to escape glob:
140
140
141 In [2]: %run print_argv.py 'print*.py'
141 In [2]: %run print_argv.py 'print*.py'
142 ['print*.py']
142 ['print*.py']
143
143
144 """
144 """
145
145
146
146
147 @py3compat.doctest_refactor_print
147 @py3compat.doctest_refactor_print
148 def doctest_reset_del():
148 def doctest_reset_del():
149 """Test that resetting doesn't cause errors in __del__ methods.
149 """Test that resetting doesn't cause errors in __del__ methods.
150
150
151 In [2]: class A(object):
151 In [2]: class A(object):
152 ...: def __del__(self):
152 ...: def __del__(self):
153 ...: print str("Hi")
153 ...: print str("Hi")
154 ...:
154 ...:
155
155
156 In [3]: a = A()
156 In [3]: a = A()
157
157
158 In [4]: get_ipython().reset()
158 In [4]: get_ipython().reset()
159 Hi
159 Hi
160
160
161 In [5]: 1+1
161 In [5]: 1+1
162 Out[5]: 2
162 Out[5]: 2
163 """
163 """
164
164
165 # For some tests, it will be handy to organize them in a class with a common
165 # For some tests, it will be handy to organize them in a class with a common
166 # setup that makes a temp file
166 # setup that makes a temp file
167
167
168 class TestMagicRunPass(tt.TempFileMixin):
168 class TestMagicRunPass(tt.TempFileMixin):
169
169
170 def setup(self):
170 def setup(self):
171 """Make a valid python temp file."""
171 """Make a valid python temp file."""
172 self.mktmp('pass\n')
172 self.mktmp('pass\n')
173
173
174 def run_tmpfile(self):
174 def run_tmpfile(self):
175 _ip = get_ipython()
175 _ip = get_ipython()
176 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
176 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
177 # See below and ticket https://bugs.launchpad.net/bugs/366353
177 # See below and ticket https://bugs.launchpad.net/bugs/366353
178 _ip.magic('run %s' % self.fname)
178 _ip.magic('run %s' % self.fname)
179
179
180 def run_tmpfile_p(self):
180 def run_tmpfile_p(self):
181 _ip = get_ipython()
181 _ip = get_ipython()
182 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
182 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
183 # See below and ticket https://bugs.launchpad.net/bugs/366353
183 # See below and ticket https://bugs.launchpad.net/bugs/366353
184 _ip.magic('run -p %s' % self.fname)
184 _ip.magic('run -p %s' % self.fname)
185
185
186 def test_builtins_id(self):
186 def test_builtins_id(self):
187 """Check that %run doesn't damage __builtins__ """
187 """Check that %run doesn't damage __builtins__ """
188 _ip = get_ipython()
188 _ip = get_ipython()
189 # Test that the id of __builtins__ is not modified by %run
189 # Test that the id of __builtins__ is not modified by %run
190 bid1 = id(_ip.user_ns['__builtins__'])
190 bid1 = id(_ip.user_ns['__builtins__'])
191 self.run_tmpfile()
191 self.run_tmpfile()
192 bid2 = id(_ip.user_ns['__builtins__'])
192 bid2 = id(_ip.user_ns['__builtins__'])
193 nt.assert_equal(bid1, bid2)
193 nt.assert_equal(bid1, bid2)
194
194
195 def test_builtins_type(self):
195 def test_builtins_type(self):
196 """Check that the type of __builtins__ doesn't change with %run.
196 """Check that the type of __builtins__ doesn't change with %run.
197
197
198 However, the above could pass if __builtins__ was already modified to
198 However, the above could pass if __builtins__ was already modified to
199 be a dict (it should be a module) by a previous use of %run. So we
199 be a dict (it should be a module) by a previous use of %run. So we
200 also check explicitly that it really is a module:
200 also check explicitly that it really is a module:
201 """
201 """
202 _ip = get_ipython()
202 _ip = get_ipython()
203 self.run_tmpfile()
203 self.run_tmpfile()
204 nt.assert_equal(type(_ip.user_ns['__builtins__']),type(sys))
204 nt.assert_equal(type(_ip.user_ns['__builtins__']),type(sys))
205
205
206 def test_prompts(self):
206 def test_prompts(self):
207 """Test that prompts correctly generate after %run"""
207 """Test that prompts correctly generate after %run"""
208 self.run_tmpfile()
208 self.run_tmpfile()
209 _ip = get_ipython()
209 _ip = get_ipython()
210 p2 = _ip.prompt_manager.render('in2').strip()
210 p2 = _ip.prompt_manager.render('in2').strip()
211 nt.assert_equal(p2[:3], '...')
211 nt.assert_equal(p2[:3], '...')
212
212
213 def test_run_profile( self ):
213 def test_run_profile( self ):
214 """Test that the option -p, which invokes the profiler, do not
214 """Test that the option -p, which invokes the profiler, do not
215 crash by invoking execfile"""
215 crash by invoking execfile"""
216 _ip = get_ipython()
216 _ip = get_ipython()
217 self.run_tmpfile_p()
217 self.run_tmpfile_p()
218
218
219
219
220 class TestMagicRunSimple(tt.TempFileMixin):
220 class TestMagicRunSimple(tt.TempFileMixin):
221
221
222 def test_simpledef(self):
222 def test_simpledef(self):
223 """Test that simple class definitions work."""
223 """Test that simple class definitions work."""
224 src = ("class foo: pass\n"
224 src = ("class foo: pass\n"
225 "def f(): return foo()")
225 "def f(): return foo()")
226 self.mktmp(src)
226 self.mktmp(src)
227 _ip.magic('run %s' % self.fname)
227 _ip.magic('run %s' % self.fname)
228 _ip.run_cell('t = isinstance(f(), foo)')
228 _ip.run_cell('t = isinstance(f(), foo)')
229 nt.assert_true(_ip.user_ns['t'])
229 nt.assert_true(_ip.user_ns['t'])
230
230
231 def test_obj_del(self):
231 def test_obj_del(self):
232 """Test that object's __del__ methods are called on exit."""
232 """Test that object's __del__ methods are called on exit."""
233 if sys.platform == 'win32':
233 if sys.platform == 'win32':
234 try:
234 try:
235 import win32api
235 import win32api
236 except ImportError:
236 except ImportError:
237 raise SkipTest("Test requires pywin32")
237 raise SkipTest("Test requires pywin32")
238 src = ("class A(object):\n"
238 src = ("class A(object):\n"
239 " def __del__(self):\n"
239 " def __del__(self):\n"
240 " print 'object A deleted'\n"
240 " print 'object A deleted'\n"
241 "a = A()\n")
241 "a = A()\n")
242 self.mktmp(py3compat.doctest_refactor_print(src))
242 self.mktmp(py3compat.doctest_refactor_print(src))
243 if dec.module_not_available('sqlite3'):
243 if dec.module_not_available('sqlite3'):
244 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
244 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
245 else:
245 else:
246 err = None
246 err = None
247 tt.ipexec_validate(self.fname, 'object A deleted', err)
247 tt.ipexec_validate(self.fname, 'object A deleted', err)
248
248
249 def test_aggressive_namespace_cleanup(self):
249 def test_aggressive_namespace_cleanup(self):
250 """Test that namespace cleanup is not too aggressive GH-238
250 """Test that namespace cleanup is not too aggressive GH-238
251
251
252 Returning from another run magic deletes the namespace"""
252 Returning from another run magic deletes the namespace"""
253 # see ticket https://github.com/ipython/ipython/issues/238
253 # see ticket https://github.com/ipython/ipython/issues/238
254 class secondtmp(tt.TempFileMixin): pass
254 class secondtmp(tt.TempFileMixin): pass
255 empty = secondtmp()
255 empty = secondtmp()
256 empty.mktmp('')
256 empty.mktmp('')
257 # On Windows, the filename will have \users in it, so we need to use the
257 # On Windows, the filename will have \users in it, so we need to use the
258 # repr so that the \u becomes \\u.
258 # repr so that the \u becomes \\u.
259 src = ("ip = get_ipython()\n"
259 src = ("ip = get_ipython()\n"
260 "for i in range(5):\n"
260 "for i in range(5):\n"
261 " try:\n"
261 " try:\n"
262 " ip.magic(%r)\n"
262 " ip.magic(%r)\n"
263 " except NameError as e:\n"
263 " except NameError as e:\n"
264 " print(i)\n"
264 " print(i)\n"
265 " break\n" % ('run ' + empty.fname))
265 " break\n" % ('run ' + empty.fname))
266 self.mktmp(src)
266 self.mktmp(src)
267 _ip.magic('run %s' % self.fname)
267 _ip.magic('run %s' % self.fname)
268 _ip.run_cell('ip == get_ipython()')
268 _ip.run_cell('ip == get_ipython()')
269 nt.assert_equal(_ip.user_ns['i'], 4)
269 nt.assert_equal(_ip.user_ns['i'], 4)
270
270
271 def test_run_second(self):
271 def test_run_second(self):
272 """Test that running a second file doesn't clobber the first, gh-3547
272 """Test that running a second file doesn't clobber the first, gh-3547
273 """
273 """
274 self.mktmp("avar = 1\n"
274 self.mktmp("avar = 1\n"
275 "def afunc():\n"
275 "def afunc():\n"
276 " return avar\n")
276 " return avar\n")
277
277
278 empty = tt.TempFileMixin()
278 empty = tt.TempFileMixin()
279 empty.mktmp("")
279 empty.mktmp("")
280
280
281 _ip.magic('run %s' % self.fname)
281 _ip.magic('run %s' % self.fname)
282 _ip.magic('run %s' % empty.fname)
282 _ip.magic('run %s' % empty.fname)
283 nt.assert_equal(_ip.user_ns['afunc'](), 1)
283 nt.assert_equal(_ip.user_ns['afunc'](), 1)
284
284
285 @dec.skip_win32
285 @dec.skip_win32
286 def test_tclass(self):
286 def test_tclass(self):
287 mydir = os.path.dirname(__file__)
287 mydir = os.path.dirname(__file__)
288 tc = os.path.join(mydir, 'tclass')
288 tc = os.path.join(mydir, 'tclass')
289 src = ("%%run '%s' C-first\n"
289 src = ("%%run '%s' C-first\n"
290 "%%run '%s' C-second\n"
290 "%%run '%s' C-second\n"
291 "%%run '%s' C-third\n") % (tc, tc, tc)
291 "%%run '%s' C-third\n") % (tc, tc, tc)
292 self.mktmp(src, '.ipy')
292 self.mktmp(src, '.ipy')
293 out = """\
293 out = """\
294 ARGV 1-: ['C-first']
294 ARGV 1-: ['C-first']
295 ARGV 1-: ['C-second']
295 ARGV 1-: ['C-second']
296 tclass.py: deleting object: C-first
296 tclass.py: deleting object: C-first
297 ARGV 1-: ['C-third']
297 ARGV 1-: ['C-third']
298 tclass.py: deleting object: C-second
298 tclass.py: deleting object: C-second
299 tclass.py: deleting object: C-third
299 tclass.py: deleting object: C-third
300 """
300 """
301 if dec.module_not_available('sqlite3'):
301 if dec.module_not_available('sqlite3'):
302 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
302 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
303 else:
303 else:
304 err = None
304 err = None
305 tt.ipexec_validate(self.fname, out, err)
305 tt.ipexec_validate(self.fname, out, err)
306
306
307 def test_run_i_after_reset(self):
307 def test_run_i_after_reset(self):
308 """Check that %run -i still works after %reset (gh-693)"""
308 """Check that %run -i still works after %reset (gh-693)"""
309 src = "yy = zz\n"
309 src = "yy = zz\n"
310 self.mktmp(src)
310 self.mktmp(src)
311 _ip.run_cell("zz = 23")
311 _ip.run_cell("zz = 23")
312 _ip.magic('run -i %s' % self.fname)
312 _ip.magic('run -i %s' % self.fname)
313 nt.assert_equal(_ip.user_ns['yy'], 23)
313 nt.assert_equal(_ip.user_ns['yy'], 23)
314 _ip.magic('reset -f')
314 _ip.magic('reset -f')
315 _ip.run_cell("zz = 23")
315 _ip.run_cell("zz = 23")
316 _ip.magic('run -i %s' % self.fname)
316 _ip.magic('run -i %s' % self.fname)
317 nt.assert_equal(_ip.user_ns['yy'], 23)
317 nt.assert_equal(_ip.user_ns['yy'], 23)
318
318
319 def test_unicode(self):
319 def test_unicode(self):
320 """Check that files in odd encodings are accepted."""
320 """Check that files in odd encodings are accepted."""
321 mydir = os.path.dirname(__file__)
321 mydir = os.path.dirname(__file__)
322 na = os.path.join(mydir, 'nonascii.py')
322 na = os.path.join(mydir, 'nonascii.py')
323 _ip.magic('run "%s"' % na)
323 _ip.magic('run "%s"' % na)
324 nt.assert_equal(_ip.user_ns['u'], u'ΠŽΡ‚β„–Π€')
324 nt.assert_equal(_ip.user_ns['u'], u'ΠŽΡ‚β„–Π€')
325
325
326 def test_run_py_file_attribute(self):
326 def test_run_py_file_attribute(self):
327 """Test handling of `__file__` attribute in `%run <file>.py`."""
327 """Test handling of `__file__` attribute in `%run <file>.py`."""
328 src = "t = __file__\n"
328 src = "t = __file__\n"
329 self.mktmp(src)
329 self.mktmp(src)
330 _missing = object()
330 _missing = object()
331 file1 = _ip.user_ns.get('__file__', _missing)
331 file1 = _ip.user_ns.get('__file__', _missing)
332 _ip.magic('run %s' % self.fname)
332 _ip.magic('run %s' % self.fname)
333 file2 = _ip.user_ns.get('__file__', _missing)
333 file2 = _ip.user_ns.get('__file__', _missing)
334
334
335 # Check that __file__ was equal to the filename in the script's
335 # Check that __file__ was equal to the filename in the script's
336 # namespace.
336 # namespace.
337 nt.assert_equal(_ip.user_ns['t'], self.fname)
337 nt.assert_equal(_ip.user_ns['t'], self.fname)
338
338
339 # Check that __file__ was not leaked back into user_ns.
339 # Check that __file__ was not leaked back into user_ns.
340 nt.assert_equal(file1, file2)
340 nt.assert_equal(file1, file2)
341
341
342 def test_run_ipy_file_attribute(self):
342 def test_run_ipy_file_attribute(self):
343 """Test handling of `__file__` attribute in `%run <file.ipy>`."""
343 """Test handling of `__file__` attribute in `%run <file.ipy>`."""
344 src = "t = __file__\n"
344 src = "t = __file__\n"
345 self.mktmp(src, ext='.ipy')
345 self.mktmp(src, ext='.ipy')
346 _missing = object()
346 _missing = object()
347 file1 = _ip.user_ns.get('__file__', _missing)
347 file1 = _ip.user_ns.get('__file__', _missing)
348 _ip.magic('run %s' % self.fname)
348 _ip.magic('run %s' % self.fname)
349 file2 = _ip.user_ns.get('__file__', _missing)
349 file2 = _ip.user_ns.get('__file__', _missing)
350
350
351 # Check that __file__ was equal to the filename in the script's
351 # Check that __file__ was equal to the filename in the script's
352 # namespace.
352 # namespace.
353 nt.assert_equal(_ip.user_ns['t'], self.fname)
353 nt.assert_equal(_ip.user_ns['t'], self.fname)
354
354
355 # Check that __file__ was not leaked back into user_ns.
355 # Check that __file__ was not leaked back into user_ns.
356 nt.assert_equal(file1, file2)
356 nt.assert_equal(file1, file2)
357
357
358 def test_run_formatting(self):
358 def test_run_formatting(self):
359 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
359 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
360 src = "pass"
360 src = "pass"
361 self.mktmp(src)
361 self.mktmp(src)
362 _ip.magic('run -t -N 1 %s' % self.fname)
362 _ip.magic('run -t -N 1 %s' % self.fname)
363 _ip.magic('run -t -N 10 %s' % self.fname)
363 _ip.magic('run -t -N 10 %s' % self.fname)
364
364
365 def test_ignore_sys_exit(self):
365 def test_ignore_sys_exit(self):
366 """Test the -e option to ignore sys.exit()"""
366 """Test the -e option to ignore sys.exit()"""
367 src = "import sys; sys.exit(1)"
367 src = "import sys; sys.exit(1)"
368 self.mktmp(src)
368 self.mktmp(src)
369 with tt.AssertPrints('SystemExit'):
369 with tt.AssertPrints('SystemExit'):
370 _ip.magic('run %s' % self.fname)
370 _ip.magic('run %s' % self.fname)
371
371
372 with tt.AssertNotPrints('SystemExit'):
372 with tt.AssertNotPrints('SystemExit'):
373 _ip.magic('run -e %s' % self.fname)
373 _ip.magic('run -e %s' % self.fname)
374
374
375 @dec.skip_without('IPython.nbformat.current') # Requires jsonschema
375 def test_run_nb(self):
376 def test_run_nb(self):
376 """Test %run notebook.ipynb"""
377 """Test %run notebook.ipynb"""
377 from IPython.nbformat import current
378 from IPython.nbformat import current
378 nb = current.new_notebook(
379 nb = current.new_notebook(
379 worksheets=[
380 worksheets=[
380 current.new_worksheet(cells=[
381 current.new_worksheet(cells=[
381 current.new_text_cell("The Ultimate Question of Everything"),
382 current.new_text_cell("The Ultimate Question of Everything"),
382 current.new_code_cell("answer=42")
383 current.new_code_cell("answer=42")
383 ])
384 ])
384 ]
385 ]
385 )
386 )
386 src = current.writes(nb, 'json')
387 src = current.writes(nb, 'json')
387 self.mktmp(src, ext='.ipynb')
388 self.mktmp(src, ext='.ipynb')
388
389
389 _ip.magic("run %s" % self.fname)
390 _ip.magic("run %s" % self.fname)
390
391
391 nt.assert_equal(_ip.user_ns['answer'], 42)
392 nt.assert_equal(_ip.user_ns['answer'], 42)
392
393
393
394
394
395
395 class TestMagicRunWithPackage(unittest.TestCase):
396 class TestMagicRunWithPackage(unittest.TestCase):
396
397
397 def writefile(self, name, content):
398 def writefile(self, name, content):
398 path = os.path.join(self.tempdir.name, name)
399 path = os.path.join(self.tempdir.name, name)
399 d = os.path.dirname(path)
400 d = os.path.dirname(path)
400 if not os.path.isdir(d):
401 if not os.path.isdir(d):
401 os.makedirs(d)
402 os.makedirs(d)
402 with open(path, 'w') as f:
403 with open(path, 'w') as f:
403 f.write(textwrap.dedent(content))
404 f.write(textwrap.dedent(content))
404
405
405 def setUp(self):
406 def setUp(self):
406 self.package = package = 'tmp{0}'.format(repr(random.random())[2:])
407 self.package = package = 'tmp{0}'.format(repr(random.random())[2:])
407 """Temporary valid python package name."""
408 """Temporary valid python package name."""
408
409
409 self.value = int(random.random() * 10000)
410 self.value = int(random.random() * 10000)
410
411
411 self.tempdir = TemporaryDirectory()
412 self.tempdir = TemporaryDirectory()
412 self.__orig_cwd = py3compat.getcwd()
413 self.__orig_cwd = py3compat.getcwd()
413 sys.path.insert(0, self.tempdir.name)
414 sys.path.insert(0, self.tempdir.name)
414
415
415 self.writefile(os.path.join(package, '__init__.py'), '')
416 self.writefile(os.path.join(package, '__init__.py'), '')
416 self.writefile(os.path.join(package, 'sub.py'), """
417 self.writefile(os.path.join(package, 'sub.py'), """
417 x = {0!r}
418 x = {0!r}
418 """.format(self.value))
419 """.format(self.value))
419 self.writefile(os.path.join(package, 'relative.py'), """
420 self.writefile(os.path.join(package, 'relative.py'), """
420 from .sub import x
421 from .sub import x
421 """)
422 """)
422 self.writefile(os.path.join(package, 'absolute.py'), """
423 self.writefile(os.path.join(package, 'absolute.py'), """
423 from {0}.sub import x
424 from {0}.sub import x
424 """.format(package))
425 """.format(package))
425
426
426 def tearDown(self):
427 def tearDown(self):
427 os.chdir(self.__orig_cwd)
428 os.chdir(self.__orig_cwd)
428 sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
429 sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
429 self.tempdir.cleanup()
430 self.tempdir.cleanup()
430
431
431 def check_run_submodule(self, submodule, opts=''):
432 def check_run_submodule(self, submodule, opts=''):
432 _ip.user_ns.pop('x', None)
433 _ip.user_ns.pop('x', None)
433 _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts))
434 _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts))
434 self.assertEqual(_ip.user_ns['x'], self.value,
435 self.assertEqual(_ip.user_ns['x'], self.value,
435 'Variable `x` is not loaded from module `{0}`.'
436 'Variable `x` is not loaded from module `{0}`.'
436 .format(submodule))
437 .format(submodule))
437
438
438 def test_run_submodule_with_absolute_import(self):
439 def test_run_submodule_with_absolute_import(self):
439 self.check_run_submodule('absolute')
440 self.check_run_submodule('absolute')
440
441
441 def test_run_submodule_with_relative_import(self):
442 def test_run_submodule_with_relative_import(self):
442 """Run submodule that has a relative import statement (#2727)."""
443 """Run submodule that has a relative import statement (#2727)."""
443 self.check_run_submodule('relative')
444 self.check_run_submodule('relative')
444
445
445 def test_prun_submodule_with_absolute_import(self):
446 def test_prun_submodule_with_absolute_import(self):
446 self.check_run_submodule('absolute', '-p')
447 self.check_run_submodule('absolute', '-p')
447
448
448 def test_prun_submodule_with_relative_import(self):
449 def test_prun_submodule_with_relative_import(self):
449 self.check_run_submodule('relative', '-p')
450 self.check_run_submodule('relative', '-p')
450
451
451 def with_fake_debugger(func):
452 def with_fake_debugger(func):
452 @functools.wraps(func)
453 @functools.wraps(func)
453 def wrapper(*args, **kwds):
454 def wrapper(*args, **kwds):
454 with tt.monkeypatch(debugger.Pdb, 'run', staticmethod(eval)):
455 with tt.monkeypatch(debugger.Pdb, 'run', staticmethod(eval)):
455 return func(*args, **kwds)
456 return func(*args, **kwds)
456 return wrapper
457 return wrapper
457
458
458 @with_fake_debugger
459 @with_fake_debugger
459 def test_debug_run_submodule_with_absolute_import(self):
460 def test_debug_run_submodule_with_absolute_import(self):
460 self.check_run_submodule('absolute', '-d')
461 self.check_run_submodule('absolute', '-d')
461
462
462 @with_fake_debugger
463 @with_fake_debugger
463 def test_debug_run_submodule_with_relative_import(self):
464 def test_debug_run_submodule_with_relative_import(self):
464 self.check_run_submodule('relative', '-d')
465 self.check_run_submodule('relative', '-d')
465
466
466 def test_run__name__():
467 def test_run__name__():
467 with TemporaryDirectory() as td:
468 with TemporaryDirectory() as td:
468 path = pjoin(td, 'foo.py')
469 path = pjoin(td, 'foo.py')
469 with open(path, 'w') as f:
470 with open(path, 'w') as f:
470 f.write("q = __name__")
471 f.write("q = __name__")
471
472
472 _ip.user_ns.pop('q', None)
473 _ip.user_ns.pop('q', None)
473 _ip.magic('run {}'.format(path))
474 _ip.magic('run {}'.format(path))
474 nt.assert_equal(_ip.user_ns.pop('q'), '__main__')
475 nt.assert_equal(_ip.user_ns.pop('q'), '__main__')
475
476
476 _ip.magic('run -n {}'.format(path))
477 _ip.magic('run -n {}'.format(path))
477 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
478 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
478
479
479 def test_run_tb():
480 def test_run_tb():
480 """Test traceback offset in %run"""
481 """Test traceback offset in %run"""
481 with TemporaryDirectory() as td:
482 with TemporaryDirectory() as td:
482 path = pjoin(td, 'foo.py')
483 path = pjoin(td, 'foo.py')
483 with open(path, 'w') as f:
484 with open(path, 'w') as f:
484 f.write('\n'.join([
485 f.write('\n'.join([
485 "def foo():",
486 "def foo():",
486 " return bar()",
487 " return bar()",
487 "def bar():",
488 "def bar():",
488 " raise RuntimeError('hello!')",
489 " raise RuntimeError('hello!')",
489 "foo()",
490 "foo()",
490 ]))
491 ]))
491 with capture_output() as io:
492 with capture_output() as io:
492 _ip.magic('run {}'.format(path))
493 _ip.magic('run {}'.format(path))
493 out = io.stdout
494 out = io.stdout
494 nt.assert_not_in("execfile", out)
495 nt.assert_not_in("execfile", out)
495 nt.assert_in("RuntimeError", out)
496 nt.assert_in("RuntimeError", out)
496 nt.assert_equal(out.count("---->"), 3)
497 nt.assert_equal(out.count("---->"), 3)
497
498
498 @dec.knownfailureif(sys.platform == 'win32', "writes to io.stdout aren't captured on Windows")
499 @dec.knownfailureif(sys.platform == 'win32', "writes to io.stdout aren't captured on Windows")
499 def test_script_tb():
500 def test_script_tb():
500 """Test traceback offset in `ipython script.py`"""
501 """Test traceback offset in `ipython script.py`"""
501 with TemporaryDirectory() as td:
502 with TemporaryDirectory() as td:
502 path = pjoin(td, 'foo.py')
503 path = pjoin(td, 'foo.py')
503 with open(path, 'w') as f:
504 with open(path, 'w') as f:
504 f.write('\n'.join([
505 f.write('\n'.join([
505 "def foo():",
506 "def foo():",
506 " return bar()",
507 " return bar()",
507 "def bar():",
508 "def bar():",
508 " raise RuntimeError('hello!')",
509 " raise RuntimeError('hello!')",
509 "foo()",
510 "foo()",
510 ]))
511 ]))
511 out, err = tt.ipexec(path)
512 out, err = tt.ipexec(path)
512 nt.assert_not_in("execfile", out)
513 nt.assert_not_in("execfile", out)
513 nt.assert_in("RuntimeError", out)
514 nt.assert_in("RuntimeError", out)
514 nt.assert_equal(out.count("---->"), 3)
515 nt.assert_equal(out.count("---->"), 3)
515
516
@@ -1,40 +1,42 b''
1 """Test help output of various IPython entry points"""
1 """Test help output of various IPython entry points"""
2
2
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (C) 2013 The IPython Development Team
4 # Copyright (C) 2013 The IPython Development Team
5 #
5 #
6 # Distributed under the terms of the BSD License. The full license is in
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING, distributed as part of this software.
7 # the file COPYING, distributed as part of this software.
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 import IPython.testing.tools as tt
14 import IPython.testing.tools as tt
15 from IPython.testing.decorators import skip_without
15
16
16 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
17 # Tests
18 # Tests
18 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
19
20
20
21
21 def test_ipython_help():
22 def test_ipython_help():
22 tt.help_all_output_test()
23 tt.help_all_output_test()
23
24
24 def test_profile_help():
25 def test_profile_help():
25 tt.help_all_output_test("profile")
26 tt.help_all_output_test("profile")
26
27
27 def test_profile_list_help():
28 def test_profile_list_help():
28 tt.help_all_output_test("profile list")
29 tt.help_all_output_test("profile list")
29
30
30 def test_profile_create_help():
31 def test_profile_create_help():
31 tt.help_all_output_test("profile create")
32 tt.help_all_output_test("profile create")
32
33
33 def test_locate_help():
34 def test_locate_help():
34 tt.help_all_output_test("locate")
35 tt.help_all_output_test("locate")
35
36
36 def test_locate_profile_help():
37 def test_locate_profile_help():
37 tt.help_all_output_test("locate profile")
38 tt.help_all_output_test("locate profile")
38
39
40 @skip_without('IPython.nbformat.current') # Requires jsonschema to be installed
39 def test_trust_help():
41 def test_trust_help():
40 tt.help_all_output_test("trust")
42 tt.help_all_output_test("trust")
General Comments 0
You need to be logged in to leave comments. Login now