Show More
@@ -1,384 +1,389 b'' | |||||
1 | """Tests for various magic functions. |
|
1 | """Tests for various magic functions. | |
2 |
|
2 | |||
3 | Needs to be run by nose (to make ipython session available). |
|
3 | Needs to be run by nose (to make ipython session available). | |
4 | """ |
|
4 | """ | |
5 | from __future__ import absolute_import |
|
5 | from __future__ import absolute_import | |
6 |
|
6 | |||
7 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
8 | # Imports |
|
8 | # Imports | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | import os |
|
11 | import os | |
12 |
|
12 | |||
13 | import nose.tools as nt |
|
13 | import nose.tools as nt | |
14 |
|
14 | |||
15 | from IPython.testing import decorators as dec |
|
15 | from IPython.testing import decorators as dec | |
16 | from IPython.testing import tools as tt |
|
16 | from IPython.testing import tools as tt | |
17 | from IPython.utils import py3compat |
|
17 | from IPython.utils import py3compat | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Test functions begin |
|
20 | # Test functions begin | |
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 |
|
22 | |||
23 | def test_rehashx(): |
|
23 | def test_rehashx(): | |
24 | # clear up everything |
|
24 | # clear up everything | |
25 | _ip = get_ipython() |
|
25 | _ip = get_ipython() | |
26 | _ip.alias_manager.alias_table.clear() |
|
26 | _ip.alias_manager.alias_table.clear() | |
27 | del _ip.db['syscmdlist'] |
|
27 | del _ip.db['syscmdlist'] | |
28 |
|
28 | |||
29 | _ip.magic('rehashx') |
|
29 | _ip.magic('rehashx') | |
30 | # Practically ALL ipython development systems will have more than 10 aliases |
|
30 | # Practically ALL ipython development systems will have more than 10 aliases | |
31 |
|
31 | |||
32 | yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10) |
|
32 | yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10) | |
33 | for key, val in _ip.alias_manager.alias_table.iteritems(): |
|
33 | for key, val in _ip.alias_manager.alias_table.iteritems(): | |
34 | # we must strip dots from alias names |
|
34 | # we must strip dots from alias names | |
35 | nt.assert_true('.' not in key) |
|
35 | nt.assert_true('.' not in key) | |
36 |
|
36 | |||
37 | # rehashx must fill up syscmdlist |
|
37 | # rehashx must fill up syscmdlist | |
38 | scoms = _ip.db['syscmdlist'] |
|
38 | scoms = _ip.db['syscmdlist'] | |
39 | yield (nt.assert_true, len(scoms) > 10) |
|
39 | yield (nt.assert_true, len(scoms) > 10) | |
40 |
|
40 | |||
41 |
|
41 | |||
42 | def test_magic_parse_options(): |
|
42 | def test_magic_parse_options(): | |
43 | """Test that we don't mangle paths when parsing magic options.""" |
|
43 | """Test that we don't mangle paths when parsing magic options.""" | |
44 | ip = get_ipython() |
|
44 | ip = get_ipython() | |
45 | path = 'c:\\x' |
|
45 | path = 'c:\\x' | |
46 | opts = ip.parse_options('-f %s' % path,'f:')[0] |
|
46 | opts = ip.parse_options('-f %s' % path,'f:')[0] | |
47 | # argv splitting is os-dependent |
|
47 | # argv splitting is os-dependent | |
48 | if os.name == 'posix': |
|
48 | if os.name == 'posix': | |
49 | expected = 'c:x' |
|
49 | expected = 'c:x' | |
50 | else: |
|
50 | else: | |
51 | expected = path |
|
51 | expected = path | |
52 | nt.assert_equals(opts['f'], expected) |
|
52 | nt.assert_equals(opts['f'], expected) | |
53 |
|
53 | |||
54 |
|
54 | |||
55 | @dec.skip_without('sqlite3') |
|
55 | @dec.skip_without('sqlite3') | |
56 | def doctest_hist_f(): |
|
56 | def doctest_hist_f(): | |
57 | """Test %hist -f with temporary filename. |
|
57 | """Test %hist -f with temporary filename. | |
58 |
|
58 | |||
59 | In [9]: import tempfile |
|
59 | In [9]: import tempfile | |
60 |
|
60 | |||
61 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') |
|
61 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') | |
62 |
|
62 | |||
63 | In [11]: %hist -nl -f $tfile 3 |
|
63 | In [11]: %hist -nl -f $tfile 3 | |
64 |
|
64 | |||
65 | In [13]: import os; os.unlink(tfile) |
|
65 | In [13]: import os; os.unlink(tfile) | |
66 | """ |
|
66 | """ | |
67 |
|
67 | |||
68 |
|
68 | |||
69 | @dec.skip_without('sqlite3') |
|
69 | @dec.skip_without('sqlite3') | |
70 | def doctest_hist_r(): |
|
70 | def doctest_hist_r(): | |
71 | """Test %hist -r |
|
71 | """Test %hist -r | |
72 |
|
72 | |||
73 | XXX - This test is not recording the output correctly. For some reason, in |
|
73 | XXX - This test is not recording the output correctly. For some reason, in | |
74 | testing mode the raw history isn't getting populated. No idea why. |
|
74 | testing mode the raw history isn't getting populated. No idea why. | |
75 | Disabling the output checking for now, though at least we do run it. |
|
75 | Disabling the output checking for now, though at least we do run it. | |
76 |
|
76 | |||
77 | In [1]: 'hist' in _ip.lsmagic() |
|
77 | In [1]: 'hist' in _ip.lsmagic() | |
78 | Out[1]: True |
|
78 | Out[1]: True | |
79 |
|
79 | |||
80 | In [2]: x=1 |
|
80 | In [2]: x=1 | |
81 |
|
81 | |||
82 | In [3]: %hist -rl 2 |
|
82 | In [3]: %hist -rl 2 | |
83 | x=1 # random |
|
83 | x=1 # random | |
84 | %hist -r 2 |
|
84 | %hist -r 2 | |
85 | """ |
|
85 | """ | |
86 |
|
86 | |||
87 |
|
87 | |||
88 | @dec.skip_without('sqlite3') |
|
88 | @dec.skip_without('sqlite3') | |
89 | def doctest_hist_op(): |
|
89 | def doctest_hist_op(): | |
90 | """Test %hist -op |
|
90 | """Test %hist -op | |
91 |
|
91 | |||
92 | In [1]: class b(float): |
|
92 | In [1]: class b(float): | |
93 | ...: pass |
|
93 | ...: pass | |
94 | ...: |
|
94 | ...: | |
95 |
|
95 | |||
96 | In [2]: class s(object): |
|
96 | In [2]: class s(object): | |
97 | ...: def __str__(self): |
|
97 | ...: def __str__(self): | |
98 | ...: return 's' |
|
98 | ...: return 's' | |
99 | ...: |
|
99 | ...: | |
100 |
|
100 | |||
101 | In [3]: |
|
101 | In [3]: | |
102 |
|
102 | |||
103 | In [4]: class r(b): |
|
103 | In [4]: class r(b): | |
104 | ...: def __repr__(self): |
|
104 | ...: def __repr__(self): | |
105 | ...: return 'r' |
|
105 | ...: return 'r' | |
106 | ...: |
|
106 | ...: | |
107 |
|
107 | |||
108 | In [5]: class sr(s,r): pass |
|
108 | In [5]: class sr(s,r): pass | |
109 | ...: |
|
109 | ...: | |
110 |
|
110 | |||
111 | In [6]: |
|
111 | In [6]: | |
112 |
|
112 | |||
113 | In [7]: bb=b() |
|
113 | In [7]: bb=b() | |
114 |
|
114 | |||
115 | In [8]: ss=s() |
|
115 | In [8]: ss=s() | |
116 |
|
116 | |||
117 | In [9]: rr=r() |
|
117 | In [9]: rr=r() | |
118 |
|
118 | |||
119 | In [10]: ssrr=sr() |
|
119 | In [10]: ssrr=sr() | |
120 |
|
120 | |||
121 | In [11]: 4.5 |
|
121 | In [11]: 4.5 | |
122 | Out[11]: 4.5 |
|
122 | Out[11]: 4.5 | |
123 |
|
123 | |||
124 | In [12]: str(ss) |
|
124 | In [12]: str(ss) | |
125 | Out[12]: 's' |
|
125 | Out[12]: 's' | |
126 |
|
126 | |||
127 | In [13]: |
|
127 | In [13]: | |
128 |
|
128 | |||
129 | In [14]: %hist -op |
|
129 | In [14]: %hist -op | |
130 | >>> class b: |
|
130 | >>> class b: | |
131 | ... pass |
|
131 | ... pass | |
132 | ... |
|
132 | ... | |
133 | >>> class s(b): |
|
133 | >>> class s(b): | |
134 | ... def __str__(self): |
|
134 | ... def __str__(self): | |
135 | ... return 's' |
|
135 | ... return 's' | |
136 | ... |
|
136 | ... | |
137 | >>> |
|
137 | >>> | |
138 | >>> class r(b): |
|
138 | >>> class r(b): | |
139 | ... def __repr__(self): |
|
139 | ... def __repr__(self): | |
140 | ... return 'r' |
|
140 | ... return 'r' | |
141 | ... |
|
141 | ... | |
142 | >>> class sr(s,r): pass |
|
142 | >>> class sr(s,r): pass | |
143 | >>> |
|
143 | >>> | |
144 | >>> bb=b() |
|
144 | >>> bb=b() | |
145 | >>> ss=s() |
|
145 | >>> ss=s() | |
146 | >>> rr=r() |
|
146 | >>> rr=r() | |
147 | >>> ssrr=sr() |
|
147 | >>> ssrr=sr() | |
148 | >>> 4.5 |
|
148 | >>> 4.5 | |
149 | 4.5 |
|
149 | 4.5 | |
150 | >>> str(ss) |
|
150 | >>> str(ss) | |
151 | 's' |
|
151 | 's' | |
152 | >>> |
|
152 | >>> | |
153 | """ |
|
153 | """ | |
154 |
|
154 | |||
155 |
|
155 | |||
156 | @dec.skip_without('sqlite3') |
|
156 | @dec.skip_without('sqlite3') | |
157 | def test_macro(): |
|
157 | def test_macro(): | |
158 | ip = get_ipython() |
|
158 | ip = get_ipython() | |
159 | ip.history_manager.reset() # Clear any existing history. |
|
159 | ip.history_manager.reset() # Clear any existing history. | |
160 | cmds = ["a=1", "def b():\n return a**2", "print(a,b())"] |
|
160 | cmds = ["a=1", "def b():\n return a**2", "print(a,b())"] | |
161 | for i, cmd in enumerate(cmds, start=1): |
|
161 | for i, cmd in enumerate(cmds, start=1): | |
162 | ip.history_manager.store_inputs(i, cmd) |
|
162 | ip.history_manager.store_inputs(i, cmd) | |
163 | ip.magic("macro test 1-3") |
|
163 | ip.magic("macro test 1-3") | |
164 | nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n") |
|
164 | nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n") | |
165 |
|
165 | |||
166 | # List macros. |
|
166 | # List macros. | |
167 | assert "test" in ip.magic("macro") |
|
167 | assert "test" in ip.magic("macro") | |
168 |
|
168 | |||
169 |
|
169 | |||
170 | @dec.skip_without('sqlite3') |
|
170 | @dec.skip_without('sqlite3') | |
171 | def test_macro_run(): |
|
171 | def test_macro_run(): | |
172 | """Test that we can run a multi-line macro successfully.""" |
|
172 | """Test that we can run a multi-line macro successfully.""" | |
173 | ip = get_ipython() |
|
173 | ip = get_ipython() | |
174 | ip.history_manager.reset() |
|
174 | ip.history_manager.reset() | |
175 | cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"), |
|
175 | cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"), | |
176 | "%macro test 2-3"] |
|
176 | "%macro test 2-3"] | |
177 | for cmd in cmds: |
|
177 | for cmd in cmds: | |
178 | ip.run_cell(cmd, store_history=True) |
|
178 | ip.run_cell(cmd, store_history=True) | |
179 | nt.assert_equal(ip.user_ns["test"].value, |
|
179 | nt.assert_equal(ip.user_ns["test"].value, | |
180 | py3compat.doctest_refactor_print("a+=1\nprint a\n")) |
|
180 | py3compat.doctest_refactor_print("a+=1\nprint a\n")) | |
181 | with tt.AssertPrints("12"): |
|
181 | with tt.AssertPrints("12"): | |
182 | ip.run_cell("test") |
|
182 | ip.run_cell("test") | |
183 | with tt.AssertPrints("13"): |
|
183 | with tt.AssertPrints("13"): | |
184 | ip.run_cell("test") |
|
184 | ip.run_cell("test") | |
185 |
|
185 | |||
186 |
|
186 | |||
187 | @dec.skipif_not_numpy |
|
187 | @dec.skipif_not_numpy | |
188 | def test_numpy_clear_array_undec(): |
|
188 | def test_numpy_clear_array_undec(): | |
189 | "Test '%clear array' functionality" |
|
189 | "Test '%clear array' functionality" | |
190 | _ip.magic("load_ext clearcmd") |
|
190 | _ip.magic("load_ext clearcmd") | |
191 | _ip.ex('import numpy as np') |
|
191 | _ip.ex('import numpy as np') | |
192 | _ip.ex('a = np.empty(2)') |
|
192 | _ip.ex('a = np.empty(2)') | |
193 | yield (nt.assert_true, 'a' in _ip.user_ns) |
|
193 | yield (nt.assert_true, 'a' in _ip.user_ns) | |
194 | _ip.magic('clear array') |
|
194 | _ip.magic('clear array') | |
195 | yield (nt.assert_false, 'a' in _ip.user_ns) |
|
195 | yield (nt.assert_false, 'a' in _ip.user_ns) | |
196 |
|
196 | |||
197 | def test_clear(): |
|
197 | def test_clear(): | |
198 | "Test '%clear' magic provided by IPython.extensions.clearcmd" |
|
198 | "Test '%clear' magic provided by IPython.extensions.clearcmd" | |
199 | _ip = get_ipython() |
|
199 | _ip = get_ipython() | |
200 | _ip.magic("load_ext clearcmd") |
|
200 | _ip.magic("load_ext clearcmd") | |
201 | _ip.run_cell("parrot = 'dead'", store_history=True) |
|
201 | _ip.run_cell("parrot = 'dead'", store_history=True) | |
202 | # test '%clear out', make an Out prompt |
|
202 | # test '%clear out', make an Out prompt | |
203 | _ip.run_cell("parrot", store_history=True) |
|
203 | _ip.run_cell("parrot", store_history=True) | |
204 | nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___']) |
|
204 | nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___']) | |
205 | _ip.magic('clear out') |
|
205 | _ip.magic('clear out') | |
206 | nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___']) |
|
206 | nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___']) | |
207 | nt.assert_true(len(_ip.user_ns['Out']) == 0) |
|
207 | nt.assert_true(len(_ip.user_ns['Out']) == 0) | |
208 |
|
208 | |||
209 | # test '%clear in' |
|
209 | # test '%clear in' | |
210 | _ip.run_cell("parrot", store_history=True) |
|
210 | _ip.run_cell("parrot", store_history=True) | |
211 | nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) |
|
211 | nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) | |
212 | _ip.magic('%clear in') |
|
212 | _ip.magic('%clear in') | |
213 | nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) |
|
213 | nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) | |
214 |
nt.assert_true(len(_ip.user_ns['In']) == |
|
214 | nt.assert_true(len(set(_ip.user_ns['In'])) == 1) | |
215 |
|
215 | |||
216 | # test '%clear dhist' |
|
216 | # test '%clear dhist' | |
217 | _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing |
|
217 | _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing | |
218 | _ip.magic('cd') |
|
218 | _ip.magic('cd') | |
219 | _ip.magic('cd -') |
|
219 | _ip.magic('cd -') | |
220 | nt.assert_true(len(_ip.user_ns['_dh']) > 0) |
|
220 | nt.assert_true(len(_ip.user_ns['_dh']) > 0) | |
221 | _ip.magic('clear dhist') |
|
221 | _ip.magic('clear dhist') | |
222 | nt.assert_true(len(_ip.user_ns['_dh']) == 0) |
|
222 | nt.assert_true(len(_ip.user_ns['_dh']) == 0) | |
223 | _ip.run_cell("_dh = [d for d in tmp]") #restore |
|
223 | _ip.run_cell("_dh = [d for d in tmp]") #restore | |
224 |
|
224 | |||
|
225 | # test that In length is preserved for %macro | |||
|
226 | _ip.run_cell("print 'foo'") | |||
|
227 | _ip.run_cell("clear in") | |||
|
228 | nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1) | |||
|
229 | ||||
225 | def test_time(): |
|
230 | def test_time(): | |
226 | _ip.magic('time None') |
|
231 | _ip.magic('time None') | |
227 |
|
232 | |||
228 |
|
233 | |||
229 | @py3compat.doctest_refactor_print |
|
234 | @py3compat.doctest_refactor_print | |
230 | def doctest_time(): |
|
235 | def doctest_time(): | |
231 | """ |
|
236 | """ | |
232 | In [10]: %time None |
|
237 | In [10]: %time None | |
233 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
238 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
234 | Wall time: 0.00 s |
|
239 | Wall time: 0.00 s | |
235 |
|
240 | |||
236 | In [11]: def f(kmjy): |
|
241 | In [11]: def f(kmjy): | |
237 | ....: %time print 2*kmjy |
|
242 | ....: %time print 2*kmjy | |
238 |
|
243 | |||
239 | In [12]: f(3) |
|
244 | In [12]: f(3) | |
240 | 6 |
|
245 | 6 | |
241 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
246 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
242 | Wall time: 0.00 s |
|
247 | Wall time: 0.00 s | |
243 | """ |
|
248 | """ | |
244 |
|
249 | |||
245 |
|
250 | |||
246 | def test_doctest_mode(): |
|
251 | def test_doctest_mode(): | |
247 | "Toggle doctest_mode twice, it should be a no-op and run without error" |
|
252 | "Toggle doctest_mode twice, it should be a no-op and run without error" | |
248 | _ip.magic('doctest_mode') |
|
253 | _ip.magic('doctest_mode') | |
249 | _ip.magic('doctest_mode') |
|
254 | _ip.magic('doctest_mode') | |
250 |
|
255 | |||
251 |
|
256 | |||
252 | def test_parse_options(): |
|
257 | def test_parse_options(): | |
253 | """Tests for basic options parsing in magics.""" |
|
258 | """Tests for basic options parsing in magics.""" | |
254 | # These are only the most minimal of tests, more should be added later. At |
|
259 | # These are only the most minimal of tests, more should be added later. At | |
255 | # the very least we check that basic text/unicode calls work OK. |
|
260 | # the very least we check that basic text/unicode calls work OK. | |
256 | nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo') |
|
261 | nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo') | |
257 | nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo') |
|
262 | nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo') | |
258 |
|
263 | |||
259 |
|
264 | |||
260 | def test_dirops(): |
|
265 | def test_dirops(): | |
261 | """Test various directory handling operations.""" |
|
266 | """Test various directory handling operations.""" | |
262 | # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/') |
|
267 | # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/') | |
263 | curpath = os.getcwdu |
|
268 | curpath = os.getcwdu | |
264 | startdir = os.getcwdu() |
|
269 | startdir = os.getcwdu() | |
265 | ipdir = os.path.realpath(_ip.ipython_dir) |
|
270 | ipdir = os.path.realpath(_ip.ipython_dir) | |
266 | try: |
|
271 | try: | |
267 | _ip.magic('cd "%s"' % ipdir) |
|
272 | _ip.magic('cd "%s"' % ipdir) | |
268 | nt.assert_equal(curpath(), ipdir) |
|
273 | nt.assert_equal(curpath(), ipdir) | |
269 | _ip.magic('cd -') |
|
274 | _ip.magic('cd -') | |
270 | nt.assert_equal(curpath(), startdir) |
|
275 | nt.assert_equal(curpath(), startdir) | |
271 | _ip.magic('pushd "%s"' % ipdir) |
|
276 | _ip.magic('pushd "%s"' % ipdir) | |
272 | nt.assert_equal(curpath(), ipdir) |
|
277 | nt.assert_equal(curpath(), ipdir) | |
273 | _ip.magic('popd') |
|
278 | _ip.magic('popd') | |
274 | nt.assert_equal(curpath(), startdir) |
|
279 | nt.assert_equal(curpath(), startdir) | |
275 | finally: |
|
280 | finally: | |
276 | os.chdir(startdir) |
|
281 | os.chdir(startdir) | |
277 |
|
282 | |||
278 |
|
283 | |||
279 | def test_xmode(): |
|
284 | def test_xmode(): | |
280 | # Calling xmode three times should be a no-op |
|
285 | # Calling xmode three times should be a no-op | |
281 | xmode = _ip.InteractiveTB.mode |
|
286 | xmode = _ip.InteractiveTB.mode | |
282 | for i in range(3): |
|
287 | for i in range(3): | |
283 | _ip.magic("xmode") |
|
288 | _ip.magic("xmode") | |
284 | nt.assert_equal(_ip.InteractiveTB.mode, xmode) |
|
289 | nt.assert_equal(_ip.InteractiveTB.mode, xmode) | |
285 |
|
290 | |||
286 | def test_reset_hard(): |
|
291 | def test_reset_hard(): | |
287 | monitor = [] |
|
292 | monitor = [] | |
288 | class A(object): |
|
293 | class A(object): | |
289 | def __del__(self): |
|
294 | def __del__(self): | |
290 | monitor.append(1) |
|
295 | monitor.append(1) | |
291 | def __repr__(self): |
|
296 | def __repr__(self): | |
292 | return "<A instance>" |
|
297 | return "<A instance>" | |
293 |
|
298 | |||
294 | _ip.user_ns["a"] = A() |
|
299 | _ip.user_ns["a"] = A() | |
295 | _ip.run_cell("a") |
|
300 | _ip.run_cell("a") | |
296 |
|
301 | |||
297 | nt.assert_equal(monitor, []) |
|
302 | nt.assert_equal(monitor, []) | |
298 | _ip.magic_reset("-f") |
|
303 | _ip.magic_reset("-f") | |
299 | nt.assert_equal(monitor, [1]) |
|
304 | nt.assert_equal(monitor, [1]) | |
300 |
|
305 | |||
301 | class TestXdel(tt.TempFileMixin): |
|
306 | class TestXdel(tt.TempFileMixin): | |
302 | def test_xdel(self): |
|
307 | def test_xdel(self): | |
303 | """Test that references from %run are cleared by xdel.""" |
|
308 | """Test that references from %run are cleared by xdel.""" | |
304 | src = ("class A(object):\n" |
|
309 | src = ("class A(object):\n" | |
305 | " monitor = []\n" |
|
310 | " monitor = []\n" | |
306 | " def __del__(self):\n" |
|
311 | " def __del__(self):\n" | |
307 | " self.monitor.append(1)\n" |
|
312 | " self.monitor.append(1)\n" | |
308 | "a = A()\n") |
|
313 | "a = A()\n") | |
309 | self.mktmp(src) |
|
314 | self.mktmp(src) | |
310 | # %run creates some hidden references... |
|
315 | # %run creates some hidden references... | |
311 | _ip.magic("run %s" % self.fname) |
|
316 | _ip.magic("run %s" % self.fname) | |
312 | # ... as does the displayhook. |
|
317 | # ... as does the displayhook. | |
313 | _ip.run_cell("a") |
|
318 | _ip.run_cell("a") | |
314 |
|
319 | |||
315 | monitor = _ip.user_ns["A"].monitor |
|
320 | monitor = _ip.user_ns["A"].monitor | |
316 | nt.assert_equal(monitor, []) |
|
321 | nt.assert_equal(monitor, []) | |
317 |
|
322 | |||
318 | _ip.magic("xdel a") |
|
323 | _ip.magic("xdel a") | |
319 |
|
324 | |||
320 | # Check that a's __del__ method has been called. |
|
325 | # Check that a's __del__ method has been called. | |
321 | nt.assert_equal(monitor, [1]) |
|
326 | nt.assert_equal(monitor, [1]) | |
322 |
|
327 | |||
323 | def doctest_who(): |
|
328 | def doctest_who(): | |
324 | """doctest for %who |
|
329 | """doctest for %who | |
325 |
|
330 | |||
326 | In [1]: %reset -f |
|
331 | In [1]: %reset -f | |
327 |
|
332 | |||
328 | In [2]: alpha = 123 |
|
333 | In [2]: alpha = 123 | |
329 |
|
334 | |||
330 | In [3]: beta = 'beta' |
|
335 | In [3]: beta = 'beta' | |
331 |
|
336 | |||
332 | In [4]: %who int |
|
337 | In [4]: %who int | |
333 | alpha |
|
338 | alpha | |
334 |
|
339 | |||
335 | In [5]: %who str |
|
340 | In [5]: %who str | |
336 | beta |
|
341 | beta | |
337 |
|
342 | |||
338 | In [6]: %whos |
|
343 | In [6]: %whos | |
339 | Variable Type Data/Info |
|
344 | Variable Type Data/Info | |
340 | ---------------------------- |
|
345 | ---------------------------- | |
341 | alpha int 123 |
|
346 | alpha int 123 | |
342 | beta str beta |
|
347 | beta str beta | |
343 |
|
348 | |||
344 | In [7]: %who_ls |
|
349 | In [7]: %who_ls | |
345 | Out[7]: ['alpha', 'beta'] |
|
350 | Out[7]: ['alpha', 'beta'] | |
346 | """ |
|
351 | """ | |
347 |
|
352 | |||
348 | @py3compat.u_format |
|
353 | @py3compat.u_format | |
349 | def doctest_precision(): |
|
354 | def doctest_precision(): | |
350 | """doctest for %precision |
|
355 | """doctest for %precision | |
351 |
|
356 | |||
352 | In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain'] |
|
357 | In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain'] | |
353 |
|
358 | |||
354 | In [2]: %precision 5 |
|
359 | In [2]: %precision 5 | |
355 | Out[2]: {u}'%.5f' |
|
360 | Out[2]: {u}'%.5f' | |
356 |
|
361 | |||
357 | In [3]: f.float_format |
|
362 | In [3]: f.float_format | |
358 | Out[3]: {u}'%.5f' |
|
363 | Out[3]: {u}'%.5f' | |
359 |
|
364 | |||
360 | In [4]: %precision %e |
|
365 | In [4]: %precision %e | |
361 | Out[4]: {u}'%e' |
|
366 | Out[4]: {u}'%e' | |
362 |
|
367 | |||
363 | In [5]: f(3.1415927) |
|
368 | In [5]: f(3.1415927) | |
364 | Out[5]: {u}'3.141593e+00' |
|
369 | Out[5]: {u}'3.141593e+00' | |
365 | """ |
|
370 | """ | |
366 |
|
371 | |||
367 | def test_psearch(): |
|
372 | def test_psearch(): | |
368 | with tt.AssertPrints("dict.fromkeys"): |
|
373 | with tt.AssertPrints("dict.fromkeys"): | |
369 | _ip.run_cell("dict.fr*?") |
|
374 | _ip.run_cell("dict.fr*?") | |
370 |
|
375 | |||
371 | def test_timeit_shlex(): |
|
376 | def test_timeit_shlex(): | |
372 | """test shlex issues with timeit (#1109)""" |
|
377 | """test shlex issues with timeit (#1109)""" | |
373 | _ip.ex("def f(*a,**kw): pass") |
|
378 | _ip.ex("def f(*a,**kw): pass") | |
374 | _ip.magic('timeit -n1 "this is a bug".count(" ")') |
|
379 | _ip.magic('timeit -n1 "this is a bug".count(" ")') | |
375 | _ip.magic('timeit -r1 -n1 f(" ", 1)') |
|
380 | _ip.magic('timeit -r1 -n1 f(" ", 1)') | |
376 | _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")') |
|
381 | _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")') | |
377 | _ip.magic('timeit -r1 -n1 ("a " + "b")') |
|
382 | _ip.magic('timeit -r1 -n1 ("a " + "b")') | |
378 | _ip.magic('timeit -r1 -n1 f("a " + "b")') |
|
383 | _ip.magic('timeit -r1 -n1 f("a " + "b")') | |
379 | _ip.magic('timeit -r1 -n1 f("a " + "b ")') |
|
384 | _ip.magic('timeit -r1 -n1 f("a " + "b ")') | |
380 |
|
385 | |||
381 |
|
386 | |||
382 | def test_timeit_arguments(): |
|
387 | def test_timeit_arguments(): | |
383 | "Test valid timeit arguments, should not cause SyntaxError (GH #1269)" |
|
388 | "Test valid timeit arguments, should not cause SyntaxError (GH #1269)" | |
384 | _ip.magic("timeit ('#')") |
|
389 | _ip.magic("timeit ('#')") |
@@ -1,87 +1,89 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ IPython extension: add %clear magic """ |
|
2 | """ IPython extension: add %clear magic """ | |
3 |
|
3 | |||
4 | import gc |
|
4 | import gc | |
5 |
|
5 | |||
6 | def clear_f(self,arg): |
|
6 | def clear_f(self,arg): | |
7 | """ Clear various data (e.g. stored history data) |
|
7 | """ Clear various data (e.g. stored history data) | |
8 |
|
8 | |||
9 | %clear in - clear input history |
|
9 | %clear in - clear input history | |
10 | %clear out - clear output history |
|
10 | %clear out - clear output history | |
11 | %clear shadow_compress - Compresses shadow history (to speed up ipython) |
|
11 | %clear shadow_compress - Compresses shadow history (to speed up ipython) | |
12 | %clear shadow_nuke - permanently erase all entries in shadow history |
|
12 | %clear shadow_nuke - permanently erase all entries in shadow history | |
13 | %clear dhist - clear dir history |
|
13 | %clear dhist - clear dir history | |
14 | %clear array - clear only variables that are NumPy arrays |
|
14 | %clear array - clear only variables that are NumPy arrays | |
15 |
|
15 | |||
16 | Examples: |
|
16 | Examples: | |
17 |
|
17 | |||
18 | In [1]: clear in |
|
18 | In [1]: clear in | |
19 | Flushing input history |
|
19 | Flushing input history | |
20 |
|
20 | |||
21 | In [2]: clear shadow_compress |
|
21 | In [2]: clear shadow_compress | |
22 | Compressing shadow history |
|
22 | Compressing shadow history | |
23 |
|
23 | |||
24 | In [3]: clear shadow_nuke |
|
24 | In [3]: clear shadow_nuke | |
25 | Erased all keys from shadow history |
|
25 | Erased all keys from shadow history | |
26 |
|
26 | |||
27 | In [4]: clear dhist |
|
27 | In [4]: clear dhist | |
28 | Clearing directory history |
|
28 | Clearing directory history | |
29 | """ |
|
29 | """ | |
30 |
|
30 | |||
31 | ip = self.shell |
|
31 | ip = self.shell | |
32 | user_ns = self.user_ns # local lookup, heavily used |
|
32 | user_ns = self.user_ns # local lookup, heavily used | |
33 |
|
33 | |||
34 |
|
34 | |||
35 | for target in arg.split(): |
|
35 | for target in arg.split(): | |
36 |
|
36 | |||
37 | if target == 'out': |
|
37 | if target == 'out': | |
38 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) |
|
38 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) | |
39 | self.displayhook.flush() |
|
39 | self.displayhook.flush() | |
40 |
|
40 | |||
41 | elif target == 'in': |
|
41 | elif target == 'in': | |
42 | print "Flushing input history" |
|
42 | print "Flushing input history" | |
43 | pc = self.displayhook.prompt_count + 1 |
|
43 | pc = self.displayhook.prompt_count + 1 | |
44 | for n in range(1, pc): |
|
44 | for n in range(1, pc): | |
45 | key = '_i'+repr(n) |
|
45 | key = '_i'+repr(n) | |
46 | user_ns.pop(key,None) |
|
46 | user_ns.pop(key,None) | |
47 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) |
|
47 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) | |
48 | del self.history_manager.input_hist_parsed[:] |
|
48 | # don't delete these, as %save and %macro depending on the length | |
49 | del self.history_manager.input_hist_raw[:] |
|
49 | # of these lists to be preserved | |
|
50 | self.history_manager.input_hist_parsed[:] = [''] * pc | |||
|
51 | self.history_manager.input_hist_raw[:] = [''] * pc | |||
50 |
|
52 | |||
51 | elif target == 'array': |
|
53 | elif target == 'array': | |
52 | # Support cleaning up numpy arrays |
|
54 | # Support cleaning up numpy arrays | |
53 | try: |
|
55 | try: | |
54 | from numpy import ndarray |
|
56 | from numpy import ndarray | |
55 | # This must be done with items and not iteritems because we're |
|
57 | # This must be done with items and not iteritems because we're | |
56 | # going to modify the dict in-place. |
|
58 | # going to modify the dict in-place. | |
57 | for x,val in user_ns.items(): |
|
59 | for x,val in user_ns.items(): | |
58 | if isinstance(val,ndarray): |
|
60 | if isinstance(val,ndarray): | |
59 | del user_ns[x] |
|
61 | del user_ns[x] | |
60 | except ImportError: |
|
62 | except ImportError: | |
61 | print "Clear array only works if Numpy is available." |
|
63 | print "Clear array only works if Numpy is available." | |
62 |
|
64 | |||
63 | elif target == 'shadow_compress': |
|
65 | elif target == 'shadow_compress': | |
64 | print "Compressing shadow history" |
|
66 | print "Compressing shadow history" | |
65 | ip.db.hcompress('shadowhist') |
|
67 | ip.db.hcompress('shadowhist') | |
66 |
|
68 | |||
67 | elif target == 'shadow_nuke': |
|
69 | elif target == 'shadow_nuke': | |
68 | print "Erased all keys from shadow history " |
|
70 | print "Erased all keys from shadow history " | |
69 | for k in ip.db.keys('shadowhist/*'): |
|
71 | for k in ip.db.keys('shadowhist/*'): | |
70 | del ip.db[k] |
|
72 | del ip.db[k] | |
71 |
|
73 | |||
72 | elif target == 'dhist': |
|
74 | elif target == 'dhist': | |
73 | print "Clearing directory history" |
|
75 | print "Clearing directory history" | |
74 | del user_ns['_dh'][:] |
|
76 | del user_ns['_dh'][:] | |
75 |
|
77 | |||
76 | gc.collect() |
|
78 | gc.collect() | |
77 |
|
79 | |||
78 | _loaded = False |
|
80 | _loaded = False | |
79 |
|
81 | |||
80 | # Activate the extension |
|
82 | # Activate the extension | |
81 | def load_ipython_extension(ip): |
|
83 | def load_ipython_extension(ip): | |
82 | """Load the extension in IPython.""" |
|
84 | """Load the extension in IPython.""" | |
83 | global _loaded |
|
85 | global _loaded | |
84 | if not _loaded: |
|
86 | if not _loaded: | |
85 | ip.define_magic("clear",clear_f) |
|
87 | ip.define_magic("clear",clear_f) | |
86 | from IPython.core.completerlib import quick_completer |
|
88 | from IPython.core.completerlib import quick_completer | |
87 | quick_completer('%clear','in out array shadow_nuke shadow_compress dhist') |
|
89 | quick_completer('%clear','in out array shadow_nuke shadow_compress dhist') |
General Comments 0
You need to be logged in to leave comments.
Login now