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