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