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