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