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