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