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