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