##// END OF EJS Templates
MAINT: convert ip.magic to to run_line magic in many places....
Matthias Bussonnier -
Show More
@@ -84,7 +84,7 b' def test_extract_symbols_raises_exception_with_non_python_code():'
84 def test_magic_not_found():
84 def test_magic_not_found():
85 # magic not found raises UsageError
85 # magic not found raises UsageError
86 with pytest.raises(UsageError):
86 with pytest.raises(UsageError):
87 _ip.magic('doesntexist')
87 _ip.run_line_magic("doesntexist", "")
88
88
89 # ensure result isn't success when a magic isn't found
89 # ensure result isn't success when a magic isn't found
90 result = _ip.run_cell('%doesntexist')
90 result = _ip.run_cell('%doesntexist')
@@ -116,13 +116,14 b' def test_config():'
116 magic.
116 magic.
117 """
117 """
118 ## should not raise.
118 ## should not raise.
119 _ip.magic('config')
119 _ip.run_line_magic("config", "")
120
120
121
121 def test_config_available_configs():
122 def test_config_available_configs():
122 """ test that config magic prints available configs in unique and
123 """ test that config magic prints available configs in unique and
123 sorted order. """
124 sorted order. """
124 with capture_output() as captured:
125 with capture_output() as captured:
125 _ip.magic('config')
126 _ip.run_line_magic("config", "")
126
127
127 stdout = captured.stdout
128 stdout = captured.stdout
128 config_classes = stdout.strip().split('\n')[1:]
129 config_classes = stdout.strip().split('\n')[1:]
@@ -131,7 +132,7 b' def test_config_available_configs():'
131 def test_config_print_class():
132 def test_config_print_class():
132 """ test that config with a classname prints the class's options. """
133 """ test that config with a classname prints the class's options. """
133 with capture_output() as captured:
134 with capture_output() as captured:
134 _ip.magic('config TerminalInteractiveShell')
135 _ip.run_line_magic("config", "TerminalInteractiveShell")
135
136
136 stdout = captured.stdout
137 stdout = captured.stdout
137 assert re.match(
138 assert re.match(
@@ -144,7 +145,7 b' def test_rehashx():'
144 _ip.alias_manager.clear_aliases()
145 _ip.alias_manager.clear_aliases()
145 del _ip.db['syscmdlist']
146 del _ip.db['syscmdlist']
146
147
147 _ip.magic('rehashx')
148 _ip.run_line_magic("rehashx", "")
148 # Practically ALL ipython development systems will have more than 10 aliases
149 # Practically ALL ipython development systems will have more than 10 aliases
149
150
150 assert len(_ip.alias_manager.aliases) > 10
151 assert len(_ip.alias_manager.aliases) > 10
@@ -277,11 +278,11 b' def test_macro():'
277 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
278 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
278 for i, cmd in enumerate(cmds, start=1):
279 for i, cmd in enumerate(cmds, start=1):
279 ip.history_manager.store_inputs(i, cmd)
280 ip.history_manager.store_inputs(i, cmd)
280 ip.magic("macro test 1-3")
281 ip.run_line_magic("macro", "test 1-3")
281 assert ip.user_ns["test"].value == "\n".join(cmds) + "\n"
282 assert ip.user_ns["test"].value == "\n".join(cmds) + "\n"
282
283
283 # List macros
284 # List macros
284 assert "test" in ip.magic("macro")
285 assert "test" in ip.run_line_magic("macro", "")
285
286
286
287
287 def test_macro_run():
288 def test_macro_run():
@@ -302,7 +303,7 b' def test_magic_magic():'
302 """Test %magic"""
303 """Test %magic"""
303 ip = get_ipython()
304 ip = get_ipython()
304 with capture_output() as captured:
305 with capture_output() as captured:
305 ip.magic("magic")
306 ip.run_line_magic("magic", "")
306
307
307 stdout = captured.stdout
308 stdout = captured.stdout
308 assert "%magic" in stdout
309 assert "%magic" in stdout
@@ -316,7 +317,7 b' def test_numpy_reset_array_undec():'
316 _ip.ex("import numpy as np")
317 _ip.ex("import numpy as np")
317 _ip.ex("a = np.empty(2)")
318 _ip.ex("a = np.empty(2)")
318 assert "a" in _ip.user_ns
319 assert "a" in _ip.user_ns
319 _ip.magic("reset -f array")
320 _ip.run_line_magic("reset", "-f array")
320 assert "a" not in _ip.user_ns
321 assert "a" not in _ip.user_ns
321
322
322
323
@@ -326,7 +327,7 b' def test_reset_out():'
326 # test '%reset -f out', make an Out prompt
327 # test '%reset -f out', make an Out prompt
327 _ip.run_cell("parrot", store_history=True)
328 _ip.run_cell("parrot", store_history=True)
328 assert "dead" in [_ip.user_ns[x] for x in ("_", "__", "___")]
329 assert "dead" in [_ip.user_ns[x] for x in ("_", "__", "___")]
329 _ip.magic("reset -f out")
330 _ip.run_line_magic("reset", "-f out")
330 assert "dead" not in [_ip.user_ns[x] for x in ("_", "__", "___")]
331 assert "dead" not in [_ip.user_ns[x] for x in ("_", "__", "___")]
331 assert len(_ip.user_ns["Out"]) == 0
332 assert len(_ip.user_ns["Out"]) == 0
332
333
@@ -336,7 +337,7 b' def test_reset_in():'
336 # test '%reset -f in'
337 # test '%reset -f in'
337 _ip.run_cell("parrot", store_history=True)
338 _ip.run_cell("parrot", store_history=True)
338 assert "parrot" in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")]
339 assert "parrot" in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")]
339 _ip.magic("%reset -f in")
340 _ip.run_line_magic("reset", "-f in")
340 assert "parrot" not in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")]
341 assert "parrot" not in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")]
341 assert len(set(_ip.user_ns["In"])) == 1
342 assert len(set(_ip.user_ns["In"])) == 1
342
343
@@ -344,10 +345,10 b' def test_reset_in():'
344 def test_reset_dhist():
345 def test_reset_dhist():
345 "Test '%reset dhist' magic"
346 "Test '%reset dhist' magic"
346 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
347 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
347 _ip.magic("cd " + os.path.dirname(pytest.__file__))
348 _ip.run_line_magic("cd", os.path.dirname(pytest.__file__))
348 _ip.magic("cd -")
349 _ip.run_line_magic("cd", "-")
349 assert len(_ip.user_ns["_dh"]) > 0
350 assert len(_ip.user_ns["_dh"]) > 0
350 _ip.magic("reset -f dhist")
351 _ip.run_line_magic("reset", "-f dhist")
351 assert len(_ip.user_ns["_dh"]) == 0
352 assert len(_ip.user_ns["_dh"]) == 0
352 _ip.run_cell("_dh = [d for d in tmp]") # restore
353 _ip.run_cell("_dh = [d for d in tmp]") # restore
353
354
@@ -472,8 +473,8 b' def test_time_local_ns():'
472
473
473 def test_doctest_mode():
474 def test_doctest_mode():
474 "Toggle doctest_mode twice, it should be a no-op and run without error"
475 "Toggle doctest_mode twice, it should be a no-op and run without error"
475 _ip.magic('doctest_mode')
476 _ip.run_line_magic("doctest_mode", "")
476 _ip.magic('doctest_mode')
477 _ip.run_line_magic("doctest_mode", "")
477
478
478
479
479 def test_parse_options():
480 def test_parse_options():
@@ -498,7 +499,9 b' def test_parse_options_preserve_non_option_string():'
498 def test_run_magic_preserve_code_block():
499 def test_run_magic_preserve_code_block():
499 """Test to assert preservation of non-option part of magic-block, while running magic."""
500 """Test to assert preservation of non-option part of magic-block, while running magic."""
500 _ip.user_ns["spaces"] = []
501 _ip.user_ns["spaces"] = []
501 _ip.magic("timeit -n1 -r1 spaces.append([s.count(' ') for s in ['document']])")
502 _ip.run_line_magic(
503 "timeit", "-n1 -r1 spaces.append([s.count(' ') for s in ['document']])"
504 )
502 assert _ip.user_ns["spaces"] == [[0]]
505 assert _ip.user_ns["spaces"] == [[0]]
503
506
504
507
@@ -509,13 +512,13 b' def test_dirops():'
509 startdir = os.getcwd()
512 startdir = os.getcwd()
510 ipdir = os.path.realpath(_ip.ipython_dir)
513 ipdir = os.path.realpath(_ip.ipython_dir)
511 try:
514 try:
512 _ip.magic('cd "%s"' % ipdir)
515 _ip.run_line_magic("cd", '"%s"' % ipdir)
513 assert curpath() == ipdir
516 assert curpath() == ipdir
514 _ip.magic('cd -')
517 _ip.run_line_magic("cd", "-")
515 assert curpath() == startdir
518 assert curpath() == startdir
516 _ip.magic('pushd "%s"' % ipdir)
519 _ip.run_line_magic("pushd", '"%s"' % ipdir)
517 assert curpath() == ipdir
520 assert curpath() == ipdir
518 _ip.magic('popd')
521 _ip.run_line_magic("popd", "")
519 assert curpath() == startdir
522 assert curpath() == startdir
520 finally:
523 finally:
521 os.chdir(startdir)
524 os.chdir(startdir)
@@ -542,7 +545,7 b' def test_xmode():'
542 # Calling xmode three times should be a no-op
545 # Calling xmode three times should be a no-op
543 xmode = _ip.InteractiveTB.mode
546 xmode = _ip.InteractiveTB.mode
544 for i in range(4):
547 for i in range(4):
545 _ip.magic("xmode")
548 _ip.run_line_magic("xmode", "")
546 assert _ip.InteractiveTB.mode == xmode
549 assert _ip.InteractiveTB.mode == xmode
547
550
548 def test_reset_hard():
551 def test_reset_hard():
@@ -557,7 +560,7 b' def test_reset_hard():'
557 _ip.run_cell("a")
560 _ip.run_cell("a")
558
561
559 assert monitor == []
562 assert monitor == []
560 _ip.magic("reset -f")
563 _ip.run_line_magic("reset", "-f")
561 assert monitor == [1]
564 assert monitor == [1]
562
565
563 class TestXdel(tt.TempFileMixin):
566 class TestXdel(tt.TempFileMixin):
@@ -570,14 +573,14 b' class TestXdel(tt.TempFileMixin):'
570 "a = A()\n")
573 "a = A()\n")
571 self.mktmp(src)
574 self.mktmp(src)
572 # %run creates some hidden references...
575 # %run creates some hidden references...
573 _ip.magic("run %s" % self.fname)
576 _ip.run_line_magic("run", "%s" % self.fname)
574 # ... as does the displayhook.
577 # ... as does the displayhook.
575 _ip.run_cell("a")
578 _ip.run_cell("a")
576
579
577 monitor = _ip.user_ns["A"].monitor
580 monitor = _ip.user_ns["A"].monitor
578 assert monitor == []
581 assert monitor == []
579
582
580 _ip.magic("xdel a")
583 _ip.run_line_magic("xdel", "a")
581
584
582 # Check that a's __del__ method has been called.
585 # Check that a's __del__ method has been called.
583 gc.collect(0)
586 gc.collect(0)
@@ -614,7 +617,7 b' def test_whos():'
614 def __repr__(self):
617 def __repr__(self):
615 raise Exception()
618 raise Exception()
616 _ip.user_ns['a'] = A()
619 _ip.user_ns['a'] = A()
617 _ip.magic("whos")
620 _ip.run_line_magic("whos", "")
618
621
619 def doctest_precision():
622 def doctest_precision():
620 """doctest for %precision
623 """doctest for %precision
@@ -655,12 +658,12 b' def test_psearch():'
655 def test_timeit_shlex():
658 def test_timeit_shlex():
656 """test shlex issues with timeit (#1109)"""
659 """test shlex issues with timeit (#1109)"""
657 _ip.ex("def f(*a,**kw): pass")
660 _ip.ex("def f(*a,**kw): pass")
658 _ip.magic('timeit -n1 "this is a bug".count(" ")')
661 _ip.run_line_magic("timeit", '-n1 "this is a bug".count(" ")')
659 _ip.magic('timeit -r1 -n1 f(" ", 1)')
662 _ip.run_line_magic("timeit", '-r1 -n1 f(" ", 1)')
660 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
663 _ip.run_line_magic("timeit", '-r1 -n1 f(" ", 1, " ", 2, " ")')
661 _ip.magic('timeit -r1 -n1 ("a " + "b")')
664 _ip.run_line_magic("timeit", '-r1 -n1 ("a " + "b")')
662 _ip.magic('timeit -r1 -n1 f("a " + "b")')
665 _ip.run_line_magic("timeit", '-r1 -n1 f("a " + "b")')
663 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
666 _ip.run_line_magic("timeit", '-r1 -n1 f("a " + "b ")')
664
667
665
668
666 def test_timeit_special_syntax():
669 def test_timeit_special_syntax():
@@ -738,9 +741,9 b' def test_extension():'
738 try:
741 try:
739 _ip.user_ns.pop('arq', None)
742 _ip.user_ns.pop('arq', None)
740 invalidate_caches() # Clear import caches
743 invalidate_caches() # Clear import caches
741 _ip.magic("load_ext daft_extension")
744 _ip.run_line_magic("load_ext", "daft_extension")
742 assert _ip.user_ns["arq"] == 185
745 assert _ip.user_ns["arq"] == 185
743 _ip.magic("unload_ext daft_extension")
746 _ip.run_line_magic("unload_ext", "daft_extension")
744 assert 'arq' not in _ip.user_ns
747 assert 'arq' not in _ip.user_ns
745 finally:
748 finally:
746 sys.path.remove(daft_path)
749 sys.path.remove(daft_path)
@@ -755,17 +758,17 b' def test_notebook_export_json():'
755 _ip.history_manager.store_inputs(i, cmd)
758 _ip.history_manager.store_inputs(i, cmd)
756 with TemporaryDirectory() as td:
759 with TemporaryDirectory() as td:
757 outfile = os.path.join(td, "nb.ipynb")
760 outfile = os.path.join(td, "nb.ipynb")
758 _ip.magic("notebook %s" % outfile)
761 _ip.run_line_magic("notebook", "%s" % outfile)
759
762
760
763
761 class TestEnv(TestCase):
764 class TestEnv(TestCase):
762
765
763 def test_env(self):
766 def test_env(self):
764 env = _ip.magic("env")
767 env = _ip.run_line_magic("env", "")
765 self.assertTrue(isinstance(env, dict))
768 self.assertTrue(isinstance(env, dict))
766
769
767 def test_env_secret(self):
770 def test_env_secret(self):
768 env = _ip.magic("env")
771 env = _ip.run_line_magic("env", "")
769 hidden = "<hidden>"
772 hidden = "<hidden>"
770 with mock.patch.dict(
773 with mock.patch.dict(
771 os.environ,
774 os.environ,
@@ -776,35 +779,35 b' class TestEnv(TestCase):'
776 "VAR": "abc"
779 "VAR": "abc"
777 }
780 }
778 ):
781 ):
779 env = _ip.magic("env")
782 env = _ip.run_line_magic("env", "")
780 assert env["API_KEY"] == hidden
783 assert env["API_KEY"] == hidden
781 assert env["SECRET_THING"] == hidden
784 assert env["SECRET_THING"] == hidden
782 assert env["JUPYTER_TOKEN"] == hidden
785 assert env["JUPYTER_TOKEN"] == hidden
783 assert env["VAR"] == "abc"
786 assert env["VAR"] == "abc"
784
787
785 def test_env_get_set_simple(self):
788 def test_env_get_set_simple(self):
786 env = _ip.magic("env var val1")
789 env = _ip.run_line_magic("env", "var val1")
787 self.assertEqual(env, None)
790 self.assertEqual(env, None)
788 self.assertEqual(os.environ['var'], 'val1')
791 self.assertEqual(os.environ["var"], "val1")
789 self.assertEqual(_ip.magic("env var"), 'val1')
792 self.assertEqual(_ip.run_line_magic("env", "var"), "val1")
790 env = _ip.magic("env var=val2")
793 env = _ip.run_line_magic("env", "var=val2")
791 self.assertEqual(env, None)
794 self.assertEqual(env, None)
792 self.assertEqual(os.environ['var'], 'val2')
795 self.assertEqual(os.environ['var'], 'val2')
793
796
794 def test_env_get_set_complex(self):
797 def test_env_get_set_complex(self):
795 env = _ip.magic("env var 'val1 '' 'val2")
798 env = _ip.run_line_magic("env", "var 'val1 '' 'val2")
796 self.assertEqual(env, None)
799 self.assertEqual(env, None)
797 self.assertEqual(os.environ['var'], "'val1 '' 'val2")
800 self.assertEqual(os.environ['var'], "'val1 '' 'val2")
798 self.assertEqual(_ip.magic("env var"), "'val1 '' 'val2")
801 self.assertEqual(_ip.run_line_magic("env", "var"), "'val1 '' 'val2")
799 env = _ip.magic('env var=val2 val3="val4')
802 env = _ip.run_line_magic("env", 'var=val2 val3="val4')
800 self.assertEqual(env, None)
803 self.assertEqual(env, None)
801 self.assertEqual(os.environ['var'], 'val2 val3="val4')
804 self.assertEqual(os.environ['var'], 'val2 val3="val4')
802
805
803 def test_env_set_bad_input(self):
806 def test_env_set_bad_input(self):
804 self.assertRaises(UsageError, lambda: _ip.magic("set_env var"))
807 self.assertRaises(UsageError, lambda: _ip.run_line_magic("set_env", "var"))
805
808
806 def test_env_set_whitespace(self):
809 def test_env_set_whitespace(self):
807 self.assertRaises(UsageError, lambda: _ip.magic("env var A=B"))
810 self.assertRaises(UsageError, lambda: _ip.run_line_magic("env", "var A=B"))
808
811
809
812
810 class CellMagicTestCase(TestCase):
813 class CellMagicTestCase(TestCase):
@@ -1308,7 +1311,7 b' def test_ls_magic():'
1308 ip = get_ipython()
1311 ip = get_ipython()
1309 json_formatter = ip.display_formatter.formatters['application/json']
1312 json_formatter = ip.display_formatter.formatters['application/json']
1310 json_formatter.enabled = True
1313 json_formatter.enabled = True
1311 lsmagic = ip.magic('lsmagic')
1314 lsmagic = ip.run_line_magic("lsmagic", "")
1312 with warnings.catch_warnings(record=True) as w:
1315 with warnings.catch_warnings(record=True) as w:
1313 j = json_formatter(lsmagic)
1316 j = json_formatter(lsmagic)
1314 assert sorted(j) == ["cell", "line"]
1317 assert sorted(j) == ["cell", "line"]
@@ -1358,16 +1361,16 b' def test_logging_magic_not_quiet():'
1358
1361
1359
1362
1360 def test_time_no_var_expand():
1363 def test_time_no_var_expand():
1361 _ip.user_ns['a'] = 5
1364 _ip.user_ns["a"] = 5
1362 _ip.user_ns['b'] = []
1365 _ip.user_ns["b"] = []
1363 _ip.magic('time b.append("{a}")')
1366 _ip.run_line_magic("time", 'b.append("{a}")')
1364 assert _ip.user_ns['b'] == ['{a}']
1367 assert _ip.user_ns["b"] == ["{a}"]
1365
1368
1366
1369
1367 # this is slow, put at the end for local testing.
1370 # this is slow, put at the end for local testing.
1368 def test_timeit_arguments():
1371 def test_timeit_arguments():
1369 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
1372 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
1370 _ip.magic("timeit -n1 -r1 a=('#')")
1373 _ip.run_line_magic("timeit", "-n1 -r1 a=('#')")
1371
1374
1372
1375
1373 MINIMAL_LAZY_MAGIC = """
1376 MINIMAL_LAZY_MAGIC = """
@@ -1442,7 +1445,7 b' def test_run_module_from_import_hook():'
1442 sys.meta_path.insert(0, MyTempImporter())
1445 sys.meta_path.insert(0, MyTempImporter())
1443
1446
1444 with capture_output() as captured:
1447 with capture_output() as captured:
1445 _ip.magic("run -m my_tmp")
1448 _ip.run_line_magic("run", "-m my_tmp")
1446 _ip.run_cell("import my_tmp")
1449 _ip.run_cell("import my_tmp")
1447
1450
1448 output = "Loaded my_tmp\nI just ran a script\nLoaded my_tmp\n"
1451 output = "Loaded my_tmp\nI just ran a script\nLoaded my_tmp\n"
@@ -180,13 +180,13 b' class TestMagicRunPass(tt.TempFileMixin):'
180 _ip = get_ipython()
180 _ip = get_ipython()
181 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
181 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
182 # See below and ticket https://bugs.launchpad.net/bugs/366353
182 # See below and ticket https://bugs.launchpad.net/bugs/366353
183 _ip.magic('run %s' % self.fname)
183 _ip.run_line_magic("run", self.fname)
184
184
185 def run_tmpfile_p(self):
185 def run_tmpfile_p(self):
186 _ip = get_ipython()
186 _ip = get_ipython()
187 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
187 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
188 # See below and ticket https://bugs.launchpad.net/bugs/366353
188 # See below and ticket https://bugs.launchpad.net/bugs/366353
189 _ip.magic('run -p %s' % self.fname)
189 _ip.run_line_magic("run", "-p %s" % self.fname)
190
190
191 def test_builtins_id(self):
191 def test_builtins_id(self):
192 """Check that %run doesn't damage __builtins__ """
192 """Check that %run doesn't damage __builtins__ """
@@ -216,20 +216,20 b' class TestMagicRunPass(tt.TempFileMixin):'
216 def test_run_debug_twice(self):
216 def test_run_debug_twice(self):
217 # https://github.com/ipython/ipython/issues/10028
217 # https://github.com/ipython/ipython/issues/10028
218 _ip = get_ipython()
218 _ip = get_ipython()
219 with tt.fake_input(['c']):
219 with tt.fake_input(["c"]):
220 _ip.magic('run -d %s' % self.fname)
220 _ip.run_line_magic("run", "-d %s" % self.fname)
221 with tt.fake_input(['c']):
221 with tt.fake_input(["c"]):
222 _ip.magic('run -d %s' % self.fname)
222 _ip.run_line_magic("run", "-d %s" % self.fname)
223
223
224 def test_run_debug_twice_with_breakpoint(self):
224 def test_run_debug_twice_with_breakpoint(self):
225 """Make a valid python temp file."""
225 """Make a valid python temp file."""
226 _ip = get_ipython()
226 _ip = get_ipython()
227 with tt.fake_input(['b 2', 'c', 'c']):
227 with tt.fake_input(["b 2", "c", "c"]):
228 _ip.magic('run -d %s' % self.fname)
228 _ip.run_line_magic("run", "-d %s" % self.fname)
229
229
230 with tt.fake_input(['c']):
230 with tt.fake_input(["c"]):
231 with tt.AssertNotPrints('KeyError'):
231 with tt.AssertNotPrints("KeyError"):
232 _ip.magic('run -d %s' % self.fname)
232 _ip.run_line_magic("run", "-d %s" % self.fname)
233
233
234
234
235 class TestMagicRunSimple(tt.TempFileMixin):
235 class TestMagicRunSimple(tt.TempFileMixin):
@@ -239,7 +239,7 b' class TestMagicRunSimple(tt.TempFileMixin):'
239 src = ("class foo: pass\n"
239 src = ("class foo: pass\n"
240 "def f(): return foo()")
240 "def f(): return foo()")
241 self.mktmp(src)
241 self.mktmp(src)
242 _ip.magic("run %s" % self.fname)
242 _ip.run_line_magic("run", str(self.fname))
243 _ip.run_cell("t = isinstance(f(), foo)")
243 _ip.run_cell("t = isinstance(f(), foo)")
244 assert _ip.user_ns["t"] is True
244 assert _ip.user_ns["t"] is True
245
245
@@ -277,7 +277,7 b' class TestMagicRunSimple(tt.TempFileMixin):'
277 " break\n" % ("run " + empty.fname)
277 " break\n" % ("run " + empty.fname)
278 )
278 )
279 self.mktmp(src)
279 self.mktmp(src)
280 _ip.magic("run %s" % self.fname)
280 _ip.run_line_magic("run", str(self.fname))
281 _ip.run_cell("ip == get_ipython()")
281 _ip.run_cell("ip == get_ipython()")
282 assert _ip.user_ns["i"] == 4
282 assert _ip.user_ns["i"] == 4
283
283
@@ -288,8 +288,8 b' class TestMagicRunSimple(tt.TempFileMixin):'
288 with tt.TempFileMixin() as empty:
288 with tt.TempFileMixin() as empty:
289 empty.mktmp("")
289 empty.mktmp("")
290
290
291 _ip.magic("run %s" % self.fname)
291 _ip.run_line_magic("run", self.fname)
292 _ip.magic("run %s" % empty.fname)
292 _ip.run_line_magic("run", empty.fname)
293 assert _ip.user_ns["afunc"]() == 1
293 assert _ip.user_ns["afunc"]() == 1
294
294
295 def test_tclass(self):
295 def test_tclass(self):
@@ -323,23 +323,23 b' tclass.py: deleting object: C-third'
323 self.mktmp(src)
323 self.mktmp(src)
324 _ip.run_cell("zz = 23")
324 _ip.run_cell("zz = 23")
325 try:
325 try:
326 _ip.magic("run -i %s" % self.fname)
326 _ip.run_line_magic("run", "-i %s" % self.fname)
327 assert _ip.user_ns["yy"] == 23
327 assert _ip.user_ns["yy"] == 23
328 finally:
328 finally:
329 _ip.magic('reset -f')
329 _ip.run_line_magic("reset", "-f")
330
330
331 _ip.run_cell("zz = 23")
331 _ip.run_cell("zz = 23")
332 try:
332 try:
333 _ip.magic("run -i %s" % self.fname)
333 _ip.run_line_magic("run", "-i %s" % self.fname)
334 assert _ip.user_ns["yy"] == 23
334 assert _ip.user_ns["yy"] == 23
335 finally:
335 finally:
336 _ip.magic('reset -f')
336 _ip.run_line_magic("reset", "-f")
337
337
338 def test_unicode(self):
338 def test_unicode(self):
339 """Check that files in odd encodings are accepted."""
339 """Check that files in odd encodings are accepted."""
340 mydir = os.path.dirname(__file__)
340 mydir = os.path.dirname(__file__)
341 na = os.path.join(mydir, 'nonascii.py')
341 na = os.path.join(mydir, "nonascii.py")
342 _ip.magic('run "%s"' % na)
342 _ip.run_line_magic("run", "%r" % na)
343 assert _ip.user_ns["u"] == "ΠŽΡ‚β„–Π€"
343 assert _ip.user_ns["u"] == "ΠŽΡ‚β„–Π€"
344
344
345 def test_run_py_file_attribute(self):
345 def test_run_py_file_attribute(self):
@@ -347,9 +347,9 b' tclass.py: deleting object: C-third'
347 src = "t = __file__\n"
347 src = "t = __file__\n"
348 self.mktmp(src)
348 self.mktmp(src)
349 _missing = object()
349 _missing = object()
350 file1 = _ip.user_ns.get('__file__', _missing)
350 file1 = _ip.user_ns.get("__file__", _missing)
351 _ip.magic('run %s' % self.fname)
351 _ip.run_line_magic("run", self.fname)
352 file2 = _ip.user_ns.get('__file__', _missing)
352 file2 = _ip.user_ns.get("__file__", _missing)
353
353
354 # Check that __file__ was equal to the filename in the script's
354 # Check that __file__ was equal to the filename in the script's
355 # namespace.
355 # namespace.
@@ -363,9 +363,9 b' tclass.py: deleting object: C-third'
363 src = "t = __file__\n"
363 src = "t = __file__\n"
364 self.mktmp(src, ext='.ipy')
364 self.mktmp(src, ext='.ipy')
365 _missing = object()
365 _missing = object()
366 file1 = _ip.user_ns.get('__file__', _missing)
366 file1 = _ip.user_ns.get("__file__", _missing)
367 _ip.magic('run %s' % self.fname)
367 _ip.run_line_magic("run", self.fname)
368 file2 = _ip.user_ns.get('__file__', _missing)
368 file2 = _ip.user_ns.get("__file__", _missing)
369
369
370 # Check that __file__ was equal to the filename in the script's
370 # Check that __file__ was equal to the filename in the script's
371 # namespace.
371 # namespace.
@@ -378,18 +378,18 b' tclass.py: deleting object: C-third'
378 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
378 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
379 src = "pass"
379 src = "pass"
380 self.mktmp(src)
380 self.mktmp(src)
381 _ip.magic('run -t -N 1 %s' % self.fname)
381 _ip.run_line_magic("run", "-t -N 1 %s" % self.fname)
382 _ip.magic('run -t -N 10 %s' % self.fname)
382 _ip.run_line_magic("run", "-t -N 10 %s" % self.fname)
383
383
384 def test_ignore_sys_exit(self):
384 def test_ignore_sys_exit(self):
385 """Test the -e option to ignore sys.exit()"""
385 """Test the -e option to ignore sys.exit()"""
386 src = "import sys; sys.exit(1)"
386 src = "import sys; sys.exit(1)"
387 self.mktmp(src)
387 self.mktmp(src)
388 with tt.AssertPrints('SystemExit'):
388 with tt.AssertPrints("SystemExit"):
389 _ip.magic('run %s' % self.fname)
389 _ip.run_line_magic("run", self.fname)
390
390
391 with tt.AssertNotPrints('SystemExit'):
391 with tt.AssertNotPrints("SystemExit"):
392 _ip.magic('run -e %s' % self.fname)
392 _ip.run_line_magic("run", "-e %s" % self.fname)
393
393
394 def test_run_nb(self):
394 def test_run_nb(self):
395 """Test %run notebook.ipynb"""
395 """Test %run notebook.ipynb"""
@@ -404,7 +404,7 b' tclass.py: deleting object: C-third'
404 src = writes(nb, version=4)
404 src = writes(nb, version=4)
405 self.mktmp(src, ext='.ipynb')
405 self.mktmp(src, ext='.ipynb')
406
406
407 _ip.magic("run %s" % self.fname)
407 _ip.run_line_magic("run", self.fname)
408
408
409 assert _ip.user_ns["answer"] == 42
409 assert _ip.user_ns["answer"] == 42
410
410
@@ -478,12 +478,16 b' class TestMagicRunWithPackage(unittest.TestCase):'
478 sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
478 sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
479 self.tempdir.cleanup()
479 self.tempdir.cleanup()
480
480
481 def check_run_submodule(self, submodule, opts=''):
481 def check_run_submodule(self, submodule, opts=""):
482 _ip.user_ns.pop('x', None)
482 _ip.user_ns.pop("x", None)
483 _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts))
483 _ip.run_line_magic(
484 self.assertEqual(_ip.user_ns['x'], self.value,
484 "run", "{2} -m {0}.{1}".format(self.package, submodule, opts)
485 'Variable `x` is not loaded from module `{0}`.'
485 )
486 .format(submodule))
486 self.assertEqual(
487 _ip.user_ns["x"],
488 self.value,
489 "Variable `x` is not loaded from module `{0}`.".format(submodule),
490 )
487
491
488 def test_run_submodule_with_absolute_import(self):
492 def test_run_submodule_with_absolute_import(self):
489 self.check_run_submodule('absolute')
493 self.check_run_submodule('absolute')
@@ -533,17 +537,17 b' def test_run__name__():'
533 f.write("q = __name__")
537 f.write("q = __name__")
534
538
535 _ip.user_ns.pop("q", None)
539 _ip.user_ns.pop("q", None)
536 _ip.magic("run {}".format(path))
540 _ip.run_line_magic("run", "{}".format(path))
537 assert _ip.user_ns.pop("q") == "__main__"
541 assert _ip.user_ns.pop("q") == "__main__"
538
542
539 _ip.magic("run -n {}".format(path))
543 _ip.run_line_magic("run", "-n {}".format(path))
540 assert _ip.user_ns.pop("q") == "foo"
544 assert _ip.user_ns.pop("q") == "foo"
541
545
542 try:
546 try:
543 _ip.magic("run -i -n {}".format(path))
547 _ip.run_line_magic("run", "-i -n {}".format(path))
544 assert _ip.user_ns.pop("q") == "foo"
548 assert _ip.user_ns.pop("q") == "foo"
545 finally:
549 finally:
546 _ip.magic('reset -f')
550 _ip.run_line_magic("reset", "-f")
547
551
548
552
549 def test_run_tb():
553 def test_run_tb():
@@ -563,7 +567,7 b' def test_run_tb():'
563 )
567 )
564 )
568 )
565 with capture_output() as io:
569 with capture_output() as io:
566 _ip.magic('run {}'.format(path))
570 _ip.run_line_magic("run", "{}".format(path))
567 out = io.stdout
571 out = io.stdout
568 assert "execfile" not in out
572 assert "execfile" not in out
569 assert "RuntimeError" in out
573 assert "RuntimeError" in out
General Comments 0
You need to be logged in to leave comments. Login now