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