##// END OF EJS Templates
fix instantiation of shell in test_inline_twice...
Min RK -
Show More
@@ -1,261 +1,242 b''
1 """Tests for pylab tools module.
1 """Tests for pylab tools module.
2 """
2 """
3 #-----------------------------------------------------------------------------
3
4 # Copyright (c) 2011, the IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 #
6 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
10
6
11 #-----------------------------------------------------------------------------
12 # Imports
13 #-----------------------------------------------------------------------------
14 from __future__ import print_function
7 from __future__ import print_function
15
8
16 from io import UnsupportedOperation, BytesIO
9 from io import UnsupportedOperation, BytesIO
17
10
18 import matplotlib
11 import matplotlib
19 matplotlib.use('Agg')
12 matplotlib.use('Agg')
20 from matplotlib.figure import Figure
13 from matplotlib.figure import Figure
21
14
22 from nose import SkipTest
15 from nose import SkipTest
23 import nose.tools as nt
16 import nose.tools as nt
24
17
25 from matplotlib import pyplot as plt
18 from matplotlib import pyplot as plt
26 import numpy as np
19 import numpy as np
27
20
28 # Our own imports
29 from IPython.core.getipython import get_ipython
21 from IPython.core.getipython import get_ipython
30 from IPython.core.interactiveshell import InteractiveShell
22 from IPython.core.interactiveshell import InteractiveShell
31 from IPython.core.display import _PNG, _JPEG
23 from IPython.core.display import _PNG, _JPEG
32 from .. import pylabtools as pt
24 from .. import pylabtools as pt
33
25
34 from IPython.testing import decorators as dec
26 from IPython.testing import decorators as dec
35
27
36 #-----------------------------------------------------------------------------
37 # Globals and constants
38 #-----------------------------------------------------------------------------
39
40 #-----------------------------------------------------------------------------
41 # Local utilities
42 #-----------------------------------------------------------------------------
43
44 #-----------------------------------------------------------------------------
45 # Classes and functions
46 #-----------------------------------------------------------------------------
47
28
48 def test_figure_to_svg():
29 def test_figure_to_svg():
49 # simple empty-figure test
30 # simple empty-figure test
50 fig = plt.figure()
31 fig = plt.figure()
51 nt.assert_equal(pt.print_figure(fig, 'svg'), None)
32 nt.assert_equal(pt.print_figure(fig, 'svg'), None)
52
33
53 plt.close('all')
34 plt.close('all')
54
35
55 # simple check for at least svg-looking output
36 # simple check for at least svg-looking output
56 fig = plt.figure()
37 fig = plt.figure()
57 ax = fig.add_subplot(1,1,1)
38 ax = fig.add_subplot(1,1,1)
58 ax.plot([1,2,3])
39 ax.plot([1,2,3])
59 plt.draw()
40 plt.draw()
60 svg = pt.print_figure(fig, 'svg')[:100].lower()
41 svg = pt.print_figure(fig, 'svg')[:100].lower()
61 nt.assert_in(u'doctype svg', svg)
42 nt.assert_in(u'doctype svg', svg)
62
43
63 def _check_pil_jpeg_bytes():
44 def _check_pil_jpeg_bytes():
64 """Skip if PIL can't write JPEGs to BytesIO objects"""
45 """Skip if PIL can't write JPEGs to BytesIO objects"""
65 # PIL's JPEG plugin can't write to BytesIO objects
46 # PIL's JPEG plugin can't write to BytesIO objects
66 # Pillow fixes this
47 # Pillow fixes this
67 from PIL import Image
48 from PIL import Image
68 buf = BytesIO()
49 buf = BytesIO()
69 img = Image.new("RGB", (4,4))
50 img = Image.new("RGB", (4,4))
70 try:
51 try:
71 img.save(buf, 'jpeg')
52 img.save(buf, 'jpeg')
72 except Exception as e:
53 except Exception as e:
73 ename = e.__class__.__name__
54 ename = e.__class__.__name__
74 raise SkipTest("PIL can't write JPEG to BytesIO: %s: %s" % (ename, e))
55 raise SkipTest("PIL can't write JPEG to BytesIO: %s: %s" % (ename, e))
75
56
76 @dec.skip_without("PIL.Image")
57 @dec.skip_without("PIL.Image")
77 def test_figure_to_jpeg():
58 def test_figure_to_jpeg():
78 _check_pil_jpeg_bytes()
59 _check_pil_jpeg_bytes()
79 # simple check for at least jpeg-looking output
60 # simple check for at least jpeg-looking output
80 fig = plt.figure()
61 fig = plt.figure()
81 ax = fig.add_subplot(1,1,1)
62 ax = fig.add_subplot(1,1,1)
82 ax.plot([1,2,3])
63 ax.plot([1,2,3])
83 plt.draw()
64 plt.draw()
84 jpeg = pt.print_figure(fig, 'jpeg', quality=50)[:100].lower()
65 jpeg = pt.print_figure(fig, 'jpeg', quality=50)[:100].lower()
85 assert jpeg.startswith(_JPEG)
66 assert jpeg.startswith(_JPEG)
86
67
87 def test_retina_figure():
68 def test_retina_figure():
88 fig = plt.figure()
69 fig = plt.figure()
89 ax = fig.add_subplot(1,1,1)
70 ax = fig.add_subplot(1,1,1)
90 ax.plot([1,2,3])
71 ax.plot([1,2,3])
91 plt.draw()
72 plt.draw()
92 png, md = pt.retina_figure(fig)
73 png, md = pt.retina_figure(fig)
93 assert png.startswith(_PNG)
74 assert png.startswith(_PNG)
94 nt.assert_in('width', md)
75 nt.assert_in('width', md)
95 nt.assert_in('height', md)
76 nt.assert_in('height', md)
96
77
97 _fmt_mime_map = {
78 _fmt_mime_map = {
98 'png': 'image/png',
79 'png': 'image/png',
99 'jpeg': 'image/jpeg',
80 'jpeg': 'image/jpeg',
100 'pdf': 'application/pdf',
81 'pdf': 'application/pdf',
101 'retina': 'image/png',
82 'retina': 'image/png',
102 'svg': 'image/svg+xml',
83 'svg': 'image/svg+xml',
103 }
84 }
104
85
105 def test_select_figure_formats_str():
86 def test_select_figure_formats_str():
106 ip = get_ipython()
87 ip = get_ipython()
107 for fmt, active_mime in _fmt_mime_map.items():
88 for fmt, active_mime in _fmt_mime_map.items():
108 pt.select_figure_formats(ip, fmt)
89 pt.select_figure_formats(ip, fmt)
109 for mime, f in ip.display_formatter.formatters.items():
90 for mime, f in ip.display_formatter.formatters.items():
110 if mime == active_mime:
91 if mime == active_mime:
111 nt.assert_in(Figure, f)
92 nt.assert_in(Figure, f)
112 else:
93 else:
113 nt.assert_not_in(Figure, f)
94 nt.assert_not_in(Figure, f)
114
95
115 def test_select_figure_formats_kwargs():
96 def test_select_figure_formats_kwargs():
116 ip = get_ipython()
97 ip = get_ipython()
117 kwargs = dict(quality=10, bbox_inches='tight')
98 kwargs = dict(quality=10, bbox_inches='tight')
118 pt.select_figure_formats(ip, 'png', **kwargs)
99 pt.select_figure_formats(ip, 'png', **kwargs)
119 formatter = ip.display_formatter.formatters['image/png']
100 formatter = ip.display_formatter.formatters['image/png']
120 f = formatter.lookup_by_type(Figure)
101 f = formatter.lookup_by_type(Figure)
121 cell = f.__closure__[0].cell_contents
102 cell = f.__closure__[0].cell_contents
122 nt.assert_equal(cell, kwargs)
103 nt.assert_equal(cell, kwargs)
123
104
124 # check that the formatter doesn't raise
105 # check that the formatter doesn't raise
125 fig = plt.figure()
106 fig = plt.figure()
126 ax = fig.add_subplot(1,1,1)
107 ax = fig.add_subplot(1,1,1)
127 ax.plot([1,2,3])
108 ax.plot([1,2,3])
128 plt.draw()
109 plt.draw()
129 formatter.enabled = True
110 formatter.enabled = True
130 png = formatter(fig)
111 png = formatter(fig)
131 assert png.startswith(_PNG)
112 assert png.startswith(_PNG)
132
113
133 def test_select_figure_formats_set():
114 def test_select_figure_formats_set():
134 ip = get_ipython()
115 ip = get_ipython()
135 for fmts in [
116 for fmts in [
136 {'png', 'svg'},
117 {'png', 'svg'},
137 ['png'],
118 ['png'],
138 ('jpeg', 'pdf', 'retina'),
119 ('jpeg', 'pdf', 'retina'),
139 {'svg'},
120 {'svg'},
140 ]:
121 ]:
141 active_mimes = {_fmt_mime_map[fmt] for fmt in fmts}
122 active_mimes = {_fmt_mime_map[fmt] for fmt in fmts}
142 pt.select_figure_formats(ip, fmts)
123 pt.select_figure_formats(ip, fmts)
143 for mime, f in ip.display_formatter.formatters.items():
124 for mime, f in ip.display_formatter.formatters.items():
144 if mime in active_mimes:
125 if mime in active_mimes:
145 nt.assert_in(Figure, f)
126 nt.assert_in(Figure, f)
146 else:
127 else:
147 nt.assert_not_in(Figure, f)
128 nt.assert_not_in(Figure, f)
148
129
149 def test_select_figure_formats_bad():
130 def test_select_figure_formats_bad():
150 ip = get_ipython()
131 ip = get_ipython()
151 with nt.assert_raises(ValueError):
132 with nt.assert_raises(ValueError):
152 pt.select_figure_formats(ip, 'foo')
133 pt.select_figure_formats(ip, 'foo')
153 with nt.assert_raises(ValueError):
134 with nt.assert_raises(ValueError):
154 pt.select_figure_formats(ip, {'png', 'foo'})
135 pt.select_figure_formats(ip, {'png', 'foo'})
155 with nt.assert_raises(ValueError):
136 with nt.assert_raises(ValueError):
156 pt.select_figure_formats(ip, ['retina', 'pdf', 'bar', 'bad'])
137 pt.select_figure_formats(ip, ['retina', 'pdf', 'bar', 'bad'])
157
138
158 def test_import_pylab():
139 def test_import_pylab():
159 ns = {}
140 ns = {}
160 pt.import_pylab(ns, import_all=False)
141 pt.import_pylab(ns, import_all=False)
161 nt.assert_true('plt' in ns)
142 nt.assert_true('plt' in ns)
162 nt.assert_equal(ns['np'], np)
143 nt.assert_equal(ns['np'], np)
163
144
164 class TestPylabSwitch(object):
145 class TestPylabSwitch(object):
165 class Shell(InteractiveShell):
146 class Shell(InteractiveShell):
166 def enable_gui(self, gui):
147 def enable_gui(self, gui):
167 pass
148 pass
168
149
169 def setup(self):
150 def setup(self):
170 import matplotlib
151 import matplotlib
171 def act_mpl(backend):
152 def act_mpl(backend):
172 matplotlib.rcParams['backend'] = backend
153 matplotlib.rcParams['backend'] = backend
173
154
174 # Save rcParams since they get modified
155 # Save rcParams since they get modified
175 self._saved_rcParams = matplotlib.rcParams
156 self._saved_rcParams = matplotlib.rcParams
176 self._saved_rcParamsOrig = matplotlib.rcParamsOrig
157 self._saved_rcParamsOrig = matplotlib.rcParamsOrig
177 matplotlib.rcParams = dict(backend='Qt4Agg')
158 matplotlib.rcParams = dict(backend='Qt4Agg')
178 matplotlib.rcParamsOrig = dict(backend='Qt4Agg')
159 matplotlib.rcParamsOrig = dict(backend='Qt4Agg')
179
160
180 # Mock out functions
161 # Mock out functions
181 self._save_am = pt.activate_matplotlib
162 self._save_am = pt.activate_matplotlib
182 pt.activate_matplotlib = act_mpl
163 pt.activate_matplotlib = act_mpl
183 self._save_ip = pt.import_pylab
164 self._save_ip = pt.import_pylab
184 pt.import_pylab = lambda *a,**kw:None
165 pt.import_pylab = lambda *a,**kw:None
185 self._save_cis = pt.configure_inline_support
166 self._save_cis = pt.configure_inline_support
186 pt.configure_inline_support = lambda *a,**kw:None
167 pt.configure_inline_support = lambda *a,**kw:None
187
168
188 def teardown(self):
169 def teardown(self):
189 pt.activate_matplotlib = self._save_am
170 pt.activate_matplotlib = self._save_am
190 pt.import_pylab = self._save_ip
171 pt.import_pylab = self._save_ip
191 pt.configure_inline_support = self._save_cis
172 pt.configure_inline_support = self._save_cis
192 import matplotlib
173 import matplotlib
193 matplotlib.rcParams = self._saved_rcParams
174 matplotlib.rcParams = self._saved_rcParams
194 matplotlib.rcParamsOrig = self._saved_rcParamsOrig
175 matplotlib.rcParamsOrig = self._saved_rcParamsOrig
195
176
196 def test_qt(self):
177 def test_qt(self):
197 s = self.Shell()
178 s = self.Shell()
198 gui, backend = s.enable_matplotlib(None)
179 gui, backend = s.enable_matplotlib(None)
199 nt.assert_equal(gui, 'qt')
180 nt.assert_equal(gui, 'qt')
200 nt.assert_equal(s.pylab_gui_select, 'qt')
181 nt.assert_equal(s.pylab_gui_select, 'qt')
201
182
202 gui, backend = s.enable_matplotlib('inline')
183 gui, backend = s.enable_matplotlib('inline')
203 nt.assert_equal(gui, 'inline')
184 nt.assert_equal(gui, 'inline')
204 nt.assert_equal(s.pylab_gui_select, 'qt')
185 nt.assert_equal(s.pylab_gui_select, 'qt')
205
186
206 gui, backend = s.enable_matplotlib('qt')
187 gui, backend = s.enable_matplotlib('qt')
207 nt.assert_equal(gui, 'qt')
188 nt.assert_equal(gui, 'qt')
208 nt.assert_equal(s.pylab_gui_select, 'qt')
189 nt.assert_equal(s.pylab_gui_select, 'qt')
209
190
210 gui, backend = s.enable_matplotlib('inline')
191 gui, backend = s.enable_matplotlib('inline')
211 nt.assert_equal(gui, 'inline')
192 nt.assert_equal(gui, 'inline')
212 nt.assert_equal(s.pylab_gui_select, 'qt')
193 nt.assert_equal(s.pylab_gui_select, 'qt')
213
194
214 gui, backend = s.enable_matplotlib()
195 gui, backend = s.enable_matplotlib()
215 nt.assert_equal(gui, 'qt')
196 nt.assert_equal(gui, 'qt')
216 nt.assert_equal(s.pylab_gui_select, 'qt')
197 nt.assert_equal(s.pylab_gui_select, 'qt')
217
198
218 def test_inline(self):
199 def test_inline(self):
219 s = self.Shell()
200 s = self.Shell()
220 gui, backend = s.enable_matplotlib('inline')
201 gui, backend = s.enable_matplotlib('inline')
221 nt.assert_equal(gui, 'inline')
202 nt.assert_equal(gui, 'inline')
222 nt.assert_equal(s.pylab_gui_select, None)
203 nt.assert_equal(s.pylab_gui_select, None)
223
204
224 gui, backend = s.enable_matplotlib('inline')
205 gui, backend = s.enable_matplotlib('inline')
225 nt.assert_equal(gui, 'inline')
206 nt.assert_equal(gui, 'inline')
226 nt.assert_equal(s.pylab_gui_select, None)
207 nt.assert_equal(s.pylab_gui_select, None)
227
208
228 gui, backend = s.enable_matplotlib('qt')
209 gui, backend = s.enable_matplotlib('qt')
229 nt.assert_equal(gui, 'qt')
210 nt.assert_equal(gui, 'qt')
230 nt.assert_equal(s.pylab_gui_select, 'qt')
211 nt.assert_equal(s.pylab_gui_select, 'qt')
231
212
232 def test_inline_twice(self):
213 def test_inline_twice(self):
233 "Using '%matplotlib inline' twice should not reset formatters"
214 "Using '%matplotlib inline' twice should not reset formatters"
234
215
235 ip = get_ipython()
216 ip = self.Shell()
236 gui, backend = ip.enable_matplotlib('inline')
217 gui, backend = ip.enable_matplotlib('inline')
237 nt.assert_equal(gui, 'inline')
218 nt.assert_equal(gui, 'inline')
238
219
239 fmts = {'png'}
220 fmts = {'png'}
240 active_mimes = {_fmt_mime_map[fmt] for fmt in fmts}
221 active_mimes = {_fmt_mime_map[fmt] for fmt in fmts}
241 pt.select_figure_formats(ip, fmts)
222 pt.select_figure_formats(ip, fmts)
242
223
243 gui, backend = ip.enable_matplotlib('inline')
224 gui, backend = ip.enable_matplotlib('inline')
244 nt.assert_equal(gui, 'inline')
225 nt.assert_equal(gui, 'inline')
245
226
246 for mime, f in ip.display_formatter.formatters.items():
227 for mime, f in ip.display_formatter.formatters.items():
247 if mime in active_mimes:
228 if mime in active_mimes:
248 nt.assert_in(Figure, f)
229 nt.assert_in(Figure, f)
249 else:
230 else:
250 nt.assert_not_in(Figure, f)
231 nt.assert_not_in(Figure, f)
251
232
252 def test_qt_gtk(self):
233 def test_qt_gtk(self):
253 s = self.Shell()
234 s = self.Shell()
254 gui, backend = s.enable_matplotlib('qt')
235 gui, backend = s.enable_matplotlib('qt')
255 nt.assert_equal(gui, 'qt')
236 nt.assert_equal(gui, 'qt')
256 nt.assert_equal(s.pylab_gui_select, 'qt')
237 nt.assert_equal(s.pylab_gui_select, 'qt')
257
238
258 gui, backend = s.enable_matplotlib('gtk')
239 gui, backend = s.enable_matplotlib('gtk')
259 nt.assert_equal(gui, 'qt')
240 nt.assert_equal(gui, 'qt')
260 nt.assert_equal(s.pylab_gui_select, 'qt')
241 nt.assert_equal(s.pylab_gui_select, 'qt')
261
242
General Comments 0
You need to be logged in to leave comments. Login now