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