Debian Codegraph @

tests/test_run.py

raw
1 # encoding: utf-8
2 """Tests for code execution (%run and related), which is particularly tricky.
3
4 Because of how %run manages namespaces, and the fact that we are trying here to
5 verify subtle object deletion and reference counting issues, the %run tests
6 will be kept in this separate file. This makes it easier to aggregate in one
7 place the tricks needed to handle it; most other magics are much easier to test
8 and we do so in a common test_magic file.
9
10 Note that any test using `run -i` should make sure to do a `reset` afterwards,
11 as otherwise it may influence later tests.
12 """
13
14 # Copyright (c) IPython Development Team.
15 # Distributed under the terms of the Modified BSD License.
16
17
18 import functools
19 import os
20 import platform
21 import random
22 import string
23 import sys
24 import textwrap
25 import unittest
26 from os.path import join as pjoin
27 from unittest.mock import patch
28
29 import pytest
30 from tempfile import TemporaryDirectory
31
32 from IPython.core import debugger
33 from IPython.testing import decorators as dec
34 from IPython.testing import tools as tt
35 from IPython.utils.io import capture_output
36
37
38 def doctest_refbug():
39 """Very nasty problem with references held by multiple runs of a script.
40 See: https://github.com/ipython/ipython/issues/141
41
42 In [1]: _ip.clear_main_mod_cache()
43 # random
44
45 In [2]: %run refbug
46
47 In [3]: call_f()
48 lowercased: hello
49
50 In [4]: %run refbug
51
52 In [5]: call_f()
53 lowercased: hello
54 lowercased: hello
55 """
56
57
58 def doctest_run_builtins():
59 r"""Check that %run doesn't damage __builtins__.
60
61 In [1]: import tempfile
62
63 In [2]: bid1 = id(__builtins__)
64
65 In [3]: fname = tempfile.mkstemp('.py')[1]
66
67 In [3]: f = open(fname, 'w', encoding='utf-8')
68
69 In [4]: dummy= f.write('pass\n')
70
71 In [5]: f.flush()
72
73 In [6]: t1 = type(__builtins__)
74
75 In [7]: %run $fname
76
77 In [7]: f.close()
78
79 In [8]: bid2 = id(__builtins__)
80
81 In [9]: t2 = type(__builtins__)
82
83 In [10]: t1 == t2
84 Out[10]: True
85
86 In [10]: bid1 == bid2
87 Out[10]: True
88
89 In [12]: try:
90 ....: os.unlink(fname)
91 ....: except:
92 ....: pass
93 ....:
94 """
95
96
97 def doctest_run_option_parser():
98 r"""Test option parser in %run.
99
100 In [1]: %run print_argv.py
101 []
102
103 In [2]: %run print_argv.py print*.py
104 ['print_argv.py']
105
106 In [3]: %run -G print_argv.py print*.py
107 ['print*.py']
108
109 """
110
111
112 @dec.skip_win32
113 def doctest_run_option_parser_for_posix():
114 r"""Test option parser in %run (Linux/OSX specific).
115
116 You need double quote to escape glob in POSIX systems:
117
118 In [1]: %run print_argv.py print\\*.py
119 ['print*.py']
120
121 You can't use quote to escape glob in POSIX systems:
122
123 In [2]: %run print_argv.py 'print*.py'
124 ['print_argv.py']
125
126 """
127
128
129 doctest_run_option_parser_for_posix.__skip_doctest__ = sys.platform == "win32"
130
131
132 @dec.skip_if_not_win32
133 def doctest_run_option_parser_for_windows():
134 r"""Test option parser in %run (Windows specific).
135
136 In Windows, you can't escape ``*` `by backslash:
137
138 In [1]: %run print_argv.py print\\*.py
139 ['print\\\\*.py']
140
141 You can use quote to escape glob:
142
143 In [2]: %run print_argv.py 'print*.py'
144 ["'print*.py'"]
145
146 """
147
148
149 doctest_run_option_parser_for_windows.__skip_doctest__ = sys.platform != "win32"
150
151
152 def doctest_reset_del():
153 """Test that resetting doesn't cause errors in __del__ methods.
154
155 In [2]: class A(object):
156 ...: def __del__(self):
157 ...: print(str("Hi"))
158 ...:
159
160 In [3]: a = A()
161
162 In [4]: get_ipython().reset(); import gc; x = gc.collect(0)
163 Hi
164
165 In [5]: 1+1
166 Out[5]: 2
167 """
168
169
170 # For some tests, it will be handy to organize them in a class with a common
171 # setup that makes a temp file
172
173 import sysconfig
174
175 is_freethreaded = bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
176
177
178 class TestMagicRunPass(tt.TempFileMixin):
179 def setUp(self):
180 content = "a = [1,2,3]\nb = 1"
181 self.mktmp(content)
182
183 def run_tmpfile(self):
184 _ip = get_ipython()
185 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
186 # See below and ticket https://bugs.launchpad.net/bugs/366353
187 _ip.run_line_magic("run", self.fname)
188
189 def run_tmpfile_p(self):
190 _ip = get_ipython()
191 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
192 # See below and ticket https://bugs.launchpad.net/bugs/366353
193 _ip.run_line_magic("run", "-p %s" % self.fname)
194
195 def test_builtins_id(self):
196 """Check that %run doesn't damage __builtins__"""
197 _ip = get_ipython()
198 # Test that the id of __builtins__ is not modified by %run
199 bid1 = id(_ip.user_ns["__builtins__"])
200 self.run_tmpfile()
201 bid2 = id(_ip.user_ns["__builtins__"])
202 assert bid1 == bid2
203
204 def test_builtins_type(self):
205 """Check that the type of __builtins__ doesn't change with %run.
206
207 However, the above could pass if __builtins__ was already modified to
208 be a dict (it should be a module) by a previous use of %run. So we
209 also check explicitly that it really is a module:
210 """
211 _ip = get_ipython()
212 self.run_tmpfile()
213 assert type(_ip.user_ns["__builtins__"]) == type(sys)
214
215 def test_run_profile(self):
216 """Test that the option -p, which invokes the profiler, do not
217 crash by invoking execfile"""
218 self.run_tmpfile_p()
219
220 def test_run_debug_twice(self):
221 # https://github.com/ipython/ipython/issues/10028
222 _ip = get_ipython()
223 with tt.fake_input(["c"]):
224 _ip.run_line_magic("run", "-d %s" % self.fname)
225 with tt.fake_input(["c"]):
226 _ip.run_line_magic("run", "-d %s" % self.fname)
227
228 def test_run_debug_twice_with_breakpoint(self):
229 """Make a valid python temp file."""
230 _ip = get_ipython()
231 with tt.fake_input(["b 2", "c", "c"]):
232 _ip.run_line_magic("run", "-d %s" % self.fname)
233
234 with tt.fake_input(["c"]):
235 with tt.AssertNotPrints("KeyError"):
236 _ip.run_line_magic("run", "-d %s" % self.fname)
237
238
239 class TestMagicRunSimple(tt.TempFileMixin):
240 def test_simpledef(self):
241 """Test that simple class definitions work."""
242 src = "class foo: pass\n" "def f(): return foo()"
243 self.mktmp(src)
244 _ip.run_line_magic("run", str(self.fname))
245 _ip.run_cell("t = isinstance(f(), foo)")
246 assert _ip.user_ns["t"] is True
247
248 @pytest.mark.xfail(
249 platform.python_implementation() == "PyPy",
250 reason="expecting __del__ call on exit is unreliable and doesn't happen on PyPy",
251 )
252 def test_obj_del(self):
253 """Test that object's __del__ methods are called on exit."""
254 src = (
255 "class A(object):\n"
256 " def __del__(self):\n"
257 " print('object A deleted')\n"
258 "a = A()\n"
259 )
260 self.mktmp(src)
261 err = None
262 tt.ipexec_validate(self.fname, "object A deleted", err)
263
264 def test_aggressive_namespace_cleanup(self):
265 """Test that namespace cleanup is not too aggressive GH-238
266
267 Returning from another run magic deletes the namespace"""
268 # see ticket https://github.com/ipython/ipython/issues/238
269
270 with tt.TempFileMixin() as empty:
271 empty.mktmp("")
272 # On Windows, the filename will have \users in it, so we need to use the
273 # repr so that the \u becomes \\u.
274 src = (
275 "ip = get_ipython()\n"
276 "for i in range(5):\n"
277 " try:\n"
278 " ip.run_line_magic(%r, %r)\n"
279 " except NameError as e:\n"
280 " print(i)\n"
281 " break\n" % ("run", empty.fname)
282 )
283 self.mktmp(src)
284 _ip.run_line_magic("run", str(self.fname))
285 _ip.run_cell("ip == get_ipython()")
286 assert _ip.user_ns["i"] == 4
287
288 def test_run_second(self):
289 """Test that running a second file doesn't clobber the first, gh-3547"""
290 self.mktmp("avar = 1\n" "def afunc():\n" " return avar\n")
291
292 with tt.TempFileMixin() as empty:
293 empty.mktmp("")
294
295 _ip.run_line_magic("run", self.fname)
296 _ip.run_line_magic("run", empty.fname)
297 assert _ip.user_ns["afunc"]() == 1
298
299 @pytest.mark.xfail(is_freethreaded, reason="C-third leaks on free-threaded python")
300 def test_tclass(self):
301 mydir = os.path.dirname(__file__)
302 tc = os.path.join(mydir, "tclass")
303 src = f"""\
304 import gc
305 %run "{tc}" C-first
306 gc.collect(0)
307 %run "{tc}" C-second
308 gc.collect(0)
309 %run "{tc}" C-third
310 gc.collect(0)
311 %reset -f
312 """
313 self.mktmp(src, ".ipy")
314 out = """\
315 ARGV 1-: ['C-first']
316 ARGV 1-: ['C-second']
317 tclass.py: deleting object: C-first
318 ARGV 1-: ['C-third']
319 tclass.py: deleting object: C-second
320 tclass.py: deleting object: C-third
321 """
322 err = None
323 tt.ipexec_validate(self.fname, out, err)
324
325 def test_run_i_after_reset(self):
326 """Check that %run -i still works after %reset (gh-693)"""
327 src = "yy = zz\n"
328 self.mktmp(src)
329 _ip.run_cell("zz = 23")
330 try:
331 _ip.run_line_magic("run", "-i %s" % self.fname)
332 assert _ip.user_ns["yy"] == 23
333 finally:
334 _ip.run_line_magic("reset", "-f")
335
336 _ip.run_cell("zz = 23")
337 try:
338 _ip.run_line_magic("run", "-i %s" % self.fname)
339 assert _ip.user_ns["yy"] == 23
340 finally:
341 _ip.run_line_magic("reset", "-f")
342
343 def test_unicode(self):
344 """Check that files in odd encodings are accepted."""
345 mydir = os.path.dirname(__file__)
346 na = os.path.join(mydir, "nonascii.py")
347 _ip.run_line_magic("run", na)
348 assert _ip.user_ns["u"] == "Ўт№Ф"
349
350 def test_run_py_file_attribute(self):
351 """Test handling of `__file__` attribute in `%run <file>.py`."""
352 src = "t = __file__\n"
353 self.mktmp(src)
354 _missing = object()
355 file1 = _ip.user_ns.get("__file__", _missing)
356 _ip.run_line_magic("run", self.fname)
357 file2 = _ip.user_ns.get("__file__", _missing)
358
359 # Check that __file__ was equal to the filename in the script's
360 # namespace.
361 assert _ip.user_ns["t"] == self.fname
362
363 # Check that __file__ was not leaked back into user_ns.
364 assert file1 == file2
365
366 def test_run_ipy_file_attribute(self):
367 """Test handling of `__file__` attribute in `%run <file.ipy>`."""
368 src = "t = __file__\n"
369 self.mktmp(src, ext=".ipy")
370 _missing = object()
371 file1 = _ip.user_ns.get("__file__", _missing)
372 _ip.run_line_magic("run", self.fname)
373 file2 = _ip.user_ns.get("__file__", _missing)
374
375 # Check that __file__ was equal to the filename in the script's
376 # namespace.
377 assert _ip.user_ns["t"] == self.fname
378
379 # Check that __file__ was not leaked back into user_ns.
380 assert file1 == file2
381
382 def test_run_formatting(self):
383 """Test that %run -t -N<N> does not raise a TypeError for N > 1."""
384 src = "pass"
385 self.mktmp(src)
386 _ip.run_line_magic("run", "-t -N 1 %s" % self.fname)
387 _ip.run_line_magic("run", "-t -N 10 %s" % self.fname)
388
389 def test_ignore_sys_exit(self):
390 """Test the -e option to ignore sys.exit()"""
391 src = "import sys; sys.exit(1)"
392 self.mktmp(src)
393 with tt.AssertPrints("SystemExit"):
394 _ip.run_line_magic("run", self.fname)
395
396 with tt.AssertNotPrints("SystemExit"):
397 _ip.run_line_magic("run", "-e %s" % self.fname)
398
399 def test_run_nb(self):
400 """Test %run notebook.ipynb"""
401 pytest.importorskip("nbformat")
402 from nbformat import v4, writes
403
404 nb = v4.new_notebook(
405 cells=[
406 v4.new_markdown_cell("The Ultimate Question of Everything"),
407 v4.new_code_cell("answer=42"),
408 ]
409 )
410 src = writes(nb, version=4)
411 self.mktmp(src, ext=".ipynb")
412
413 _ip.run_line_magic("run", self.fname)
414
415 assert _ip.user_ns["answer"] == 42
416
417 def test_run_nb_error(self):
418 """Test %run notebook.ipynb error"""
419 pytest.importorskip("nbformat")
420 from nbformat import v4, writes
421
422 # %run when a file name isn't provided
423 pytest.raises(Exception, _ip.run_line_magic, "run")
424
425 # %run when a file doesn't exist
426 pytest.raises(Exception, _ip.run_line_magic, "run", "foobar.ipynb")
427
428 # %run on a notebook with an error
429 nb = v4.new_notebook(cells=[v4.new_code_cell("0/0")])
430 src = writes(nb, version=4)
431 self.mktmp(src, ext=".ipynb")
432 pytest.raises(Exception, _ip.run_line_magic, "run", self.fname)
433
434 def test_file_options(self):
435 src = "import sys\n" 'a = " ".join(sys.argv[1:])\n'
436 self.mktmp(src)
437 test_opts = "-x 3 --verbose"
438 _ip.run_line_magic("run", "{0} {1}".format(self.fname, test_opts))
439 assert _ip.user_ns["a"] == test_opts
440
441
442 class TestMagicRunWithPackage(unittest.TestCase):
443 def writefile(self, name, content):
444 path = os.path.join(self.tempdir.name, name)
445 d = os.path.dirname(path)
446 if not os.path.isdir(d):
447 os.makedirs(d)
448 with open(path, "w", encoding="utf-8") as f:
449 f.write(textwrap.dedent(content))
450
451 def setUp(self):
452 self.package = package = "tmp{0}".format(
453 "".join([random.choice(string.ascii_letters) for i in range(10)])
454 )
455 """Temporary (probably) valid python package name."""
456
457 self.value = int(random.random() * 10000)
458
459 self.tempdir = TemporaryDirectory()
460 self.__orig_cwd = os.getcwd()
461 sys.path.insert(0, self.tempdir.name)
462
463 self.writefile(os.path.join(package, "__init__.py"), "")
464 self.writefile(
465 os.path.join(package, "sub.py"),
466 """
467 x = {0!r}
468 """.format(
469 self.value
470 ),
471 )
472 self.writefile(
473 os.path.join(package, "relative.py"),
474 """
475 from .sub import x
476 """,
477 )
478 self.writefile(
479 os.path.join(package, "absolute.py"),
480 """
481 from {0}.sub import x
482 """.format(
483 package
484 ),
485 )
486 self.writefile(
487 os.path.join(package, "args.py"),
488 """
489 import sys
490 a = " ".join(sys.argv[1:])
491 """.format(
492 package
493 ),
494 )
495
496 def tearDown(self):
497 os.chdir(self.__orig_cwd)
498 sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
499 self.tempdir.cleanup()
500
501 def check_run_submodule(self, submodule, opts=""):
502 _ip.user_ns.pop("x", None)
503 _ip.run_line_magic(
504 "run", "{2} -m {0}.{1}".format(self.package, submodule, opts)
505 )
506 self.assertEqual(
507 _ip.user_ns["x"],
508 self.value,
509 "Variable `x` is not loaded from module `{0}`.".format(submodule),
510 )
511
512 def test_run_submodule_with_absolute_import(self):
513 self.check_run_submodule("absolute")
514
515 def test_run_submodule_with_relative_import(self):
516 """Run submodule that has a relative import statement (#2727)."""
517 self.check_run_submodule("relative")
518
519 def test_prun_submodule_with_absolute_import(self):
520 self.check_run_submodule("absolute", "-p")
521
522 def test_prun_submodule_with_relative_import(self):
523 self.check_run_submodule("relative", "-p")
524
525 def with_fake_debugger(func):
526 @functools.wraps(func)
527 def wrapper(*args, **kwds):
528 with patch.object(debugger.Pdb, "run", staticmethod(eval)):
529 return func(*args, **kwds)
530
531 return wrapper
532
533 @with_fake_debugger
534 def test_debug_run_submodule_with_absolute_import(self):
535 self.check_run_submodule("absolute", "-d")
536
537 @with_fake_debugger
538 def test_debug_run_submodule_with_relative_import(self):
539 self.check_run_submodule("relative", "-d")
540
541 def test_module_options(self):
542 _ip.user_ns.pop("a", None)
543 test_opts = "-x abc -m test"
544 _ip.run_line_magic("run", "-m {0}.args {1}".format(self.package, test_opts))
545 assert _ip.user_ns["a"] == test_opts
546
547 def test_module_options_with_separator(self):
548 _ip.user_ns.pop("a", None)
549 test_opts = "-x abc -m test"
550 _ip.run_line_magic("run", "-m {0}.args -- {1}".format(self.package, test_opts))
551 assert _ip.user_ns["a"] == test_opts
552
553
554 def test_run__name__():
555 with TemporaryDirectory() as td:
556 path = pjoin(td, "foo.py")
557 with open(path, "w", encoding="utf-8") as f:
558 f.write("q = __name__")
559
560 _ip.user_ns.pop("q", None)
561 _ip.run_line_magic("run", "{}".format(path))
562 assert _ip.user_ns.pop("q") == "__main__"
563
564 _ip.run_line_magic("run", "-n {}".format(path))
565 assert _ip.user_ns.pop("q") == "foo"
566
567 try:
568 _ip.run_line_magic("run", "-i -n {}".format(path))
569 assert _ip.user_ns.pop("q") == "foo"
570 finally:
571 _ip.run_line_magic("reset", "-f")
572
573
574 def test_run_tb():
575 """Test traceback offset in %run"""
576 with TemporaryDirectory() as td:
577 path = pjoin(td, "foo.py")
578 with open(path, "w", encoding="utf-8") as f:
579 f.write(
580 "\n".join(
581 [
582 "def foo():",
583 " return bar()",
584 "def bar():",
585 " raise RuntimeError('hello!')",
586 "foo()",
587 ]
588 )
589 )
590 with capture_output() as io:
591 _ip.run_line_magic("run", "{}".format(path))
592 out = io.stdout
593 assert "execfile" not in out
594 assert "RuntimeError" in out
595 assert out.count("---->") == 3
596 del ip.user_ns["bar"]
597 del ip.user_ns["foo"]
598
599
600 def test_multiprocessing_run():
601 """Set we can run mutiprocesgin without messing up up main namespace
602
603 Note that import `nose.tools as nt` modify the values
604 sys.module['__mp_main__'] so we need to temporarily set it to None to test
605 the issue.
606 """
607 with TemporaryDirectory() as td:
608 mpm = sys.modules.get("__mp_main__")
609 sys.modules["__mp_main__"] = None
610 try:
611 path = pjoin(td, "test.py")
612 with open(path, "w", encoding="utf-8") as f:
613 f.write("import multiprocessing\nprint('hoy')")
614 with capture_output() as io:
615 _ip.run_line_magic("run", path)
616 _ip.run_cell("i_m_undefined")
617 out = io.stdout
618 assert "hoy" in out
619 assert "AttributeError" not in out
620 assert "NameError" in out
621 assert out.count("---->") == 1
622 except:
623 raise
624 finally:
625 sys.modules["__mp_main__"] = mpm
626
627
628 def test_script_tb():
629 """Test traceback offset in `ipython script.py`"""
630 with TemporaryDirectory() as td:
631 path = pjoin(td, "foo.py")
632 with open(path, "w", encoding="utf-8") as f:
633 f.write(
634 "\n".join(
635 [
636 "def foo():",
637 " return bar()",
638 "def bar():",
639 " raise RuntimeError('hello!')",
640 "foo()",
641 ]
642 )
643 )
644 out, err = tt.ipexec(path)
645 assert "execfile" not in out
646 assert "RuntimeError" in out
647 assert out.count("---->") == 3