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