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