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