Debian Codegraph @

tests/test_interactiveshell.py

raw
1 # -*- coding: utf-8 -*-
2 """Tests for the key interactiveshell module.
3
4 Historically the main classes in interactiveshell have been under-tested. This
5 module should grow as many single-method tests as possible to trap many of the
6 recurring bugs we seem to encounter with high-level interaction.
7 """
8
9 # Copyright (c) IPython Development Team.
10 # Distributed under the terms of the Modified BSD License.
11
12 import asyncio
13 import ast
14 import os
15 import signal
16 import shutil
17 import sys
18 import tempfile
19 import time
20 import unittest
21 import pytest
22 from unittest import mock
23
24 from os.path import join
25
26 from IPython.core.error import InputRejected
27 from IPython.core import interactiveshell
28 from IPython.core.oinspect import OInfo
29 from IPython.testing.decorators import (
30 skipif,
31 skip_win32,
32 onlyif_unicode_paths,
33 onlyif_cmds_exist,
34 skip_if_not_osx,
35 )
36 from IPython.testing import tools as tt
37 from IPython.utils.process import find_cmd
38
39 # -----------------------------------------------------------------------------
40 # Globals
41 # -----------------------------------------------------------------------------
42 # This is used by every single test, no point repeating it ad nauseam
43
44 # -----------------------------------------------------------------------------
45 # Tests
46 # -----------------------------------------------------------------------------
47
48
49 class DerivedInterrupt(KeyboardInterrupt):
50 pass
51
52
53 def test_stream_performance(capsys) -> None:
54 """It should be fast to execute."""
55 src = "for i in range(250_000): print(i)"
56 start = time.perf_counter()
57 ip.run_cell(src)
58 end = time.perf_counter()
59 # We try to read as otherwise on failure, pytest will print the 250k lines to stdout.
60 capsys.readouterr()
61 duration = end - start
62 assert duration < 10
63
64
65 class InteractiveShellTestCase(unittest.TestCase):
66 def test_naked_string_cells(self):
67 """Test that cells with only naked strings are fully executed"""
68 # First, single-line inputs
69 ip.run_cell('"a"\n')
70 self.assertEqual(ip.user_ns["_"], "a")
71 # And also multi-line cells
72 ip.run_cell('"""a\nb"""\n')
73 self.assertEqual(ip.user_ns["_"], "a\nb")
74
75 def test_run_empty_cell(self):
76 """Just make sure we don't get a horrible error with a blank
77 cell of input. Yes, I did overlook that."""
78 old_xc = ip.execution_count
79 res = ip.run_cell("")
80 self.assertEqual(ip.execution_count, old_xc)
81 self.assertEqual(res.execution_count, None)
82
83 def test_run_cell_multiline(self):
84 """Multi-block, multi-line cells must execute correctly."""
85 src = "\n".join(
86 [
87 "x=1",
88 "y=2",
89 "if 1:",
90 " x += 1",
91 " y += 1",
92 ]
93 )
94 res = ip.run_cell(src)
95 self.assertEqual(ip.user_ns["x"], 2)
96 self.assertEqual(ip.user_ns["y"], 3)
97 self.assertEqual(res.success, True)
98 self.assertEqual(res.result, None)
99
100 def test_multiline_string_cells(self):
101 "Code sprinkled with multiline strings should execute (GH-306)"
102 ip.run_cell("tmp=0")
103 self.assertEqual(ip.user_ns["tmp"], 0)
104 res = ip.run_cell('tmp=1;"""a\nb"""\n')
105 self.assertEqual(ip.user_ns["tmp"], 1)
106 self.assertEqual(res.success, True)
107 self.assertEqual(res.result, "a\nb")
108
109 def test_dont_cache_with_semicolon(self):
110 "Ending a line with semicolon should not cache the returned object (GH-307)"
111 oldlen = len(ip.user_ns["Out"])
112 for cell in ["1;", "1;1;"]:
113 res = ip.run_cell(cell, store_history=True)
114 newlen = len(ip.user_ns["Out"])
115 self.assertEqual(oldlen, newlen)
116 self.assertIsNone(res.result)
117 i = 0
118 # also test the default caching behavior
119 for cell in ["1", "1;1"]:
120 ip.run_cell(cell, store_history=True)
121 newlen = len(ip.user_ns["Out"])
122 i += 1
123 self.assertEqual(oldlen + i, newlen)
124
125 def test_syntax_error(self):
126 res = ip.run_cell("raise = 3")
127 self.assertIsInstance(res.error_before_exec, SyntaxError)
128
129 def test_open_standard_input_stream(self):
130 res = ip.run_cell("open(0)")
131 self.assertIsInstance(res.error_in_exec, ValueError)
132
133 def test_open_standard_output_stream(self):
134 res = ip.run_cell("open(1)")
135 self.assertIsInstance(res.error_in_exec, ValueError)
136
137 def test_open_standard_error_stream(self):
138 res = ip.run_cell("open(2)")
139 self.assertIsInstance(res.error_in_exec, ValueError)
140
141 def test_In_variable(self):
142 "Verify that In variable grows with user input (GH-284)"
143 oldlen = len(ip.user_ns["In"])
144 ip.run_cell("1;", store_history=True)
145 newlen = len(ip.user_ns["In"])
146 self.assertEqual(oldlen + 1, newlen)
147 self.assertEqual(ip.user_ns["In"][-1], "1;")
148
149 def test_magic_names_in_string(self):
150 ip.run_cell('a = """\n%exit\n"""')
151 self.assertEqual(ip.user_ns["a"], "\n%exit\n")
152
153 def test_trailing_newline(self):
154 """test that running !(command) does not raise a SyntaxError"""
155 ip.run_cell("!(true)\n", False)
156 ip.run_cell("!(true)\n\n\n", False)
157
158 def test_gh_597(self):
159 """Pretty-printing lists of objects with non-ascii reprs may cause
160 problems."""
161
162 class Spam(object):
163 def __repr__(self):
164 return "\xe9" * 50
165
166 import IPython.core.formatters
167
168 f = IPython.core.formatters.PlainTextFormatter()
169 f([Spam(), Spam()])
170
171 def test_future_flags(self):
172 """Check that future flags are used for parsing code (gh-777)"""
173 ip.run_cell("from __future__ import barry_as_FLUFL")
174 try:
175 ip.run_cell("prfunc_return_val = 1 <> 2")
176 assert "prfunc_return_val" in ip.user_ns
177 finally:
178 # Reset compiler flags so we don't mess up other tests.
179 ip.compile.reset_compiler_flags()
180
181 def test_can_pickle(self):
182 "Can we pickle objects defined interactively (GH-29)"
183 ip = get_ipython()
184 ip.reset()
185 ip.run_cell(
186 (
187 "class Mylist(list):\n"
188 " def __init__(self,x=[]):\n"
189 " list.__init__(self,x)"
190 )
191 )
192 ip.run_cell("w=Mylist([1,2,3])")
193
194 from pickle import dumps
195
196 # We need to swap in our main module - this is only necessary
197 # inside the test framework, because IPython puts the interactive module
198 # in place (but the test framework undoes this).
199 _main = sys.modules["__main__"]
200 sys.modules["__main__"] = ip.user_module
201 try:
202 res = dumps(ip.user_ns["w"])
203 finally:
204 sys.modules["__main__"] = _main
205 self.assertTrue(isinstance(res, bytes))
206
207 def test_global_ns(self):
208 "Code in functions must be able to access variables outside them."
209 ip = get_ipython()
210 ip.run_cell("a = 10")
211 ip.run_cell(("def f(x):\n" " return x + a"))
212 ip.run_cell("b = f(12)")
213 self.assertEqual(ip.user_ns["b"], 22)
214
215 def test_bad_custom_tb(self):
216 """Check that InteractiveShell is protected from bad custom exception handlers"""
217 ip.set_custom_exc((IOError,), lambda etype, value, tb: 1 / 0)
218 self.assertEqual(ip.custom_exceptions, (IOError,))
219 with tt.AssertPrints("Custom TB Handler failed", channel="stderr"):
220 ip.run_cell('raise IOError("foo")')
221 self.assertEqual(ip.custom_exceptions, ())
222
223 def test_bad_custom_tb_return(self):
224 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
225 ip.set_custom_exc((NameError,), lambda etype, value, tb, tb_offset=None: 1)
226 self.assertEqual(ip.custom_exceptions, (NameError,))
227 with tt.AssertPrints("Custom TB Handler failed", channel="stderr"):
228 ip.run_cell("a=abracadabra")
229 self.assertEqual(ip.custom_exceptions, ())
230
231 def test_drop_by_id(self):
232 myvars = {"a": object(), "b": object(), "c": object()}
233 ip.push(myvars, interactive=False)
234 for name in myvars:
235 assert name in ip.user_ns, name
236 assert name in ip.user_ns_hidden, name
237 ip.user_ns["b"] = 12
238 ip.drop_by_id(myvars)
239 for name in ["a", "c"]:
240 assert name not in ip.user_ns, name
241 assert name not in ip.user_ns_hidden, name
242 assert ip.user_ns["b"] == 12
243 ip.reset()
244
245 def test_var_expand(self):
246 ip.user_ns["f"] = "Ca\xf1o"
247 self.assertEqual(ip.var_expand("echo $f"), "echo Ca\xf1o")
248 self.assertEqual(ip.var_expand("echo {f}"), "echo Ca\xf1o")
249 self.assertEqual(ip.var_expand("echo {f[:-1]}"), "echo Ca\xf1")
250 self.assertEqual(ip.var_expand("echo {1*2}"), "echo 2")
251
252 self.assertEqual(
253 ip.var_expand("grep x | awk '{print $1}'"), "grep x | awk '{print $1}'"
254 )
255
256 ip.user_ns["f"] = b"Ca\xc3\xb1o"
257 # This should not raise any exception:
258 ip.var_expand("echo $f")
259
260 def test_var_expand_local(self):
261 """Test local variable expansion in !system and %magic calls"""
262 # !system
263 ip.run_cell(
264 "def test():\n"
265 ' lvar = "ttt"\n'
266 " ret = !echo {lvar}\n"
267 " return ret[0]\n"
268 )
269 res = ip.user_ns["test"]()
270 self.assertIn("ttt", res)
271
272 # %magic
273 ip.run_cell(
274 "def makemacro():\n"
275 ' macroname = "macro_var_expand_locals"\n'
276 " %macro {macroname} codestr\n"
277 )
278 ip.user_ns["codestr"] = "str(12)"
279 ip.run_cell("makemacro()")
280 self.assertIn("macro_var_expand_locals", ip.user_ns)
281
282 def test_var_expand_self(self):
283 """Test variable expansion with the name 'self', which was failing.
284
285 See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218
286 """
287 ip.run_cell(
288 "class cTest:\n"
289 ' classvar="see me"\n'
290 " def test(self):\n"
291 " res = !echo Variable: {self.classvar}\n"
292 " return res[0]\n"
293 )
294 self.assertIn("see me", ip.user_ns["cTest"]().test())
295
296 def test_bad_var_expand(self):
297 """var_expand on invalid formats shouldn't raise"""
298 # SyntaxError
299 self.assertEqual(ip.var_expand("{'a':5}"), "{'a':5}")
300 # NameError
301 self.assertEqual(ip.var_expand("{asdf}"), "{asdf}")
302 # ZeroDivisionError
303 self.assertEqual(ip.var_expand("{1/0}"), "{1/0}")
304
305 def test_silent_postexec(self):
306 """run_cell(silent=True) doesn't invoke pre/post_run_cell callbacks"""
307 pre_explicit = mock.Mock()
308 pre_always = mock.Mock()
309 post_explicit = mock.Mock()
310 post_always = mock.Mock()
311 all_mocks = [pre_explicit, pre_always, post_explicit, post_always]
312
313 ip.events.register("pre_run_cell", pre_explicit)
314 ip.events.register("pre_execute", pre_always)
315 ip.events.register("post_run_cell", post_explicit)
316 ip.events.register("post_execute", post_always)
317
318 try:
319 ip.run_cell("1", silent=True)
320 assert pre_always.called
321 assert not pre_explicit.called
322 assert post_always.called
323 assert not post_explicit.called
324 # double-check that non-silent exec did what we expected
325 # silent to avoid
326 ip.run_cell("1")
327 assert pre_explicit.called
328 assert post_explicit.called
329 (info,) = pre_explicit.call_args[0]
330 (result,) = post_explicit.call_args[0]
331 self.assertEqual(info, result.info)
332 # check that post hooks are always called
333 [m.reset_mock() for m in all_mocks]
334 ip.run_cell("syntax error")
335 assert pre_always.called
336 assert pre_explicit.called
337 assert post_always.called
338 assert post_explicit.called
339 (info,) = pre_explicit.call_args[0]
340 (result,) = post_explicit.call_args[0]
341 self.assertEqual(info, result.info)
342 finally:
343 # remove post-exec
344 ip.events.unregister("pre_run_cell", pre_explicit)
345 ip.events.unregister("pre_execute", pre_always)
346 ip.events.unregister("post_run_cell", post_explicit)
347 ip.events.unregister("post_execute", post_always)
348
349 def test_silent_noadvance(self):
350 """run_cell(silent=True) doesn't advance execution_count"""
351 ec = ip.execution_count
352 # silent should force store_history=False
353 ip.run_cell("1", store_history=True, silent=True)
354
355 self.assertEqual(ec, ip.execution_count)
356 # double-check that non-silent exec did what we expected
357 # silent to avoid
358 ip.run_cell("1", store_history=True)
359 self.assertEqual(ec + 1, ip.execution_count)
360
361 def test_silent_nodisplayhook(self):
362 """run_cell(silent=True) doesn't trigger displayhook"""
363 d = dict(called=False)
364
365 trap = ip.display_trap
366 save_hook = trap.hook
367
368 def failing_hook(*args, **kwargs):
369 d["called"] = True
370
371 try:
372 trap.hook = failing_hook
373 res = ip.run_cell("1", silent=True)
374 self.assertFalse(d["called"])
375 self.assertIsNone(res.result)
376 # double-check that non-silent exec did what we expected
377 # silent to avoid
378 ip.run_cell("1")
379 self.assertTrue(d["called"])
380 finally:
381 trap.hook = save_hook
382
383 def test_ofind_line_magic(self):
384 from IPython.core.magic import register_line_magic
385
386 @register_line_magic
387 def lmagic(line):
388 "A line magic"
389
390 # Get info on line magic
391 lfind = ip._ofind("lmagic")
392 info = OInfo(
393 found=True,
394 isalias=False,
395 ismagic=True,
396 namespace="IPython internal",
397 obj=lmagic,
398 parent=None,
399 )
400 self.assertEqual(lfind, info)
401
402 def test_ofind_cell_magic(self):
403 from IPython.core.magic import register_cell_magic
404
405 @register_cell_magic
406 def cmagic(line, cell):
407 "A cell magic"
408
409 # Get info on cell magic
410 find = ip._ofind("cmagic")
411 info = OInfo(
412 found=True,
413 isalias=False,
414 ismagic=True,
415 namespace="IPython internal",
416 obj=cmagic,
417 parent=None,
418 )
419 self.assertEqual(find, info)
420
421 def test_ofind_property_with_error(self):
422 class A(object):
423 @property
424 def foo(self):
425 raise NotImplementedError() # pragma: no cover
426
427 a = A()
428
429 found = ip._ofind("a.foo", [("locals", locals())])
430 info = OInfo(
431 found=True,
432 isalias=False,
433 ismagic=False,
434 namespace="locals",
435 obj=A.foo,
436 parent=a,
437 )
438 self.assertEqual(found, info)
439
440 def test_ofind_multiple_attribute_lookups(self):
441 class A(object):
442 @property
443 def foo(self):
444 raise NotImplementedError() # pragma: no cover
445
446 a = A()
447 a.a = A()
448 a.a.a = A()
449
450 found = ip._ofind("a.a.a.foo", [("locals", locals())])
451 info = OInfo(
452 found=True,
453 isalias=False,
454 ismagic=False,
455 namespace="locals",
456 obj=A.foo,
457 parent=a.a.a,
458 )
459 self.assertEqual(found, info)
460
461 def test_ofind_slotted_attributes(self):
462 class A(object):
463 __slots__ = ["foo"]
464
465 def __init__(self):
466 self.foo = "bar"
467
468 a = A()
469 found = ip._ofind("a.foo", [("locals", locals())])
470 info = OInfo(
471 found=True,
472 isalias=False,
473 ismagic=False,
474 namespace="locals",
475 obj=a.foo,
476 parent=a,
477 )
478 self.assertEqual(found, info)
479
480 found = ip._ofind("a.bar", [("locals", locals())])
481 expected = OInfo(
482 found=False,
483 isalias=False,
484 ismagic=False,
485 namespace=None,
486 obj=None,
487 parent=a,
488 )
489 assert found == expected
490
491 def test_ofind_prefers_property_to_instance_level_attribute(self):
492 class A(object):
493 @property
494 def foo(self):
495 return "bar"
496
497 a = A()
498 a.__dict__["foo"] = "baz"
499 self.assertEqual(a.foo, "bar")
500 found = ip._ofind("a.foo", [("locals", locals())])
501 self.assertIs(found.obj, A.foo)
502
503 def test_custom_syntaxerror_exception(self):
504 called = []
505
506 def my_handler(shell, etype, value, tb, tb_offset=None):
507 called.append(etype)
508 shell.showtraceback((etype, value, tb), tb_offset=tb_offset)
509
510 ip.set_custom_exc((SyntaxError,), my_handler)
511 try:
512 ip.run_cell("1f")
513 # Check that this was called, and only once.
514 self.assertEqual(called, [SyntaxError])
515 finally:
516 # Reset the custom exception hook
517 ip.set_custom_exc((), None)
518
519 def test_custom_exception(self):
520 called = []
521
522 def my_handler(shell, etype, value, tb, tb_offset=None):
523 called.append(etype)
524 shell.showtraceback((etype, value, tb), tb_offset=tb_offset)
525
526 ip.set_custom_exc((ValueError,), my_handler)
527 try:
528 res = ip.run_cell("raise ValueError('test')")
529 # Check that this was called, and only once.
530 self.assertEqual(called, [ValueError])
531 # Check that the error is on the result object
532 self.assertIsInstance(res.error_in_exec, ValueError)
533 finally:
534 # Reset the custom exception hook
535 ip.set_custom_exc((), None)
536
537 @mock.patch("builtins.print")
538 def test_showtraceback_with_surrogates(self, mocked_print):
539 values = []
540
541 def mock_print_func(value, sep=" ", end="\n", file=sys.stdout, flush=False):
542 values.append(value)
543 if value == chr(0xD8FF):
544 raise UnicodeEncodeError("utf-8", chr(0xD8FF), 0, 1, "")
545
546 # mock builtins.print
547 mocked_print.side_effect = mock_print_func
548
549 # ip._showtraceback() is replaced in globalipapp.py.
550 # Call original method to test.
551 interactiveshell.InteractiveShell._showtraceback(ip, None, None, chr(0xD8FF))
552
553 self.assertEqual(mocked_print.call_count, 2)
554 self.assertEqual(values, [chr(0xD8FF), "\\ud8ff"])
555
556 def test_mktempfile(self):
557 filename = ip.mktempfile()
558 # Check that we can open the file again on Windows
559 with open(filename, "w", encoding="utf-8") as f:
560 f.write("abc")
561
562 filename = ip.mktempfile(data="blah")
563 with open(filename, "r", encoding="utf-8") as f:
564 self.assertEqual(f.read(), "blah")
565
566 def test_new_main_mod(self):
567 # Smoketest to check that this accepts a unicode module name
568 name = "jiefmw"
569 mod = ip.new_main_mod("%s.py" % name, name)
570 self.assertEqual(mod.__name__, name)
571
572 def test_get_exception_only(self):
573 try:
574 raise KeyboardInterrupt
575 except KeyboardInterrupt:
576 msg = ip.get_exception_only()
577 self.assertEqual(msg, "KeyboardInterrupt\n")
578
579 try:
580 raise DerivedInterrupt("foo")
581 except KeyboardInterrupt:
582 msg = ip.get_exception_only()
583 self.assertEqual(msg, "tests.test_interactiveshell.DerivedInterrupt: foo\n")
584
585 def test_inspect_text(self):
586 ip.run_cell("a = 5")
587 text = ip.object_inspect_text("a")
588 self.assertIsInstance(text, str)
589
590 def test_last_execution_result(self):
591 """Check that last execution result gets set correctly (GH-10702)"""
592 result = ip.run_cell("a = 5; a")
593 self.assertTrue(ip.last_execution_succeeded)
594 self.assertEqual(ip.last_execution_result.result, 5)
595
596 result = ip.run_cell("a = x_invalid_id_x")
597 self.assertFalse(ip.last_execution_succeeded)
598 self.assertFalse(ip.last_execution_result.success)
599 self.assertIsInstance(ip.last_execution_result.error_in_exec, NameError)
600
601 def test_reset_aliasing(self):
602 """Check that standard posix aliases work after %reset."""
603 if os.name != "posix":
604 return
605
606 ip.reset()
607 for cmd in ("clear", "more", "less", "man"):
608 res = ip.run_cell("%" + cmd)
609 self.assertEqual(res.success, True)
610
611
612 @pytest.mark.skipif(
613 sys.implementation.name == "pypy"
614 and ((7, 3, 13) < sys.implementation.version < (7, 3, 16)),
615 reason="Unicode issues with scandir on PyPy, see https://github.com/pypy/pypy/issues/4860",
616 )
617 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
618 @onlyif_unicode_paths
619 def setUp(self):
620 self.BASETESTDIR = tempfile.mkdtemp()
621 self.TESTDIR = join(self.BASETESTDIR, "åäö")
622 os.mkdir(self.TESTDIR)
623 with open(
624 join(self.TESTDIR, "åäötestscript.py"), "w", encoding="utf-8"
625 ) as sfile:
626 sfile.write("pass\n")
627 self.oldpath = os.getcwd()
628 os.chdir(self.TESTDIR)
629 self.fname = "åäötestscript.py"
630
631 def tearDown(self):
632 os.chdir(self.oldpath)
633 shutil.rmtree(self.BASETESTDIR)
634
635 @onlyif_unicode_paths
636 def test_1(self):
637 """Test safe_execfile with non-ascii path"""
638 ip.safe_execfile(self.fname, {}, raise_exceptions=True)
639
640
641 class ExitCodeChecks(tt.TempFileMixin):
642 def setUp(self):
643 self.system = ip.system_raw
644
645 def test_exit_code_ok(self):
646 self.system("exit 0")
647 self.assertEqual(ip.user_ns["_exit_code"], 0)
648
649 def test_exit_code_error(self):
650 self.system("exit 1")
651 self.assertEqual(ip.user_ns["_exit_code"], 1)
652
653 @skipif(not hasattr(signal, "SIGALRM"))
654 def test_exit_code_signal(self):
655 self.mktmp(
656 "import signal, time\n"
657 "signal.setitimer(signal.ITIMER_REAL, 0.1)\n"
658 "time.sleep(1)\n"
659 )
660 self.system("%s %s" % (sys.executable, self.fname))
661 self.assertEqual(ip.user_ns["_exit_code"], -signal.SIGALRM)
662
663 @onlyif_cmds_exist("csh")
664 def test_exit_code_signal_csh(self): # pragma: no cover
665 SHELL = os.environ.get("SHELL", None)
666 os.environ["SHELL"] = find_cmd("csh")
667 try:
668 self.test_exit_code_signal()
669 finally:
670 if SHELL is not None:
671 os.environ["SHELL"] = SHELL
672 else:
673 del os.environ["SHELL"]
674
675
676 class TestSystemRaw(ExitCodeChecks):
677 def setUp(self):
678 super().setUp()
679 self.system = ip.system_raw
680
681 @onlyif_unicode_paths
682 def test_1(self):
683 """Test system_raw with non-ascii cmd"""
684 cmd = """python -c "'åäö'" """
685 ip.system_raw(cmd)
686
687 @mock.patch("subprocess.call", side_effect=KeyboardInterrupt)
688 @mock.patch("os.system", side_effect=KeyboardInterrupt)
689 def test_control_c(self, *mocks):
690 try:
691 self.system("sleep 1 # won't happen")
692 except KeyboardInterrupt: # pragma: no cove
693 self.fail(
694 "system call should intercept "
695 "keyboard interrupt from subprocess.call"
696 )
697 self.assertEqual(ip.user_ns["_exit_code"], -signal.SIGINT)
698
699
700 @pytest.mark.parametrize("magic_cmd", ["pip", "conda", "cd"])
701 def test_magic_warnings(magic_cmd):
702 if sys.platform == "win32":
703 to_mock = "os.system"
704 expected_arg, expected_kwargs = magic_cmd, dict()
705 else:
706 to_mock = "subprocess.call"
707 expected_arg, expected_kwargs = magic_cmd, dict(
708 shell=True, executable=os.environ.get("SHELL", None)
709 )
710
711 with mock.patch(to_mock, return_value=0) as mock_sub:
712 with pytest.warns(Warning, match=r"You executed the system command"):
713 ip.system_raw(magic_cmd)
714 mock_sub.assert_called_once_with(expected_arg, **expected_kwargs)
715
716
717 # TODO: Exit codes are currently ignored on Windows.
718 class TestSystemPipedExitCode(ExitCodeChecks):
719 def setUp(self):
720 super().setUp()
721 self.system = ip.system_piped
722
723 @skip_win32
724 def test_exit_code_ok(self):
725 ExitCodeChecks.test_exit_code_ok(self)
726
727 @skip_win32
728 def test_exit_code_error(self):
729 ExitCodeChecks.test_exit_code_error(self)
730
731 @skip_win32
732 def test_exit_code_signal(self):
733 ExitCodeChecks.test_exit_code_signal(self)
734
735
736 class TestModules(tt.TempFileMixin):
737 def test_extraneous_loads(self):
738 """Test we're not loading modules on startup that we shouldn't."""
739 self.mktmp(
740 "import sys\n"
741 "print('numpy' in sys.modules)\n"
742 "print('ipyparallel' in sys.modules)\n"
743 "print('ipykernel' in sys.modules)\n"
744 )
745 out = "False\nFalse\nFalse\n"
746 tt.ipexec_validate(self.fname, out)
747
748
749 class Negator(ast.NodeTransformer):
750 """Negates all number literals in an AST."""
751
752 def visit_Num(self, node):
753 node.value = -node.value
754 return node
755
756 def visit_Constant(self, node):
757 if isinstance(node.value, int):
758 return self.visit_Num(node)
759 return node
760
761
762 class TestAstTransform(unittest.TestCase):
763 def setUp(self):
764 self.negator = Negator()
765 ip.ast_transformers.append(self.negator)
766
767 def tearDown(self):
768 ip.ast_transformers.remove(self.negator)
769
770 def test_non_int_const(self):
771 with tt.AssertPrints("hello"):
772 ip.run_cell('print("hello")')
773
774 def test_run_cell(self):
775 with tt.AssertPrints("-34"):
776 ip.run_cell("print(12 + 22)")
777
778 # A named reference to a number shouldn't be transformed.
779 ip.user_ns["n"] = 55
780 with tt.AssertNotPrints("-55"):
781 ip.run_cell("print(n)")
782
783 def test_timeit(self):
784 called = set()
785
786 def f(x):
787 called.add(x)
788
789 ip.push({"f": f})
790
791 with tt.AssertPrints("std. dev. of"):
792 ip.run_line_magic("timeit", "-n1 f(1)")
793 self.assertEqual(called, {-1})
794 called.clear()
795
796 with tt.AssertPrints("std. dev. of"):
797 ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)")
798 self.assertEqual(called, {-2, -3})
799
800 def test_time(self):
801 called = []
802
803 def f(x):
804 called.append(x)
805
806 ip.push({"f": f})
807
808 # Test with an expression
809 with tt.AssertPrints("Wall time: "):
810 ip.run_line_magic("time", "f(5+9)")
811 self.assertEqual(called, [-14])
812 called[:] = []
813
814 # Test with a statement (different code path)
815 with tt.AssertPrints("Wall time: "):
816 ip.run_line_magic("time", "a = f(-3 + -2)")
817 self.assertEqual(called, [5])
818
819 def test_macro(self):
820 ip.push({"a": 10})
821 # The AST transformation makes this do a+=-1
822 ip.define_macro("amacro", "a+=1\nprint(a)")
823
824 with tt.AssertPrints("9"):
825 ip.run_cell("amacro")
826 with tt.AssertPrints("8"):
827 ip.run_cell("amacro")
828
829
830 class TestMiscTransform(unittest.TestCase):
831 def test_transform_only_once(self):
832 cleanup = 0
833 line_t = 0
834
835 def count_cleanup(lines):
836 nonlocal cleanup
837 cleanup += 1
838 return lines
839
840 def count_line_t(lines):
841 nonlocal line_t
842 line_t += 1
843 return lines
844
845 ip.input_transformer_manager.cleanup_transforms.append(count_cleanup)
846 ip.input_transformer_manager.line_transforms.append(count_line_t)
847
848 ip.run_cell("1")
849
850 assert cleanup == 1
851 assert line_t == 1
852
853
854 class IntegerWrapper(ast.NodeTransformer):
855 """Wraps all integers in a call to Integer()"""
856
857 # for Python 3.7 and earlier
858 def visit_Num(self, node):
859 if isinstance(node.value, int):
860 return ast.Call(
861 func=ast.Name(id="Integer", ctx=ast.Load()), args=[node], keywords=[]
862 )
863 return node
864
865 # For Python 3.8+
866 def visit_Constant(self, node):
867 if isinstance(node.value, int):
868 return self.visit_Num(node)
869 return node
870
871
872 class TestAstTransform2(unittest.TestCase):
873 def setUp(self):
874 self.intwrapper = IntegerWrapper()
875 ip.ast_transformers.append(self.intwrapper)
876
877 self.calls = []
878
879 def Integer(*args):
880 self.calls.append(args)
881 return args
882
883 ip.push({"Integer": Integer})
884
885 def tearDown(self):
886 ip.ast_transformers.remove(self.intwrapper)
887 del ip.user_ns["Integer"]
888
889 def test_run_cell(self):
890 ip.run_cell("n = 2")
891 self.assertEqual(self.calls, [(2,)])
892
893 # This shouldn't throw an error
894 ip.run_cell("o = 2.0")
895 self.assertEqual(ip.user_ns["o"], 2.0)
896
897 def test_run_cell_non_int(self):
898 ip.run_cell("n = 'a'")
899 assert self.calls == []
900
901 def test_timeit(self):
902 called = set()
903
904 def f(x):
905 called.add(x)
906
907 ip.push({"f": f})
908
909 with tt.AssertPrints("std. dev. of"):
910 ip.run_line_magic("timeit", "-n1 f(1)")
911 self.assertEqual(called, {(1,)})
912 called.clear()
913
914 with tt.AssertPrints("std. dev. of"):
915 ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)")
916 self.assertEqual(called, {(2,), (3,)})
917
918
919 class ErrorTransformer(ast.NodeTransformer):
920 """Throws an error when it sees a number."""
921
922 def visit_Constant(self, node):
923 if isinstance(node.value, int):
924 raise ValueError("test")
925 return node
926
927
928 class TestAstTransformError(unittest.TestCase):
929 def test_unregistering(self):
930 err_transformer = ErrorTransformer()
931 ip.ast_transformers.append(err_transformer)
932
933 with self.assertWarnsRegex(UserWarning, "It will be unregistered"):
934 ip.run_cell("1 + 2")
935
936 # This should have been removed.
937 self.assertNotIn(err_transformer, ip.ast_transformers)
938
939
940 class StringRejector(ast.NodeTransformer):
941 """Throws an InputRejected when it sees a string literal.
942
943 Used to verify that NodeTransformers can signal that a piece of code should
944 not be executed by throwing an InputRejected.
945 """
946
947 def visit_Constant(self, node):
948 if isinstance(node.value, str):
949 raise InputRejected("test")
950 return node
951
952
953 class TestAstTransformInputRejection(unittest.TestCase):
954 def setUp(self):
955 self.transformer = StringRejector()
956 ip.ast_transformers.append(self.transformer)
957
958 def tearDown(self):
959 ip.ast_transformers.remove(self.transformer)
960
961 def test_input_rejection(self):
962 """Check that NodeTransformers can reject input."""
963
964 expect_exception_tb = tt.AssertPrints("InputRejected: test")
965 expect_no_cell_output = tt.AssertNotPrints("'unsafe'", suppress=False)
966
967 # Run the same check twice to verify that the transformer is not
968 # disabled after raising.
969 with expect_exception_tb, expect_no_cell_output:
970 ip.run_cell("'unsafe'")
971
972 with expect_exception_tb, expect_no_cell_output:
973 res = ip.run_cell("'unsafe'")
974
975 self.assertIsInstance(res.error_before_exec, InputRejected)
976
977
978 def test__IPYTHON__():
979 # This shouldn't raise a NameError, that's all
980 __IPYTHON__
981
982
983 class DummyRepr(object):
984 def __repr__(self):
985 return "DummyRepr"
986
987 def _repr_html_(self):
988 return "<b>dummy</b>"
989
990 def _repr_javascript_(self):
991 return "console.log('hi');", {"key": "value"}
992
993
994 def test_user_variables():
995 # enable all formatters
996 ip.display_formatter.active_types = ip.display_formatter.format_types
997
998 ip.user_ns["dummy"] = d = DummyRepr()
999 keys = {"dummy", "doesnotexist"}
1000 r = ip.user_expressions({key: key for key in keys})
1001
1002 assert keys == set(r.keys())
1003 dummy = r["dummy"]
1004 assert {"status", "data", "metadata"} == set(dummy.keys())
1005 assert dummy["status"] == "ok"
1006 data = dummy["data"]
1007 metadata = dummy["metadata"]
1008 assert data.get("text/html") == d._repr_html_()
1009 js, jsmd = d._repr_javascript_()
1010 assert data.get("application/javascript") == js
1011 assert metadata.get("application/javascript") == jsmd
1012
1013 dne = r["doesnotexist"]
1014 assert dne["status"] == "error"
1015 assert dne["ename"] == "NameError"
1016
1017 # back to text only
1018 ip.display_formatter.active_types = ["text/plain"]
1019
1020
1021 def test_user_expression():
1022 # enable all formatters
1023 ip.display_formatter.active_types = ip.display_formatter.format_types
1024 query = {
1025 "a": "1 + 2",
1026 "b": "1/0",
1027 }
1028 r = ip.user_expressions(query)
1029 import pprint
1030
1031 pprint.pprint(r)
1032 assert set(r.keys()) == set(query.keys())
1033 a = r["a"]
1034 assert {"status", "data", "metadata"} == set(a.keys())
1035 assert a["status"] == "ok"
1036 data = a["data"]
1037 metadata = a["metadata"]
1038 assert data.get("text/plain") == "3"
1039
1040 b = r["b"]
1041 assert b["status"] == "error"
1042 assert b["ename"] == "ZeroDivisionError"
1043
1044 # back to text only
1045 ip.display_formatter.active_types = ["text/plain"]
1046
1047
1048 class TestSyntaxErrorTransformer(unittest.TestCase):
1049 """Check that SyntaxError raised by an input transformer is handled by run_cell()"""
1050
1051 @staticmethod
1052 def transformer(lines):
1053 for line in lines:
1054 pos = line.find("syntaxerror")
1055 if pos >= 0:
1056 e = SyntaxError('input contains "syntaxerror"')
1057 e.text = line
1058 e.offset = pos + 1
1059 raise e
1060 return lines
1061
1062 def setUp(self):
1063 ip.input_transformers_post.append(self.transformer)
1064
1065 def tearDown(self):
1066 ip.input_transformers_post.remove(self.transformer)
1067
1068 def test_syntaxerror_input_transformer(self):
1069 with tt.AssertPrints("1234"):
1070 ip.run_cell("1234")
1071 with tt.AssertPrints("SyntaxError: invalid syntax"):
1072 ip.run_cell("1 2 3") # plain python syntax error
1073 with tt.AssertPrints('SyntaxError: input contains "syntaxerror"'):
1074 ip.run_cell("2345 # syntaxerror") # input transformer syntax error
1075 with tt.AssertPrints("3456"):
1076 ip.run_cell("3456")
1077
1078
1079 class TestWarningSuppression(unittest.TestCase):
1080 def test_warning_suppression(self):
1081 ip.run_cell("import warnings")
1082 try:
1083 with self.assertWarnsRegex(UserWarning, "asdf"):
1084 ip.run_cell("warnings.warn('asdf')")
1085 # Here's the real test -- if we run that again, we should get the
1086 # warning again. Traditionally, each warning was only issued once per
1087 # IPython session (approximately), even if the user typed in new and
1088 # different code that should have also triggered the warning, leading
1089 # to much confusion.
1090 with self.assertWarnsRegex(UserWarning, "asdf"):
1091 ip.run_cell("warnings.warn('asdf')")
1092 finally:
1093 ip.run_cell("del warnings")
1094
1095 def test_deprecation_warning(self):
1096 ip.run_cell(
1097 """
1098 import warnings
1099 def wrn():
1100 warnings.warn(
1101 "I AM A WARNING",
1102 DeprecationWarning
1103 )
1104 """
1105 )
1106 try:
1107 with self.assertWarnsRegex(DeprecationWarning, "I AM A WARNING"):
1108 ip.run_cell("wrn()")
1109 finally:
1110 ip.run_cell("del warnings")
1111 ip.run_cell("del wrn")
1112
1113
1114 class TestImportNoDeprecate(tt.TempFileMixin):
1115 def setUp(self):
1116 """Make a valid python temp file."""
1117 self.mktmp(
1118 """
1119 import warnings
1120 def wrn():
1121 warnings.warn(
1122 "I AM A WARNING",
1123 DeprecationWarning
1124 )
1125 """
1126 )
1127 super().setUp()
1128
1129 def test_no_dep(self):
1130 """
1131 No deprecation warning should be raised from imported functions
1132 """
1133 ip.run_cell("from {} import wrn".format(self.fname))
1134
1135 with tt.AssertNotPrints("I AM A WARNING"):
1136 ip.run_cell("wrn()")
1137 ip.run_cell("del wrn")
1138
1139
1140 def test_custom_exc_count():
1141 hook = mock.Mock(return_value=None)
1142 ip.set_custom_exc((SyntaxError,), hook)
1143 before = ip.execution_count
1144 ip.run_cell("def foo()", store_history=True)
1145 # restore default excepthook
1146 ip.set_custom_exc((), None)
1147 assert hook.call_count == 1
1148 assert ip.execution_count == before + 1
1149
1150
1151 def test_run_cell_async():
1152 ip.run_cell("import asyncio")
1153 coro = ip.run_cell_async("await asyncio.sleep(0.01)\n5")
1154 assert asyncio.iscoroutine(coro)
1155 loop = asyncio.new_event_loop()
1156 result = loop.run_until_complete(coro)
1157 assert isinstance(result, interactiveshell.ExecutionResult)
1158 assert result.result == 5
1159
1160
1161 def test_run_cell_await():
1162 ip.run_cell("import asyncio")
1163 result = ip.run_cell("await asyncio.sleep(0.01); 10")
1164 assert ip.user_ns["_"] == 10
1165
1166
1167 def test_run_cell_asyncio_run():
1168 ip.run_cell("import asyncio")
1169 result = ip.run_cell("await asyncio.sleep(0.01); 1")
1170 assert ip.user_ns["_"] == 1
1171 result = ip.run_cell("asyncio.run(asyncio.sleep(0.01)); 2")
1172 assert ip.user_ns["_"] == 2
1173 result = ip.run_cell("await asyncio.sleep(0.01); 3")
1174 assert ip.user_ns["_"] == 3
1175
1176
1177 def test_should_run_async():
1178 assert not ip.should_run_async("a = 5", transformed_cell="a = 5")
1179 assert ip.should_run_async("await x", transformed_cell="await x")
1180 assert ip.should_run_async(
1181 "import asyncio; await asyncio.sleep(1)",
1182 transformed_cell="import asyncio; await asyncio.sleep(1)",
1183 )
1184
1185
1186 def test_set_custom_completer():
1187 num_completers = len(ip.Completer.matchers)
1188
1189 def foo(*args, **kwargs):
1190 return "I'm a completer!"
1191
1192 ip.set_custom_completer(foo, 0)
1193
1194 # check that we've really added a new completer
1195 assert len(ip.Completer.matchers) == num_completers + 1
1196
1197 # check that the first completer is the function we defined
1198 assert ip.Completer.matchers[0]() == "I'm a completer!"
1199
1200 # clean up
1201 ip.Completer.custom_matchers.pop()
1202
1203
1204 class TestShowTracebackAttack(unittest.TestCase):
1205 """Test that the interactive shell is resilient against the client attack of
1206 manipulating the showtracebacks method. These attacks shouldn't result in an
1207 unhandled exception in the kernel."""
1208
1209 def setUp(self):
1210 self.orig_showtraceback = interactiveshell.InteractiveShell.showtraceback
1211
1212 def tearDown(self):
1213 interactiveshell.InteractiveShell.showtraceback = self.orig_showtraceback
1214
1215 def test_set_show_tracebacks_none(self):
1216 """Test the case of the client setting showtracebacks to None"""
1217
1218 result = ip.run_cell(
1219 """
1220 import IPython.core.interactiveshell
1221 IPython.core.interactiveshell.InteractiveShell.showtraceback = None
1222
1223 assert False, "This should not raise an exception"
1224 """
1225 )
1226 print(result)
1227
1228 assert result.result is None
1229 assert isinstance(result.error_in_exec, TypeError)
1230 assert str(result.error_in_exec) == "'NoneType' object is not callable"
1231
1232 def test_set_show_tracebacks_noop(self):
1233 """Test the case of the client setting showtracebacks to a no op lambda"""
1234
1235 result = ip.run_cell(
1236 """
1237 import IPython.core.interactiveshell
1238 IPython.core.interactiveshell.InteractiveShell.showtraceback = lambda *args, **kwargs: None
1239
1240 assert False, "This should not raise an exception"
1241 """
1242 )
1243 print(result)
1244
1245 assert result.result is None
1246 assert isinstance(result.error_in_exec, AssertionError)
1247 assert str(result.error_in_exec) == "This should not raise an exception"
1248
1249
1250 @skip_if_not_osx
1251 def test_enable_gui_osx():
1252 simple_prompt = ip.simple_prompt
1253 ip.simple_prompt = False
1254
1255 ip.enable_gui("osx")
1256 assert ip.active_eventloop == "osx"
1257 ip.enable_gui()
1258
1259 # The following line fails for IPython <= 8.25.0
1260 ip.enable_gui("macosx")
1261 assert ip.active_eventloop == "osx"
1262 ip.enable_gui()
1263
1264 ip.simple_prompt = simple_prompt