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