##// END OF EJS Templates
Write tests for custom serialization
Jason Grout -
Show More
@@ -337,6 +337,19 b' casper.execute_cell_then = function(index, then_callback, expect_failure) {'
337 337 return return_val;
338 338 };
339 339
340 casper.append_cell_execute_then = function(text, then_callback, expect_failure) {
341 // Append a code cell and execute it, optionally calling a then_callback
342 var c = this.append_cell(text);
343 return this.execute_cell_then(c, then_callback, expect_failure);
344 };
345
346 casper.assert_output_equals = function(text, output_text, message) {
347 // Append a code cell with the text, then assert the output is equal to output_text
348 this.append_cell_execute_then(text, function(index) {
349 this.test.assertEquals(this.get_output_cell(index).text.trim(), output_text, message);
350 });
351 };
352
340 353 casper.wait_for_element = function(index, selector){
341 354 // Utility function that allows us to easily wait for an element
342 355 // within a cell. Uses JQuery selector to look for the element.
@@ -71,7 +71,7 b' casper.notebook_test(function () {'
71 71 ' c = CInt(0, sync=True)',
72 72 ' d = CInt(-1, sync=True)', // See if it sends a full state.
73 73 ' def set_state(self, sync_data):',
74 ' widgets.Widget.set_state(self, sync_data)'+
74 ' widgets.Widget.set_state(self, sync_data)',
75 75 ' self.d = len(sync_data)',
76 76 'multiset = MultiSetWidget()',
77 77 'display(multiset)',
@@ -139,158 +139,159 b' casper.notebook_test(function () {'
139 139 });
140 140
141 141
142 /* New Test
143
142 this.thenEvaluate(function() {
143 define('TestWidget', ['widgets/js/widget', 'base/js/utils'], function(widget, utils) {
144 var TestWidget = widget.DOMWidgetView.extend({
145 render: function () {
146 this.listenTo(this.model, 'msg:custom', this.handle_msg);
147 },
148 handle_msg: function(content, buffers) {
149 this.msg = [content, buffers];
150 }
151 });
144 152
145 %%javascript
146 define('TestWidget', ['widgets/js/widget', 'base/js/utils'], function(widget, utils) {
147 var TestWidget = widget.DOMWidgetView.extend({
148 render: function () {
149 this.listenTo(this.model, 'msg:custom', this.handle_msg);
150 window.w = this;
151 console.log('data:', this.model.get('data'));
152 },
153 handle_msg: function(content, buffers) {
154 this.msg = [content, buffers];
155 }
153 var floatArray = {
154 deserialize: function (value, model) {
155 // DataView -> float64 typed array
156 return new Float64Array(value.buffer);
157 },
158 // serialization automatically handled by message buffers
159 };
160
161 var floatList = {
162 deserialize: function (value, model) {
163 // list of floats -> list of strings
164 return value.map(function(x) {return x.toString()});
165 },
166 serialize: function(value, model) {
167 // list of strings -> list of floats
168 return value.map(function(x) {return parseFloat(x);})
169 }
170 };
171 return {TestWidget: TestWidget, floatArray: floatArray, floatList: floatList};
172 });
156 173 });
157 174
158 var floatArray = {
159 deserialize: function (value, model) {
160 // DataView -> float64 typed array
161 return new Float64Array(value.buffer);
162 },
163 // serialization automatically handled by message buffers
164 };
165
175 var testwidget = {};
176 this.append_cell_execute_then([
177 'from IPython.html import widgets',
178 'from IPython.utils.traitlets import Unicode, Instance, List',
179 'from IPython.display import display',
180 'from array import array',
181 'def _array_to_memoryview(x):',
182 ' if x is None: return None, {}',
183 ' try:',
184 ' y = memoryview(x)',
185 ' except TypeError:',
186 " # in python 2, arrays don't support the new buffer protocol",
187 ' y = memoryview(buffer(x))',
188 " return y, {'serialization': ('floatArray', 'TestWidget')}",
189 'def _memoryview_to_array(x):',
190 " return array('d', x.tobytes())",
191 'arrays_binary = {',
192 " 'from_json': _memoryview_to_array,",
193 " 'to_json': _array_to_memoryview",
194 '}',
195 '',
196 'def _array_to_list(x):',
197 ' if x is None: return None, {}',
198 " return list(x), {'serialization': ('floatList', 'TestWidget')}",
199 'def _list_to_array(x):',
200 " return array('d',x)",
201 'arrays_list = {',
202 " 'from_json': _list_to_array,",
203 " 'to_json': _array_to_list",
204 '}',
205 '',
206 'class TestWidget(widgets.DOMWidget):',
207 " _view_module = Unicode('TestWidget', sync=True)",
208 " _view_name = Unicode('TestWidget', sync=True)",
209 ' array_binary = Instance(array, sync=True, **arrays_binary)',
210 ' array_list = Instance(array, sync=True, **arrays_list)',
211 ' msg = {}',
212 ' def __init__(self, **kwargs):',
213 ' super(widgets.DOMWidget, self).__init__(**kwargs)',
214 ' self.on_msg(self._msg)',
215 ' def _msg(self, _, content, buffers):',
216 ' self.msg = [content, buffers]',
217 'x=TestWidget()',
218 'display(x)',
219 'print x.model_id'].join('\n'), function(index){
220 testwidget.index = index;
221 testwidget.model_id = this.get_output_cell(index).text.trim();
222 });
223 this.wait_for_widget(testwidget);
224
225
226 this.append_cell_execute_then('x.array_list = array("d", [1.5, 2.0, 3.1])');
227 this.wait_for_widget(testwidget);
228 this.then(function() {
229 var result = this.evaluate(function(index) {
230 var v = IPython.notebook.get_cell(index).widget_views[0];
231 var result = v.model.get('array_list');
232 var z = result.slice();
233 z[0]+="1234";
234 z[1]+="5678";
235 v.model.set('array_list', z);
236 v.touch();
237 return result;
238 }, testwidget.index);
239 this.test.assertEquals(result, ["1.5", "2", "3.1"], "JSON custom serializer kernel -> js");
240 });
166 241
167 var floatList = {
168 deserialize: function (value, model) {
169 // list of floats -> list of strings
170 return value.map(function(x) {return x.toString()});
171 },
172 serialize: function(value, model) {
173 // list of strings -> list of floats
174 return value.map(function(x) {return parseFloat(x);})
175 }
176 };
177 return {TestWidget: TestWidget, floatArray: floatArray, floatList: floatList};
178 });
179
180
181 --------------
182
183
184 from IPython.html import widgets
185 from IPython.utils.traitlets import Unicode, Instance, List
186 from IPython.display import display
187 from array import array
188 def _array_to_memoryview(x):
189 if x is None: return None, {}
190 try:
191 y = memoryview(x)
192 except TypeError:
193 # in python 2, arrays don't support the new buffer protocol
194 y = memoryview(buffer(x))
195 return y, {'serialization': ('floatArray', 'TestWidget')}
196
197 def _memoryview_to_array(x):
198 return array('d', x.tobytes())
199
200 arrays_binary = {
201 'from_json': _memoryview_to_array,
202 'to_json': _array_to_memoryview
203 }
204
205 def _array_to_list(x):
206 if x is None: return None, {}
207 return list(x), {'serialization': ('floatList', 'TestWidget')}
208
209 def _list_to_array(x):
210 return array('d',x)
211
212 arrays_list = {
213 'from_json': _list_to_array,
214 'to_json': _array_to_list
215 }
216
217
218 class TestWidget(widgets.DOMWidget):
219 _view_module = Unicode('TestWidget', sync=True)
220 _view_name = Unicode('TestWidget', sync=True)
221 array_binary = Instance(array, sync=True, **arrays_binary)
222 array_list = Instance(array, sync=True, **arrays_list)
223 def __init__(self, **kwargs):
224 super(widgets.DOMWidget, self).__init__(**kwargs)
225 self.on_msg(self._msg)
226 def _msg(self, _, content, buffers):
227 self.msg = [content, buffers]
228
229
230 ----------------
231
232 x=TestWidget()
233 display(x)
234 x.array_binary=array('d', [1.5,2.5,5])
235 print x.model_id
236
237 -----------------
238
239 %%javascript
240 console.log(w.model.get('array_binary'))
241 var z = w.model.get('array_binary')
242 z[0]*=3
243 z[1]*=3
244 z[2]*=3
245 // we set to null so that we recognize the change
246 // when we set data back to z
247 w.model.set('array_binary', null)
248 w.model.set('array_binary', z)
249 console.log(w.model.get('array_binary'))
250 w.touch()
251
252 ----------------
253 x.array_binary.tolist() == [4.5, 7.5, 15.0]
254 ----------------
255
256 x.array_list = array('d', [1.5, 2.0, 3.1])
257 ----------------
258
259 %%javascript
260 console.log(w.model.get('array_list'))
261 var z = w.model.get('array_list')
262 z[0]+="1234"
263 z[1]+="5678"
264 // we set to null so that we recognize the change
265 // when we set data back to z
266 w.model.set('array_list', null)
267 w.model.set('array_list', z)
268 w.touch()
269
270 -----------------
271
272 x.array_list.tolist() == [1.51234, 25678.0, 3.1]
273
274 -------------------
275 x.send('some content', [memoryview(b'binarycontent'), memoryview('morecontent')])
276
277 -------------------
278
279 %%javascript
280 console.log(w.msg[0] === 'some content')
281 var d=new TextDecoder('utf-8')
282 console.log(d.decode(w.msg[1][0])==='binarycontent')
283 console.log(d.decode(w.msg[1][1])==='morecontent')
284 w.send('content back', [new Uint8Array([1,2,3,4]), new Float64Array([2.1828, 3.14159])])
285
286 --------------------
287
288 print x.msg[0] == 'content back'
289 print x.msg[1][0].tolist() == [1,2,3,4]
290 print array('d', x.msg[1][1].tobytes()).tolist() == [2.1828, 3.14159]
291
292
293 */
294
242 this.assert_output_equals('print x.array_list.tolist() == [1.51234, 25678.0, 3.1]',
243 'True', 'JSON custom serializer js -> kernel');
244
245 if (this.slimerjs) {
246 this.append_cell_execute_then("x.array_binary=array('d', [1.5,2.5,5])", function() {
247 this.evaluate(function(index) {
248 var v = IPython.notebook.get_cell(index).widget_views[0];
249 var z = v.model.get('array_binary');
250 z[0]*=3;
251 z[1]*=3;
252 z[2]*=3;
253 // we set to null so that we recognize the change
254 // when we set data back to z
255 v.model.set('array_binary', null);
256 v.model.set('array_binary', z);
257 v.touch();
258 }, textwidget.index);
259 });
260 this.wait_for_widget(testwidget);
261 this.assert_output_equals('x.array_binary.tolist() == [4.5, 7.5, 15.0]',
262 'True\n', 'Binary custom serializer js -> kernel')
263
264 this.append_cell_execute_then('x.send("some content", [memoryview(b"binarycontent"), memoryview("morecontent")])');
265 this.wait_for_widget(testwidget);
266
267 this.then(function() {
268 var result = this.evaluate(function(index) {
269 var v = IPython.notebook.get_cell(index).widget_views[0];
270 var d = new TextDecoder('utf-8');
271 return {text: v.msg[0],
272 binary0: d.decode(v.msg[1][0]),
273 binary1: d.decode(v.msg[1][1])};
274 }, testwidget.index);
275 this.test.assertEquals(result, {text: 'some content',
276 binary0: 'binarycontent',
277 binary1: 'morecontent'},
278 "Binary widget messages kernel -> js");
279 });
280
281 this.then(function() {
282 this.evaluate(function(index) {
283 var v = IPython.notebook.get_cell(index).widget_views[0];
284 v.send('content back', [new Uint8Array([1,2,3,4]), new Float64Array([2.1828, 3.14159])])
285 }, testwidget.index);
286 });
287 this.wait_for_widget(testwidget);
288 this.assert_output_equals([
289 'all([x.msg[0] == "content back",',
290 ' x.msg[1][0].tolist() == [1,2,3,4],',
291 ' array("d", x.msg[1][1].tobytes()).tolist() == [2.1828, 3.14159]])'].join('\n'),
292 'True', 'Binary buffers message js -> kernel');
293 } else {
294 console.log("skipping binary websocket tests on phantomjs");
295 }
295 296
296 297 });
General Comments 0
You need to be logged in to leave comments. Login now