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