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