##// END OF EJS Templates
Merge pull request #12617 from Carreau/skip-ipykernel
Matthias Bussonnier -
r26085:887e93ef merge
parent child Browse files
Show More
@@ -1,455 +1,459 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 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 nt.assert_equal(u'<img src="%s" width="200" height="200"/>' % (thisurl), img._repr_html_())
25 nt.assert_equal(u'<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 nt.assert_equal(u'<img src="%s" width="200" height="200"/>' % (thisurl), img._repr_html_())
27 nt.assert_equal(u'<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 nt.assert_equal(u'<img src="%s" width="200"/>' % (thisurl), img._repr_html_())
29 nt.assert_equal(u'<img src="%s" width="200"/>' % (thisurl), img._repr_html_())
30 img = display.Image(url=thisurl)
30 img = display.Image(url=thisurl)
31 nt.assert_equal(u'<img src="%s"/>' % (thisurl), img._repr_html_())
31 nt.assert_equal(u'<img src="%s"/>' % (thisurl), img._repr_html_())
32 img = display.Image(url=thisurl, unconfined=True)
32 img = display.Image(url=thisurl, unconfined=True)
33 nt.assert_equal(u'<img src="%s" class="unconfined"/>' % (thisurl), img._repr_html_())
33 nt.assert_equal(u'<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 nt.assert_equal(sorted(data), sorted([mime, 'text/plain']))
42 nt.assert_equal(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 nt.assert_equal(u'<IPython.core.display.GeoJSON object>', str(gj))
64 nt.assert_equal(u'<IPython.core.display.GeoJSON object>', str(gj))
65
65
66 def test_retina_png():
66 def test_retina_png():
67 here = os.path.dirname(__file__)
67 here = os.path.dirname(__file__)
68 img = display.Image(os.path.join(here, "2x2.png"), retina=True)
68 img = display.Image(os.path.join(here, "2x2.png"), retina=True)
69 nt.assert_equal(img.height, 1)
69 nt.assert_equal(img.height, 1)
70 nt.assert_equal(img.width, 1)
70 nt.assert_equal(img.width, 1)
71 data, md = img._repr_png_()
71 data, md = img._repr_png_()
72 nt.assert_equal(md['width'], 1)
72 nt.assert_equal(md['width'], 1)
73 nt.assert_equal(md['height'], 1)
73 nt.assert_equal(md['height'], 1)
74
74
75 def test_embed_svg_url():
75 def test_embed_svg_url():
76 import gzip
76 import gzip
77 from io import BytesIO
77 from io import BytesIO
78 svg_data = b'<svg><circle x="0" y="0" r="1"/></svg>'
78 svg_data = b'<svg><circle x="0" y="0" r="1"/></svg>'
79 url = 'http://test.com/circle.svg'
79 url = 'http://test.com/circle.svg'
80
80
81 gzip_svg = BytesIO()
81 gzip_svg = BytesIO()
82 with gzip.open(gzip_svg, 'wb') as fp:
82 with gzip.open(gzip_svg, 'wb') as fp:
83 fp.write(svg_data)
83 fp.write(svg_data)
84 gzip_svg = gzip_svg.getvalue()
84 gzip_svg = gzip_svg.getvalue()
85
85
86 def mocked_urlopen(*args, **kwargs):
86 def mocked_urlopen(*args, **kwargs):
87 class MockResponse:
87 class MockResponse:
88 def __init__(self, svg):
88 def __init__(self, svg):
89 self._svg_data = svg
89 self._svg_data = svg
90 self.headers = {'content-type': 'image/svg+xml'}
90 self.headers = {'content-type': 'image/svg+xml'}
91
91
92 def read(self):
92 def read(self):
93 return self._svg_data
93 return self._svg_data
94
94
95 if args[0] == url:
95 if args[0] == url:
96 return MockResponse(svg_data)
96 return MockResponse(svg_data)
97 elif args[0] == url + 'z':
97 elif args[0] == url + 'z':
98 ret= MockResponse(gzip_svg)
98 ret= MockResponse(gzip_svg)
99 ret.headers['content-encoding']= 'gzip'
99 ret.headers['content-encoding']= 'gzip'
100 return ret
100 return ret
101 return MockResponse(None)
101 return MockResponse(None)
102
102
103 with mock.patch('urllib.request.urlopen', side_effect=mocked_urlopen):
103 with mock.patch('urllib.request.urlopen', side_effect=mocked_urlopen):
104 svg = display.SVG(url=url)
104 svg = display.SVG(url=url)
105 nt.assert_true(svg._repr_svg_().startswith('<svg'))
105 nt.assert_true(svg._repr_svg_().startswith('<svg'))
106 svg = display.SVG(url=url + 'z')
106 svg = display.SVG(url=url + 'z')
107 nt.assert_true(svg._repr_svg_().startswith('<svg'))
107 nt.assert_true(svg._repr_svg_().startswith('<svg'))
108
108
109 def test_retina_jpeg():
109 def test_retina_jpeg():
110 here = os.path.dirname(__file__)
110 here = os.path.dirname(__file__)
111 img = display.Image(os.path.join(here, "2x2.jpg"), retina=True)
111 img = display.Image(os.path.join(here, "2x2.jpg"), retina=True)
112 nt.assert_equal(img.height, 1)
112 nt.assert_equal(img.height, 1)
113 nt.assert_equal(img.width, 1)
113 nt.assert_equal(img.width, 1)
114 data, md = img._repr_jpeg_()
114 data, md = img._repr_jpeg_()
115 nt.assert_equal(md['width'], 1)
115 nt.assert_equal(md['width'], 1)
116 nt.assert_equal(md['height'], 1)
116 nt.assert_equal(md['height'], 1)
117
117
118 def test_base64image():
118 def test_base64image():
119 display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC")
119 display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC")
120
120
121 def test_image_filename_defaults():
121 def test_image_filename_defaults():
122 '''test format constraint, and validity of jpeg and png'''
122 '''test format constraint, and validity of jpeg and png'''
123 tpath = ipath.get_ipython_package_dir()
123 tpath = ipath.get_ipython_package_dir()
124 nt.assert_raises(ValueError, display.Image, filename=os.path.join(tpath, 'testing/tests/badformat.zip'),
124 nt.assert_raises(ValueError, display.Image, filename=os.path.join(tpath, 'testing/tests/badformat.zip'),
125 embed=True)
125 embed=True)
126 nt.assert_raises(ValueError, display.Image)
126 nt.assert_raises(ValueError, display.Image)
127 nt.assert_raises(ValueError, display.Image, data='this is not an image', format='badformat', embed=True)
127 nt.assert_raises(ValueError, display.Image, data='this is not an image', format='badformat', embed=True)
128 # check boths paths to allow packages to test at build and install time
128 # check boths paths to allow packages to test at build and install time
129 imgfile = os.path.join(tpath, 'core/tests/2x2.png')
129 imgfile = os.path.join(tpath, 'core/tests/2x2.png')
130 img = display.Image(filename=imgfile)
130 img = display.Image(filename=imgfile)
131 nt.assert_equal('png', img.format)
131 nt.assert_equal('png', img.format)
132 nt.assert_is_not_none(img._repr_png_())
132 nt.assert_is_not_none(img._repr_png_())
133 img = display.Image(filename=os.path.join(tpath, 'testing/tests/logo.jpg'), embed=False)
133 img = display.Image(filename=os.path.join(tpath, 'testing/tests/logo.jpg'), embed=False)
134 nt.assert_equal('jpeg', img.format)
134 nt.assert_equal('jpeg', img.format)
135 nt.assert_is_none(img._repr_jpeg_())
135 nt.assert_is_none(img._repr_jpeg_())
136
136
137 def _get_inline_config():
137 def _get_inline_config():
138 from ipykernel.pylab.config import InlineBackend
138 from ipykernel.pylab.config import InlineBackend
139 return InlineBackend.instance()
139 return InlineBackend.instance()
140
140
141 @dec.skip_without('matplotlib')
141
142 @dec.skip_without("ipykernel")
143 @dec.skip_without("matplotlib")
142 def test_set_matplotlib_close():
144 def test_set_matplotlib_close():
143 cfg = _get_inline_config()
145 cfg = _get_inline_config()
144 cfg.close_figures = False
146 cfg.close_figures = False
145 display.set_matplotlib_close()
147 display.set_matplotlib_close()
146 assert cfg.close_figures
148 assert cfg.close_figures
147 display.set_matplotlib_close(False)
149 display.set_matplotlib_close(False)
148 assert not cfg.close_figures
150 assert not cfg.close_figures
149
151
150 _fmt_mime_map = {
152 _fmt_mime_map = {
151 'png': 'image/png',
153 'png': 'image/png',
152 'jpeg': 'image/jpeg',
154 'jpeg': 'image/jpeg',
153 'pdf': 'application/pdf',
155 'pdf': 'application/pdf',
154 'retina': 'image/png',
156 'retina': 'image/png',
155 'svg': 'image/svg+xml',
157 'svg': 'image/svg+xml',
156 }
158 }
157
159
158 @dec.skip_without('matplotlib')
160 @dec.skip_without('matplotlib')
159 def test_set_matplotlib_formats():
161 def test_set_matplotlib_formats():
160 from matplotlib.figure import Figure
162 from matplotlib.figure import Figure
161 formatters = get_ipython().display_formatter.formatters
163 formatters = get_ipython().display_formatter.formatters
162 for formats in [
164 for formats in [
163 ('png',),
165 ('png',),
164 ('pdf', 'svg'),
166 ('pdf', 'svg'),
165 ('jpeg', 'retina', 'png'),
167 ('jpeg', 'retina', 'png'),
166 (),
168 (),
167 ]:
169 ]:
168 active_mimes = {_fmt_mime_map[fmt] for fmt in formats}
170 active_mimes = {_fmt_mime_map[fmt] for fmt in formats}
169 display.set_matplotlib_formats(*formats)
171 display.set_matplotlib_formats(*formats)
170 for mime, f in formatters.items():
172 for mime, f in formatters.items():
171 if mime in active_mimes:
173 if mime in active_mimes:
172 nt.assert_in(Figure, f)
174 nt.assert_in(Figure, f)
173 else:
175 else:
174 nt.assert_not_in(Figure, f)
176 nt.assert_not_in(Figure, f)
175
177
176 @dec.skip_without('matplotlib')
178
179 @dec.skip_without("ipykernel")
180 @dec.skip_without("matplotlib")
177 def test_set_matplotlib_formats_kwargs():
181 def test_set_matplotlib_formats_kwargs():
178 from matplotlib.figure import Figure
182 from matplotlib.figure import Figure
179 ip = get_ipython()
183 ip = get_ipython()
180 cfg = _get_inline_config()
184 cfg = _get_inline_config()
181 cfg.print_figure_kwargs.update(dict(foo='bar'))
185 cfg.print_figure_kwargs.update(dict(foo='bar'))
182 kwargs = dict(quality=10)
186 kwargs = dict(quality=10)
183 display.set_matplotlib_formats('png', **kwargs)
187 display.set_matplotlib_formats('png', **kwargs)
184 formatter = ip.display_formatter.formatters['image/png']
188 formatter = ip.display_formatter.formatters['image/png']
185 f = formatter.lookup_by_type(Figure)
189 f = formatter.lookup_by_type(Figure)
186 cell = f.__closure__[0].cell_contents
190 cell = f.__closure__[0].cell_contents
187 expected = kwargs
191 expected = kwargs
188 expected.update(cfg.print_figure_kwargs)
192 expected.update(cfg.print_figure_kwargs)
189 nt.assert_equal(cell, expected)
193 nt.assert_equal(cell, expected)
190
194
191 def test_display_available():
195 def test_display_available():
192 """
196 """
193 Test that display is available without import
197 Test that display is available without import
194
198
195 We don't really care if it's in builtin or anything else, but it should
199 We don't really care if it's in builtin or anything else, but it should
196 always be available.
200 always be available.
197 """
201 """
198 ip = get_ipython()
202 ip = get_ipython()
199 with AssertNotPrints('NameError'):
203 with AssertNotPrints('NameError'):
200 ip.run_cell('display')
204 ip.run_cell('display')
201 try:
205 try:
202 ip.run_cell('del display')
206 ip.run_cell('del display')
203 except NameError:
207 except NameError:
204 pass # it's ok, it might be in builtins
208 pass # it's ok, it might be in builtins
205 # even if deleted it should be back
209 # even if deleted it should be back
206 with AssertNotPrints('NameError'):
210 with AssertNotPrints('NameError'):
207 ip.run_cell('display')
211 ip.run_cell('display')
208
212
209 def test_textdisplayobj_pretty_repr():
213 def test_textdisplayobj_pretty_repr():
210 p = display.Pretty("This is a simple test")
214 p = display.Pretty("This is a simple test")
211 nt.assert_equal(repr(p), '<IPython.core.display.Pretty object>')
215 nt.assert_equal(repr(p), '<IPython.core.display.Pretty object>')
212 nt.assert_equal(p.data, 'This is a simple test')
216 nt.assert_equal(p.data, 'This is a simple test')
213
217
214 p._show_mem_addr = True
218 p._show_mem_addr = True
215 nt.assert_equal(repr(p), object.__repr__(p))
219 nt.assert_equal(repr(p), object.__repr__(p))
216
220
217 def test_displayobject_repr():
221 def test_displayobject_repr():
218 h = display.HTML('<br />')
222 h = display.HTML('<br />')
219 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
223 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
220 h._show_mem_addr = True
224 h._show_mem_addr = True
221 nt.assert_equal(repr(h), object.__repr__(h))
225 nt.assert_equal(repr(h), object.__repr__(h))
222 h._show_mem_addr = False
226 h._show_mem_addr = False
223 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
227 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
224
228
225 j = display.Javascript('')
229 j = display.Javascript('')
226 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
230 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
227 j._show_mem_addr = True
231 j._show_mem_addr = True
228 nt.assert_equal(repr(j), object.__repr__(j))
232 nt.assert_equal(repr(j), object.__repr__(j))
229 j._show_mem_addr = False
233 j._show_mem_addr = False
230 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
234 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
231
235
232 @mock.patch('warnings.warn')
236 @mock.patch('warnings.warn')
233 def test_encourage_iframe_over_html(m_warn):
237 def test_encourage_iframe_over_html(m_warn):
234 display.HTML()
238 display.HTML()
235 m_warn.assert_not_called()
239 m_warn.assert_not_called()
236
240
237 display.HTML('<br />')
241 display.HTML('<br />')
238 m_warn.assert_not_called()
242 m_warn.assert_not_called()
239
243
240 display.HTML('<html><p>Lots of content here</p><iframe src="http://a.com"></iframe>')
244 display.HTML('<html><p>Lots of content here</p><iframe src="http://a.com"></iframe>')
241 m_warn.assert_not_called()
245 m_warn.assert_not_called()
242
246
243 display.HTML('<iframe src="http://a.com"></iframe>')
247 display.HTML('<iframe src="http://a.com"></iframe>')
244 m_warn.assert_called_with('Consider using IPython.display.IFrame instead')
248 m_warn.assert_called_with('Consider using IPython.display.IFrame instead')
245
249
246 m_warn.reset_mock()
250 m_warn.reset_mock()
247 display.HTML('<IFRAME SRC="http://a.com"></IFRAME>')
251 display.HTML('<IFRAME SRC="http://a.com"></IFRAME>')
248 m_warn.assert_called_with('Consider using IPython.display.IFrame instead')
252 m_warn.assert_called_with('Consider using IPython.display.IFrame instead')
249
253
250 def test_progress():
254 def test_progress():
251 p = display.ProgressBar(10)
255 p = display.ProgressBar(10)
252 nt.assert_in('0/10',repr(p))
256 nt.assert_in('0/10',repr(p))
253 p.html_width = '100%'
257 p.html_width = '100%'
254 p.progress = 5
258 p.progress = 5
255 nt.assert_equal(p._repr_html_(), "<progress style='width:100%' max='10' value='5'></progress>")
259 nt.assert_equal(p._repr_html_(), "<progress style='width:100%' max='10' value='5'></progress>")
256
260
257 def test_progress_iter():
261 def test_progress_iter():
258 with capture_output(display=False) as captured:
262 with capture_output(display=False) as captured:
259 for i in display.ProgressBar(5):
263 for i in display.ProgressBar(5):
260 out = captured.stdout
264 out = captured.stdout
261 nt.assert_in('{0}/5'.format(i), out)
265 nt.assert_in('{0}/5'.format(i), out)
262 out = captured.stdout
266 out = captured.stdout
263 nt.assert_in('5/5', out)
267 nt.assert_in('5/5', out)
264
268
265 def test_json():
269 def test_json():
266 d = {'a': 5}
270 d = {'a': 5}
267 lis = [d]
271 lis = [d]
268 metadata = [
272 metadata = [
269 {'expanded': False, 'root': 'root'},
273 {'expanded': False, 'root': 'root'},
270 {'expanded': True, 'root': 'root'},
274 {'expanded': True, 'root': 'root'},
271 {'expanded': False, 'root': 'custom'},
275 {'expanded': False, 'root': 'custom'},
272 {'expanded': True, 'root': 'custom'},
276 {'expanded': True, 'root': 'custom'},
273 ]
277 ]
274 json_objs = [
278 json_objs = [
275 display.JSON(d),
279 display.JSON(d),
276 display.JSON(d, expanded=True),
280 display.JSON(d, expanded=True),
277 display.JSON(d, root='custom'),
281 display.JSON(d, root='custom'),
278 display.JSON(d, expanded=True, root='custom'),
282 display.JSON(d, expanded=True, root='custom'),
279 ]
283 ]
280 for j, md in zip(json_objs, metadata):
284 for j, md in zip(json_objs, metadata):
281 nt.assert_equal(j._repr_json_(), (d, md))
285 nt.assert_equal(j._repr_json_(), (d, md))
282
286
283 with warnings.catch_warnings(record=True) as w:
287 with warnings.catch_warnings(record=True) as w:
284 warnings.simplefilter("always")
288 warnings.simplefilter("always")
285 j = display.JSON(json.dumps(d))
289 j = display.JSON(json.dumps(d))
286 nt.assert_equal(len(w), 1)
290 nt.assert_equal(len(w), 1)
287 nt.assert_equal(j._repr_json_(), (d, metadata[0]))
291 nt.assert_equal(j._repr_json_(), (d, metadata[0]))
288
292
289 json_objs = [
293 json_objs = [
290 display.JSON(lis),
294 display.JSON(lis),
291 display.JSON(lis, expanded=True),
295 display.JSON(lis, expanded=True),
292 display.JSON(lis, root='custom'),
296 display.JSON(lis, root='custom'),
293 display.JSON(lis, expanded=True, root='custom'),
297 display.JSON(lis, expanded=True, root='custom'),
294 ]
298 ]
295 for j, md in zip(json_objs, metadata):
299 for j, md in zip(json_objs, metadata):
296 nt.assert_equal(j._repr_json_(), (lis, md))
300 nt.assert_equal(j._repr_json_(), (lis, md))
297
301
298 with warnings.catch_warnings(record=True) as w:
302 with warnings.catch_warnings(record=True) as w:
299 warnings.simplefilter("always")
303 warnings.simplefilter("always")
300 j = display.JSON(json.dumps(lis))
304 j = display.JSON(json.dumps(lis))
301 nt.assert_equal(len(w), 1)
305 nt.assert_equal(len(w), 1)
302 nt.assert_equal(j._repr_json_(), (lis, metadata[0]))
306 nt.assert_equal(j._repr_json_(), (lis, metadata[0]))
303
307
304 def test_video_embedding():
308 def test_video_embedding():
305 """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash"""
309 """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash"""
306 v = display.Video("http://ignored")
310 v = display.Video("http://ignored")
307 assert not v.embed
311 assert not v.embed
308 html = v._repr_html_()
312 html = v._repr_html_()
309 nt.assert_not_in('src="data:', html)
313 nt.assert_not_in('src="data:', html)
310 nt.assert_in('src="http://ignored"', html)
314 nt.assert_in('src="http://ignored"', html)
311
315
312 with nt.assert_raises(ValueError):
316 with nt.assert_raises(ValueError):
313 v = display.Video(b'abc')
317 v = display.Video(b'abc')
314
318
315 with NamedFileInTemporaryDirectory('test.mp4') as f:
319 with NamedFileInTemporaryDirectory('test.mp4') as f:
316 f.write(b'abc')
320 f.write(b'abc')
317 f.close()
321 f.close()
318
322
319 v = display.Video(f.name)
323 v = display.Video(f.name)
320 assert not v.embed
324 assert not v.embed
321 html = v._repr_html_()
325 html = v._repr_html_()
322 nt.assert_not_in('src="data:', html)
326 nt.assert_not_in('src="data:', html)
323
327
324 v = display.Video(f.name, embed=True)
328 v = display.Video(f.name, embed=True)
325 html = v._repr_html_()
329 html = v._repr_html_()
326 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
330 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
327
331
328 v = display.Video(f.name, embed=True, mimetype='video/other')
332 v = display.Video(f.name, embed=True, mimetype='video/other')
329 html = v._repr_html_()
333 html = v._repr_html_()
330 nt.assert_in('src="data:video/other;base64,YWJj"',html)
334 nt.assert_in('src="data:video/other;base64,YWJj"',html)
331
335
332 v = display.Video(b'abc', embed=True, mimetype='video/mp4')
336 v = display.Video(b'abc', embed=True, mimetype='video/mp4')
333 html = v._repr_html_()
337 html = v._repr_html_()
334 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
338 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
335
339
336 v = display.Video(u'YWJj', embed=True, mimetype='video/xyz')
340 v = display.Video(u'YWJj', embed=True, mimetype='video/xyz')
337 html = v._repr_html_()
341 html = v._repr_html_()
338 nt.assert_in('src="data:video/xyz;base64,YWJj"',html)
342 nt.assert_in('src="data:video/xyz;base64,YWJj"',html)
339
343
340 def test_html_metadata():
344 def test_html_metadata():
341 s = "<h1>Test</h1>"
345 s = "<h1>Test</h1>"
342 h = display.HTML(s, metadata={"isolated": True})
346 h = display.HTML(s, metadata={"isolated": True})
343 nt.assert_equal(h._repr_html_(), (s, {"isolated": True}))
347 nt.assert_equal(h._repr_html_(), (s, {"isolated": True}))
344
348
345 def test_display_id():
349 def test_display_id():
346 ip = get_ipython()
350 ip = get_ipython()
347 with mock.patch.object(ip.display_pub, 'publish') as pub:
351 with mock.patch.object(ip.display_pub, 'publish') as pub:
348 handle = display.display('x')
352 handle = display.display('x')
349 nt.assert_is(handle, None)
353 nt.assert_is(handle, None)
350 handle = display.display('y', display_id='secret')
354 handle = display.display('y', display_id='secret')
351 nt.assert_is_instance(handle, display.DisplayHandle)
355 nt.assert_is_instance(handle, display.DisplayHandle)
352 handle2 = display.display('z', display_id=True)
356 handle2 = display.display('z', display_id=True)
353 nt.assert_is_instance(handle2, display.DisplayHandle)
357 nt.assert_is_instance(handle2, display.DisplayHandle)
354 nt.assert_not_equal(handle.display_id, handle2.display_id)
358 nt.assert_not_equal(handle.display_id, handle2.display_id)
355
359
356 nt.assert_equal(pub.call_count, 3)
360 nt.assert_equal(pub.call_count, 3)
357 args, kwargs = pub.call_args_list[0]
361 args, kwargs = pub.call_args_list[0]
358 nt.assert_equal(args, ())
362 nt.assert_equal(args, ())
359 nt.assert_equal(kwargs, {
363 nt.assert_equal(kwargs, {
360 'data': {
364 'data': {
361 'text/plain': repr('x')
365 'text/plain': repr('x')
362 },
366 },
363 'metadata': {},
367 'metadata': {},
364 })
368 })
365 args, kwargs = pub.call_args_list[1]
369 args, kwargs = pub.call_args_list[1]
366 nt.assert_equal(args, ())
370 nt.assert_equal(args, ())
367 nt.assert_equal(kwargs, {
371 nt.assert_equal(kwargs, {
368 'data': {
372 'data': {
369 'text/plain': repr('y')
373 'text/plain': repr('y')
370 },
374 },
371 'metadata': {},
375 'metadata': {},
372 'transient': {
376 'transient': {
373 'display_id': handle.display_id,
377 'display_id': handle.display_id,
374 },
378 },
375 })
379 })
376 args, kwargs = pub.call_args_list[2]
380 args, kwargs = pub.call_args_list[2]
377 nt.assert_equal(args, ())
381 nt.assert_equal(args, ())
378 nt.assert_equal(kwargs, {
382 nt.assert_equal(kwargs, {
379 'data': {
383 'data': {
380 'text/plain': repr('z')
384 'text/plain': repr('z')
381 },
385 },
382 'metadata': {},
386 'metadata': {},
383 'transient': {
387 'transient': {
384 'display_id': handle2.display_id,
388 'display_id': handle2.display_id,
385 },
389 },
386 })
390 })
387
391
388
392
389 def test_update_display():
393 def test_update_display():
390 ip = get_ipython()
394 ip = get_ipython()
391 with mock.patch.object(ip.display_pub, 'publish') as pub:
395 with mock.patch.object(ip.display_pub, 'publish') as pub:
392 with nt.assert_raises(TypeError):
396 with nt.assert_raises(TypeError):
393 display.update_display('x')
397 display.update_display('x')
394 display.update_display('x', display_id='1')
398 display.update_display('x', display_id='1')
395 display.update_display('y', display_id='2')
399 display.update_display('y', display_id='2')
396 args, kwargs = pub.call_args_list[0]
400 args, kwargs = pub.call_args_list[0]
397 nt.assert_equal(args, ())
401 nt.assert_equal(args, ())
398 nt.assert_equal(kwargs, {
402 nt.assert_equal(kwargs, {
399 'data': {
403 'data': {
400 'text/plain': repr('x')
404 'text/plain': repr('x')
401 },
405 },
402 'metadata': {},
406 'metadata': {},
403 'transient': {
407 'transient': {
404 'display_id': '1',
408 'display_id': '1',
405 },
409 },
406 'update': True,
410 'update': True,
407 })
411 })
408 args, kwargs = pub.call_args_list[1]
412 args, kwargs = pub.call_args_list[1]
409 nt.assert_equal(args, ())
413 nt.assert_equal(args, ())
410 nt.assert_equal(kwargs, {
414 nt.assert_equal(kwargs, {
411 'data': {
415 'data': {
412 'text/plain': repr('y')
416 'text/plain': repr('y')
413 },
417 },
414 'metadata': {},
418 'metadata': {},
415 'transient': {
419 'transient': {
416 'display_id': '2',
420 'display_id': '2',
417 },
421 },
418 'update': True,
422 'update': True,
419 })
423 })
420
424
421
425
422 def test_display_handle():
426 def test_display_handle():
423 ip = get_ipython()
427 ip = get_ipython()
424 handle = display.DisplayHandle()
428 handle = display.DisplayHandle()
425 nt.assert_is_instance(handle.display_id, str)
429 nt.assert_is_instance(handle.display_id, str)
426 handle = display.DisplayHandle('my-id')
430 handle = display.DisplayHandle('my-id')
427 nt.assert_equal(handle.display_id, 'my-id')
431 nt.assert_equal(handle.display_id, 'my-id')
428 with mock.patch.object(ip.display_pub, 'publish') as pub:
432 with mock.patch.object(ip.display_pub, 'publish') as pub:
429 handle.display('x')
433 handle.display('x')
430 handle.update('y')
434 handle.update('y')
431
435
432 args, kwargs = pub.call_args_list[0]
436 args, kwargs = pub.call_args_list[0]
433 nt.assert_equal(args, ())
437 nt.assert_equal(args, ())
434 nt.assert_equal(kwargs, {
438 nt.assert_equal(kwargs, {
435 'data': {
439 'data': {
436 'text/plain': repr('x')
440 'text/plain': repr('x')
437 },
441 },
438 'metadata': {},
442 'metadata': {},
439 'transient': {
443 'transient': {
440 'display_id': handle.display_id,
444 'display_id': handle.display_id,
441 }
445 }
442 })
446 })
443 args, kwargs = pub.call_args_list[1]
447 args, kwargs = pub.call_args_list[1]
444 nt.assert_equal(args, ())
448 nt.assert_equal(args, ())
445 nt.assert_equal(kwargs, {
449 nt.assert_equal(kwargs, {
446 'data': {
450 'data': {
447 'text/plain': repr('y')
451 'text/plain': repr('y')
448 },
452 },
449 'metadata': {},
453 'metadata': {},
450 'transient': {
454 'transient': {
451 'display_id': handle.display_id,
455 'display_id': handle.display_id,
452 },
456 },
453 'update': True,
457 'update': True,
454 })
458 })
455
459
General Comments 0
You need to be logged in to leave comments. Login now