Debian Codegraph @

tests/test_magic.py

raw
1 # -*- coding: utf-8 -*-
2 """Tests for various magic functions."""
3
4 import collections
5 import gc
6 import io
7 import json
8 import os
9 import platform
10 import re
11 import shlex
12 import signal
13 import sys
14 import warnings
15 from importlib import invalidate_caches
16 from io import StringIO
17 from pathlib import Path
18 from time import sleep
19 from threading import Thread
20 from subprocess import CalledProcessError
21 from textwrap import dedent
22 from unittest import TestCase, mock
23
24 import pytest
25
26 from IPython import get_ipython
27 from IPython.core import magic
28 from IPython.core.error import UsageError
29 from IPython.core.magic import (
30 Magics,
31 cell_magic,
32 line_magic,
33 magics_class,
34 register_cell_magic,
35 register_line_magic,
36 )
37 from IPython.core.magics import code, execution, logging, osm, script
38 from IPython.core.history import HistoryOutput
39 from IPython.testing import decorators as dec
40 from IPython.testing import tools as tt
41 from IPython.utils.io import capture_output
42 from IPython.utils.process import find_cmd
43 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
44 from IPython.utils.syspathcontext import prepended_to_syspath
45
46 from .test_debugger import PdbTestInput
47
48 from tempfile import NamedTemporaryFile
49
50
51 @magic.magics_class
52 class DummyMagics(magic.Magics):
53 pass
54
55
56 def test_extract_code_ranges():
57 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
58 expected = [
59 (0, 1),
60 (2, 3),
61 (4, 6),
62 (6, 9),
63 (9, 14),
64 (16, None),
65 (None, 9),
66 (9, None),
67 (None, 13),
68 (None, None),
69 ]
70 actual = list(code.extract_code_ranges(instr))
71 assert actual == expected
72
73
74 def test_extract_symbols():
75 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
76 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
77 expected = [
78 ([], ["a"]),
79 (["def b():\n return 42\n"], []),
80 (["class A: pass\n"], []),
81 (["class A: pass\n", "def b():\n return 42\n"], []),
82 (["class A: pass\n"], ["a"]),
83 ([], ["z"]),
84 ]
85 for symbols, exp in zip(symbols_args, expected):
86 assert code.extract_symbols(source, symbols) == exp
87
88
89 def test_extract_symbols_raises_exception_with_non_python_code():
90 source = "=begin A Ruby program :)=end\n" "def hello\n" "puts 'Hello world'\n" "end"
91 with pytest.raises(SyntaxError):
92 code.extract_symbols(source, "hello")
93
94
95 def test_magic_not_found():
96 # magic not found raises UsageError
97 with pytest.raises(UsageError):
98 _ip.run_line_magic("doesntexist", "")
99
100 # ensure result isn't success when a magic isn't found
101 result = _ip.run_cell("%doesntexist")
102 assert isinstance(result.error_in_exec, UsageError)
103
104
105 def test_cell_magic_not_found():
106 # magic not found raises UsageError
107 with pytest.raises(UsageError):
108 _ip.run_cell_magic("doesntexist", "line", "cell")
109
110 # ensure result isn't success when a magic isn't found
111 result = _ip.run_cell("%%doesntexist")
112 assert isinstance(result.error_in_exec, UsageError)
113
114
115 def test_magic_error_status():
116 def fail(shell):
117 1 / 0
118
119 _ip.register_magic_function(fail)
120 result = _ip.run_cell("%fail")
121 assert isinstance(result.error_in_exec, ZeroDivisionError)
122
123
124 def test_config():
125 """test that config magic does not raise
126 can happen if Configurable init is moved too early into
127 Magics.__init__ as then a Config object will be registered as a
128 magic.
129 """
130 ## should not raise.
131 _ip.run_line_magic("config", "")
132
133
134 def test_config_available_configs():
135 """test that config magic prints available configs in unique and
136 sorted order."""
137 with capture_output() as captured:
138 _ip.run_line_magic("config", "")
139
140 stdout = captured.stdout
141 config_classes = stdout.strip().split("\n")[1:]
142 assert config_classes == sorted(set(config_classes))
143
144
145 def test_config_print_class():
146 """test that config with a classname prints the class's options."""
147 with capture_output() as captured:
148 _ip.run_line_magic("config", "TerminalInteractiveShell")
149
150 stdout = captured.stdout
151 assert re.match(
152 "TerminalInteractiveShell.* options", stdout.splitlines()[0]
153 ), f"{stdout}\n\n1st line of stdout not like 'TerminalInteractiveShell.* options'"
154
155
156 def test_rehashx():
157 # clear up everything
158 _ip.alias_manager.clear_aliases()
159 del _ip.db["syscmdlist"]
160
161 _ip.run_line_magic("rehashx", "")
162 # Practically ALL ipython development systems will have more than 10 aliases
163
164 assert len(_ip.alias_manager.aliases) > 10
165 for name, cmd in _ip.alias_manager.aliases:
166 # we must strip dots from alias names
167 assert "." not in name
168
169 # rehashx must fill up syscmdlist
170 scoms = _ip.db["syscmdlist"]
171 assert len(scoms) > 10
172
173
174 def test_magic_parse_options():
175 """Test that we don't mangle paths when parsing magic options."""
176 ip = get_ipython()
177 path = "c:\\x"
178 m = DummyMagics(ip)
179 opts = m.parse_options("-f %s" % path, "f:")[0]
180 # argv splitting is os-dependent
181 if os.name == "posix":
182 expected = "c:x"
183 else:
184 expected = path
185 assert opts["f"] == expected
186
187
188 def test_magic_parse_long_options():
189 """Magic.parse_options can handle --foo=bar long options"""
190 ip = get_ipython()
191 m = DummyMagics(ip)
192 opts, _ = m.parse_options("--foo --bar=bubble", "a", "foo", "bar=")
193 assert "foo" in opts
194 assert "bar" in opts
195 assert opts["bar"] == "bubble"
196
197
198 def doctest_hist_f():
199 """Test %hist -f with temporary filename.
200
201 In [9]: import tempfile, os
202
203 In [10]: fd, tfile = tempfile.mkstemp('.py','tmp-ipython-')
204 In [11]: os.close(fd)
205
206 In [12]: %history -nl -y -f $tfile 3
207
208 In [14]: import os; os.unlink(tfile)
209 """
210
211
212 def doctest_hist_op():
213 """Test %hist -op
214
215 In [1]: class b(float):
216 ...: pass
217 ...:
218
219 In [2]: class s(object):
220 ...: def __str__(self):
221 ...: return 's'
222 ...:
223
224 In [3]:
225
226 In [4]: class r(b):
227 ...: def __repr__(self):
228 ...: return 'r'
229 ...:
230
231 In [5]: class sr(s,r): pass
232 ...:
233
234 In [6]:
235
236 In [7]: bb=b()
237
238 In [8]: ss=s()
239
240 In [9]: rr=r()
241
242 In [10]: ssrr=sr()
243
244 In [11]: 4.5
245 Out[11]: 4.5
246
247 In [12]: str(ss)
248 Out[12]: 's'
249
250 In [13]:
251
252 In [14]: %hist -op
253 >>> class b:
254 ... pass
255 ...
256 >>> class s(b):
257 ... def __str__(self):
258 ... return 's'
259 ...
260 >>>
261 >>> class r(b):
262 ... def __repr__(self):
263 ... return 'r'
264 ...
265 >>> class sr(s,r): pass
266 >>>
267 >>> bb=b()
268 >>> ss=s()
269 >>> rr=r()
270 >>> ssrr=sr()
271 >>> 4.5
272 4.5
273 >>> str(ss)
274 's'
275 >>>
276 """
277
278
279 def test_hist_pof():
280 ip = get_ipython()
281 ip.run_cell("1+2", store_history=True)
282 # raise Exception(ip.history_manager.session_number)
283 # raise Exception(list(ip.history_manager._get_range_session()))
284 with TemporaryDirectory() as td:
285 tf = os.path.join(td, "hist.py")
286 ip.run_line_magic("history", "-pof %s" % tf)
287 assert os.path.isfile(tf)
288
289
290 def test_macro():
291 ip = get_ipython()
292 ip.history_manager.reset() # Clear any existing history.
293 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
294 for i, cmd in enumerate(cmds, start=1):
295 ip.history_manager.store_inputs(i, cmd)
296 ip.run_line_magic("macro", "test 1-3")
297 assert ip.user_ns["test"].value == "\n".join(cmds) + "\n"
298
299 # List macros
300 assert "test" in ip.run_line_magic("macro", "")
301
302
303 def test_macro_run():
304 """Test that we can run a multi-line macro successfully."""
305 ip = get_ipython()
306 ip.history_manager.reset()
307 cmds = ["a=10", "a+=1", "print(a)", "%macro test 2-3"]
308 for cmd in cmds:
309 ip.run_cell(cmd, store_history=True)
310 assert ip.user_ns["test"].value == "a+=1\nprint(a)\n"
311 with tt.AssertPrints("12"):
312 ip.run_cell("test")
313 with tt.AssertPrints("13"):
314 ip.run_cell("test")
315
316
317 def test_magic_magic():
318 """Test %magic"""
319 ip = get_ipython()
320 with capture_output() as captured:
321 ip.run_line_magic("magic", "")
322
323 stdout = captured.stdout
324 assert "%magic" in stdout
325 assert "IPython" in stdout
326 assert "Available" in stdout
327
328
329 @dec.skipif_not_numpy
330 def test_numpy_reset_array_undec():
331 "Test '%reset array' functionality"
332 _ip.ex("import numpy as np")
333 _ip.ex("a = np.empty(2)")
334 assert "a" in _ip.user_ns
335 _ip.run_line_magic("reset", "-f array")
336 assert "a" not in _ip.user_ns
337
338
339 @pytest.fixture()
340 def underscore_not_in_builtins():
341 import builtins
342
343 if "_" in builtins.__dict__:
344 del builtins.__dict__["_"]
345
346
347 def test_reset_out(underscore_not_in_builtins):
348 "Test '%reset out' magic"
349 _ip.run_cell("parrot = 'dead'", store_history=True)
350 # test '%reset -f out', make an Out prompt
351 _ip.run_cell("parrot", store_history=True)
352 assert "dead" in [_ip.user_ns[x] for x in ("_", "__", "___")]
353 _ip.run_line_magic("reset", "-f out")
354 assert "dead" not in [_ip.user_ns[x] for x in ("_", "__", "___")]
355 assert len(_ip.user_ns["Out"]) == 0
356
357
358 def test_reset_in():
359 "Test '%reset in' magic"
360 # test '%reset -f in'
361 _ip.run_cell("parrot", store_history=True)
362 assert "parrot" in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")]
363 _ip.run_line_magic("reset", "-f in")
364 assert "parrot" not in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")]
365 assert len(set(_ip.user_ns["In"])) == 1
366
367
368 def test_reset_dhist():
369 "Test '%reset dhist' magic"
370 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
371 _ip.run_line_magic("cd", os.path.dirname(pytest.__file__))
372 _ip.run_line_magic("cd", "-")
373 assert len(_ip.user_ns["_dh"]) > 0
374 _ip.run_line_magic("reset", "-f dhist")
375 assert len(_ip.user_ns["_dh"]) == 0
376 _ip.run_cell("_dh = [d for d in tmp]") # restore
377
378
379 def test_reset_in_length():
380 "Test that '%reset in' preserves In[] length"
381 _ip.run_cell("print 'foo'")
382 _ip.run_cell("reset -f in")
383 assert len(_ip.user_ns["In"]) == _ip.displayhook.prompt_count + 1
384
385
386 class TestResetErrors(TestCase):
387 def test_reset_redefine(self):
388 @magics_class
389 class KernelMagics(Magics):
390 @line_magic
391 def less(self, shell):
392 pass
393
394 _ip.register_magics(KernelMagics)
395
396 with self.assertLogs() as cm:
397 # hack, we want to just capture logs, but assertLogs fails if not
398 # logs get produce.
399 # so log one things we ignore.
400 import logging as log_mod
401
402 log = log_mod.getLogger()
403 log.info("Nothing")
404 # end hack.
405 _ip.run_cell("reset -f")
406
407 assert len(cm.output) == 1
408 for out in cm.output:
409 assert "Invalid alias" not in out
410
411
412 def test_tb_syntaxerror():
413 """test %tb after a SyntaxError"""
414 ip = get_ipython()
415 ip.run_cell("for")
416
417 # trap and validate stdout
418 save_stdout = sys.stdout
419 try:
420 sys.stdout = StringIO()
421 ip.run_cell("%tb")
422 out = sys.stdout.getvalue()
423 finally:
424 sys.stdout = save_stdout
425 # trim output, and only check the last line
426 last_line = out.rstrip().splitlines()[-1].strip()
427 assert last_line == "SyntaxError: invalid syntax"
428
429
430 def test_time():
431 ip = get_ipython()
432
433 with tt.AssertPrints("Wall time: "):
434 ip.run_cell("%time None")
435
436 ip.run_cell("def f(kmjy):\n" " %time print (2*kmjy)")
437
438 with tt.AssertPrints("Wall time: "):
439 with tt.AssertPrints("hihi", suppress=False):
440 ip.run_cell("f('hi')")
441
442 with tt.AssertPrints("a space"):
443 with tt.AssertPrints("Wall time: ", suppress=False):
444 with tt.AssertPrints("CPU times: ", suppress=False):
445 ip.run_cell('%time print("a space")')
446
447
448 # ';' at the end of %time prevents instruction value to be printed.
449 # This tests fix for #13837.
450 def test_time_no_output_with_semicolon():
451 ip = get_ipython()
452
453 # Test %time cases
454 with tt.AssertPrints(" 123456"):
455 with tt.AssertPrints("Wall time: ", suppress=False):
456 with tt.AssertPrints("CPU times: ", suppress=False):
457 ip.run_cell("%time 123000+456")
458
459 with tt.AssertNotPrints(" 123456"):
460 with tt.AssertPrints("Wall time: ", suppress=False):
461 with tt.AssertPrints("CPU times: ", suppress=False):
462 ip.run_cell("%time 123000+456;")
463
464 with tt.AssertPrints(" 123456"):
465 with tt.AssertPrints("Wall time: ", suppress=False):
466 with tt.AssertPrints("CPU times: ", suppress=False):
467 ip.run_cell("%time 123000+456 # Comment")
468
469 with tt.AssertNotPrints(" 123456"):
470 with tt.AssertPrints("Wall time: ", suppress=False):
471 with tt.AssertPrints("CPU times: ", suppress=False):
472 ip.run_cell("%time 123000+456; # Comment")
473
474 with tt.AssertPrints(" 123456"):
475 with tt.AssertPrints("Wall time: ", suppress=False):
476 with tt.AssertPrints("CPU times: ", suppress=False):
477 ip.run_cell("%time 123000+456 # ;Comment")
478
479 # Test %%time cases
480 with tt.AssertPrints("123456"):
481 with tt.AssertPrints("Wall time: ", suppress=False):
482 with tt.AssertPrints("CPU times: ", suppress=False):
483 ip.run_cell("%%time\n123000+456\n\n\n")
484
485 with tt.AssertNotPrints("123456"):
486 with tt.AssertPrints("Wall time: ", suppress=False):
487 with tt.AssertPrints("CPU times: ", suppress=False):
488 ip.run_cell("%%time\n123000+456;\n\n\n")
489
490 with tt.AssertPrints("123456"):
491 with tt.AssertPrints("Wall time: ", suppress=False):
492 with tt.AssertPrints("CPU times: ", suppress=False):
493 ip.run_cell("%%time\n123000+456 # Comment\n\n\n")
494
495 with tt.AssertNotPrints("123456"):
496 with tt.AssertPrints("Wall time: ", suppress=False):
497 with tt.AssertPrints("CPU times: ", suppress=False):
498 ip.run_cell("%%time\n123000+456; # Comment\n\n\n")
499
500 with tt.AssertPrints("123456"):
501 with tt.AssertPrints("Wall time: ", suppress=False):
502 with tt.AssertPrints("CPU times: ", suppress=False):
503 ip.run_cell("%%time\n123000+456 # ;Comment\n\n\n")
504
505
506 def test_time_last_not_expression():
507 ip.run_cell("%%time\n" "var_1 = 1\n" "var_2 = 2\n")
508 assert ip.user_ns["var_1"] == 1
509 del ip.user_ns["var_1"]
510 assert ip.user_ns["var_2"] == 2
511 del ip.user_ns["var_2"]
512
513
514 @dec.skip_win32
515 def test_time2():
516 ip = get_ipython()
517
518 with tt.AssertPrints("CPU times: user "):
519 ip.run_cell("%time None")
520
521
522 def test_time3():
523 """Erroneous magic function calls, issue gh-3334"""
524 ip = get_ipython()
525 ip.user_ns.pop("run", None)
526
527 with tt.AssertNotPrints("not found", channel="stderr"):
528 ip.run_cell("%%time\n" "run = 0\n" "run += 1")
529
530
531 def test_multiline_time(underscore_not_in_builtins):
532 """Make sure last statement from time return a value."""
533 ip = get_ipython()
534 ip.user_ns.pop("run", None)
535
536 ip.run_cell(
537 dedent(
538 """\
539 %%time
540 a = "ho"
541 b = "hey"
542 a+b
543 """
544 )
545 )
546 assert ip.user_ns_hidden["_"] == "hohey"
547
548
549 def test_time_local_ns():
550 """
551 Test that local_ns is actually global_ns when running a cell magic
552 """
553 ip = get_ipython()
554 ip.run_cell("%%time\n" "myvar = 1")
555 assert ip.user_ns["myvar"] == 1
556 del ip.user_ns["myvar"]
557
558
559 def test_time_microseconds_display():
560 """Ensure ASCII is used when necessary"""
561 with mock.patch("sys.stdout", io.TextIOWrapper(StringIO(), encoding="utf-8")):
562 assert execution._format_time(0.000001) == "1 \u03bcs"
563 with mock.patch("sys.stdout", io.TextIOWrapper(StringIO(), encoding="ascii")):
564 assert execution._format_time(0.000001) == "1 us"
565
566
567 # Test %%capture magic. Added to test issue #13926
568 def test_capture():
569 ip = get_ipython()
570
571 # Test %%capture nominal case
572 ip.run_cell("%%capture abc\n1+2")
573 with tt.AssertPrints("True", suppress=False):
574 ip.run_cell("'abc' in locals()")
575 with tt.AssertPrints("True", suppress=False):
576 ip.run_cell("'outputs' in dir(abc)")
577 with tt.AssertPrints("3", suppress=False):
578 ip.run_cell("abc.outputs[0]")
579
580 # Test %%capture with ';' at end of expression
581 ip.run_cell("%%capture abc\n7+8;")
582 with tt.AssertPrints("False", suppress=False):
583 ip.run_cell("'abc' in locals()")
584
585
586 def test_doctest_mode():
587 "Toggle doctest_mode twice, it should be a no-op and run without error"
588 _ip.run_line_magic("doctest_mode", "")
589 _ip.run_line_magic("doctest_mode", "")
590
591
592 def test_parse_options():
593 """Tests for basic options parsing in magics."""
594 # These are only the most minimal of tests, more should be added later. At
595 # the very least we check that basic text/unicode calls work OK.
596 m = DummyMagics(_ip)
597 assert m.parse_options("foo", "")[1] == "foo"
598 assert m.parse_options("foo", "")[1] == "foo"
599
600
601 def test_parse_options_preserve_non_option_string():
602 """Test to assert preservation of non-option part of magic-block, while parsing magic options."""
603 m = DummyMagics(_ip)
604 opts, stmt = m.parse_options(
605 " -n1 -r 13 _ = 314 + foo", "n:r:", preserve_non_opts=True
606 )
607 assert opts == {"n": "1", "r": "13"}
608 assert stmt == "_ = 314 + foo"
609
610
611 def test_run_magic_preserve_code_block():
612 """Test to assert preservation of non-option part of magic-block, while running magic."""
613 _ip.user_ns["spaces"] = []
614 _ip.run_line_magic(
615 "timeit", "-n1 -r1 spaces.append([s.count(' ') for s in ['document']])"
616 )
617 assert _ip.user_ns["spaces"] == [[0]]
618
619
620 def test_dirops():
621 """Test various directory handling operations."""
622 # curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
623 curpath = os.getcwd
624 startdir = os.getcwd()
625 ipdir = os.path.realpath(_ip.ipython_dir)
626 try:
627 _ip.run_line_magic("cd", '"%s"' % ipdir)
628 assert curpath() == ipdir
629 _ip.run_line_magic("cd", "-")
630 assert curpath() == startdir
631 _ip.run_line_magic("pushd", '"%s"' % ipdir)
632 assert curpath() == ipdir
633 _ip.run_line_magic("popd", "")
634 assert curpath() == startdir
635 finally:
636 os.chdir(startdir)
637
638
639 def test_cd_force_quiet():
640 """Test OSMagics.cd_force_quiet option"""
641 _ip.config.OSMagics.cd_force_quiet = True
642 osmagics = osm.OSMagics(shell=_ip)
643
644 startdir = os.getcwd()
645 ipdir = os.path.realpath(_ip.ipython_dir)
646
647 try:
648 with tt.AssertNotPrints(ipdir):
649 osmagics.cd('"%s"' % ipdir)
650 with tt.AssertNotPrints(startdir):
651 osmagics.cd("-")
652 finally:
653 os.chdir(startdir)
654
655
656 def test_xmode():
657 # Calling xmode three times should be a no-op
658 xmode = _ip.InteractiveTB.mode
659 for i in range(5):
660 _ip.run_line_magic("xmode", "")
661 assert _ip.InteractiveTB.mode == xmode
662
663
664 def test_reset_hard():
665 monitor = []
666
667 class A(object):
668 def __del__(self):
669 monitor.append(1)
670
671 def __repr__(self):
672 return "<A instance>"
673
674 _ip.user_ns["a"] = A()
675 _ip.run_cell("a")
676
677 assert monitor == []
678 _ip.run_line_magic("reset", "-f")
679 assert monitor == [1]
680
681
682 class TestXdel(tt.TempFileMixin):
683 def test_xdel(self):
684 """Test that references from %run are cleared by xdel."""
685 src = (
686 "class A(object):\n"
687 " monitor = []\n"
688 " def __del__(self):\n"
689 " self.monitor.append(1)\n"
690 "a = A()\n"
691 )
692 self.mktmp(src)
693 # %run creates some hidden references...
694 _ip.run_line_magic("run", "%s" % self.fname)
695 # ... as does the displayhook.
696 _ip.run_cell("a")
697
698 monitor = _ip.user_ns["A"].monitor
699 assert monitor == []
700
701 _ip.run_line_magic("xdel", "a")
702
703 # Check that a's __del__ method has been called.
704 gc.collect(0)
705 assert monitor == [1]
706
707
708 def doctest_who():
709 """doctest for %who
710
711 In [1]: %reset -sf
712
713 In [2]: alpha = 123
714
715 In [3]: beta = 'beta'
716
717 In [4]: %who int
718 alpha
719
720 In [5]: %who str
721 beta
722
723 In [6]: %whos
724 Variable Type Data/Info
725 ----------------------------
726 alpha int 123
727 beta str beta
728
729 In [7]: %who_ls
730 Out[7]: ['alpha', 'beta']
731 """
732
733
734 def test_whos():
735 """Check that whos is protected against objects where repr() fails."""
736
737 class A(object):
738 def __repr__(self):
739 raise Exception()
740
741 _ip.user_ns["a"] = A()
742 _ip.run_line_magic("whos", "")
743
744
745 @pytest.mark.parametrize(
746 "input,expected",
747 (
748 (
749 "The quick brown fox jumps over the lazy dog",
750 "The quick brown fox jumps over the lazy dog",
751 ),
752 (
753 " ".join(["The quick brown fox jumps over the lazy dog"] * 2),
754 "The quick brown fox jumps<...>x jumps over the lazy dog",
755 ),
756 ("\nThis is \n\na long\n\nstring\n", r"\nThis is \n\na long\n\nstring\n"),
757 (
758 "\rThis is \r\ra long\r\rstring\r",
759 r"\rThis is \r\ra long\r\rstring\r",
760 ),
761 ),
762 )
763 def test_whos_longstr(input, expected):
764 ip = get_ipython()
765 ip.user_ns["input"] = input
766 ip.user_ns["expected"] = expected
767 with capture_output() as captured:
768 ip.run_line_magic("whos", "")
769 stdout = captured.stdout
770 from_whos = " ".join(
771 re.split(
772 r"\s+str\s+",
773 [l for l in stdout.splitlines() if l.startswith("expected")][0],
774 )[1:]
775 )
776 assert expected == from_whos
777
778
779 def test_whos_len_namedtuple():
780 _ip = get_ipython()
781 _ip.run_line_magic("reset", "-f")
782 _ip.user_ns["alpha"] = 123
783 _ip.user_ns["beta"] = "test"
784 _ip.user_ns["nt"] = collections.namedtuple("MyNamedTuple", "col1 col2")
785 _ip.user_ns["x"] = _ip.user_ns["nt"]("a", "b")
786 expected = (
787 "Variable Type Data/Info\n"
788 "------------------------------------\n"
789 "alpha int 123\n"
790 "beta str test\n"
791 "nt type <class 'tests.test_magic.MyNamedTuple'>\n"
792 "x MyNamedTuple MyNamedTuple(col1='a', col2='b')\n"
793 )
794 with capture_output() as captured:
795 ip.run_line_magic("whos", "")
796 stdout = captured.stdout
797 assert stdout == expected.strip() + "\n"
798
799
800 @dec.skip_without("pandas")
801 def test_whos_len_pandas():
802 import pandas as pd
803
804 _ip = get_ipython()
805 _ip.run_line_magic("reset", "-f")
806 df = pd.DataFrame({"a": range(10), "b": range(10, 20)})
807 _ip.user_ns["df"] = df
808 s = df["a"]
809 _ip.user_ns["s"] = s
810 expected = (
811 "Variable Type Data/Info\n"
812 "---------------------------------\n"
813 "df DataFrame Shape: (10, 2)\n"
814 "s Series Shape: (10,)\n"
815 )
816 with capture_output() as captured:
817 ip.run_line_magic("whos", "")
818 stdout = captured.stdout
819 assert stdout == expected.strip() + "\n"
820
821
822 def doctest_precision():
823 """doctest for %precision
824
825 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
826
827 In [2]: %precision 5
828 Out[2]: '%.5f'
829
830 In [3]: f.float_format
831 Out[3]: '%.5f'
832
833 In [4]: %precision %e
834 Out[4]: '%e'
835
836 In [5]: f(3.1415927)
837 Out[5]: '3.141593e+00'
838 """
839
840
841 def test_debug_magic():
842 """Test debugging a small code with %debug
843
844 In [1]: with PdbTestInput(['c']):
845 ...: %debug print("a b") #doctest: +ELLIPSIS
846 ...:
847 ...
848 ipdb> c
849 a b
850 In [2]:
851 """
852
853
854 def test_debug_magic_locals():
855 """Test debugging a small code with %debug with locals
856
857 In [1]: with PdbTestInput(['c']):
858 ...: def fun():
859 ...: res = 1
860 ...: %debug print(res)
861 ...: fun()
862 ...:
863 ...
864 ipdb> c
865 1
866 In [2]:
867 """
868
869
870 def test_psearch():
871 with tt.AssertPrints("dict.fromkeys"):
872 _ip.run_cell("dict.fr*?")
873 with tt.AssertPrints("π.is_integer"):
874 _ip.run_cell("π = 3.14;\nπ.is_integ*?")
875
876
877 def test_timeit_shlex():
878 """test shlex issues with timeit (#1109)"""
879 _ip.ex("def f(*a,**kw): pass")
880 _ip.run_line_magic("timeit", '-n1 "this is a bug".count(" ")')
881 _ip.run_line_magic("timeit", '-r1 -n1 f(" ", 1)')
882 _ip.run_line_magic("timeit", '-r1 -n1 f(" ", 1, " ", 2, " ")')
883 _ip.run_line_magic("timeit", '-r1 -n1 ("a " + "b")')
884 _ip.run_line_magic("timeit", '-r1 -n1 f("a " + "b")')
885 _ip.run_line_magic("timeit", '-r1 -n1 f("a " + "b ")')
886
887
888 def test_timeit_special_syntax():
889 "Test %%timeit with IPython special syntax"
890
891 @register_line_magic
892 def lmagic(line):
893 ip = get_ipython()
894 ip.user_ns["lmagic_out"] = line
895
896 # line mode test
897 _ip.run_line_magic("timeit", "-n1 -r1 %lmagic my line")
898 assert _ip.user_ns["lmagic_out"] == "my line"
899 # cell mode test
900 _ip.run_cell_magic("timeit", "-n1 -r1", "%lmagic my line2")
901 assert _ip.user_ns["lmagic_out"] == "my line2"
902
903
904 def test_timeit_return():
905 """
906 test whether timeit -o return object
907 """
908
909 res = _ip.run_line_magic("timeit", "-n10 -r10 -o 1")
910 assert res is not None
911
912
913 def test_timeit_save():
914 """
915 test whether timeit -v save object
916 """
917
918 name = "some_variable_name"
919 _ip.run_line_magic("timeit", "-n10 -r10 -v %s 1" % name)
920 assert _ip.user_ns[name] is not None
921
922
923 def test_timeit_quiet():
924 """
925 test quiet option of timeit magic
926 """
927 with tt.AssertNotPrints("loops"):
928 _ip.run_cell("%timeit -n1 -r1 -q 1")
929
930
931 def test_timeit_return_quiet():
932 with tt.AssertNotPrints("loops"):
933 res = _ip.run_line_magic("timeit", "-n1 -r1 -q -o 1")
934 assert res is not None
935
936
937 def test_timeit_invalid_return():
938 with pytest.raises(SyntaxError):
939 _ip.run_line_magic("timeit", "return")
940
941
942 def test_timeit_raise_on_interrupt():
943 ip = get_ipython()
944
945 with pytest.raises(KeyboardInterrupt):
946 thread = Thread(target=_interrupt_after_1s)
947 thread.start()
948 ip.run_cell_magic("timeit", "", "from time import sleep; sleep(2)")
949 thread.join()
950
951
952 @dec.skipif(execution.profile is None)
953 def test_prun_special_syntax():
954 "Test %%prun with IPython special syntax"
955
956 @register_line_magic
957 def lmagic(line):
958 ip = get_ipython()
959 ip.user_ns["lmagic_out"] = line
960
961 # line mode test
962 _ip.run_line_magic("prun", "-q %lmagic my line")
963 assert _ip.user_ns["lmagic_out"] == "my line"
964 # cell mode test
965 _ip.run_cell_magic("prun", "-q", "%lmagic my line2")
966 assert _ip.user_ns["lmagic_out"] == "my line2"
967
968
969 @dec.skipif(execution.profile is None)
970 def test_prun_quotes():
971 "Test that prun does not clobber string escapes (GH #1302)"
972 _ip.run_line_magic("prun", r"-q x = '\t'")
973 assert _ip.user_ns["x"] == "\t"
974
975
976 def test_extension():
977 # Debugging information for failures of this test
978 assert "daft_extension" not in sys.modules
979 daft_path = os.path.join(os.path.dirname(__file__), "fake_ext_dir")
980 if daft_path in sys.path:
981 # it is likely pytest added this path
982 # when scanning for tests
983 sys.path.remove(daft_path)
984 print("sys.path:")
985 for p in sys.path:
986 print(" ", p)
987 print("CWD", os.getcwd())
988
989 with pytest.raises(ModuleNotFoundError):
990 import daft_extension
991
992 with pytest.raises(ModuleNotFoundError):
993 _ip.run_line_magic("load_ext", "daft_extension")
994 sys.path.insert(0, daft_path)
995 import daft_extension
996
997 try:
998 _ip.user_ns.pop("arq", None)
999 invalidate_caches() # Clear import caches
1000 _ip.run_line_magic("load_ext", "daft_extension")
1001 assert _ip.user_ns["arq"] == 185
1002 _ip.run_line_magic("unload_ext", "daft_extension")
1003 assert "arq" not in _ip.user_ns
1004 finally:
1005 sys.path.remove(daft_path)
1006
1007
1008 def test_notebook_export_json():
1009 pytest.importorskip("nbformat")
1010 from nbformat import read, sign
1011
1012 _ip = get_ipython()
1013 _ip.history_manager.reset() # Clear any existing history.
1014 _ip.run_line_magic("config", "NotebookNotary.algorithm = 'sha384'")
1015 cmds = ["a=1", "def b():\n return a**2", "print('noël, été', b())"]
1016 for i, cmd in enumerate(cmds, start=1):
1017 _ip.history_manager.store_inputs(i, cmd)
1018 with TemporaryDirectory() as td:
1019 outfile = os.path.join(td, "nb.ipynb")
1020 _ip.run_line_magic("notebook", "%s" % outfile)
1021 with open(outfile) as f:
1022 exported = json.load(f)
1023 nb = read(outfile, as_version=4)
1024
1025 # check metadata
1026 language_info = exported["metadata"]["language_info"]
1027 assert language_info["name"] == "python"
1028 assert language_info["file_extension"] == ".py"
1029 assert language_info["version"] == platform.python_version()
1030
1031 kernelspec = exported["metadata"]["kernelspec"]
1032 assert kernelspec["language"] == "python"
1033
1034 # Check if notebook is trusted
1035 notary = sign.NotebookNotary(algorithm="sha384")
1036 is_trusted = notary.check_signature(nb)
1037 assert is_trusted, "Exported notebook should be trusted"
1038
1039
1040 def test_notebook_export_json_with_output():
1041 """Tests if notebook export correctly captures outputs, errors, display outputs, and stream outputs."""
1042 pytest.importorskip("nbformat")
1043 pytest.importorskip("nbclient")
1044 import nbformat
1045 from nbclient import NotebookClient
1046
1047 _ip = get_ipython()
1048 _ip.history_manager.reset()
1049 _ip.colors = "neutral"
1050 _ip.execution_count = 1
1051
1052 try:
1053 commands = [
1054 "1/0",
1055 "print('test')",
1056 "display('test')",
1057 "1+1",
1058 "display('a'), display('b')",
1059 "import sys\nprint('test', file=sys.stderr)",
1060 ]
1061
1062 clean_nb = nbformat.v4.new_notebook(
1063 cells=[nbformat.v4.new_code_cell(source=cmd) for cmd in commands]
1064 )
1065
1066 with TemporaryDirectory() as td:
1067 outfile = os.path.join(td, "nb.ipynb")
1068 client = NotebookClient(
1069 clean_nb,
1070 timeout=600,
1071 kernel_name="python3",
1072 resources={"metadata": {"path": td}},
1073 allow_errors=True,
1074 )
1075 client.execute()
1076 nbformat.write(clean_nb, outfile)
1077 expected_nb = nbformat.read(outfile, as_version=4)
1078
1079 for cmd in commands:
1080 _ip.run_cell(cmd, store_history=True, silent=False)
1081 print(f"\n{_ip.history_manager.outputs}\n")
1082
1083 with TemporaryDirectory() as td:
1084 outfile = os.path.join(td, "nb.ipynb")
1085 _ip.run_cell(f"%notebook {outfile}", store_history=True)
1086 sleep(2)
1087 actual_nb = nbformat.read(outfile, as_version=4)
1088
1089 assert len(actual_nb["cells"]) == len(commands)
1090 assert len(expected_nb["cells"]) == len(commands)
1091
1092 for i, command in enumerate(commands):
1093 actual = actual_nb["cells"][i]
1094 expected = expected_nb["cells"][i]
1095 assert expected["source"] == command
1096 assert actual["source"] == expected["source"]
1097 assert (
1098 actual["outputs"] == expected["outputs"]
1099 ), f"Outputs do not match for cell {i+1} with source {command!r}"
1100 finally:
1101 _ip.colors = "nocolor"
1102
1103
1104 def test_notebook_export_single_display():
1105 """Test that multiple MIME types create a single display_data output, not multiple."""
1106 pytest.importorskip("nbformat")
1107
1108 _ip = get_ipython()
1109 orig_outputs = _ip.history_manager.outputs.copy()
1110 orig_execution_count = _ip.execution_count
1111 _ip.history_manager.reset()
1112
1113 try:
1114 execution_count = _ip.execution_count = 1
1115 _ip.run_cell("'test'", store_history=True, silent=False)
1116
1117 # Mock display output with multiple MIME types
1118 test_display_history = HistoryOutput(
1119 output_type="display_data",
1120 bundle={"text/plain": "test", "text/html": "<div>test</div>"},
1121 )
1122 _ip.history_manager.outputs[execution_count] = [test_display_history]
1123
1124 with TemporaryDirectory() as td:
1125 outfile = f"{td}/test.ipynb"
1126 _ip.run_cell(f"%notebook {outfile}", store_history=True, silent=False)
1127
1128 # Verify single display_data output with both MIME types
1129 with open(outfile, "r") as f:
1130 nb = json.load(f)
1131
1132 cell = nb["cells"][0]
1133 display_outputs = [
1134 out for out in cell["outputs"] if out["output_type"] == "display_data"
1135 ]
1136
1137 assert (
1138 len(display_outputs) == 1
1139 ), f"Expected 1 display_data output, got {len(display_outputs)}"
1140
1141 output_data = display_outputs[0]["data"]
1142 assert set(output_data.keys()) == {"text/plain", "text/html"}
1143 assert output_data["text/plain"] == ["test"]
1144 assert output_data["text/html"] == ["<div>test</div>"]
1145
1146 finally:
1147 _ip.history_manager.outputs = orig_outputs
1148 _ip.execution_count = orig_execution_count
1149
1150
1151 class TestEnv(TestCase):
1152 def test_env(self):
1153 env = _ip.run_line_magic("env", "")
1154 self.assertTrue(isinstance(env, dict))
1155
1156 def test_env_secret(self):
1157 env = _ip.run_line_magic("env", "")
1158 hidden = "<hidden>"
1159 with mock.patch.dict(
1160 os.environ,
1161 {
1162 "API_KEY": "abc123",
1163 "SECRET_THING": "ssshhh",
1164 "JUPYTER_TOKEN": "",
1165 "VAR": "abc",
1166 },
1167 ):
1168 env = _ip.run_line_magic("env", "")
1169 assert env["API_KEY"] == hidden
1170 assert env["SECRET_THING"] == hidden
1171 assert env["JUPYTER_TOKEN"] == hidden
1172 assert env["VAR"] == "abc"
1173
1174 def test_env_get_set_simple(self):
1175 env = _ip.run_line_magic("env", "var val1")
1176 self.assertEqual(env, None)
1177 self.assertEqual(os.environ["var"], "val1")
1178 self.assertEqual(_ip.run_line_magic("env", "var"), "val1")
1179 env = _ip.run_line_magic("env", "var=val2")
1180 self.assertEqual(env, None)
1181 self.assertEqual(os.environ["var"], "val2")
1182
1183 def test_env_get_set_complex(self):
1184 env = _ip.run_line_magic("env", "var 'val1 '' 'val2")
1185 self.assertEqual(env, None)
1186 self.assertEqual(os.environ["var"], "'val1 '' 'val2")
1187 self.assertEqual(_ip.run_line_magic("env", "var"), "'val1 '' 'val2")
1188 env = _ip.run_line_magic("env", 'var=val2 val3="val4')
1189 self.assertEqual(env, None)
1190 self.assertEqual(os.environ["var"], 'val2 val3="val4')
1191
1192 def test_env_set_bad_input(self):
1193 self.assertRaises(UsageError, lambda: _ip.run_line_magic("set_env", "var"))
1194
1195 def test_env_set_whitespace(self):
1196 self.assertRaises(UsageError, lambda: _ip.run_line_magic("env", "var A=B"))
1197
1198
1199 def check_ident(magic):
1200 # Manually called, we get the result
1201 out = _ip.run_cell_magic(magic, "a", "b")
1202 assert out == ("a", "b")
1203 # Via run_cell, it goes into the user's namespace via displayhook
1204 _ip.run_cell("%%" + magic + " c\nd\n")
1205 assert _ip.user_ns["_"] == ("c", "d\n")
1206
1207
1208 def test_cell_magic_func_deco(underscore_not_in_builtins):
1209 "Cell magic using simple decorator"
1210
1211 @register_cell_magic
1212 def cellm(line, cell):
1213 return line, cell
1214
1215 check_ident("cellm")
1216
1217
1218 def test_cell_magic_reg(underscore_not_in_builtins):
1219 "Cell magic manually registered"
1220
1221 def cellm(line, cell):
1222 return line, cell
1223
1224 _ip.register_magic_function(cellm, "cell", "cellm2")
1225 check_ident("cellm2")
1226
1227
1228 def test_cell_magic_class(underscore_not_in_builtins):
1229 "Cell magics declared via a class"
1230
1231 @magics_class
1232 class MyMagics(Magics):
1233 @cell_magic
1234 def cellm3(self, line, cell):
1235 return line, cell
1236
1237 _ip.register_magics(MyMagics)
1238 check_ident("cellm3")
1239
1240
1241 def test_cell_magic_class2(underscore_not_in_builtins):
1242 "Cell magics declared via a class, #2"
1243
1244 @magics_class
1245 class MyMagics2(Magics):
1246 @cell_magic("cellm4")
1247 def cellm33(self, line, cell):
1248 return line, cell
1249
1250 _ip.register_magics(MyMagics2)
1251 check_ident("cellm4")
1252 # Check that nothing is registered as 'cellm33'
1253 c33 = _ip.find_cell_magic("cellm33")
1254 assert c33 == None
1255
1256
1257 def test_file():
1258 """Basic %%writefile"""
1259 ip = get_ipython()
1260 with TemporaryDirectory() as td:
1261 fname = os.path.join(td, "file1")
1262 ip.run_cell_magic(
1263 "writefile",
1264 fname,
1265 "\n".join(
1266 [
1267 "line1",
1268 "line2",
1269 ]
1270 ),
1271 )
1272 s = Path(fname).read_text(encoding="utf-8")
1273 assert "line1\n" in s
1274 assert "line2" in s
1275
1276
1277 @dec.skip_win32
1278 def test_file_single_quote():
1279 """Basic %%writefile with embedded single quotes"""
1280 ip = get_ipython()
1281 with TemporaryDirectory() as td:
1282 fname = os.path.join(td, "'file1'")
1283 ip.run_cell_magic(
1284 "writefile",
1285 fname,
1286 "\n".join(
1287 [
1288 "line1",
1289 "line2",
1290 ]
1291 ),
1292 )
1293 s = Path(fname).read_text(encoding="utf-8")
1294 assert "line1\n" in s
1295 assert "line2" in s
1296
1297
1298 @dec.skip_win32
1299 def test_file_double_quote():
1300 """Basic %%writefile with embedded double quotes"""
1301 ip = get_ipython()
1302 with TemporaryDirectory() as td:
1303 fname = os.path.join(td, '"file1"')
1304 ip.run_cell_magic(
1305 "writefile",
1306 fname,
1307 "\n".join(
1308 [
1309 "line1",
1310 "line2",
1311 ]
1312 ),
1313 )
1314 s = Path(fname).read_text(encoding="utf-8")
1315 assert "line1\n" in s
1316 assert "line2" in s
1317
1318
1319 def test_file_var_expand():
1320 """%%writefile $filename"""
1321 ip = get_ipython()
1322 with TemporaryDirectory() as td:
1323 fname = os.path.join(td, "file1")
1324 ip.user_ns["filename"] = fname
1325 ip.run_cell_magic(
1326 "writefile",
1327 "$filename",
1328 "\n".join(
1329 [
1330 "line1",
1331 "line2",
1332 ]
1333 ),
1334 )
1335 s = Path(fname).read_text(encoding="utf-8")
1336 assert "line1\n" in s
1337 assert "line2" in s
1338
1339
1340 def test_file_unicode():
1341 """%%writefile with unicode cell"""
1342 ip = get_ipython()
1343 with TemporaryDirectory() as td:
1344 fname = os.path.join(td, "file1")
1345 ip.run_cell_magic(
1346 "writefile",
1347 fname,
1348 "\n".join(
1349 [
1350 "liné1",
1351 "liné2",
1352 ]
1353 ),
1354 )
1355 with io.open(fname, encoding="utf-8") as f:
1356 s = f.read()
1357 assert "liné1\n" in s
1358 assert "liné2" in s
1359
1360
1361 def test_file_amend():
1362 """%%writefile -a amends files"""
1363 ip = get_ipython()
1364 with TemporaryDirectory() as td:
1365 fname = os.path.join(td, "file2")
1366 ip.run_cell_magic(
1367 "writefile",
1368 fname,
1369 "\n".join(
1370 [
1371 "line1",
1372 "line2",
1373 ]
1374 ),
1375 )
1376 ip.run_cell_magic(
1377 "writefile",
1378 "-a %s" % fname,
1379 "\n".join(
1380 [
1381 "line3",
1382 "line4",
1383 ]
1384 ),
1385 )
1386 s = Path(fname).read_text(encoding="utf-8")
1387 assert "line1\n" in s
1388 assert "line3\n" in s
1389
1390
1391 def test_file_spaces():
1392 """%%file with spaces in filename"""
1393 ip = get_ipython()
1394 with TemporaryWorkingDirectory() as td:
1395 fname = "file name"
1396 ip.run_cell_magic(
1397 "file",
1398 '"%s"' % fname,
1399 "\n".join(
1400 [
1401 "line1",
1402 "line2",
1403 ]
1404 ),
1405 )
1406 s = Path(fname).read_text(encoding="utf-8")
1407 assert "line1\n" in s
1408 assert "line2" in s
1409
1410
1411 def test_script_config():
1412 ip = get_ipython()
1413 ip.config.ScriptMagics.script_magics = ["whoda"]
1414 sm = script.ScriptMagics(shell=ip)
1415 assert "whoda" in sm.magics["cell"]
1416
1417
1418 def _interrupt_after_1s():
1419 sleep(1)
1420 signal.raise_signal(signal.SIGINT)
1421
1422
1423 def test_script_raise_on_interrupt():
1424 ip = get_ipython()
1425
1426 with pytest.raises(CalledProcessError):
1427 thread = Thread(target=_interrupt_after_1s)
1428 thread.start()
1429 ip.run_cell_magic(
1430 "script", f"{sys.executable}", "from time import sleep; sleep(2)"
1431 )
1432 thread.join()
1433
1434
1435 def test_script_do_not_raise_on_interrupt():
1436 ip = get_ipython()
1437
1438 thread = Thread(target=_interrupt_after_1s)
1439 thread.start()
1440 ip.run_cell_magic(
1441 "script",
1442 f"--no-raise-error {sys.executable}",
1443 "from time import sleep; sleep(2)",
1444 )
1445 thread.join()
1446
1447
1448 def test_script_out():
1449 ip = get_ipython()
1450 ip.run_cell_magic("script", f"--out output {sys.executable}", "print('hi')")
1451 assert ip.user_ns["output"].strip() == "hi"
1452
1453
1454 def test_script_out_multiple_lines():
1455 ip = get_ipython()
1456 code = "print('hi')\nprint('this')\nprint('is')\nprint('ipython')"
1457 ip.run_cell_magic("script", f"--out output {sys.executable}", code)
1458 assert ip.user_ns["output"].strip().splitlines() == ["hi", "this", "is", "ipython"]
1459
1460
1461 def test_script_err():
1462 ip = get_ipython()
1463 ip.run_cell_magic(
1464 "script",
1465 f"--err error {sys.executable}",
1466 "import sys; print('hello', file=sys.stderr)",
1467 )
1468 assert ip.user_ns["error"].strip() == "hello"
1469
1470
1471 def test_script_out_err():
1472 ip = get_ipython()
1473 ip.run_cell_magic(
1474 "script",
1475 f"--out output --err error {sys.executable}",
1476 "\n".join(
1477 [
1478 "import sys",
1479 "print('hi')",
1480 "print('hello', file=sys.stderr)",
1481 ]
1482 ),
1483 )
1484 assert ip.user_ns["output"].strip() == "hi"
1485 assert ip.user_ns["error"].strip() == "hello"
1486
1487
1488 @pytest.mark.asyncio
1489 async def test_script_bg_out():
1490 ip = get_ipython()
1491 ip.run_cell_magic("script", f"--bg --out output {sys.executable}", "print('hi')")
1492 assert (await ip.user_ns["output"].read()).strip() == b"hi"
1493 assert ip.user_ns["output"].at_eof()
1494
1495
1496 @pytest.mark.asyncio
1497 async def test_script_bg_err():
1498 ip = get_ipython()
1499 ip.run_cell_magic(
1500 "script",
1501 f"--bg --err error {sys.executable}",
1502 "import sys; print('hello', file=sys.stderr)",
1503 )
1504 assert (await ip.user_ns["error"].read()).strip() == b"hello"
1505 assert ip.user_ns["error"].at_eof()
1506
1507
1508 @pytest.mark.asyncio
1509 async def test_script_bg_out_err():
1510 ip = get_ipython()
1511 ip.run_cell_magic(
1512 "script",
1513 f"--bg --out output --err error {sys.executable}",
1514 "\n".join(
1515 [
1516 "import sys",
1517 "print('hi')",
1518 "print('hello', file=sys.stderr)",
1519 ]
1520 ),
1521 )
1522 assert (await ip.user_ns["output"].read()).strip() == b"hi"
1523 assert (await ip.user_ns["error"].read()).strip() == b"hello"
1524 assert ip.user_ns["output"].at_eof()
1525 assert ip.user_ns["error"].at_eof()
1526
1527
1528 @pytest.mark.asyncio
1529 async def test_script_bg_proc():
1530 ip = get_ipython()
1531 ip.run_cell_magic(
1532 "script",
1533 f"--bg --out output --proc p {sys.executable}",
1534 "\n".join(
1535 [
1536 "import sys",
1537 "print('hi')",
1538 "print('hello', file=sys.stderr)",
1539 ]
1540 ),
1541 )
1542 p = ip.user_ns["p"]
1543 await p.wait()
1544 stdout = await p.stdout.read()
1545 stderr = await p.stderr.read()
1546 assert p.returncode == 0, (stdout, stderr)
1547 assert stdout.strip() == b"hi"
1548 # not captured, so empty
1549 assert (stderr) == b""
1550 assert p.stdout.at_eof()
1551 assert p.stderr.at_eof()
1552
1553
1554 def test_script_defaults():
1555 ip = get_ipython()
1556 for cmd in ["sh", "bash", "perl", "ruby"]:
1557 try:
1558 find_cmd(cmd)
1559 except Exception:
1560 pass
1561 else:
1562 assert cmd in ip.magics_manager.magics["cell"]
1563
1564
1565 @pytest.mark.asyncio
1566 async def test_script_streams_continuously(capsys):
1567 ip = get_ipython()
1568 # Windows is slow to start up a thread on CI
1569 is_windows = os.name == "nt"
1570 step = 3 if is_windows else 1
1571 code = dedent(
1572 f"""\
1573 import time
1574 for _ in range(3):
1575 time.sleep({step})
1576 print(".", flush=True, end="")
1577 """
1578 )
1579
1580 def print_numbers():
1581 for i in range(3):
1582 sleep(step)
1583 print(i, flush=True, end="")
1584
1585 thread = Thread(target=print_numbers)
1586 thread.start()
1587 sleep(step / 2)
1588 ip.run_cell_magic("script", sys.executable, code)
1589 thread.join()
1590
1591 captured = capsys.readouterr()
1592 # If the streaming was line-wise or broken
1593 # we would get `012...`
1594 assert captured.out == "0.1.2."
1595
1596
1597 def test_script_streams_multibyte_unicode(capsys):
1598 ip = get_ipython()
1599 # € in UTF-8 is encoded using 3 bytes
1600 code = "print('€' * 1000, end='')"
1601 is_windows = os.name == "nt"
1602 command = sys.executable
1603 if is_windows:
1604 # windows does not use UTF for streams/pipes by default
1605 command += " -X utf8"
1606 ip.run_cell_magic("script", command, code)
1607
1608 captured = capsys.readouterr()
1609 assert captured.out == "€" * 1000
1610
1611
1612 @magics_class
1613 class FooFoo(Magics):
1614 """class with both %foo and %%foo magics"""
1615
1616 @line_magic("foo")
1617 def line_foo(self, line):
1618 "I am line foo"
1619 pass
1620
1621 @cell_magic("foo")
1622 def cell_foo(self, line, cell):
1623 "I am cell foo, not line foo"
1624 pass
1625
1626
1627 def test_line_cell_info():
1628 """%%foo and %foo magics are distinguishable to inspect"""
1629 ip = get_ipython()
1630 ip.magics_manager.register(FooFoo)
1631 oinfo = ip.object_inspect("foo")
1632 assert oinfo["found"] is True
1633 assert oinfo["ismagic"] is True
1634
1635 oinfo = ip.object_inspect("%%foo")
1636 assert oinfo["found"] is True
1637 assert oinfo["ismagic"] is True
1638 assert oinfo["docstring"] == FooFoo.cell_foo.__doc__
1639
1640 oinfo = ip.object_inspect("%foo")
1641 assert oinfo["found"] is True
1642 assert oinfo["ismagic"] is True
1643 assert oinfo["docstring"] == FooFoo.line_foo.__doc__
1644
1645
1646 def test_multiple_magics():
1647 ip = get_ipython()
1648 foo1 = FooFoo(ip)
1649 foo2 = FooFoo(ip)
1650 mm = ip.magics_manager
1651 mm.register(foo1)
1652 assert mm.magics["line"]["foo"].__self__ is foo1
1653 mm.register(foo2)
1654 assert mm.magics["line"]["foo"].__self__ is foo2
1655
1656
1657 def test_alias_magic():
1658 """Test %alias_magic."""
1659 ip = get_ipython()
1660 mm = ip.magics_manager
1661
1662 # Basic operation: both cell and line magics are created, if possible.
1663 ip.run_line_magic("alias_magic", "timeit_alias timeit")
1664 assert "timeit_alias" in mm.magics["line"]
1665 assert "timeit_alias" in mm.magics["cell"]
1666
1667 # --cell is specified, line magic not created.
1668 ip.run_line_magic("alias_magic", "--cell timeit_cell_alias timeit")
1669 assert "timeit_cell_alias" not in mm.magics["line"]
1670 assert "timeit_cell_alias" in mm.magics["cell"]
1671
1672 # Test that line alias is created successfully.
1673 ip.run_line_magic("alias_magic", "--line env_alias env")
1674 assert ip.run_line_magic("env", "") == ip.run_line_magic("env_alias", "")
1675
1676 # Test that line alias with parameters passed in is created successfully.
1677 ip.run_line_magic(
1678 "alias_magic", "--line history_alias history --params " + shlex.quote("3")
1679 )
1680 assert "history_alias" in mm.magics["line"]
1681
1682
1683 def test_save():
1684 """Test %save."""
1685 ip = get_ipython()
1686 ip.history_manager.reset() # Clear any existing history.
1687 cmds = ["a=1", "def b():\n return a**2", "print(a, b())"]
1688 for i, cmd in enumerate(cmds, start=1):
1689 ip.history_manager.store_inputs(i, cmd)
1690 with TemporaryDirectory() as tmpdir:
1691 file = os.path.join(tmpdir, "testsave.py")
1692 ip.run_line_magic("save", "%s 1-10" % file)
1693 content = Path(file).read_text(encoding="utf-8")
1694 assert content.count(cmds[0]) == 1
1695 assert "coding: utf-8" in content
1696 ip.run_line_magic("save", "-a %s 1-10" % file)
1697 content = Path(file).read_text(encoding="utf-8")
1698 assert content.count(cmds[0]) == 2
1699 assert "coding: utf-8" in content
1700
1701
1702 def test_save_with_no_args():
1703 ip = get_ipython()
1704 ip.history_manager.reset() # Clear any existing history.
1705 cmds = ["a=1", "def b():\n return a**2", "print(a, b())", "%save"]
1706 for i, cmd in enumerate(cmds, start=1):
1707 ip.history_manager.store_inputs(i, cmd)
1708
1709 with TemporaryDirectory() as tmpdir:
1710 path = os.path.join(tmpdir, "testsave.py")
1711 ip.run_line_magic("save", path)
1712 content = Path(path).read_text(encoding="utf-8")
1713 expected_content = dedent(
1714 """\
1715 # coding: utf-8
1716 a=1
1717 def b():
1718 return a**2
1719 print(a, b())
1720 """
1721 )
1722 assert content == expected_content
1723
1724
1725 def test_store():
1726 """Test %store."""
1727 ip = get_ipython()
1728 ip.run_line_magic("load_ext", "storemagic")
1729
1730 # make sure the storage is empty
1731 ip.run_line_magic("store", "-z")
1732 ip.user_ns["var"] = 42
1733 ip.run_line_magic("store", "var")
1734 ip.user_ns["var"] = 39
1735 ip.run_line_magic("store", "-r")
1736 assert ip.user_ns["var"] == 42
1737
1738 ip.run_line_magic("store", "-d var")
1739 ip.user_ns["var"] = 39
1740 ip.run_line_magic("store", "-r")
1741 assert ip.user_ns["var"] == 39
1742
1743
1744 def _run_edit_test(
1745 arg_s, exp_filename=None, exp_lineno=-1, exp_contents=None, exp_is_temp=None
1746 ):
1747 ip = get_ipython()
1748 M = code.CodeMagics(ip)
1749 last_call = ["", ""]
1750 opts, args = M.parse_options(arg_s, "prxn:")
1751 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
1752
1753 if exp_filename is not None:
1754 assert exp_filename == filename
1755 if exp_contents is not None:
1756 with io.open(filename, "r", encoding="utf-8") as f:
1757 contents = f.read()
1758 assert exp_contents == contents
1759 if exp_lineno != -1:
1760 assert exp_lineno == lineno
1761 if exp_is_temp is not None:
1762 assert exp_is_temp == is_temp
1763
1764
1765 def test_edit_interactive():
1766 """%edit on interactively defined objects"""
1767 ip = get_ipython()
1768 n = ip.execution_count
1769 ip.run_cell("def foo(): return 1", store_history=True)
1770
1771 with pytest.raises(code.InteractivelyDefined) as e:
1772 _run_edit_test("foo")
1773 assert e.value.index == n
1774
1775
1776 def test_edit_cell():
1777 """%edit [cell id]"""
1778 ip = get_ipython()
1779
1780 ip.run_cell("def foo(): return 1", store_history=True)
1781
1782 # test
1783 _run_edit_test("1", exp_contents=ip.user_ns["In"][1], exp_is_temp=True)
1784
1785
1786 def test_edit_fname():
1787 """%edit file"""
1788 # test
1789 _run_edit_test("test file.py", exp_filename="test file.py")
1790
1791
1792 def test_bookmark():
1793 ip = get_ipython()
1794 ip.run_line_magic("bookmark", "bmname")
1795 with tt.AssertPrints("bmname"):
1796 ip.run_line_magic("bookmark", "-l")
1797 ip.run_line_magic("bookmark", "-d bmname")
1798
1799
1800 def test_ls_magic():
1801 ip = get_ipython()
1802 json_formatter = ip.display_formatter.formatters["application/json"]
1803 json_formatter.enabled = True
1804 lsmagic = ip.run_line_magic("lsmagic", "")
1805 with warnings.catch_warnings(record=True) as w:
1806 j = json_formatter(lsmagic)
1807 assert sorted(j) == ["cell", "line"]
1808 assert w == [] # no warnings
1809
1810
1811 def test_strip_initial_indent():
1812 def sii(s):
1813 lines = s.splitlines()
1814 return "\n".join(code.strip_initial_indent(lines))
1815
1816 assert sii(" a = 1\nb = 2") == "a = 1\nb = 2"
1817 assert sii(" a\n b\nc") == "a\n b\nc"
1818 assert sii("a\n b") == "a\n b"
1819
1820
1821 def test_logging_magic_quiet_from_arg():
1822 _ip.config.LoggingMagics.quiet = False
1823 lm = logging.LoggingMagics(shell=_ip)
1824 with TemporaryDirectory() as td:
1825 try:
1826 with tt.AssertNotPrints(re.compile("Activating.*")):
1827 lm.logstart("-q {}".format(os.path.join(td, "quiet_from_arg.log")))
1828 finally:
1829 _ip.logger.logstop()
1830
1831
1832 def test_logging_magic_quiet_from_config():
1833 _ip.config.LoggingMagics.quiet = True
1834 lm = logging.LoggingMagics(shell=_ip)
1835 with TemporaryDirectory() as td:
1836 try:
1837 with tt.AssertNotPrints(re.compile("Activating.*")):
1838 lm.logstart(os.path.join(td, "quiet_from_config.log"))
1839 finally:
1840 _ip.logger.logstop()
1841
1842
1843 def test_logging_magic_not_quiet():
1844 _ip.config.LoggingMagics.quiet = False
1845 lm = logging.LoggingMagics(shell=_ip)
1846 with TemporaryDirectory() as td:
1847 try:
1848 with tt.AssertPrints(re.compile("Activating.*")):
1849 lm.logstart(os.path.join(td, "not_quiet.log"))
1850 finally:
1851 _ip.logger.logstop()
1852
1853
1854 def test_time_no_var_expand():
1855 _ip.user_ns["a"] = 5
1856 _ip.user_ns["b"] = []
1857 _ip.run_line_magic("time", 'b.append("{a}")')
1858 assert _ip.user_ns["b"] == ["{a}"]
1859
1860
1861 # this is slow, put at the end for local testing.
1862 def test_timeit_arguments():
1863 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
1864 _ip.run_line_magic("timeit", "-n1 -r1 a=('#')")
1865
1866
1867 def test_time_raise_on_interrupt():
1868 ip = get_ipython()
1869
1870 with pytest.raises(KeyboardInterrupt):
1871 thread = Thread(target=_interrupt_after_1s)
1872 thread.start()
1873 ip.run_cell_magic("time", "", "from time import sleep; sleep(2)")
1874 thread.join()
1875
1876
1877 MINIMAL_LAZY_MAGIC = """
1878 from IPython.core.magic import (
1879 Magics,
1880 magics_class,
1881 line_magic,
1882 cell_magic,
1883 )
1884
1885
1886 @magics_class
1887 class LazyMagics(Magics):
1888 @line_magic
1889 def lazy_line(self, line):
1890 print("Lazy Line")
1891
1892 @cell_magic
1893 def lazy_cell(self, line, cell):
1894 print("Lazy Cell")
1895
1896
1897 def load_ipython_extension(ipython):
1898 ipython.register_magics(LazyMagics)
1899 """
1900
1901
1902 def test_lazy_magics():
1903 with pytest.raises(UsageError):
1904 ip.run_line_magic("lazy_line", "")
1905
1906 startdir = os.getcwd()
1907
1908 with TemporaryDirectory() as tmpdir:
1909 with prepended_to_syspath(tmpdir):
1910 ptempdir = Path(tmpdir)
1911 tf = ptempdir / "lazy_magic_module.py"
1912 tf.write_text(MINIMAL_LAZY_MAGIC)
1913 ip.magics_manager.register_lazy("lazy_line", Path(tf.name).name[:-3])
1914 with tt.AssertPrints("Lazy Line"):
1915 ip.run_line_magic("lazy_line", "")
1916
1917
1918 TEST_MODULE = """
1919 print('Loaded my_tmp')
1920 if __name__ == "__main__":
1921 print('I just ran a script')
1922 """
1923
1924
1925 def test_run_module_from_import_hook():
1926 "Test that a module can be loaded via an import hook"
1927 with TemporaryDirectory() as tmpdir:
1928 fullpath = os.path.join(tmpdir, "my_tmp.py")
1929 Path(fullpath).write_text(TEST_MODULE, encoding="utf-8")
1930
1931 import importlib.abc
1932 import importlib.util
1933
1934 class MyTempImporter(importlib.abc.MetaPathFinder, importlib.abc.SourceLoader):
1935 def find_spec(self, fullname, path, target=None):
1936 if fullname == "my_tmp":
1937 return importlib.util.spec_from_loader(fullname, self)
1938
1939 def get_filename(self, fullname):
1940 assert fullname == "my_tmp"
1941 return fullpath
1942
1943 def get_data(self, path):
1944 assert Path(path).samefile(fullpath)
1945 return Path(fullpath).read_text(encoding="utf-8")
1946
1947 sys.meta_path.insert(0, MyTempImporter())
1948
1949 with capture_output() as captured:
1950 _ip.run_line_magic("run", "-m my_tmp")
1951 _ip.run_cell("import my_tmp")
1952
1953 output = "Loaded my_tmp\nI just ran a script\nLoaded my_tmp\n"
1954 assert output == captured.stdout
1955
1956 sys.meta_path.pop(0)