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