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