##// END OF EJS Templates
Add first set of cell magic tests.
Fernando Perez -
Show More
@@ -1,492 +1,537 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 import nose.tools as nt
18 import nose.tools as nt
19
19
20 from IPython.core import magic
20 from IPython.core import magic
21 from IPython.core.magic import (Magics, magics_class, line_magic,
21 from IPython.core.magic import (Magics, magics_class, line_magic,
22 cell_magic, line_cell_magic,
22 cell_magic, line_cell_magic,
23 register_line_magic, register_cell_magic,
23 register_line_magic, register_cell_magic,
24 register_line_cell_magic)
24 register_line_cell_magic)
25 from IPython.core.magics import execution
25 from IPython.core.magics import execution
26 from IPython.nbformat.v3.tests.nbexamples import nb0
26 from IPython.nbformat.v3.tests.nbexamples import nb0
27 from IPython.nbformat import current
27 from IPython.nbformat import current
28 from IPython.testing import decorators as dec
28 from IPython.testing import decorators as dec
29 from IPython.testing import tools as tt
29 from IPython.testing import tools as tt
30 from IPython.utils import py3compat
30 from IPython.utils import py3compat
31 from IPython.utils.tempdir import TemporaryDirectory
31 from IPython.utils.tempdir import TemporaryDirectory
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # Test functions begin
34 # Test functions begin
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36
36
37 @magic.magics_class
37 @magic.magics_class
38 class DummyMagics(magic.Magics): pass
38 class DummyMagics(magic.Magics): pass
39
39
40 def test_rehashx():
40 def test_rehashx():
41 # clear up everything
41 # clear up everything
42 _ip = get_ipython()
42 _ip = get_ipython()
43 _ip.alias_manager.alias_table.clear()
43 _ip.alias_manager.alias_table.clear()
44 del _ip.db['syscmdlist']
44 del _ip.db['syscmdlist']
45
45
46 _ip.magic('rehashx')
46 _ip.magic('rehashx')
47 # Practically ALL ipython development systems will have more than 10 aliases
47 # Practically ALL ipython development systems will have more than 10 aliases
48
48
49 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
49 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
50 for key, val in _ip.alias_manager.alias_table.iteritems():
50 for key, val in _ip.alias_manager.alias_table.iteritems():
51 # we must strip dots from alias names
51 # we must strip dots from alias names
52 nt.assert_true('.' not in key)
52 nt.assert_true('.' not in key)
53
53
54 # rehashx must fill up syscmdlist
54 # rehashx must fill up syscmdlist
55 scoms = _ip.db['syscmdlist']
55 scoms = _ip.db['syscmdlist']
56 yield (nt.assert_true, len(scoms) > 10)
56 yield (nt.assert_true, len(scoms) > 10)
57
57
58
58
59 def test_magic_parse_options():
59 def test_magic_parse_options():
60 """Test that we don't mangle paths when parsing magic options."""
60 """Test that we don't mangle paths when parsing magic options."""
61 ip = get_ipython()
61 ip = get_ipython()
62 path = 'c:\\x'
62 path = 'c:\\x'
63 m = DummyMagics(ip)
63 m = DummyMagics(ip)
64 opts = m.parse_options('-f %s' % path,'f:')[0]
64 opts = m.parse_options('-f %s' % path,'f:')[0]
65 # argv splitting is os-dependent
65 # argv splitting is os-dependent
66 if os.name == 'posix':
66 if os.name == 'posix':
67 expected = 'c:x'
67 expected = 'c:x'
68 else:
68 else:
69 expected = path
69 expected = path
70 nt.assert_equals(opts['f'], expected)
70 nt.assert_equals(opts['f'], expected)
71
71
72
72
73 @dec.skip_without('sqlite3')
73 @dec.skip_without('sqlite3')
74 def doctest_hist_f():
74 def doctest_hist_f():
75 """Test %hist -f with temporary filename.
75 """Test %hist -f with temporary filename.
76
76
77 In [9]: import tempfile
77 In [9]: import tempfile
78
78
79 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
79 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
80
80
81 In [11]: %hist -nl -f $tfile 3
81 In [11]: %hist -nl -f $tfile 3
82
82
83 In [13]: import os; os.unlink(tfile)
83 In [13]: import os; os.unlink(tfile)
84 """
84 """
85
85
86
86
87 @dec.skip_without('sqlite3')
87 @dec.skip_without('sqlite3')
88 def doctest_hist_r():
88 def doctest_hist_r():
89 """Test %hist -r
89 """Test %hist -r
90
90
91 XXX - This test is not recording the output correctly. For some reason, in
91 XXX - This test is not recording the output correctly. For some reason, in
92 testing mode the raw history isn't getting populated. No idea why.
92 testing mode the raw history isn't getting populated. No idea why.
93 Disabling the output checking for now, though at least we do run it.
93 Disabling the output checking for now, though at least we do run it.
94
94
95 In [1]: 'hist' in _ip.lsmagic()
95 In [1]: 'hist' in _ip.lsmagic()
96 Out[1]: True
96 Out[1]: True
97
97
98 In [2]: x=1
98 In [2]: x=1
99
99
100 In [3]: %hist -rl 2
100 In [3]: %hist -rl 2
101 x=1 # random
101 x=1 # random
102 %hist -r 2
102 %hist -r 2
103 """
103 """
104
104
105
105
106 @dec.skip_without('sqlite3')
106 @dec.skip_without('sqlite3')
107 def doctest_hist_op():
107 def doctest_hist_op():
108 """Test %hist -op
108 """Test %hist -op
109
109
110 In [1]: class b(float):
110 In [1]: class b(float):
111 ...: pass
111 ...: pass
112 ...:
112 ...:
113
113
114 In [2]: class s(object):
114 In [2]: class s(object):
115 ...: def __str__(self):
115 ...: def __str__(self):
116 ...: return 's'
116 ...: return 's'
117 ...:
117 ...:
118
118
119 In [3]:
119 In [3]:
120
120
121 In [4]: class r(b):
121 In [4]: class r(b):
122 ...: def __repr__(self):
122 ...: def __repr__(self):
123 ...: return 'r'
123 ...: return 'r'
124 ...:
124 ...:
125
125
126 In [5]: class sr(s,r): pass
126 In [5]: class sr(s,r): pass
127 ...:
127 ...:
128
128
129 In [6]:
129 In [6]:
130
130
131 In [7]: bb=b()
131 In [7]: bb=b()
132
132
133 In [8]: ss=s()
133 In [8]: ss=s()
134
134
135 In [9]: rr=r()
135 In [9]: rr=r()
136
136
137 In [10]: ssrr=sr()
137 In [10]: ssrr=sr()
138
138
139 In [11]: 4.5
139 In [11]: 4.5
140 Out[11]: 4.5
140 Out[11]: 4.5
141
141
142 In [12]: str(ss)
142 In [12]: str(ss)
143 Out[12]: 's'
143 Out[12]: 's'
144
144
145 In [13]:
145 In [13]:
146
146
147 In [14]: %hist -op
147 In [14]: %hist -op
148 >>> class b:
148 >>> class b:
149 ... pass
149 ... pass
150 ...
150 ...
151 >>> class s(b):
151 >>> class s(b):
152 ... def __str__(self):
152 ... def __str__(self):
153 ... return 's'
153 ... return 's'
154 ...
154 ...
155 >>>
155 >>>
156 >>> class r(b):
156 >>> class r(b):
157 ... def __repr__(self):
157 ... def __repr__(self):
158 ... return 'r'
158 ... return 'r'
159 ...
159 ...
160 >>> class sr(s,r): pass
160 >>> class sr(s,r): pass
161 >>>
161 >>>
162 >>> bb=b()
162 >>> bb=b()
163 >>> ss=s()
163 >>> ss=s()
164 >>> rr=r()
164 >>> rr=r()
165 >>> ssrr=sr()
165 >>> ssrr=sr()
166 >>> 4.5
166 >>> 4.5
167 4.5
167 4.5
168 >>> str(ss)
168 >>> str(ss)
169 's'
169 's'
170 >>>
170 >>>
171 """
171 """
172
172
173
173
174 @dec.skip_without('sqlite3')
174 @dec.skip_without('sqlite3')
175 def test_macro():
175 def test_macro():
176 ip = get_ipython()
176 ip = get_ipython()
177 ip.history_manager.reset() # Clear any existing history.
177 ip.history_manager.reset() # Clear any existing history.
178 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
178 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
179 for i, cmd in enumerate(cmds, start=1):
179 for i, cmd in enumerate(cmds, start=1):
180 ip.history_manager.store_inputs(i, cmd)
180 ip.history_manager.store_inputs(i, cmd)
181 ip.magic("macro test 1-3")
181 ip.magic("macro test 1-3")
182 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
182 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
183
183
184 # List macros.
184 # List macros.
185 assert "test" in ip.magic("macro")
185 assert "test" in ip.magic("macro")
186
186
187
187
188 @dec.skip_without('sqlite3')
188 @dec.skip_without('sqlite3')
189 def test_macro_run():
189 def test_macro_run():
190 """Test that we can run a multi-line macro successfully."""
190 """Test that we can run a multi-line macro successfully."""
191 ip = get_ipython()
191 ip = get_ipython()
192 ip.history_manager.reset()
192 ip.history_manager.reset()
193 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
193 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
194 "%macro test 2-3"]
194 "%macro test 2-3"]
195 for cmd in cmds:
195 for cmd in cmds:
196 ip.run_cell(cmd, store_history=True)
196 ip.run_cell(cmd, store_history=True)
197 nt.assert_equal(ip.user_ns["test"].value,
197 nt.assert_equal(ip.user_ns["test"].value,
198 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
198 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
199 with tt.AssertPrints("12"):
199 with tt.AssertPrints("12"):
200 ip.run_cell("test")
200 ip.run_cell("test")
201 with tt.AssertPrints("13"):
201 with tt.AssertPrints("13"):
202 ip.run_cell("test")
202 ip.run_cell("test")
203
203
204
204
205 @dec.skipif_not_numpy
205 @dec.skipif_not_numpy
206 def test_numpy_reset_array_undec():
206 def test_numpy_reset_array_undec():
207 "Test '%reset array' functionality"
207 "Test '%reset array' functionality"
208 _ip.ex('import numpy as np')
208 _ip.ex('import numpy as np')
209 _ip.ex('a = np.empty(2)')
209 _ip.ex('a = np.empty(2)')
210 yield (nt.assert_true, 'a' in _ip.user_ns)
210 yield (nt.assert_true, 'a' in _ip.user_ns)
211 _ip.magic('reset -f array')
211 _ip.magic('reset -f array')
212 yield (nt.assert_false, 'a' in _ip.user_ns)
212 yield (nt.assert_false, 'a' in _ip.user_ns)
213
213
214 def test_reset_out():
214 def test_reset_out():
215 "Test '%reset out' magic"
215 "Test '%reset out' magic"
216 _ip.run_cell("parrot = 'dead'", store_history=True)
216 _ip.run_cell("parrot = 'dead'", store_history=True)
217 # test '%reset -f out', make an Out prompt
217 # test '%reset -f out', make an Out prompt
218 _ip.run_cell("parrot", store_history=True)
218 _ip.run_cell("parrot", store_history=True)
219 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
219 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
220 _ip.magic('reset -f out')
220 _ip.magic('reset -f out')
221 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
221 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
222 nt.assert_true(len(_ip.user_ns['Out']) == 0)
222 nt.assert_true(len(_ip.user_ns['Out']) == 0)
223
223
224 def test_reset_in():
224 def test_reset_in():
225 "Test '%reset in' magic"
225 "Test '%reset in' magic"
226 # test '%reset -f in'
226 # test '%reset -f in'
227 _ip.run_cell("parrot", store_history=True)
227 _ip.run_cell("parrot", store_history=True)
228 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
228 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
229 _ip.magic('%reset -f in')
229 _ip.magic('%reset -f in')
230 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
230 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
231 nt.assert_true(len(set(_ip.user_ns['In'])) == 1)
231 nt.assert_true(len(set(_ip.user_ns['In'])) == 1)
232
232
233 def test_reset_dhist():
233 def test_reset_dhist():
234 "Test '%reset dhist' magic"
234 "Test '%reset dhist' magic"
235 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
235 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
236 _ip.magic('cd ' + os.path.dirname(nt.__file__))
236 _ip.magic('cd ' + os.path.dirname(nt.__file__))
237 _ip.magic('cd -')
237 _ip.magic('cd -')
238 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
238 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
239 _ip.magic('reset -f dhist')
239 _ip.magic('reset -f dhist')
240 nt.assert_true(len(_ip.user_ns['_dh']) == 0)
240 nt.assert_true(len(_ip.user_ns['_dh']) == 0)
241 _ip.run_cell("_dh = [d for d in tmp]") #restore
241 _ip.run_cell("_dh = [d for d in tmp]") #restore
242
242
243 def test_reset_in_length():
243 def test_reset_in_length():
244 "Test that '%reset in' preserves In[] length"
244 "Test that '%reset in' preserves In[] length"
245 _ip.run_cell("print 'foo'")
245 _ip.run_cell("print 'foo'")
246 _ip.run_cell("reset -f in")
246 _ip.run_cell("reset -f in")
247 nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1)
247 nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1)
248
248
249 def test_time():
249 def test_time():
250 _ip.magic('time None')
250 _ip.magic('time None')
251
251
252 def test_tb_syntaxerror():
252 def test_tb_syntaxerror():
253 """test %tb after a SyntaxError"""
253 """test %tb after a SyntaxError"""
254 ip = get_ipython()
254 ip = get_ipython()
255 ip.run_cell("for")
255 ip.run_cell("for")
256
256
257 # trap and validate stdout
257 # trap and validate stdout
258 save_stdout = sys.stdout
258 save_stdout = sys.stdout
259 try:
259 try:
260 sys.stdout = StringIO()
260 sys.stdout = StringIO()
261 ip.run_cell("%tb")
261 ip.run_cell("%tb")
262 out = sys.stdout.getvalue()
262 out = sys.stdout.getvalue()
263 finally:
263 finally:
264 sys.stdout = save_stdout
264 sys.stdout = save_stdout
265 # trim output, and only check the last line
265 # trim output, and only check the last line
266 last_line = out.rstrip().splitlines()[-1].strip()
266 last_line = out.rstrip().splitlines()[-1].strip()
267 nt.assert_equals(last_line, "SyntaxError: invalid syntax")
267 nt.assert_equals(last_line, "SyntaxError: invalid syntax")
268
268
269
269
270 @py3compat.doctest_refactor_print
270 @py3compat.doctest_refactor_print
271 def doctest_time():
271 def doctest_time():
272 """
272 """
273 In [10]: %time None
273 In [10]: %time None
274 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
274 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
275 Wall time: 0.00 s
275 Wall time: 0.00 s
276
276
277 In [11]: def f(kmjy):
277 In [11]: def f(kmjy):
278 ....: %time print 2*kmjy
278 ....: %time print 2*kmjy
279
279
280 In [12]: f(3)
280 In [12]: f(3)
281 6
281 6
282 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
282 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
283 Wall time: 0.00 s
283 Wall time: 0.00 s
284 """
284 """
285
285
286
286
287 def test_doctest_mode():
287 def test_doctest_mode():
288 "Toggle doctest_mode twice, it should be a no-op and run without error"
288 "Toggle doctest_mode twice, it should be a no-op and run without error"
289 _ip.magic('doctest_mode')
289 _ip.magic('doctest_mode')
290 _ip.magic('doctest_mode')
290 _ip.magic('doctest_mode')
291
291
292
292
293 def test_parse_options():
293 def test_parse_options():
294 """Tests for basic options parsing in magics."""
294 """Tests for basic options parsing in magics."""
295 # These are only the most minimal of tests, more should be added later. At
295 # These are only the most minimal of tests, more should be added later. At
296 # the very least we check that basic text/unicode calls work OK.
296 # the very least we check that basic text/unicode calls work OK.
297 m = DummyMagics(_ip)
297 m = DummyMagics(_ip)
298 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
298 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
299 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
299 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
300
300
301
301
302 def test_dirops():
302 def test_dirops():
303 """Test various directory handling operations."""
303 """Test various directory handling operations."""
304 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
304 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
305 curpath = os.getcwdu
305 curpath = os.getcwdu
306 startdir = os.getcwdu()
306 startdir = os.getcwdu()
307 ipdir = os.path.realpath(_ip.ipython_dir)
307 ipdir = os.path.realpath(_ip.ipython_dir)
308 try:
308 try:
309 _ip.magic('cd "%s"' % ipdir)
309 _ip.magic('cd "%s"' % ipdir)
310 nt.assert_equal(curpath(), ipdir)
310 nt.assert_equal(curpath(), ipdir)
311 _ip.magic('cd -')
311 _ip.magic('cd -')
312 nt.assert_equal(curpath(), startdir)
312 nt.assert_equal(curpath(), startdir)
313 _ip.magic('pushd "%s"' % ipdir)
313 _ip.magic('pushd "%s"' % ipdir)
314 nt.assert_equal(curpath(), ipdir)
314 nt.assert_equal(curpath(), ipdir)
315 _ip.magic('popd')
315 _ip.magic('popd')
316 nt.assert_equal(curpath(), startdir)
316 nt.assert_equal(curpath(), startdir)
317 finally:
317 finally:
318 os.chdir(startdir)
318 os.chdir(startdir)
319
319
320
320
321 def test_xmode():
321 def test_xmode():
322 # Calling xmode three times should be a no-op
322 # Calling xmode three times should be a no-op
323 xmode = _ip.InteractiveTB.mode
323 xmode = _ip.InteractiveTB.mode
324 for i in range(3):
324 for i in range(3):
325 _ip.magic("xmode")
325 _ip.magic("xmode")
326 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
326 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
327
327
328 def test_reset_hard():
328 def test_reset_hard():
329 monitor = []
329 monitor = []
330 class A(object):
330 class A(object):
331 def __del__(self):
331 def __del__(self):
332 monitor.append(1)
332 monitor.append(1)
333 def __repr__(self):
333 def __repr__(self):
334 return "<A instance>"
334 return "<A instance>"
335
335
336 _ip.user_ns["a"] = A()
336 _ip.user_ns["a"] = A()
337 _ip.run_cell("a")
337 _ip.run_cell("a")
338
338
339 nt.assert_equal(monitor, [])
339 nt.assert_equal(monitor, [])
340 _ip.magic("reset -f")
340 _ip.magic("reset -f")
341 nt.assert_equal(monitor, [1])
341 nt.assert_equal(monitor, [1])
342
342
343 class TestXdel(tt.TempFileMixin):
343 class TestXdel(tt.TempFileMixin):
344 def test_xdel(self):
344 def test_xdel(self):
345 """Test that references from %run are cleared by xdel."""
345 """Test that references from %run are cleared by xdel."""
346 src = ("class A(object):\n"
346 src = ("class A(object):\n"
347 " monitor = []\n"
347 " monitor = []\n"
348 " def __del__(self):\n"
348 " def __del__(self):\n"
349 " self.monitor.append(1)\n"
349 " self.monitor.append(1)\n"
350 "a = A()\n")
350 "a = A()\n")
351 self.mktmp(src)
351 self.mktmp(src)
352 # %run creates some hidden references...
352 # %run creates some hidden references...
353 _ip.magic("run %s" % self.fname)
353 _ip.magic("run %s" % self.fname)
354 # ... as does the displayhook.
354 # ... as does the displayhook.
355 _ip.run_cell("a")
355 _ip.run_cell("a")
356
356
357 monitor = _ip.user_ns["A"].monitor
357 monitor = _ip.user_ns["A"].monitor
358 nt.assert_equal(monitor, [])
358 nt.assert_equal(monitor, [])
359
359
360 _ip.magic("xdel a")
360 _ip.magic("xdel a")
361
361
362 # Check that a's __del__ method has been called.
362 # Check that a's __del__ method has been called.
363 nt.assert_equal(monitor, [1])
363 nt.assert_equal(monitor, [1])
364
364
365 def doctest_who():
365 def doctest_who():
366 """doctest for %who
366 """doctest for %who
367
367
368 In [1]: %reset -f
368 In [1]: %reset -f
369
369
370 In [2]: alpha = 123
370 In [2]: alpha = 123
371
371
372 In [3]: beta = 'beta'
372 In [3]: beta = 'beta'
373
373
374 In [4]: %who int
374 In [4]: %who int
375 alpha
375 alpha
376
376
377 In [5]: %who str
377 In [5]: %who str
378 beta
378 beta
379
379
380 In [6]: %whos
380 In [6]: %whos
381 Variable Type Data/Info
381 Variable Type Data/Info
382 ----------------------------
382 ----------------------------
383 alpha int 123
383 alpha int 123
384 beta str beta
384 beta str beta
385
385
386 In [7]: %who_ls
386 In [7]: %who_ls
387 Out[7]: ['alpha', 'beta']
387 Out[7]: ['alpha', 'beta']
388 """
388 """
389
389
390 def test_whos():
390 def test_whos():
391 """Check that whos is protected against objects where repr() fails."""
391 """Check that whos is protected against objects where repr() fails."""
392 class A(object):
392 class A(object):
393 def __repr__(self):
393 def __repr__(self):
394 raise Exception()
394 raise Exception()
395 _ip.user_ns['a'] = A()
395 _ip.user_ns['a'] = A()
396 _ip.magic("whos")
396 _ip.magic("whos")
397
397
398 @py3compat.u_format
398 @py3compat.u_format
399 def doctest_precision():
399 def doctest_precision():
400 """doctest for %precision
400 """doctest for %precision
401
401
402 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
402 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
403
403
404 In [2]: %precision 5
404 In [2]: %precision 5
405 Out[2]: {u}'%.5f'
405 Out[2]: {u}'%.5f'
406
406
407 In [3]: f.float_format
407 In [3]: f.float_format
408 Out[3]: {u}'%.5f'
408 Out[3]: {u}'%.5f'
409
409
410 In [4]: %precision %e
410 In [4]: %precision %e
411 Out[4]: {u}'%e'
411 Out[4]: {u}'%e'
412
412
413 In [5]: f(3.1415927)
413 In [5]: f(3.1415927)
414 Out[5]: {u}'3.141593e+00'
414 Out[5]: {u}'3.141593e+00'
415 """
415 """
416
416
417 def test_psearch():
417 def test_psearch():
418 with tt.AssertPrints("dict.fromkeys"):
418 with tt.AssertPrints("dict.fromkeys"):
419 _ip.run_cell("dict.fr*?")
419 _ip.run_cell("dict.fr*?")
420
420
421 def test_timeit_shlex():
421 def test_timeit_shlex():
422 """test shlex issues with timeit (#1109)"""
422 """test shlex issues with timeit (#1109)"""
423 _ip.ex("def f(*a,**kw): pass")
423 _ip.ex("def f(*a,**kw): pass")
424 _ip.magic('timeit -n1 "this is a bug".count(" ")')
424 _ip.magic('timeit -n1 "this is a bug".count(" ")')
425 _ip.magic('timeit -r1 -n1 f(" ", 1)')
425 _ip.magic('timeit -r1 -n1 f(" ", 1)')
426 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
426 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
427 _ip.magic('timeit -r1 -n1 ("a " + "b")')
427 _ip.magic('timeit -r1 -n1 ("a " + "b")')
428 _ip.magic('timeit -r1 -n1 f("a " + "b")')
428 _ip.magic('timeit -r1 -n1 f("a " + "b")')
429 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
429 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
430
430
431
431
432 def test_timeit_arguments():
432 def test_timeit_arguments():
433 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
433 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
434 _ip.magic("timeit ('#')")
434 _ip.magic("timeit ('#')")
435
435
436
436
437 @dec.skipif(execution.profile is None)
437 @dec.skipif(execution.profile is None)
438 def test_prun_quotes():
438 def test_prun_quotes():
439 "Test that prun does not clobber string escapes (GH #1302)"
439 "Test that prun does not clobber string escapes (GH #1302)"
440 _ip.magic("prun -q x = '\t'")
440 _ip.magic("prun -q x = '\t'")
441 nt.assert_equal(_ip.user_ns['x'], '\t')
441 nt.assert_equal(_ip.user_ns['x'], '\t')
442
442
443 def test_extension():
443 def test_extension():
444 tmpdir = TemporaryDirectory()
444 tmpdir = TemporaryDirectory()
445 orig_ipython_dir = _ip.ipython_dir
445 orig_ipython_dir = _ip.ipython_dir
446 try:
446 try:
447 _ip.ipython_dir = tmpdir.name
447 _ip.ipython_dir = tmpdir.name
448 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
448 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
449 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
449 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
450 _ip.magic("install_ext %s" % url)
450 _ip.magic("install_ext %s" % url)
451 _ip.user_ns.pop('arq', None)
451 _ip.user_ns.pop('arq', None)
452 _ip.magic("load_ext daft_extension")
452 _ip.magic("load_ext daft_extension")
453 tt.assert_equal(_ip.user_ns['arq'], 185)
453 tt.assert_equal(_ip.user_ns['arq'], 185)
454 _ip.magic("unload_ext daft_extension")
454 _ip.magic("unload_ext daft_extension")
455 assert 'arq' not in _ip.user_ns
455 assert 'arq' not in _ip.user_ns
456 finally:
456 finally:
457 _ip.ipython_dir = orig_ipython_dir
457 _ip.ipython_dir = orig_ipython_dir
458
458
459 def test_notebook_export_json():
459 def test_notebook_export_json():
460 with TemporaryDirectory() as td:
460 with TemporaryDirectory() as td:
461 outfile = os.path.join(td, "nb.ipynb")
461 outfile = os.path.join(td, "nb.ipynb")
462 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
462 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
463 _ip.magic("notebook -e %s" % outfile)
463 _ip.magic("notebook -e %s" % outfile)
464
464
465 def test_notebook_export_py():
465 def test_notebook_export_py():
466 with TemporaryDirectory() as td:
466 with TemporaryDirectory() as td:
467 outfile = os.path.join(td, "nb.py")
467 outfile = os.path.join(td, "nb.py")
468 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
468 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
469 _ip.magic("notebook -e %s" % outfile)
469 _ip.magic("notebook -e %s" % outfile)
470
470
471 def test_notebook_reformat_py():
471 def test_notebook_reformat_py():
472 with TemporaryDirectory() as td:
472 with TemporaryDirectory() as td:
473 infile = os.path.join(td, "nb.ipynb")
473 infile = os.path.join(td, "nb.ipynb")
474 with io.open(infile, 'w', encoding='utf-8') as f:
474 with io.open(infile, 'w', encoding='utf-8') as f:
475 current.write(nb0, f, 'json')
475 current.write(nb0, f, 'json')
476
476
477 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
477 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
478 _ip.magic("notebook -f py %s" % infile)
478 _ip.magic("notebook -f py %s" % infile)
479
479
480 def test_notebook_reformat_json():
480 def test_notebook_reformat_json():
481 with TemporaryDirectory() as td:
481 with TemporaryDirectory() as td:
482 infile = os.path.join(td, "nb.py")
482 infile = os.path.join(td, "nb.py")
483 with io.open(infile, 'w', encoding='utf-8') as f:
483 with io.open(infile, 'w', encoding='utf-8') as f:
484 current.write(nb0, f, 'py')
484 current.write(nb0, f, 'py')
485
485
486 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
486 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
487 _ip.magic("notebook -f ipynb %s" % infile)
487 _ip.magic("notebook -f ipynb %s" % infile)
488 _ip.magic("notebook -f json %s" % infile)
488 _ip.magic("notebook -f json %s" % infile)
489
489
490 def test_env():
490 def test_env():
491 env = _ip.magic("env")
491 env = _ip.magic("env")
492 assert isinstance(env, dict), type(env)
492 assert isinstance(env, dict), type(env)
493
494
495 class CellMagicTestCase(TestCase):
496
497 def check_ident(self, magic):
498 out = _ip.cell_magic(magic, 'a', 'b')
499 nt.assert_equals(out, ('a','b'))
500 out = _ip.run_cell('%%' + magic +' a\nb')
501 nt.assert_equals(out, ('a','b'))
502
503 def test_cell_magic_func_deco(self):
504 "Cell magic using simple decorator"
505 @register_cell_magic
506 def cellm(line, cell):
507 return line, cell
508
509 self.check_ident('cellm')
510
511 def test_cell_magic_reg(self):
512 "Cell magic manually registered"
513 def cellm(line, cell):
514 return line, cell
515
516 _ip.register_magic_function(cellm, 'cell', 'cellm2')
517 self.check_ident('cellm2')
518
519 def test_cell_magic_class(self):
520 "Cell magics declared via a class"
521 @magics_class
522 class MyMagics(Magics):
523
524 @cell_magic
525 def cellm3(self, line, cell):
526 return line, cell
527
528 @cell_magic('cellm4')
529 def cellm33(self, line, cell):
530 return line, cell
531
532 _ip.register_magics(MyMagics)
533 self.check_ident('cellm3')
534 self.check_ident('cellm4')
535 # Check that nothing is registered as 'cellm33'
536 c33 = _ip.find_cell_magic('cellm33')
537 nt.assert_equals(c33, None)
General Comments 0
You need to be logged in to leave comments. Login now