Show More
@@ -1,910 +1,910 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 | from __future__ import absolute_import |
|
6 | from __future__ import absolute_import | |
7 |
|
7 | |||
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 | # Imports |
|
9 | # Imports | |
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 |
|
11 | |||
12 | import io |
|
12 | import io | |
13 | import os |
|
13 | import os | |
14 | import sys |
|
14 | import sys | |
15 | from StringIO import StringIO |
|
15 | from StringIO import StringIO | |
16 | from unittest import TestCase |
|
16 | from unittest import TestCase | |
17 |
|
17 | |||
18 | try: |
|
18 | try: | |
19 | from importlib import invalidate_caches # Required from Python 3.3 |
|
19 | from importlib import invalidate_caches # Required from Python 3.3 | |
20 | except ImportError: |
|
20 | except ImportError: | |
21 | def invalidate_caches(): |
|
21 | def invalidate_caches(): | |
22 | pass |
|
22 | pass | |
23 |
|
23 | |||
24 | import nose.tools as nt |
|
24 | import nose.tools as nt | |
25 |
|
25 | |||
26 | from IPython.core import magic |
|
26 | from IPython.core import magic | |
27 | from IPython.core.magic import (Magics, magics_class, line_magic, |
|
27 | from IPython.core.magic import (Magics, magics_class, line_magic, | |
28 | cell_magic, line_cell_magic, |
|
28 | cell_magic, line_cell_magic, | |
29 | register_line_magic, register_cell_magic, |
|
29 | register_line_magic, register_cell_magic, | |
30 | register_line_cell_magic) |
|
30 | register_line_cell_magic) | |
31 | from IPython.core.magics import execution, script, code |
|
31 | from IPython.core.magics import execution, script, code | |
32 | from IPython.nbformat.v3.tests.nbexamples import nb0 |
|
32 | from IPython.nbformat.v3.tests.nbexamples import nb0 | |
33 | from IPython.nbformat import current |
|
33 | from IPython.nbformat import current | |
34 | from IPython.testing import decorators as dec |
|
34 | from IPython.testing import decorators as dec | |
35 | from IPython.testing import tools as tt |
|
35 | from IPython.testing import tools as tt | |
36 | from IPython.utils import py3compat |
|
36 | from IPython.utils import py3compat | |
37 | from IPython.utils.io import capture_output |
|
37 | from IPython.utils.io import capture_output | |
38 | from IPython.utils.tempdir import TemporaryDirectory |
|
38 | from IPython.utils.tempdir import TemporaryDirectory | |
39 | from IPython.utils.process import find_cmd |
|
39 | from IPython.utils.process import find_cmd | |
40 |
|
40 | |||
41 | #----------------------------------------------------------------------------- |
|
41 | #----------------------------------------------------------------------------- | |
42 | # Test functions begin |
|
42 | # Test functions begin | |
43 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
44 |
|
44 | |||
45 | @magic.magics_class |
|
45 | @magic.magics_class | |
46 | class DummyMagics(magic.Magics): pass |
|
46 | class DummyMagics(magic.Magics): pass | |
47 |
|
47 | |||
48 | def test_extract_code_ranges(): |
|
48 | def test_extract_code_ranges(): | |
49 | 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 :" | |
50 |
expected = [(0, 1), |
|
50 | expected = [(0, 1), | |
51 | (2, 3), |
|
51 | (2, 3), | |
52 | (4, 6), |
|
52 | (4, 6), | |
53 | (6, 9), |
|
53 | (6, 9), | |
54 |
(9, 14), |
|
54 | (9, 14), | |
55 | (16, None), |
|
55 | (16, None), | |
56 | (None, 9), |
|
56 | (None, 9), | |
57 | (9, None), |
|
57 | (9, None), | |
58 | (None, 13), |
|
58 | (None, 13), | |
59 | (None, None)] |
|
59 | (None, None)] | |
60 | actual = list(code.extract_code_ranges(instr)) |
|
60 | actual = list(code.extract_code_ranges(instr)) | |
61 | nt.assert_equal(actual, expected) |
|
61 | nt.assert_equal(actual, expected) | |
62 |
|
62 | |||
63 | def test_rehashx(): |
|
63 | def test_rehashx(): | |
64 | # clear up everything |
|
64 | # clear up everything | |
65 | _ip = get_ipython() |
|
65 | _ip = get_ipython() | |
66 | _ip.alias_manager.clear_aliases() |
|
66 | _ip.alias_manager.clear_aliases() | |
67 | del _ip.db['syscmdlist'] |
|
67 | del _ip.db['syscmdlist'] | |
68 |
|
68 | |||
69 | _ip.magic('rehashx') |
|
69 | _ip.magic('rehashx') | |
70 | # Practically ALL ipython development systems will have more than 10 aliases |
|
70 | # Practically ALL ipython development systems will have more than 10 aliases | |
71 |
|
71 | |||
72 | nt.assert_true(len(_ip.alias_manager.aliases) > 10) |
|
72 | nt.assert_true(len(_ip.alias_manager.aliases) > 10) | |
73 | for name, cmd in _ip.alias_manager.aliases: |
|
73 | for name, cmd in _ip.alias_manager.aliases: | |
74 | # we must strip dots from alias names |
|
74 | # we must strip dots from alias names | |
75 | nt.assert_not_in('.', name) |
|
75 | nt.assert_not_in('.', name) | |
76 |
|
76 | |||
77 | # rehashx must fill up syscmdlist |
|
77 | # rehashx must fill up syscmdlist | |
78 | scoms = _ip.db['syscmdlist'] |
|
78 | scoms = _ip.db['syscmdlist'] | |
79 | nt.assert_true(len(scoms) > 10) |
|
79 | nt.assert_true(len(scoms) > 10) | |
80 |
|
80 | |||
81 |
|
81 | |||
82 | def test_magic_parse_options(): |
|
82 | def test_magic_parse_options(): | |
83 | """Test that we don't mangle paths when parsing magic options.""" |
|
83 | """Test that we don't mangle paths when parsing magic options.""" | |
84 | ip = get_ipython() |
|
84 | ip = get_ipython() | |
85 | path = 'c:\\x' |
|
85 | path = 'c:\\x' | |
86 | m = DummyMagics(ip) |
|
86 | m = DummyMagics(ip) | |
87 | opts = m.parse_options('-f %s' % path,'f:')[0] |
|
87 | opts = m.parse_options('-f %s' % path,'f:')[0] | |
88 | # argv splitting is os-dependent |
|
88 | # argv splitting is os-dependent | |
89 | if os.name == 'posix': |
|
89 | if os.name == 'posix': | |
90 | expected = 'c:x' |
|
90 | expected = 'c:x' | |
91 | else: |
|
91 | else: | |
92 | expected = path |
|
92 | expected = path | |
93 | nt.assert_equal(opts['f'], expected) |
|
93 | nt.assert_equal(opts['f'], expected) | |
94 |
|
94 | |||
95 | def test_magic_parse_long_options(): |
|
95 | def test_magic_parse_long_options(): | |
96 | """Magic.parse_options can handle --foo=bar long options""" |
|
96 | """Magic.parse_options can handle --foo=bar long options""" | |
97 | ip = get_ipython() |
|
97 | ip = get_ipython() | |
98 | m = DummyMagics(ip) |
|
98 | m = DummyMagics(ip) | |
99 | opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=') |
|
99 | opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=') | |
100 | nt.assert_in('foo', opts) |
|
100 | nt.assert_in('foo', opts) | |
101 | nt.assert_in('bar', opts) |
|
101 | nt.assert_in('bar', opts) | |
102 | nt.assert_equal(opts['bar'], "bubble") |
|
102 | nt.assert_equal(opts['bar'], "bubble") | |
103 |
|
103 | |||
104 |
|
104 | |||
105 | @dec.skip_without('sqlite3') |
|
105 | @dec.skip_without('sqlite3') | |
106 | def doctest_hist_f(): |
|
106 | def doctest_hist_f(): | |
107 | """Test %hist -f with temporary filename. |
|
107 | """Test %hist -f with temporary filename. | |
108 |
|
108 | |||
109 | In [9]: import tempfile |
|
109 | In [9]: import tempfile | |
110 |
|
110 | |||
111 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') |
|
111 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') | |
112 |
|
112 | |||
113 | In [11]: %hist -nl -f $tfile 3 |
|
113 | In [11]: %hist -nl -f $tfile 3 | |
114 |
|
114 | |||
115 | In [13]: import os; os.unlink(tfile) |
|
115 | In [13]: import os; os.unlink(tfile) | |
116 | """ |
|
116 | """ | |
117 |
|
117 | |||
118 |
|
118 | |||
119 | @dec.skip_without('sqlite3') |
|
119 | @dec.skip_without('sqlite3') | |
120 | def doctest_hist_r(): |
|
120 | def doctest_hist_r(): | |
121 | """Test %hist -r |
|
121 | """Test %hist -r | |
122 |
|
122 | |||
123 | XXX - This test is not recording the output correctly. For some reason, in |
|
123 | XXX - This test is not recording the output correctly. For some reason, in | |
124 | testing mode the raw history isn't getting populated. No idea why. |
|
124 | testing mode the raw history isn't getting populated. No idea why. | |
125 | Disabling the output checking for now, though at least we do run it. |
|
125 | Disabling the output checking for now, though at least we do run it. | |
126 |
|
126 | |||
127 | In [1]: 'hist' in _ip.lsmagic() |
|
127 | In [1]: 'hist' in _ip.lsmagic() | |
128 | Out[1]: True |
|
128 | Out[1]: True | |
129 |
|
129 | |||
130 | In [2]: x=1 |
|
130 | In [2]: x=1 | |
131 |
|
131 | |||
132 | In [3]: %hist -rl 2 |
|
132 | In [3]: %hist -rl 2 | |
133 | x=1 # random |
|
133 | x=1 # random | |
134 | %hist -r 2 |
|
134 | %hist -r 2 | |
135 | """ |
|
135 | """ | |
136 |
|
136 | |||
137 |
|
137 | |||
138 | @dec.skip_without('sqlite3') |
|
138 | @dec.skip_without('sqlite3') | |
139 | def doctest_hist_op(): |
|
139 | def doctest_hist_op(): | |
140 | """Test %hist -op |
|
140 | """Test %hist -op | |
141 |
|
141 | |||
142 | In [1]: class b(float): |
|
142 | In [1]: class b(float): | |
143 | ...: pass |
|
143 | ...: pass | |
144 | ...: |
|
144 | ...: | |
145 |
|
145 | |||
146 | In [2]: class s(object): |
|
146 | In [2]: class s(object): | |
147 | ...: def __str__(self): |
|
147 | ...: def __str__(self): | |
148 | ...: return 's' |
|
148 | ...: return 's' | |
149 | ...: |
|
149 | ...: | |
150 |
|
150 | |||
151 | In [3]: |
|
151 | In [3]: | |
152 |
|
152 | |||
153 | In [4]: class r(b): |
|
153 | In [4]: class r(b): | |
154 | ...: def __repr__(self): |
|
154 | ...: def __repr__(self): | |
155 | ...: return 'r' |
|
155 | ...: return 'r' | |
156 | ...: |
|
156 | ...: | |
157 |
|
157 | |||
158 | In [5]: class sr(s,r): pass |
|
158 | In [5]: class sr(s,r): pass | |
159 | ...: |
|
159 | ...: | |
160 |
|
160 | |||
161 | In [6]: |
|
161 | In [6]: | |
162 |
|
162 | |||
163 | In [7]: bb=b() |
|
163 | In [7]: bb=b() | |
164 |
|
164 | |||
165 | In [8]: ss=s() |
|
165 | In [8]: ss=s() | |
166 |
|
166 | |||
167 | In [9]: rr=r() |
|
167 | In [9]: rr=r() | |
168 |
|
168 | |||
169 | In [10]: ssrr=sr() |
|
169 | In [10]: ssrr=sr() | |
170 |
|
170 | |||
171 | In [11]: 4.5 |
|
171 | In [11]: 4.5 | |
172 | Out[11]: 4.5 |
|
172 | Out[11]: 4.5 | |
173 |
|
173 | |||
174 | In [12]: str(ss) |
|
174 | In [12]: str(ss) | |
175 | Out[12]: 's' |
|
175 | Out[12]: 's' | |
176 |
|
176 | |||
177 | In [13]: |
|
177 | In [13]: | |
178 |
|
178 | |||
179 | In [14]: %hist -op |
|
179 | In [14]: %hist -op | |
180 | >>> class b: |
|
180 | >>> class b: | |
181 | ... pass |
|
181 | ... pass | |
182 | ... |
|
182 | ... | |
183 | >>> class s(b): |
|
183 | >>> class s(b): | |
184 | ... def __str__(self): |
|
184 | ... def __str__(self): | |
185 | ... return 's' |
|
185 | ... return 's' | |
186 | ... |
|
186 | ... | |
187 | >>> |
|
187 | >>> | |
188 | >>> class r(b): |
|
188 | >>> class r(b): | |
189 | ... def __repr__(self): |
|
189 | ... def __repr__(self): | |
190 | ... return 'r' |
|
190 | ... return 'r' | |
191 | ... |
|
191 | ... | |
192 | >>> class sr(s,r): pass |
|
192 | >>> class sr(s,r): pass | |
193 | >>> |
|
193 | >>> | |
194 | >>> bb=b() |
|
194 | >>> bb=b() | |
195 | >>> ss=s() |
|
195 | >>> ss=s() | |
196 | >>> rr=r() |
|
196 | >>> rr=r() | |
197 | >>> ssrr=sr() |
|
197 | >>> ssrr=sr() | |
198 | >>> 4.5 |
|
198 | >>> 4.5 | |
199 | 4.5 |
|
199 | 4.5 | |
200 | >>> str(ss) |
|
200 | >>> str(ss) | |
201 | 's' |
|
201 | 's' | |
202 | >>> |
|
202 | >>> | |
203 | """ |
|
203 | """ | |
204 |
|
204 | |||
205 |
|
205 | |||
206 | @dec.skip_without('sqlite3') |
|
206 | @dec.skip_without('sqlite3') | |
207 | def test_macro(): |
|
207 | def test_macro(): | |
208 | ip = get_ipython() |
|
208 | ip = get_ipython() | |
209 | ip.history_manager.reset() # Clear any existing history. |
|
209 | ip.history_manager.reset() # Clear any existing history. | |
210 | cmds = ["a=1", "def b():\n return a**2", "print(a,b())"] |
|
210 | cmds = ["a=1", "def b():\n return a**2", "print(a,b())"] | |
211 | for i, cmd in enumerate(cmds, start=1): |
|
211 | for i, cmd in enumerate(cmds, start=1): | |
212 | ip.history_manager.store_inputs(i, cmd) |
|
212 | ip.history_manager.store_inputs(i, cmd) | |
213 | ip.magic("macro test 1-3") |
|
213 | ip.magic("macro test 1-3") | |
214 | nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n") |
|
214 | nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n") | |
215 |
|
215 | |||
216 | # List macros |
|
216 | # List macros | |
217 | nt.assert_in("test", ip.magic("macro")) |
|
217 | nt.assert_in("test", ip.magic("macro")) | |
218 |
|
218 | |||
219 |
|
219 | |||
220 | @dec.skip_without('sqlite3') |
|
220 | @dec.skip_without('sqlite3') | |
221 | def test_macro_run(): |
|
221 | def test_macro_run(): | |
222 | """Test that we can run a multi-line macro successfully.""" |
|
222 | """Test that we can run a multi-line macro successfully.""" | |
223 | ip = get_ipython() |
|
223 | ip = get_ipython() | |
224 | ip.history_manager.reset() |
|
224 | ip.history_manager.reset() | |
225 | cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"), |
|
225 | cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"), | |
226 | "%macro test 2-3"] |
|
226 | "%macro test 2-3"] | |
227 | for cmd in cmds: |
|
227 | for cmd in cmds: | |
228 | ip.run_cell(cmd, store_history=True) |
|
228 | ip.run_cell(cmd, store_history=True) | |
229 | nt.assert_equal(ip.user_ns["test"].value, |
|
229 | nt.assert_equal(ip.user_ns["test"].value, | |
230 | py3compat.doctest_refactor_print("a+=1\nprint a\n")) |
|
230 | py3compat.doctest_refactor_print("a+=1\nprint a\n")) | |
231 | with tt.AssertPrints("12"): |
|
231 | with tt.AssertPrints("12"): | |
232 | ip.run_cell("test") |
|
232 | ip.run_cell("test") | |
233 | with tt.AssertPrints("13"): |
|
233 | with tt.AssertPrints("13"): | |
234 | ip.run_cell("test") |
|
234 | ip.run_cell("test") | |
235 |
|
235 | |||
236 |
|
236 | |||
237 | def test_magic_magic(): |
|
237 | def test_magic_magic(): | |
238 | """Test %magic""" |
|
238 | """Test %magic""" | |
239 | ip = get_ipython() |
|
239 | ip = get_ipython() | |
240 | with capture_output() as captured: |
|
240 | with capture_output() as captured: | |
241 | ip.magic("magic") |
|
241 | ip.magic("magic") | |
242 |
|
242 | |||
243 | stdout = captured.stdout |
|
243 | stdout = captured.stdout | |
244 | nt.assert_in('%magic', stdout) |
|
244 | nt.assert_in('%magic', stdout) | |
245 | nt.assert_in('IPython', stdout) |
|
245 | nt.assert_in('IPython', stdout) | |
246 | nt.assert_in('Available', stdout) |
|
246 | nt.assert_in('Available', stdout) | |
247 |
|
247 | |||
248 |
|
248 | |||
249 | @dec.skipif_not_numpy |
|
249 | @dec.skipif_not_numpy | |
250 | def test_numpy_reset_array_undec(): |
|
250 | def test_numpy_reset_array_undec(): | |
251 | "Test '%reset array' functionality" |
|
251 | "Test '%reset array' functionality" | |
252 | _ip.ex('import numpy as np') |
|
252 | _ip.ex('import numpy as np') | |
253 | _ip.ex('a = np.empty(2)') |
|
253 | _ip.ex('a = np.empty(2)') | |
254 | nt.assert_in('a', _ip.user_ns) |
|
254 | nt.assert_in('a', _ip.user_ns) | |
255 | _ip.magic('reset -f array') |
|
255 | _ip.magic('reset -f array') | |
256 | nt.assert_not_in('a', _ip.user_ns) |
|
256 | nt.assert_not_in('a', _ip.user_ns) | |
257 |
|
257 | |||
258 | def test_reset_out(): |
|
258 | def test_reset_out(): | |
259 | "Test '%reset out' magic" |
|
259 | "Test '%reset out' magic" | |
260 | _ip.run_cell("parrot = 'dead'", store_history=True) |
|
260 | _ip.run_cell("parrot = 'dead'", store_history=True) | |
261 | # test '%reset -f out', make an Out prompt |
|
261 | # test '%reset -f out', make an Out prompt | |
262 | _ip.run_cell("parrot", store_history=True) |
|
262 | _ip.run_cell("parrot", store_history=True) | |
263 | nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___']) |
|
263 | nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___']) | |
264 | _ip.magic('reset -f out') |
|
264 | _ip.magic('reset -f out') | |
265 | nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___']) |
|
265 | nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___']) | |
266 | nt.assert_equal(len(_ip.user_ns['Out']), 0) |
|
266 | nt.assert_equal(len(_ip.user_ns['Out']), 0) | |
267 |
|
267 | |||
268 | def test_reset_in(): |
|
268 | def test_reset_in(): | |
269 | "Test '%reset in' magic" |
|
269 | "Test '%reset in' magic" | |
270 | # test '%reset -f in' |
|
270 | # test '%reset -f in' | |
271 | _ip.run_cell("parrot", store_history=True) |
|
271 | _ip.run_cell("parrot", store_history=True) | |
272 | nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) |
|
272 | nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) | |
273 | _ip.magic('%reset -f in') |
|
273 | _ip.magic('%reset -f in') | |
274 | nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) |
|
274 | nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) | |
275 | nt.assert_equal(len(set(_ip.user_ns['In'])), 1) |
|
275 | nt.assert_equal(len(set(_ip.user_ns['In'])), 1) | |
276 |
|
276 | |||
277 | def test_reset_dhist(): |
|
277 | def test_reset_dhist(): | |
278 | "Test '%reset dhist' magic" |
|
278 | "Test '%reset dhist' magic" | |
279 | _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing |
|
279 | _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing | |
280 | _ip.magic('cd ' + os.path.dirname(nt.__file__)) |
|
280 | _ip.magic('cd ' + os.path.dirname(nt.__file__)) | |
281 | _ip.magic('cd -') |
|
281 | _ip.magic('cd -') | |
282 | nt.assert_true(len(_ip.user_ns['_dh']) > 0) |
|
282 | nt.assert_true(len(_ip.user_ns['_dh']) > 0) | |
283 | _ip.magic('reset -f dhist') |
|
283 | _ip.magic('reset -f dhist') | |
284 | nt.assert_equal(len(_ip.user_ns['_dh']), 0) |
|
284 | nt.assert_equal(len(_ip.user_ns['_dh']), 0) | |
285 | _ip.run_cell("_dh = [d for d in tmp]") #restore |
|
285 | _ip.run_cell("_dh = [d for d in tmp]") #restore | |
286 |
|
286 | |||
287 | def test_reset_in_length(): |
|
287 | def test_reset_in_length(): | |
288 | "Test that '%reset in' preserves In[] length" |
|
288 | "Test that '%reset in' preserves In[] length" | |
289 | _ip.run_cell("print 'foo'") |
|
289 | _ip.run_cell("print 'foo'") | |
290 | _ip.run_cell("reset -f in") |
|
290 | _ip.run_cell("reset -f in") | |
291 | nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1) |
|
291 | nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1) | |
292 |
|
292 | |||
293 | def test_tb_syntaxerror(): |
|
293 | def test_tb_syntaxerror(): | |
294 | """test %tb after a SyntaxError""" |
|
294 | """test %tb after a SyntaxError""" | |
295 | ip = get_ipython() |
|
295 | ip = get_ipython() | |
296 | ip.run_cell("for") |
|
296 | ip.run_cell("for") | |
297 |
|
297 | |||
298 | # trap and validate stdout |
|
298 | # trap and validate stdout | |
299 | save_stdout = sys.stdout |
|
299 | save_stdout = sys.stdout | |
300 | try: |
|
300 | try: | |
301 | sys.stdout = StringIO() |
|
301 | sys.stdout = StringIO() | |
302 | ip.run_cell("%tb") |
|
302 | ip.run_cell("%tb") | |
303 | out = sys.stdout.getvalue() |
|
303 | out = sys.stdout.getvalue() | |
304 | finally: |
|
304 | finally: | |
305 | sys.stdout = save_stdout |
|
305 | sys.stdout = save_stdout | |
306 | # trim output, and only check the last line |
|
306 | # trim output, and only check the last line | |
307 | last_line = out.rstrip().splitlines()[-1].strip() |
|
307 | last_line = out.rstrip().splitlines()[-1].strip() | |
308 | nt.assert_equal(last_line, "SyntaxError: invalid syntax") |
|
308 | nt.assert_equal(last_line, "SyntaxError: invalid syntax") | |
309 |
|
309 | |||
310 |
|
310 | |||
311 | def test_time(): |
|
311 | def test_time(): | |
312 | ip = get_ipython() |
|
312 | ip = get_ipython() | |
313 |
|
313 | |||
314 | with tt.AssertPrints("Wall time: "): |
|
314 | with tt.AssertPrints("Wall time: "): | |
315 | ip.run_cell("%time None") |
|
315 | ip.run_cell("%time None") | |
316 |
|
316 | |||
317 | ip.run_cell("def f(kmjy):\n" |
|
317 | ip.run_cell("def f(kmjy):\n" | |
318 | " %time print (2*kmjy)") |
|
318 | " %time print (2*kmjy)") | |
319 |
|
319 | |||
320 | with tt.AssertPrints("Wall time: "): |
|
320 | with tt.AssertPrints("Wall time: "): | |
321 | with tt.AssertPrints("hihi", suppress=False): |
|
321 | with tt.AssertPrints("hihi", suppress=False): | |
322 | ip.run_cell("f('hi')") |
|
322 | ip.run_cell("f('hi')") | |
323 |
|
323 | |||
324 |
|
324 | |||
325 | @dec.skip_win32 |
|
325 | @dec.skip_win32 | |
326 | def test_time2(): |
|
326 | def test_time2(): | |
327 | ip = get_ipython() |
|
327 | ip = get_ipython() | |
328 |
|
328 | |||
329 | with tt.AssertPrints("CPU times: user "): |
|
329 | with tt.AssertPrints("CPU times: user "): | |
330 | ip.run_cell("%time None") |
|
330 | ip.run_cell("%time None") | |
331 |
|
331 | |||
332 | def test_time3(): |
|
332 | def test_time3(): | |
333 | """Erroneous magic function calls, issue gh-3334""" |
|
333 | """Erroneous magic function calls, issue gh-3334""" | |
334 | ip = get_ipython() |
|
334 | ip = get_ipython() | |
335 | ip.user_ns.pop('run', None) |
|
335 | ip.user_ns.pop('run', None) | |
336 |
|
336 | |||
337 | with tt.AssertNotPrints("not found", channel='stderr'): |
|
337 | with tt.AssertNotPrints("not found", channel='stderr'): | |
338 | ip.run_cell("%%time\n" |
|
338 | ip.run_cell("%%time\n" | |
339 | "run = 0\n" |
|
339 | "run = 0\n" | |
340 | "run += 1") |
|
340 | "run += 1") | |
341 |
|
341 | |||
342 | def test_doctest_mode(): |
|
342 | def test_doctest_mode(): | |
343 | "Toggle doctest_mode twice, it should be a no-op and run without error" |
|
343 | "Toggle doctest_mode twice, it should be a no-op and run without error" | |
344 | _ip.magic('doctest_mode') |
|
344 | _ip.magic('doctest_mode') | |
345 | _ip.magic('doctest_mode') |
|
345 | _ip.magic('doctest_mode') | |
346 |
|
346 | |||
347 |
|
347 | |||
348 | def test_parse_options(): |
|
348 | def test_parse_options(): | |
349 | """Tests for basic options parsing in magics.""" |
|
349 | """Tests for basic options parsing in magics.""" | |
350 | # These are only the most minimal of tests, more should be added later. At |
|
350 | # These are only the most minimal of tests, more should be added later. At | |
351 | # the very least we check that basic text/unicode calls work OK. |
|
351 | # the very least we check that basic text/unicode calls work OK. | |
352 | m = DummyMagics(_ip) |
|
352 | m = DummyMagics(_ip) | |
353 | nt.assert_equal(m.parse_options('foo', '')[1], 'foo') |
|
353 | nt.assert_equal(m.parse_options('foo', '')[1], 'foo') | |
354 | nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo') |
|
354 | nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo') | |
355 |
|
355 | |||
356 |
|
356 | |||
357 | def test_dirops(): |
|
357 | def test_dirops(): | |
358 | """Test various directory handling operations.""" |
|
358 | """Test various directory handling operations.""" | |
359 | # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/') |
|
359 | # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/') | |
360 | curpath = os.getcwdu |
|
360 | curpath = os.getcwdu | |
361 | startdir = os.getcwdu() |
|
361 | startdir = os.getcwdu() | |
362 | ipdir = os.path.realpath(_ip.ipython_dir) |
|
362 | ipdir = os.path.realpath(_ip.ipython_dir) | |
363 | try: |
|
363 | try: | |
364 | _ip.magic('cd "%s"' % ipdir) |
|
364 | _ip.magic('cd "%s"' % ipdir) | |
365 | nt.assert_equal(curpath(), ipdir) |
|
365 | nt.assert_equal(curpath(), ipdir) | |
366 | _ip.magic('cd -') |
|
366 | _ip.magic('cd -') | |
367 | nt.assert_equal(curpath(), startdir) |
|
367 | nt.assert_equal(curpath(), startdir) | |
368 | _ip.magic('pushd "%s"' % ipdir) |
|
368 | _ip.magic('pushd "%s"' % ipdir) | |
369 | nt.assert_equal(curpath(), ipdir) |
|
369 | nt.assert_equal(curpath(), ipdir) | |
370 | _ip.magic('popd') |
|
370 | _ip.magic('popd') | |
371 | nt.assert_equal(curpath(), startdir) |
|
371 | nt.assert_equal(curpath(), startdir) | |
372 | finally: |
|
372 | finally: | |
373 | os.chdir(startdir) |
|
373 | os.chdir(startdir) | |
374 |
|
374 | |||
375 |
|
375 | |||
376 | def test_xmode(): |
|
376 | def test_xmode(): | |
377 | # Calling xmode three times should be a no-op |
|
377 | # Calling xmode three times should be a no-op | |
378 | xmode = _ip.InteractiveTB.mode |
|
378 | xmode = _ip.InteractiveTB.mode | |
379 | for i in range(3): |
|
379 | for i in range(3): | |
380 | _ip.magic("xmode") |
|
380 | _ip.magic("xmode") | |
381 | nt.assert_equal(_ip.InteractiveTB.mode, xmode) |
|
381 | nt.assert_equal(_ip.InteractiveTB.mode, xmode) | |
382 |
|
382 | |||
383 | def test_reset_hard(): |
|
383 | def test_reset_hard(): | |
384 | monitor = [] |
|
384 | monitor = [] | |
385 | class A(object): |
|
385 | class A(object): | |
386 | def __del__(self): |
|
386 | def __del__(self): | |
387 | monitor.append(1) |
|
387 | monitor.append(1) | |
388 | def __repr__(self): |
|
388 | def __repr__(self): | |
389 | return "<A instance>" |
|
389 | return "<A instance>" | |
390 |
|
390 | |||
391 | _ip.user_ns["a"] = A() |
|
391 | _ip.user_ns["a"] = A() | |
392 | _ip.run_cell("a") |
|
392 | _ip.run_cell("a") | |
393 |
|
393 | |||
394 | nt.assert_equal(monitor, []) |
|
394 | nt.assert_equal(monitor, []) | |
395 | _ip.magic("reset -f") |
|
395 | _ip.magic("reset -f") | |
396 | nt.assert_equal(monitor, [1]) |
|
396 | nt.assert_equal(monitor, [1]) | |
397 |
|
397 | |||
398 | class TestXdel(tt.TempFileMixin): |
|
398 | class TestXdel(tt.TempFileMixin): | |
399 | def test_xdel(self): |
|
399 | def test_xdel(self): | |
400 | """Test that references from %run are cleared by xdel.""" |
|
400 | """Test that references from %run are cleared by xdel.""" | |
401 | src = ("class A(object):\n" |
|
401 | src = ("class A(object):\n" | |
402 | " monitor = []\n" |
|
402 | " monitor = []\n" | |
403 | " def __del__(self):\n" |
|
403 | " def __del__(self):\n" | |
404 | " self.monitor.append(1)\n" |
|
404 | " self.monitor.append(1)\n" | |
405 | "a = A()\n") |
|
405 | "a = A()\n") | |
406 | self.mktmp(src) |
|
406 | self.mktmp(src) | |
407 | # %run creates some hidden references... |
|
407 | # %run creates some hidden references... | |
408 | _ip.magic("run %s" % self.fname) |
|
408 | _ip.magic("run %s" % self.fname) | |
409 | # ... as does the displayhook. |
|
409 | # ... as does the displayhook. | |
410 | _ip.run_cell("a") |
|
410 | _ip.run_cell("a") | |
411 |
|
411 | |||
412 | monitor = _ip.user_ns["A"].monitor |
|
412 | monitor = _ip.user_ns["A"].monitor | |
413 | nt.assert_equal(monitor, []) |
|
413 | nt.assert_equal(monitor, []) | |
414 |
|
414 | |||
415 | _ip.magic("xdel a") |
|
415 | _ip.magic("xdel a") | |
416 |
|
416 | |||
417 | # Check that a's __del__ method has been called. |
|
417 | # Check that a's __del__ method has been called. | |
418 | nt.assert_equal(monitor, [1]) |
|
418 | nt.assert_equal(monitor, [1]) | |
419 |
|
419 | |||
420 | def doctest_who(): |
|
420 | def doctest_who(): | |
421 | """doctest for %who |
|
421 | """doctest for %who | |
422 |
|
422 | |||
423 | In [1]: %reset -f |
|
423 | In [1]: %reset -f | |
424 |
|
424 | |||
425 | In [2]: alpha = 123 |
|
425 | In [2]: alpha = 123 | |
426 |
|
426 | |||
427 | In [3]: beta = 'beta' |
|
427 | In [3]: beta = 'beta' | |
428 |
|
428 | |||
429 | In [4]: %who int |
|
429 | In [4]: %who int | |
430 | alpha |
|
430 | alpha | |
431 |
|
431 | |||
432 | In [5]: %who str |
|
432 | In [5]: %who str | |
433 | beta |
|
433 | beta | |
434 |
|
434 | |||
435 | In [6]: %whos |
|
435 | In [6]: %whos | |
436 | Variable Type Data/Info |
|
436 | Variable Type Data/Info | |
437 | ---------------------------- |
|
437 | ---------------------------- | |
438 | alpha int 123 |
|
438 | alpha int 123 | |
439 | beta str beta |
|
439 | beta str beta | |
440 |
|
440 | |||
441 | In [7]: %who_ls |
|
441 | In [7]: %who_ls | |
442 | Out[7]: ['alpha', 'beta'] |
|
442 | Out[7]: ['alpha', 'beta'] | |
443 | """ |
|
443 | """ | |
444 |
|
444 | |||
445 | def test_whos(): |
|
445 | def test_whos(): | |
446 | """Check that whos is protected against objects where repr() fails.""" |
|
446 | """Check that whos is protected against objects where repr() fails.""" | |
447 | class A(object): |
|
447 | class A(object): | |
448 | def __repr__(self): |
|
448 | def __repr__(self): | |
449 | raise Exception() |
|
449 | raise Exception() | |
450 | _ip.user_ns['a'] = A() |
|
450 | _ip.user_ns['a'] = A() | |
451 | _ip.magic("whos") |
|
451 | _ip.magic("whos") | |
452 |
|
452 | |||
453 | @py3compat.u_format |
|
453 | @py3compat.u_format | |
454 | def doctest_precision(): |
|
454 | def doctest_precision(): | |
455 | """doctest for %precision |
|
455 | """doctest for %precision | |
456 |
|
456 | |||
457 | In [1]: f = get_ipython().display_formatter.formatters['text/plain'] |
|
457 | In [1]: f = get_ipython().display_formatter.formatters['text/plain'] | |
458 |
|
458 | |||
459 | In [2]: %precision 5 |
|
459 | In [2]: %precision 5 | |
460 | Out[2]: {u}'%.5f' |
|
460 | Out[2]: {u}'%.5f' | |
461 |
|
461 | |||
462 | In [3]: f.float_format |
|
462 | In [3]: f.float_format | |
463 | Out[3]: {u}'%.5f' |
|
463 | Out[3]: {u}'%.5f' | |
464 |
|
464 | |||
465 | In [4]: %precision %e |
|
465 | In [4]: %precision %e | |
466 | Out[4]: {u}'%e' |
|
466 | Out[4]: {u}'%e' | |
467 |
|
467 | |||
468 | In [5]: f(3.1415927) |
|
468 | In [5]: f(3.1415927) | |
469 | Out[5]: {u}'3.141593e+00' |
|
469 | Out[5]: {u}'3.141593e+00' | |
470 | """ |
|
470 | """ | |
471 |
|
471 | |||
472 | def test_psearch(): |
|
472 | def test_psearch(): | |
473 | with tt.AssertPrints("dict.fromkeys"): |
|
473 | with tt.AssertPrints("dict.fromkeys"): | |
474 | _ip.run_cell("dict.fr*?") |
|
474 | _ip.run_cell("dict.fr*?") | |
475 |
|
475 | |||
476 | def test_timeit_shlex(): |
|
476 | def test_timeit_shlex(): | |
477 | """test shlex issues with timeit (#1109)""" |
|
477 | """test shlex issues with timeit (#1109)""" | |
478 | _ip.ex("def f(*a,**kw): pass") |
|
478 | _ip.ex("def f(*a,**kw): pass") | |
479 | _ip.magic('timeit -n1 "this is a bug".count(" ")') |
|
479 | _ip.magic('timeit -n1 "this is a bug".count(" ")') | |
480 | _ip.magic('timeit -r1 -n1 f(" ", 1)') |
|
480 | _ip.magic('timeit -r1 -n1 f(" ", 1)') | |
481 | _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")') |
|
481 | _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")') | |
482 | _ip.magic('timeit -r1 -n1 ("a " + "b")') |
|
482 | _ip.magic('timeit -r1 -n1 ("a " + "b")') | |
483 | _ip.magic('timeit -r1 -n1 f("a " + "b")') |
|
483 | _ip.magic('timeit -r1 -n1 f("a " + "b")') | |
484 | _ip.magic('timeit -r1 -n1 f("a " + "b ")') |
|
484 | _ip.magic('timeit -r1 -n1 f("a " + "b ")') | |
485 |
|
485 | |||
486 |
|
486 | |||
487 | def test_timeit_arguments(): |
|
487 | def test_timeit_arguments(): | |
488 | "Test valid timeit arguments, should not cause SyntaxError (GH #1269)" |
|
488 | "Test valid timeit arguments, should not cause SyntaxError (GH #1269)" | |
489 | _ip.magic("timeit ('#')") |
|
489 | _ip.magic("timeit ('#')") | |
490 |
|
490 | |||
491 |
|
491 | |||
492 | def test_timeit_special_syntax(): |
|
492 | def test_timeit_special_syntax(): | |
493 | "Test %%timeit with IPython special syntax" |
|
493 | "Test %%timeit with IPython special syntax" | |
494 | @register_line_magic |
|
494 | @register_line_magic | |
495 | def lmagic(line): |
|
495 | def lmagic(line): | |
496 | ip = get_ipython() |
|
496 | ip = get_ipython() | |
497 | ip.user_ns['lmagic_out'] = line |
|
497 | ip.user_ns['lmagic_out'] = line | |
498 |
|
498 | |||
499 | # line mode test |
|
499 | # line mode test | |
500 | _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line') |
|
500 | _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line') | |
501 | nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line') |
|
501 | nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line') | |
502 | # cell mode test |
|
502 | # cell mode test | |
503 | _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2') |
|
503 | _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2') | |
504 | nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2') |
|
504 | nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2') | |
505 |
|
505 | |||
506 | def test_timeit_return(): |
|
506 | def test_timeit_return(): | |
507 | """ |
|
507 | """ | |
508 | test wether timeit -o return object |
|
508 | test wether timeit -o return object | |
509 | """ |
|
509 | """ | |
510 |
|
510 | |||
511 | res = _ip.run_line_magic('timeit','-n10 -r10 -o 1') |
|
511 | res = _ip.run_line_magic('timeit','-n10 -r10 -o 1') | |
512 | assert(res is not None) |
|
512 | assert(res is not None) | |
513 |
|
513 | |||
514 | def test_timeit_quiet(): |
|
514 | def test_timeit_quiet(): | |
515 | """ |
|
515 | """ | |
516 | test quiet option of timeit magic |
|
516 | test quiet option of timeit magic | |
517 | """ |
|
517 | """ | |
518 | with tt.AssertNotPrints("loops"): |
|
518 | with tt.AssertNotPrints("loops"): | |
519 | _ip.run_cell("%timeit -n1 -r1 -q 1") |
|
519 | _ip.run_cell("%timeit -n1 -r1 -q 1") | |
520 |
|
520 | |||
521 | @dec.skipif(execution.profile is None) |
|
521 | @dec.skipif(execution.profile is None) | |
522 | def test_prun_special_syntax(): |
|
522 | def test_prun_special_syntax(): | |
523 | "Test %%prun with IPython special syntax" |
|
523 | "Test %%prun with IPython special syntax" | |
524 | @register_line_magic |
|
524 | @register_line_magic | |
525 | def lmagic(line): |
|
525 | def lmagic(line): | |
526 | ip = get_ipython() |
|
526 | ip = get_ipython() | |
527 | ip.user_ns['lmagic_out'] = line |
|
527 | ip.user_ns['lmagic_out'] = line | |
528 |
|
528 | |||
529 | # line mode test |
|
529 | # line mode test | |
530 | _ip.run_line_magic('prun', '-q %lmagic my line') |
|
530 | _ip.run_line_magic('prun', '-q %lmagic my line') | |
531 | nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line') |
|
531 | nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line') | |
532 | # cell mode test |
|
532 | # cell mode test | |
533 | _ip.run_cell_magic('prun', '-q', '%lmagic my line2') |
|
533 | _ip.run_cell_magic('prun', '-q', '%lmagic my line2') | |
534 | nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2') |
|
534 | nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2') | |
535 |
|
535 | |||
536 | @dec.skipif(execution.profile is None) |
|
536 | @dec.skipif(execution.profile is None) | |
537 | def test_prun_quotes(): |
|
537 | def test_prun_quotes(): | |
538 | "Test that prun does not clobber string escapes (GH #1302)" |
|
538 | "Test that prun does not clobber string escapes (GH #1302)" | |
539 | _ip.magic(r"prun -q x = '\t'") |
|
539 | _ip.magic(r"prun -q x = '\t'") | |
540 | nt.assert_equal(_ip.user_ns['x'], '\t') |
|
540 | nt.assert_equal(_ip.user_ns['x'], '\t') | |
541 |
|
541 | |||
542 | def test_extension(): |
|
542 | def test_extension(): | |
543 | tmpdir = TemporaryDirectory() |
|
543 | tmpdir = TemporaryDirectory() | |
544 | orig_ipython_dir = _ip.ipython_dir |
|
544 | orig_ipython_dir = _ip.ipython_dir | |
545 | try: |
|
545 | try: | |
546 | _ip.ipython_dir = tmpdir.name |
|
546 | _ip.ipython_dir = tmpdir.name | |
547 | nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension") |
|
547 | nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension") | |
548 | url = os.path.join(os.path.dirname(__file__), "daft_extension.py") |
|
548 | url = os.path.join(os.path.dirname(__file__), "daft_extension.py") | |
549 | _ip.magic("install_ext %s" % url) |
|
549 | _ip.magic("install_ext %s" % url) | |
550 | _ip.user_ns.pop('arq', None) |
|
550 | _ip.user_ns.pop('arq', None) | |
551 | invalidate_caches() # Clear import caches |
|
551 | invalidate_caches() # Clear import caches | |
552 | _ip.magic("load_ext daft_extension") |
|
552 | _ip.magic("load_ext daft_extension") | |
553 | nt.assert_equal(_ip.user_ns['arq'], 185) |
|
553 | nt.assert_equal(_ip.user_ns['arq'], 185) | |
554 | _ip.magic("unload_ext daft_extension") |
|
554 | _ip.magic("unload_ext daft_extension") | |
555 | assert 'arq' not in _ip.user_ns |
|
555 | assert 'arq' not in _ip.user_ns | |
556 | finally: |
|
556 | finally: | |
557 | _ip.ipython_dir = orig_ipython_dir |
|
557 | _ip.ipython_dir = orig_ipython_dir | |
558 | tmpdir.cleanup() |
|
558 | tmpdir.cleanup() | |
559 |
|
559 | |||
560 | def test_notebook_export_json(): |
|
560 | def test_notebook_export_json(): | |
561 | with TemporaryDirectory() as td: |
|
561 | with TemporaryDirectory() as td: | |
562 | outfile = os.path.join(td, "nb.ipynb") |
|
562 | outfile = os.path.join(td, "nb.ipynb") | |
563 | _ip.ex(py3compat.u_format(u"u = {u}'héllo'")) |
|
563 | _ip.ex(py3compat.u_format(u"u = {u}'héllo'")) | |
564 | _ip.magic("notebook -e %s" % outfile) |
|
564 | _ip.magic("notebook -e %s" % outfile) | |
565 |
|
565 | |||
566 | def test_notebook_export_py(): |
|
566 | def test_notebook_export_py(): | |
567 | with TemporaryDirectory() as td: |
|
567 | with TemporaryDirectory() as td: | |
568 | outfile = os.path.join(td, "nb.py") |
|
568 | outfile = os.path.join(td, "nb.py") | |
569 | _ip.ex(py3compat.u_format(u"u = {u}'héllo'")) |
|
569 | _ip.ex(py3compat.u_format(u"u = {u}'héllo'")) | |
570 | _ip.magic("notebook -e %s" % outfile) |
|
570 | _ip.magic("notebook -e %s" % outfile) | |
571 |
|
571 | |||
572 | def test_notebook_reformat_py(): |
|
572 | def test_notebook_reformat_py(): | |
573 | with TemporaryDirectory() as td: |
|
573 | with TemporaryDirectory() as td: | |
574 | infile = os.path.join(td, "nb.ipynb") |
|
574 | infile = os.path.join(td, "nb.ipynb") | |
575 | with io.open(infile, 'w', encoding='utf-8') as f: |
|
575 | with io.open(infile, 'w', encoding='utf-8') as f: | |
576 | current.write(nb0, f, 'json') |
|
576 | current.write(nb0, f, 'json') | |
577 |
|
577 | |||
578 | _ip.ex(py3compat.u_format(u"u = {u}'héllo'")) |
|
578 | _ip.ex(py3compat.u_format(u"u = {u}'héllo'")) | |
579 | _ip.magic("notebook -f py %s" % infile) |
|
579 | _ip.magic("notebook -f py %s" % infile) | |
580 |
|
580 | |||
581 | def test_notebook_reformat_json(): |
|
581 | def test_notebook_reformat_json(): | |
582 | with TemporaryDirectory() as td: |
|
582 | with TemporaryDirectory() as td: | |
583 | infile = os.path.join(td, "nb.py") |
|
583 | infile = os.path.join(td, "nb.py") | |
584 | with io.open(infile, 'w', encoding='utf-8') as f: |
|
584 | with io.open(infile, 'w', encoding='utf-8') as f: | |
585 | current.write(nb0, f, 'py') |
|
585 | current.write(nb0, f, 'py') | |
586 |
|
586 | |||
587 | _ip.ex(py3compat.u_format(u"u = {u}'héllo'")) |
|
587 | _ip.ex(py3compat.u_format(u"u = {u}'héllo'")) | |
588 | _ip.magic("notebook -f ipynb %s" % infile) |
|
588 | _ip.magic("notebook -f ipynb %s" % infile) | |
589 | _ip.magic("notebook -f json %s" % infile) |
|
589 | _ip.magic("notebook -f json %s" % infile) | |
590 |
|
590 | |||
591 | def test_env(): |
|
591 | def test_env(): | |
592 | env = _ip.magic("env") |
|
592 | env = _ip.magic("env") | |
593 | assert isinstance(env, dict), type(env) |
|
593 | assert isinstance(env, dict), type(env) | |
594 |
|
594 | |||
595 |
|
595 | |||
596 | class CellMagicTestCase(TestCase): |
|
596 | class CellMagicTestCase(TestCase): | |
597 |
|
597 | |||
598 | def check_ident(self, magic): |
|
598 | def check_ident(self, magic): | |
599 | # Manually called, we get the result |
|
599 | # Manually called, we get the result | |
600 | out = _ip.run_cell_magic(magic, 'a', 'b') |
|
600 | out = _ip.run_cell_magic(magic, 'a', 'b') | |
601 | nt.assert_equal(out, ('a','b')) |
|
601 | nt.assert_equal(out, ('a','b')) | |
602 | # Via run_cell, it goes into the user's namespace via displayhook |
|
602 | # Via run_cell, it goes into the user's namespace via displayhook | |
603 | _ip.run_cell('%%' + magic +' c\nd') |
|
603 | _ip.run_cell('%%' + magic +' c\nd') | |
604 | nt.assert_equal(_ip.user_ns['_'], ('c','d')) |
|
604 | nt.assert_equal(_ip.user_ns['_'], ('c','d')) | |
605 |
|
605 | |||
606 | def test_cell_magic_func_deco(self): |
|
606 | def test_cell_magic_func_deco(self): | |
607 | "Cell magic using simple decorator" |
|
607 | "Cell magic using simple decorator" | |
608 | @register_cell_magic |
|
608 | @register_cell_magic | |
609 | def cellm(line, cell): |
|
609 | def cellm(line, cell): | |
610 | return line, cell |
|
610 | return line, cell | |
611 |
|
611 | |||
612 | self.check_ident('cellm') |
|
612 | self.check_ident('cellm') | |
613 |
|
613 | |||
614 | def test_cell_magic_reg(self): |
|
614 | def test_cell_magic_reg(self): | |
615 | "Cell magic manually registered" |
|
615 | "Cell magic manually registered" | |
616 | def cellm(line, cell): |
|
616 | def cellm(line, cell): | |
617 | return line, cell |
|
617 | return line, cell | |
618 |
|
618 | |||
619 | _ip.register_magic_function(cellm, 'cell', 'cellm2') |
|
619 | _ip.register_magic_function(cellm, 'cell', 'cellm2') | |
620 | self.check_ident('cellm2') |
|
620 | self.check_ident('cellm2') | |
621 |
|
621 | |||
622 | def test_cell_magic_class(self): |
|
622 | def test_cell_magic_class(self): | |
623 | "Cell magics declared via a class" |
|
623 | "Cell magics declared via a class" | |
624 | @magics_class |
|
624 | @magics_class | |
625 | class MyMagics(Magics): |
|
625 | class MyMagics(Magics): | |
626 |
|
626 | |||
627 | @cell_magic |
|
627 | @cell_magic | |
628 | def cellm3(self, line, cell): |
|
628 | def cellm3(self, line, cell): | |
629 | return line, cell |
|
629 | return line, cell | |
630 |
|
630 | |||
631 | _ip.register_magics(MyMagics) |
|
631 | _ip.register_magics(MyMagics) | |
632 | self.check_ident('cellm3') |
|
632 | self.check_ident('cellm3') | |
633 |
|
633 | |||
634 | def test_cell_magic_class2(self): |
|
634 | def test_cell_magic_class2(self): | |
635 | "Cell magics declared via a class, #2" |
|
635 | "Cell magics declared via a class, #2" | |
636 | @magics_class |
|
636 | @magics_class | |
637 | class MyMagics2(Magics): |
|
637 | class MyMagics2(Magics): | |
638 |
|
638 | |||
639 | @cell_magic('cellm4') |
|
639 | @cell_magic('cellm4') | |
640 | def cellm33(self, line, cell): |
|
640 | def cellm33(self, line, cell): | |
641 | return line, cell |
|
641 | return line, cell | |
642 |
|
642 | |||
643 | _ip.register_magics(MyMagics2) |
|
643 | _ip.register_magics(MyMagics2) | |
644 | self.check_ident('cellm4') |
|
644 | self.check_ident('cellm4') | |
645 | # Check that nothing is registered as 'cellm33' |
|
645 | # Check that nothing is registered as 'cellm33' | |
646 | c33 = _ip.find_cell_magic('cellm33') |
|
646 | c33 = _ip.find_cell_magic('cellm33') | |
647 | nt.assert_equal(c33, None) |
|
647 | nt.assert_equal(c33, None) | |
648 |
|
648 | |||
649 | def test_file(): |
|
649 | def test_file(): | |
650 | """Basic %%file""" |
|
650 | """Basic %%file""" | |
651 | ip = get_ipython() |
|
651 | ip = get_ipython() | |
652 | with TemporaryDirectory() as td: |
|
652 | with TemporaryDirectory() as td: | |
653 | fname = os.path.join(td, 'file1') |
|
653 | fname = os.path.join(td, 'file1') | |
654 | ip.run_cell_magic("file", fname, u'\n'.join([ |
|
654 | ip.run_cell_magic("file", fname, u'\n'.join([ | |
655 | 'line1', |
|
655 | 'line1', | |
656 | 'line2', |
|
656 | 'line2', | |
657 | ])) |
|
657 | ])) | |
658 | with open(fname) as f: |
|
658 | with open(fname) as f: | |
659 | s = f.read() |
|
659 | s = f.read() | |
660 | nt.assert_in('line1\n', s) |
|
660 | nt.assert_in('line1\n', s) | |
661 | nt.assert_in('line2', s) |
|
661 | nt.assert_in('line2', s) | |
662 |
|
662 | |||
663 | def test_file_var_expand(): |
|
663 | def test_file_var_expand(): | |
664 | """%%file $filename""" |
|
664 | """%%file $filename""" | |
665 | ip = get_ipython() |
|
665 | ip = get_ipython() | |
666 | with TemporaryDirectory() as td: |
|
666 | with TemporaryDirectory() as td: | |
667 | fname = os.path.join(td, 'file1') |
|
667 | fname = os.path.join(td, 'file1') | |
668 | ip.user_ns['filename'] = fname |
|
668 | ip.user_ns['filename'] = fname | |
669 | ip.run_cell_magic("file", '$filename', u'\n'.join([ |
|
669 | ip.run_cell_magic("file", '$filename', u'\n'.join([ | |
670 | 'line1', |
|
670 | 'line1', | |
671 | 'line2', |
|
671 | 'line2', | |
672 | ])) |
|
672 | ])) | |
673 | with open(fname) as f: |
|
673 | with open(fname) as f: | |
674 | s = f.read() |
|
674 | s = f.read() | |
675 | nt.assert_in('line1\n', s) |
|
675 | nt.assert_in('line1\n', s) | |
676 | nt.assert_in('line2', s) |
|
676 | nt.assert_in('line2', s) | |
677 |
|
677 | |||
678 | def test_file_unicode(): |
|
678 | def test_file_unicode(): | |
679 | """%%file with unicode cell""" |
|
679 | """%%file with unicode cell""" | |
680 | ip = get_ipython() |
|
680 | ip = get_ipython() | |
681 | with TemporaryDirectory() as td: |
|
681 | with TemporaryDirectory() as td: | |
682 | fname = os.path.join(td, 'file1') |
|
682 | fname = os.path.join(td, 'file1') | |
683 | ip.run_cell_magic("file", fname, u'\n'.join([ |
|
683 | ip.run_cell_magic("file", fname, u'\n'.join([ | |
684 | u'liné1', |
|
684 | u'liné1', | |
685 | u'liné2', |
|
685 | u'liné2', | |
686 | ])) |
|
686 | ])) | |
687 | with io.open(fname, encoding='utf-8') as f: |
|
687 | with io.open(fname, encoding='utf-8') as f: | |
688 | s = f.read() |
|
688 | s = f.read() | |
689 | nt.assert_in(u'liné1\n', s) |
|
689 | nt.assert_in(u'liné1\n', s) | |
690 | nt.assert_in(u'liné2', s) |
|
690 | nt.assert_in(u'liné2', s) | |
691 |
|
691 | |||
692 | def test_file_amend(): |
|
692 | def test_file_amend(): | |
693 | """%%file -a amends files""" |
|
693 | """%%file -a amends files""" | |
694 | ip = get_ipython() |
|
694 | ip = get_ipython() | |
695 | with TemporaryDirectory() as td: |
|
695 | with TemporaryDirectory() as td: | |
696 | fname = os.path.join(td, 'file2') |
|
696 | fname = os.path.join(td, 'file2') | |
697 | ip.run_cell_magic("file", fname, u'\n'.join([ |
|
697 | ip.run_cell_magic("file", fname, u'\n'.join([ | |
698 | 'line1', |
|
698 | 'line1', | |
699 | 'line2', |
|
699 | 'line2', | |
700 | ])) |
|
700 | ])) | |
701 | ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([ |
|
701 | ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([ | |
702 | 'line3', |
|
702 | 'line3', | |
703 | 'line4', |
|
703 | 'line4', | |
704 | ])) |
|
704 | ])) | |
705 | with open(fname) as f: |
|
705 | with open(fname) as f: | |
706 | s = f.read() |
|
706 | s = f.read() | |
707 | nt.assert_in('line1\n', s) |
|
707 | nt.assert_in('line1\n', s) | |
708 | nt.assert_in('line3\n', s) |
|
708 | nt.assert_in('line3\n', s) | |
709 |
|
709 | |||
710 |
|
710 | |||
711 | def test_script_config(): |
|
711 | def test_script_config(): | |
712 | ip = get_ipython() |
|
712 | ip = get_ipython() | |
713 | ip.config.ScriptMagics.script_magics = ['whoda'] |
|
713 | ip.config.ScriptMagics.script_magics = ['whoda'] | |
714 | sm = script.ScriptMagics(shell=ip) |
|
714 | sm = script.ScriptMagics(shell=ip) | |
715 | nt.assert_in('whoda', sm.magics['cell']) |
|
715 | nt.assert_in('whoda', sm.magics['cell']) | |
716 |
|
716 | |||
717 | @dec.skip_win32 |
|
717 | @dec.skip_win32 | |
718 | def test_script_out(): |
|
718 | def test_script_out(): | |
719 | ip = get_ipython() |
|
719 | ip = get_ipython() | |
720 | ip.run_cell_magic("script", "--out output sh", "echo 'hi'") |
|
720 | ip.run_cell_magic("script", "--out output sh", "echo 'hi'") | |
721 | nt.assert_equal(ip.user_ns['output'], 'hi\n') |
|
721 | nt.assert_equal(ip.user_ns['output'], 'hi\n') | |
722 |
|
722 | |||
723 | @dec.skip_win32 |
|
723 | @dec.skip_win32 | |
724 | def test_script_err(): |
|
724 | def test_script_err(): | |
725 | ip = get_ipython() |
|
725 | ip = get_ipython() | |
726 | ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2") |
|
726 | ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2") | |
727 | nt.assert_equal(ip.user_ns['error'], 'hello\n') |
|
727 | nt.assert_equal(ip.user_ns['error'], 'hello\n') | |
728 |
|
728 | |||
729 | @dec.skip_win32 |
|
729 | @dec.skip_win32 | |
730 | def test_script_out_err(): |
|
730 | def test_script_out_err(): | |
731 | ip = get_ipython() |
|
731 | ip = get_ipython() | |
732 | ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2") |
|
732 | ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2") | |
733 | nt.assert_equal(ip.user_ns['output'], 'hi\n') |
|
733 | nt.assert_equal(ip.user_ns['output'], 'hi\n') | |
734 | nt.assert_equal(ip.user_ns['error'], 'hello\n') |
|
734 | nt.assert_equal(ip.user_ns['error'], 'hello\n') | |
735 |
|
735 | |||
736 | @dec.skip_win32 |
|
736 | @dec.skip_win32 | |
737 | def test_script_bg_out(): |
|
737 | def test_script_bg_out(): | |
738 | ip = get_ipython() |
|
738 | ip = get_ipython() | |
739 | ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'") |
|
739 | ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'") | |
740 | nt.assert_equal(ip.user_ns['output'].read(), b'hi\n') |
|
740 | nt.assert_equal(ip.user_ns['output'].read(), b'hi\n') | |
741 |
|
741 | |||
742 | @dec.skip_win32 |
|
742 | @dec.skip_win32 | |
743 | def test_script_bg_err(): |
|
743 | def test_script_bg_err(): | |
744 | ip = get_ipython() |
|
744 | ip = get_ipython() | |
745 | ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2") |
|
745 | ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2") | |
746 | nt.assert_equal(ip.user_ns['error'].read(), b'hello\n') |
|
746 | nt.assert_equal(ip.user_ns['error'].read(), b'hello\n') | |
747 |
|
747 | |||
748 | @dec.skip_win32 |
|
748 | @dec.skip_win32 | |
749 | def test_script_bg_out_err(): |
|
749 | def test_script_bg_out_err(): | |
750 | ip = get_ipython() |
|
750 | ip = get_ipython() | |
751 | ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2") |
|
751 | ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2") | |
752 | nt.assert_equal(ip.user_ns['output'].read(), b'hi\n') |
|
752 | nt.assert_equal(ip.user_ns['output'].read(), b'hi\n') | |
753 | nt.assert_equal(ip.user_ns['error'].read(), b'hello\n') |
|
753 | nt.assert_equal(ip.user_ns['error'].read(), b'hello\n') | |
754 |
|
754 | |||
755 | def test_script_defaults(): |
|
755 | def test_script_defaults(): | |
756 | ip = get_ipython() |
|
756 | ip = get_ipython() | |
757 | for cmd in ['sh', 'bash', 'perl', 'ruby']: |
|
757 | for cmd in ['sh', 'bash', 'perl', 'ruby']: | |
758 | try: |
|
758 | try: | |
759 | find_cmd(cmd) |
|
759 | find_cmd(cmd) | |
760 | except Exception: |
|
760 | except Exception: | |
761 | pass |
|
761 | pass | |
762 | else: |
|
762 | else: | |
763 | nt.assert_in(cmd, ip.magics_manager.magics['cell']) |
|
763 | nt.assert_in(cmd, ip.magics_manager.magics['cell']) | |
764 |
|
764 | |||
765 |
|
765 | |||
766 | @magics_class |
|
766 | @magics_class | |
767 | class FooFoo(Magics): |
|
767 | class FooFoo(Magics): | |
768 | """class with both %foo and %%foo magics""" |
|
768 | """class with both %foo and %%foo magics""" | |
769 | @line_magic('foo') |
|
769 | @line_magic('foo') | |
770 | def line_foo(self, line): |
|
770 | def line_foo(self, line): | |
771 | "I am line foo" |
|
771 | "I am line foo" | |
772 | pass |
|
772 | pass | |
773 |
|
773 | |||
774 | @cell_magic("foo") |
|
774 | @cell_magic("foo") | |
775 | def cell_foo(self, line, cell): |
|
775 | def cell_foo(self, line, cell): | |
776 | "I am cell foo, not line foo" |
|
776 | "I am cell foo, not line foo" | |
777 | pass |
|
777 | pass | |
778 |
|
778 | |||
779 | def test_line_cell_info(): |
|
779 | def test_line_cell_info(): | |
780 | """%%foo and %foo magics are distinguishable to inspect""" |
|
780 | """%%foo and %foo magics are distinguishable to inspect""" | |
781 | ip = get_ipython() |
|
781 | ip = get_ipython() | |
782 | ip.magics_manager.register(FooFoo) |
|
782 | ip.magics_manager.register(FooFoo) | |
783 | oinfo = ip.object_inspect('foo') |
|
783 | oinfo = ip.object_inspect('foo') | |
784 | nt.assert_true(oinfo['found']) |
|
784 | nt.assert_true(oinfo['found']) | |
785 | nt.assert_true(oinfo['ismagic']) |
|
785 | nt.assert_true(oinfo['ismagic']) | |
786 |
|
786 | |||
787 | oinfo = ip.object_inspect('%%foo') |
|
787 | oinfo = ip.object_inspect('%%foo') | |
788 | nt.assert_true(oinfo['found']) |
|
788 | nt.assert_true(oinfo['found']) | |
789 | nt.assert_true(oinfo['ismagic']) |
|
789 | nt.assert_true(oinfo['ismagic']) | |
790 | nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__) |
|
790 | nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__) | |
791 |
|
791 | |||
792 | oinfo = ip.object_inspect('%foo') |
|
792 | oinfo = ip.object_inspect('%foo') | |
793 | nt.assert_true(oinfo['found']) |
|
793 | nt.assert_true(oinfo['found']) | |
794 | nt.assert_true(oinfo['ismagic']) |
|
794 | nt.assert_true(oinfo['ismagic']) | |
795 | nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__) |
|
795 | nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__) | |
796 |
|
796 | |||
797 | def test_multiple_magics(): |
|
797 | def test_multiple_magics(): | |
798 | ip = get_ipython() |
|
798 | ip = get_ipython() | |
799 | foo1 = FooFoo(ip) |
|
799 | foo1 = FooFoo(ip) | |
800 | foo2 = FooFoo(ip) |
|
800 | foo2 = FooFoo(ip) | |
801 | mm = ip.magics_manager |
|
801 | mm = ip.magics_manager | |
802 | mm.register(foo1) |
|
802 | mm.register(foo1) | |
803 | nt.assert_true(mm.magics['line']['foo'].im_self is foo1) |
|
803 | nt.assert_true(mm.magics['line']['foo'].im_self is foo1) | |
804 | mm.register(foo2) |
|
804 | mm.register(foo2) | |
805 | nt.assert_true(mm.magics['line']['foo'].im_self is foo2) |
|
805 | nt.assert_true(mm.magics['line']['foo'].im_self is foo2) | |
806 |
|
806 | |||
807 | def test_alias_magic(): |
|
807 | def test_alias_magic(): | |
808 | """Test %alias_magic.""" |
|
808 | """Test %alias_magic.""" | |
809 | ip = get_ipython() |
|
809 | ip = get_ipython() | |
810 | mm = ip.magics_manager |
|
810 | mm = ip.magics_manager | |
811 |
|
811 | |||
812 | # Basic operation: both cell and line magics are created, if possible. |
|
812 | # Basic operation: both cell and line magics are created, if possible. | |
813 | ip.run_line_magic('alias_magic', 'timeit_alias timeit') |
|
813 | ip.run_line_magic('alias_magic', 'timeit_alias timeit') | |
814 | nt.assert_in('timeit_alias', mm.magics['line']) |
|
814 | nt.assert_in('timeit_alias', mm.magics['line']) | |
815 | nt.assert_in('timeit_alias', mm.magics['cell']) |
|
815 | nt.assert_in('timeit_alias', mm.magics['cell']) | |
816 |
|
816 | |||
817 | # --cell is specified, line magic not created. |
|
817 | # --cell is specified, line magic not created. | |
818 | ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit') |
|
818 | ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit') | |
819 | nt.assert_not_in('timeit_cell_alias', mm.magics['line']) |
|
819 | nt.assert_not_in('timeit_cell_alias', mm.magics['line']) | |
820 | nt.assert_in('timeit_cell_alias', mm.magics['cell']) |
|
820 | nt.assert_in('timeit_cell_alias', mm.magics['cell']) | |
821 |
|
821 | |||
822 | # Test that line alias is created successfully. |
|
822 | # Test that line alias is created successfully. | |
823 | ip.run_line_magic('alias_magic', '--line env_alias env') |
|
823 | ip.run_line_magic('alias_magic', '--line env_alias env') | |
824 | nt.assert_equal(ip.run_line_magic('env', ''), |
|
824 | nt.assert_equal(ip.run_line_magic('env', ''), | |
825 | ip.run_line_magic('env_alias', '')) |
|
825 | ip.run_line_magic('env_alias', '')) | |
826 |
|
826 | |||
827 | def test_save(): |
|
827 | def test_save(): | |
828 | """Test %save.""" |
|
828 | """Test %save.""" | |
829 | ip = get_ipython() |
|
829 | ip = get_ipython() | |
830 | ip.history_manager.reset() # Clear any existing history. |
|
830 | ip.history_manager.reset() # Clear any existing history. | |
831 | cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"] |
|
831 | cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"] | |
832 | for i, cmd in enumerate(cmds, start=1): |
|
832 | for i, cmd in enumerate(cmds, start=1): | |
833 | ip.history_manager.store_inputs(i, cmd) |
|
833 | ip.history_manager.store_inputs(i, cmd) | |
834 | with TemporaryDirectory() as tmpdir: |
|
834 | with TemporaryDirectory() as tmpdir: | |
835 | file = os.path.join(tmpdir, "testsave.py") |
|
835 | file = os.path.join(tmpdir, "testsave.py") | |
836 | ip.run_line_magic("save", "%s 1-10" % file) |
|
836 | ip.run_line_magic("save", "%s 1-10" % file) | |
837 | with open(file) as f: |
|
837 | with open(file) as f: | |
838 | content = f.read() |
|
838 | content = f.read() | |
839 | nt.assert_equal(content.count(cmds[0]), 1) |
|
839 | nt.assert_equal(content.count(cmds[0]), 1) | |
840 | nt.assert_in('coding: utf-8', content) |
|
840 | nt.assert_in('coding: utf-8', content) | |
841 | ip.run_line_magic("save", "-a %s 1-10" % file) |
|
841 | ip.run_line_magic("save", "-a %s 1-10" % file) | |
842 | with open(file) as f: |
|
842 | with open(file) as f: | |
843 | content = f.read() |
|
843 | content = f.read() | |
844 | nt.assert_equal(content.count(cmds[0]), 2) |
|
844 | nt.assert_equal(content.count(cmds[0]), 2) | |
845 | nt.assert_in('coding: utf-8', content) |
|
845 | nt.assert_in('coding: utf-8', content) | |
846 |
|
846 | |||
847 |
|
847 | |||
848 | def test_store(): |
|
848 | def test_store(): | |
849 | """Test %store.""" |
|
849 | """Test %store.""" | |
850 | ip = get_ipython() |
|
850 | ip = get_ipython() | |
851 | ip.run_line_magic('load_ext', 'storemagic') |
|
851 | ip.run_line_magic('load_ext', 'storemagic') | |
852 |
|
852 | |||
853 | # make sure the storage is empty |
|
853 | # make sure the storage is empty | |
854 | ip.run_line_magic('store', '-z') |
|
854 | ip.run_line_magic('store', '-z') | |
855 | ip.user_ns['var'] = 42 |
|
855 | ip.user_ns['var'] = 42 | |
856 | ip.run_line_magic('store', 'var') |
|
856 | ip.run_line_magic('store', 'var') | |
857 | ip.user_ns['var'] = 39 |
|
857 | ip.user_ns['var'] = 39 | |
858 | ip.run_line_magic('store', '-r') |
|
858 | ip.run_line_magic('store', '-r') | |
859 | nt.assert_equal(ip.user_ns['var'], 42) |
|
859 | nt.assert_equal(ip.user_ns['var'], 42) | |
860 |
|
860 | |||
861 | ip.run_line_magic('store', '-d var') |
|
861 | ip.run_line_magic('store', '-d var') | |
862 | ip.user_ns['var'] = 39 |
|
862 | ip.user_ns['var'] = 39 | |
863 | ip.run_line_magic('store' , '-r') |
|
863 | ip.run_line_magic('store' , '-r') | |
864 | nt.assert_equal(ip.user_ns['var'], 39) |
|
864 | nt.assert_equal(ip.user_ns['var'], 39) | |
865 |
|
865 | |||
866 |
|
866 | |||
867 | def _run_edit_test(arg_s, exp_filename=None, |
|
867 | def _run_edit_test(arg_s, exp_filename=None, | |
868 | exp_lineno=-1, |
|
868 | exp_lineno=-1, | |
869 | exp_contents=None, |
|
869 | exp_contents=None, | |
870 | exp_is_temp=None): |
|
870 | exp_is_temp=None): | |
871 | ip = get_ipython() |
|
871 | ip = get_ipython() | |
872 | M = code.CodeMagics(ip) |
|
872 | M = code.CodeMagics(ip) | |
873 | last_call = ['',''] |
|
873 | last_call = ['',''] | |
874 | opts,args = M.parse_options(arg_s,'prxn:') |
|
874 | opts,args = M.parse_options(arg_s,'prxn:') | |
875 | filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call) |
|
875 | filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call) | |
876 |
|
876 | |||
877 | if exp_filename is not None: |
|
877 | if exp_filename is not None: | |
878 | nt.assert_equal(exp_filename, filename) |
|
878 | nt.assert_equal(exp_filename, filename) | |
879 | if exp_contents is not None: |
|
879 | if exp_contents is not None: | |
880 | with io.open(filename, 'r') as f: |
|
880 | with io.open(filename, 'r') as f: | |
881 | contents = f.read() |
|
881 | contents = f.read() | |
882 | nt.assert_equal(exp_contents, contents) |
|
882 | nt.assert_equal(exp_contents, contents) | |
883 | if exp_lineno != -1: |
|
883 | if exp_lineno != -1: | |
884 | nt.assert_equal(exp_lineno, lineno) |
|
884 | nt.assert_equal(exp_lineno, lineno) | |
885 | if exp_is_temp is not None: |
|
885 | if exp_is_temp is not None: | |
886 | nt.assert_equal(exp_is_temp, is_temp) |
|
886 | nt.assert_equal(exp_is_temp, is_temp) | |
887 |
|
887 | |||
888 |
|
888 | |||
889 | def test_edit_interactive(): |
|
889 | def test_edit_interactive(): | |
890 | """%edit on interactively defined objects""" |
|
890 | """%edit on interactively defined objects""" | |
891 | ip = get_ipython() |
|
891 | ip = get_ipython() | |
892 | n = ip.execution_count |
|
892 | n = ip.execution_count | |
893 | ip.run_cell(u"def foo(): return 1", store_history=True) |
|
893 | ip.run_cell(u"def foo(): return 1", store_history=True) | |
894 |
|
894 | |||
895 | try: |
|
895 | try: | |
896 | _run_edit_test("foo") |
|
896 | _run_edit_test("foo") | |
897 | except code.InteractivelyDefined as e: |
|
897 | except code.InteractivelyDefined as e: | |
898 | nt.assert_equal(e.index, n) |
|
898 | nt.assert_equal(e.index, n) | |
899 | else: |
|
899 | else: | |
900 | raise AssertionError("Should have raised InteractivelyDefined") |
|
900 | raise AssertionError("Should have raised InteractivelyDefined") | |
901 |
|
901 | |||
902 |
|
902 | |||
903 | def test_edit_cell(): |
|
903 | def test_edit_cell(): | |
904 | """%edit [cell id]""" |
|
904 | """%edit [cell id]""" | |
905 | ip = get_ipython() |
|
905 | ip = get_ipython() | |
906 |
|
906 | |||
907 | ip.run_cell(u"def foo(): return 1", store_history=True) |
|
907 | ip.run_cell(u"def foo(): return 1", store_history=True) | |
908 |
|
908 | |||
909 | # test |
|
909 | # test | |
910 | _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True) |
|
910 | _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True) |
General Comments 0
You need to be logged in to leave comments.
Login now