Show More
@@ -1,511 +1,515 b'' | |||||
1 | # Copyright (c) IPython Development Team. |
|
1 | # Copyright (c) IPython Development Team. | |
2 | # Distributed under the terms of the Modified BSD License. |
|
2 | # Distributed under the terms of the Modified BSD License. | |
3 |
|
3 | |||
4 | import json |
|
4 | import json | |
5 | import os |
|
5 | import os | |
6 | import warnings |
|
6 | import warnings | |
7 |
|
7 | |||
8 | from unittest import mock |
|
8 | from unittest import mock | |
9 |
|
9 | |||
10 | import pytest |
|
10 | import pytest | |
11 |
|
11 | |||
12 | from IPython import display |
|
12 | from IPython import display | |
13 | from IPython.core.getipython import get_ipython |
|
13 | from IPython.core.getipython import get_ipython | |
14 | from IPython.utils.io import capture_output |
|
14 | from IPython.utils.io import capture_output | |
15 | from IPython.utils.tempdir import NamedFileInTemporaryDirectory |
|
15 | from IPython.utils.tempdir import NamedFileInTemporaryDirectory | |
16 | from IPython import paths as ipath |
|
16 | from IPython import paths as ipath | |
17 | from IPython.testing.tools import AssertNotPrints |
|
17 | from IPython.testing.tools import AssertNotPrints | |
18 |
|
18 | |||
19 | import IPython.testing.decorators as dec |
|
19 | import IPython.testing.decorators as dec | |
20 |
|
20 | |||
21 | def test_image_size(): |
|
21 | def test_image_size(): | |
22 | """Simple test for display.Image(args, width=x,height=y)""" |
|
22 | """Simple test for display.Image(args, width=x,height=y)""" | |
23 | thisurl = 'http://www.google.fr/images/srpr/logo3w.png' |
|
23 | thisurl = 'http://www.google.fr/images/srpr/logo3w.png' | |
24 | img = display.Image(url=thisurl, width=200, height=200) |
|
24 | img = display.Image(url=thisurl, width=200, height=200) | |
25 | assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_() |
|
25 | assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_() | |
26 | img = display.Image(url=thisurl, metadata={'width':200, 'height':200}) |
|
26 | img = display.Image(url=thisurl, metadata={'width':200, 'height':200}) | |
27 | assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_() |
|
27 | assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_() | |
28 | img = display.Image(url=thisurl, width=200) |
|
28 | img = display.Image(url=thisurl, width=200) | |
29 | assert '<img src="%s" width="200"/>' % (thisurl) == img._repr_html_() |
|
29 | assert '<img src="%s" width="200"/>' % (thisurl) == img._repr_html_() | |
30 | img = display.Image(url=thisurl) |
|
30 | img = display.Image(url=thisurl) | |
31 | assert '<img src="%s"/>' % (thisurl) == img._repr_html_() |
|
31 | assert '<img src="%s"/>' % (thisurl) == img._repr_html_() | |
32 | img = display.Image(url=thisurl, unconfined=True) |
|
32 | img = display.Image(url=thisurl, unconfined=True) | |
33 | assert '<img src="%s" class="unconfined"/>' % (thisurl) == img._repr_html_() |
|
33 | assert '<img src="%s" class="unconfined"/>' % (thisurl) == img._repr_html_() | |
34 |
|
34 | |||
35 |
|
35 | |||
36 | def test_image_mimes(): |
|
36 | def test_image_mimes(): | |
37 | fmt = get_ipython().display_formatter.format |
|
37 | fmt = get_ipython().display_formatter.format | |
38 | for format in display.Image._ACCEPTABLE_EMBEDDINGS: |
|
38 | for format in display.Image._ACCEPTABLE_EMBEDDINGS: | |
39 | mime = display.Image._MIMETYPES[format] |
|
39 | mime = display.Image._MIMETYPES[format] | |
40 | img = display.Image(b'garbage', format=format) |
|
40 | img = display.Image(b'garbage', format=format) | |
41 | data, metadata = fmt(img) |
|
41 | data, metadata = fmt(img) | |
42 | assert sorted(data) == sorted([mime, "text/plain"]) |
|
42 | assert sorted(data) == sorted([mime, "text/plain"]) | |
43 |
|
43 | |||
44 |
|
44 | |||
45 | def test_geojson(): |
|
45 | def test_geojson(): | |
46 |
|
46 | |||
47 | gj = display.GeoJSON(data={ |
|
47 | gj = display.GeoJSON(data={ | |
48 | "type": "Feature", |
|
48 | "type": "Feature", | |
49 | "geometry": { |
|
49 | "geometry": { | |
50 | "type": "Point", |
|
50 | "type": "Point", | |
51 | "coordinates": [-81.327, 296.038] |
|
51 | "coordinates": [-81.327, 296.038] | |
52 | }, |
|
52 | }, | |
53 | "properties": { |
|
53 | "properties": { | |
54 | "name": "Inca City" |
|
54 | "name": "Inca City" | |
55 | } |
|
55 | } | |
56 | }, |
|
56 | }, | |
57 | url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png", |
|
57 | url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png", | |
58 | layer_options={ |
|
58 | layer_options={ | |
59 | "basemap_id": "celestia_mars-shaded-16k_global", |
|
59 | "basemap_id": "celestia_mars-shaded-16k_global", | |
60 | "attribution": "Celestia/praesepe", |
|
60 | "attribution": "Celestia/praesepe", | |
61 | "minZoom": 0, |
|
61 | "minZoom": 0, | |
62 | "maxZoom": 18, |
|
62 | "maxZoom": 18, | |
63 | }, |
|
63 | }, | |
64 | ) |
|
64 | ) | |
65 | assert "<IPython.core.display.GeoJSON object>" == str(gj) |
|
65 | assert "<IPython.core.display.GeoJSON object>" == str(gj) | |
66 |
|
66 | |||
67 |
|
67 | |||
68 | def test_retina_png(): |
|
68 | def test_retina_png(): | |
69 | here = os.path.dirname(__file__) |
|
69 | here = os.path.dirname(__file__) | |
70 | img = display.Image(os.path.join(here, "2x2.png"), retina=True) |
|
70 | img = display.Image(os.path.join(here, "2x2.png"), retina=True) | |
71 | assert img.height == 1 |
|
71 | assert img.height == 1 | |
72 | assert img.width == 1 |
|
72 | assert img.width == 1 | |
73 | data, md = img._repr_png_() |
|
73 | data, md = img._repr_png_() | |
74 | assert md["width"] == 1 |
|
74 | assert md["width"] == 1 | |
75 | assert md["height"] == 1 |
|
75 | assert md["height"] == 1 | |
76 |
|
76 | |||
77 |
|
77 | |||
78 | def test_embed_svg_url(): |
|
78 | def test_embed_svg_url(): | |
79 | import gzip |
|
79 | import gzip | |
80 | from io import BytesIO |
|
80 | from io import BytesIO | |
81 | svg_data = b'<svg><circle x="0" y="0" r="1"/></svg>' |
|
81 | svg_data = b'<svg><circle x="0" y="0" r="1"/></svg>' | |
82 | url = 'http://test.com/circle.svg' |
|
82 | url = 'http://test.com/circle.svg' | |
83 |
|
83 | |||
84 | gzip_svg = BytesIO() |
|
84 | gzip_svg = BytesIO() | |
85 | with gzip.open(gzip_svg, 'wb') as fp: |
|
85 | with gzip.open(gzip_svg, 'wb') as fp: | |
86 | fp.write(svg_data) |
|
86 | fp.write(svg_data) | |
87 | gzip_svg = gzip_svg.getvalue() |
|
87 | gzip_svg = gzip_svg.getvalue() | |
88 |
|
88 | |||
89 | def mocked_urlopen(*args, **kwargs): |
|
89 | def mocked_urlopen(*args, **kwargs): | |
90 | class MockResponse: |
|
90 | class MockResponse: | |
91 | def __init__(self, svg): |
|
91 | def __init__(self, svg): | |
92 | self._svg_data = svg |
|
92 | self._svg_data = svg | |
93 | self.headers = {'content-type': 'image/svg+xml'} |
|
93 | self.headers = {'content-type': 'image/svg+xml'} | |
94 |
|
94 | |||
95 | def read(self): |
|
95 | def read(self): | |
96 | return self._svg_data |
|
96 | return self._svg_data | |
97 |
|
97 | |||
98 | if args[0] == url: |
|
98 | if args[0] == url: | |
99 | return MockResponse(svg_data) |
|
99 | return MockResponse(svg_data) | |
100 | elif args[0] == url + "z": |
|
100 | elif args[0] == url + "z": | |
101 | ret = MockResponse(gzip_svg) |
|
101 | ret = MockResponse(gzip_svg) | |
102 | ret.headers["content-encoding"] = "gzip" |
|
102 | ret.headers["content-encoding"] = "gzip" | |
103 | return ret |
|
103 | return ret | |
104 | return MockResponse(None) |
|
104 | return MockResponse(None) | |
105 |
|
105 | |||
106 | with mock.patch('urllib.request.urlopen', side_effect=mocked_urlopen): |
|
106 | with mock.patch('urllib.request.urlopen', side_effect=mocked_urlopen): | |
107 | svg = display.SVG(url=url) |
|
107 | svg = display.SVG(url=url) | |
108 | assert svg._repr_svg_().startswith("<svg") is True |
|
108 | assert svg._repr_svg_().startswith("<svg") is True | |
109 | svg = display.SVG(url=url + "z") |
|
109 | svg = display.SVG(url=url + "z") | |
110 | assert svg._repr_svg_().startswith("<svg") is True |
|
110 | assert svg._repr_svg_().startswith("<svg") is True | |
111 |
|
111 | |||
112 |
|
112 | |||
113 | def test_retina_jpeg(): |
|
113 | def test_retina_jpeg(): | |
114 | here = os.path.dirname(__file__) |
|
114 | here = os.path.dirname(__file__) | |
115 | img = display.Image(os.path.join(here, "2x2.jpg"), retina=True) |
|
115 | img = display.Image(os.path.join(here, "2x2.jpg"), retina=True) | |
116 | assert img.height == 1 |
|
116 | assert img.height == 1 | |
117 | assert img.width == 1 |
|
117 | assert img.width == 1 | |
118 | data, md = img._repr_jpeg_() |
|
118 | data, md = img._repr_jpeg_() | |
119 | assert md["width"] == 1 |
|
119 | assert md["width"] == 1 | |
120 | assert md["height"] == 1 |
|
120 | assert md["height"] == 1 | |
121 |
|
121 | |||
122 |
|
122 | |||
123 | def test_base64image(): |
|
123 | def test_base64image(): | |
124 | display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC") |
|
124 | display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC") | |
125 |
|
125 | |||
126 | def test_image_filename_defaults(): |
|
126 | def test_image_filename_defaults(): | |
127 | '''test format constraint, and validity of jpeg and png''' |
|
127 | '''test format constraint, and validity of jpeg and png''' | |
128 | tpath = ipath.get_ipython_package_dir() |
|
128 | tpath = ipath.get_ipython_package_dir() | |
129 | pytest.raises( |
|
129 | pytest.raises( | |
130 | ValueError, |
|
130 | ValueError, | |
131 | display.Image, |
|
131 | display.Image, | |
132 | filename=os.path.join(tpath, "testing/tests/badformat.zip"), |
|
132 | filename=os.path.join(tpath, "testing/tests/badformat.zip"), | |
133 | embed=True, |
|
133 | embed=True, | |
134 | ) |
|
134 | ) | |
135 | pytest.raises(ValueError, display.Image) |
|
135 | pytest.raises(ValueError, display.Image) | |
136 | pytest.raises( |
|
136 | pytest.raises( | |
137 | ValueError, |
|
137 | ValueError, | |
138 | display.Image, |
|
138 | display.Image, | |
139 | data="this is not an image", |
|
139 | data="this is not an image", | |
140 | format="badformat", |
|
140 | format="badformat", | |
141 | embed=True, |
|
141 | embed=True, | |
142 | ) |
|
142 | ) | |
143 | # check boths paths to allow packages to test at build and install time |
|
143 | # check boths paths to allow packages to test at build and install time | |
144 | imgfile = os.path.join(tpath, 'core/tests/2x2.png') |
|
144 | imgfile = os.path.join(tpath, 'core/tests/2x2.png') | |
145 | img = display.Image(filename=imgfile) |
|
145 | img = display.Image(filename=imgfile) | |
146 | assert "png" == img.format |
|
146 | assert "png" == img.format | |
147 | assert img._repr_png_() is not None |
|
147 | assert img._repr_png_() is not None | |
148 | img = display.Image( |
|
148 | img = display.Image( | |
149 | filename=os.path.join(tpath, "testing/tests/logo.jpg"), embed=False |
|
149 | filename=os.path.join(tpath, "testing/tests/logo.jpg"), embed=False | |
150 | ) |
|
150 | ) | |
151 | assert "jpeg" == img.format |
|
151 | assert "jpeg" == img.format | |
152 | assert img._repr_jpeg_() is None |
|
152 | assert img._repr_jpeg_() is None | |
153 |
|
153 | |||
154 | def _get_inline_config(): |
|
154 | def _get_inline_config(): | |
155 | from matplotlib_inline.config import InlineBackend |
|
155 | from matplotlib_inline.config import InlineBackend | |
156 | return InlineBackend.instance() |
|
156 | return InlineBackend.instance() | |
157 |
|
157 | |||
158 |
|
158 | |||
159 | @dec.skip_without("ipykernel") |
|
159 | @dec.skip_without("ipykernel") | |
160 | @dec.skip_without("matplotlib") |
|
160 | @dec.skip_without("matplotlib") | |
161 | def test_set_matplotlib_close(): |
|
161 | def test_set_matplotlib_close(): | |
162 | cfg = _get_inline_config() |
|
162 | cfg = _get_inline_config() | |
163 | cfg.close_figures = False |
|
163 | cfg.close_figures = False | |
164 | display.set_matplotlib_close() |
|
164 | with pytest.deprecated_call(): | |
|
165 | display.set_matplotlib_close() | |||
165 | assert cfg.close_figures |
|
166 | assert cfg.close_figures | |
166 | display.set_matplotlib_close(False) |
|
167 | with pytest.deprecated_call(): | |
|
168 | display.set_matplotlib_close(False) | |||
167 | assert not cfg.close_figures |
|
169 | assert not cfg.close_figures | |
168 |
|
170 | |||
169 | _fmt_mime_map = { |
|
171 | _fmt_mime_map = { | |
170 | 'png': 'image/png', |
|
172 | 'png': 'image/png', | |
171 | 'jpeg': 'image/jpeg', |
|
173 | 'jpeg': 'image/jpeg', | |
172 | 'pdf': 'application/pdf', |
|
174 | 'pdf': 'application/pdf', | |
173 | 'retina': 'image/png', |
|
175 | 'retina': 'image/png', | |
174 | 'svg': 'image/svg+xml', |
|
176 | 'svg': 'image/svg+xml', | |
175 | } |
|
177 | } | |
176 |
|
178 | |||
177 | @dec.skip_without('matplotlib') |
|
179 | @dec.skip_without('matplotlib') | |
178 | def test_set_matplotlib_formats(): |
|
180 | def test_set_matplotlib_formats(): | |
179 | from matplotlib.figure import Figure |
|
181 | from matplotlib.figure import Figure | |
180 | formatters = get_ipython().display_formatter.formatters |
|
182 | formatters = get_ipython().display_formatter.formatters | |
181 | for formats in [ |
|
183 | for formats in [ | |
182 | ('png',), |
|
184 | ('png',), | |
183 | ('pdf', 'svg'), |
|
185 | ('pdf', 'svg'), | |
184 | ('jpeg', 'retina', 'png'), |
|
186 | ('jpeg', 'retina', 'png'), | |
185 | (), |
|
187 | (), | |
186 | ]: |
|
188 | ]: | |
187 | active_mimes = {_fmt_mime_map[fmt] for fmt in formats} |
|
189 | active_mimes = {_fmt_mime_map[fmt] for fmt in formats} | |
188 | display.set_matplotlib_formats(*formats) |
|
190 | with pytest.deprecated_call(): | |
|
191 | display.set_matplotlib_formats(*formats) | |||
189 | for mime, f in formatters.items(): |
|
192 | for mime, f in formatters.items(): | |
190 | if mime in active_mimes: |
|
193 | if mime in active_mimes: | |
191 | assert Figure in f |
|
194 | assert Figure in f | |
192 | else: |
|
195 | else: | |
193 | assert Figure not in f |
|
196 | assert Figure not in f | |
194 |
|
197 | |||
195 |
|
198 | |||
196 | @dec.skip_without("ipykernel") |
|
199 | @dec.skip_without("ipykernel") | |
197 | @dec.skip_without("matplotlib") |
|
200 | @dec.skip_without("matplotlib") | |
198 | def test_set_matplotlib_formats_kwargs(): |
|
201 | def test_set_matplotlib_formats_kwargs(): | |
199 | from matplotlib.figure import Figure |
|
202 | from matplotlib.figure import Figure | |
200 | ip = get_ipython() |
|
203 | ip = get_ipython() | |
201 | cfg = _get_inline_config() |
|
204 | cfg = _get_inline_config() | |
202 | cfg.print_figure_kwargs.update(dict(foo='bar')) |
|
205 | cfg.print_figure_kwargs.update(dict(foo='bar')) | |
203 | kwargs = dict(dpi=150) |
|
206 | kwargs = dict(dpi=150) | |
204 | display.set_matplotlib_formats('png', **kwargs) |
|
207 | with pytest.deprecated_call(): | |
205 | formatter = ip.display_formatter.formatters['image/png'] |
|
208 | display.set_matplotlib_formats("png", **kwargs) | |
|
209 | formatter = ip.display_formatter.formatters["image/png"] | |||
206 | f = formatter.lookup_by_type(Figure) |
|
210 | f = formatter.lookup_by_type(Figure) | |
207 | formatter_kwargs = f.keywords |
|
211 | formatter_kwargs = f.keywords | |
208 | expected = kwargs |
|
212 | expected = kwargs | |
209 | expected["base64"] = True |
|
213 | expected["base64"] = True | |
210 | expected["fmt"] = "png" |
|
214 | expected["fmt"] = "png" | |
211 | expected.update(cfg.print_figure_kwargs) |
|
215 | expected.update(cfg.print_figure_kwargs) | |
212 | assert formatter_kwargs == expected |
|
216 | assert formatter_kwargs == expected | |
213 |
|
217 | |||
214 | def test_display_available(): |
|
218 | def test_display_available(): | |
215 | """ |
|
219 | """ | |
216 | Test that display is available without import |
|
220 | Test that display is available without import | |
217 |
|
221 | |||
218 | We don't really care if it's in builtin or anything else, but it should |
|
222 | We don't really care if it's in builtin or anything else, but it should | |
219 | always be available. |
|
223 | always be available. | |
220 | """ |
|
224 | """ | |
221 | ip = get_ipython() |
|
225 | ip = get_ipython() | |
222 | with AssertNotPrints('NameError'): |
|
226 | with AssertNotPrints('NameError'): | |
223 | ip.run_cell('display') |
|
227 | ip.run_cell('display') | |
224 | try: |
|
228 | try: | |
225 | ip.run_cell('del display') |
|
229 | ip.run_cell('del display') | |
226 | except NameError: |
|
230 | except NameError: | |
227 | pass # it's ok, it might be in builtins |
|
231 | pass # it's ok, it might be in builtins | |
228 | # even if deleted it should be back |
|
232 | # even if deleted it should be back | |
229 | with AssertNotPrints('NameError'): |
|
233 | with AssertNotPrints('NameError'): | |
230 | ip.run_cell('display') |
|
234 | ip.run_cell('display') | |
231 |
|
235 | |||
232 | def test_textdisplayobj_pretty_repr(): |
|
236 | def test_textdisplayobj_pretty_repr(): | |
233 | p = display.Pretty("This is a simple test") |
|
237 | p = display.Pretty("This is a simple test") | |
234 | assert repr(p) == "<IPython.core.display.Pretty object>" |
|
238 | assert repr(p) == "<IPython.core.display.Pretty object>" | |
235 | assert p.data == "This is a simple test" |
|
239 | assert p.data == "This is a simple test" | |
236 |
|
240 | |||
237 | p._show_mem_addr = True |
|
241 | p._show_mem_addr = True | |
238 | assert repr(p) == object.__repr__(p) |
|
242 | assert repr(p) == object.__repr__(p) | |
239 |
|
243 | |||
240 |
|
244 | |||
241 | def test_displayobject_repr(): |
|
245 | def test_displayobject_repr(): | |
242 | h = display.HTML("<br />") |
|
246 | h = display.HTML("<br />") | |
243 | assert repr(h) == "<IPython.core.display.HTML object>" |
|
247 | assert repr(h) == "<IPython.core.display.HTML object>" | |
244 | h._show_mem_addr = True |
|
248 | h._show_mem_addr = True | |
245 | assert repr(h) == object.__repr__(h) |
|
249 | assert repr(h) == object.__repr__(h) | |
246 | h._show_mem_addr = False |
|
250 | h._show_mem_addr = False | |
247 | assert repr(h) == "<IPython.core.display.HTML object>" |
|
251 | assert repr(h) == "<IPython.core.display.HTML object>" | |
248 |
|
252 | |||
249 | j = display.Javascript("") |
|
253 | j = display.Javascript("") | |
250 | assert repr(j) == "<IPython.core.display.Javascript object>" |
|
254 | assert repr(j) == "<IPython.core.display.Javascript object>" | |
251 | j._show_mem_addr = True |
|
255 | j._show_mem_addr = True | |
252 | assert repr(j) == object.__repr__(j) |
|
256 | assert repr(j) == object.__repr__(j) | |
253 | j._show_mem_addr = False |
|
257 | j._show_mem_addr = False | |
254 | assert repr(j) == "<IPython.core.display.Javascript object>" |
|
258 | assert repr(j) == "<IPython.core.display.Javascript object>" | |
255 |
|
259 | |||
256 | @mock.patch('warnings.warn') |
|
260 | @mock.patch('warnings.warn') | |
257 | def test_encourage_iframe_over_html(m_warn): |
|
261 | def test_encourage_iframe_over_html(m_warn): | |
258 | display.HTML() |
|
262 | display.HTML() | |
259 | m_warn.assert_not_called() |
|
263 | m_warn.assert_not_called() | |
260 |
|
264 | |||
261 | display.HTML('<br />') |
|
265 | display.HTML('<br />') | |
262 | m_warn.assert_not_called() |
|
266 | m_warn.assert_not_called() | |
263 |
|
267 | |||
264 | display.HTML('<html><p>Lots of content here</p><iframe src="http://a.com"></iframe>') |
|
268 | display.HTML('<html><p>Lots of content here</p><iframe src="http://a.com"></iframe>') | |
265 | m_warn.assert_not_called() |
|
269 | m_warn.assert_not_called() | |
266 |
|
270 | |||
267 | display.HTML('<iframe src="http://a.com"></iframe>') |
|
271 | display.HTML('<iframe src="http://a.com"></iframe>') | |
268 | m_warn.assert_called_with('Consider using IPython.display.IFrame instead') |
|
272 | m_warn.assert_called_with('Consider using IPython.display.IFrame instead') | |
269 |
|
273 | |||
270 | m_warn.reset_mock() |
|
274 | m_warn.reset_mock() | |
271 | display.HTML('<IFRAME SRC="http://a.com"></IFRAME>') |
|
275 | display.HTML('<IFRAME SRC="http://a.com"></IFRAME>') | |
272 | m_warn.assert_called_with('Consider using IPython.display.IFrame instead') |
|
276 | m_warn.assert_called_with('Consider using IPython.display.IFrame instead') | |
273 |
|
277 | |||
274 | def test_progress(): |
|
278 | def test_progress(): | |
275 | p = display.ProgressBar(10) |
|
279 | p = display.ProgressBar(10) | |
276 | assert "0/10" in repr(p) |
|
280 | assert "0/10" in repr(p) | |
277 | p.html_width = "100%" |
|
281 | p.html_width = "100%" | |
278 | p.progress = 5 |
|
282 | p.progress = 5 | |
279 | assert ( |
|
283 | assert ( | |
280 | p._repr_html_() == "<progress style='width:100%' max='10' value='5'></progress>" |
|
284 | p._repr_html_() == "<progress style='width:100%' max='10' value='5'></progress>" | |
281 | ) |
|
285 | ) | |
282 |
|
286 | |||
283 |
|
287 | |||
284 | def test_progress_iter(): |
|
288 | def test_progress_iter(): | |
285 | with capture_output(display=False) as captured: |
|
289 | with capture_output(display=False) as captured: | |
286 | for i in display.ProgressBar(5): |
|
290 | for i in display.ProgressBar(5): | |
287 | out = captured.stdout |
|
291 | out = captured.stdout | |
288 | assert "{0}/5".format(i) in out |
|
292 | assert "{0}/5".format(i) in out | |
289 | out = captured.stdout |
|
293 | out = captured.stdout | |
290 | assert "5/5" in out |
|
294 | assert "5/5" in out | |
291 |
|
295 | |||
292 |
|
296 | |||
293 | def test_json(): |
|
297 | def test_json(): | |
294 | d = {'a': 5} |
|
298 | d = {'a': 5} | |
295 | lis = [d] |
|
299 | lis = [d] | |
296 | metadata = [ |
|
300 | metadata = [ | |
297 | {'expanded': False, 'root': 'root'}, |
|
301 | {'expanded': False, 'root': 'root'}, | |
298 | {'expanded': True, 'root': 'root'}, |
|
302 | {'expanded': True, 'root': 'root'}, | |
299 | {'expanded': False, 'root': 'custom'}, |
|
303 | {'expanded': False, 'root': 'custom'}, | |
300 | {'expanded': True, 'root': 'custom'}, |
|
304 | {'expanded': True, 'root': 'custom'}, | |
301 | ] |
|
305 | ] | |
302 | json_objs = [ |
|
306 | json_objs = [ | |
303 | display.JSON(d), |
|
307 | display.JSON(d), | |
304 | display.JSON(d, expanded=True), |
|
308 | display.JSON(d, expanded=True), | |
305 | display.JSON(d, root='custom'), |
|
309 | display.JSON(d, root='custom'), | |
306 | display.JSON(d, expanded=True, root='custom'), |
|
310 | display.JSON(d, expanded=True, root='custom'), | |
307 | ] |
|
311 | ] | |
308 | for j, md in zip(json_objs, metadata): |
|
312 | for j, md in zip(json_objs, metadata): | |
309 | assert j._repr_json_() == (d, md) |
|
313 | assert j._repr_json_() == (d, md) | |
310 |
|
314 | |||
311 | with warnings.catch_warnings(record=True) as w: |
|
315 | with warnings.catch_warnings(record=True) as w: | |
312 | warnings.simplefilter("always") |
|
316 | warnings.simplefilter("always") | |
313 | j = display.JSON(json.dumps(d)) |
|
317 | j = display.JSON(json.dumps(d)) | |
314 | assert len(w) == 1 |
|
318 | assert len(w) == 1 | |
315 | assert j._repr_json_() == (d, metadata[0]) |
|
319 | assert j._repr_json_() == (d, metadata[0]) | |
316 |
|
320 | |||
317 | json_objs = [ |
|
321 | json_objs = [ | |
318 | display.JSON(lis), |
|
322 | display.JSON(lis), | |
319 | display.JSON(lis, expanded=True), |
|
323 | display.JSON(lis, expanded=True), | |
320 | display.JSON(lis, root='custom'), |
|
324 | display.JSON(lis, root='custom'), | |
321 | display.JSON(lis, expanded=True, root='custom'), |
|
325 | display.JSON(lis, expanded=True, root='custom'), | |
322 | ] |
|
326 | ] | |
323 | for j, md in zip(json_objs, metadata): |
|
327 | for j, md in zip(json_objs, metadata): | |
324 | assert j._repr_json_() == (lis, md) |
|
328 | assert j._repr_json_() == (lis, md) | |
325 |
|
329 | |||
326 | with warnings.catch_warnings(record=True) as w: |
|
330 | with warnings.catch_warnings(record=True) as w: | |
327 | warnings.simplefilter("always") |
|
331 | warnings.simplefilter("always") | |
328 | j = display.JSON(json.dumps(lis)) |
|
332 | j = display.JSON(json.dumps(lis)) | |
329 | assert len(w) == 1 |
|
333 | assert len(w) == 1 | |
330 | assert j._repr_json_() == (lis, metadata[0]) |
|
334 | assert j._repr_json_() == (lis, metadata[0]) | |
331 |
|
335 | |||
332 |
|
336 | |||
333 | def test_video_embedding(): |
|
337 | def test_video_embedding(): | |
334 | """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash""" |
|
338 | """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash""" | |
335 | v = display.Video("http://ignored") |
|
339 | v = display.Video("http://ignored") | |
336 | assert not v.embed |
|
340 | assert not v.embed | |
337 | html = v._repr_html_() |
|
341 | html = v._repr_html_() | |
338 | assert 'src="data:' not in html |
|
342 | assert 'src="data:' not in html | |
339 | assert 'src="http://ignored"' in html |
|
343 | assert 'src="http://ignored"' in html | |
340 |
|
344 | |||
341 | with pytest.raises(ValueError): |
|
345 | with pytest.raises(ValueError): | |
342 | v = display.Video(b'abc') |
|
346 | v = display.Video(b'abc') | |
343 |
|
347 | |||
344 | with NamedFileInTemporaryDirectory('test.mp4') as f: |
|
348 | with NamedFileInTemporaryDirectory('test.mp4') as f: | |
345 | f.write(b'abc') |
|
349 | f.write(b'abc') | |
346 | f.close() |
|
350 | f.close() | |
347 |
|
351 | |||
348 | v = display.Video(f.name) |
|
352 | v = display.Video(f.name) | |
349 | assert not v.embed |
|
353 | assert not v.embed | |
350 | html = v._repr_html_() |
|
354 | html = v._repr_html_() | |
351 | assert 'src="data:' not in html |
|
355 | assert 'src="data:' not in html | |
352 |
|
356 | |||
353 | v = display.Video(f.name, embed=True) |
|
357 | v = display.Video(f.name, embed=True) | |
354 | html = v._repr_html_() |
|
358 | html = v._repr_html_() | |
355 | assert 'src="data:video/mp4;base64,YWJj"' in html |
|
359 | assert 'src="data:video/mp4;base64,YWJj"' in html | |
356 |
|
360 | |||
357 | v = display.Video(f.name, embed=True, mimetype='video/other') |
|
361 | v = display.Video(f.name, embed=True, mimetype='video/other') | |
358 | html = v._repr_html_() |
|
362 | html = v._repr_html_() | |
359 | assert 'src="data:video/other;base64,YWJj"' in html |
|
363 | assert 'src="data:video/other;base64,YWJj"' in html | |
360 |
|
364 | |||
361 | v = display.Video(b'abc', embed=True, mimetype='video/mp4') |
|
365 | v = display.Video(b'abc', embed=True, mimetype='video/mp4') | |
362 | html = v._repr_html_() |
|
366 | html = v._repr_html_() | |
363 | assert 'src="data:video/mp4;base64,YWJj"' in html |
|
367 | assert 'src="data:video/mp4;base64,YWJj"' in html | |
364 |
|
368 | |||
365 | v = display.Video(u'YWJj', embed=True, mimetype='video/xyz') |
|
369 | v = display.Video(u'YWJj', embed=True, mimetype='video/xyz') | |
366 | html = v._repr_html_() |
|
370 | html = v._repr_html_() | |
367 | assert 'src="data:video/xyz;base64,YWJj"' in html |
|
371 | assert 'src="data:video/xyz;base64,YWJj"' in html | |
368 |
|
372 | |||
369 | def test_html_metadata(): |
|
373 | def test_html_metadata(): | |
370 | s = "<h1>Test</h1>" |
|
374 | s = "<h1>Test</h1>" | |
371 | h = display.HTML(s, metadata={"isolated": True}) |
|
375 | h = display.HTML(s, metadata={"isolated": True}) | |
372 | assert h._repr_html_() == (s, {"isolated": True}) |
|
376 | assert h._repr_html_() == (s, {"isolated": True}) | |
373 |
|
377 | |||
374 |
|
378 | |||
375 | def test_display_id(): |
|
379 | def test_display_id(): | |
376 | ip = get_ipython() |
|
380 | ip = get_ipython() | |
377 | with mock.patch.object(ip.display_pub, 'publish') as pub: |
|
381 | with mock.patch.object(ip.display_pub, 'publish') as pub: | |
378 | handle = display.display('x') |
|
382 | handle = display.display('x') | |
379 | assert handle is None |
|
383 | assert handle is None | |
380 | handle = display.display('y', display_id='secret') |
|
384 | handle = display.display('y', display_id='secret') | |
381 | assert isinstance(handle, display.DisplayHandle) |
|
385 | assert isinstance(handle, display.DisplayHandle) | |
382 | handle2 = display.display('z', display_id=True) |
|
386 | handle2 = display.display('z', display_id=True) | |
383 | assert isinstance(handle2, display.DisplayHandle) |
|
387 | assert isinstance(handle2, display.DisplayHandle) | |
384 | assert handle.display_id != handle2.display_id |
|
388 | assert handle.display_id != handle2.display_id | |
385 |
|
389 | |||
386 | assert pub.call_count == 3 |
|
390 | assert pub.call_count == 3 | |
387 | args, kwargs = pub.call_args_list[0] |
|
391 | args, kwargs = pub.call_args_list[0] | |
388 | assert args == () |
|
392 | assert args == () | |
389 | assert kwargs == { |
|
393 | assert kwargs == { | |
390 | 'data': { |
|
394 | 'data': { | |
391 | 'text/plain': repr('x') |
|
395 | 'text/plain': repr('x') | |
392 | }, |
|
396 | }, | |
393 | 'metadata': {}, |
|
397 | 'metadata': {}, | |
394 | } |
|
398 | } | |
395 | args, kwargs = pub.call_args_list[1] |
|
399 | args, kwargs = pub.call_args_list[1] | |
396 | assert args == () |
|
400 | assert args == () | |
397 | assert kwargs == { |
|
401 | assert kwargs == { | |
398 | 'data': { |
|
402 | 'data': { | |
399 | 'text/plain': repr('y') |
|
403 | 'text/plain': repr('y') | |
400 | }, |
|
404 | }, | |
401 | 'metadata': {}, |
|
405 | 'metadata': {}, | |
402 | 'transient': { |
|
406 | 'transient': { | |
403 | 'display_id': handle.display_id, |
|
407 | 'display_id': handle.display_id, | |
404 | }, |
|
408 | }, | |
405 | } |
|
409 | } | |
406 | args, kwargs = pub.call_args_list[2] |
|
410 | args, kwargs = pub.call_args_list[2] | |
407 | assert args == () |
|
411 | assert args == () | |
408 | assert kwargs == { |
|
412 | assert kwargs == { | |
409 | 'data': { |
|
413 | 'data': { | |
410 | 'text/plain': repr('z') |
|
414 | 'text/plain': repr('z') | |
411 | }, |
|
415 | }, | |
412 | 'metadata': {}, |
|
416 | 'metadata': {}, | |
413 | 'transient': { |
|
417 | 'transient': { | |
414 | 'display_id': handle2.display_id, |
|
418 | 'display_id': handle2.display_id, | |
415 | }, |
|
419 | }, | |
416 | } |
|
420 | } | |
417 |
|
421 | |||
418 |
|
422 | |||
419 | def test_update_display(): |
|
423 | def test_update_display(): | |
420 | ip = get_ipython() |
|
424 | ip = get_ipython() | |
421 | with mock.patch.object(ip.display_pub, 'publish') as pub: |
|
425 | with mock.patch.object(ip.display_pub, 'publish') as pub: | |
422 | with pytest.raises(TypeError): |
|
426 | with pytest.raises(TypeError): | |
423 | display.update_display('x') |
|
427 | display.update_display('x') | |
424 | display.update_display('x', display_id='1') |
|
428 | display.update_display('x', display_id='1') | |
425 | display.update_display('y', display_id='2') |
|
429 | display.update_display('y', display_id='2') | |
426 | args, kwargs = pub.call_args_list[0] |
|
430 | args, kwargs = pub.call_args_list[0] | |
427 | assert args == () |
|
431 | assert args == () | |
428 | assert kwargs == { |
|
432 | assert kwargs == { | |
429 | 'data': { |
|
433 | 'data': { | |
430 | 'text/plain': repr('x') |
|
434 | 'text/plain': repr('x') | |
431 | }, |
|
435 | }, | |
432 | 'metadata': {}, |
|
436 | 'metadata': {}, | |
433 | 'transient': { |
|
437 | 'transient': { | |
434 | 'display_id': '1', |
|
438 | 'display_id': '1', | |
435 | }, |
|
439 | }, | |
436 | 'update': True, |
|
440 | 'update': True, | |
437 | } |
|
441 | } | |
438 | args, kwargs = pub.call_args_list[1] |
|
442 | args, kwargs = pub.call_args_list[1] | |
439 | assert args == () |
|
443 | assert args == () | |
440 | assert kwargs == { |
|
444 | assert kwargs == { | |
441 | 'data': { |
|
445 | 'data': { | |
442 | 'text/plain': repr('y') |
|
446 | 'text/plain': repr('y') | |
443 | }, |
|
447 | }, | |
444 | 'metadata': {}, |
|
448 | 'metadata': {}, | |
445 | 'transient': { |
|
449 | 'transient': { | |
446 | 'display_id': '2', |
|
450 | 'display_id': '2', | |
447 | }, |
|
451 | }, | |
448 | 'update': True, |
|
452 | 'update': True, | |
449 | } |
|
453 | } | |
450 |
|
454 | |||
451 |
|
455 | |||
452 | def test_display_handle(): |
|
456 | def test_display_handle(): | |
453 | ip = get_ipython() |
|
457 | ip = get_ipython() | |
454 | handle = display.DisplayHandle() |
|
458 | handle = display.DisplayHandle() | |
455 | assert isinstance(handle.display_id, str) |
|
459 | assert isinstance(handle.display_id, str) | |
456 | handle = display.DisplayHandle("my-id") |
|
460 | handle = display.DisplayHandle("my-id") | |
457 | assert handle.display_id == "my-id" |
|
461 | assert handle.display_id == "my-id" | |
458 | with mock.patch.object(ip.display_pub, "publish") as pub: |
|
462 | with mock.patch.object(ip.display_pub, "publish") as pub: | |
459 | handle.display("x") |
|
463 | handle.display("x") | |
460 | handle.update("y") |
|
464 | handle.update("y") | |
461 |
|
465 | |||
462 | args, kwargs = pub.call_args_list[0] |
|
466 | args, kwargs = pub.call_args_list[0] | |
463 | assert args == () |
|
467 | assert args == () | |
464 | assert kwargs == { |
|
468 | assert kwargs == { | |
465 | 'data': { |
|
469 | 'data': { | |
466 | 'text/plain': repr('x') |
|
470 | 'text/plain': repr('x') | |
467 | }, |
|
471 | }, | |
468 | 'metadata': {}, |
|
472 | 'metadata': {}, | |
469 | 'transient': { |
|
473 | 'transient': { | |
470 | 'display_id': handle.display_id, |
|
474 | 'display_id': handle.display_id, | |
471 | } |
|
475 | } | |
472 | } |
|
476 | } | |
473 | args, kwargs = pub.call_args_list[1] |
|
477 | args, kwargs = pub.call_args_list[1] | |
474 | assert args == () |
|
478 | assert args == () | |
475 | assert kwargs == { |
|
479 | assert kwargs == { | |
476 | 'data': { |
|
480 | 'data': { | |
477 | 'text/plain': repr('y') |
|
481 | 'text/plain': repr('y') | |
478 | }, |
|
482 | }, | |
479 | 'metadata': {}, |
|
483 | 'metadata': {}, | |
480 | 'transient': { |
|
484 | 'transient': { | |
481 | 'display_id': handle.display_id, |
|
485 | 'display_id': handle.display_id, | |
482 | }, |
|
486 | }, | |
483 | 'update': True, |
|
487 | 'update': True, | |
484 | } |
|
488 | } | |
485 |
|
489 | |||
486 |
|
490 | |||
487 | def test_image_alt_tag(): |
|
491 | def test_image_alt_tag(): | |
488 | """Simple test for display.Image(args, alt=x,)""" |
|
492 | """Simple test for display.Image(args, alt=x,)""" | |
489 | thisurl = "http://example.com/image.png" |
|
493 | thisurl = "http://example.com/image.png" | |
490 | img = display.Image(url=thisurl, alt="an image") |
|
494 | img = display.Image(url=thisurl, alt="an image") | |
491 | assert '<img src="%s" alt="an image"/>' % (thisurl) == img._repr_html_() |
|
495 | assert '<img src="%s" alt="an image"/>' % (thisurl) == img._repr_html_() | |
492 | img = display.Image(url=thisurl, unconfined=True, alt="an image") |
|
496 | img = display.Image(url=thisurl, unconfined=True, alt="an image") | |
493 | assert ( |
|
497 | assert ( | |
494 | '<img src="%s" class="unconfined" alt="an image"/>' % (thisurl) |
|
498 | '<img src="%s" class="unconfined" alt="an image"/>' % (thisurl) | |
495 | == img._repr_html_() |
|
499 | == img._repr_html_() | |
496 | ) |
|
500 | ) | |
497 | img = display.Image(url=thisurl, alt='>"& <') |
|
501 | img = display.Image(url=thisurl, alt='>"& <') | |
498 | assert '<img src="%s" alt=">"& <"/>' % (thisurl) == img._repr_html_() |
|
502 | assert '<img src="%s" alt=">"& <"/>' % (thisurl) == img._repr_html_() | |
499 |
|
503 | |||
500 | img = display.Image(url=thisurl, metadata={"alt": "an image"}) |
|
504 | img = display.Image(url=thisurl, metadata={"alt": "an image"}) | |
501 | assert img.alt == "an image" |
|
505 | assert img.alt == "an image" | |
502 | here = os.path.dirname(__file__) |
|
506 | here = os.path.dirname(__file__) | |
503 | img = display.Image(os.path.join(here, "2x2.png"), alt="an image") |
|
507 | img = display.Image(os.path.join(here, "2x2.png"), alt="an image") | |
504 | assert img.alt == "an image" |
|
508 | assert img.alt == "an image" | |
505 | _, md = img._repr_png_() |
|
509 | _, md = img._repr_png_() | |
506 | assert md["alt"] == "an image" |
|
510 | assert md["alt"] == "an image" | |
507 |
|
511 | |||
508 |
|
512 | |||
509 | def test_image_bad_filename_raises_proper_exception(): |
|
513 | def test_image_bad_filename_raises_proper_exception(): | |
510 | with pytest.raises(FileNotFoundError): |
|
514 | with pytest.raises(FileNotFoundError): | |
511 | display.Image("/this/file/does/not/exist/")._repr_png_() |
|
515 | display.Image("/this/file/does/not/exist/")._repr_png_() |
@@ -1,274 +1,274 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 binascii import a2b_base64 |
|
8 | from binascii import a2b_base64 | |
9 | from io import BytesIO |
|
9 | from io import BytesIO | |
10 |
|
10 | |||
11 | import pytest |
|
11 | import pytest | |
12 |
|
12 | |||
13 | matplotlib = pytest.importorskip("matplotlib") |
|
13 | matplotlib = pytest.importorskip("matplotlib") | |
14 | matplotlib.use('Agg') |
|
14 | matplotlib.use('Agg') | |
15 | from matplotlib.figure import Figure |
|
15 | from matplotlib.figure import Figure | |
16 |
|
16 | |||
17 | from matplotlib import pyplot as plt |
|
17 | from matplotlib import pyplot as plt | |
18 | from matplotlib_inline import backend_inline |
|
18 | from matplotlib_inline import backend_inline | |
19 | import numpy as np |
|
19 | import numpy as np | |
20 |
|
20 | |||
21 | from IPython.core.getipython import get_ipython |
|
21 | from IPython.core.getipython import get_ipython | |
22 | from IPython.core.interactiveshell import InteractiveShell |
|
22 | from IPython.core.interactiveshell import InteractiveShell | |
23 | from IPython.core.display import _PNG, _JPEG |
|
23 | from IPython.core.display import _PNG, _JPEG | |
24 | from .. import pylabtools as pt |
|
24 | from .. import pylabtools as pt | |
25 |
|
25 | |||
26 | from IPython.testing import decorators as dec |
|
26 | from IPython.testing import decorators as dec | |
27 |
|
27 | |||
28 |
|
28 | |||
29 | def test_figure_to_svg(): |
|
29 | def test_figure_to_svg(): | |
30 | # simple empty-figure test |
|
30 | # simple empty-figure test | |
31 | fig = plt.figure() |
|
31 | fig = plt.figure() | |
32 | assert pt.print_figure(fig, "svg") is None |
|
32 | assert pt.print_figure(fig, "svg") is None | |
33 |
|
33 | |||
34 | plt.close('all') |
|
34 | plt.close('all') | |
35 |
|
35 | |||
36 | # simple check for at least svg-looking output |
|
36 | # simple check for at least svg-looking output | |
37 | fig = plt.figure() |
|
37 | fig = plt.figure() | |
38 | ax = fig.add_subplot(1,1,1) |
|
38 | ax = fig.add_subplot(1,1,1) | |
39 | ax.plot([1,2,3]) |
|
39 | ax.plot([1,2,3]) | |
40 | plt.draw() |
|
40 | plt.draw() | |
41 | svg = pt.print_figure(fig, "svg")[:100].lower() |
|
41 | svg = pt.print_figure(fig, "svg")[:100].lower() | |
42 | assert "doctype svg" in svg |
|
42 | assert "doctype svg" in svg | |
43 |
|
43 | |||
44 |
|
44 | |||
45 | def _check_pil_jpeg_bytes(): |
|
45 | def _check_pil_jpeg_bytes(): | |
46 | """Skip if PIL can't write JPEGs to BytesIO objects""" |
|
46 | """Skip if PIL can't write JPEGs to BytesIO objects""" | |
47 | # PIL's JPEG plugin can't write to BytesIO objects |
|
47 | # PIL's JPEG plugin can't write to BytesIO objects | |
48 | # Pillow fixes this |
|
48 | # Pillow fixes this | |
49 | from PIL import Image |
|
49 | from PIL import Image | |
50 | buf = BytesIO() |
|
50 | buf = BytesIO() | |
51 | img = Image.new("RGB", (4,4)) |
|
51 | img = Image.new("RGB", (4,4)) | |
52 | try: |
|
52 | try: | |
53 | img.save(buf, 'jpeg') |
|
53 | img.save(buf, 'jpeg') | |
54 | except Exception as e: |
|
54 | except Exception as e: | |
55 | ename = e.__class__.__name__ |
|
55 | ename = e.__class__.__name__ | |
56 | raise pytest.skip("PIL can't write JPEG to BytesIO: %s: %s" % (ename, e)) from e |
|
56 | raise pytest.skip("PIL can't write JPEG to BytesIO: %s: %s" % (ename, e)) from e | |
57 |
|
57 | |||
58 | @dec.skip_without("PIL.Image") |
|
58 | @dec.skip_without("PIL.Image") | |
59 | def test_figure_to_jpeg(): |
|
59 | def test_figure_to_jpeg(): | |
60 | _check_pil_jpeg_bytes() |
|
60 | _check_pil_jpeg_bytes() | |
61 | # simple check for at least jpeg-looking output |
|
61 | # simple check for at least jpeg-looking output | |
62 | fig = plt.figure() |
|
62 | fig = plt.figure() | |
63 | ax = fig.add_subplot(1,1,1) |
|
63 | ax = fig.add_subplot(1,1,1) | |
64 | ax.plot([1,2,3]) |
|
64 | ax.plot([1,2,3]) | |
65 | plt.draw() |
|
65 | plt.draw() | |
66 | jpeg = pt.print_figure(fig, 'jpeg', pil_kwargs={'optimize': 50})[:100].lower() |
|
66 | jpeg = pt.print_figure(fig, 'jpeg', pil_kwargs={'optimize': 50})[:100].lower() | |
67 | assert jpeg.startswith(_JPEG) |
|
67 | assert jpeg.startswith(_JPEG) | |
68 |
|
68 | |||
69 | def test_retina_figure(): |
|
69 | def test_retina_figure(): | |
70 | # simple empty-figure test |
|
70 | # simple empty-figure test | |
71 | fig = plt.figure() |
|
71 | fig = plt.figure() | |
72 | assert pt.retina_figure(fig) == None |
|
72 | assert pt.retina_figure(fig) == None | |
73 | plt.close('all') |
|
73 | plt.close('all') | |
74 |
|
74 | |||
75 | fig = plt.figure() |
|
75 | fig = plt.figure() | |
76 | ax = fig.add_subplot(1,1,1) |
|
76 | ax = fig.add_subplot(1,1,1) | |
77 | ax.plot([1,2,3]) |
|
77 | ax.plot([1,2,3]) | |
78 | plt.draw() |
|
78 | plt.draw() | |
79 | png, md = pt.retina_figure(fig) |
|
79 | png, md = pt.retina_figure(fig) | |
80 | assert png.startswith(_PNG) |
|
80 | assert png.startswith(_PNG) | |
81 | assert "width" in md |
|
81 | assert "width" in md | |
82 | assert "height" in md |
|
82 | assert "height" in md | |
83 |
|
83 | |||
84 |
|
84 | |||
85 | _fmt_mime_map = { |
|
85 | _fmt_mime_map = { | |
86 | 'png': 'image/png', |
|
86 | 'png': 'image/png', | |
87 | 'jpeg': 'image/jpeg', |
|
87 | 'jpeg': 'image/jpeg', | |
88 | 'pdf': 'application/pdf', |
|
88 | 'pdf': 'application/pdf', | |
89 | 'retina': 'image/png', |
|
89 | 'retina': 'image/png', | |
90 | 'svg': 'image/svg+xml', |
|
90 | 'svg': 'image/svg+xml', | |
91 | } |
|
91 | } | |
92 |
|
92 | |||
93 | def test_select_figure_formats_str(): |
|
93 | def test_select_figure_formats_str(): | |
94 | ip = get_ipython() |
|
94 | ip = get_ipython() | |
95 | for fmt, active_mime in _fmt_mime_map.items(): |
|
95 | for fmt, active_mime in _fmt_mime_map.items(): | |
96 | pt.select_figure_formats(ip, fmt) |
|
96 | pt.select_figure_formats(ip, fmt) | |
97 | for mime, f in ip.display_formatter.formatters.items(): |
|
97 | for mime, f in ip.display_formatter.formatters.items(): | |
98 | if mime == active_mime: |
|
98 | if mime == active_mime: | |
99 | assert Figure in f |
|
99 | assert Figure in f | |
100 | else: |
|
100 | else: | |
101 | assert Figure not in f |
|
101 | assert Figure not in f | |
102 |
|
102 | |||
103 | def test_select_figure_formats_kwargs(): |
|
103 | def test_select_figure_formats_kwargs(): | |
104 | ip = get_ipython() |
|
104 | ip = get_ipython() | |
105 |
kwargs = dict( |
|
105 | kwargs = dict(bbox_inches="tight") | |
106 |
pt.select_figure_formats(ip, |
|
106 | pt.select_figure_formats(ip, "png", **kwargs) | |
107 |
formatter = ip.display_formatter.formatters[ |
|
107 | formatter = ip.display_formatter.formatters["image/png"] | |
108 | f = formatter.lookup_by_type(Figure) |
|
108 | f = formatter.lookup_by_type(Figure) | |
109 | cell = f.keywords |
|
109 | cell = f.keywords | |
110 | expected = kwargs |
|
110 | expected = kwargs | |
111 | expected["base64"] = True |
|
111 | expected["base64"] = True | |
112 | expected["fmt"] = "png" |
|
112 | expected["fmt"] = "png" | |
113 | assert cell == expected |
|
113 | assert cell == expected | |
114 |
|
114 | |||
115 | # check that the formatter doesn't raise |
|
115 | # check that the formatter doesn't raise | |
116 | fig = plt.figure() |
|
116 | fig = plt.figure() | |
117 | ax = fig.add_subplot(1,1,1) |
|
117 | ax = fig.add_subplot(1,1,1) | |
118 | ax.plot([1,2,3]) |
|
118 | ax.plot([1,2,3]) | |
119 | plt.draw() |
|
119 | plt.draw() | |
120 | formatter.enabled = True |
|
120 | formatter.enabled = True | |
121 | png = formatter(fig) |
|
121 | png = formatter(fig) | |
122 | assert isinstance(png, str) |
|
122 | assert isinstance(png, str) | |
123 | png_bytes = a2b_base64(png) |
|
123 | png_bytes = a2b_base64(png) | |
124 | assert png_bytes.startswith(_PNG) |
|
124 | assert png_bytes.startswith(_PNG) | |
125 |
|
125 | |||
126 | def test_select_figure_formats_set(): |
|
126 | def test_select_figure_formats_set(): | |
127 | ip = get_ipython() |
|
127 | ip = get_ipython() | |
128 | for fmts in [ |
|
128 | for fmts in [ | |
129 | {'png', 'svg'}, |
|
129 | {'png', 'svg'}, | |
130 | ['png'], |
|
130 | ['png'], | |
131 | ('jpeg', 'pdf', 'retina'), |
|
131 | ('jpeg', 'pdf', 'retina'), | |
132 | {'svg'}, |
|
132 | {'svg'}, | |
133 | ]: |
|
133 | ]: | |
134 | active_mimes = {_fmt_mime_map[fmt] for fmt in fmts} |
|
134 | active_mimes = {_fmt_mime_map[fmt] for fmt in fmts} | |
135 | pt.select_figure_formats(ip, fmts) |
|
135 | pt.select_figure_formats(ip, fmts) | |
136 | for mime, f in ip.display_formatter.formatters.items(): |
|
136 | for mime, f in ip.display_formatter.formatters.items(): | |
137 | if mime in active_mimes: |
|
137 | if mime in active_mimes: | |
138 | assert Figure in f |
|
138 | assert Figure in f | |
139 | else: |
|
139 | else: | |
140 | assert Figure not in f |
|
140 | assert Figure not in f | |
141 |
|
141 | |||
142 | def test_select_figure_formats_bad(): |
|
142 | def test_select_figure_formats_bad(): | |
143 | ip = get_ipython() |
|
143 | ip = get_ipython() | |
144 | with pytest.raises(ValueError): |
|
144 | with pytest.raises(ValueError): | |
145 | pt.select_figure_formats(ip, 'foo') |
|
145 | pt.select_figure_formats(ip, 'foo') | |
146 | with pytest.raises(ValueError): |
|
146 | with pytest.raises(ValueError): | |
147 | pt.select_figure_formats(ip, {'png', 'foo'}) |
|
147 | pt.select_figure_formats(ip, {'png', 'foo'}) | |
148 | with pytest.raises(ValueError): |
|
148 | with pytest.raises(ValueError): | |
149 | pt.select_figure_formats(ip, ['retina', 'pdf', 'bar', 'bad']) |
|
149 | pt.select_figure_formats(ip, ['retina', 'pdf', 'bar', 'bad']) | |
150 |
|
150 | |||
151 | def test_import_pylab(): |
|
151 | def test_import_pylab(): | |
152 | ns = {} |
|
152 | ns = {} | |
153 | pt.import_pylab(ns, import_all=False) |
|
153 | pt.import_pylab(ns, import_all=False) | |
154 | assert "plt" in ns |
|
154 | assert "plt" in ns | |
155 | assert ns["np"] == np |
|
155 | assert ns["np"] == np | |
156 |
|
156 | |||
157 |
|
157 | |||
158 | from traitlets.config import Config |
|
158 | from traitlets.config import Config | |
159 |
|
159 | |||
160 |
|
160 | |||
161 | class TestPylabSwitch(object): |
|
161 | class TestPylabSwitch(object): | |
162 | class Shell(InteractiveShell): |
|
162 | class Shell(InteractiveShell): | |
163 | def init_history(self): |
|
163 | def init_history(self): | |
164 | """Sets up the command history, and starts regular autosaves.""" |
|
164 | """Sets up the command history, and starts regular autosaves.""" | |
165 | self.config.HistoryManager.hist_file = ":memory:" |
|
165 | self.config.HistoryManager.hist_file = ":memory:" | |
166 | super().init_history() |
|
166 | super().init_history() | |
167 |
|
167 | |||
168 | def enable_gui(self, gui): |
|
168 | def enable_gui(self, gui): | |
169 | pass |
|
169 | pass | |
170 |
|
170 | |||
171 | def setup(self): |
|
171 | def setup(self): | |
172 | import matplotlib |
|
172 | import matplotlib | |
173 | def act_mpl(backend): |
|
173 | def act_mpl(backend): | |
174 | matplotlib.rcParams['backend'] = backend |
|
174 | matplotlib.rcParams['backend'] = backend | |
175 |
|
175 | |||
176 | # Save rcParams since they get modified |
|
176 | # Save rcParams since they get modified | |
177 | self._saved_rcParams = matplotlib.rcParams |
|
177 | self._saved_rcParams = matplotlib.rcParams | |
178 | self._saved_rcParamsOrig = matplotlib.rcParamsOrig |
|
178 | self._saved_rcParamsOrig = matplotlib.rcParamsOrig | |
179 | matplotlib.rcParams = dict(backend='Qt4Agg') |
|
179 | matplotlib.rcParams = dict(backend='Qt4Agg') | |
180 | matplotlib.rcParamsOrig = dict(backend='Qt4Agg') |
|
180 | matplotlib.rcParamsOrig = dict(backend='Qt4Agg') | |
181 |
|
181 | |||
182 | # Mock out functions |
|
182 | # Mock out functions | |
183 | self._save_am = pt.activate_matplotlib |
|
183 | self._save_am = pt.activate_matplotlib | |
184 | pt.activate_matplotlib = act_mpl |
|
184 | pt.activate_matplotlib = act_mpl | |
185 | self._save_ip = pt.import_pylab |
|
185 | self._save_ip = pt.import_pylab | |
186 | pt.import_pylab = lambda *a,**kw:None |
|
186 | pt.import_pylab = lambda *a,**kw:None | |
187 | self._save_cis = backend_inline.configure_inline_support |
|
187 | self._save_cis = backend_inline.configure_inline_support | |
188 | backend_inline.configure_inline_support = lambda *a, **kw: None |
|
188 | backend_inline.configure_inline_support = lambda *a, **kw: None | |
189 |
|
189 | |||
190 | def teardown(self): |
|
190 | def teardown(self): | |
191 | pt.activate_matplotlib = self._save_am |
|
191 | pt.activate_matplotlib = self._save_am | |
192 | pt.import_pylab = self._save_ip |
|
192 | pt.import_pylab = self._save_ip | |
193 | backend_inline.configure_inline_support = self._save_cis |
|
193 | backend_inline.configure_inline_support = self._save_cis | |
194 | import matplotlib |
|
194 | import matplotlib | |
195 | matplotlib.rcParams = self._saved_rcParams |
|
195 | matplotlib.rcParams = self._saved_rcParams | |
196 | matplotlib.rcParamsOrig = self._saved_rcParamsOrig |
|
196 | matplotlib.rcParamsOrig = self._saved_rcParamsOrig | |
197 |
|
197 | |||
198 | def test_qt(self): |
|
198 | def test_qt(self): | |
199 |
|
199 | |||
200 | s = self.Shell() |
|
200 | s = self.Shell() | |
201 | gui, backend = s.enable_matplotlib(None) |
|
201 | gui, backend = s.enable_matplotlib(None) | |
202 | assert gui == "qt" |
|
202 | assert gui == "qt" | |
203 | assert s.pylab_gui_select == "qt" |
|
203 | assert s.pylab_gui_select == "qt" | |
204 |
|
204 | |||
205 | gui, backend = s.enable_matplotlib("inline") |
|
205 | gui, backend = s.enable_matplotlib("inline") | |
206 | assert gui == "inline" |
|
206 | assert gui == "inline" | |
207 | assert s.pylab_gui_select == "qt" |
|
207 | assert s.pylab_gui_select == "qt" | |
208 |
|
208 | |||
209 | gui, backend = s.enable_matplotlib("qt") |
|
209 | gui, backend = s.enable_matplotlib("qt") | |
210 | assert gui == "qt" |
|
210 | assert gui == "qt" | |
211 | assert s.pylab_gui_select == "qt" |
|
211 | assert s.pylab_gui_select == "qt" | |
212 |
|
212 | |||
213 | gui, backend = s.enable_matplotlib("inline") |
|
213 | gui, backend = s.enable_matplotlib("inline") | |
214 | assert gui == "inline" |
|
214 | assert gui == "inline" | |
215 | assert s.pylab_gui_select == "qt" |
|
215 | assert s.pylab_gui_select == "qt" | |
216 |
|
216 | |||
217 | gui, backend = s.enable_matplotlib() |
|
217 | gui, backend = s.enable_matplotlib() | |
218 | assert gui == "qt" |
|
218 | assert gui == "qt" | |
219 | assert s.pylab_gui_select == "qt" |
|
219 | assert s.pylab_gui_select == "qt" | |
220 |
|
220 | |||
221 | def test_inline(self): |
|
221 | def test_inline(self): | |
222 | s = self.Shell() |
|
222 | s = self.Shell() | |
223 | gui, backend = s.enable_matplotlib("inline") |
|
223 | gui, backend = s.enable_matplotlib("inline") | |
224 | assert gui == "inline" |
|
224 | assert gui == "inline" | |
225 | assert s.pylab_gui_select == None |
|
225 | assert s.pylab_gui_select == None | |
226 |
|
226 | |||
227 | gui, backend = s.enable_matplotlib("inline") |
|
227 | gui, backend = s.enable_matplotlib("inline") | |
228 | assert gui == "inline" |
|
228 | assert gui == "inline" | |
229 | assert s.pylab_gui_select == None |
|
229 | assert s.pylab_gui_select == None | |
230 |
|
230 | |||
231 | gui, backend = s.enable_matplotlib("qt") |
|
231 | gui, backend = s.enable_matplotlib("qt") | |
232 | assert gui == "qt" |
|
232 | assert gui == "qt" | |
233 | assert s.pylab_gui_select == "qt" |
|
233 | assert s.pylab_gui_select == "qt" | |
234 |
|
234 | |||
235 | def test_inline_twice(self): |
|
235 | def test_inline_twice(self): | |
236 | "Using '%matplotlib inline' twice should not reset formatters" |
|
236 | "Using '%matplotlib inline' twice should not reset formatters" | |
237 |
|
237 | |||
238 | ip = self.Shell() |
|
238 | ip = self.Shell() | |
239 | gui, backend = ip.enable_matplotlib("inline") |
|
239 | gui, backend = ip.enable_matplotlib("inline") | |
240 | assert gui == "inline" |
|
240 | assert gui == "inline" | |
241 |
|
241 | |||
242 | fmts = {'png'} |
|
242 | fmts = {'png'} | |
243 | active_mimes = {_fmt_mime_map[fmt] for fmt in fmts} |
|
243 | active_mimes = {_fmt_mime_map[fmt] for fmt in fmts} | |
244 | pt.select_figure_formats(ip, fmts) |
|
244 | pt.select_figure_formats(ip, fmts) | |
245 |
|
245 | |||
246 | gui, backend = ip.enable_matplotlib("inline") |
|
246 | gui, backend = ip.enable_matplotlib("inline") | |
247 | assert gui == "inline" |
|
247 | assert gui == "inline" | |
248 |
|
248 | |||
249 | for mime, f in ip.display_formatter.formatters.items(): |
|
249 | for mime, f in ip.display_formatter.formatters.items(): | |
250 | if mime in active_mimes: |
|
250 | if mime in active_mimes: | |
251 | assert Figure in f |
|
251 | assert Figure in f | |
252 | else: |
|
252 | else: | |
253 | assert Figure not in f |
|
253 | assert Figure not in f | |
254 |
|
254 | |||
255 | def test_qt_gtk(self): |
|
255 | def test_qt_gtk(self): | |
256 | s = self.Shell() |
|
256 | s = self.Shell() | |
257 | gui, backend = s.enable_matplotlib("qt") |
|
257 | gui, backend = s.enable_matplotlib("qt") | |
258 | assert gui == "qt" |
|
258 | assert gui == "qt" | |
259 | assert s.pylab_gui_select == "qt" |
|
259 | assert s.pylab_gui_select == "qt" | |
260 |
|
260 | |||
261 | gui, backend = s.enable_matplotlib("gtk") |
|
261 | gui, backend = s.enable_matplotlib("gtk") | |
262 | assert gui == "qt" |
|
262 | assert gui == "qt" | |
263 | assert s.pylab_gui_select == "qt" |
|
263 | assert s.pylab_gui_select == "qt" | |
264 |
|
264 | |||
265 |
|
265 | |||
266 | def test_no_gui_backends(): |
|
266 | def test_no_gui_backends(): | |
267 | for k in ['agg', 'svg', 'pdf', 'ps']: |
|
267 | for k in ['agg', 'svg', 'pdf', 'ps']: | |
268 | assert k not in pt.backend2gui |
|
268 | assert k not in pt.backend2gui | |
269 |
|
269 | |||
270 |
|
270 | |||
271 | def test_figure_no_canvas(): |
|
271 | def test_figure_no_canvas(): | |
272 | fig = Figure() |
|
272 | fig = Figure() | |
273 | fig.canvas = None |
|
273 | fig.canvas = None | |
274 | pt.print_figure(fig) |
|
274 | pt.print_figure(fig) |
@@ -1,8 +1,20 b'' | |||||
1 | coverage: |
|
1 | coverage: | |
2 | status: |
|
2 | status: | |
3 | patch: off |
|
3 | patch: off | |
4 | project: |
|
4 | project: | |
5 | default: |
|
5 | default: | |
6 | target: auto |
|
6 | target: auto | |
7 | codecov: |
|
7 | codecov: | |
8 | require_ci_to_pass: false |
|
8 | require_ci_to_pass: false | |
|
9 | ||||
|
10 | ignore: | |||
|
11 | - IPython/kernel/* | |||
|
12 | - IPython/consoleapp.py | |||
|
13 | - IPython/core/inputsplitter.py | |||
|
14 | - IPython/lib/inputhook*.py | |||
|
15 | - IPython/lib/kernel.py | |||
|
16 | - IPython/utils/jsonutil.py | |||
|
17 | - IPython/utils/localinterfaces.py | |||
|
18 | - IPython/utils/log.py | |||
|
19 | - IPython/utils/signatures.py | |||
|
20 | - IPython/utils/traitlets.py |
@@ -1,43 +1,47 b'' | |||||
1 | [pytest] |
|
1 | [pytest] | |
2 | addopts = --durations=10 |
|
2 | addopts = --durations=10 | |
3 | -p IPython.testing.plugin.pytest_ipdoctest --ipdoctest-modules |
|
3 | -p IPython.testing.plugin.pytest_ipdoctest --ipdoctest-modules | |
4 | --ignore=docs |
|
4 | --ignore=docs | |
5 | --ignore=examples |
|
5 | --ignore=examples | |
6 | --ignore=htmlcov |
|
6 | --ignore=htmlcov | |
7 | --ignore=ipython_kernel |
|
7 | --ignore=ipython_kernel | |
8 | --ignore=ipython_parallel |
|
8 | --ignore=ipython_parallel | |
9 | --ignore=results |
|
9 | --ignore=results | |
10 | --ignore=tmp |
|
10 | --ignore=tmp | |
11 | --ignore=tools |
|
11 | --ignore=tools | |
12 | --ignore=traitlets |
|
12 | --ignore=traitlets | |
13 | --ignore=IPython/core/tests/daft_extension |
|
13 | --ignore=IPython/core/tests/daft_extension | |
14 | --ignore=IPython/sphinxext |
|
14 | --ignore=IPython/sphinxext | |
15 | --ignore=IPython/terminal/pt_inputhooks |
|
15 | --ignore=IPython/terminal/pt_inputhooks | |
16 | --ignore=IPython/__main__.py |
|
16 | --ignore=IPython/__main__.py | |
17 | --ignore=IPython/config.py |
|
17 | --ignore=IPython/config.py | |
18 | --ignore=IPython/frontend.py |
|
18 | --ignore=IPython/frontend.py | |
19 | --ignore=IPython/html.py |
|
19 | --ignore=IPython/html.py | |
20 | --ignore=IPython/nbconvert.py |
|
20 | --ignore=IPython/nbconvert.py | |
21 | --ignore=IPython/nbformat.py |
|
21 | --ignore=IPython/nbformat.py | |
22 | --ignore=IPython/parallel.py |
|
22 | --ignore=IPython/parallel.py | |
23 | --ignore=IPython/qt.py |
|
23 | --ignore=IPython/qt.py | |
24 | --ignore=IPython/external/qt_for_kernel.py |
|
24 | --ignore=IPython/external/qt_for_kernel.py | |
25 | --ignore=IPython/html/widgets/widget_link.py |
|
25 | --ignore=IPython/html/widgets/widget_link.py | |
26 | --ignore=IPython/html/widgets/widget_output.py |
|
26 | --ignore=IPython/html/widgets/widget_output.py | |
27 | --ignore=IPython/lib/inputhookglut.py |
|
|||
28 | --ignore=IPython/lib/inputhookgtk.py |
|
|||
29 | --ignore=IPython/lib/inputhookgtk3.py |
|
|||
30 | --ignore=IPython/lib/inputhookgtk4.py |
|
|||
31 | --ignore=IPython/lib/inputhookpyglet.py |
|
|||
32 | --ignore=IPython/lib/inputhookqt4.py |
|
|||
33 | --ignore=IPython/lib/inputhookwx.py |
|
|||
34 | --ignore=IPython/terminal/console.py |
|
27 | --ignore=IPython/terminal/console.py | |
35 | --ignore=IPython/terminal/ptshell.py |
|
28 | --ignore=IPython/terminal/ptshell.py | |
36 | --ignore=IPython/utils/_process_cli.py |
|
29 | --ignore=IPython/utils/_process_cli.py | |
37 | --ignore=IPython/utils/_process_posix.py |
|
30 | --ignore=IPython/utils/_process_posix.py | |
38 | --ignore=IPython/utils/_process_win32.py |
|
31 | --ignore=IPython/utils/_process_win32.py | |
39 | --ignore=IPython/utils/_process_win32_controller.py |
|
32 | --ignore=IPython/utils/_process_win32_controller.py | |
40 | --ignore=IPython/utils/daemonize.py |
|
33 | --ignore=IPython/utils/daemonize.py | |
41 | --ignore=IPython/utils/eventful.py |
|
34 | --ignore=IPython/utils/eventful.py | |
|
35 | ||||
|
36 | --ignore=IPython/kernel | |||
|
37 | --ignore=IPython/consoleapp.py | |||
|
38 | --ignore=IPython/core/inputsplitter.py | |||
|
39 | --ignore-glob=IPython/lib/inputhook*.py | |||
|
40 | --ignore=IPython/lib/kernel.py | |||
|
41 | --ignore=IPython/utils/jsonutil.py | |||
|
42 | --ignore=IPython/utils/localinterfaces.py | |||
|
43 | --ignore=IPython/utils/log.py | |||
|
44 | --ignore=IPython/utils/signatures.py | |||
|
45 | --ignore=IPython/utils/traitlets.py | |||
42 | doctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS |
|
46 | doctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS | |
43 | ipdoctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS |
|
47 | ipdoctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS |
General Comments 0
You need to be logged in to leave comments.
Login now