Debian Codegraph @

tests/test_pylabtools.py

raw
1 """Tests for pylab tools module."""
2
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
5
6
7 from binascii import a2b_base64
8 from io import BytesIO
9
10 import pytest
11
12 matplotlib = pytest.importorskip("matplotlib")
13 matplotlib.use("Agg")
14 from matplotlib.figure import Figure
15
16 from matplotlib import pyplot as plt
17 from matplotlib_inline import backend_inline
18 import numpy as np
19
20 from IPython.core.getipython import get_ipython
21 from IPython.core.interactiveshell import InteractiveShell
22 from IPython.core.display import _PNG, _JPEG
23 from IPython.core import pylabtools as pt
24
25 from IPython.testing import decorators as dec
26 from .test_history import hmmax3
27
28
29 def test_figure_to_svg():
30 # simple empty-figure test
31 fig = plt.figure()
32 assert pt.print_figure(fig, "svg") is None
33
34 plt.close("all")
35
36 # simple check for at least svg-looking output
37 fig = plt.figure()
38 ax = fig.add_subplot(1, 1, 1)
39 ax.plot([1, 2, 3])
40 plt.draw()
41 svg = pt.print_figure(fig, "svg")[:100].lower()
42 assert "doctype svg" in svg
43
44
45 def _check_pil_jpeg_bytes():
46 """Skip if PIL can't write JPEGs to BytesIO objects"""
47 # PIL's JPEG plugin can't write to BytesIO objects
48 # Pillow fixes this
49 from PIL import Image
50
51 buf = BytesIO()
52 img = Image.new("RGB", (4, 4))
53 try:
54 img.save(buf, "jpeg")
55 except Exception as e:
56 ename = e.__class__.__name__
57 raise pytest.skip("PIL can't write JPEG to BytesIO: %s: %s" % (ename, e)) from e
58
59
60 @dec.skip_without("PIL.Image")
61 def test_figure_to_jpeg():
62 _check_pil_jpeg_bytes()
63 # simple check for at least jpeg-looking output
64 fig = plt.figure()
65 ax = fig.add_subplot(1, 1, 1)
66 ax.plot([1, 2, 3])
67 plt.draw()
68 jpeg = pt.print_figure(fig, "jpeg", pil_kwargs={"optimize": 50})[:100].lower()
69 assert jpeg.startswith(_JPEG)
70
71
72 def test_retina_figure():
73 # simple empty-figure test
74 fig = plt.figure()
75 assert pt.retina_figure(fig) == None
76 plt.close("all")
77
78 fig = plt.figure()
79 ax = fig.add_subplot(1, 1, 1)
80 ax.plot([1, 2, 3])
81 plt.draw()
82 png, md = pt.retina_figure(fig)
83 assert png.startswith(_PNG)
84 assert "width" in md
85 assert "height" in md
86
87
88 _fmt_mime_map = {
89 "png": "image/png",
90 "jpeg": "image/jpeg",
91 "pdf": "application/pdf",
92 "retina": "image/png",
93 "svg": "image/svg+xml",
94 }
95
96
97 def test_select_figure_formats_str():
98 ip = get_ipython()
99 for fmt, active_mime in _fmt_mime_map.items():
100 pt.select_figure_formats(ip, fmt)
101 for mime, f in ip.display_formatter.formatters.items():
102 if mime == active_mime:
103 assert Figure in f
104 else:
105 assert Figure not in f
106
107
108 def test_select_figure_formats_kwargs():
109 ip = get_ipython()
110 kwargs = dict(bbox_inches="tight")
111 pt.select_figure_formats(ip, "png", **kwargs)
112 formatter = ip.display_formatter.formatters["image/png"]
113 f = formatter.lookup_by_type(Figure)
114 cell = f.keywords
115 expected = kwargs
116 expected["base64"] = True
117 expected["fmt"] = "png"
118 assert cell == expected
119
120 # check that the formatter doesn't raise
121 fig = plt.figure()
122 ax = fig.add_subplot(1, 1, 1)
123 ax.plot([1, 2, 3])
124 plt.draw()
125 formatter.enabled = True
126 png = formatter(fig)
127 assert isinstance(png, str)
128 png_bytes = a2b_base64(png)
129 assert png_bytes.startswith(_PNG)
130
131
132 def test_select_figure_formats_set():
133 ip = get_ipython()
134 for fmts in [
135 {"png", "svg"},
136 ["png"],
137 ("jpeg", "pdf", "retina"),
138 {"svg"},
139 ]:
140 active_mimes = {_fmt_mime_map[fmt] for fmt in fmts}
141 pt.select_figure_formats(ip, fmts)
142 for mime, f in ip.display_formatter.formatters.items():
143 if mime in active_mimes:
144 assert Figure in f
145 else:
146 assert Figure not in f
147
148
149 def test_select_figure_formats_bad():
150 ip = get_ipython()
151 with pytest.raises(ValueError):
152 pt.select_figure_formats(ip, "foo")
153 with pytest.raises(ValueError):
154 pt.select_figure_formats(ip, {"png", "foo"})
155 with pytest.raises(ValueError):
156 pt.select_figure_formats(ip, ["retina", "pdf", "bar", "bad"])
157
158
159 def test_import_pylab():
160 ns = {}
161 pt.import_pylab(ns, import_all=False)
162 assert "plt" in ns
163 assert ns["np"] == np
164
165
166 @pytest.fixture
167 def shell_pylab_fixture(hmmax3):
168 import matplotlib
169
170 def act_mpl(backend):
171 matplotlib.rcParams["backend"] = backend
172
173 # Save rcParams since they get modified
174 _saved_rcParams = matplotlib.rcParams
175 _saved_rcParamsOrig = matplotlib.rcParamsOrig
176 matplotlib.rcParams = dict(backend="QtAgg")
177 matplotlib.rcParamsOrig = dict(backend="QtAgg")
178
179 # Mock out functions
180 _save_am = pt.activate_matplotlib
181 pt.activate_matplotlib = act_mpl
182 _save_ip = pt.import_pylab
183 pt.import_pylab = lambda *a, **kw: None
184 s = Shell()
185 yield s
186 s.configurables = []
187 s.history_manager = None
188 pt.activate_matplotlib = _save_am
189 pt.import_pylab = _save_ip
190 matplotlib.rcParams = _saved_rcParams
191 matplotlib.rcParamsOrig = _saved_rcParamsOrig
192
193
194 class Shell(InteractiveShell):
195 def init_history(self):
196 """Sets up the command history, and starts regular autosaves."""
197 self.config.HistoryManager.hist_file = ":memory:"
198 super().init_history()
199
200 def enable_gui(self, gui):
201 pass
202
203
204 def test_just_shell_no_leak(shell_pylab_fixture):
205 s = shell_pylab_fixture
206
207
208 def test_qt(shell_pylab_fixture):
209 s = shell_pylab_fixture
210 gui, backend = s.enable_matplotlib(None)
211 assert gui == "qt"
212 assert s.pylab_gui_select == "qt"
213
214 gui, backend = s.enable_matplotlib("inline")
215 assert gui is None
216 assert s.pylab_gui_select == "qt"
217
218 gui, backend = s.enable_matplotlib("qt")
219 assert gui == "qt"
220 assert s.pylab_gui_select == "qt"
221
222 gui, backend = s.enable_matplotlib("inline")
223 assert gui is None
224 assert s.pylab_gui_select == "qt"
225
226 gui, backend = s.enable_matplotlib()
227 assert gui == "qt"
228 assert s.pylab_gui_select == "qt"
229 s.configurables = []
230 s.history_manager = None
231
232
233 def test_inline(shell_pylab_fixture):
234 s = shell_pylab_fixture
235 gui, backend = s.enable_matplotlib("inline")
236 assert gui is None
237 assert s.pylab_gui_select == None
238
239 gui, backend = s.enable_matplotlib("inline")
240 assert gui is None
241 assert s.pylab_gui_select == None
242
243 gui, backend = s.enable_matplotlib("qt")
244 assert gui == "qt"
245 assert s.pylab_gui_select == "qt"
246
247
248 def test_inline_twice(shell_pylab_fixture):
249 "Using '%matplotlib inline' twice should not reset formatters"
250
251 ip = shell_pylab_fixture
252 gui, backend = ip.enable_matplotlib("inline")
253 assert gui is None
254
255 fmts = {"png"}
256 active_mimes = {_fmt_mime_map[fmt] for fmt in fmts}
257 pt.select_figure_formats(ip, fmts)
258
259 gui, backend = ip.enable_matplotlib("inline")
260 assert gui is None
261
262 for mime, f in ip.display_formatter.formatters.items():
263 if mime in active_mimes:
264 assert Figure in f
265 else:
266 assert Figure not in f
267
268
269 def test_qt_gtk(shell_pylab_fixture):
270 s = shell_pylab_fixture
271 gui, backend = s.enable_matplotlib("qt")
272 assert gui == "qt"
273 assert s.pylab_gui_select == "qt"
274
275 gui, backend = s.enable_matplotlib("gtk3")
276 assert gui == "qt"
277 assert s.pylab_gui_select == "qt"
278
279
280 @dec.skipif(not pt._matplotlib_manages_backends())
281 def test_backend_module_name_case_sensitive(shell_pylab_fixture):
282 # Matplotlib backend names are case insensitive unless explicitly specified using
283 # "module://some_module.some_name" syntax which are case sensitive for mpl >= 3.9.1
284 all_lowercase = "module://matplotlib_inline.backend_inline"
285 some_uppercase = "module://matplotlib_inline.Backend_inline"
286 mpl3_9_1 = matplotlib.__version_info__ >= (3, 9, 1)
287
288 s = shell_pylab_fixture
289 s.enable_matplotlib(all_lowercase)
290 if mpl3_9_1:
291 with pytest.raises(RuntimeError):
292 s.enable_matplotlib(some_uppercase)
293 else:
294 s.enable_matplotlib(some_uppercase)
295
296 s.run_line_magic("matplotlib", all_lowercase)
297 if mpl3_9_1:
298 with pytest.raises(RuntimeError):
299 s.run_line_magic("matplotlib", some_uppercase)
300 else:
301 s.run_line_magic("matplotlib", some_uppercase)
302
303
304 def test_no_gui_backends():
305 for k in ["agg", "svg", "pdf", "ps"]:
306 assert k not in pt.backend2gui
307
308
309 def test_figure_no_canvas():
310 fig = Figure()
311 fig.canvas = None
312 pt.print_figure(fig)
313
314
315 @pytest.mark.parametrize(
316 "name, expected_gui, expected_backend",
317 [
318 # name is gui
319 ("gtk3", "gtk3", "gtk3agg"),
320 ("gtk4", "gtk4", "gtk4agg"),
321 ("headless", None, "agg"),
322 ("osx", "osx", "macosx"),
323 ("qt", "qt", "qtagg"),
324 ("qt5", "qt5", "qt5agg"),
325 ("qt6", "qt6", "qtagg"),
326 ("tk", "tk", "tkagg"),
327 ("wx", "wx", "wxagg"),
328 # name is backend
329 ("agg", None, "agg"),
330 ("cairo", None, "cairo"),
331 ("pdf", None, "pdf"),
332 ("ps", None, "ps"),
333 ("svg", None, "svg"),
334 ("template", None, "template"),
335 ("gtk3agg", "gtk3", "gtk3agg"),
336 ("gtk3cairo", "gtk3", "gtk3cairo"),
337 ("gtk4agg", "gtk4", "gtk4agg"),
338 ("gtk4cairo", "gtk4", "gtk4cairo"),
339 ("macosx", "osx", "macosx"),
340 ("nbagg", "nbagg", "nbagg"),
341 ("notebook", "nbagg", "notebook"),
342 ("qtagg", "qt", "qtagg"),
343 ("qtcairo", "qt", "qtcairo"),
344 ("qt5agg", "qt5", "qt5agg"),
345 ("qt5cairo", "qt5", "qt5cairo"),
346 ("tkagg", "tk", "tkagg"),
347 ("tkcairo", "tk", "tkcairo"),
348 ("webagg", "webagg", "webagg"),
349 ("wxagg", "wx", "wxagg"),
350 ("wxcairo", "wx", "wxcairo"),
351 ],
352 )
353 def test_backend_builtin(name, expected_gui, expected_backend):
354 # Test correct identification of Matplotlib built-in backends without importing and using them,
355 # otherwise we would need to ensure all the complex dependencies such as windowing toolkits are
356 # installed.
357
358 mpl_manages_backends = pt._matplotlib_manages_backends()
359 if not mpl_manages_backends:
360 # Backends not supported before _matplotlib_manages_backends or supported
361 # but with different expected_gui or expected_backend.
362 if (
363 name.endswith("agg")
364 or name.endswith("cairo")
365 or name in ("headless", "macosx", "pdf", "ps", "svg", "template")
366 ):
367 pytest.skip()
368 elif name == "qt6":
369 expected_backend = "qtagg"
370 elif name == "notebook":
371 expected_backend, expected_gui = expected_gui, expected_backend
372
373 gui, backend = pt.find_gui_and_backend(name)
374 if not mpl_manages_backends:
375 gui = gui.lower() if gui else None
376 backend = backend.lower() if backend else None
377 assert gui == expected_gui
378 assert backend == expected_backend
379
380
381 def test_backend_entry_point():
382 gui, backend = pt.find_gui_and_backend("inline")
383 assert gui is None
384 expected_backend = (
385 "inline"
386 if pt._matplotlib_manages_backends()
387 else "module://matplotlib_inline.backend_inline"
388 )
389 assert backend == expected_backend
390
391
392 def test_backend_unknown():
393 with pytest.raises(RuntimeError if pt._matplotlib_manages_backends() else KeyError):
394 pt.find_gui_and_backend("name-does-not-exist")