##// END OF EJS Templates
Specify encoding for io.open in notebook_reformat tests.
Thomas Kluyver -
Show More
@@ -1,469 +1,469 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tests for various magic functions.
3 3
4 4 Needs to be run by nose (to make ipython session available).
5 5 """
6 6 from __future__ import absolute_import
7 7
8 8 #-----------------------------------------------------------------------------
9 9 # Imports
10 10 #-----------------------------------------------------------------------------
11 11
12 12 import io
13 13 import os
14 14 import sys
15 15 from StringIO import StringIO
16 16
17 17 import nose.tools as nt
18 18
19 19 from IPython.nbformat.v3.tests.nbexamples import nb0
20 20 from IPython.nbformat import current
21 21 from IPython.testing import decorators as dec
22 22 from IPython.testing import tools as tt
23 23 from IPython.utils import py3compat
24 24 from IPython.utils.tempdir import TemporaryDirectory
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Test functions begin
28 28 #-----------------------------------------------------------------------------
29 29
30 30
31 31 def test_rehashx():
32 32 # clear up everything
33 33 _ip = get_ipython()
34 34 _ip.alias_manager.alias_table.clear()
35 35 del _ip.db['syscmdlist']
36 36
37 37 _ip.magic('rehashx')
38 38 # Practically ALL ipython development systems will have more than 10 aliases
39 39
40 40 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
41 41 for key, val in _ip.alias_manager.alias_table.iteritems():
42 42 # we must strip dots from alias names
43 43 nt.assert_true('.' not in key)
44 44
45 45 # rehashx must fill up syscmdlist
46 46 scoms = _ip.db['syscmdlist']
47 47 yield (nt.assert_true, len(scoms) > 10)
48 48
49 49
50 50 def test_magic_parse_options():
51 51 """Test that we don't mangle paths when parsing magic options."""
52 52 ip = get_ipython()
53 53 path = 'c:\\x'
54 54 opts = ip.parse_options('-f %s' % path,'f:')[0]
55 55 # argv splitting is os-dependent
56 56 if os.name == 'posix':
57 57 expected = 'c:x'
58 58 else:
59 59 expected = path
60 60 nt.assert_equals(opts['f'], expected)
61 61
62 62
63 63 @dec.skip_without('sqlite3')
64 64 def doctest_hist_f():
65 65 """Test %hist -f with temporary filename.
66 66
67 67 In [9]: import tempfile
68 68
69 69 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
70 70
71 71 In [11]: %hist -nl -f $tfile 3
72 72
73 73 In [13]: import os; os.unlink(tfile)
74 74 """
75 75
76 76
77 77 @dec.skip_without('sqlite3')
78 78 def doctest_hist_r():
79 79 """Test %hist -r
80 80
81 81 XXX - This test is not recording the output correctly. For some reason, in
82 82 testing mode the raw history isn't getting populated. No idea why.
83 83 Disabling the output checking for now, though at least we do run it.
84 84
85 85 In [1]: 'hist' in _ip.lsmagic()
86 86 Out[1]: True
87 87
88 88 In [2]: x=1
89 89
90 90 In [3]: %hist -rl 2
91 91 x=1 # random
92 92 %hist -r 2
93 93 """
94 94
95 95
96 96 @dec.skip_without('sqlite3')
97 97 def doctest_hist_op():
98 98 """Test %hist -op
99 99
100 100 In [1]: class b(float):
101 101 ...: pass
102 102 ...:
103 103
104 104 In [2]: class s(object):
105 105 ...: def __str__(self):
106 106 ...: return 's'
107 107 ...:
108 108
109 109 In [3]:
110 110
111 111 In [4]: class r(b):
112 112 ...: def __repr__(self):
113 113 ...: return 'r'
114 114 ...:
115 115
116 116 In [5]: class sr(s,r): pass
117 117 ...:
118 118
119 119 In [6]:
120 120
121 121 In [7]: bb=b()
122 122
123 123 In [8]: ss=s()
124 124
125 125 In [9]: rr=r()
126 126
127 127 In [10]: ssrr=sr()
128 128
129 129 In [11]: 4.5
130 130 Out[11]: 4.5
131 131
132 132 In [12]: str(ss)
133 133 Out[12]: 's'
134 134
135 135 In [13]:
136 136
137 137 In [14]: %hist -op
138 138 >>> class b:
139 139 ... pass
140 140 ...
141 141 >>> class s(b):
142 142 ... def __str__(self):
143 143 ... return 's'
144 144 ...
145 145 >>>
146 146 >>> class r(b):
147 147 ... def __repr__(self):
148 148 ... return 'r'
149 149 ...
150 150 >>> class sr(s,r): pass
151 151 >>>
152 152 >>> bb=b()
153 153 >>> ss=s()
154 154 >>> rr=r()
155 155 >>> ssrr=sr()
156 156 >>> 4.5
157 157 4.5
158 158 >>> str(ss)
159 159 's'
160 160 >>>
161 161 """
162 162
163 163
164 164 @dec.skip_without('sqlite3')
165 165 def test_macro():
166 166 ip = get_ipython()
167 167 ip.history_manager.reset() # Clear any existing history.
168 168 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
169 169 for i, cmd in enumerate(cmds, start=1):
170 170 ip.history_manager.store_inputs(i, cmd)
171 171 ip.magic("macro test 1-3")
172 172 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
173 173
174 174 # List macros.
175 175 assert "test" in ip.magic("macro")
176 176
177 177
178 178 @dec.skip_without('sqlite3')
179 179 def test_macro_run():
180 180 """Test that we can run a multi-line macro successfully."""
181 181 ip = get_ipython()
182 182 ip.history_manager.reset()
183 183 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
184 184 "%macro test 2-3"]
185 185 for cmd in cmds:
186 186 ip.run_cell(cmd, store_history=True)
187 187 nt.assert_equal(ip.user_ns["test"].value,
188 188 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
189 189 with tt.AssertPrints("12"):
190 190 ip.run_cell("test")
191 191 with tt.AssertPrints("13"):
192 192 ip.run_cell("test")
193 193
194 194
195 195 @dec.skipif_not_numpy
196 196 def test_numpy_reset_array_undec():
197 197 "Test '%reset array' functionality"
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('reset -f array')
202 202 yield (nt.assert_false, 'a' in _ip.user_ns)
203 203
204 204 def test_reset_out():
205 205 "Test '%reset out' magic"
206 206 _ip.run_cell("parrot = 'dead'", store_history=True)
207 207 # test '%reset -f out', make an Out prompt
208 208 _ip.run_cell("parrot", store_history=True)
209 209 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
210 210 _ip.magic('reset -f out')
211 211 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
212 212 nt.assert_true(len(_ip.user_ns['Out']) == 0)
213 213
214 214 def test_reset_in():
215 215 "Test '%reset in' magic"
216 216 # test '%reset -f in'
217 217 _ip.run_cell("parrot", store_history=True)
218 218 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
219 219 _ip.magic('%reset -f in')
220 220 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
221 221 nt.assert_true(len(set(_ip.user_ns['In'])) == 1)
222 222
223 223 def test_reset_dhist():
224 224 "Test '%reset dhist' magic"
225 225 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
226 226 _ip.magic('cd ' + os.path.dirname(nt.__file__))
227 227 _ip.magic('cd -')
228 228 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
229 229 _ip.magic('reset -f dhist')
230 230 nt.assert_true(len(_ip.user_ns['_dh']) == 0)
231 231 _ip.run_cell("_dh = [d for d in tmp]") #restore
232 232
233 233 def test_reset_in_length():
234 234 "Test that '%reset in' preserves In[] length"
235 235 _ip.run_cell("print 'foo'")
236 236 _ip.run_cell("reset -f in")
237 237 nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1)
238 238
239 239 def test_time():
240 240 _ip.magic('time None')
241 241
242 242 def test_tb_syntaxerror():
243 243 """test %tb after a SyntaxError"""
244 244 ip = get_ipython()
245 245 ip.run_cell("for")
246 246
247 247 # trap and validate stdout
248 248 save_stdout = sys.stdout
249 249 try:
250 250 sys.stdout = StringIO()
251 251 ip.run_cell("%tb")
252 252 out = sys.stdout.getvalue()
253 253 finally:
254 254 sys.stdout = save_stdout
255 255 # trim output, and only check the last line
256 256 last_line = out.rstrip().splitlines()[-1].strip()
257 257 nt.assert_equals(last_line, "SyntaxError: invalid syntax")
258 258
259 259
260 260 @py3compat.doctest_refactor_print
261 261 def doctest_time():
262 262 """
263 263 In [10]: %time None
264 264 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
265 265 Wall time: 0.00 s
266 266
267 267 In [11]: def f(kmjy):
268 268 ....: %time print 2*kmjy
269 269
270 270 In [12]: f(3)
271 271 6
272 272 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
273 273 Wall time: 0.00 s
274 274 """
275 275
276 276
277 277 def test_doctest_mode():
278 278 "Toggle doctest_mode twice, it should be a no-op and run without error"
279 279 _ip.magic('doctest_mode')
280 280 _ip.magic('doctest_mode')
281 281
282 282
283 283 def test_parse_options():
284 284 """Tests for basic options parsing in magics."""
285 285 # These are only the most minimal of tests, more should be added later. At
286 286 # the very least we check that basic text/unicode calls work OK.
287 287 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
288 288 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
289 289
290 290
291 291 def test_dirops():
292 292 """Test various directory handling operations."""
293 293 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
294 294 curpath = os.getcwdu
295 295 startdir = os.getcwdu()
296 296 ipdir = os.path.realpath(_ip.ipython_dir)
297 297 try:
298 298 _ip.magic('cd "%s"' % ipdir)
299 299 nt.assert_equal(curpath(), ipdir)
300 300 _ip.magic('cd -')
301 301 nt.assert_equal(curpath(), startdir)
302 302 _ip.magic('pushd "%s"' % ipdir)
303 303 nt.assert_equal(curpath(), ipdir)
304 304 _ip.magic('popd')
305 305 nt.assert_equal(curpath(), startdir)
306 306 finally:
307 307 os.chdir(startdir)
308 308
309 309
310 310 def test_xmode():
311 311 # Calling xmode three times should be a no-op
312 312 xmode = _ip.InteractiveTB.mode
313 313 for i in range(3):
314 314 _ip.magic("xmode")
315 315 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
316 316
317 317 def test_reset_hard():
318 318 monitor = []
319 319 class A(object):
320 320 def __del__(self):
321 321 monitor.append(1)
322 322 def __repr__(self):
323 323 return "<A instance>"
324 324
325 325 _ip.user_ns["a"] = A()
326 326 _ip.run_cell("a")
327 327
328 328 nt.assert_equal(monitor, [])
329 329 _ip.magic_reset("-f")
330 330 nt.assert_equal(monitor, [1])
331 331
332 332 class TestXdel(tt.TempFileMixin):
333 333 def test_xdel(self):
334 334 """Test that references from %run are cleared by xdel."""
335 335 src = ("class A(object):\n"
336 336 " monitor = []\n"
337 337 " def __del__(self):\n"
338 338 " self.monitor.append(1)\n"
339 339 "a = A()\n")
340 340 self.mktmp(src)
341 341 # %run creates some hidden references...
342 342 _ip.magic("run %s" % self.fname)
343 343 # ... as does the displayhook.
344 344 _ip.run_cell("a")
345 345
346 346 monitor = _ip.user_ns["A"].monitor
347 347 nt.assert_equal(monitor, [])
348 348
349 349 _ip.magic("xdel a")
350 350
351 351 # Check that a's __del__ method has been called.
352 352 nt.assert_equal(monitor, [1])
353 353
354 354 def doctest_who():
355 355 """doctest for %who
356 356
357 357 In [1]: %reset -f
358 358
359 359 In [2]: alpha = 123
360 360
361 361 In [3]: beta = 'beta'
362 362
363 363 In [4]: %who int
364 364 alpha
365 365
366 366 In [5]: %who str
367 367 beta
368 368
369 369 In [6]: %whos
370 370 Variable Type Data/Info
371 371 ----------------------------
372 372 alpha int 123
373 373 beta str beta
374 374
375 375 In [7]: %who_ls
376 376 Out[7]: ['alpha', 'beta']
377 377 """
378 378
379 379 @py3compat.u_format
380 380 def doctest_precision():
381 381 """doctest for %precision
382 382
383 383 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
384 384
385 385 In [2]: %precision 5
386 386 Out[2]: {u}'%.5f'
387 387
388 388 In [3]: f.float_format
389 389 Out[3]: {u}'%.5f'
390 390
391 391 In [4]: %precision %e
392 392 Out[4]: {u}'%e'
393 393
394 394 In [5]: f(3.1415927)
395 395 Out[5]: {u}'3.141593e+00'
396 396 """
397 397
398 398 def test_psearch():
399 399 with tt.AssertPrints("dict.fromkeys"):
400 400 _ip.run_cell("dict.fr*?")
401 401
402 402 def test_timeit_shlex():
403 403 """test shlex issues with timeit (#1109)"""
404 404 _ip.ex("def f(*a,**kw): pass")
405 405 _ip.magic('timeit -n1 "this is a bug".count(" ")')
406 406 _ip.magic('timeit -r1 -n1 f(" ", 1)')
407 407 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
408 408 _ip.magic('timeit -r1 -n1 ("a " + "b")')
409 409 _ip.magic('timeit -r1 -n1 f("a " + "b")')
410 410 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
411 411
412 412
413 413 def test_timeit_arguments():
414 414 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
415 415 _ip.magic("timeit ('#')")
416 416
417 417 @dec.skipif(_ip.magic_prun == _ip.profile_missing_notice)
418 418 def test_prun_quotes():
419 419 "Test that prun does not clobber string escapes (GH #1302)"
420 420 _ip.magic("prun -q x = '\t'")
421 421 nt.assert_equal(_ip.user_ns['x'], '\t')
422 422
423 423 def test_extension():
424 424 tmpdir = TemporaryDirectory()
425 425 orig_ipython_dir = _ip.ipython_dir
426 426 try:
427 427 _ip.ipython_dir = tmpdir.name
428 428 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
429 429 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
430 430 _ip.magic("install_ext %s" % url)
431 431 _ip.user_ns.pop('arq', None)
432 432 _ip.magic("load_ext daft_extension")
433 433 tt.assert_equal(_ip.user_ns['arq'], 185)
434 434 _ip.magic("unload_ext daft_extension")
435 435 assert 'arq' not in _ip.user_ns
436 436 finally:
437 437 _ip.ipython_dir = orig_ipython_dir
438 438
439 439 def test_notebook_export_json():
440 440 with TemporaryDirectory() as td:
441 441 outfile = os.path.join(td, "nb.ipynb")
442 442 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
443 443 _ip.magic("notebook -e %s" % outfile)
444 444
445 445 def test_notebook_export_py():
446 446 with TemporaryDirectory() as td:
447 447 outfile = os.path.join(td, "nb.py")
448 448 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
449 449 _ip.magic("notebook -e %s" % outfile)
450 450
451 451 def test_notebook_reformat_py():
452 452 with TemporaryDirectory() as td:
453 453 infile = os.path.join(td, "nb.ipynb")
454 with io.open(infile, 'w') as f:
454 with io.open(infile, 'w', encoding='utf-8') as f:
455 455 current.write(nb0, f, 'json')
456 456
457 457 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
458 458 _ip.magic("notebook -f py %s" % infile)
459 459
460 460 def test_notebook_reformat_json():
461 461 with TemporaryDirectory() as td:
462 462 infile = os.path.join(td, "nb.py")
463 with io.open(infile, 'w') as f:
463 with io.open(infile, 'w', encoding='utf-8') as f:
464 464 current.write(nb0, f, 'py')
465 465
466 466 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
467 467 _ip.magic("notebook -f ipynb %s" % infile)
468 468 _ip.magic("notebook -f json %s" % infile)
469 469
General Comments 0
You need to be logged in to leave comments. Login now