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