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