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