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