##// END OF EJS Templates
Add test that display is available without imports.
Matthias Bussonnier -
Show More
@@ -1,334 +1,354
1 1 # Copyright (c) IPython Development Team.
2 2 # Distributed under the terms of the Modified BSD License.
3 3
4 4 import json
5 5 import os
6 6 import warnings
7 7
8 8 from unittest import mock
9 9
10 10 import nose.tools as nt
11 11
12 12 from IPython.core import display
13 13 from IPython.core.getipython import get_ipython
14 14 from IPython.utils.tempdir import NamedFileInTemporaryDirectory
15 15 from IPython import paths as ipath
16 from IPython.testing.tools import AssertPrints, AssertNotPrints
16 17
17 18 import IPython.testing.decorators as dec
18 19
19 20 def test_image_size():
20 21 """Simple test for display.Image(args, width=x,height=y)"""
21 22 thisurl = 'http://www.google.fr/images/srpr/logo3w.png'
22 23 img = display.Image(url=thisurl, width=200, height=200)
23 24 nt.assert_equal(u'<img src="%s" width="200" height="200"/>' % (thisurl), img._repr_html_())
24 25 img = display.Image(url=thisurl, width=200)
25 26 nt.assert_equal(u'<img src="%s" width="200"/>' % (thisurl), img._repr_html_())
26 27 img = display.Image(url=thisurl)
27 28 nt.assert_equal(u'<img src="%s"/>' % (thisurl), img._repr_html_())
28 29 img = display.Image(url=thisurl, unconfined=True)
29 30 nt.assert_equal(u'<img src="%s" class="unconfined"/>' % (thisurl), img._repr_html_())
30 31
31 32
32 33 def test_geojson():
33 34
34 35 gj = display.GeoJSON(data={
35 36 "type": "Feature",
36 37 "geometry": {
37 38 "type": "Point",
38 39 "coordinates": [-81.327, 296.038]
39 40 },
40 41 "properties": {
41 42 "name": "Inca City"
42 43 }
43 44 },
44 45 url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png",
45 46 layer_options={
46 47 "basemap_id": "celestia_mars-shaded-16k_global",
47 48 "attribution": "Celestia/praesepe",
48 49 "minZoom": 0,
49 50 "maxZoom": 18,
50 51 })
51 52 nt.assert_equal(u'<IPython.core.display.GeoJSON object>', str(gj))
52 53
53 54 def test_retina_png():
54 55 here = os.path.dirname(__file__)
55 56 img = display.Image(os.path.join(here, "2x2.png"), retina=True)
56 57 nt.assert_equal(img.height, 1)
57 58 nt.assert_equal(img.width, 1)
58 59 data, md = img._repr_png_()
59 60 nt.assert_equal(md['width'], 1)
60 61 nt.assert_equal(md['height'], 1)
61 62
62 63 def test_retina_jpeg():
63 64 here = os.path.dirname(__file__)
64 65 img = display.Image(os.path.join(here, "2x2.jpg"), retina=True)
65 66 nt.assert_equal(img.height, 1)
66 67 nt.assert_equal(img.width, 1)
67 68 data, md = img._repr_jpeg_()
68 69 nt.assert_equal(md['width'], 1)
69 70 nt.assert_equal(md['height'], 1)
70 71
71 72 def test_base64image():
72 73 display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC")
73 74
74 75 def test_image_filename_defaults():
75 76 '''test format constraint, and validity of jpeg and png'''
76 77 tpath = ipath.get_ipython_package_dir()
77 78 nt.assert_raises(ValueError, display.Image, filename=os.path.join(tpath, 'testing/tests/badformat.gif'),
78 79 embed=True)
79 80 nt.assert_raises(ValueError, display.Image)
80 81 nt.assert_raises(ValueError, display.Image, data='this is not an image', format='badformat', embed=True)
81 82 # check boths paths to allow packages to test at build and install time
82 83 imgfile = os.path.join(tpath, 'core/tests/2x2.png')
83 84 img = display.Image(filename=imgfile)
84 85 nt.assert_equal('png', img.format)
85 86 nt.assert_is_not_none(img._repr_png_())
86 87 img = display.Image(filename=os.path.join(tpath, 'testing/tests/logo.jpg'), embed=False)
87 88 nt.assert_equal('jpeg', img.format)
88 89 nt.assert_is_none(img._repr_jpeg_())
89 90
90 91 def _get_inline_config():
91 92 from ipykernel.pylab.config import InlineBackend
92 93 return InlineBackend.instance()
93 94
94 95 @dec.skip_without('matplotlib')
95 96 def test_set_matplotlib_close():
96 97 cfg = _get_inline_config()
97 98 cfg.close_figures = False
98 99 display.set_matplotlib_close()
99 100 assert cfg.close_figures
100 101 display.set_matplotlib_close(False)
101 102 assert not cfg.close_figures
102 103
103 104 _fmt_mime_map = {
104 105 'png': 'image/png',
105 106 'jpeg': 'image/jpeg',
106 107 'pdf': 'application/pdf',
107 108 'retina': 'image/png',
108 109 'svg': 'image/svg+xml',
109 110 }
110 111
111 112 @dec.skip_without('matplotlib')
112 113 def test_set_matplotlib_formats():
113 114 from matplotlib.figure import Figure
114 115 formatters = get_ipython().display_formatter.formatters
115 116 for formats in [
116 117 ('png',),
117 118 ('pdf', 'svg'),
118 119 ('jpeg', 'retina', 'png'),
119 120 (),
120 121 ]:
121 122 active_mimes = {_fmt_mime_map[fmt] for fmt in formats}
122 123 display.set_matplotlib_formats(*formats)
123 124 for mime, f in formatters.items():
124 125 if mime in active_mimes:
125 126 nt.assert_in(Figure, f)
126 127 else:
127 128 nt.assert_not_in(Figure, f)
128 129
129 130 @dec.skip_without('matplotlib')
130 131 def test_set_matplotlib_formats_kwargs():
131 132 from matplotlib.figure import Figure
132 133 ip = get_ipython()
133 134 cfg = _get_inline_config()
134 135 cfg.print_figure_kwargs.update(dict(foo='bar'))
135 136 kwargs = dict(quality=10)
136 137 display.set_matplotlib_formats('png', **kwargs)
137 138 formatter = ip.display_formatter.formatters['image/png']
138 139 f = formatter.lookup_by_type(Figure)
139 140 cell = f.__closure__[0].cell_contents
140 141 expected = kwargs
141 142 expected.update(cfg.print_figure_kwargs)
142 143 nt.assert_equal(cell, expected)
143 144
145 def test_display_available():
146 """
147 Test that display is available without import
148
149 We don't really care if it's in builtin or anything else, but it should
150 always be available.
151 """
152 ip = get_ipython()
153 with AssertNotPrints('NameError'):
154 ip.run_cell('display')
155 try:
156 ip.run_cell('del display')
157 except NameError:
158 pass # it's ok, it might be in builtins
159 # even if deleted it should be back
160 with AssertNotPrints('NameError'):
161 ip.run_cell('display')
162
163
144 164 def test_displayobject_repr():
145 165 h = display.HTML('<br />')
146 166 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
147 167 h._show_mem_addr = True
148 168 nt.assert_equal(repr(h), object.__repr__(h))
149 169 h._show_mem_addr = False
150 170 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
151 171
152 172 j = display.Javascript('')
153 173 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
154 174 j._show_mem_addr = True
155 175 nt.assert_equal(repr(j), object.__repr__(j))
156 176 j._show_mem_addr = False
157 177 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
158 178
159 179 def test_json():
160 180 d = {'a': 5}
161 181 lis = [d]
162 182 md = {'expanded': False}
163 183 md2 = {'expanded': True}
164 184 j = display.JSON(d)
165 185 j2 = display.JSON(d, expanded=True)
166 186 nt.assert_equal(j._repr_json_(), (d, md))
167 187 nt.assert_equal(j2._repr_json_(), (d, md2))
168 188
169 189 with warnings.catch_warnings(record=True) as w:
170 190 warnings.simplefilter("always")
171 191 j = display.JSON(json.dumps(d))
172 192 nt.assert_equal(len(w), 1)
173 193 nt.assert_equal(j._repr_json_(), (d, md))
174 194 nt.assert_equal(j2._repr_json_(), (d, md2))
175 195
176 196 j = display.JSON(lis)
177 197 j2 = display.JSON(lis, expanded=True)
178 198 nt.assert_equal(j._repr_json_(), (lis, md))
179 199 nt.assert_equal(j2._repr_json_(), (lis, md2))
180 200
181 201 with warnings.catch_warnings(record=True) as w:
182 202 warnings.simplefilter("always")
183 203 j = display.JSON(json.dumps(lis))
184 204 nt.assert_equal(len(w), 1)
185 205 nt.assert_equal(j._repr_json_(), (lis, md))
186 206 nt.assert_equal(j2._repr_json_(), (lis, md2))
187 207
188 208 def test_video_embedding():
189 209 """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash"""
190 210 v = display.Video("http://ignored")
191 211 assert not v.embed
192 212 html = v._repr_html_()
193 213 nt.assert_not_in('src="data:', html)
194 214 nt.assert_in('src="http://ignored"', html)
195 215
196 216 with nt.assert_raises(ValueError):
197 217 v = display.Video(b'abc')
198 218
199 219 with NamedFileInTemporaryDirectory('test.mp4') as f:
200 220 f.write(b'abc')
201 221 f.close()
202 222
203 223 v = display.Video(f.name)
204 224 assert not v.embed
205 225 html = v._repr_html_()
206 226 nt.assert_not_in('src="data:', html)
207 227
208 228 v = display.Video(f.name, embed=True)
209 229 html = v._repr_html_()
210 230 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
211 231
212 232 v = display.Video(f.name, embed=True, mimetype='video/other')
213 233 html = v._repr_html_()
214 234 nt.assert_in('src="data:video/other;base64,YWJj"',html)
215 235
216 236 v = display.Video(b'abc', embed=True, mimetype='video/mp4')
217 237 html = v._repr_html_()
218 238 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
219 239
220 240 v = display.Video(u'YWJj', embed=True, mimetype='video/xyz')
221 241 html = v._repr_html_()
222 242 nt.assert_in('src="data:video/xyz;base64,YWJj"',html)
223 243
224 244
225 245 def test_display_id():
226 246 ip = get_ipython()
227 247 with mock.patch.object(ip.display_pub, 'publish') as pub:
228 248 handle = display.display('x')
229 249 nt.assert_is(handle, None)
230 250 handle = display.display('y', display_id='secret')
231 251 nt.assert_is_instance(handle, display.DisplayHandle)
232 252 handle2 = display.display('z', display_id=True)
233 253 nt.assert_is_instance(handle2, display.DisplayHandle)
234 254 nt.assert_not_equal(handle.display_id, handle2.display_id)
235 255
236 256 nt.assert_equal(pub.call_count, 3)
237 257 args, kwargs = pub.call_args_list[0]
238 258 nt.assert_equal(args, ())
239 259 nt.assert_equal(kwargs, {
240 260 'data': {
241 261 'text/plain': repr('x')
242 262 },
243 263 'metadata': {},
244 264 })
245 265 args, kwargs = pub.call_args_list[1]
246 266 nt.assert_equal(args, ())
247 267 nt.assert_equal(kwargs, {
248 268 'data': {
249 269 'text/plain': repr('y')
250 270 },
251 271 'metadata': {},
252 272 'transient': {
253 273 'display_id': handle.display_id,
254 274 },
255 275 })
256 276 args, kwargs = pub.call_args_list[2]
257 277 nt.assert_equal(args, ())
258 278 nt.assert_equal(kwargs, {
259 279 'data': {
260 280 'text/plain': repr('z')
261 281 },
262 282 'metadata': {},
263 283 'transient': {
264 284 'display_id': handle2.display_id,
265 285 },
266 286 })
267 287
268 288
269 289 def test_update_display():
270 290 ip = get_ipython()
271 291 with mock.patch.object(ip.display_pub, 'publish') as pub:
272 292 with nt.assert_raises(TypeError):
273 293 display.update_display('x')
274 294 display.update_display('x', display_id='1')
275 295 display.update_display('y', display_id='2')
276 296 args, kwargs = pub.call_args_list[0]
277 297 nt.assert_equal(args, ())
278 298 nt.assert_equal(kwargs, {
279 299 'data': {
280 300 'text/plain': repr('x')
281 301 },
282 302 'metadata': {},
283 303 'transient': {
284 304 'display_id': '1',
285 305 },
286 306 'update': True,
287 307 })
288 308 args, kwargs = pub.call_args_list[1]
289 309 nt.assert_equal(args, ())
290 310 nt.assert_equal(kwargs, {
291 311 'data': {
292 312 'text/plain': repr('y')
293 313 },
294 314 'metadata': {},
295 315 'transient': {
296 316 'display_id': '2',
297 317 },
298 318 'update': True,
299 319 })
300 320
301 321
302 322 def test_display_handle():
303 323 ip = get_ipython()
304 324 handle = display.DisplayHandle()
305 325 nt.assert_is_instance(handle.display_id, str)
306 326 handle = display.DisplayHandle('my-id')
307 327 nt.assert_equal(handle.display_id, 'my-id')
308 328 with mock.patch.object(ip.display_pub, 'publish') as pub:
309 329 handle.display('x')
310 330 handle.update('y')
311 331
312 332 args, kwargs = pub.call_args_list[0]
313 333 nt.assert_equal(args, ())
314 334 nt.assert_equal(kwargs, {
315 335 'data': {
316 336 'text/plain': repr('x')
317 337 },
318 338 'metadata': {},
319 339 'transient': {
320 340 'display_id': handle.display_id,
321 341 }
322 342 })
323 343 args, kwargs = pub.call_args_list[1]
324 344 nt.assert_equal(args, ())
325 345 nt.assert_equal(kwargs, {
326 346 'data': {
327 347 'text/plain': repr('y')
328 348 },
329 349 'metadata': {},
330 350 'transient': {
331 351 'display_id': handle.display_id,
332 352 },
333 353 'update': True,
334 354 })
General Comments 0
You need to be logged in to leave comments. Login now