##// END OF EJS Templates
more agressive skip on windows
Matthias Bussonnier -
Show More
@@ -1,1321 +1,1341 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
7 7 import asyncio
8 8 import io
9 9 import os
10 10 import re
11 11 import shlex
12 12 import sys
13 13 import warnings
14 14 from importlib import invalidate_caches
15 15 from io import StringIO
16 16 from pathlib import Path
17 17 from textwrap import dedent
18 18 from unittest import TestCase, mock
19 19
20 20 import nose.tools as nt
21 21
22 import pytest
23
22 24 from IPython import get_ipython
23 25 from IPython.core import magic
24 26 from IPython.core.error import UsageError
25 27 from IPython.core.magic import (
26 28 Magics,
27 29 cell_magic,
28 30 line_magic,
29 31 magics_class,
30 32 register_cell_magic,
31 33 register_line_magic,
32 34 )
33 35 from IPython.core.magics import code, execution, logging, osm, script
34 36 from IPython.testing import decorators as dec
35 37 from IPython.testing import tools as tt
36 38 from IPython.utils.io import capture_output
37 39 from IPython.utils.process import find_cmd
38 40 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
39 41
40 42 from .test_debugger import PdbTestInput
41 43
42 44
43 45 @magic.magics_class
44 46 class DummyMagics(magic.Magics): pass
45 47
46 48 def test_extract_code_ranges():
47 49 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
48 50 expected = [(0, 1),
49 51 (2, 3),
50 52 (4, 6),
51 53 (6, 9),
52 54 (9, 14),
53 55 (16, None),
54 56 (None, 9),
55 57 (9, None),
56 58 (None, 13),
57 59 (None, None)]
58 60 actual = list(code.extract_code_ranges(instr))
59 61 nt.assert_equal(actual, expected)
60 62
61 63 def test_extract_symbols():
62 64 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
63 65 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
64 66 expected = [([], ['a']),
65 67 (["def b():\n return 42\n"], []),
66 68 (["class A: pass\n"], []),
67 69 (["class A: pass\n", "def b():\n return 42\n"], []),
68 70 (["class A: pass\n"], ['a']),
69 71 ([], ['z'])]
70 72 for symbols, exp in zip(symbols_args, expected):
71 73 nt.assert_equal(code.extract_symbols(source, symbols), exp)
72 74
73 75
74 76 def test_extract_symbols_raises_exception_with_non_python_code():
75 77 source = ("=begin A Ruby program :)=end\n"
76 78 "def hello\n"
77 79 "puts 'Hello world'\n"
78 80 "end")
79 81 with nt.assert_raises(SyntaxError):
80 82 code.extract_symbols(source, "hello")
81 83
82 84
83 85 def test_magic_not_found():
84 86 # magic not found raises UsageError
85 87 with nt.assert_raises(UsageError):
86 88 _ip.magic('doesntexist')
87 89
88 90 # ensure result isn't success when a magic isn't found
89 91 result = _ip.run_cell('%doesntexist')
90 92 assert isinstance(result.error_in_exec, UsageError)
91 93
92 94
93 95 def test_cell_magic_not_found():
94 96 # magic not found raises UsageError
95 97 with nt.assert_raises(UsageError):
96 98 _ip.run_cell_magic('doesntexist', 'line', 'cell')
97 99
98 100 # ensure result isn't success when a magic isn't found
99 101 result = _ip.run_cell('%%doesntexist')
100 102 assert isinstance(result.error_in_exec, UsageError)
101 103
102 104
103 105 def test_magic_error_status():
104 106 def fail(shell):
105 107 1/0
106 108 _ip.register_magic_function(fail)
107 109 result = _ip.run_cell('%fail')
108 110 assert isinstance(result.error_in_exec, ZeroDivisionError)
109 111
110 112
111 113 def test_config():
112 114 """ test that config magic does not raise
113 115 can happen if Configurable init is moved too early into
114 116 Magics.__init__ as then a Config object will be registered as a
115 117 magic.
116 118 """
117 119 ## should not raise.
118 120 _ip.magic('config')
119 121
120 122 def test_config_available_configs():
121 123 """ test that config magic prints available configs in unique and
122 124 sorted order. """
123 125 with capture_output() as captured:
124 126 _ip.magic('config')
125 127
126 128 stdout = captured.stdout
127 129 config_classes = stdout.strip().split('\n')[1:]
128 130 nt.assert_list_equal(config_classes, sorted(set(config_classes)))
129 131
130 132 def test_config_print_class():
131 133 """ test that config with a classname prints the class's options. """
132 134 with capture_output() as captured:
133 135 _ip.magic('config TerminalInteractiveShell')
134 136
135 137 stdout = captured.stdout
136 138 if not re.match("TerminalInteractiveShell.* options", stdout.splitlines()[0]):
137 139 print(stdout)
138 140 raise AssertionError("1st line of stdout not like "
139 141 "'TerminalInteractiveShell.* options'")
140 142
141 143 def test_rehashx():
142 144 # clear up everything
143 145 _ip.alias_manager.clear_aliases()
144 146 del _ip.db['syscmdlist']
145 147
146 148 _ip.magic('rehashx')
147 149 # Practically ALL ipython development systems will have more than 10 aliases
148 150
149 151 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
150 152 for name, cmd in _ip.alias_manager.aliases:
151 153 # we must strip dots from alias names
152 154 nt.assert_not_in('.', name)
153 155
154 156 # rehashx must fill up syscmdlist
155 157 scoms = _ip.db['syscmdlist']
156 158 nt.assert_true(len(scoms) > 10)
157 159
158 160
159 161
160 162 def test_magic_parse_options():
161 163 """Test that we don't mangle paths when parsing magic options."""
162 164 ip = get_ipython()
163 165 path = 'c:\\x'
164 166 m = DummyMagics(ip)
165 167 opts = m.parse_options('-f %s' % path,'f:')[0]
166 168 # argv splitting is os-dependent
167 169 if os.name == 'posix':
168 170 expected = 'c:x'
169 171 else:
170 172 expected = path
171 173 nt.assert_equal(opts['f'], expected)
172 174
173 175 def test_magic_parse_long_options():
174 176 """Magic.parse_options can handle --foo=bar long options"""
175 177 ip = get_ipython()
176 178 m = DummyMagics(ip)
177 179 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
178 180 nt.assert_in('foo', opts)
179 181 nt.assert_in('bar', opts)
180 182 nt.assert_equal(opts['bar'], "bubble")
181 183
182 184
183 185 def doctest_hist_f():
184 186 """Test %hist -f with temporary filename.
185 187
186 188 In [9]: import tempfile
187 189
188 190 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
189 191
190 192 In [11]: %hist -nl -f $tfile 3
191 193
192 194 In [13]: import os; os.unlink(tfile)
193 195 """
194 196
195 197
196 198 def doctest_hist_op():
197 199 """Test %hist -op
198 200
199 201 In [1]: class b(float):
200 202 ...: pass
201 203 ...:
202 204
203 205 In [2]: class s(object):
204 206 ...: def __str__(self):
205 207 ...: return 's'
206 208 ...:
207 209
208 210 In [3]:
209 211
210 212 In [4]: class r(b):
211 213 ...: def __repr__(self):
212 214 ...: return 'r'
213 215 ...:
214 216
215 217 In [5]: class sr(s,r): pass
216 218 ...:
217 219
218 220 In [6]:
219 221
220 222 In [7]: bb=b()
221 223
222 224 In [8]: ss=s()
223 225
224 226 In [9]: rr=r()
225 227
226 228 In [10]: ssrr=sr()
227 229
228 230 In [11]: 4.5
229 231 Out[11]: 4.5
230 232
231 233 In [12]: str(ss)
232 234 Out[12]: 's'
233 235
234 236 In [13]:
235 237
236 238 In [14]: %hist -op
237 239 >>> class b:
238 240 ... pass
239 241 ...
240 242 >>> class s(b):
241 243 ... def __str__(self):
242 244 ... return 's'
243 245 ...
244 246 >>>
245 247 >>> class r(b):
246 248 ... def __repr__(self):
247 249 ... return 'r'
248 250 ...
249 251 >>> class sr(s,r): pass
250 252 >>>
251 253 >>> bb=b()
252 254 >>> ss=s()
253 255 >>> rr=r()
254 256 >>> ssrr=sr()
255 257 >>> 4.5
256 258 4.5
257 259 >>> str(ss)
258 260 's'
259 261 >>>
260 262 """
261 263
262 264 def test_hist_pof():
263 265 ip = get_ipython()
264 266 ip.run_cell(u"1+2", store_history=True)
265 267 #raise Exception(ip.history_manager.session_number)
266 268 #raise Exception(list(ip.history_manager._get_range_session()))
267 269 with TemporaryDirectory() as td:
268 270 tf = os.path.join(td, 'hist.py')
269 271 ip.run_line_magic('history', '-pof %s' % tf)
270 272 assert os.path.isfile(tf)
271 273
272 274
273 275 def test_macro():
274 276 ip = get_ipython()
275 277 ip.history_manager.reset() # Clear any existing history.
276 278 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
277 279 for i, cmd in enumerate(cmds, start=1):
278 280 ip.history_manager.store_inputs(i, cmd)
279 281 ip.magic("macro test 1-3")
280 282 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
281 283
282 284 # List macros
283 285 nt.assert_in("test", ip.magic("macro"))
284 286
285 287
286 288 def test_macro_run():
287 289 """Test that we can run a multi-line macro successfully."""
288 290 ip = get_ipython()
289 291 ip.history_manager.reset()
290 292 cmds = ["a=10", "a+=1", "print(a)", "%macro test 2-3"]
291 293 for cmd in cmds:
292 294 ip.run_cell(cmd, store_history=True)
293 295 nt.assert_equal(ip.user_ns["test"].value, "a+=1\nprint(a)\n")
294 296 with tt.AssertPrints("12"):
295 297 ip.run_cell("test")
296 298 with tt.AssertPrints("13"):
297 299 ip.run_cell("test")
298 300
299 301
300 302 def test_magic_magic():
301 303 """Test %magic"""
302 304 ip = get_ipython()
303 305 with capture_output() as captured:
304 306 ip.magic("magic")
305 307
306 308 stdout = captured.stdout
307 309 nt.assert_in('%magic', stdout)
308 310 nt.assert_in('IPython', stdout)
309 311 nt.assert_in('Available', stdout)
310 312
311 313
312 314 @dec.skipif_not_numpy
313 315 def test_numpy_reset_array_undec():
314 316 "Test '%reset array' functionality"
315 317 _ip.ex('import numpy as np')
316 318 _ip.ex('a = np.empty(2)')
317 319 nt.assert_in('a', _ip.user_ns)
318 320 _ip.magic('reset -f array')
319 321 nt.assert_not_in('a', _ip.user_ns)
320 322
321 323 def test_reset_out():
322 324 "Test '%reset out' magic"
323 325 _ip.run_cell("parrot = 'dead'", store_history=True)
324 326 # test '%reset -f out', make an Out prompt
325 327 _ip.run_cell("parrot", store_history=True)
326 328 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
327 329 _ip.magic('reset -f out')
328 330 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
329 331 nt.assert_equal(len(_ip.user_ns['Out']), 0)
330 332
331 333 def test_reset_in():
332 334 "Test '%reset in' magic"
333 335 # test '%reset -f in'
334 336 _ip.run_cell("parrot", store_history=True)
335 337 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
336 338 _ip.magic('%reset -f in')
337 339 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
338 340 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
339 341
340 342 def test_reset_dhist():
341 343 "Test '%reset dhist' magic"
342 344 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
343 345 _ip.magic('cd ' + os.path.dirname(nt.__file__))
344 346 _ip.magic('cd -')
345 347 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
346 348 _ip.magic('reset -f dhist')
347 349 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
348 350 _ip.run_cell("_dh = [d for d in tmp]") #restore
349 351
350 352 def test_reset_in_length():
351 353 "Test that '%reset in' preserves In[] length"
352 354 _ip.run_cell("print 'foo'")
353 355 _ip.run_cell("reset -f in")
354 356 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
355 357
356 358 class TestResetErrors(TestCase):
357 359
358 360 def test_reset_redefine(self):
359 361
360 362 @magics_class
361 363 class KernelMagics(Magics):
362 364 @line_magic
363 365 def less(self, shell): pass
364 366
365 367 _ip.register_magics(KernelMagics)
366 368
367 369 with self.assertLogs() as cm:
368 370 # hack, we want to just capture logs, but assertLogs fails if not
369 371 # logs get produce.
370 372 # so log one things we ignore.
371 373 import logging as log_mod
372 374 log = log_mod.getLogger()
373 375 log.info('Nothing')
374 376 # end hack.
375 377 _ip.run_cell("reset -f")
376 378
377 379 assert len(cm.output) == 1
378 380 for out in cm.output:
379 381 assert "Invalid alias" not in out
380 382
381 383 def test_tb_syntaxerror():
382 384 """test %tb after a SyntaxError"""
383 385 ip = get_ipython()
384 386 ip.run_cell("for")
385 387
386 388 # trap and validate stdout
387 389 save_stdout = sys.stdout
388 390 try:
389 391 sys.stdout = StringIO()
390 392 ip.run_cell("%tb")
391 393 out = sys.stdout.getvalue()
392 394 finally:
393 395 sys.stdout = save_stdout
394 396 # trim output, and only check the last line
395 397 last_line = out.rstrip().splitlines()[-1].strip()
396 398 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
397 399
398 400
399 401 def test_time():
400 402 ip = get_ipython()
401 403
402 404 with tt.AssertPrints("Wall time: "):
403 405 ip.run_cell("%time None")
404 406
405 407 ip.run_cell("def f(kmjy):\n"
406 408 " %time print (2*kmjy)")
407 409
408 410 with tt.AssertPrints("Wall time: "):
409 411 with tt.AssertPrints("hihi", suppress=False):
410 412 ip.run_cell("f('hi')")
411 413
412 414 def test_time_last_not_expression():
413 415 ip.run_cell("%%time\n"
414 416 "var_1 = 1\n"
415 417 "var_2 = 2\n")
416 418 assert ip.user_ns['var_1'] == 1
417 419 del ip.user_ns['var_1']
418 420 assert ip.user_ns['var_2'] == 2
419 421 del ip.user_ns['var_2']
420 422
421 423
422 424 @dec.skip_win32
423 425 def test_time2():
424 426 ip = get_ipython()
425 427
426 428 with tt.AssertPrints("CPU times: user "):
427 429 ip.run_cell("%time None")
428 430
429 431 def test_time3():
430 432 """Erroneous magic function calls, issue gh-3334"""
431 433 ip = get_ipython()
432 434 ip.user_ns.pop('run', None)
433 435
434 436 with tt.AssertNotPrints("not found", channel='stderr'):
435 437 ip.run_cell("%%time\n"
436 438 "run = 0\n"
437 439 "run += 1")
438 440
439 441 def test_multiline_time():
440 442 """Make sure last statement from time return a value."""
441 443 ip = get_ipython()
442 444 ip.user_ns.pop('run', None)
443 445
444 446 ip.run_cell(dedent("""\
445 447 %%time
446 448 a = "ho"
447 449 b = "hey"
448 450 a+b
449 451 """))
450 452 nt.assert_equal(ip.user_ns_hidden['_'], 'hohey')
451 453
452 454 def test_time_local_ns():
453 455 """
454 456 Test that local_ns is actually global_ns when running a cell magic
455 457 """
456 458 ip = get_ipython()
457 459 ip.run_cell("%%time\n"
458 460 "myvar = 1")
459 461 nt.assert_equal(ip.user_ns['myvar'], 1)
460 462 del ip.user_ns['myvar']
461 463
462 464 def test_doctest_mode():
463 465 "Toggle doctest_mode twice, it should be a no-op and run without error"
464 466 _ip.magic('doctest_mode')
465 467 _ip.magic('doctest_mode')
466 468
467 469
468 470 def test_parse_options():
469 471 """Tests for basic options parsing in magics."""
470 472 # These are only the most minimal of tests, more should be added later. At
471 473 # the very least we check that basic text/unicode calls work OK.
472 474 m = DummyMagics(_ip)
473 475 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
474 476 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
475 477
476 478
477 479 def test_parse_options_preserve_non_option_string():
478 480 """Test to assert preservation of non-option part of magic-block, while parsing magic options."""
479 481 m = DummyMagics(_ip)
480 482 opts, stmt = m.parse_options(
481 483 " -n1 -r 13 _ = 314 + foo", "n:r:", preserve_non_opts=True
482 484 )
483 485 nt.assert_equal(opts, {"n": "1", "r": "13"})
484 486 nt.assert_equal(stmt, "_ = 314 + foo")
485 487
486 488
487 489 def test_run_magic_preserve_code_block():
488 490 """Test to assert preservation of non-option part of magic-block, while running magic."""
489 491 _ip.user_ns["spaces"] = []
490 492 _ip.magic("timeit -n1 -r1 spaces.append([s.count(' ') for s in ['document']])")
491 493 assert _ip.user_ns["spaces"] == [[0]]
492 494
493 495
494 496 def test_dirops():
495 497 """Test various directory handling operations."""
496 498 # curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
497 499 curpath = os.getcwd
498 500 startdir = os.getcwd()
499 501 ipdir = os.path.realpath(_ip.ipython_dir)
500 502 try:
501 503 _ip.magic('cd "%s"' % ipdir)
502 504 nt.assert_equal(curpath(), ipdir)
503 505 _ip.magic('cd -')
504 506 nt.assert_equal(curpath(), startdir)
505 507 _ip.magic('pushd "%s"' % ipdir)
506 508 nt.assert_equal(curpath(), ipdir)
507 509 _ip.magic('popd')
508 510 nt.assert_equal(curpath(), startdir)
509 511 finally:
510 512 os.chdir(startdir)
511 513
512 514
513 515 def test_cd_force_quiet():
514 516 """Test OSMagics.cd_force_quiet option"""
515 517 _ip.config.OSMagics.cd_force_quiet = True
516 518 osmagics = osm.OSMagics(shell=_ip)
517 519
518 520 startdir = os.getcwd()
519 521 ipdir = os.path.realpath(_ip.ipython_dir)
520 522
521 523 try:
522 524 with tt.AssertNotPrints(ipdir):
523 525 osmagics.cd('"%s"' % ipdir)
524 526 with tt.AssertNotPrints(startdir):
525 527 osmagics.cd('-')
526 528 finally:
527 529 os.chdir(startdir)
528 530
529 531
530 532 def test_xmode():
531 533 # Calling xmode three times should be a no-op
532 534 xmode = _ip.InteractiveTB.mode
533 535 for i in range(4):
534 536 _ip.magic("xmode")
535 537 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
536 538
537 539 def test_reset_hard():
538 540 monitor = []
539 541 class A(object):
540 542 def __del__(self):
541 543 monitor.append(1)
542 544 def __repr__(self):
543 545 return "<A instance>"
544 546
545 547 _ip.user_ns["a"] = A()
546 548 _ip.run_cell("a")
547 549
548 550 nt.assert_equal(monitor, [])
549 551 _ip.magic("reset -f")
550 552 nt.assert_equal(monitor, [1])
551 553
552 554 class TestXdel(tt.TempFileMixin):
553 555 def test_xdel(self):
554 556 """Test that references from %run are cleared by xdel."""
555 557 src = ("class A(object):\n"
556 558 " monitor = []\n"
557 559 " def __del__(self):\n"
558 560 " self.monitor.append(1)\n"
559 561 "a = A()\n")
560 562 self.mktmp(src)
561 563 # %run creates some hidden references...
562 564 _ip.magic("run %s" % self.fname)
563 565 # ... as does the displayhook.
564 566 _ip.run_cell("a")
565 567
566 568 monitor = _ip.user_ns["A"].monitor
567 569 nt.assert_equal(monitor, [])
568 570
569 571 _ip.magic("xdel a")
570 572
571 573 # Check that a's __del__ method has been called.
572 574 nt.assert_equal(monitor, [1])
573 575
574 576 def doctest_who():
575 577 """doctest for %who
576 578
577 579 In [1]: %reset -f
578 580
579 581 In [2]: alpha = 123
580 582
581 583 In [3]: beta = 'beta'
582 584
583 585 In [4]: %who int
584 586 alpha
585 587
586 588 In [5]: %who str
587 589 beta
588 590
589 591 In [6]: %whos
590 592 Variable Type Data/Info
591 593 ----------------------------
592 594 alpha int 123
593 595 beta str beta
594 596
595 597 In [7]: %who_ls
596 598 Out[7]: ['alpha', 'beta']
597 599 """
598 600
599 601 def test_whos():
600 602 """Check that whos is protected against objects where repr() fails."""
601 603 class A(object):
602 604 def __repr__(self):
603 605 raise Exception()
604 606 _ip.user_ns['a'] = A()
605 607 _ip.magic("whos")
606 608
607 609 def doctest_precision():
608 610 """doctest for %precision
609 611
610 612 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
611 613
612 614 In [2]: %precision 5
613 615 Out[2]: '%.5f'
614 616
615 617 In [3]: f.float_format
616 618 Out[3]: '%.5f'
617 619
618 620 In [4]: %precision %e
619 621 Out[4]: '%e'
620 622
621 623 In [5]: f(3.1415927)
622 624 Out[5]: '3.141593e+00'
623 625 """
624 626
625 627 def test_debug_magic():
626 628 """Test debugging a small code with %debug
627 629
628 630 In [1]: with PdbTestInput(['c']):
629 631 ...: %debug print("a b") #doctest: +ELLIPSIS
630 632 ...:
631 633 ...
632 634 ipdb> c
633 635 a b
634 636 In [2]:
635 637 """
636 638
637 639 def test_psearch():
638 640 with tt.AssertPrints("dict.fromkeys"):
639 641 _ip.run_cell("dict.fr*?")
640 642 with tt.AssertPrints("Ο€.is_integer"):
641 643 _ip.run_cell("Ο€ = 3.14;\nΟ€.is_integ*?")
642 644
643 645 def test_timeit_shlex():
644 646 """test shlex issues with timeit (#1109)"""
645 647 _ip.ex("def f(*a,**kw): pass")
646 648 _ip.magic('timeit -n1 "this is a bug".count(" ")')
647 649 _ip.magic('timeit -r1 -n1 f(" ", 1)')
648 650 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
649 651 _ip.magic('timeit -r1 -n1 ("a " + "b")')
650 652 _ip.magic('timeit -r1 -n1 f("a " + "b")')
651 653 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
652 654
653 655
654 656 def test_timeit_special_syntax():
655 657 "Test %%timeit with IPython special syntax"
656 658 @register_line_magic
657 659 def lmagic(line):
658 660 ip = get_ipython()
659 661 ip.user_ns['lmagic_out'] = line
660 662
661 663 # line mode test
662 664 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
663 665 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
664 666 # cell mode test
665 667 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
666 668 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
667 669
668 670 def test_timeit_return():
669 671 """
670 672 test whether timeit -o return object
671 673 """
672 674
673 675 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
674 676 assert(res is not None)
675 677
676 678 def test_timeit_quiet():
677 679 """
678 680 test quiet option of timeit magic
679 681 """
680 682 with tt.AssertNotPrints("loops"):
681 683 _ip.run_cell("%timeit -n1 -r1 -q 1")
682 684
683 685 def test_timeit_return_quiet():
684 686 with tt.AssertNotPrints("loops"):
685 687 res = _ip.run_line_magic('timeit', '-n1 -r1 -q -o 1')
686 688 assert (res is not None)
687 689
688 690 def test_timeit_invalid_return():
689 691 with nt.assert_raises_regex(SyntaxError, "outside function"):
690 692 _ip.run_line_magic('timeit', 'return')
691 693
692 694 @dec.skipif(execution.profile is None)
693 695 def test_prun_special_syntax():
694 696 "Test %%prun with IPython special syntax"
695 697 @register_line_magic
696 698 def lmagic(line):
697 699 ip = get_ipython()
698 700 ip.user_ns['lmagic_out'] = line
699 701
700 702 # line mode test
701 703 _ip.run_line_magic('prun', '-q %lmagic my line')
702 704 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
703 705 # cell mode test
704 706 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
705 707 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
706 708
707 709 @dec.skipif(execution.profile is None)
708 710 def test_prun_quotes():
709 711 "Test that prun does not clobber string escapes (GH #1302)"
710 712 _ip.magic(r"prun -q x = '\t'")
711 713 nt.assert_equal(_ip.user_ns['x'], '\t')
712 714
713 715 def test_extension():
714 716 # Debugging information for failures of this test
715 717 print('sys.path:')
716 718 for p in sys.path:
717 719 print(' ', p)
718 720 print('CWD', os.getcwd())
719 721
720 722 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
721 723 daft_path = os.path.join(os.path.dirname(__file__), "daft_extension")
722 724 sys.path.insert(0, daft_path)
723 725 try:
724 726 _ip.user_ns.pop('arq', None)
725 727 invalidate_caches() # Clear import caches
726 728 _ip.magic("load_ext daft_extension")
727 729 nt.assert_equal(_ip.user_ns['arq'], 185)
728 730 _ip.magic("unload_ext daft_extension")
729 731 assert 'arq' not in _ip.user_ns
730 732 finally:
731 733 sys.path.remove(daft_path)
732 734
733 735
734 736 def test_notebook_export_json():
735 737 _ip = get_ipython()
736 738 _ip.history_manager.reset() # Clear any existing history.
737 739 cmds = [u"a=1", u"def b():\n return a**2", u"print('noΓ«l, Γ©tΓ©', b())"]
738 740 for i, cmd in enumerate(cmds, start=1):
739 741 _ip.history_manager.store_inputs(i, cmd)
740 742 with TemporaryDirectory() as td:
741 743 outfile = os.path.join(td, "nb.ipynb")
742 744 _ip.magic("notebook -e %s" % outfile)
743 745
744 746
745 747 class TestEnv(TestCase):
746 748
747 749 def test_env(self):
748 750 env = _ip.magic("env")
749 751 self.assertTrue(isinstance(env, dict))
750 752
751 753 def test_env_secret(self):
752 754 env = _ip.magic("env")
753 755 hidden = "<hidden>"
754 756 with mock.patch.dict(
755 757 os.environ,
756 758 {
757 759 "API_KEY": "abc123",
758 760 "SECRET_THING": "ssshhh",
759 761 "JUPYTER_TOKEN": "",
760 762 "VAR": "abc"
761 763 }
762 764 ):
763 765 env = _ip.magic("env")
764 766 assert env["API_KEY"] == hidden
765 767 assert env["SECRET_THING"] == hidden
766 768 assert env["JUPYTER_TOKEN"] == hidden
767 769 assert env["VAR"] == "abc"
768 770
769 771 def test_env_get_set_simple(self):
770 772 env = _ip.magic("env var val1")
771 773 self.assertEqual(env, None)
772 774 self.assertEqual(os.environ['var'], 'val1')
773 775 self.assertEqual(_ip.magic("env var"), 'val1')
774 776 env = _ip.magic("env var=val2")
775 777 self.assertEqual(env, None)
776 778 self.assertEqual(os.environ['var'], 'val2')
777 779
778 780 def test_env_get_set_complex(self):
779 781 env = _ip.magic("env var 'val1 '' 'val2")
780 782 self.assertEqual(env, None)
781 783 self.assertEqual(os.environ['var'], "'val1 '' 'val2")
782 784 self.assertEqual(_ip.magic("env var"), "'val1 '' 'val2")
783 785 env = _ip.magic('env var=val2 val3="val4')
784 786 self.assertEqual(env, None)
785 787 self.assertEqual(os.environ['var'], 'val2 val3="val4')
786 788
787 789 def test_env_set_bad_input(self):
788 790 self.assertRaises(UsageError, lambda: _ip.magic("set_env var"))
789 791
790 792 def test_env_set_whitespace(self):
791 793 self.assertRaises(UsageError, lambda: _ip.magic("env var A=B"))
792 794
793 795
794 796 class CellMagicTestCase(TestCase):
795 797
796 798 def check_ident(self, magic):
797 799 # Manually called, we get the result
798 800 out = _ip.run_cell_magic(magic, 'a', 'b')
799 801 nt.assert_equal(out, ('a','b'))
800 802 # Via run_cell, it goes into the user's namespace via displayhook
801 803 _ip.run_cell('%%' + magic +' c\nd\n')
802 804 nt.assert_equal(_ip.user_ns['_'], ('c','d\n'))
803 805
804 806 def test_cell_magic_func_deco(self):
805 807 "Cell magic using simple decorator"
806 808 @register_cell_magic
807 809 def cellm(line, cell):
808 810 return line, cell
809 811
810 812 self.check_ident('cellm')
811 813
812 814 def test_cell_magic_reg(self):
813 815 "Cell magic manually registered"
814 816 def cellm(line, cell):
815 817 return line, cell
816 818
817 819 _ip.register_magic_function(cellm, 'cell', 'cellm2')
818 820 self.check_ident('cellm2')
819 821
820 822 def test_cell_magic_class(self):
821 823 "Cell magics declared via a class"
822 824 @magics_class
823 825 class MyMagics(Magics):
824 826
825 827 @cell_magic
826 828 def cellm3(self, line, cell):
827 829 return line, cell
828 830
829 831 _ip.register_magics(MyMagics)
830 832 self.check_ident('cellm3')
831 833
832 834 def test_cell_magic_class2(self):
833 835 "Cell magics declared via a class, #2"
834 836 @magics_class
835 837 class MyMagics2(Magics):
836 838
837 839 @cell_magic('cellm4')
838 840 def cellm33(self, line, cell):
839 841 return line, cell
840 842
841 843 _ip.register_magics(MyMagics2)
842 844 self.check_ident('cellm4')
843 845 # Check that nothing is registered as 'cellm33'
844 846 c33 = _ip.find_cell_magic('cellm33')
845 847 nt.assert_equal(c33, None)
846 848
847 849 def test_file():
848 850 """Basic %%writefile"""
849 851 ip = get_ipython()
850 852 with TemporaryDirectory() as td:
851 853 fname = os.path.join(td, 'file1')
852 854 ip.run_cell_magic("writefile", fname, u'\n'.join([
853 855 'line1',
854 856 'line2',
855 857 ]))
856 858 s = Path(fname).read_text()
857 859 nt.assert_in('line1\n', s)
858 860 nt.assert_in('line2', s)
859 861
860 862 @dec.skip_win32
861 863 def test_file_single_quote():
862 864 """Basic %%writefile with embedded single quotes"""
863 865 ip = get_ipython()
864 866 with TemporaryDirectory() as td:
865 867 fname = os.path.join(td, '\'file1\'')
866 868 ip.run_cell_magic("writefile", fname, u'\n'.join([
867 869 'line1',
868 870 'line2',
869 871 ]))
870 872 s = Path(fname).read_text()
871 873 nt.assert_in('line1\n', s)
872 874 nt.assert_in('line2', s)
873 875
874 876 @dec.skip_win32
875 877 def test_file_double_quote():
876 878 """Basic %%writefile with embedded double quotes"""
877 879 ip = get_ipython()
878 880 with TemporaryDirectory() as td:
879 881 fname = os.path.join(td, '"file1"')
880 882 ip.run_cell_magic("writefile", fname, u'\n'.join([
881 883 'line1',
882 884 'line2',
883 885 ]))
884 886 s = Path(fname).read_text()
885 887 nt.assert_in('line1\n', s)
886 888 nt.assert_in('line2', s)
887 889
888 890 def test_file_var_expand():
889 891 """%%writefile $filename"""
890 892 ip = get_ipython()
891 893 with TemporaryDirectory() as td:
892 894 fname = os.path.join(td, 'file1')
893 895 ip.user_ns['filename'] = fname
894 896 ip.run_cell_magic("writefile", '$filename', u'\n'.join([
895 897 'line1',
896 898 'line2',
897 899 ]))
898 900 s = Path(fname).read_text()
899 901 nt.assert_in('line1\n', s)
900 902 nt.assert_in('line2', s)
901 903
902 904 def test_file_unicode():
903 905 """%%writefile with unicode cell"""
904 906 ip = get_ipython()
905 907 with TemporaryDirectory() as td:
906 908 fname = os.path.join(td, 'file1')
907 909 ip.run_cell_magic("writefile", fname, u'\n'.join([
908 910 u'linΓ©1',
909 911 u'linΓ©2',
910 912 ]))
911 913 with io.open(fname, encoding='utf-8') as f:
912 914 s = f.read()
913 915 nt.assert_in(u'linΓ©1\n', s)
914 916 nt.assert_in(u'linΓ©2', s)
915 917
916 918 def test_file_amend():
917 919 """%%writefile -a amends files"""
918 920 ip = get_ipython()
919 921 with TemporaryDirectory() as td:
920 922 fname = os.path.join(td, 'file2')
921 923 ip.run_cell_magic("writefile", fname, u'\n'.join([
922 924 'line1',
923 925 'line2',
924 926 ]))
925 927 ip.run_cell_magic("writefile", "-a %s" % fname, u'\n'.join([
926 928 'line3',
927 929 'line4',
928 930 ]))
929 931 s = Path(fname).read_text()
930 932 nt.assert_in('line1\n', s)
931 933 nt.assert_in('line3\n', s)
932 934
933 935 def test_file_spaces():
934 936 """%%file with spaces in filename"""
935 937 ip = get_ipython()
936 938 with TemporaryWorkingDirectory() as td:
937 939 fname = "file name"
938 940 ip.run_cell_magic("file", '"%s"'%fname, u'\n'.join([
939 941 'line1',
940 942 'line2',
941 943 ]))
942 944 s = Path(fname).read_text()
943 945 nt.assert_in('line1\n', s)
944 946 nt.assert_in('line2', s)
945 947
946 948 def test_script_config():
947 949 ip = get_ipython()
948 950 ip.config.ScriptMagics.script_magics = ['whoda']
949 951 sm = script.ScriptMagics(shell=ip)
950 952 nt.assert_in('whoda', sm.magics['cell'])
951 953
952 954 @dec.skip_iptest_but_not_pytest
953 955 @dec.skip_win32
956 @pytest.mark.skipif(
957 sys.platform == "win32", reason="This test does not run under Windows"
958 )
954 959 def test_script_out():
955 960 assert asyncio.get_event_loop().is_running() is False
956 961
957 962 ip = get_ipython()
958 963 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
959 964 assert asyncio.get_event_loop().is_running() is False
960 965 nt.assert_equal(ip.user_ns['output'], 'hi\n')
961 966
962 967 @dec.skip_iptest_but_not_pytest
963 968 @dec.skip_win32
969 @pytest.mark.skipif(
970 sys.platform == "win32", reason="This test does not run under Windows"
971 )
964 972 def test_script_err():
965 973 ip = get_ipython()
966 974 assert asyncio.get_event_loop().is_running() is False
967 975 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
968 976 assert asyncio.get_event_loop().is_running() is False
969 977 nt.assert_equal(ip.user_ns['error'], 'hello\n')
970 978
971 979
972 980 @dec.skip_iptest_but_not_pytest
973 981 @dec.skip_win32
982 @pytest.mark.skipif(
983 sys.platform == "win32", reason="This test does not run under Windows"
984 )
974 985 def test_script_out_err():
975 986
976 987 ip = get_ipython()
977 988 ip.run_cell_magic(
978 989 "script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2"
979 990 )
980 991 nt.assert_equal(ip.user_ns["output"], "hi\n")
981 992 nt.assert_equal(ip.user_ns["error"], "hello\n")
982 993
983 994
984 995 @dec.skip_iptest_but_not_pytest
985 996 @dec.skip_win32
997 @pytest.mark.skipif(
998 sys.platform == "win32", reason="This test does not run under Windows"
999 )
986 1000 async def test_script_bg_out():
987 1001 ip = get_ipython()
988 1002 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
989 1003 nt.assert_equal((await ip.user_ns["output"].read()), b"hi\n")
990 1004 ip.user_ns["output"].close()
991 1005 asyncio.get_event_loop().stop()
992 1006
993 1007 @dec.skip_iptest_but_not_pytest
994 1008 @dec.skip_win32
1009 @pytest.mark.skipif(
1010 sys.platform == "win32", reason="This test does not run under Windows"
1011 )
995 1012 async def test_script_bg_err():
996 1013 ip = get_ipython()
997 1014 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
998 1015 nt.assert_equal((await ip.user_ns["error"].read()), b"hello\n")
999 1016 ip.user_ns["error"].close()
1000 1017
1001 1018
1002 1019 @dec.skip_iptest_but_not_pytest
1003 1020 @dec.skip_win32
1021 @pytest.mark.skipif(
1022 sys.platform == "win32", reason="This test does not run under Windows"
1023 )
1004 1024 async def test_script_bg_out_err():
1005 1025 ip = get_ipython()
1006 1026 ip.run_cell_magic(
1007 1027 "script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2"
1008 1028 )
1009 1029 nt.assert_equal((await ip.user_ns["output"].read()), b"hi\n")
1010 1030 nt.assert_equal((await ip.user_ns["error"].read()), b"hello\n")
1011 1031 ip.user_ns["output"].close()
1012 1032 ip.user_ns["error"].close()
1013 1033
1014 1034
1015 1035 def test_script_defaults():
1016 1036 ip = get_ipython()
1017 1037 for cmd in ['sh', 'bash', 'perl', 'ruby']:
1018 1038 try:
1019 1039 find_cmd(cmd)
1020 1040 except Exception:
1021 1041 pass
1022 1042 else:
1023 1043 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
1024 1044
1025 1045
1026 1046 @magics_class
1027 1047 class FooFoo(Magics):
1028 1048 """class with both %foo and %%foo magics"""
1029 1049 @line_magic('foo')
1030 1050 def line_foo(self, line):
1031 1051 "I am line foo"
1032 1052 pass
1033 1053
1034 1054 @cell_magic("foo")
1035 1055 def cell_foo(self, line, cell):
1036 1056 "I am cell foo, not line foo"
1037 1057 pass
1038 1058
1039 1059 def test_line_cell_info():
1040 1060 """%%foo and %foo magics are distinguishable to inspect"""
1041 1061 ip = get_ipython()
1042 1062 ip.magics_manager.register(FooFoo)
1043 1063 oinfo = ip.object_inspect('foo')
1044 1064 nt.assert_true(oinfo['found'])
1045 1065 nt.assert_true(oinfo['ismagic'])
1046 1066
1047 1067 oinfo = ip.object_inspect('%%foo')
1048 1068 nt.assert_true(oinfo['found'])
1049 1069 nt.assert_true(oinfo['ismagic'])
1050 1070 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
1051 1071
1052 1072 oinfo = ip.object_inspect('%foo')
1053 1073 nt.assert_true(oinfo['found'])
1054 1074 nt.assert_true(oinfo['ismagic'])
1055 1075 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
1056 1076
1057 1077 def test_multiple_magics():
1058 1078 ip = get_ipython()
1059 1079 foo1 = FooFoo(ip)
1060 1080 foo2 = FooFoo(ip)
1061 1081 mm = ip.magics_manager
1062 1082 mm.register(foo1)
1063 1083 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
1064 1084 mm.register(foo2)
1065 1085 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
1066 1086
1067 1087 def test_alias_magic():
1068 1088 """Test %alias_magic."""
1069 1089 ip = get_ipython()
1070 1090 mm = ip.magics_manager
1071 1091
1072 1092 # Basic operation: both cell and line magics are created, if possible.
1073 1093 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
1074 1094 nt.assert_in('timeit_alias', mm.magics['line'])
1075 1095 nt.assert_in('timeit_alias', mm.magics['cell'])
1076 1096
1077 1097 # --cell is specified, line magic not created.
1078 1098 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
1079 1099 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
1080 1100 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
1081 1101
1082 1102 # Test that line alias is created successfully.
1083 1103 ip.run_line_magic('alias_magic', '--line env_alias env')
1084 1104 nt.assert_equal(ip.run_line_magic('env', ''),
1085 1105 ip.run_line_magic('env_alias', ''))
1086 1106
1087 1107 # Test that line alias with parameters passed in is created successfully.
1088 1108 ip.run_line_magic('alias_magic', '--line history_alias history --params ' + shlex.quote('3'))
1089 1109 nt.assert_in('history_alias', mm.magics['line'])
1090 1110
1091 1111
1092 1112 def test_save():
1093 1113 """Test %save."""
1094 1114 ip = get_ipython()
1095 1115 ip.history_manager.reset() # Clear any existing history.
1096 1116 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
1097 1117 for i, cmd in enumerate(cmds, start=1):
1098 1118 ip.history_manager.store_inputs(i, cmd)
1099 1119 with TemporaryDirectory() as tmpdir:
1100 1120 file = os.path.join(tmpdir, "testsave.py")
1101 1121 ip.run_line_magic("save", "%s 1-10" % file)
1102 1122 content = Path(file).read_text()
1103 1123 nt.assert_equal(content.count(cmds[0]), 1)
1104 1124 nt.assert_in("coding: utf-8", content)
1105 1125 ip.run_line_magic("save", "-a %s 1-10" % file)
1106 1126 content = Path(file).read_text()
1107 1127 nt.assert_equal(content.count(cmds[0]), 2)
1108 1128 nt.assert_in("coding: utf-8", content)
1109 1129
1110 1130
1111 1131 def test_save_with_no_args():
1112 1132 ip = get_ipython()
1113 1133 ip.history_manager.reset() # Clear any existing history.
1114 1134 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())", "%save"]
1115 1135 for i, cmd in enumerate(cmds, start=1):
1116 1136 ip.history_manager.store_inputs(i, cmd)
1117 1137
1118 1138 with TemporaryDirectory() as tmpdir:
1119 1139 path = os.path.join(tmpdir, "testsave.py")
1120 1140 ip.run_line_magic("save", path)
1121 1141 content = Path(path).read_text()
1122 1142 expected_content = dedent(
1123 1143 """\
1124 1144 # coding: utf-8
1125 1145 a=1
1126 1146 def b():
1127 1147 return a**2
1128 1148 print(a, b())
1129 1149 """
1130 1150 )
1131 1151 nt.assert_equal(content, expected_content)
1132 1152
1133 1153
1134 1154 def test_store():
1135 1155 """Test %store."""
1136 1156 ip = get_ipython()
1137 1157 ip.run_line_magic('load_ext', 'storemagic')
1138 1158
1139 1159 # make sure the storage is empty
1140 1160 ip.run_line_magic('store', '-z')
1141 1161 ip.user_ns['var'] = 42
1142 1162 ip.run_line_magic('store', 'var')
1143 1163 ip.user_ns['var'] = 39
1144 1164 ip.run_line_magic('store', '-r')
1145 1165 nt.assert_equal(ip.user_ns['var'], 42)
1146 1166
1147 1167 ip.run_line_magic('store', '-d var')
1148 1168 ip.user_ns['var'] = 39
1149 1169 ip.run_line_magic('store' , '-r')
1150 1170 nt.assert_equal(ip.user_ns['var'], 39)
1151 1171
1152 1172
1153 1173 def _run_edit_test(arg_s, exp_filename=None,
1154 1174 exp_lineno=-1,
1155 1175 exp_contents=None,
1156 1176 exp_is_temp=None):
1157 1177 ip = get_ipython()
1158 1178 M = code.CodeMagics(ip)
1159 1179 last_call = ['','']
1160 1180 opts,args = M.parse_options(arg_s,'prxn:')
1161 1181 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
1162 1182
1163 1183 if exp_filename is not None:
1164 1184 nt.assert_equal(exp_filename, filename)
1165 1185 if exp_contents is not None:
1166 1186 with io.open(filename, 'r', encoding='utf-8') as f:
1167 1187 contents = f.read()
1168 1188 nt.assert_equal(exp_contents, contents)
1169 1189 if exp_lineno != -1:
1170 1190 nt.assert_equal(exp_lineno, lineno)
1171 1191 if exp_is_temp is not None:
1172 1192 nt.assert_equal(exp_is_temp, is_temp)
1173 1193
1174 1194
1175 1195 def test_edit_interactive():
1176 1196 """%edit on interactively defined objects"""
1177 1197 ip = get_ipython()
1178 1198 n = ip.execution_count
1179 1199 ip.run_cell(u"def foo(): return 1", store_history=True)
1180 1200
1181 1201 try:
1182 1202 _run_edit_test("foo")
1183 1203 except code.InteractivelyDefined as e:
1184 1204 nt.assert_equal(e.index, n)
1185 1205 else:
1186 1206 raise AssertionError("Should have raised InteractivelyDefined")
1187 1207
1188 1208
1189 1209 def test_edit_cell():
1190 1210 """%edit [cell id]"""
1191 1211 ip = get_ipython()
1192 1212
1193 1213 ip.run_cell(u"def foo(): return 1", store_history=True)
1194 1214
1195 1215 # test
1196 1216 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
1197 1217
1198 1218 def test_edit_fname():
1199 1219 """%edit file"""
1200 1220 # test
1201 1221 _run_edit_test("test file.py", exp_filename="test file.py")
1202 1222
1203 1223 def test_bookmark():
1204 1224 ip = get_ipython()
1205 1225 ip.run_line_magic('bookmark', 'bmname')
1206 1226 with tt.AssertPrints('bmname'):
1207 1227 ip.run_line_magic('bookmark', '-l')
1208 1228 ip.run_line_magic('bookmark', '-d bmname')
1209 1229
1210 1230 def test_ls_magic():
1211 1231 ip = get_ipython()
1212 1232 json_formatter = ip.display_formatter.formatters['application/json']
1213 1233 json_formatter.enabled = True
1214 1234 lsmagic = ip.magic('lsmagic')
1215 1235 with warnings.catch_warnings(record=True) as w:
1216 1236 j = json_formatter(lsmagic)
1217 1237 nt.assert_equal(sorted(j), ['cell', 'line'])
1218 1238 nt.assert_equal(w, []) # no warnings
1219 1239
1220 1240 def test_strip_initial_indent():
1221 1241 def sii(s):
1222 1242 lines = s.splitlines()
1223 1243 return '\n'.join(code.strip_initial_indent(lines))
1224 1244
1225 1245 nt.assert_equal(sii(" a = 1\nb = 2"), "a = 1\nb = 2")
1226 1246 nt.assert_equal(sii(" a\n b\nc"), "a\n b\nc")
1227 1247 nt.assert_equal(sii("a\n b"), "a\n b")
1228 1248
1229 1249 def test_logging_magic_quiet_from_arg():
1230 1250 _ip.config.LoggingMagics.quiet = False
1231 1251 lm = logging.LoggingMagics(shell=_ip)
1232 1252 with TemporaryDirectory() as td:
1233 1253 try:
1234 1254 with tt.AssertNotPrints(re.compile("Activating.*")):
1235 1255 lm.logstart('-q {}'.format(
1236 1256 os.path.join(td, "quiet_from_arg.log")))
1237 1257 finally:
1238 1258 _ip.logger.logstop()
1239 1259
1240 1260 def test_logging_magic_quiet_from_config():
1241 1261 _ip.config.LoggingMagics.quiet = True
1242 1262 lm = logging.LoggingMagics(shell=_ip)
1243 1263 with TemporaryDirectory() as td:
1244 1264 try:
1245 1265 with tt.AssertNotPrints(re.compile("Activating.*")):
1246 1266 lm.logstart(os.path.join(td, "quiet_from_config.log"))
1247 1267 finally:
1248 1268 _ip.logger.logstop()
1249 1269
1250 1270
1251 1271 def test_logging_magic_not_quiet():
1252 1272 _ip.config.LoggingMagics.quiet = False
1253 1273 lm = logging.LoggingMagics(shell=_ip)
1254 1274 with TemporaryDirectory() as td:
1255 1275 try:
1256 1276 with tt.AssertPrints(re.compile("Activating.*")):
1257 1277 lm.logstart(os.path.join(td, "not_quiet.log"))
1258 1278 finally:
1259 1279 _ip.logger.logstop()
1260 1280
1261 1281
1262 1282 def test_time_no_var_expand():
1263 1283 _ip.user_ns['a'] = 5
1264 1284 _ip.user_ns['b'] = []
1265 1285 _ip.magic('time b.append("{a}")')
1266 1286 assert _ip.user_ns['b'] == ['{a}']
1267 1287
1268 1288
1269 1289 # this is slow, put at the end for local testing.
1270 1290 def test_timeit_arguments():
1271 1291 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
1272 1292 if sys.version_info < (3,7):
1273 1293 _ip.magic("timeit -n1 -r1 ('#')")
1274 1294 else:
1275 1295 # 3.7 optimize no-op statement like above out, and complain there is
1276 1296 # nothing in the for loop.
1277 1297 _ip.magic("timeit -n1 -r1 a=('#')")
1278 1298
1279 1299
1280 1300 TEST_MODULE = """
1281 1301 print('Loaded my_tmp')
1282 1302 if __name__ == "__main__":
1283 1303 print('I just ran a script')
1284 1304 """
1285 1305
1286 1306
1287 1307 def test_run_module_from_import_hook():
1288 1308 "Test that a module can be loaded via an import hook"
1289 1309 with TemporaryDirectory() as tmpdir:
1290 1310 fullpath = os.path.join(tmpdir, 'my_tmp.py')
1291 1311 Path(fullpath).write_text(TEST_MODULE)
1292 1312
1293 1313 class MyTempImporter(object):
1294 1314 def __init__(self):
1295 1315 pass
1296 1316
1297 1317 def find_module(self, fullname, path=None):
1298 1318 if 'my_tmp' in fullname:
1299 1319 return self
1300 1320 return None
1301 1321
1302 1322 def load_module(self, name):
1303 1323 import imp
1304 1324 return imp.load_source('my_tmp', fullpath)
1305 1325
1306 1326 def get_code(self, fullname):
1307 1327 return compile(Path(fullpath).read_text(), "foo", "exec")
1308 1328
1309 1329 def is_package(self, __):
1310 1330 return False
1311 1331
1312 1332 sys.meta_path.insert(0, MyTempImporter())
1313 1333
1314 1334 with capture_output() as captured:
1315 1335 _ip.magic("run -m my_tmp")
1316 1336 _ip.run_cell("import my_tmp")
1317 1337
1318 1338 output = "Loaded my_tmp\nI just ran a script\nLoaded my_tmp\n"
1319 1339 nt.assert_equal(output, captured.stdout)
1320 1340
1321 1341 sys.meta_path.pop(0)
General Comments 0
You need to be logged in to leave comments. Login now