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