##// END OF EJS Templates
update some test skips for removed packages
Min RK -
Show More
@@ -1,155 +1,152 b''
1 1 # Copyright (c) IPython Development Team.
2 2 # Distributed under the terms of the Modified BSD License.
3 3
4 4 import json
5 5 import os
6 6 import warnings
7 7
8 8 import nose.tools as nt
9 9
10 10 from IPython.core import display
11 11 from IPython.core.getipython import get_ipython
12 12 from IPython.utils import path as ipath
13 13
14 14 import IPython.testing.decorators as dec
15 15
16 16 def test_image_size():
17 17 """Simple test for display.Image(args, width=x,height=y)"""
18 18 thisurl = 'http://www.google.fr/images/srpr/logo3w.png'
19 19 img = display.Image(url=thisurl, width=200, height=200)
20 20 nt.assert_equal(u'<img src="%s" width="200" height="200"/>' % (thisurl), img._repr_html_())
21 21 img = display.Image(url=thisurl, width=200)
22 22 nt.assert_equal(u'<img src="%s" width="200"/>' % (thisurl), img._repr_html_())
23 23 img = display.Image(url=thisurl)
24 24 nt.assert_equal(u'<img src="%s"/>' % (thisurl), img._repr_html_())
25 25 img = display.Image(url=thisurl, unconfined=True)
26 26 nt.assert_equal(u'<img src="%s" class="unconfined"/>' % (thisurl), img._repr_html_())
27 27
28 28 def test_retina_png():
29 29 here = os.path.dirname(__file__)
30 30 img = display.Image(os.path.join(here, "2x2.png"), retina=True)
31 31 nt.assert_equal(img.height, 1)
32 32 nt.assert_equal(img.width, 1)
33 33 data, md = img._repr_png_()
34 34 nt.assert_equal(md['width'], 1)
35 35 nt.assert_equal(md['height'], 1)
36 36
37 37 def test_retina_jpeg():
38 38 here = os.path.dirname(__file__)
39 39 img = display.Image(os.path.join(here, "2x2.jpg"), retina=True)
40 40 nt.assert_equal(img.height, 1)
41 41 nt.assert_equal(img.width, 1)
42 42 data, md = img._repr_jpeg_()
43 43 nt.assert_equal(md['width'], 1)
44 44 nt.assert_equal(md['height'], 1)
45 45
46 46 def test_image_filename_defaults():
47 47 '''test format constraint, and validity of jpeg and png'''
48 48 tpath = ipath.get_ipython_package_dir()
49 49 nt.assert_raises(ValueError, display.Image, filename=os.path.join(tpath, 'testing/tests/badformat.gif'),
50 50 embed=True)
51 51 nt.assert_raises(ValueError, display.Image)
52 52 nt.assert_raises(ValueError, display.Image, data='this is not an image', format='badformat', embed=True)
53 from IPython.html import DEFAULT_STATIC_FILES_PATH
54 53 # check boths paths to allow packages to test at build and install time
55 imgfile = os.path.join(tpath, 'html/static/base/images/logo.png')
56 if not os.path.exists(imgfile):
57 imgfile = os.path.join(DEFAULT_STATIC_FILES_PATH, 'base/images/logo.png')
54 imgfile = os.path.join(tpath, 'core/tests/2x2.png')
58 55 img = display.Image(filename=imgfile)
59 56 nt.assert_equal('png', img.format)
60 57 nt.assert_is_not_none(img._repr_png_())
61 58 img = display.Image(filename=os.path.join(tpath, 'testing/tests/logo.jpg'), embed=False)
62 59 nt.assert_equal('jpeg', img.format)
63 60 nt.assert_is_none(img._repr_jpeg_())
64 61
65 62 def _get_inline_config():
66 63 from IPython.kernel.zmq.pylab.config import InlineBackend
67 64 return InlineBackend.instance()
68 65
69 66 @dec.skip_without('matplotlib')
70 67 def test_set_matplotlib_close():
71 68 cfg = _get_inline_config()
72 69 cfg.close_figures = False
73 70 display.set_matplotlib_close()
74 71 assert cfg.close_figures
75 72 display.set_matplotlib_close(False)
76 73 assert not cfg.close_figures
77 74
78 75 _fmt_mime_map = {
79 76 'png': 'image/png',
80 77 'jpeg': 'image/jpeg',
81 78 'pdf': 'application/pdf',
82 79 'retina': 'image/png',
83 80 'svg': 'image/svg+xml',
84 81 }
85 82
86 83 @dec.skip_without('matplotlib')
87 84 def test_set_matplotlib_formats():
88 85 from matplotlib.figure import Figure
89 86 formatters = get_ipython().display_formatter.formatters
90 87 for formats in [
91 88 ('png',),
92 89 ('pdf', 'svg'),
93 90 ('jpeg', 'retina', 'png'),
94 91 (),
95 92 ]:
96 93 active_mimes = {_fmt_mime_map[fmt] for fmt in formats}
97 94 display.set_matplotlib_formats(*formats)
98 95 for mime, f in formatters.items():
99 96 if mime in active_mimes:
100 97 nt.assert_in(Figure, f)
101 98 else:
102 99 nt.assert_not_in(Figure, f)
103 100
104 101 @dec.skip_without('matplotlib')
105 102 def test_set_matplotlib_formats_kwargs():
106 103 from matplotlib.figure import Figure
107 104 ip = get_ipython()
108 105 cfg = _get_inline_config()
109 106 cfg.print_figure_kwargs.update(dict(foo='bar'))
110 107 kwargs = dict(quality=10)
111 108 display.set_matplotlib_formats('png', **kwargs)
112 109 formatter = ip.display_formatter.formatters['image/png']
113 110 f = formatter.lookup_by_type(Figure)
114 111 cell = f.__closure__[0].cell_contents
115 112 expected = kwargs
116 113 expected.update(cfg.print_figure_kwargs)
117 114 nt.assert_equal(cell, expected)
118 115
119 116 def test_displayobject_repr():
120 117 h = display.HTML('<br />')
121 118 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
122 119 h._show_mem_addr = True
123 120 nt.assert_equal(repr(h), object.__repr__(h))
124 121 h._show_mem_addr = False
125 122 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
126 123
127 124 j = display.Javascript('')
128 125 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
129 126 j._show_mem_addr = True
130 127 nt.assert_equal(repr(j), object.__repr__(j))
131 128 j._show_mem_addr = False
132 129 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
133 130
134 131 def test_json():
135 132 d = {'a': 5}
136 133 lis = [d]
137 134 j = display.JSON(d)
138 135 nt.assert_equal(j._repr_json_(), d)
139 136
140 137 with warnings.catch_warnings(record=True) as w:
141 138 warnings.simplefilter("always")
142 139 j = display.JSON(json.dumps(d))
143 140 nt.assert_equal(len(w), 1)
144 141 nt.assert_equal(j._repr_json_(), d)
145 142
146 143 j = display.JSON(lis)
147 144 nt.assert_equal(j._repr_json_(), lis)
148 145
149 146 with warnings.catch_warnings(record=True) as w:
150 147 warnings.simplefilter("always")
151 148 j = display.JSON(json.dumps(lis))
152 149 nt.assert_equal(len(w), 1)
153 150 nt.assert_equal(j._repr_json_(), lis)
154 151
155 152
@@ -1,998 +1,996 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 import io
9 9 import os
10 10 import sys
11 11 import warnings
12 12 from unittest import TestCase, skipIf
13 13
14 14 try:
15 15 from importlib import invalidate_caches # Required from Python 3.3
16 16 except ImportError:
17 17 def invalidate_caches():
18 18 pass
19 19
20 20 import nose.tools as nt
21 21
22 22 from IPython import get_ipython
23 23 from IPython.core import magic
24 24 from IPython.core.error import UsageError
25 25 from IPython.core.magic import (Magics, magics_class, line_magic,
26 26 cell_magic, line_cell_magic,
27 27 register_line_magic, register_cell_magic,
28 28 register_line_cell_magic)
29 29 from IPython.core.magics import execution, script, code
30 30 from IPython.testing import decorators as dec
31 31 from IPython.testing import tools as tt
32 32 from IPython.utils import py3compat
33 33 from IPython.utils.io import capture_output
34 34 from IPython.utils.tempdir import TemporaryDirectory
35 35 from IPython.utils.process import find_cmd
36 36
37 37 if py3compat.PY3:
38 38 from io import StringIO
39 39 else:
40 40 from StringIO import StringIO
41 41
42 42
43 43 @magic.magics_class
44 44 class DummyMagics(magic.Magics): pass
45 45
46 46 def test_extract_code_ranges():
47 47 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
48 48 expected = [(0, 1),
49 49 (2, 3),
50 50 (4, 6),
51 51 (6, 9),
52 52 (9, 14),
53 53 (16, None),
54 54 (None, 9),
55 55 (9, None),
56 56 (None, 13),
57 57 (None, None)]
58 58 actual = list(code.extract_code_ranges(instr))
59 59 nt.assert_equal(actual, expected)
60 60
61 61 def test_extract_symbols():
62 62 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
63 63 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
64 64 expected = [([], ['a']),
65 65 (["def b():\n return 42\n"], []),
66 66 (["class A: pass\n"], []),
67 67 (["class A: pass\n", "def b():\n return 42\n"], []),
68 68 (["class A: pass\n"], ['a']),
69 69 ([], ['z'])]
70 70 for symbols, exp in zip(symbols_args, expected):
71 71 nt.assert_equal(code.extract_symbols(source, symbols), exp)
72 72
73 73
74 74 def test_extract_symbols_raises_exception_with_non_python_code():
75 75 source = ("=begin A Ruby program :)=end\n"
76 76 "def hello\n"
77 77 "puts 'Hello world'\n"
78 78 "end")
79 79 with nt.assert_raises(SyntaxError):
80 80 code.extract_symbols(source, "hello")
81 81
82 82 def test_config():
83 83 """ test that config magic does not raise
84 84 can happen if Configurable init is moved too early into
85 85 Magics.__init__ as then a Config object will be registerd as a
86 86 magic.
87 87 """
88 88 ## should not raise.
89 89 _ip.magic('config')
90 90
91 91 def test_rehashx():
92 92 # clear up everything
93 93 _ip = get_ipython()
94 94 _ip.alias_manager.clear_aliases()
95 95 del _ip.db['syscmdlist']
96 96
97 97 _ip.magic('rehashx')
98 98 # Practically ALL ipython development systems will have more than 10 aliases
99 99
100 100 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
101 101 for name, cmd in _ip.alias_manager.aliases:
102 102 # we must strip dots from alias names
103 103 nt.assert_not_in('.', name)
104 104
105 105 # rehashx must fill up syscmdlist
106 106 scoms = _ip.db['syscmdlist']
107 107 nt.assert_true(len(scoms) > 10)
108 108
109 109
110 110 def test_magic_parse_options():
111 111 """Test that we don't mangle paths when parsing magic options."""
112 112 ip = get_ipython()
113 113 path = 'c:\\x'
114 114 m = DummyMagics(ip)
115 115 opts = m.parse_options('-f %s' % path,'f:')[0]
116 116 # argv splitting is os-dependent
117 117 if os.name == 'posix':
118 118 expected = 'c:x'
119 119 else:
120 120 expected = path
121 121 nt.assert_equal(opts['f'], expected)
122 122
123 123 def test_magic_parse_long_options():
124 124 """Magic.parse_options can handle --foo=bar long options"""
125 125 ip = get_ipython()
126 126 m = DummyMagics(ip)
127 127 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
128 128 nt.assert_in('foo', opts)
129 129 nt.assert_in('bar', opts)
130 130 nt.assert_equal(opts['bar'], "bubble")
131 131
132 132
133 133 @dec.skip_without('sqlite3')
134 134 def doctest_hist_f():
135 135 """Test %hist -f with temporary filename.
136 136
137 137 In [9]: import tempfile
138 138
139 139 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
140 140
141 141 In [11]: %hist -nl -f $tfile 3
142 142
143 143 In [13]: import os; os.unlink(tfile)
144 144 """
145 145
146 146
147 147 @dec.skip_without('sqlite3')
148 148 def doctest_hist_r():
149 149 """Test %hist -r
150 150
151 151 XXX - This test is not recording the output correctly. For some reason, in
152 152 testing mode the raw history isn't getting populated. No idea why.
153 153 Disabling the output checking for now, though at least we do run it.
154 154
155 155 In [1]: 'hist' in _ip.lsmagic()
156 156 Out[1]: True
157 157
158 158 In [2]: x=1
159 159
160 160 In [3]: %hist -rl 2
161 161 x=1 # random
162 162 %hist -r 2
163 163 """
164 164
165 165
166 166 @dec.skip_without('sqlite3')
167 167 def doctest_hist_op():
168 168 """Test %hist -op
169 169
170 170 In [1]: class b(float):
171 171 ...: pass
172 172 ...:
173 173
174 174 In [2]: class s(object):
175 175 ...: def __str__(self):
176 176 ...: return 's'
177 177 ...:
178 178
179 179 In [3]:
180 180
181 181 In [4]: class r(b):
182 182 ...: def __repr__(self):
183 183 ...: return 'r'
184 184 ...:
185 185
186 186 In [5]: class sr(s,r): pass
187 187 ...:
188 188
189 189 In [6]:
190 190
191 191 In [7]: bb=b()
192 192
193 193 In [8]: ss=s()
194 194
195 195 In [9]: rr=r()
196 196
197 197 In [10]: ssrr=sr()
198 198
199 199 In [11]: 4.5
200 200 Out[11]: 4.5
201 201
202 202 In [12]: str(ss)
203 203 Out[12]: 's'
204 204
205 205 In [13]:
206 206
207 207 In [14]: %hist -op
208 208 >>> class b:
209 209 ... pass
210 210 ...
211 211 >>> class s(b):
212 212 ... def __str__(self):
213 213 ... return 's'
214 214 ...
215 215 >>>
216 216 >>> class r(b):
217 217 ... def __repr__(self):
218 218 ... return 'r'
219 219 ...
220 220 >>> class sr(s,r): pass
221 221 >>>
222 222 >>> bb=b()
223 223 >>> ss=s()
224 224 >>> rr=r()
225 225 >>> ssrr=sr()
226 226 >>> 4.5
227 227 4.5
228 228 >>> str(ss)
229 229 's'
230 230 >>>
231 231 """
232 232
233 233 def test_hist_pof():
234 234 ip = get_ipython()
235 235 ip.run_cell(u"1+2", store_history=True)
236 236 #raise Exception(ip.history_manager.session_number)
237 237 #raise Exception(list(ip.history_manager._get_range_session()))
238 238 with TemporaryDirectory() as td:
239 239 tf = os.path.join(td, 'hist.py')
240 240 ip.run_line_magic('history', '-pof %s' % tf)
241 241 assert os.path.isfile(tf)
242 242
243 243
244 244 @dec.skip_without('sqlite3')
245 245 def test_macro():
246 246 ip = get_ipython()
247 247 ip.history_manager.reset() # Clear any existing history.
248 248 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
249 249 for i, cmd in enumerate(cmds, start=1):
250 250 ip.history_manager.store_inputs(i, cmd)
251 251 ip.magic("macro test 1-3")
252 252 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
253 253
254 254 # List macros
255 255 nt.assert_in("test", ip.magic("macro"))
256 256
257 257
258 258 @dec.skip_without('sqlite3')
259 259 def test_macro_run():
260 260 """Test that we can run a multi-line macro successfully."""
261 261 ip = get_ipython()
262 262 ip.history_manager.reset()
263 263 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
264 264 "%macro test 2-3"]
265 265 for cmd in cmds:
266 266 ip.run_cell(cmd, store_history=True)
267 267 nt.assert_equal(ip.user_ns["test"].value,
268 268 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
269 269 with tt.AssertPrints("12"):
270 270 ip.run_cell("test")
271 271 with tt.AssertPrints("13"):
272 272 ip.run_cell("test")
273 273
274 274
275 275 def test_magic_magic():
276 276 """Test %magic"""
277 277 ip = get_ipython()
278 278 with capture_output() as captured:
279 279 ip.magic("magic")
280 280
281 281 stdout = captured.stdout
282 282 nt.assert_in('%magic', stdout)
283 283 nt.assert_in('IPython', stdout)
284 284 nt.assert_in('Available', stdout)
285 285
286 286
287 287 @dec.skipif_not_numpy
288 288 def test_numpy_reset_array_undec():
289 289 "Test '%reset array' functionality"
290 290 _ip.ex('import numpy as np')
291 291 _ip.ex('a = np.empty(2)')
292 292 nt.assert_in('a', _ip.user_ns)
293 293 _ip.magic('reset -f array')
294 294 nt.assert_not_in('a', _ip.user_ns)
295 295
296 296 def test_reset_out():
297 297 "Test '%reset out' magic"
298 298 _ip.run_cell("parrot = 'dead'", store_history=True)
299 299 # test '%reset -f out', make an Out prompt
300 300 _ip.run_cell("parrot", store_history=True)
301 301 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
302 302 _ip.magic('reset -f out')
303 303 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
304 304 nt.assert_equal(len(_ip.user_ns['Out']), 0)
305 305
306 306 def test_reset_in():
307 307 "Test '%reset in' magic"
308 308 # test '%reset -f in'
309 309 _ip.run_cell("parrot", store_history=True)
310 310 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
311 311 _ip.magic('%reset -f in')
312 312 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
313 313 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
314 314
315 315 def test_reset_dhist():
316 316 "Test '%reset dhist' magic"
317 317 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
318 318 _ip.magic('cd ' + os.path.dirname(nt.__file__))
319 319 _ip.magic('cd -')
320 320 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
321 321 _ip.magic('reset -f dhist')
322 322 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
323 323 _ip.run_cell("_dh = [d for d in tmp]") #restore
324 324
325 325 def test_reset_in_length():
326 326 "Test that '%reset in' preserves In[] length"
327 327 _ip.run_cell("print 'foo'")
328 328 _ip.run_cell("reset -f in")
329 329 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
330 330
331 331 def test_tb_syntaxerror():
332 332 """test %tb after a SyntaxError"""
333 333 ip = get_ipython()
334 334 ip.run_cell("for")
335 335
336 336 # trap and validate stdout
337 337 save_stdout = sys.stdout
338 338 try:
339 339 sys.stdout = StringIO()
340 340 ip.run_cell("%tb")
341 341 out = sys.stdout.getvalue()
342 342 finally:
343 343 sys.stdout = save_stdout
344 344 # trim output, and only check the last line
345 345 last_line = out.rstrip().splitlines()[-1].strip()
346 346 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
347 347
348 348
349 349 def test_time():
350 350 ip = get_ipython()
351 351
352 352 with tt.AssertPrints("Wall time: "):
353 353 ip.run_cell("%time None")
354 354
355 355 ip.run_cell("def f(kmjy):\n"
356 356 " %time print (2*kmjy)")
357 357
358 358 with tt.AssertPrints("Wall time: "):
359 359 with tt.AssertPrints("hihi", suppress=False):
360 360 ip.run_cell("f('hi')")
361 361
362 362
363 363 @dec.skip_win32
364 364 def test_time2():
365 365 ip = get_ipython()
366 366
367 367 with tt.AssertPrints("CPU times: user "):
368 368 ip.run_cell("%time None")
369 369
370 370 def test_time3():
371 371 """Erroneous magic function calls, issue gh-3334"""
372 372 ip = get_ipython()
373 373 ip.user_ns.pop('run', None)
374 374
375 375 with tt.AssertNotPrints("not found", channel='stderr'):
376 376 ip.run_cell("%%time\n"
377 377 "run = 0\n"
378 378 "run += 1")
379 379
380 380 @dec.skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
381 381 def test_time_futures():
382 382 "Test %time with __future__ environments"
383 383 ip = get_ipython()
384 384 ip.autocall = 0
385 385 ip.run_cell("from __future__ import division")
386 386 with tt.AssertPrints('0.25'):
387 387 ip.run_line_magic('time', 'print(1/4)')
388 388 ip.compile.reset_compiler_flags()
389 389 with tt.AssertNotPrints('0.25'):
390 390 ip.run_line_magic('time', 'print(1/4)')
391 391
392 392 def test_doctest_mode():
393 393 "Toggle doctest_mode twice, it should be a no-op and run without error"
394 394 _ip.magic('doctest_mode')
395 395 _ip.magic('doctest_mode')
396 396
397 397
398 398 def test_parse_options():
399 399 """Tests for basic options parsing in magics."""
400 400 # These are only the most minimal of tests, more should be added later. At
401 401 # the very least we check that basic text/unicode calls work OK.
402 402 m = DummyMagics(_ip)
403 403 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
404 404 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
405 405
406 406
407 407 def test_dirops():
408 408 """Test various directory handling operations."""
409 409 # curpath = lambda :os.path.splitdrive(py3compat.getcwd())[1].replace('\\','/')
410 410 curpath = py3compat.getcwd
411 411 startdir = py3compat.getcwd()
412 412 ipdir = os.path.realpath(_ip.ipython_dir)
413 413 try:
414 414 _ip.magic('cd "%s"' % ipdir)
415 415 nt.assert_equal(curpath(), ipdir)
416 416 _ip.magic('cd -')
417 417 nt.assert_equal(curpath(), startdir)
418 418 _ip.magic('pushd "%s"' % ipdir)
419 419 nt.assert_equal(curpath(), ipdir)
420 420 _ip.magic('popd')
421 421 nt.assert_equal(curpath(), startdir)
422 422 finally:
423 423 os.chdir(startdir)
424 424
425 425
426 426 def test_xmode():
427 427 # Calling xmode three times should be a no-op
428 428 xmode = _ip.InteractiveTB.mode
429 429 for i in range(3):
430 430 _ip.magic("xmode")
431 431 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
432 432
433 433 def test_reset_hard():
434 434 monitor = []
435 435 class A(object):
436 436 def __del__(self):
437 437 monitor.append(1)
438 438 def __repr__(self):
439 439 return "<A instance>"
440 440
441 441 _ip.user_ns["a"] = A()
442 442 _ip.run_cell("a")
443 443
444 444 nt.assert_equal(monitor, [])
445 445 _ip.magic("reset -f")
446 446 nt.assert_equal(monitor, [1])
447 447
448 448 class TestXdel(tt.TempFileMixin):
449 449 def test_xdel(self):
450 450 """Test that references from %run are cleared by xdel."""
451 451 src = ("class A(object):\n"
452 452 " monitor = []\n"
453 453 " def __del__(self):\n"
454 454 " self.monitor.append(1)\n"
455 455 "a = A()\n")
456 456 self.mktmp(src)
457 457 # %run creates some hidden references...
458 458 _ip.magic("run %s" % self.fname)
459 459 # ... as does the displayhook.
460 460 _ip.run_cell("a")
461 461
462 462 monitor = _ip.user_ns["A"].monitor
463 463 nt.assert_equal(monitor, [])
464 464
465 465 _ip.magic("xdel a")
466 466
467 467 # Check that a's __del__ method has been called.
468 468 nt.assert_equal(monitor, [1])
469 469
470 470 def doctest_who():
471 471 """doctest for %who
472 472
473 473 In [1]: %reset -f
474 474
475 475 In [2]: alpha = 123
476 476
477 477 In [3]: beta = 'beta'
478 478
479 479 In [4]: %who int
480 480 alpha
481 481
482 482 In [5]: %who str
483 483 beta
484 484
485 485 In [6]: %whos
486 486 Variable Type Data/Info
487 487 ----------------------------
488 488 alpha int 123
489 489 beta str beta
490 490
491 491 In [7]: %who_ls
492 492 Out[7]: ['alpha', 'beta']
493 493 """
494 494
495 495 def test_whos():
496 496 """Check that whos is protected against objects where repr() fails."""
497 497 class A(object):
498 498 def __repr__(self):
499 499 raise Exception()
500 500 _ip.user_ns['a'] = A()
501 501 _ip.magic("whos")
502 502
503 503 @py3compat.u_format
504 504 def doctest_precision():
505 505 """doctest for %precision
506 506
507 507 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
508 508
509 509 In [2]: %precision 5
510 510 Out[2]: {u}'%.5f'
511 511
512 512 In [3]: f.float_format
513 513 Out[3]: {u}'%.5f'
514 514
515 515 In [4]: %precision %e
516 516 Out[4]: {u}'%e'
517 517
518 518 In [5]: f(3.1415927)
519 519 Out[5]: {u}'3.141593e+00'
520 520 """
521 521
522 522 def test_psearch():
523 523 with tt.AssertPrints("dict.fromkeys"):
524 524 _ip.run_cell("dict.fr*?")
525 525
526 526 def test_timeit_shlex():
527 527 """test shlex issues with timeit (#1109)"""
528 528 _ip.ex("def f(*a,**kw): pass")
529 529 _ip.magic('timeit -n1 "this is a bug".count(" ")')
530 530 _ip.magic('timeit -r1 -n1 f(" ", 1)')
531 531 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
532 532 _ip.magic('timeit -r1 -n1 ("a " + "b")')
533 533 _ip.magic('timeit -r1 -n1 f("a " + "b")')
534 534 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
535 535
536 536
537 537 def test_timeit_arguments():
538 538 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
539 539 _ip.magic("timeit ('#')")
540 540
541 541
542 542 def test_timeit_special_syntax():
543 543 "Test %%timeit with IPython special syntax"
544 544 @register_line_magic
545 545 def lmagic(line):
546 546 ip = get_ipython()
547 547 ip.user_ns['lmagic_out'] = line
548 548
549 549 # line mode test
550 550 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
551 551 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
552 552 # cell mode test
553 553 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
554 554 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
555 555
556 556 def test_timeit_return():
557 557 """
558 558 test wether timeit -o return object
559 559 """
560 560
561 561 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
562 562 assert(res is not None)
563 563
564 564 def test_timeit_quiet():
565 565 """
566 566 test quiet option of timeit magic
567 567 """
568 568 with tt.AssertNotPrints("loops"):
569 569 _ip.run_cell("%timeit -n1 -r1 -q 1")
570 570
571 571 @dec.skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
572 572 def test_timeit_futures():
573 573 "Test %timeit with __future__ environments"
574 574 ip = get_ipython()
575 575 ip.run_cell("from __future__ import division")
576 576 with tt.AssertPrints('0.25'):
577 577 ip.run_line_magic('timeit', '-n1 -r1 print(1/4)')
578 578 ip.compile.reset_compiler_flags()
579 579 with tt.AssertNotPrints('0.25'):
580 580 ip.run_line_magic('timeit', '-n1 -r1 print(1/4)')
581 581
582 582 @dec.skipif(execution.profile is None)
583 583 def test_prun_special_syntax():
584 584 "Test %%prun with IPython special syntax"
585 585 @register_line_magic
586 586 def lmagic(line):
587 587 ip = get_ipython()
588 588 ip.user_ns['lmagic_out'] = line
589 589
590 590 # line mode test
591 591 _ip.run_line_magic('prun', '-q %lmagic my line')
592 592 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
593 593 # cell mode test
594 594 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
595 595 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
596 596
597 597 @dec.skipif(execution.profile is None)
598 598 def test_prun_quotes():
599 599 "Test that prun does not clobber string escapes (GH #1302)"
600 600 _ip.magic(r"prun -q x = '\t'")
601 601 nt.assert_equal(_ip.user_ns['x'], '\t')
602 602
603 603 def test_extension():
604 604 tmpdir = TemporaryDirectory()
605 605 orig_ipython_dir = _ip.ipython_dir
606 606 try:
607 607 _ip.ipython_dir = tmpdir.name
608 608 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
609 609 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
610 610 _ip.magic("install_ext %s" % url)
611 611 _ip.user_ns.pop('arq', None)
612 612 invalidate_caches() # Clear import caches
613 613 _ip.magic("load_ext daft_extension")
614 614 nt.assert_equal(_ip.user_ns['arq'], 185)
615 615 _ip.magic("unload_ext daft_extension")
616 616 assert 'arq' not in _ip.user_ns
617 617 finally:
618 618 _ip.ipython_dir = orig_ipython_dir
619 619 tmpdir.cleanup()
620 620
621 621
622 # The nose skip decorator doesn't work on classes, so this uses unittest's skipIf
623 @skipIf(dec.module_not_available('IPython.nbformat'), 'nbformat not importable')
624 class NotebookExportMagicTests(TestCase):
625 def test_notebook_export_json(self):
626 _ip = get_ipython()
627 _ip.history_manager.reset() # Clear any existing history.
628 cmds = [u"a=1", u"def b():\n return a**2", u"print('noël, été', b())"]
629 for i, cmd in enumerate(cmds, start=1):
630 _ip.history_manager.store_inputs(i, cmd)
631 with TemporaryDirectory() as td:
632 outfile = os.path.join(td, "nb.ipynb")
633 _ip.magic("notebook -e %s" % outfile)
622 @dec.skip_without('jupyter_nbformat')
623 def test_notebook_export_json():
624 _ip = get_ipython()
625 _ip.history_manager.reset() # Clear any existing history.
626 cmds = [u"a=1", u"def b():\n return a**2", u"print('noël, été', b())"]
627 for i, cmd in enumerate(cmds, start=1):
628 _ip.history_manager.store_inputs(i, cmd)
629 with TemporaryDirectory() as td:
630 outfile = os.path.join(td, "nb.ipynb")
631 _ip.magic("notebook -e %s" % outfile)
634 632
635 633
636 634 class TestEnv(TestCase):
637 635
638 636 def test_env(self):
639 637 env = _ip.magic("env")
640 638 self.assertTrue(isinstance(env, dict))
641 639
642 640 def test_env_get_set_simple(self):
643 641 env = _ip.magic("env var val1")
644 642 self.assertEqual(env, None)
645 643 self.assertEqual(os.environ['var'], 'val1')
646 644 self.assertEqual(_ip.magic("env var"), 'val1')
647 645 env = _ip.magic("env var=val2")
648 646 self.assertEqual(env, None)
649 647 self.assertEqual(os.environ['var'], 'val2')
650 648
651 649 def test_env_get_set_complex(self):
652 650 env = _ip.magic("env var 'val1 '' 'val2")
653 651 self.assertEqual(env, None)
654 652 self.assertEqual(os.environ['var'], "'val1 '' 'val2")
655 653 self.assertEqual(_ip.magic("env var"), "'val1 '' 'val2")
656 654 env = _ip.magic('env var=val2 val3="val4')
657 655 self.assertEqual(env, None)
658 656 self.assertEqual(os.environ['var'], 'val2 val3="val4')
659 657
660 658 def test_env_set_bad_input(self):
661 659 self.assertRaises(UsageError, lambda: _ip.magic("set_env var"))
662 660
663 661 def test_env_set_whitespace(self):
664 662 self.assertRaises(UsageError, lambda: _ip.magic("env var A=B"))
665 663
666 664
667 665 class CellMagicTestCase(TestCase):
668 666
669 667 def check_ident(self, magic):
670 668 # Manually called, we get the result
671 669 out = _ip.run_cell_magic(magic, 'a', 'b')
672 670 nt.assert_equal(out, ('a','b'))
673 671 # Via run_cell, it goes into the user's namespace via displayhook
674 672 _ip.run_cell('%%' + magic +' c\nd')
675 673 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
676 674
677 675 def test_cell_magic_func_deco(self):
678 676 "Cell magic using simple decorator"
679 677 @register_cell_magic
680 678 def cellm(line, cell):
681 679 return line, cell
682 680
683 681 self.check_ident('cellm')
684 682
685 683 def test_cell_magic_reg(self):
686 684 "Cell magic manually registered"
687 685 def cellm(line, cell):
688 686 return line, cell
689 687
690 688 _ip.register_magic_function(cellm, 'cell', 'cellm2')
691 689 self.check_ident('cellm2')
692 690
693 691 def test_cell_magic_class(self):
694 692 "Cell magics declared via a class"
695 693 @magics_class
696 694 class MyMagics(Magics):
697 695
698 696 @cell_magic
699 697 def cellm3(self, line, cell):
700 698 return line, cell
701 699
702 700 _ip.register_magics(MyMagics)
703 701 self.check_ident('cellm3')
704 702
705 703 def test_cell_magic_class2(self):
706 704 "Cell magics declared via a class, #2"
707 705 @magics_class
708 706 class MyMagics2(Magics):
709 707
710 708 @cell_magic('cellm4')
711 709 def cellm33(self, line, cell):
712 710 return line, cell
713 711
714 712 _ip.register_magics(MyMagics2)
715 713 self.check_ident('cellm4')
716 714 # Check that nothing is registered as 'cellm33'
717 715 c33 = _ip.find_cell_magic('cellm33')
718 716 nt.assert_equal(c33, None)
719 717
720 718 def test_file():
721 719 """Basic %%file"""
722 720 ip = get_ipython()
723 721 with TemporaryDirectory() as td:
724 722 fname = os.path.join(td, 'file1')
725 723 ip.run_cell_magic("file", fname, u'\n'.join([
726 724 'line1',
727 725 'line2',
728 726 ]))
729 727 with open(fname) as f:
730 728 s = f.read()
731 729 nt.assert_in('line1\n', s)
732 730 nt.assert_in('line2', s)
733 731
734 732 def test_file_var_expand():
735 733 """%%file $filename"""
736 734 ip = get_ipython()
737 735 with TemporaryDirectory() as td:
738 736 fname = os.path.join(td, 'file1')
739 737 ip.user_ns['filename'] = fname
740 738 ip.run_cell_magic("file", '$filename', u'\n'.join([
741 739 'line1',
742 740 'line2',
743 741 ]))
744 742 with open(fname) as f:
745 743 s = f.read()
746 744 nt.assert_in('line1\n', s)
747 745 nt.assert_in('line2', s)
748 746
749 747 def test_file_unicode():
750 748 """%%file with unicode cell"""
751 749 ip = get_ipython()
752 750 with TemporaryDirectory() as td:
753 751 fname = os.path.join(td, 'file1')
754 752 ip.run_cell_magic("file", fname, u'\n'.join([
755 753 u'liné1',
756 754 u'liné2',
757 755 ]))
758 756 with io.open(fname, encoding='utf-8') as f:
759 757 s = f.read()
760 758 nt.assert_in(u'liné1\n', s)
761 759 nt.assert_in(u'liné2', s)
762 760
763 761 def test_file_amend():
764 762 """%%file -a amends files"""
765 763 ip = get_ipython()
766 764 with TemporaryDirectory() as td:
767 765 fname = os.path.join(td, 'file2')
768 766 ip.run_cell_magic("file", fname, u'\n'.join([
769 767 'line1',
770 768 'line2',
771 769 ]))
772 770 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
773 771 'line3',
774 772 'line4',
775 773 ]))
776 774 with open(fname) as f:
777 775 s = f.read()
778 776 nt.assert_in('line1\n', s)
779 777 nt.assert_in('line3\n', s)
780 778
781 779
782 780 def test_script_config():
783 781 ip = get_ipython()
784 782 ip.config.ScriptMagics.script_magics = ['whoda']
785 783 sm = script.ScriptMagics(shell=ip)
786 784 nt.assert_in('whoda', sm.magics['cell'])
787 785
788 786 @dec.skip_win32
789 787 def test_script_out():
790 788 ip = get_ipython()
791 789 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
792 790 nt.assert_equal(ip.user_ns['output'], 'hi\n')
793 791
794 792 @dec.skip_win32
795 793 def test_script_err():
796 794 ip = get_ipython()
797 795 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
798 796 nt.assert_equal(ip.user_ns['error'], 'hello\n')
799 797
800 798 @dec.skip_win32
801 799 def test_script_out_err():
802 800 ip = get_ipython()
803 801 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
804 802 nt.assert_equal(ip.user_ns['output'], 'hi\n')
805 803 nt.assert_equal(ip.user_ns['error'], 'hello\n')
806 804
807 805 @dec.skip_win32
808 806 def test_script_bg_out():
809 807 ip = get_ipython()
810 808 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
811 809 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
812 810
813 811 @dec.skip_win32
814 812 def test_script_bg_err():
815 813 ip = get_ipython()
816 814 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
817 815 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
818 816
819 817 @dec.skip_win32
820 818 def test_script_bg_out_err():
821 819 ip = get_ipython()
822 820 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
823 821 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
824 822 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
825 823
826 824 def test_script_defaults():
827 825 ip = get_ipython()
828 826 for cmd in ['sh', 'bash', 'perl', 'ruby']:
829 827 try:
830 828 find_cmd(cmd)
831 829 except Exception:
832 830 pass
833 831 else:
834 832 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
835 833
836 834
837 835 @magics_class
838 836 class FooFoo(Magics):
839 837 """class with both %foo and %%foo magics"""
840 838 @line_magic('foo')
841 839 def line_foo(self, line):
842 840 "I am line foo"
843 841 pass
844 842
845 843 @cell_magic("foo")
846 844 def cell_foo(self, line, cell):
847 845 "I am cell foo, not line foo"
848 846 pass
849 847
850 848 def test_line_cell_info():
851 849 """%%foo and %foo magics are distinguishable to inspect"""
852 850 ip = get_ipython()
853 851 ip.magics_manager.register(FooFoo)
854 852 oinfo = ip.object_inspect('foo')
855 853 nt.assert_true(oinfo['found'])
856 854 nt.assert_true(oinfo['ismagic'])
857 855
858 856 oinfo = ip.object_inspect('%%foo')
859 857 nt.assert_true(oinfo['found'])
860 858 nt.assert_true(oinfo['ismagic'])
861 859 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
862 860
863 861 oinfo = ip.object_inspect('%foo')
864 862 nt.assert_true(oinfo['found'])
865 863 nt.assert_true(oinfo['ismagic'])
866 864 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
867 865
868 866 def test_multiple_magics():
869 867 ip = get_ipython()
870 868 foo1 = FooFoo(ip)
871 869 foo2 = FooFoo(ip)
872 870 mm = ip.magics_manager
873 871 mm.register(foo1)
874 872 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
875 873 mm.register(foo2)
876 874 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
877 875
878 876 def test_alias_magic():
879 877 """Test %alias_magic."""
880 878 ip = get_ipython()
881 879 mm = ip.magics_manager
882 880
883 881 # Basic operation: both cell and line magics are created, if possible.
884 882 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
885 883 nt.assert_in('timeit_alias', mm.magics['line'])
886 884 nt.assert_in('timeit_alias', mm.magics['cell'])
887 885
888 886 # --cell is specified, line magic not created.
889 887 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
890 888 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
891 889 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
892 890
893 891 # Test that line alias is created successfully.
894 892 ip.run_line_magic('alias_magic', '--line env_alias env')
895 893 nt.assert_equal(ip.run_line_magic('env', ''),
896 894 ip.run_line_magic('env_alias', ''))
897 895
898 896 def test_save():
899 897 """Test %save."""
900 898 ip = get_ipython()
901 899 ip.history_manager.reset() # Clear any existing history.
902 900 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
903 901 for i, cmd in enumerate(cmds, start=1):
904 902 ip.history_manager.store_inputs(i, cmd)
905 903 with TemporaryDirectory() as tmpdir:
906 904 file = os.path.join(tmpdir, "testsave.py")
907 905 ip.run_line_magic("save", "%s 1-10" % file)
908 906 with open(file) as f:
909 907 content = f.read()
910 908 nt.assert_equal(content.count(cmds[0]), 1)
911 909 nt.assert_in('coding: utf-8', content)
912 910 ip.run_line_magic("save", "-a %s 1-10" % file)
913 911 with open(file) as f:
914 912 content = f.read()
915 913 nt.assert_equal(content.count(cmds[0]), 2)
916 914 nt.assert_in('coding: utf-8', content)
917 915
918 916
919 917 def test_store():
920 918 """Test %store."""
921 919 ip = get_ipython()
922 920 ip.run_line_magic('load_ext', 'storemagic')
923 921
924 922 # make sure the storage is empty
925 923 ip.run_line_magic('store', '-z')
926 924 ip.user_ns['var'] = 42
927 925 ip.run_line_magic('store', 'var')
928 926 ip.user_ns['var'] = 39
929 927 ip.run_line_magic('store', '-r')
930 928 nt.assert_equal(ip.user_ns['var'], 42)
931 929
932 930 ip.run_line_magic('store', '-d var')
933 931 ip.user_ns['var'] = 39
934 932 ip.run_line_magic('store' , '-r')
935 933 nt.assert_equal(ip.user_ns['var'], 39)
936 934
937 935
938 936 def _run_edit_test(arg_s, exp_filename=None,
939 937 exp_lineno=-1,
940 938 exp_contents=None,
941 939 exp_is_temp=None):
942 940 ip = get_ipython()
943 941 M = code.CodeMagics(ip)
944 942 last_call = ['','']
945 943 opts,args = M.parse_options(arg_s,'prxn:')
946 944 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
947 945
948 946 if exp_filename is not None:
949 947 nt.assert_equal(exp_filename, filename)
950 948 if exp_contents is not None:
951 949 with io.open(filename, 'r', encoding='utf-8') as f:
952 950 contents = f.read()
953 951 nt.assert_equal(exp_contents, contents)
954 952 if exp_lineno != -1:
955 953 nt.assert_equal(exp_lineno, lineno)
956 954 if exp_is_temp is not None:
957 955 nt.assert_equal(exp_is_temp, is_temp)
958 956
959 957
960 958 def test_edit_interactive():
961 959 """%edit on interactively defined objects"""
962 960 ip = get_ipython()
963 961 n = ip.execution_count
964 962 ip.run_cell(u"def foo(): return 1", store_history=True)
965 963
966 964 try:
967 965 _run_edit_test("foo")
968 966 except code.InteractivelyDefined as e:
969 967 nt.assert_equal(e.index, n)
970 968 else:
971 969 raise AssertionError("Should have raised InteractivelyDefined")
972 970
973 971
974 972 def test_edit_cell():
975 973 """%edit [cell id]"""
976 974 ip = get_ipython()
977 975
978 976 ip.run_cell(u"def foo(): return 1", store_history=True)
979 977
980 978 # test
981 979 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
982 980
983 981 def test_bookmark():
984 982 ip = get_ipython()
985 983 ip.run_line_magic('bookmark', 'bmname')
986 984 with tt.AssertPrints('bmname'):
987 985 ip.run_line_magic('bookmark', '-l')
988 986 ip.run_line_magic('bookmark', '-d bmname')
989 987
990 988 def test_ls_magic():
991 989 ip = get_ipython()
992 990 json_formatter = ip.display_formatter.formatters['application/json']
993 991 json_formatter.enabled = True
994 992 lsmagic = ip.magic('lsmagic')
995 993 with warnings.catch_warnings(record=True) as w:
996 994 j = json_formatter(lsmagic)
997 995 nt.assert_equal(sorted(j), ['cell', 'line'])
998 996 nt.assert_equal(w, []) # no warnings
@@ -1,517 +1,517 b''
1 1 # encoding: utf-8
2 2 """Tests for code execution (%run and related), which is particularly tricky.
3 3
4 4 Because of how %run manages namespaces, and the fact that we are trying here to
5 5 verify subtle object deletion and reference counting issues, the %run tests
6 6 will be kept in this separate file. This makes it easier to aggregate in one
7 7 place the tricks needed to handle it; most other magics are much easier to test
8 8 and we do so in a common test_magic file.
9 9 """
10 10
11 11 # Copyright (c) IPython Development Team.
12 12 # Distributed under the terms of the Modified BSD License.
13 13
14 14 from __future__ import absolute_import
15 15
16 16
17 17 import functools
18 18 import os
19 19 from os.path import join as pjoin
20 20 import random
21 21 import sys
22 22 import tempfile
23 23 import textwrap
24 24 import unittest
25 25
26 26 try:
27 27 from unittest.mock import patch
28 28 except ImportError:
29 29 from mock import patch
30 30
31 31 import nose.tools as nt
32 32 from nose import SkipTest
33 33
34 34 from IPython.testing import decorators as dec
35 35 from IPython.testing import tools as tt
36 36 from IPython.utils import py3compat
37 37 from IPython.utils.io import capture_output
38 38 from IPython.utils.tempdir import TemporaryDirectory
39 39 from IPython.core import debugger
40 40
41 41
42 42 def doctest_refbug():
43 43 """Very nasty problem with references held by multiple runs of a script.
44 44 See: https://github.com/ipython/ipython/issues/141
45 45
46 46 In [1]: _ip.clear_main_mod_cache()
47 47 # random
48 48
49 49 In [2]: %run refbug
50 50
51 51 In [3]: call_f()
52 52 lowercased: hello
53 53
54 54 In [4]: %run refbug
55 55
56 56 In [5]: call_f()
57 57 lowercased: hello
58 58 lowercased: hello
59 59 """
60 60
61 61
62 62 def doctest_run_builtins():
63 63 r"""Check that %run doesn't damage __builtins__.
64 64
65 65 In [1]: import tempfile
66 66
67 67 In [2]: bid1 = id(__builtins__)
68 68
69 69 In [3]: fname = tempfile.mkstemp('.py')[1]
70 70
71 71 In [3]: f = open(fname,'w')
72 72
73 73 In [4]: dummy= f.write('pass\n')
74 74
75 75 In [5]: f.flush()
76 76
77 77 In [6]: t1 = type(__builtins__)
78 78
79 79 In [7]: %run $fname
80 80
81 81 In [7]: f.close()
82 82
83 83 In [8]: bid2 = id(__builtins__)
84 84
85 85 In [9]: t2 = type(__builtins__)
86 86
87 87 In [10]: t1 == t2
88 88 Out[10]: True
89 89
90 90 In [10]: bid1 == bid2
91 91 Out[10]: True
92 92
93 93 In [12]: try:
94 94 ....: os.unlink(fname)
95 95 ....: except:
96 96 ....: pass
97 97 ....:
98 98 """
99 99
100 100
101 101 def doctest_run_option_parser():
102 102 r"""Test option parser in %run.
103 103
104 104 In [1]: %run print_argv.py
105 105 []
106 106
107 107 In [2]: %run print_argv.py print*.py
108 108 ['print_argv.py']
109 109
110 110 In [3]: %run -G print_argv.py print*.py
111 111 ['print*.py']
112 112
113 113 """
114 114
115 115
116 116 @dec.skip_win32
117 117 def doctest_run_option_parser_for_posix():
118 118 r"""Test option parser in %run (Linux/OSX specific).
119 119
120 120 You need double quote to escape glob in POSIX systems:
121 121
122 122 In [1]: %run print_argv.py print\\*.py
123 123 ['print*.py']
124 124
125 125 You can't use quote to escape glob in POSIX systems:
126 126
127 127 In [2]: %run print_argv.py 'print*.py'
128 128 ['print_argv.py']
129 129
130 130 """
131 131
132 132
133 133 @dec.skip_if_not_win32
134 134 def doctest_run_option_parser_for_windows():
135 135 r"""Test option parser in %run (Windows specific).
136 136
137 137 In Windows, you can't escape ``*` `by backslash:
138 138
139 139 In [1]: %run print_argv.py print\\*.py
140 140 ['print\\*.py']
141 141
142 142 You can use quote to escape glob:
143 143
144 144 In [2]: %run print_argv.py 'print*.py'
145 145 ['print*.py']
146 146
147 147 """
148 148
149 149
150 150 @py3compat.doctest_refactor_print
151 151 def doctest_reset_del():
152 152 """Test that resetting doesn't cause errors in __del__ methods.
153 153
154 154 In [2]: class A(object):
155 155 ...: def __del__(self):
156 156 ...: print str("Hi")
157 157 ...:
158 158
159 159 In [3]: a = A()
160 160
161 161 In [4]: get_ipython().reset()
162 162 Hi
163 163
164 164 In [5]: 1+1
165 165 Out[5]: 2
166 166 """
167 167
168 168 # For some tests, it will be handy to organize them in a class with a common
169 169 # setup that makes a temp file
170 170
171 171 class TestMagicRunPass(tt.TempFileMixin):
172 172
173 173 def setup(self):
174 174 """Make a valid python temp file."""
175 175 self.mktmp('pass\n')
176 176
177 177 def run_tmpfile(self):
178 178 _ip = get_ipython()
179 179 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
180 180 # See below and ticket https://bugs.launchpad.net/bugs/366353
181 181 _ip.magic('run %s' % self.fname)
182 182
183 183 def run_tmpfile_p(self):
184 184 _ip = get_ipython()
185 185 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
186 186 # See below and ticket https://bugs.launchpad.net/bugs/366353
187 187 _ip.magic('run -p %s' % self.fname)
188 188
189 189 def test_builtins_id(self):
190 190 """Check that %run doesn't damage __builtins__ """
191 191 _ip = get_ipython()
192 192 # Test that the id of __builtins__ is not modified by %run
193 193 bid1 = id(_ip.user_ns['__builtins__'])
194 194 self.run_tmpfile()
195 195 bid2 = id(_ip.user_ns['__builtins__'])
196 196 nt.assert_equal(bid1, bid2)
197 197
198 198 def test_builtins_type(self):
199 199 """Check that the type of __builtins__ doesn't change with %run.
200 200
201 201 However, the above could pass if __builtins__ was already modified to
202 202 be a dict (it should be a module) by a previous use of %run. So we
203 203 also check explicitly that it really is a module:
204 204 """
205 205 _ip = get_ipython()
206 206 self.run_tmpfile()
207 207 nt.assert_equal(type(_ip.user_ns['__builtins__']),type(sys))
208 208
209 209 def test_prompts(self):
210 210 """Test that prompts correctly generate after %run"""
211 211 self.run_tmpfile()
212 212 _ip = get_ipython()
213 213 p2 = _ip.prompt_manager.render('in2').strip()
214 214 nt.assert_equal(p2[:3], '...')
215 215
216 216 def test_run_profile( self ):
217 217 """Test that the option -p, which invokes the profiler, do not
218 218 crash by invoking execfile"""
219 219 _ip = get_ipython()
220 220 self.run_tmpfile_p()
221 221
222 222
223 223 class TestMagicRunSimple(tt.TempFileMixin):
224 224
225 225 def test_simpledef(self):
226 226 """Test that simple class definitions work."""
227 227 src = ("class foo: pass\n"
228 228 "def f(): return foo()")
229 229 self.mktmp(src)
230 230 _ip.magic('run %s' % self.fname)
231 231 _ip.run_cell('t = isinstance(f(), foo)')
232 232 nt.assert_true(_ip.user_ns['t'])
233 233
234 234 def test_obj_del(self):
235 235 """Test that object's __del__ methods are called on exit."""
236 236 if sys.platform == 'win32':
237 237 try:
238 238 import win32api
239 239 except ImportError:
240 240 raise SkipTest("Test requires pywin32")
241 241 src = ("class A(object):\n"
242 242 " def __del__(self):\n"
243 243 " print 'object A deleted'\n"
244 244 "a = A()\n")
245 245 self.mktmp(py3compat.doctest_refactor_print(src))
246 246 if dec.module_not_available('sqlite3'):
247 247 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
248 248 else:
249 249 err = None
250 250 tt.ipexec_validate(self.fname, 'object A deleted', err)
251 251
252 252 def test_aggressive_namespace_cleanup(self):
253 253 """Test that namespace cleanup is not too aggressive GH-238
254 254
255 255 Returning from another run magic deletes the namespace"""
256 256 # see ticket https://github.com/ipython/ipython/issues/238
257 257 class secondtmp(tt.TempFileMixin): pass
258 258 empty = secondtmp()
259 259 empty.mktmp('')
260 260 # On Windows, the filename will have \users in it, so we need to use the
261 261 # repr so that the \u becomes \\u.
262 262 src = ("ip = get_ipython()\n"
263 263 "for i in range(5):\n"
264 264 " try:\n"
265 265 " ip.magic(%r)\n"
266 266 " except NameError as e:\n"
267 267 " print(i)\n"
268 268 " break\n" % ('run ' + empty.fname))
269 269 self.mktmp(src)
270 270 _ip.magic('run %s' % self.fname)
271 271 _ip.run_cell('ip == get_ipython()')
272 272 nt.assert_equal(_ip.user_ns['i'], 4)
273 273
274 274 def test_run_second(self):
275 275 """Test that running a second file doesn't clobber the first, gh-3547
276 276 """
277 277 self.mktmp("avar = 1\n"
278 278 "def afunc():\n"
279 279 " return avar\n")
280 280
281 281 empty = tt.TempFileMixin()
282 282 empty.mktmp("")
283 283
284 284 _ip.magic('run %s' % self.fname)
285 285 _ip.magic('run %s' % empty.fname)
286 286 nt.assert_equal(_ip.user_ns['afunc'](), 1)
287 287
288 288 @dec.skip_win32
289 289 def test_tclass(self):
290 290 mydir = os.path.dirname(__file__)
291 291 tc = os.path.join(mydir, 'tclass')
292 292 src = ("%%run '%s' C-first\n"
293 293 "%%run '%s' C-second\n"
294 294 "%%run '%s' C-third\n") % (tc, tc, tc)
295 295 self.mktmp(src, '.ipy')
296 296 out = """\
297 297 ARGV 1-: ['C-first']
298 298 ARGV 1-: ['C-second']
299 299 tclass.py: deleting object: C-first
300 300 ARGV 1-: ['C-third']
301 301 tclass.py: deleting object: C-second
302 302 tclass.py: deleting object: C-third
303 303 """
304 304 if dec.module_not_available('sqlite3'):
305 305 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
306 306 else:
307 307 err = None
308 308 tt.ipexec_validate(self.fname, out, err)
309 309
310 310 def test_run_i_after_reset(self):
311 311 """Check that %run -i still works after %reset (gh-693)"""
312 312 src = "yy = zz\n"
313 313 self.mktmp(src)
314 314 _ip.run_cell("zz = 23")
315 315 _ip.magic('run -i %s' % self.fname)
316 316 nt.assert_equal(_ip.user_ns['yy'], 23)
317 317 _ip.magic('reset -f')
318 318 _ip.run_cell("zz = 23")
319 319 _ip.magic('run -i %s' % self.fname)
320 320 nt.assert_equal(_ip.user_ns['yy'], 23)
321 321
322 322 def test_unicode(self):
323 323 """Check that files in odd encodings are accepted."""
324 324 mydir = os.path.dirname(__file__)
325 325 na = os.path.join(mydir, 'nonascii.py')
326 326 _ip.magic('run "%s"' % na)
327 327 nt.assert_equal(_ip.user_ns['u'], u'Ўт№Ф')
328 328
329 329 def test_run_py_file_attribute(self):
330 330 """Test handling of `__file__` attribute in `%run <file>.py`."""
331 331 src = "t = __file__\n"
332 332 self.mktmp(src)
333 333 _missing = object()
334 334 file1 = _ip.user_ns.get('__file__', _missing)
335 335 _ip.magic('run %s' % self.fname)
336 336 file2 = _ip.user_ns.get('__file__', _missing)
337 337
338 338 # Check that __file__ was equal to the filename in the script's
339 339 # namespace.
340 340 nt.assert_equal(_ip.user_ns['t'], self.fname)
341 341
342 342 # Check that __file__ was not leaked back into user_ns.
343 343 nt.assert_equal(file1, file2)
344 344
345 345 def test_run_ipy_file_attribute(self):
346 346 """Test handling of `__file__` attribute in `%run <file.ipy>`."""
347 347 src = "t = __file__\n"
348 348 self.mktmp(src, ext='.ipy')
349 349 _missing = object()
350 350 file1 = _ip.user_ns.get('__file__', _missing)
351 351 _ip.magic('run %s' % self.fname)
352 352 file2 = _ip.user_ns.get('__file__', _missing)
353 353
354 354 # Check that __file__ was equal to the filename in the script's
355 355 # namespace.
356 356 nt.assert_equal(_ip.user_ns['t'], self.fname)
357 357
358 358 # Check that __file__ was not leaked back into user_ns.
359 359 nt.assert_equal(file1, file2)
360 360
361 361 def test_run_formatting(self):
362 362 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
363 363 src = "pass"
364 364 self.mktmp(src)
365 365 _ip.magic('run -t -N 1 %s' % self.fname)
366 366 _ip.magic('run -t -N 10 %s' % self.fname)
367 367
368 368 def test_ignore_sys_exit(self):
369 369 """Test the -e option to ignore sys.exit()"""
370 370 src = "import sys; sys.exit(1)"
371 371 self.mktmp(src)
372 372 with tt.AssertPrints('SystemExit'):
373 373 _ip.magic('run %s' % self.fname)
374 374
375 375 with tt.AssertNotPrints('SystemExit'):
376 376 _ip.magic('run -e %s' % self.fname)
377 377
378 @dec.skip_without('IPython.nbformat') # Requires jsonschema
378 @dec.skip_without('jupyter_nbformat') # Requires jsonschema
379 379 def test_run_nb(self):
380 380 """Test %run notebook.ipynb"""
381 from IPython.nbformat import v4, writes
381 from jupyter_nbformat import v4, writes
382 382 nb = v4.new_notebook(
383 383 cells=[
384 384 v4.new_markdown_cell("The Ultimate Question of Everything"),
385 385 v4.new_code_cell("answer=42")
386 386 ]
387 387 )
388 388 src = writes(nb, version=4)
389 389 self.mktmp(src, ext='.ipynb')
390 390
391 391 _ip.magic("run %s" % self.fname)
392 392
393 393 nt.assert_equal(_ip.user_ns['answer'], 42)
394 394
395 395
396 396
397 397 class TestMagicRunWithPackage(unittest.TestCase):
398 398
399 399 def writefile(self, name, content):
400 400 path = os.path.join(self.tempdir.name, name)
401 401 d = os.path.dirname(path)
402 402 if not os.path.isdir(d):
403 403 os.makedirs(d)
404 404 with open(path, 'w') as f:
405 405 f.write(textwrap.dedent(content))
406 406
407 407 def setUp(self):
408 408 self.package = package = 'tmp{0}'.format(repr(random.random())[2:])
409 409 """Temporary valid python package name."""
410 410
411 411 self.value = int(random.random() * 10000)
412 412
413 413 self.tempdir = TemporaryDirectory()
414 414 self.__orig_cwd = py3compat.getcwd()
415 415 sys.path.insert(0, self.tempdir.name)
416 416
417 417 self.writefile(os.path.join(package, '__init__.py'), '')
418 418 self.writefile(os.path.join(package, 'sub.py'), """
419 419 x = {0!r}
420 420 """.format(self.value))
421 421 self.writefile(os.path.join(package, 'relative.py'), """
422 422 from .sub import x
423 423 """)
424 424 self.writefile(os.path.join(package, 'absolute.py'), """
425 425 from {0}.sub import x
426 426 """.format(package))
427 427
428 428 def tearDown(self):
429 429 os.chdir(self.__orig_cwd)
430 430 sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
431 431 self.tempdir.cleanup()
432 432
433 433 def check_run_submodule(self, submodule, opts=''):
434 434 _ip.user_ns.pop('x', None)
435 435 _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts))
436 436 self.assertEqual(_ip.user_ns['x'], self.value,
437 437 'Variable `x` is not loaded from module `{0}`.'
438 438 .format(submodule))
439 439
440 440 def test_run_submodule_with_absolute_import(self):
441 441 self.check_run_submodule('absolute')
442 442
443 443 def test_run_submodule_with_relative_import(self):
444 444 """Run submodule that has a relative import statement (#2727)."""
445 445 self.check_run_submodule('relative')
446 446
447 447 def test_prun_submodule_with_absolute_import(self):
448 448 self.check_run_submodule('absolute', '-p')
449 449
450 450 def test_prun_submodule_with_relative_import(self):
451 451 self.check_run_submodule('relative', '-p')
452 452
453 453 def with_fake_debugger(func):
454 454 @functools.wraps(func)
455 455 def wrapper(*args, **kwds):
456 456 with patch.object(debugger.Pdb, 'run', staticmethod(eval)):
457 457 return func(*args, **kwds)
458 458 return wrapper
459 459
460 460 @with_fake_debugger
461 461 def test_debug_run_submodule_with_absolute_import(self):
462 462 self.check_run_submodule('absolute', '-d')
463 463
464 464 @with_fake_debugger
465 465 def test_debug_run_submodule_with_relative_import(self):
466 466 self.check_run_submodule('relative', '-d')
467 467
468 468 def test_run__name__():
469 469 with TemporaryDirectory() as td:
470 470 path = pjoin(td, 'foo.py')
471 471 with open(path, 'w') as f:
472 472 f.write("q = __name__")
473 473
474 474 _ip.user_ns.pop('q', None)
475 475 _ip.magic('run {}'.format(path))
476 476 nt.assert_equal(_ip.user_ns.pop('q'), '__main__')
477 477
478 478 _ip.magic('run -n {}'.format(path))
479 479 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
480 480
481 481 def test_run_tb():
482 482 """Test traceback offset in %run"""
483 483 with TemporaryDirectory() as td:
484 484 path = pjoin(td, 'foo.py')
485 485 with open(path, 'w') as f:
486 486 f.write('\n'.join([
487 487 "def foo():",
488 488 " return bar()",
489 489 "def bar():",
490 490 " raise RuntimeError('hello!')",
491 491 "foo()",
492 492 ]))
493 493 with capture_output() as io:
494 494 _ip.magic('run {}'.format(path))
495 495 out = io.stdout
496 496 nt.assert_not_in("execfile", out)
497 497 nt.assert_in("RuntimeError", out)
498 498 nt.assert_equal(out.count("---->"), 3)
499 499
500 500 @dec.knownfailureif(sys.platform == 'win32', "writes to io.stdout aren't captured on Windows")
501 501 def test_script_tb():
502 502 """Test traceback offset in `ipython script.py`"""
503 503 with TemporaryDirectory() as td:
504 504 path = pjoin(td, 'foo.py')
505 505 with open(path, 'w') as f:
506 506 f.write('\n'.join([
507 507 "def foo():",
508 508 " return bar()",
509 509 "def bar():",
510 510 " raise RuntimeError('hello!')",
511 511 "foo()",
512 512 ]))
513 513 out, err = tt.ipexec(path)
514 514 nt.assert_not_in("execfile", out)
515 515 nt.assert_in("RuntimeError", out)
516 516 nt.assert_equal(out.count("---->"), 3)
517 517
@@ -1,30 +1,30 b''
1 1 """Test help output of various IPython entry points"""
2 2
3 3 # Copyright (c) IPython Development Team.
4 4 # Distributed under the terms of the Modified BSD License.
5 5
6 6 import IPython.testing.tools as tt
7 7 from IPython.testing.decorators import skip_without
8 8
9 9
10 10 def test_ipython_help():
11 11 tt.help_all_output_test()
12 12
13 13 def test_profile_help():
14 14 tt.help_all_output_test("profile")
15 15
16 16 def test_profile_list_help():
17 17 tt.help_all_output_test("profile list")
18 18
19 19 def test_profile_create_help():
20 20 tt.help_all_output_test("profile create")
21 21
22 22 def test_locate_help():
23 23 tt.help_all_output_test("locate")
24 24
25 25 def test_locate_profile_help():
26 26 tt.help_all_output_test("locate profile")
27 27
28 @skip_without('IPython.nbformat') # Requires jsonschema to be installed
28 @skip_without('jupyter_nbformat') # Requires jsonschema to be installed
29 29 def test_trust_help():
30 30 tt.help_all_output_test("trust")
General Comments 0
You need to be logged in to leave comments. Login now