##// END OF EJS Templates
Move tests for magics that are terminal-specific to their own file.
Fernando Perez -
Show More
@@ -0,0 +1,164 b''
1 """Tests for various magic functions specific to the terminal frontend.
2
3 Needs to be run by nose (to make ipython session available).
4 """
5 from __future__ import absolute_import
6
7 #-----------------------------------------------------------------------------
8 # Imports
9 #-----------------------------------------------------------------------------
10
11 import sys
12 from StringIO import StringIO
13
14 import nose.tools as nt
15
16 from IPython.testing import decorators as dec
17 from IPython.testing import tools as tt
18
19 #-----------------------------------------------------------------------------
20 # Test functions begin
21 #-----------------------------------------------------------------------------
22
23 def check_cpaste(code, should_fail=False):
24 """Execute code via 'cpaste' and ensure it was executed, unless
25 should_fail is set.
26 """
27 _ip.user_ns['code_ran'] = False
28
29 src = StringIO()
30 if not hasattr(src, 'encoding'):
31 # IPython expects stdin to have an encoding attribute
32 src.encoding = None
33 src.write('\n')
34 src.write(code)
35 src.write('\n--\n')
36 src.seek(0)
37
38 stdin_save = sys.stdin
39 sys.stdin = src
40
41 try:
42 context = tt.AssertPrints if should_fail else tt.AssertNotPrints
43 with context("Traceback (most recent call last)"):
44 _ip.magic('cpaste')
45
46 if not should_fail:
47 assert _ip.user_ns['code_ran']
48 finally:
49 sys.stdin = stdin_save
50
51
52 def test_cpaste():
53 """Test cpaste magic"""
54
55 def run():
56 """Marker function: sets a flag when executed.
57 """
58 _ip.user_ns['code_ran'] = True
59 return 'run' # return string so '+ run()' doesn't result in success
60
61 tests = {'pass': ["run()",
62 "In [1]: run()",
63 "In [1]: if 1:\n ...: run()",
64 "> > > run()",
65 ">>> run()",
66 " >>> run()",
67 ],
68
69 'fail': ["1 + run()",
70 "++ run()"]}
71
72 _ip.user_ns['run'] = run
73
74 for code in tests['pass']:
75 check_cpaste(code)
76
77 for code in tests['fail']:
78 check_cpaste(code, should_fail=True)
79
80
81 # Multiple tests for clipboard pasting
82 def test_paste():
83 _ip = get_ipython()
84
85 def paste(txt, flags='-q'):
86 """Paste input text, by default in quiet mode"""
87 hooks.clipboard_get = lambda : txt
88 _ip.magic('paste '+flags)
89
90 # Inject fake clipboard hook but save original so we can restore it later
91 hooks = _ip.hooks
92 user_ns = _ip.user_ns
93 original_clip = hooks.clipboard_get
94
95 try:
96 # Run tests with fake clipboard function
97 user_ns.pop('x', None)
98 paste('x=1')
99 nt.assert_equal(user_ns['x'], 1)
100
101 user_ns.pop('x', None)
102 paste('>>> x=2')
103 nt.assert_equal(user_ns['x'], 2)
104
105 paste("""
106 >>> x = [1,2,3]
107 >>> y = []
108 >>> for i in x:
109 ... y.append(i**2)
110 ...
111 """)
112 nt.assert_equal(user_ns['x'], [1,2,3])
113 nt.assert_equal(user_ns['y'], [1,4,9])
114
115 # Now, test that paste -r works
116 user_ns.pop('x', None)
117 nt.assert_false('x' in user_ns)
118 _ip.magic('paste -r')
119 nt.assert_equal(user_ns['x'], [1,2,3])
120
121 # Test pasting of email-quoted contents
122 paste("""
123 >> def foo(x):
124 >> return x + 1
125 >> x = foo(1.1)
126 """)
127 nt.assert_equal(user_ns['x'], 2.1)
128
129 # Email again; some programs add a space also at each quoting level
130 paste("""
131 > > def foo(x):
132 > > return x + 1
133 > > x = foo(2.1)
134 """)
135 nt.assert_equal(user_ns['x'], 3.1)
136
137 # Email quoting of interactive input
138 paste("""
139 >> >>> def f(x):
140 >> ... return x+1
141 >> ...
142 >> >>> x = f(2.5)
143 """)
144 nt.assert_equal(user_ns['x'], 3.5)
145
146 # Also test paste echoing, by temporarily faking the writer
147 w = StringIO()
148 writer = _ip.write
149 _ip.write = w.write
150 code = """
151 a = 100
152 b = 200"""
153 try:
154 paste(code,'')
155 out = w.getvalue()
156 finally:
157 _ip.write = writer
158 nt.assert_equal(user_ns['a'], 100)
159 nt.assert_equal(user_ns['b'], 200)
160 nt.assert_equal(out, code+"\n## -- End pasted text --\n")
161
162 finally:
163 # Restore original hook
164 hooks.clipboard_get = original_clip
@@ -1,463 +1,342 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 import sys
13 import tempfile
14 import types
15 from StringIO import StringIO
16
12
17 import nose.tools as nt
13 import nose.tools as nt
18
14
19 from IPython.utils.path import get_long_path_name
20 from IPython.testing import decorators as dec
15 from IPython.testing import decorators as dec
21 from IPython.testing import tools as tt
16 from IPython.testing import tools as tt
22 from IPython.utils import py3compat
17 from IPython.utils import py3compat
23
18
24 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
25 # Test functions begin
20 # Test functions begin
26 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
27 def test_rehashx():
23 def test_rehashx():
28 # clear up everything
24 # clear up everything
29 _ip = get_ipython()
25 _ip = get_ipython()
30 _ip.alias_manager.alias_table.clear()
26 _ip.alias_manager.alias_table.clear()
31 del _ip.db['syscmdlist']
27 del _ip.db['syscmdlist']
32
28
33 _ip.magic('rehashx')
29 _ip.magic('rehashx')
34 # Practically ALL ipython development systems will have more than 10 aliases
30 # Practically ALL ipython development systems will have more than 10 aliases
35
31
36 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
32 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
37 for key, val in _ip.alias_manager.alias_table.iteritems():
33 for key, val in _ip.alias_manager.alias_table.iteritems():
38 # we must strip dots from alias names
34 # we must strip dots from alias names
39 nt.assert_true('.' not in key)
35 nt.assert_true('.' not in key)
40
36
41 # rehashx must fill up syscmdlist
37 # rehashx must fill up syscmdlist
42 scoms = _ip.db['syscmdlist']
38 scoms = _ip.db['syscmdlist']
43 yield (nt.assert_true, len(scoms) > 10)
39 yield (nt.assert_true, len(scoms) > 10)
44
40
45
41
46 def test_magic_parse_options():
42 def test_magic_parse_options():
47 """Test that we don't mangle paths when parsing magic options."""
43 """Test that we don't mangle paths when parsing magic options."""
48 ip = get_ipython()
44 ip = get_ipython()
49 path = 'c:\\x'
45 path = 'c:\\x'
50 opts = ip.parse_options('-f %s' % path,'f:')[0]
46 opts = ip.parse_options('-f %s' % path,'f:')[0]
51 # argv splitting is os-dependent
47 # argv splitting is os-dependent
52 if os.name == 'posix':
48 if os.name == 'posix':
53 expected = 'c:x'
49 expected = 'c:x'
54 else:
50 else:
55 expected = path
51 expected = path
56 nt.assert_equals(opts['f'], expected)
52 nt.assert_equals(opts['f'], expected)
57
53
58
54
59 @dec.skip_without('sqlite3')
55 @dec.skip_without('sqlite3')
60 def doctest_hist_f():
56 def doctest_hist_f():
61 """Test %hist -f with temporary filename.
57 """Test %hist -f with temporary filename.
62
58
63 In [9]: import tempfile
59 In [9]: import tempfile
64
60
65 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
61 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
66
62
67 In [11]: %hist -nl -f $tfile 3
63 In [11]: %hist -nl -f $tfile 3
68
64
69 In [13]: import os; os.unlink(tfile)
65 In [13]: import os; os.unlink(tfile)
70 """
66 """
71
67
72
68
73 @dec.skip_without('sqlite3')
69 @dec.skip_without('sqlite3')
74 def doctest_hist_r():
70 def doctest_hist_r():
75 """Test %hist -r
71 """Test %hist -r
76
72
77 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
78 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.
79 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.
80
76
81 In [1]: 'hist' in _ip.lsmagic()
77 In [1]: 'hist' in _ip.lsmagic()
82 Out[1]: True
78 Out[1]: True
83
79
84 In [2]: x=1
80 In [2]: x=1
85
81
86 In [3]: %hist -rl 2
82 In [3]: %hist -rl 2
87 x=1 # random
83 x=1 # random
88 %hist -r 2
84 %hist -r 2
89 """
85 """
90
86
91
87
92 @dec.skip_without('sqlite3')
88 @dec.skip_without('sqlite3')
93 def doctest_hist_op():
89 def doctest_hist_op():
94 """Test %hist -op
90 """Test %hist -op
95
91
96 In [1]: class b(float):
92 In [1]: class b(float):
97 ...: pass
93 ...: pass
98 ...:
94 ...:
99
95
100 In [2]: class s(object):
96 In [2]: class s(object):
101 ...: def __str__(self):
97 ...: def __str__(self):
102 ...: return 's'
98 ...: return 's'
103 ...:
99 ...:
104
100
105 In [3]:
101 In [3]:
106
102
107 In [4]: class r(b):
103 In [4]: class r(b):
108 ...: def __repr__(self):
104 ...: def __repr__(self):
109 ...: return 'r'
105 ...: return 'r'
110 ...:
106 ...:
111
107
112 In [5]: class sr(s,r): pass
108 In [5]: class sr(s,r): pass
113 ...:
109 ...:
114
110
115 In [6]:
111 In [6]:
116
112
117 In [7]: bb=b()
113 In [7]: bb=b()
118
114
119 In [8]: ss=s()
115 In [8]: ss=s()
120
116
121 In [9]: rr=r()
117 In [9]: rr=r()
122
118
123 In [10]: ssrr=sr()
119 In [10]: ssrr=sr()
124
120
125 In [11]: 4.5
121 In [11]: 4.5
126 Out[11]: 4.5
122 Out[11]: 4.5
127
123
128 In [12]: str(ss)
124 In [12]: str(ss)
129 Out[12]: 's'
125 Out[12]: 's'
130
126
131 In [13]:
127 In [13]:
132
128
133 In [14]: %hist -op
129 In [14]: %hist -op
134 >>> class b:
130 >>> class b:
135 ... pass
131 ... pass
136 ...
132 ...
137 >>> class s(b):
133 >>> class s(b):
138 ... def __str__(self):
134 ... def __str__(self):
139 ... return 's'
135 ... return 's'
140 ...
136 ...
141 >>>
137 >>>
142 >>> class r(b):
138 >>> class r(b):
143 ... def __repr__(self):
139 ... def __repr__(self):
144 ... return 'r'
140 ... return 'r'
145 ...
141 ...
146 >>> class sr(s,r): pass
142 >>> class sr(s,r): pass
147 >>>
143 >>>
148 >>> bb=b()
144 >>> bb=b()
149 >>> ss=s()
145 >>> ss=s()
150 >>> rr=r()
146 >>> rr=r()
151 >>> ssrr=sr()
147 >>> ssrr=sr()
152 >>> 4.5
148 >>> 4.5
153 4.5
149 4.5
154 >>> str(ss)
150 >>> str(ss)
155 's'
151 's'
156 >>>
152 >>>
157 """
153 """
158
154
159
155
160 @dec.skip_without('sqlite3')
156 @dec.skip_without('sqlite3')
161 def test_macro():
157 def test_macro():
162 ip = get_ipython()
158 ip = get_ipython()
163 ip.history_manager.reset() # Clear any existing history.
159 ip.history_manager.reset() # Clear any existing history.
164 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())"]
165 for i, cmd in enumerate(cmds, start=1):
161 for i, cmd in enumerate(cmds, start=1):
166 ip.history_manager.store_inputs(i, cmd)
162 ip.history_manager.store_inputs(i, cmd)
167 ip.magic("macro test 1-3")
163 ip.magic("macro test 1-3")
168 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")
169
165
170 # List macros.
166 # List macros.
171 assert "test" in ip.magic("macro")
167 assert "test" in ip.magic("macro")
172
168
173
169
174 @dec.skip_without('sqlite3')
170 @dec.skip_without('sqlite3')
175 def test_macro_run():
171 def test_macro_run():
176 """Test that we can run a multi-line macro successfully."""
172 """Test that we can run a multi-line macro successfully."""
177 ip = get_ipython()
173 ip = get_ipython()
178 ip.history_manager.reset()
174 ip.history_manager.reset()
179 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
175 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
180 "%macro test 2-3"]
176 "%macro test 2-3"]
181 for cmd in cmds:
177 for cmd in cmds:
182 ip.run_cell(cmd, store_history=True)
178 ip.run_cell(cmd, store_history=True)
183 nt.assert_equal(ip.user_ns["test"].value,
179 nt.assert_equal(ip.user_ns["test"].value,
184 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
180 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
185 with tt.AssertPrints("12"):
181 with tt.AssertPrints("12"):
186 ip.run_cell("test")
182 ip.run_cell("test")
187 with tt.AssertPrints("13"):
183 with tt.AssertPrints("13"):
188 ip.run_cell("test")
184 ip.run_cell("test")
189
185
190
186
191 # XXX failing for now, until we get clearcmd out of quarantine. But we should
187 # XXX failing for now, until we get clearcmd out of quarantine. But we should
192 # fix this and revert the skip to happen only if numpy is not around.
188 # fix this and revert the skip to happen only if numpy is not around.
193 #@dec.skipif_not_numpy
189 #@dec.skipif_not_numpy
194 @dec.skip_known_failure
190 @dec.skip_known_failure
195 def test_numpy_clear_array_undec():
191 def test_numpy_clear_array_undec():
196 from IPython.extensions import clearcmd
192 from IPython.extensions import clearcmd
197
193
198 _ip.ex('import numpy as np')
194 _ip.ex('import numpy as np')
199 _ip.ex('a = np.empty(2)')
195 _ip.ex('a = np.empty(2)')
200 yield (nt.assert_true, 'a' in _ip.user_ns)
196 yield (nt.assert_true, 'a' in _ip.user_ns)
201 _ip.magic('clear array')
197 _ip.magic('clear array')
202 yield (nt.assert_false, 'a' in _ip.user_ns)
198 yield (nt.assert_false, 'a' in _ip.user_ns)
203
199
204
200
205 # Multiple tests for clipboard pasting
206 @dec.parametric
207 def test_paste():
208 _ip = get_ipython()
209 def paste(txt, flags='-q'):
210 """Paste input text, by default in quiet mode"""
211 hooks.clipboard_get = lambda : txt
212 _ip.magic('paste '+flags)
213
214 # Inject fake clipboard hook but save original so we can restore it later
215 hooks = _ip.hooks
216 user_ns = _ip.user_ns
217 original_clip = hooks.clipboard_get
218
219 try:
220 # Run tests with fake clipboard function
221 user_ns.pop('x', None)
222 paste('x=1')
223 yield nt.assert_equal(user_ns['x'], 1)
224
225 user_ns.pop('x', None)
226 paste('>>> x=2')
227 yield nt.assert_equal(user_ns['x'], 2)
228
229 paste("""
230 >>> x = [1,2,3]
231 >>> y = []
232 >>> for i in x:
233 ... y.append(i**2)
234 ...
235 """)
236 yield nt.assert_equal(user_ns['x'], [1,2,3])
237 yield nt.assert_equal(user_ns['y'], [1,4,9])
238
239 # Now, test that paste -r works
240 user_ns.pop('x', None)
241 yield nt.assert_false('x' in user_ns)
242 _ip.magic('paste -r')
243 yield nt.assert_equal(user_ns['x'], [1,2,3])
244
245 # Also test paste echoing, by temporarily faking the writer
246 w = StringIO()
247 writer = _ip.write
248 _ip.write = w.write
249 code = """
250 a = 100
251 b = 200"""
252 try:
253 paste(code,'')
254 out = w.getvalue()
255 finally:
256 _ip.write = writer
257 yield nt.assert_equal(user_ns['a'], 100)
258 yield nt.assert_equal(user_ns['b'], 200)
259 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
260
261 finally:
262 # Restore original hook
263 hooks.clipboard_get = original_clip
264
265
266 def test_time():
201 def test_time():
267 _ip.magic('time None')
202 _ip.magic('time None')
268
203
269
204
270 @py3compat.doctest_refactor_print
205 @py3compat.doctest_refactor_print
271 def doctest_time():
206 def doctest_time():
272 """
207 """
273 In [10]: %time None
208 In [10]: %time None
274 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
209 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
275 Wall time: 0.00 s
210 Wall time: 0.00 s
276
211
277 In [11]: def f(kmjy):
212 In [11]: def f(kmjy):
278 ....: %time print 2*kmjy
213 ....: %time print 2*kmjy
279
214
280 In [12]: f(3)
215 In [12]: f(3)
281 6
216 6
282 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
217 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
283 Wall time: 0.00 s
218 Wall time: 0.00 s
284 """
219 """
285
220
286
221
287 def test_doctest_mode():
222 def test_doctest_mode():
288 "Toggle doctest_mode twice, it should be a no-op and run without error"
223 "Toggle doctest_mode twice, it should be a no-op and run without error"
289 _ip.magic('doctest_mode')
224 _ip.magic('doctest_mode')
290 _ip.magic('doctest_mode')
225 _ip.magic('doctest_mode')
291
226
292
227
293 def test_parse_options():
228 def test_parse_options():
294 """Tests for basic options parsing in magics."""
229 """Tests for basic options parsing in magics."""
295 # These are only the most minimal of tests, more should be added later. At
230 # These are only the most minimal of tests, more should be added later. At
296 # the very least we check that basic text/unicode calls work OK.
231 # the very least we check that basic text/unicode calls work OK.
297 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
232 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
298 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
233 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
299
234
300
235
301 def test_dirops():
236 def test_dirops():
302 """Test various directory handling operations."""
237 """Test various directory handling operations."""
303 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
238 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
304 curpath = os.getcwdu
239 curpath = os.getcwdu
305 startdir = os.getcwdu()
240 startdir = os.getcwdu()
306 ipdir = _ip.ipython_dir
241 ipdir = _ip.ipython_dir
307 try:
242 try:
308 _ip.magic('cd "%s"' % ipdir)
243 _ip.magic('cd "%s"' % ipdir)
309 nt.assert_equal(curpath(), ipdir)
244 nt.assert_equal(curpath(), ipdir)
310 _ip.magic('cd -')
245 _ip.magic('cd -')
311 nt.assert_equal(curpath(), startdir)
246 nt.assert_equal(curpath(), startdir)
312 _ip.magic('pushd "%s"' % ipdir)
247 _ip.magic('pushd "%s"' % ipdir)
313 nt.assert_equal(curpath(), ipdir)
248 nt.assert_equal(curpath(), ipdir)
314 _ip.magic('popd')
249 _ip.magic('popd')
315 nt.assert_equal(curpath(), startdir)
250 nt.assert_equal(curpath(), startdir)
316 finally:
251 finally:
317 os.chdir(startdir)
252 os.chdir(startdir)
318
253
319
254
320 def check_cpaste(code, should_fail=False):
321 """Execute code via 'cpaste' and ensure it was executed, unless
322 should_fail is set.
323 """
324 _ip.user_ns['code_ran'] = False
325
326 src = StringIO()
327 if not hasattr(src, 'encoding'):
328 # IPython expects stdin to have an encoding attribute
329 src.encoding = None
330 src.write('\n')
331 src.write(code)
332 src.write('\n--\n')
333 src.seek(0)
334
335 stdin_save = sys.stdin
336 sys.stdin = src
337
338 try:
339 context = tt.AssertPrints if should_fail else tt.AssertNotPrints
340 with context("Traceback (most recent call last)"):
341 _ip.magic('cpaste')
342
343 if not should_fail:
344 assert _ip.user_ns['code_ran']
345 finally:
346 sys.stdin = stdin_save
347
348
349 def test_cpaste():
350 """Test cpaste magic"""
351
352 def run():
353 """Marker function: sets a flag when executed.
354 """
355 _ip.user_ns['code_ran'] = True
356 return 'run' # return string so '+ run()' doesn't result in success
357
358 tests = {'pass': ["run()",
359 "In [1]: run()",
360 "In [1]: if 1:\n ...: run()",
361 ">>> run()",
362 " >>> run()",
363 ],
364
365 'fail': ["1 + run()",
366 "++ run()"]}
367
368 _ip.user_ns['run'] = run
369
370 for code in tests['pass']:
371 check_cpaste(code)
372
373 for code in tests['fail']:
374 check_cpaste(code, should_fail=True)
375
376 def test_xmode():
255 def test_xmode():
377 # Calling xmode three times should be a no-op
256 # Calling xmode three times should be a no-op
378 xmode = _ip.InteractiveTB.mode
257 xmode = _ip.InteractiveTB.mode
379 for i in range(3):
258 for i in range(3):
380 _ip.magic("xmode")
259 _ip.magic("xmode")
381 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
260 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
382
261
383 def test_reset_hard():
262 def test_reset_hard():
384 monitor = []
263 monitor = []
385 class A(object):
264 class A(object):
386 def __del__(self):
265 def __del__(self):
387 monitor.append(1)
266 monitor.append(1)
388 def __repr__(self):
267 def __repr__(self):
389 return "<A instance>"
268 return "<A instance>"
390
269
391 _ip.user_ns["a"] = A()
270 _ip.user_ns["a"] = A()
392 _ip.run_cell("a")
271 _ip.run_cell("a")
393
272
394 nt.assert_equal(monitor, [])
273 nt.assert_equal(monitor, [])
395 _ip.magic_reset("-f")
274 _ip.magic_reset("-f")
396 nt.assert_equal(monitor, [1])
275 nt.assert_equal(monitor, [1])
397
276
398 class TestXdel(tt.TempFileMixin):
277 class TestXdel(tt.TempFileMixin):
399 def test_xdel(self):
278 def test_xdel(self):
400 """Test that references from %run are cleared by xdel."""
279 """Test that references from %run are cleared by xdel."""
401 src = ("class A(object):\n"
280 src = ("class A(object):\n"
402 " monitor = []\n"
281 " monitor = []\n"
403 " def __del__(self):\n"
282 " def __del__(self):\n"
404 " self.monitor.append(1)\n"
283 " self.monitor.append(1)\n"
405 "a = A()\n")
284 "a = A()\n")
406 self.mktmp(src)
285 self.mktmp(src)
407 # %run creates some hidden references...
286 # %run creates some hidden references...
408 _ip.magic("run %s" % self.fname)
287 _ip.magic("run %s" % self.fname)
409 # ... as does the displayhook.
288 # ... as does the displayhook.
410 _ip.run_cell("a")
289 _ip.run_cell("a")
411
290
412 monitor = _ip.user_ns["A"].monitor
291 monitor = _ip.user_ns["A"].monitor
413 nt.assert_equal(monitor, [])
292 nt.assert_equal(monitor, [])
414
293
415 _ip.magic("xdel a")
294 _ip.magic("xdel a")
416
295
417 # Check that a's __del__ method has been called.
296 # Check that a's __del__ method has been called.
418 nt.assert_equal(monitor, [1])
297 nt.assert_equal(monitor, [1])
419
298
420 def doctest_who():
299 def doctest_who():
421 """doctest for %who
300 """doctest for %who
422
301
423 In [1]: %reset -f
302 In [1]: %reset -f
424
303
425 In [2]: alpha = 123
304 In [2]: alpha = 123
426
305
427 In [3]: beta = 'beta'
306 In [3]: beta = 'beta'
428
307
429 In [4]: %who int
308 In [4]: %who int
430 alpha
309 alpha
431
310
432 In [5]: %who str
311 In [5]: %who str
433 beta
312 beta
434
313
435 In [6]: %whos
314 In [6]: %whos
436 Variable Type Data/Info
315 Variable Type Data/Info
437 ----------------------------
316 ----------------------------
438 alpha int 123
317 alpha int 123
439 beta str beta
318 beta str beta
440
319
441 In [7]: %who_ls
320 In [7]: %who_ls
442 Out[7]: ['alpha', 'beta']
321 Out[7]: ['alpha', 'beta']
443 """
322 """
444
323
445 @py3compat.u_format
324 @py3compat.u_format
446 def doctest_precision():
325 def doctest_precision():
447 """doctest for %precision
326 """doctest for %precision
448
327
449 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
328 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
450
329
451 In [2]: %precision 5
330 In [2]: %precision 5
452 Out[2]: {u}'%.5f'
331 Out[2]: {u}'%.5f'
453
332
454 In [3]: f.float_format
333 In [3]: f.float_format
455 Out[3]: {u}'%.5f'
334 Out[3]: {u}'%.5f'
456
335
457 In [4]: %precision %e
336 In [4]: %precision %e
458 Out[4]: {u}'%e'
337 Out[4]: {u}'%e'
459
338
460 In [5]: f(3.1415927)
339 In [5]: f(3.1415927)
461 Out[5]: {u}'3.141593e+00'
340 Out[5]: {u}'3.141593e+00'
462 """
341 """
463
342
General Comments 0
You need to be logged in to leave comments. Login now