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