##// END OF EJS Templates
Merge pull request #5277 from minrk/check-jpeg-test...
Thomas Kluyver -
r15690:a5c527b5 merge
parent child Browse files
Show More
@@ -1,224 +1,241 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 # PIL's JPEG plugin can't write to BytesIO objects
66 # Pillow fixes this
67 from PIL import Image
68 buf = BytesIO()
69 img = Image.new("RGB", (4,4))
70 try:
71 img.save(buf, 'jpeg')
72 except Exception as e:
73 ename = e.__class__.__name__
74 raise SkipTest("PIL can't write JPEG to BytesIO: %s: %s" % (ename, e))
75
60 @dec.skip_without("PIL.Image")
76 @dec.skip_without("PIL.Image")
61 def test_figure_to_jpg():
77 def test_figure_to_jpeg():
62 # simple check for at least jpg-looking output
78 _check_pil_jpeg_bytes()
79 # simple check for at least jpeg-looking output
63 fig = plt.figure()
80 fig = plt.figure()
64 ax = fig.add_subplot(1,1,1)
81 ax = fig.add_subplot(1,1,1)
65 ax.plot([1,2,3])
82 ax.plot([1,2,3])
66 plt.draw()
83 plt.draw()
67 jpg = pt.print_figure(fig, 'jpg', quality=50)[:100].lower()
84 jpeg = pt.print_figure(fig, 'jpeg', quality=50)[:100].lower()
68 assert jpg.startswith(_JPEG)
85 assert jpeg.startswith(_JPEG)
69
86
70 def test_retina_figure():
87 def test_retina_figure():
71 fig = plt.figure()
88 fig = plt.figure()
72 ax = fig.add_subplot(1,1,1)
89 ax = fig.add_subplot(1,1,1)
73 ax.plot([1,2,3])
90 ax.plot([1,2,3])
74 plt.draw()
91 plt.draw()
75 png, md = pt.retina_figure(fig)
92 png, md = pt.retina_figure(fig)
76 assert png.startswith(_PNG)
93 assert png.startswith(_PNG)
77 nt.assert_in('width', md)
94 nt.assert_in('width', md)
78 nt.assert_in('height', md)
95 nt.assert_in('height', md)
79
96
80 _fmt_mime_map = {
97 _fmt_mime_map = {
81 'png': 'image/png',
98 'png': 'image/png',
82 'jpeg': 'image/jpeg',
99 'jpeg': 'image/jpeg',
83 'pdf': 'application/pdf',
100 'pdf': 'application/pdf',
84 'retina': 'image/png',
101 'retina': 'image/png',
85 'svg': 'image/svg+xml',
102 'svg': 'image/svg+xml',
86 }
103 }
87
104
88 def test_select_figure_formats_str():
105 def test_select_figure_formats_str():
89 ip = get_ipython()
106 ip = get_ipython()
90 for fmt, active_mime in _fmt_mime_map.items():
107 for fmt, active_mime in _fmt_mime_map.items():
91 pt.select_figure_formats(ip, fmt)
108 pt.select_figure_formats(ip, fmt)
92 for mime, f in ip.display_formatter.formatters.items():
109 for mime, f in ip.display_formatter.formatters.items():
93 if mime == active_mime:
110 if mime == active_mime:
94 nt.assert_in(Figure, f)
111 nt.assert_in(Figure, f)
95 else:
112 else:
96 nt.assert_not_in(Figure, f)
113 nt.assert_not_in(Figure, f)
97
114
98 def test_select_figure_formats_kwargs():
115 def test_select_figure_formats_kwargs():
99 ip = get_ipython()
116 ip = get_ipython()
100 kwargs = dict(quality=10, bbox_inches='tight')
117 kwargs = dict(quality=10, bbox_inches='tight')
101 pt.select_figure_formats(ip, 'png', **kwargs)
118 pt.select_figure_formats(ip, 'png', **kwargs)
102 formatter = ip.display_formatter.formatters['image/png']
119 formatter = ip.display_formatter.formatters['image/png']
103 f = formatter.lookup_by_type(Figure)
120 f = formatter.lookup_by_type(Figure)
104 cell = f.__closure__[0].cell_contents
121 cell = f.__closure__[0].cell_contents
105 nt.assert_equal(cell, kwargs)
122 nt.assert_equal(cell, kwargs)
106
123
107 # check that the formatter doesn't raise
124 # check that the formatter doesn't raise
108 fig = plt.figure()
125 fig = plt.figure()
109 ax = fig.add_subplot(1,1,1)
126 ax = fig.add_subplot(1,1,1)
110 ax.plot([1,2,3])
127 ax.plot([1,2,3])
111 plt.draw()
128 plt.draw()
112 formatter.enabled = True
129 formatter.enabled = True
113 png = formatter(fig)
130 png = formatter(fig)
114 assert png.startswith(_PNG)
131 assert png.startswith(_PNG)
115
132
116 def test_select_figure_formats_set():
133 def test_select_figure_formats_set():
117 ip = get_ipython()
134 ip = get_ipython()
118 for fmts in [
135 for fmts in [
119 {'png', 'svg'},
136 {'png', 'svg'},
120 ['png'],
137 ['png'],
121 ('jpeg', 'pdf', 'retina'),
138 ('jpeg', 'pdf', 'retina'),
122 {'svg'},
139 {'svg'},
123 ]:
140 ]:
124 active_mimes = {_fmt_mime_map[fmt] for fmt in fmts}
141 active_mimes = {_fmt_mime_map[fmt] for fmt in fmts}
125 pt.select_figure_formats(ip, fmts)
142 pt.select_figure_formats(ip, fmts)
126 for mime, f in ip.display_formatter.formatters.items():
143 for mime, f in ip.display_formatter.formatters.items():
127 if mime in active_mimes:
144 if mime in active_mimes:
128 nt.assert_in(Figure, f)
145 nt.assert_in(Figure, f)
129 else:
146 else:
130 nt.assert_not_in(Figure, f)
147 nt.assert_not_in(Figure, f)
131
148
132 def test_select_figure_formats_bad():
149 def test_select_figure_formats_bad():
133 ip = get_ipython()
150 ip = get_ipython()
134 with nt.assert_raises(ValueError):
151 with nt.assert_raises(ValueError):
135 pt.select_figure_formats(ip, 'foo')
152 pt.select_figure_formats(ip, 'foo')
136 with nt.assert_raises(ValueError):
153 with nt.assert_raises(ValueError):
137 pt.select_figure_formats(ip, {'png', 'foo'})
154 pt.select_figure_formats(ip, {'png', 'foo'})
138 with nt.assert_raises(ValueError):
155 with nt.assert_raises(ValueError):
139 pt.select_figure_formats(ip, ['retina', 'pdf', 'bar', 'bad'])
156 pt.select_figure_formats(ip, ['retina', 'pdf', 'bar', 'bad'])
140
157
141 def test_import_pylab():
158 def test_import_pylab():
142 ns = {}
159 ns = {}
143 pt.import_pylab(ns, import_all=False)
160 pt.import_pylab(ns, import_all=False)
144 nt.assert_true('plt' in ns)
161 nt.assert_true('plt' in ns)
145 nt.assert_equal(ns['np'], np)
162 nt.assert_equal(ns['np'], np)
146
163
147 class TestPylabSwitch(object):
164 class TestPylabSwitch(object):
148 class Shell(InteractiveShell):
165 class Shell(InteractiveShell):
149 def enable_gui(self, gui):
166 def enable_gui(self, gui):
150 pass
167 pass
151
168
152 def setup(self):
169 def setup(self):
153 import matplotlib
170 import matplotlib
154 def act_mpl(backend):
171 def act_mpl(backend):
155 matplotlib.rcParams['backend'] = backend
172 matplotlib.rcParams['backend'] = backend
156
173
157 # Save rcParams since they get modified
174 # Save rcParams since they get modified
158 self._saved_rcParams = matplotlib.rcParams
175 self._saved_rcParams = matplotlib.rcParams
159 self._saved_rcParamsOrig = matplotlib.rcParamsOrig
176 self._saved_rcParamsOrig = matplotlib.rcParamsOrig
160 matplotlib.rcParams = dict(backend='Qt4Agg')
177 matplotlib.rcParams = dict(backend='Qt4Agg')
161 matplotlib.rcParamsOrig = dict(backend='Qt4Agg')
178 matplotlib.rcParamsOrig = dict(backend='Qt4Agg')
162
179
163 # Mock out functions
180 # Mock out functions
164 self._save_am = pt.activate_matplotlib
181 self._save_am = pt.activate_matplotlib
165 pt.activate_matplotlib = act_mpl
182 pt.activate_matplotlib = act_mpl
166 self._save_ip = pt.import_pylab
183 self._save_ip = pt.import_pylab
167 pt.import_pylab = lambda *a,**kw:None
184 pt.import_pylab = lambda *a,**kw:None
168 self._save_cis = pt.configure_inline_support
185 self._save_cis = pt.configure_inline_support
169 pt.configure_inline_support = lambda *a,**kw:None
186 pt.configure_inline_support = lambda *a,**kw:None
170
187
171 def teardown(self):
188 def teardown(self):
172 pt.activate_matplotlib = self._save_am
189 pt.activate_matplotlib = self._save_am
173 pt.import_pylab = self._save_ip
190 pt.import_pylab = self._save_ip
174 pt.configure_inline_support = self._save_cis
191 pt.configure_inline_support = self._save_cis
175 import matplotlib
192 import matplotlib
176 matplotlib.rcParams = self._saved_rcParams
193 matplotlib.rcParams = self._saved_rcParams
177 matplotlib.rcParamsOrig = self._saved_rcParamsOrig
194 matplotlib.rcParamsOrig = self._saved_rcParamsOrig
178
195
179 def test_qt(self):
196 def test_qt(self):
180 s = self.Shell()
197 s = self.Shell()
181 gui, backend = s.enable_matplotlib(None)
198 gui, backend = s.enable_matplotlib(None)
182 nt.assert_equal(gui, 'qt')
199 nt.assert_equal(gui, 'qt')
183 nt.assert_equal(s.pylab_gui_select, 'qt')
200 nt.assert_equal(s.pylab_gui_select, 'qt')
184
201
185 gui, backend = s.enable_matplotlib('inline')
202 gui, backend = s.enable_matplotlib('inline')
186 nt.assert_equal(gui, 'inline')
203 nt.assert_equal(gui, 'inline')
187 nt.assert_equal(s.pylab_gui_select, 'qt')
204 nt.assert_equal(s.pylab_gui_select, 'qt')
188
205
189 gui, backend = s.enable_matplotlib('qt')
206 gui, backend = s.enable_matplotlib('qt')
190 nt.assert_equal(gui, 'qt')
207 nt.assert_equal(gui, 'qt')
191 nt.assert_equal(s.pylab_gui_select, 'qt')
208 nt.assert_equal(s.pylab_gui_select, 'qt')
192
209
193 gui, backend = s.enable_matplotlib('inline')
210 gui, backend = s.enable_matplotlib('inline')
194 nt.assert_equal(gui, 'inline')
211 nt.assert_equal(gui, 'inline')
195 nt.assert_equal(s.pylab_gui_select, 'qt')
212 nt.assert_equal(s.pylab_gui_select, 'qt')
196
213
197 gui, backend = s.enable_matplotlib()
214 gui, backend = s.enable_matplotlib()
198 nt.assert_equal(gui, 'qt')
215 nt.assert_equal(gui, 'qt')
199 nt.assert_equal(s.pylab_gui_select, 'qt')
216 nt.assert_equal(s.pylab_gui_select, 'qt')
200
217
201 def test_inline(self):
218 def test_inline(self):
202 s = self.Shell()
219 s = self.Shell()
203 gui, backend = s.enable_matplotlib('inline')
220 gui, backend = s.enable_matplotlib('inline')
204 nt.assert_equal(gui, 'inline')
221 nt.assert_equal(gui, 'inline')
205 nt.assert_equal(s.pylab_gui_select, None)
222 nt.assert_equal(s.pylab_gui_select, None)
206
223
207 gui, backend = s.enable_matplotlib('inline')
224 gui, backend = s.enable_matplotlib('inline')
208 nt.assert_equal(gui, 'inline')
225 nt.assert_equal(gui, 'inline')
209 nt.assert_equal(s.pylab_gui_select, None)
226 nt.assert_equal(s.pylab_gui_select, None)
210
227
211 gui, backend = s.enable_matplotlib('qt')
228 gui, backend = s.enable_matplotlib('qt')
212 nt.assert_equal(gui, 'qt')
229 nt.assert_equal(gui, 'qt')
213 nt.assert_equal(s.pylab_gui_select, 'qt')
230 nt.assert_equal(s.pylab_gui_select, 'qt')
214
231
215 def test_qt_gtk(self):
232 def test_qt_gtk(self):
216 s = self.Shell()
233 s = self.Shell()
217 gui, backend = s.enable_matplotlib('qt')
234 gui, backend = s.enable_matplotlib('qt')
218 nt.assert_equal(gui, 'qt')
235 nt.assert_equal(gui, 'qt')
219 nt.assert_equal(s.pylab_gui_select, 'qt')
236 nt.assert_equal(s.pylab_gui_select, 'qt')
220
237
221 gui, backend = s.enable_matplotlib('gtk')
238 gui, backend = s.enable_matplotlib('gtk')
222 nt.assert_equal(gui, 'qt')
239 nt.assert_equal(gui, 'qt')
223 nt.assert_equal(s.pylab_gui_select, 'qt')
240 nt.assert_equal(s.pylab_gui_select, 'qt')
224
241
General Comments 0
You need to be logged in to leave comments. Login now