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