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