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