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