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