##// END OF EJS Templates
Change directory to simplify test_globlist...
Takafumi Arakaki -
Show More
@@ -1,775 +1,776 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 StringIO import StringIO
16 16 from unittest import TestCase
17 17
18 18 try:
19 19 from importlib import invalidate_caches # Required from Python 3.3
20 20 except ImportError:
21 21 def invalidate_caches():
22 22 pass
23 23
24 24 import nose.tools as nt
25 25
26 26 from IPython.core import magic
27 27 from IPython.core.magic import (Magics, magics_class, line_magic,
28 28 cell_magic, line_cell_magic,
29 29 register_line_magic, register_cell_magic,
30 30 register_line_cell_magic)
31 31 from IPython.core.magics import execution, script
32 32 from IPython.core.magics.execution import globlist
33 33 from IPython.nbformat.v3.tests.nbexamples import nb0
34 34 from IPython.nbformat import current
35 35 from IPython.testing import decorators as dec
36 36 from IPython.testing import tools as tt
37 37 from IPython.utils import py3compat
38 38 from IPython.utils.tempdir import TemporaryDirectory
39 39 from IPython.utils.process import find_cmd
40 40
41 41 #-----------------------------------------------------------------------------
42 42 # Test functions begin
43 43 #-----------------------------------------------------------------------------
44 44
45 45 @magic.magics_class
46 46 class DummyMagics(magic.Magics): pass
47 47
48 48 def test_rehashx():
49 49 # clear up everything
50 50 _ip = get_ipython()
51 51 _ip.alias_manager.alias_table.clear()
52 52 del _ip.db['syscmdlist']
53 53
54 54 _ip.magic('rehashx')
55 55 # Practically ALL ipython development systems will have more than 10 aliases
56 56
57 57 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
58 58 for key, val in _ip.alias_manager.alias_table.iteritems():
59 59 # we must strip dots from alias names
60 60 nt.assert_true('.' not in key)
61 61
62 62 # rehashx must fill up syscmdlist
63 63 scoms = _ip.db['syscmdlist']
64 64 yield (nt.assert_true, len(scoms) > 10)
65 65
66 66
67 67 def test_magic_parse_options():
68 68 """Test that we don't mangle paths when parsing magic options."""
69 69 ip = get_ipython()
70 70 path = 'c:\\x'
71 71 m = DummyMagics(ip)
72 72 opts = m.parse_options('-f %s' % path,'f:')[0]
73 73 # argv splitting is os-dependent
74 74 if os.name == 'posix':
75 75 expected = 'c:x'
76 76 else:
77 77 expected = path
78 78 nt.assert_equals(opts['f'], expected)
79 79
80 80 def test_magic_parse_long_options():
81 81 """Magic.parse_options can handle --foo=bar long options"""
82 82 ip = get_ipython()
83 83 m = DummyMagics(ip)
84 84 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
85 85 nt.assert_true('foo' in opts)
86 86 nt.assert_true('bar' in opts)
87 87 nt.assert_true(opts['bar'], "bubble")
88 88
89 89
90 90 def test_globlist():
91 91 """Test glob expansion for %run magic."""
92 92 filenames_start_with_a = map('a{0}'.format, range(3))
93 93 filenames_end_with_b = map('{0}b'.format, range(3))
94 94 filenames = filenames_start_with_a + filenames_end_with_b
95 95
96 96 with TemporaryDirectory() as td:
97
98 def getpaths(names):
99 return [os.path.join(td, fn) for fn in names]
100
101 # create files
102 for p in getpaths(filenames):
103 open(p, 'w').close()
104
105 def assert_match(patterns, matches):
106 # glob returns unordered list. that's why sorted is required.
107 nt.assert_equals(sorted(globlist(getpaths(patterns))),
108 sorted(getpaths(matches)))
109
110 assert_match(['*'], filenames)
111 assert_match(['a*'], filenames_start_with_a)
112 assert_match(['*c'], ['*c'])
113 assert_match(['*', 'a*', '*b', '*c'],
114 filenames
115 + filenames_start_with_a
116 + filenames_end_with_b
117 + ['*c'])
97 save = os.getcwdu()
98 try:
99 os.chdir(td)
100
101 # Create empty files
102 for fname in filenames:
103 open(os.path.join(td, fname), 'w').close()
104
105 def assert_match(patterns, matches):
106 # glob returns unordered list. that's why sorted is required.
107 nt.assert_equals(sorted(globlist(patterns)), sorted(matches))
108
109 assert_match(['*'], filenames)
110 assert_match(['a*'], filenames_start_with_a)
111 assert_match(['*c'], ['*c'])
112 assert_match(['*', 'a*', '*b', '*c'],
113 filenames
114 + filenames_start_with_a
115 + filenames_end_with_b
116 + ['*c'])
117 finally:
118 os.chdir(save)
118 119
119 120
120 121 @dec.skip_without('sqlite3')
121 122 def doctest_hist_f():
122 123 """Test %hist -f with temporary filename.
123 124
124 125 In [9]: import tempfile
125 126
126 127 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
127 128
128 129 In [11]: %hist -nl -f $tfile 3
129 130
130 131 In [13]: import os; os.unlink(tfile)
131 132 """
132 133
133 134
134 135 @dec.skip_without('sqlite3')
135 136 def doctest_hist_r():
136 137 """Test %hist -r
137 138
138 139 XXX - This test is not recording the output correctly. For some reason, in
139 140 testing mode the raw history isn't getting populated. No idea why.
140 141 Disabling the output checking for now, though at least we do run it.
141 142
142 143 In [1]: 'hist' in _ip.lsmagic()
143 144 Out[1]: True
144 145
145 146 In [2]: x=1
146 147
147 148 In [3]: %hist -rl 2
148 149 x=1 # random
149 150 %hist -r 2
150 151 """
151 152
152 153
153 154 @dec.skip_without('sqlite3')
154 155 def doctest_hist_op():
155 156 """Test %hist -op
156 157
157 158 In [1]: class b(float):
158 159 ...: pass
159 160 ...:
160 161
161 162 In [2]: class s(object):
162 163 ...: def __str__(self):
163 164 ...: return 's'
164 165 ...:
165 166
166 167 In [3]:
167 168
168 169 In [4]: class r(b):
169 170 ...: def __repr__(self):
170 171 ...: return 'r'
171 172 ...:
172 173
173 174 In [5]: class sr(s,r): pass
174 175 ...:
175 176
176 177 In [6]:
177 178
178 179 In [7]: bb=b()
179 180
180 181 In [8]: ss=s()
181 182
182 183 In [9]: rr=r()
183 184
184 185 In [10]: ssrr=sr()
185 186
186 187 In [11]: 4.5
187 188 Out[11]: 4.5
188 189
189 190 In [12]: str(ss)
190 191 Out[12]: 's'
191 192
192 193 In [13]:
193 194
194 195 In [14]: %hist -op
195 196 >>> class b:
196 197 ... pass
197 198 ...
198 199 >>> class s(b):
199 200 ... def __str__(self):
200 201 ... return 's'
201 202 ...
202 203 >>>
203 204 >>> class r(b):
204 205 ... def __repr__(self):
205 206 ... return 'r'
206 207 ...
207 208 >>> class sr(s,r): pass
208 209 >>>
209 210 >>> bb=b()
210 211 >>> ss=s()
211 212 >>> rr=r()
212 213 >>> ssrr=sr()
213 214 >>> 4.5
214 215 4.5
215 216 >>> str(ss)
216 217 's'
217 218 >>>
218 219 """
219 220
220 221
221 222 @dec.skip_without('sqlite3')
222 223 def test_macro():
223 224 ip = get_ipython()
224 225 ip.history_manager.reset() # Clear any existing history.
225 226 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
226 227 for i, cmd in enumerate(cmds, start=1):
227 228 ip.history_manager.store_inputs(i, cmd)
228 229 ip.magic("macro test 1-3")
229 230 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
230 231
231 232 # List macros.
232 233 assert "test" in ip.magic("macro")
233 234
234 235
235 236 @dec.skip_without('sqlite3')
236 237 def test_macro_run():
237 238 """Test that we can run a multi-line macro successfully."""
238 239 ip = get_ipython()
239 240 ip.history_manager.reset()
240 241 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
241 242 "%macro test 2-3"]
242 243 for cmd in cmds:
243 244 ip.run_cell(cmd, store_history=True)
244 245 nt.assert_equal(ip.user_ns["test"].value,
245 246 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
246 247 with tt.AssertPrints("12"):
247 248 ip.run_cell("test")
248 249 with tt.AssertPrints("13"):
249 250 ip.run_cell("test")
250 251
251 252
252 253 @dec.skipif_not_numpy
253 254 def test_numpy_reset_array_undec():
254 255 "Test '%reset array' functionality"
255 256 _ip.ex('import numpy as np')
256 257 _ip.ex('a = np.empty(2)')
257 258 yield (nt.assert_true, 'a' in _ip.user_ns)
258 259 _ip.magic('reset -f array')
259 260 yield (nt.assert_false, 'a' in _ip.user_ns)
260 261
261 262 def test_reset_out():
262 263 "Test '%reset out' magic"
263 264 _ip.run_cell("parrot = 'dead'", store_history=True)
264 265 # test '%reset -f out', make an Out prompt
265 266 _ip.run_cell("parrot", store_history=True)
266 267 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
267 268 _ip.magic('reset -f out')
268 269 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
269 270 nt.assert_true(len(_ip.user_ns['Out']) == 0)
270 271
271 272 def test_reset_in():
272 273 "Test '%reset in' magic"
273 274 # test '%reset -f in'
274 275 _ip.run_cell("parrot", store_history=True)
275 276 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
276 277 _ip.magic('%reset -f in')
277 278 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
278 279 nt.assert_true(len(set(_ip.user_ns['In'])) == 1)
279 280
280 281 def test_reset_dhist():
281 282 "Test '%reset dhist' magic"
282 283 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
283 284 _ip.magic('cd ' + os.path.dirname(nt.__file__))
284 285 _ip.magic('cd -')
285 286 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
286 287 _ip.magic('reset -f dhist')
287 288 nt.assert_true(len(_ip.user_ns['_dh']) == 0)
288 289 _ip.run_cell("_dh = [d for d in tmp]") #restore
289 290
290 291 def test_reset_in_length():
291 292 "Test that '%reset in' preserves In[] length"
292 293 _ip.run_cell("print 'foo'")
293 294 _ip.run_cell("reset -f in")
294 295 nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1)
295 296
296 297 def test_time():
297 298 _ip.magic('time None')
298 299
299 300 def test_tb_syntaxerror():
300 301 """test %tb after a SyntaxError"""
301 302 ip = get_ipython()
302 303 ip.run_cell("for")
303 304
304 305 # trap and validate stdout
305 306 save_stdout = sys.stdout
306 307 try:
307 308 sys.stdout = StringIO()
308 309 ip.run_cell("%tb")
309 310 out = sys.stdout.getvalue()
310 311 finally:
311 312 sys.stdout = save_stdout
312 313 # trim output, and only check the last line
313 314 last_line = out.rstrip().splitlines()[-1].strip()
314 315 nt.assert_equals(last_line, "SyntaxError: invalid syntax")
315 316
316 317
317 318 @py3compat.doctest_refactor_print
318 319 def doctest_time():
319 320 """
320 321 In [10]: %time None
321 322 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
322 323 Wall time: 0.00 s
323 324
324 325 In [11]: def f(kmjy):
325 326 ....: %time print 2*kmjy
326 327
327 328 In [12]: f(3)
328 329 6
329 330 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
330 331 Wall time: 0.00 s
331 332 """
332 333
333 334
334 335 def test_doctest_mode():
335 336 "Toggle doctest_mode twice, it should be a no-op and run without error"
336 337 _ip.magic('doctest_mode')
337 338 _ip.magic('doctest_mode')
338 339
339 340
340 341 def test_parse_options():
341 342 """Tests for basic options parsing in magics."""
342 343 # These are only the most minimal of tests, more should be added later. At
343 344 # the very least we check that basic text/unicode calls work OK.
344 345 m = DummyMagics(_ip)
345 346 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
346 347 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
347 348
348 349
349 350 def test_dirops():
350 351 """Test various directory handling operations."""
351 352 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
352 353 curpath = os.getcwdu
353 354 startdir = os.getcwdu()
354 355 ipdir = os.path.realpath(_ip.ipython_dir)
355 356 try:
356 357 _ip.magic('cd "%s"' % ipdir)
357 358 nt.assert_equal(curpath(), ipdir)
358 359 _ip.magic('cd -')
359 360 nt.assert_equal(curpath(), startdir)
360 361 _ip.magic('pushd "%s"' % ipdir)
361 362 nt.assert_equal(curpath(), ipdir)
362 363 _ip.magic('popd')
363 364 nt.assert_equal(curpath(), startdir)
364 365 finally:
365 366 os.chdir(startdir)
366 367
367 368
368 369 def test_xmode():
369 370 # Calling xmode three times should be a no-op
370 371 xmode = _ip.InteractiveTB.mode
371 372 for i in range(3):
372 373 _ip.magic("xmode")
373 374 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
374 375
375 376 def test_reset_hard():
376 377 monitor = []
377 378 class A(object):
378 379 def __del__(self):
379 380 monitor.append(1)
380 381 def __repr__(self):
381 382 return "<A instance>"
382 383
383 384 _ip.user_ns["a"] = A()
384 385 _ip.run_cell("a")
385 386
386 387 nt.assert_equal(monitor, [])
387 388 _ip.magic("reset -f")
388 389 nt.assert_equal(monitor, [1])
389 390
390 391 class TestXdel(tt.TempFileMixin):
391 392 def test_xdel(self):
392 393 """Test that references from %run are cleared by xdel."""
393 394 src = ("class A(object):\n"
394 395 " monitor = []\n"
395 396 " def __del__(self):\n"
396 397 " self.monitor.append(1)\n"
397 398 "a = A()\n")
398 399 self.mktmp(src)
399 400 # %run creates some hidden references...
400 401 _ip.magic("run %s" % self.fname)
401 402 # ... as does the displayhook.
402 403 _ip.run_cell("a")
403 404
404 405 monitor = _ip.user_ns["A"].monitor
405 406 nt.assert_equal(monitor, [])
406 407
407 408 _ip.magic("xdel a")
408 409
409 410 # Check that a's __del__ method has been called.
410 411 nt.assert_equal(monitor, [1])
411 412
412 413 def doctest_who():
413 414 """doctest for %who
414 415
415 416 In [1]: %reset -f
416 417
417 418 In [2]: alpha = 123
418 419
419 420 In [3]: beta = 'beta'
420 421
421 422 In [4]: %who int
422 423 alpha
423 424
424 425 In [5]: %who str
425 426 beta
426 427
427 428 In [6]: %whos
428 429 Variable Type Data/Info
429 430 ----------------------------
430 431 alpha int 123
431 432 beta str beta
432 433
433 434 In [7]: %who_ls
434 435 Out[7]: ['alpha', 'beta']
435 436 """
436 437
437 438 def test_whos():
438 439 """Check that whos is protected against objects where repr() fails."""
439 440 class A(object):
440 441 def __repr__(self):
441 442 raise Exception()
442 443 _ip.user_ns['a'] = A()
443 444 _ip.magic("whos")
444 445
445 446 @py3compat.u_format
446 447 def doctest_precision():
447 448 """doctest for %precision
448 449
449 450 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
450 451
451 452 In [2]: %precision 5
452 453 Out[2]: {u}'%.5f'
453 454
454 455 In [3]: f.float_format
455 456 Out[3]: {u}'%.5f'
456 457
457 458 In [4]: %precision %e
458 459 Out[4]: {u}'%e'
459 460
460 461 In [5]: f(3.1415927)
461 462 Out[5]: {u}'3.141593e+00'
462 463 """
463 464
464 465 def test_psearch():
465 466 with tt.AssertPrints("dict.fromkeys"):
466 467 _ip.run_cell("dict.fr*?")
467 468
468 469 def test_timeit_shlex():
469 470 """test shlex issues with timeit (#1109)"""
470 471 _ip.ex("def f(*a,**kw): pass")
471 472 _ip.magic('timeit -n1 "this is a bug".count(" ")')
472 473 _ip.magic('timeit -r1 -n1 f(" ", 1)')
473 474 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
474 475 _ip.magic('timeit -r1 -n1 ("a " + "b")')
475 476 _ip.magic('timeit -r1 -n1 f("a " + "b")')
476 477 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
477 478
478 479
479 480 def test_timeit_arguments():
480 481 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
481 482 _ip.magic("timeit ('#')")
482 483
483 484
484 485 def test_timeit_special_syntax():
485 486 "Test %%timeit with IPython special syntax"
486 487 from IPython.core.magic import register_line_magic
487 488
488 489 @register_line_magic
489 490 def lmagic(line):
490 491 ip = get_ipython()
491 492 ip.user_ns['lmagic_out'] = line
492 493
493 494 # line mode test
494 495 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
495 496 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
496 497 # cell mode test
497 498 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
498 499 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
499 500
500 501
501 502 @dec.skipif(execution.profile is None)
502 503 def test_prun_quotes():
503 504 "Test that prun does not clobber string escapes (GH #1302)"
504 505 _ip.magic(r"prun -q x = '\t'")
505 506 nt.assert_equal(_ip.user_ns['x'], '\t')
506 507
507 508 def test_extension():
508 509 tmpdir = TemporaryDirectory()
509 510 orig_ipython_dir = _ip.ipython_dir
510 511 try:
511 512 _ip.ipython_dir = tmpdir.name
512 513 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
513 514 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
514 515 _ip.magic("install_ext %s" % url)
515 516 _ip.user_ns.pop('arq', None)
516 517 invalidate_caches() # Clear import caches
517 518 _ip.magic("load_ext daft_extension")
518 519 tt.assert_equal(_ip.user_ns['arq'], 185)
519 520 _ip.magic("unload_ext daft_extension")
520 521 assert 'arq' not in _ip.user_ns
521 522 finally:
522 523 _ip.ipython_dir = orig_ipython_dir
523 524 tmpdir.cleanup()
524 525
525 526 def test_notebook_export_json():
526 527 with TemporaryDirectory() as td:
527 528 outfile = os.path.join(td, "nb.ipynb")
528 529 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
529 530 _ip.magic("notebook -e %s" % outfile)
530 531
531 532 def test_notebook_export_py():
532 533 with TemporaryDirectory() as td:
533 534 outfile = os.path.join(td, "nb.py")
534 535 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
535 536 _ip.magic("notebook -e %s" % outfile)
536 537
537 538 def test_notebook_reformat_py():
538 539 with TemporaryDirectory() as td:
539 540 infile = os.path.join(td, "nb.ipynb")
540 541 with io.open(infile, 'w', encoding='utf-8') as f:
541 542 current.write(nb0, f, 'json')
542 543
543 544 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
544 545 _ip.magic("notebook -f py %s" % infile)
545 546
546 547 def test_notebook_reformat_json():
547 548 with TemporaryDirectory() as td:
548 549 infile = os.path.join(td, "nb.py")
549 550 with io.open(infile, 'w', encoding='utf-8') as f:
550 551 current.write(nb0, f, 'py')
551 552
552 553 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
553 554 _ip.magic("notebook -f ipynb %s" % infile)
554 555 _ip.magic("notebook -f json %s" % infile)
555 556
556 557 def test_env():
557 558 env = _ip.magic("env")
558 559 assert isinstance(env, dict), type(env)
559 560
560 561
561 562 class CellMagicTestCase(TestCase):
562 563
563 564 def check_ident(self, magic):
564 565 # Manually called, we get the result
565 566 out = _ip.run_cell_magic(magic, 'a', 'b')
566 567 nt.assert_equals(out, ('a','b'))
567 568 # Via run_cell, it goes into the user's namespace via displayhook
568 569 _ip.run_cell('%%' + magic +' c\nd')
569 570 nt.assert_equals(_ip.user_ns['_'], ('c','d'))
570 571
571 572 def test_cell_magic_func_deco(self):
572 573 "Cell magic using simple decorator"
573 574 @register_cell_magic
574 575 def cellm(line, cell):
575 576 return line, cell
576 577
577 578 self.check_ident('cellm')
578 579
579 580 def test_cell_magic_reg(self):
580 581 "Cell magic manually registered"
581 582 def cellm(line, cell):
582 583 return line, cell
583 584
584 585 _ip.register_magic_function(cellm, 'cell', 'cellm2')
585 586 self.check_ident('cellm2')
586 587
587 588 def test_cell_magic_class(self):
588 589 "Cell magics declared via a class"
589 590 @magics_class
590 591 class MyMagics(Magics):
591 592
592 593 @cell_magic
593 594 def cellm3(self, line, cell):
594 595 return line, cell
595 596
596 597 _ip.register_magics(MyMagics)
597 598 self.check_ident('cellm3')
598 599
599 600 def test_cell_magic_class2(self):
600 601 "Cell magics declared via a class, #2"
601 602 @magics_class
602 603 class MyMagics2(Magics):
603 604
604 605 @cell_magic('cellm4')
605 606 def cellm33(self, line, cell):
606 607 return line, cell
607 608
608 609 _ip.register_magics(MyMagics2)
609 610 self.check_ident('cellm4')
610 611 # Check that nothing is registered as 'cellm33'
611 612 c33 = _ip.find_cell_magic('cellm33')
612 613 nt.assert_equals(c33, None)
613 614
614 615 def test_file():
615 616 """Basic %%file"""
616 617 ip = get_ipython()
617 618 with TemporaryDirectory() as td:
618 619 fname = os.path.join(td, 'file1')
619 620 ip.run_cell_magic("file", fname, u'\n'.join([
620 621 'line1',
621 622 'line2',
622 623 ]))
623 624 with open(fname) as f:
624 625 s = f.read()
625 626 nt.assert_in('line1\n', s)
626 627 nt.assert_in('line2', s)
627 628
628 629 def test_file_unicode():
629 630 """%%file with unicode cell"""
630 631 ip = get_ipython()
631 632 with TemporaryDirectory() as td:
632 633 fname = os.path.join(td, 'file1')
633 634 ip.run_cell_magic("file", fname, u'\n'.join([
634 635 u'linΓ©1',
635 636 u'linΓ©2',
636 637 ]))
637 638 with io.open(fname, encoding='utf-8') as f:
638 639 s = f.read()
639 640 nt.assert_in(u'linΓ©1\n', s)
640 641 nt.assert_in(u'linΓ©2', s)
641 642
642 643 def test_file_amend():
643 644 """%%file -a amends files"""
644 645 ip = get_ipython()
645 646 with TemporaryDirectory() as td:
646 647 fname = os.path.join(td, 'file2')
647 648 ip.run_cell_magic("file", fname, u'\n'.join([
648 649 'line1',
649 650 'line2',
650 651 ]))
651 652 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
652 653 'line3',
653 654 'line4',
654 655 ]))
655 656 with open(fname) as f:
656 657 s = f.read()
657 658 nt.assert_in('line1\n', s)
658 659 nt.assert_in('line3\n', s)
659 660
660 661
661 662 def test_script_config():
662 663 ip = get_ipython()
663 664 ip.config.ScriptMagics.script_magics = ['whoda']
664 665 sm = script.ScriptMagics(shell=ip)
665 666 nt.assert_in('whoda', sm.magics['cell'])
666 667
667 668 @dec.skip_win32
668 669 def test_script_out():
669 670 ip = get_ipython()
670 671 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
671 672 nt.assert_equals(ip.user_ns['output'], 'hi\n')
672 673
673 674 @dec.skip_win32
674 675 def test_script_err():
675 676 ip = get_ipython()
676 677 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
677 678 nt.assert_equals(ip.user_ns['error'], 'hello\n')
678 679
679 680 @dec.skip_win32
680 681 def test_script_out_err():
681 682 ip = get_ipython()
682 683 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
683 684 nt.assert_equals(ip.user_ns['output'], 'hi\n')
684 685 nt.assert_equals(ip.user_ns['error'], 'hello\n')
685 686
686 687 @dec.skip_win32
687 688 def test_script_bg_out():
688 689 ip = get_ipython()
689 690 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
690 691 nt.assert_equals(ip.user_ns['output'].read(), b'hi\n')
691 692
692 693 @dec.skip_win32
693 694 def test_script_bg_err():
694 695 ip = get_ipython()
695 696 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
696 697 nt.assert_equals(ip.user_ns['error'].read(), b'hello\n')
697 698
698 699 @dec.skip_win32
699 700 def test_script_bg_out_err():
700 701 ip = get_ipython()
701 702 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
702 703 nt.assert_equals(ip.user_ns['output'].read(), b'hi\n')
703 704 nt.assert_equals(ip.user_ns['error'].read(), b'hello\n')
704 705
705 706 def test_script_defaults():
706 707 ip = get_ipython()
707 708 for cmd in ['sh', 'bash', 'perl', 'ruby']:
708 709 try:
709 710 find_cmd(cmd)
710 711 except Exception:
711 712 pass
712 713 else:
713 714 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
714 715
715 716
716 717 @magics_class
717 718 class FooFoo(Magics):
718 719 """class with both %foo and %%foo magics"""
719 720 @line_magic('foo')
720 721 def line_foo(self, line):
721 722 "I am line foo"
722 723 pass
723 724
724 725 @cell_magic("foo")
725 726 def cell_foo(self, line, cell):
726 727 "I am cell foo, not line foo"
727 728 pass
728 729
729 730 def test_line_cell_info():
730 731 """%%foo and %foo magics are distinguishable to inspect"""
731 732 ip = get_ipython()
732 733 ip.magics_manager.register(FooFoo)
733 734 oinfo = ip.object_inspect('foo')
734 735 nt.assert_true(oinfo['found'])
735 736 nt.assert_true(oinfo['ismagic'])
736 737
737 738 oinfo = ip.object_inspect('%%foo')
738 739 nt.assert_true(oinfo['found'])
739 740 nt.assert_true(oinfo['ismagic'])
740 741 nt.assert_equals(oinfo['docstring'], FooFoo.cell_foo.__doc__)
741 742
742 743 oinfo = ip.object_inspect('%foo')
743 744 nt.assert_true(oinfo['found'])
744 745 nt.assert_true(oinfo['ismagic'])
745 746 nt.assert_equals(oinfo['docstring'], FooFoo.line_foo.__doc__)
746 747
747 748 def test_multiple_magics():
748 749 ip = get_ipython()
749 750 foo1 = FooFoo(ip)
750 751 foo2 = FooFoo(ip)
751 752 mm = ip.magics_manager
752 753 mm.register(foo1)
753 754 nt.assert_true(mm.magics['line']['foo'].im_self is foo1)
754 755 mm.register(foo2)
755 756 nt.assert_true(mm.magics['line']['foo'].im_self is foo2)
756 757
757 758 def test_alias_magic():
758 759 """Test %alias_magic."""
759 760 ip = get_ipython()
760 761 mm = ip.magics_manager
761 762
762 763 # Basic operation: both cell and line magics are created, if possible.
763 764 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
764 765 nt.assert_true('timeit_alias' in mm.magics['line'])
765 766 nt.assert_true('timeit_alias' in mm.magics['cell'])
766 767
767 768 # --cell is specified, line magic not created.
768 769 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
769 770 nt.assert_false('timeit_cell_alias' in mm.magics['line'])
770 771 nt.assert_true('timeit_cell_alias' in mm.magics['cell'])
771 772
772 773 # Test that line alias is created successfully.
773 774 ip.run_line_magic('alias_magic', '--line env_alias env')
774 775 nt.assert_equal(ip.run_line_magic('env', ''),
775 776 ip.run_line_magic('env_alias', ''))
General Comments 0
You need to be logged in to leave comments. Login now