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