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