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