How to use onError method in sinon

Best JavaScript code snippet using sinon

XmlStore.js

Source:XmlStore.js Github

copy

Full Screen

...33 function onComplete(items, request) {34 t.assertEqual(20, items.length);35 d.callback(true);36 }37 function onError(error, request) {38 d.errback(error);39 }40 store.fetch({query:{isbn:"*"}, onComplete: onComplete, onError: onError});41 return d; //Object42 },43 function testReadAPI_fetch_one(t){44 // summary:45 // Simple test of fetching one xml items through an XML element called isbn46 // description:47 // Simple test of fetching one xml items through an XML element called isbn48 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();49 var d = new doh.Deferred();50 function onComplete(items, request) {51 t.assertEqual(1, items.length);52 d.callback(true);53 }54 function onError(error, request) {55 d.errback(error);56 }57 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});58 return d; //Object59 },60 {61 name: "testReadAPI_fetch_paging",62 timeout: 10000,63 runTest: function(t){64 // summary:65 // Simple test of fetching one xml items through an XML element called isbn66 // description:67 // Simple test of fetching one xml items through an XML element called isbn68 var store = dojox.data.tests.stores.XmlStore.getBooksStore();69 var d = new doh.Deferred();70 71 var dumpSixthFetch = function(items, request){72 t.assertEqual(18, items.length);73 d.callback(true);74 };75 var dumpFifthFetch = function(items, request){76 t.assertEqual(11, items.length);77 request.start = 2;78 request.count = 20;79 request.onComplete = dumpSixthFetch;80 store.fetch(request);81 };82 var dumpFourthFetch = function(items, request){83 t.assertEqual(18, items.length);84 request.start = 9;85 request.count = 100;86 request.onComplete = dumpFifthFetch;87 store.fetch(request);88 };89 var dumpThirdFetch = function (items, request){90 t.assertEqual(5, items.length);91 request.start = 2;92 request.count = 20;93 request.onComplete = dumpFourthFetch;94 store.fetch(request);95 };96 var dumpSecondFetch = function(items, request){97 t.assertEqual(1, items.length);98 request.start = 0;99 request.count = 5;100 request.onComplete = dumpThirdFetch;101 store.fetch(request);102 };103 var dumpFirstFetch = function(items, request){104 t.assertEqual(5, items.length);105 request.start = 3;106 request.count = 1;107 request.onComplete = dumpSecondFetch;108 store.fetch(request);109 };110 var completed = function(items, request){111 t.assertEqual(20, items.length);112 request.start = 1;113 request.count = 5;114 request.onComplete = dumpFirstFetch;115 store.fetch(request);116 };117 118 function error(errData, request){119 d.errback(errData);120 }121 store.fetch({onComplete: completed, onError: error});122 return d; //Object123 }124 },125 function testReadAPI_fetch_pattern0(t){126 // summary:127 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match128 // description:129 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match130 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();131 var d = new doh.Deferred();132 function onComplete(items, request) {133 t.assertEqual(1, items.length);134 d.callback(true);135 }136 function onError(error, request) {137 d.errback(error);138 }139 store.fetch({query:{isbn:"?9B574"}, onComplete: onComplete, onError: onError});140 return d; //Object141 },142 143 function testReadAPI_fetch_pattern1(t){144 // summary:145 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match146 // description:147 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match148 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();149 var d = new doh.Deferred();150 function onComplete(items, request) {151 t.assertEqual(4, items.length);152 d.callback(true);153 }154 function onError(error, request) {155 d.errback(error);156 }157 store.fetch({query:{isbn:"A9B57?"}, onComplete: onComplete, onError: onError});158 return d; //Object159 },160 function testReadAPI_fetch_pattern1_preventCacheOff(t){161 // summary:162 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match163 // with preventCache off to test that it doesn't pass it when told not to.164 // description:165 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match166 // with preventCache off to test that it doesn't pass it when told not to.167 var store = dojox.data.tests.stores.XmlStore.getBooks2StorePC();168 var d = new doh.Deferred();169 function onComplete(items, request) {170 t.assertEqual(4, items.length);171 d.callback(true);172 }173 function onError(error, request) {174 d.errback(error);175 }176 store.fetch({query:{isbn:"A9B57?"}, onComplete: onComplete, onError: onError});177 return d; //Object178 },179 function testReadAPI_fetch_pattern2(t){180 // summary:181 // Simple test of fetching one xml items through an XML element called isbn with * pattern match182 // description:183 // Simple test of fetching one xml items through an XML element called isbn with * pattern match184 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();185 var d = new doh.Deferred();186 function onComplete(items, request) {187 t.assertEqual(5, items.length);188 d.callback(true);189 }190 function onError(error, request) {191 d.errback(error);192 }193 store.fetch({query:{isbn:"A9*"}, onComplete: onComplete, onError: onError});194 return d; //Object195 },196 function testReadAPI_fetch_pattern_multi(t){197 // summary:198 // Simple test of fetching one xml items with a pattern of multiple attrs.199 // description:200 // Simple test of fetching one xml items with a pattern of multiple attrs.201 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();202 var d = new doh.Deferred();203 function onComplete(items, request) {204 t.assertEqual(1, items.length);205 d.callback(true);206 }207 function onError(error, request) {208 d.errback(error);209 }210 store.fetch({query:{isbn:"A9B57?", title: "?itle of 3"}, onComplete: onComplete, onError: onError});211 return d; //Object212 },213 function testReadAPI_fetch_pattern_multiValuedValue(t){214 // summary:215 // Simple test of fetching one xml items with a pattern of multiple attrs.216 // description:217 // Simple test of fetching one xml items with a pattern of multiple attrs.218 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();219 var d = new doh.Deferred();220 function onComplete(items, request) {221 t.assertEqual(1, items.length);222 d.callback(true);223 }224 function onError(error, request) {225 d.errback(error);226 }227 store.fetch({query:{author:"Third Author of 5"}, onComplete: onComplete, onError: onError});228 return d; //Object229 },230 function testReadAPI_fetch_pattern_caseInsensitive(t){231 // summary:232 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match and in case insensitive mode.233 // description:234 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match and in case insensitive mode.235 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();236 var d = new doh.Deferred();237 function onComplete(items, request) {238 t.assertEqual(1, items.length);239 d.callback(true);240 }241 function onError(error, request) {242 d.errback(error);243 }244 store.fetch({query:{isbn:"?9b574"}, queryOptions: {ignoreCase: true}, onComplete: onComplete, onError: onError});245 return d; //Object246 },247 function testReadAPI_fetch_pattern_caseSensitive(t){248 // summary:249 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match and in case sensitive mode.250 // description:251 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match and in case sensitive mode.252 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();253 var d = new doh.Deferred();254 function onComplete(items, request) {255 t.assertEqual(1, items.length);256 d.callback(true);257 }258 function onError(error, request) {259 d.errback(error);260 }261 store.fetch({query:{isbn:"?9B574"}, queryOptions: {ignoreCase: false}, onComplete: onComplete, onError: onError});262 return d; //Object263 },264 function testReadAPI_fetch_regexp(t){265 // summary:266 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match267 // description:268 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match269 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();270 var d = new doh.Deferred();271 function onComplete(items, request) {272 t.assertEqual(1, items.length);273 d.callback(true);274 }275 function onError(error, request) {276 d.errback(error);277 }278 store.fetch({query:{isbn: new RegExp("^.9B574$")}, onComplete: onComplete, onError: onError});279 return d; //Object280 },281 function testReadAPI_fetch_all_rootItem(t){282 // summary:283 // Simple test of fetching all xml items through an XML element called isbn284 // description:285 // Simple test of fetching all xml items through an XML element called isbn286 var store = new dojox.data.XmlStore({url: require.toUrl("dojox/data/tests/stores/books3.xml").toString(),287 rootItem:"book"});288 var d = new doh.Deferred();289 function onComplete(items, request) {290 t.assertEqual(5, items.length);291 d.callback(true);292 }293 function onError(error, request) {294 d.errback(error);295 }296 store.fetch({query:{isbn:"*"}, onComplete: onComplete, onError: onError});297 return d; //Object298 },299 function testReadAPI_fetch_withAttrMap_all(t){300 var store = new dojox.data.XmlStore({url: require.toUrl("dojox/data/tests/stores/books_isbnAttr.xml").toString(),301 attributeMap: {"book.isbn": "@isbn"}});302 var d = new doh.Deferred();303 function onComplete(items, request) {304 t.assertEqual(5, items.length);305 d.callback(true);306 }307 function onError(error, request) {308 console.debug(error);309 d.errback(error);310 }311 store.fetch({query:{isbn:"*"}, onComplete: onComplete, onError: onError});312 return d; //Object313 },314 function testReadAPI_fetch_withAttrMap_one(t){315 var store = new dojox.data.XmlStore({url: require.toUrl("dojox/data/tests/stores/books_isbnAttr.xml").toString(),316 attributeMap: {"book.isbn": "@isbn"}});317 var d = new doh.Deferred();318 function onComplete(items, request) {319 t.assertEqual(1, items.length);320 d.callback(true);321 }322 function onError(error, request) {323 console.debug(error);324 d.errback(error);325 }326 store.fetch({query:{isbn:"2"}, onComplete: onComplete, onError: onError});327 return d; //Object328 },329 function testReadAPI_fetch_withAttrMap_pattern0(t){330 // summary:331 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match332 // description:333 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match334 var store = new dojox.data.XmlStore({url: require.toUrl("dojox/data/tests/stores/books_isbnAttr2.xml").toString(),335 attributeMap: {"book.isbn": "@isbn"}});336 var d = new doh.Deferred();337 function onComplete(items, request) {338 t.assertEqual(3, items.length);339 d.callback(true);340 }341 function onError(error, request) {342 d.errback(error);343 }344 store.fetch({query:{isbn:"ABC?"}, onComplete: onComplete, onError: onError});345 return d; //Object346 },347 function testReadAPI_fetch_withAttrMap_pattern1(t){348 // summary:349 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match350 // description:351 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match352 var store = new dojox.data.XmlStore({url: require.toUrl("dojox/data/tests/stores/books_isbnAttr2.xml").toString(),353 attributeMap: {"book.isbn": "@isbn"}});354 var d = new doh.Deferred();355 function onComplete(items, request) {356 t.assertEqual(5, items.length);357 d.callback(true);358 }359 function onError(error, request) {360 d.errback(error);361 }362 store.fetch({query:{isbn:"A*"}, onComplete: onComplete, onError: onError});363 return d; //Object364 },365 function testReadAPI_fetch_withAttrMap_pattern2(t){366 // summary:367 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match368 // description:369 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match370 var store = new dojox.data.XmlStore({url: require.toUrl("dojox/data/tests/stores/books_isbnAttr2.xml").toString(),371 attributeMap: {"book.isbn": "@isbn"}});372 var d = new doh.Deferred();373 function onComplete(items, request) {374 t.assertEqual(2, items.length);375 d.callback(true);376 }377 function onError(error, request) {378 d.errback(error);379 }380 store.fetch({query:{isbn:"?C*"}, onComplete: onComplete, onError: onError});381 return d; //Object382 },383 function testReadAPI_getLabel(t){384 // summary:385 // Simple test of the getLabel function against a store set that has a label defined.386 // description:387 // Simple test of the getLabel function against a store set that has a label defined.388 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();389 390 var d = new doh.Deferred();391 function onComplete(items, request){392 t.assertEqual(items.length, 1);393 var label = store.getLabel(items[0]);394 t.assertTrue(label !== null);395 t.assertEqual("Title of 4", label);396 d.callback(true);397 }398 function onError(error, request) {399 d.errback(error);400 }401 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});402 return d;403 },404 function testReadAPI_getLabelAttributes(t){405 // summary:406 // Simple test of the getLabelAttributes function against a store set that has a label defined.407 // description:408 // Simple test of the getLabelAttributes function against a store set that has a label defined.409 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();410 411 var d = new doh.Deferred();412 function onComplete(items, request){413 t.assertEqual(items.length, 1);414 var labelList = store.getLabelAttributes(items[0]);415 t.assertTrue(dojo.isArray(labelList));416 t.assertEqual("title", labelList[0]);417 d.callback(true);418 }419 function onError(error, request) {420 d.errback(error);421 }422 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});423 return d;424 },425 function testReadAPI_getValue(t){426 // summary:427 // Simple test of the getValue API428 // description:429 // Simple test of the getValue API430 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();431 var d = new doh.Deferred();432 function onComplete(items, request) {433 t.assertEqual(1, items.length);434 var item = items[0];435 t.assertTrue(store.hasAttribute(item,"isbn"));436 t.assertEqual(store.getValue(item,"isbn"), "A9B574");437 d.callback(true);438 }439 function onError(error, request) {440 d.errback(error);441 }442 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});443 return d; //Object444 },445 function testReadAPI_getValue_cdata(t) {446 // summary:447 // Simple test of the getValue text() special attribute.448 // description:449 // Simple test of the getValue text() special attribute.450 var store = dojox.data.tests.stores.XmlStore.getCDataTestStore();451 var d = new doh.Deferred();452 function onComplete(items, request) {453 t.assertEqual(1, items.length);454 var item = items[0];455 try{456 t.assertTrue(store.hasAttribute(item,"ids"));457 t.assertEqual(store.getValue(item,"ids"), "{68d3c190-4b83-11dd-c204-000000000001}17");458 var title = store.getValue(item, "title");459 t.assertTrue(store.isItem(title));460 var titleValue = store.getValue(title, "text()");461 t.assertEqual("<b>First</b> 3", dojo.trim(titleValue));462 d.callback(true);463 } catch (e) {464 d.errback(e);465 }466 }467 function onError(error, request) {468 d.errback(error);469 }470 store.fetch({query:{ids:"{68d3c190-4b83-11dd-c204-000000000001}17"}, onComplete: onComplete, onError: onError});471 return d; //Object472 },473 function testReadAPI_getValues_cdata(t) {474 // summary:475 // Simple test of the getValues text() special attribute.476 // description:477 // Simple test of the getValues text() special attribute.478 var store = dojox.data.tests.stores.XmlStore.getCDataTestStore();479 var d = new doh.Deferred();480 function onComplete(items, request) {481 t.assertEqual(1, items.length);482 var item = items[0];483 try{484 t.assertTrue(store.hasAttribute(item,"ids"));485 t.assertEqual(store.getValue(item,"ids"), "{68d3c190-4b83-11dd-c204-000000000001}17");486 var title = store.getValue(item, "title");487 t.assertTrue(store.isItem(title));488 var titleValue = store.getValues(title, "text()");489 t.assertEqual("<b>First</b> 3", dojo.trim(titleValue[0]));490 d.callback(true);491 } catch (e) {492 d.errback(e);493 }494 }495 function onError(error, request) {496 d.errback(error);497 }498 store.fetch({query:{ids:"{68d3c190-4b83-11dd-c204-000000000001}17"}, onComplete: onComplete, onError: onError});499 return d; //Object500 },501 function testReadAPI_getValue_cdata_toString(t) {502 // summary:503 // Simple test of the getValue and toString of the resulting 'XmlItem' API504 // description:505 // Simple test of the getValue and toString of the resulting 'XmlItem' API506 var store = dojox.data.tests.stores.XmlStore.getCDataTestStore();507 var d = new doh.Deferred();508 function onComplete(items, request) {509 t.assertEqual(1, items.length);510 var item = items[0];511 try{512 t.assertTrue(store.hasAttribute(item,"ids"));513 t.assertEqual(store.getValue(item,"ids"), "{68d3c190-4b83-11dd-c204-000000000001}17");514 var title = store.getValue(item, "title");515 t.assertTrue(store.isItem(title));516 var firstText = title.toString();517 t.assertEqual("<b>First</b> 3", dojo.trim(firstText));518 d.callback(true);519 } catch (e) {520 d.errback(e);521 }522 }523 function onError(error, request) {524 d.errback(error);525 }526 store.fetch({query:{ids:"{68d3c190-4b83-11dd-c204-000000000001}17"}, onComplete: onComplete, onError: onError});527 return d; //Object528 },529 function testReadAPI_getValues(t){530 // summary:531 // Simple test of the getValues API532 // description:533 // Simple test of the getValues API534 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();535 var d = new doh.Deferred();536 function onComplete(items, request) {537 t.assertEqual(1, items.length);538 var item = items[0];539 t.assertTrue(store.hasAttribute(item,"isbn"));540 var values = store.getValues(item,"isbn");541 t.assertEqual(1,values.length);542 t.assertEqual("A9B574", values[0]);543 d.callback(true);544 }545 function onError(error, request) {546 d.errback(error);547 }548 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});549 return d; //Object550 },551 function testReadAPI_isItem(t){552 // summary:553 // Simple test of the isItem API554 // description:555 // Simple test of the isItem API556 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();557 var d = new doh.Deferred();558 function onComplete(items, request) {559 t.assertEqual(1, items.length);560 var item = items[0];561 t.assertTrue(store.isItem(item));562 t.assertTrue(!store.isItem({}));563 t.assertTrue(!store.isItem("Foo"));564 t.assertTrue(!store.isItem(1));565 d.callback(true);566 }567 function onError(error, request) {568 d.errback(error);569 }570 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});571 return d; //Object572 },573 function testReadAPI_isItem_multistore(t){574 // summary:575 // Simple test of the isItem API across multiple store instances.576 // description:577 // Simple test of the isItem API across multiple store instances.578 var store1 = dojox.data.tests.stores.XmlStore.getBooks2Store();579 var store2 = dojox.data.tests.stores.XmlStore.getBooks2Store();580 var d = new doh.Deferred();581 var onError = function(error, request) {582 d.errback(error);583 };584 var onComplete1 = function(items, request) {585 t.assertEqual(1, items.length);586 var item1 = items[0];587 t.assertTrue(store1.isItem(item1));588 var onComplete2 = function(items, request) {589 t.assertEqual(1, items.length);590 var item2 = items[0];591 t.assertTrue(store2.isItem(item2));592 t.assertTrue(!store1.isItem(item2));593 t.assertTrue(!store2.isItem(item1));594 d.callback(true);595 };596 store2.fetch({query:{isbn:"A9B574"}, onComplete: onComplete2, onError: onError});597 };598 store1.fetch({query:{isbn:"A9B574"}, onComplete: onComplete1, onError: onError});599 return d; //Object600 },601 function testReadAPI_hasAttribute(t){602 // summary:603 // Simple test of the hasAttribute API604 // description:605 // Simple test of the hasAttribute API606 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();607 var d = new doh.Deferred();608 function onComplete(items, request) {609 t.assertEqual(1, items.length);610 var item = items[0];611 t.assertTrue(store.hasAttribute(item,"isbn"));612 t.assertTrue(!store.hasAttribute(item,"bob"));613 //Verify that XML attributes return false in this case.614 t.assertTrue(store.hasAttribute(item,"@xmlAttribute"));615 t.assertFalse(store.hasAttribute(item,"@bogus"));616 d.callback(true);617 }618 function onError(error, request) {619 d.errback(error);620 }621 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});622 return d; //Object623 },624 function testReadAPI_containsValue(t){625 // summary:626 // Simple test of the containsValue API627 // description:628 // Simple test of the containsValue API629 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();630 var d = new doh.Deferred();631 function onComplete(items, request) {632 t.assertEqual(1, items.length);633 var item = items[0];634 t.assertTrue(store.containsValue(item,"isbn", "A9B574"));635 t.assertTrue(!store.containsValue(item,"isbn", "bob"));636 d.callback(true);637 }638 function onError(error, request) {639 d.errback(error);640 }641 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});642 return d; //Object643 },644 function testReadAPI_sortDescending(t){645 // summary:646 // Simple test of the sorting API in descending order.647 // description:648 // Simple test of the sorting API in descending order.649 var store = dojox.data.tests.stores.XmlStore.getBooksStore();650 //Comparison is done as a string type (toString comparison), so the order won't be numeric651 //So have to compare in 'alphabetic' order.652 var order = [9,8,7,6,5,4,3,20,2,19,18,17,16,15,14,13,12,11,10,1];653 654 var d = new doh.Deferred();655 function onComplete(items, request) {656 console.log("Number of items: " + items.length);657 t.assertEqual(20, items.length);658 for(var i = 0; i < items.length; i++){659 t.assertEqual(order[i], store.getValue(items[i],"isbn").toString());660 }661 d.callback(true);662 }663 function onError(error, request) {664 d.errback(error);665 }666 var sortAttributes = [{attribute: "isbn", descending: true}];667 store.fetch({query:{isbn:"*"}, sort: sortAttributes, onComplete: onComplete, onError: onError});668 return d; //Object669 },670 function testReadAPI_sortAscending(t){671 // summary:672 // Simple test of the sorting API in ascending order.673 // description:674 // Simple test of the sorting API in ascending order.675 var store = dojox.data.tests.stores.XmlStore.getBooksStore();676 //Comparison is done as a string type (toString comparison), so the order won't be numeric677 //So have to compare in 'alphabetic' order.678 var order = [1,10,11,12,13,14,15,16,17,18,19,2,20,3,4,5,6,7,8,9];679 680 var d = new doh.Deferred();681 function onComplete(items, request) {682 t.assertEqual(20, items.length);683 var itemId = 1;684 for(var i = 0; i < items.length; i++){685 t.assertEqual(order[i], store.getValue(items[i],"isbn").toString());686 }687 d.callback(true);688 }689 function onError(error, request) {690 d.errback(error);691 }692 var sortAttributes = [{attribute: "isbn"}];693 store.fetch({query:{isbn:"*"}, sort: sortAttributes, onComplete: onComplete, onError: onError});694 return d; //Object695 },696 function testReadAPI_sortDescendingNumeric(t){697 // summary:698 // Simple test of the sorting API in descending order using a numeric comparator.699 // description:700 // Simple test of the sorting API in descending order using a numeric comparator.701 var store = dojox.data.tests.stores.XmlStore.getBooksStore();702 //isbn should be treated as a numeric, not as a string comparison703 store.comparatorMap = {};704 store.comparatorMap["isbn"] = function(a, b){705 var ret = 0;706 if(parseInt(a.toString(), 10) > parseInt(b.toString(), 10)){707 ret = 1;708 }else if(parseInt(a.toString(), 10) < parseInt(b.toString(), 10)){709 ret = -1;710 }711 return ret; //int, {-1,0,1}712 };713 var d = new doh.Deferred();714 function onComplete(items, request) {715 t.assertEqual(20, items.length);716 var itemId = 20;717 for(var i = 0; i < items.length; i++){718 t.assertEqual(itemId, store.getValue(items[i],"isbn").toString());719 itemId--;720 }721 d.callback(true);722 }723 function onError(error, request) {724 d.errback(error);725 }726 var sortAttributes = [{attribute: "isbn", descending: true}];727 store.fetch({query:{isbn:"*"}, sort: sortAttributes, onComplete: onComplete, onError: onError});728 return d; //Object729 },730 function testReadAPI_sortAscendingNumeric(t){731 // summary:732 // Simple test of the sorting API in ascending order using a numeric comparator.733 // description:734 // Simple test of the sorting API in ascending order using a numeric comparator.735 var store = dojox.data.tests.stores.XmlStore.getBooksStore();736 //isbn should be treated as a numeric, not as a string comparison737 store.comparatorMap = {};738 store.comparatorMap["isbn"] = function(a, b){739 var ret = 0;740 if(parseInt(a.toString(), 10) > parseInt(b.toString(), 10)){741 ret = 1;742 }else if(parseInt(a.toString(), 10) < parseInt(b.toString(), 10)){743 ret = -1;744 }745 return ret; //int, {-1,0,1}746 };747 var d = new doh.Deferred();748 function onComplete(items, request) {749 t.assertEqual(20, items.length);750 var itemId = 1;751 for(var i = 0; i < items.length; i++){752 t.assertEqual(itemId, store.getValue(items[i],"isbn").toString());753 itemId++;754 }755 d.callback(true);756 }757 function onError(error, request) {758 d.errback(error);759 }760 var sortAttributes = [{attribute: "isbn"}];761 store.fetch({query:{isbn:"*"}, sort: sortAttributes, onComplete: onComplete, onError: onError});762 return d; //Object763 },764 function testReadAPI_isItemLoaded(t){765 // summary:766 // Simple test of the isItemLoaded API767 // description:768 // Simple test of the isItemLoaded API769 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();770 var d = new doh.Deferred();771 function onComplete(items, request) {772 t.assertEqual(1, items.length);773 var item = items[0];774 t.assertTrue(store.isItemLoaded(item));775 d.callback(true);776 }777 function onError(error, request) {778 d.errback(error);779 }780 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});781 return d; //Object782 },783 function testReadAPI_getFeatures(t){784 // summary:785 // Simple test of the getFeatures function of the store786 // description:787 // Simple test of the getFeatures function of the store788 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();789 var features = store.getFeatures();790 var count = 0;791 var i;792 for(i in features){793 t.assertTrue((i === "dojo.data.api.Read" || i === "dojo.data.api.Write" || "dojo.data.api.Identity"));794 count++;795 }796 t.assertEqual(3, count);797 },798 function testReadAPI_getAttributes(t){799 // summary:800 // Simple test of the getAttributes API801 // description:802 // Simple test of the getAttributes API803 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();804 var d = new doh.Deferred();805 function onComplete(items, request) {806 t.assertEqual(1, items.length);807 var item = items[0];808 var attributes = store.getAttributes(item);809 //Should be six, as all items should have tagName, childNodes, and text() special attributes810 //in addition to any doc defined ones, which in this case are author, title, and isbn811 //FIXME: Figure out why IE returns 5! Need to get firebug lite working in IE for that.812 //Suspect it's childNodes, may not be defined if there are no child nodes.813 for(var i = 0; i < attributes.length; i++){814 console.log("attribute found: " + attributes[i]);815 }816 if(dojo.isIE){817 t.assertEqual(5,attributes.length);818 }else{819 t.assertEqual(6,attributes.length);820 }821 d.callback(true);822 }823 function onError(error, request) {824 d.errback(error);825 }826 store.fetch({query:{isbn:"A9B577"}, onComplete: onComplete, onError: onError});827 return d; //Object828 },829 function testWriteAPI_setValue(t){830 // summary:831 // Simple test of the setValue API832 // description:833 // Simple test of the setValue API834 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();835 var d = new doh.Deferred();836 function onComplete(items, request) {837 t.assertEqual(1, items.length);838 var item = items[0];839 t.assertTrue(store.containsValue(item,"isbn", "A9B574"));840 store.setValue(item, "isbn", "A9B574-new");841 t.assertEqual(store.getValue(item,"isbn").toString(), "A9B574-new");842 d.callback(true);843 }844 function onError(error, request) {845 d.errback(error);846 }847 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});848 return d; //Object849 },850 function testWriteAPI_setValues(t){851 // summary:852 // Simple test of the setValues API853 // description:854 // Simple test of the setValues API855 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();856 var d = new doh.Deferred();857 function onComplete(items, request) {858 t.assertEqual(1, items.length);859 var item = items[0];860 t.assertTrue(store.containsValue(item,"isbn", "A9B574"));861 store.setValues(item, "isbn", ["A9B574-new1", "A9B574-new2"]);862 var values = store.getValues(item,"isbn");863 t.assertEqual(values[0].toString(), "A9B574-new1");864 t.assertEqual(values[1].toString(), "A9B574-new2");865 store.setValues(values[0], "text()", ["A9B574", "-new3"]);866 t.assertEqual(store.getValue(values[0],"text()").toString(), "A9B574-new3");867 d.callback(true);868 }869 function onError(error, request) {870 d.errback(error);871 }872 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});873 return d; //Object874 },875 function testWriteAPI_unsetAttribute(t){876 // summary:877 // Simple test of the unsetAttribute API878 // description:879 // Simple test of the unsetAttribute API880 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();881 var d = new doh.Deferred();882 function onComplete(items, request) {883 t.assertEqual(1, items.length);884 var item = items[0];885 t.assertTrue(store.containsValue(item,"isbn", "A9B574"));886 store.unsetAttribute(item,"isbn");887 t.assertTrue(!store.hasAttribute(item,"isbn"));888 t.assertTrue(store.isDirty(item));889 d.callback(true);890 }891 function onError(error, request) {892 d.errback(error);893 }894 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});895 return d; //Object896 },897 function testWriteAPI_isDirty(t){898 // summary:899 // Simple test of the isDirty API900 // description:901 // Simple test of the isDirty API902 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();903 var d = new doh.Deferred();904 function onComplete(items, request) {905 t.assertEqual(1, items.length);906 var item = items[0];907 t.assertTrue(store.containsValue(item,"isbn", "A9B574"));908 store.setValue(item, "isbn", "A9B574-new");909 t.assertEqual(store.getValue(item,"isbn").toString(), "A9B574-new");910 t.assertTrue(store.isDirty(item));911 d.callback(true);912 }913 function onError(error, request) {914 d.errback(error);915 }916 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});917 return d; //Object918 },919 function testWriteAPI_revert(t){920 // summary:921 // Simple test of the write revert API922 // description:923 // Simple test of the write revert API924 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();925 var d = new doh.Deferred();926 var onError = function(error, request) {927 d.errback(error);928 };929 var onComplete = function(items, request) {930 t.assertEqual(1, items.length);931 var item = items[0];932 t.assertTrue(store.containsValue(item,"isbn", "A9B574"));933 t.assertTrue(!store.isDirty(item));934 store.setValue(item, "isbn", "A9B574-new");935 t.assertEqual(store.getValue(item,"isbn").toString(), "A9B574-new");936 t.assertTrue(store.isDirty(item));937 store.revert();938 939 //Fetch again to see if it reset the state.940 var onComplete1 = function(items, request) {941 t.assertEqual(1, items.length);942 var item = items[0];943 t.assertTrue(store.containsValue(item,"isbn", "A9B574"));944 d.callback(true);945 };946 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete1, onError: onError});947 };948 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});949 return d; //Object950 },951 function testIdentityAPI_getIdentity(t) {952 // summary:953 // Simple test of the Identity getIdentity API954 // description:955 // Simple test of the Identity getIdentity API956 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();957 var d = new doh.Deferred();958 function onComplete(items, request) {959 t.assertEqual(1, items.length);960 var item = items[0];961 try {962 t.assertTrue(store.containsValue(item,"isbn", "A9B5CC"));963 t.assertTrue(store.getIdentity(item) !== null);964 d.callback(true);965 } catch (e) {966 d.errback(e);967 }968 }969 function onError(error, request) {970 d.errback(error);971 }972 store.fetch({query:{isbn:"A9B5CC"}, onComplete: onComplete, onError: onError});973 return d; //Object974 },975 function testIdentityAPI_getIdentityAttributes(t) {976 // summary:977 // Simple test of the Identity getIdentityAttributes API where it defaults to internal xpath (no keyAttribute)978 // description:979 // Simple test of the Identity getIdentityAttributes API where it defaults to internal xpath (no keyAttribute)980 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();981 var d = new doh.Deferred();982 function onItem(item, request) {983 try{984 t.assertTrue(item !== null);985 var idAttrs = store.getIdentityAttributes(item);986 t.assertTrue(idAttrs === null);987 t.assertEqual("/books[0]/book[4]", store.getIdentity(item));988 d.callback(true);989 }catch(e){990 d.errback(e);991 }992 }993 function onError(error, request) {994 d.errback(error);995 }996 store.fetchItemByIdentity({identity: "/books[0]/book[4]", onItem: onItem, onError: onError});997 return d; //Object998 },999 function testIdentityAPI_getIdentityAttributes_usingKeyAttributeIdentity(t) {1000 // summary:1001 // Simple test of the Identity getIdentityAttributes API where identity is specified by the keyAttribute param1002 // description:1003 // Simple test of the Identity getIdentityAttributes API where identity is specified by the keyAttribute param1004 var store = dojox.data.tests.stores.XmlStore.getBooks3Store();1005 var d = new doh.Deferred();1006 function onItem(item, request) {1007 try{1008 t.assertTrue(item !== null);1009 var idAttrs = store.getIdentityAttributes(item);1010 t.assertTrue(idAttrs !== null);1011 t.assertTrue(idAttrs.length === 1);1012 t.assertTrue(idAttrs[0] === "isbn");1013 d.callback(true);1014 }catch(e){1015 d.errback(e);1016 }1017 }1018 function onError(error, request) {1019 d.errback(error);1020 }1021 store.fetchItemByIdentity({identity: "A9B574", onItem: onItem, onError: onError});1022 return d; //Object1023 },1024 function testIdentityAPI_fetchItemByIdentity(t) {1025 // summary:1026 // Simple test of the Identity getIdentity API where the store defaults the identity to a xpathlike lookup.1027 // description:1028 // Simple test of the Identity getIdentity API where the store defaults the identity to a xpathlike lookup.1029 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();1030 var d = new doh.Deferred();1031 function onItem(item, request) {1032 try{1033 t.assertTrue(item !== null);1034 t.assertEqual("/books[0]/book[4]", store.getIdentity(item));1035 d.callback(true);1036 }catch(e){1037 d.errback(e);1038 }1039 }1040 function onError(error, request) {1041 d.errback(error);1042 }1043 store.fetchItemByIdentity({identity: "/books[0]/book[4]", onItem: onItem, onError: onError});1044 return d; //Object1045 1046 },1047 function testIdentityAPI_fetchItemByIdentity2(t) {1048 // summary:1049 // Simple test of the Identity getIdentity API where the store defaults the identity to a xpathlike lookup.1050 // description:1051 // Simple test of the Identity getIdentity API where the store defaults the identity to a xpathlike lookup.1052 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();1053 var d = new doh.Deferred();1054 function onItem(item, request) {1055 try{1056 t.assertTrue(item !== null);1057 t.assertEqual("/books[0]/book[0]", store.getIdentity(item));1058 d.callback(true);1059 }catch(e){1060 d.errback(e);1061 }1062 }1063 function onError(error, request) {1064 d.errback(error);1065 }1066 store.fetchItemByIdentity({identity: "/books[0]/book[0]", onItem: onItem, onError: onError});1067 return d; //Object1068 1069 },1070 function testIdentityAPI_fetchItemByIdentity3(t) {1071 // summary:1072 // Simple test of the Identity getIdentity API where the store defaults the identity to a xpathlike lookup.1073 // description:1074 // Simple test of the Identity getIdentity API where the store defaults the identity to a xpathlike lookup.1075 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();1076 var d = new doh.Deferred();1077 function onItem(item, request) {1078 try{1079 t.assertTrue(item !== null);1080 t.assertEqual("/books[0]/book[2]", store.getIdentity(item));1081 d.callback(true);1082 }catch(e){1083 d.errback(e);1084 }1085 }1086 function onError(error, request) {1087 d.errback(error);1088 }1089 store.fetchItemByIdentity({identity: "/books[0]/book[2]", onItem: onItem, onError: onError});1090 return d; //Object1091 1092 },1093 function testIdentityAPI_fetchItemByIdentity_usingKeyAttributeIdentity(t) {1094 // summary:1095 // Simple test of the Identity getIdentity API where identity is specified by the keyAttribute param1096 // description:1097 // Simple test of the Identity getIdentity API where identity is specified by the keyAttribute param1098 var store = dojox.data.tests.stores.XmlStore.getBooks3Store();1099 var d = new doh.Deferred();1100 function onItem(item, request) {1101 try{1102 t.assertTrue(item !== null);1103 t.assertEqual("A9B574", store.getIdentity(item));1104 d.callback(true);1105 }catch(e){1106 d.errback(e);1107 }1108 }1109 function onError(error, request) {1110 d.errback(error);1111 }1112 store.fetchItemByIdentity({identity: "A9B574", onItem: onItem, onError: onError});1113 return d; //Object1114 },1115 function testIdentityAPI_fetchItemByIdentity_usingKeyAttributeIdentity2(t) {1116 // summary:1117 // Simple test of the Identity getIdentity API where identity is specified by the keyAttribute param1118 // description:1119 // Simple test of the Identity getIdentity API where identity is specified by the keyAttribute param1120 var store = dojox.data.tests.stores.XmlStore.getBooks3Store();1121 var d = new doh.Deferred();1122 function onItem(item, request) {1123 try{1124 t.assertTrue(item !== null);1125 t.assertEqual("A9B57C", store.getIdentity(item));1126 d.callback(true);1127 }catch(e){1128 d.errback(e);1129 }1130 }1131 function onError(error, request) {1132 d.errback(error);1133 }1134 store.fetchItemByIdentity({identity: "A9B57C", onItem: onItem, onError: onError});1135 return d; //Object1136 },1137 function testIdentityAPI_fetchItemByIdentity_usingKeyAttributeIdentity3(t) {1138 // summary:1139 // Simple test of the Identity getIdentity API where identity is specified by the keyAttribute param1140 // description:1141 // Simple test of the Identity getIdentity API where identity is specified by the keyAttribute param1142 var store = dojox.data.tests.stores.XmlStore.getBooks3Store();1143 var d = new doh.Deferred();1144 function onItem(item, request) {1145 try{1146 t.assertTrue(item !== null);1147 t.assertEqual("A9B5CC", store.getIdentity(item));1148 d.callback(true);1149 }catch(e){1150 d.errback(e);1151 }1152 }1153 function onError(error, request) {1154 d.errback(error);1155 }1156 store.fetchItemByIdentity({identity: "A9B5CC", onItem: onItem, onError: onError});1157 return d; //Object1158 },1159 function testIdentityAPI_fetchItemByIdentity_usingKeyAttributeIdentity4(t) {1160 // summary:1161 // Simple test of the Identity getIdentity API where identity is specified by the keyAttribute param1162 // description:1163 // Simple test of the Identity getIdentity API where identity is specified by the keyAttribute param1164 var store = dojox.data.tests.stores.XmlStore.getGeographyStore();1165 var d = new doh.Deferred();1166 function onItem(item, request) {1167 try{1168 t.assertTrue(item !== null);1169 t.assertEqual("Mexico City", store.getIdentity(item));1170 d.callback(true);1171 }catch(e){1172 d.errback(e);1173 }1174 }1175 function onError(error, request) {1176 d.errback(error);1177 }1178 store.fetchItemByIdentity({identity: "Mexico City", onItem: onItem, onError: onError});1179 return d; //Object1180 },1181 function testIdentityAPI_fetchItemByIdentity_fails(t) {1182 // summary:1183 // Simple test of the Identity getIdentity API1184 // description:1185 // Simple test of the Identity getIdentity API1186 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();1187 var d = new doh.Deferred();1188 function onItem(item, request) {1189 t.assertTrue(item === null);1190 d.callback(true);1191 }1192 function onError(error, request) {1193 d.errback(error);1194 }1195 //In memory stores use dojo query syntax for the identifier.1196 store.fetchItemByIdentity({identity: "/books[0]/book[200]", onItem: onItem, onError: onError});1197 return d; //Object1198 },1199 function testIdentityAPI_fetchItemByIdentity_fails2(t) {1200 // summary:1201 // Simple test of the Identity getIdentity API1202 // description:1203 // Simple test of the Identity getIdentity API1204 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();1205 var d = new doh.Deferred();1206 function onItem(item, request) {1207 t.assertTrue(item === null);1208 d.callback(true);1209 }1210 function onError(error, request) {1211 d.errback(error);1212 }1213 //In memory stores use dojo query syntax for the identifier.1214 store.fetchItemByIdentity({identity: "/books[1]/book[4]", onItem: onItem, onError: onError});1215 return d; //Object1216 },1217 function testIdentityAPI_fetchItemByIdentity_fails3(t) {1218 // summary:1219 // Simple test of the Identity getIdentity API1220 // description:1221 // Simple test of the Identity getIdentity API1222 var store = dojox.data.tests.stores.XmlStore.getBooks2Store();1223 var d = new doh.Deferred();1224 function onItem(item, request) {1225 t.assertTrue(item === null);1226 d.callback(true);1227 }1228 function onError(error, request) {1229 d.errback(error);1230 }1231 //In memory stores use dojo query syntax for the identifier.1232 store.fetchItemByIdentity({identity: "/books[1]/book[200]", onItem: onItem, onError: onError});1233 return d; //Object1234 },1235 function testIdentityAPI_fetchItemByIdentity_usingKeyAttributeIdentity_fails(t) {1236 // summary:1237 // Simple test of the Identity getIdentity API where identity is specified by the keyAttribute param1238 // description:1239 // Simple test of the Identity getIdentity API where identity is specified by the keyAttribute param1240 var store = dojox.data.tests.stores.XmlStore.getBooks3Store();1241 var d = new doh.Deferred();1242 function onItem(item, request) {1243 try{1244 t.assertTrue(item === null);1245 d.callback(true);1246 }catch(e){1247 d.errback(e);1248 }1249 }1250 function onError(error, request) {1251 d.errback(error);1252 }1253 store.fetchItemByIdentity({identity: "A9B574_NONEXISTANT", onItem: onItem, onError: onError});1254 return d; //Object1255 },1256 function testReadAPI_functionConformance(t){1257 // summary:1258 // Simple test read API conformance. Checks to see all declared functions are actual functions on the instances.1259 // description:1260 // Simple test read API conformance. Checks to see all declared functions are actual functions on the instances.1261 var testStore = dojox.data.tests.stores.XmlStore.getBooksStore();1262 var readApi = new dojo.data.api.Read();1263 var passed = true;1264 var i;...

Full Screen

Full Screen

HtmlStore.js

Source:HtmlStore.js Github

copy

Full Screen

...35 function onComplete(items, request) {36 t.assertEqual(20, items.length);37 d.callback(true);38 }39 function onError(error, request) {40 d.errback(error);41 }42 store.fetch({query:{isbn:"*"}, onComplete: onComplete, onError: onError});43 return d; //Object44 },45 function testReadAPI_fetch_all_table_Whitespace(t){46 // summary:47 // Simple test of fetching all table row items through an header called isbn48 // description:49 // Simple test of fetching all table row items through an header called isbn50 var store = dojox.data.tests.stores.HtmlStore.getBooksStoreWhitespace();51 var d = new doh.Deferred();52 function onComplete(items, request) {53 t.assertEqual(20, items.length);54 d.callback(true);55 }56 function onError(error, request) {57 d.errback(error);58 }59 store.fetch({query:{isbn:"*"}, onComplete: onComplete, onError: onError});60 return d; //Object61 },62 function testReadAPI_fetch_all_list(t){63 // summary:64 // Simple test of fetching all xml items through an XML element called isbn65 // description:66 // Simple test of fetching all xml items through an XML element called isbn67 var store = dojox.data.tests.stores.HtmlStore.getBooks3Store();68 var d = new doh.Deferred();69 function onComplete(items, request) {70 t.assertEqual(5, items.length);71 d.callback(true);72 }73 function onError(error, request) {74 d.errback(error);75 }76 store.fetch({query:{name:"*"}, onComplete: onComplete, onError: onError});77 return d; //Object78 },79 function testReadAPI_fetch_one_table(t){80 // summary:81 // Simple test of fetching one xml items through an XML element called isbn82 // description:83 // Simple test of fetching one xml items through an XML element called isbn84 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();85 var d = new doh.Deferred();86 function onComplete(items, request) {87 t.assertEqual(1, items.length);88 d.callback(true);89 }90 function onError(error, request) {91 d.errback(error);92 }93 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});94 return d; //Object95 },96 function testReadAPI_fetch_one_table_Whitespace(t){97 // summary:98 // Simple test of fetching one item through an element called isbn99 // description:100 // Simple test of fetching one item through an element called isbn101 var store = dojox.data.tests.stores.HtmlStore.getBooksStoreWhitespace();102 var d = new doh.Deferred();103 function onComplete(items, request) {104 t.assertEqual(1, items.length);105 d.callback(true);106 }107 function onError(error, request) {108 d.errback(error);109 }110 store.fetch({query:{isbn:"19"}, onComplete: onComplete, onError: onError});111 return d; //Object112 },113 function testReadAPI_fetch_one_list(t){114 // summary:115 // Simple test of fetching one xml items through an XML element called isbn116 // description:117 // Simple test of fetching one xml items through an XML element called isbn118 var store = dojox.data.tests.stores.HtmlStore.getBooks3Store();119 var d = new doh.Deferred();120 function onComplete(items, request) {121 t.assertEqual(1, items.length);122 d.callback(true);123 }124 function onError(error, request) {125 d.errback(error);126 }127 store.fetch({query:{name:"A9B57C - Title of 1 - Author of 1"}, onComplete: onComplete, onError: onError});128 return d; //Object129 },130 function testReadAPI_fetch_one_list_oncreate(t){131 // summary:132 // Simple test of fetching one xml items through an XML element called isbn133 // description:134 // Simple test of fetching one xml items through an XML element called isbn135 var store = dojox.data.tests.stores.HtmlStore.getBooks3StoreOnCreate();136 var d = new doh.Deferred();137 function onComplete(items, request) {138 t.assertEqual(1, items.length);139 d.callback(true);140 }141 function onError(error, request) {142 d.errback(error);143 }144 store.fetch({query:{name:"A9B57C - Title of 1 - Author of 1"}, onComplete: onComplete, onError: onError});145 return d; //Object146 },147 function testReadAPI_fetch_one_list_Whitespace(t){148 // summary:149 // Simple test of fetching one item through an attribute called name150 // description:151 // Simple test of fetching one item through an attribute called name152 var store = dojox.data.tests.stores.HtmlStore.getBooks3StoreWhitespace();153 var d = new doh.Deferred();154 function onComplete(items, request) {155 t.assertEqual(1, items.length);156 d.callback(true);157 }158 function onError(error, request) {159 d.errback(error);160 }161 store.fetch({query:{name:"A9B57C - Title of 1 - Author of 1"}, onComplete: onComplete, onError: onError});162 return d; //Object163 },164 function testReadAPI_fetch_paging(t){165 // summary:166 // Simple test of fetching one xml items through an XML element called isbn167 // description:168 // Simple test of fetching one xml items through an XML element called isbn169 var store = dojox.data.tests.stores.HtmlStore.getBooksStore();170 171 var d = new doh.Deferred();172 function dumpFirstFetch(items, request){173 t.assertEqual(5, items.length);174 request.start = 3;175 request.count = 1;176 request.onComplete = dumpSecondFetch;177 store.fetch(request);178 }179 function dumpSecondFetch(items, request){180 t.assertEqual(1, items.length);181 request.start = 0;182 request.count = 5;183 request.onComplete = dumpThirdFetch;184 store.fetch(request);185 }186 function dumpThirdFetch(items, request){187 t.assertEqual(5, items.length);188 request.start = 2;189 request.count = 20;190 request.onComplete = dumpFourthFetch;191 store.fetch(request);192 }193 function dumpFourthFetch(items, request){194 t.assertEqual(18, items.length);195 request.start = 9;196 request.count = 100;197 request.onComplete = dumpFifthFetch;198 store.fetch(request);199 }200 function dumpFifthFetch(items, request){201 t.assertEqual(11, items.length);202 request.start = 2;203 request.count = 20;204 request.onComplete = dumpSixthFetch;205 store.fetch(request);206 }207 function dumpSixthFetch(items, request){208 t.assertEqual(18, items.length);209 d.callback(true);210 }211 function completed(items, request){212 t.assertEqual(20, items.length);213 request.start = 1;214 request.count = 5;215 request.onComplete = dumpFirstFetch;216 store.fetch(request);217 }218 function error(errData, request){219 d.errback(errData);220 }221 store.fetch({onComplete: completed, onError: error});222 return d; //Object223 },224 function testReadAPI_fetch_pattern0(t){225 // summary:226 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match227 // description:228 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match229 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();230 var d = new doh.Deferred();231 function onComplete(items, request) {232 t.assertEqual(1, items.length);233 d.callback(true);234 }235 function onError(error, request) {236 d.errback(error);237 }238 store.fetch({query:{isbn:"?9B574"}, onComplete: onComplete, onError: onError});239 return d; //Object240 },241 function testReadAPI_fetch_pattern1(t){242 // summary:243 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match244 // description:245 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match246 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();247 var d = new doh.Deferred();248 function onComplete(items, request) {249 t.assertEqual(4, items.length);250 d.callback(true);251 }252 function onError(error, request) {253 d.errback(error);254 }255 store.fetch({query:{isbn:"A9B57?"}, onComplete: onComplete, onError: onError});256 return d; //Object257 },258 function testReadAPI_fetch_pattern2(t){259 // summary:260 // Simple test of fetching one xml items through an XML element called isbn with * pattern match261 // description:262 // Simple test of fetching one xml items through an XML element called isbn with * pattern match263 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();264 var d = new doh.Deferred();265 function onComplete(items, request) {266 t.assertEqual(5, items.length);267 d.callback(true);268 }269 function onError(error, request) {270 d.errback(error);271 }272 store.fetch({query:{isbn:"A9*"}, onComplete: onComplete, onError: onError});273 return d; //Object274 },275 function testReadAPI_fetch_pattern_caseInsensitive(t){276 // summary:277 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match and in case insensitive mode.278 // description:279 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match and in case insensitive mode.280 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();281 var d = new doh.Deferred();282 function onComplete(items, request) {283 t.assertEqual(1, items.length);284 d.callback(true);285 }286 function onError(error, request) {287 d.errback(error);288 }289 store.fetch({query:{isbn:"?9b574"}, queryOptions: {ignoreCase: true}, onComplete: onComplete, onError: onError});290 return d; //Object291 },292 function testReadAPI_fetch_pattern_caseSensitive(t){293 // summary:294 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match and in case sensitive mode.295 // description:296 // Simple test of fetching one xml items through an XML element called isbn with ? pattern match and in case sensitive mode.297 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();298 var d = new doh.Deferred();299 function onComplete(items, request) {300 t.assertEqual(1, items.length);301 d.callback(true);302 }303 function onError(error, request) {304 d.errback(error);305 }306 store.fetch({query:{isbn:"?9B574"}, queryOptions: {ignoreCase: false}, onComplete: onComplete, onError: onError});307 return d; //Object308 },309 function testReadAPI_getLabel_table(t){310 // summary:311 // Simple test of the getLabel function against a store set that has a label defined.312 // description:313 // Simple test of the getLabel function against a store set that has a label defined.314 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();315 316 var d = new doh.Deferred();317 function onComplete(items, request){318 t.assertEqual(items.length, 1);319 var label = store.getLabel(items[0]);320 t.assertTrue(label !== null);321 t.assertEqual("Item #4", label);322 d.callback(true);323 }324 function onError(error, request) {325 d.errback(error);326 }327 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});328 return d;329 },330 function testReadAPI_getLabel_list(t){331 // summary:332 // Simple test of the getLabel function against a store set that has a label defined.333 // description:334 // Simple test of the getLabel function against a store set that has a label defined.335 var store = dojox.data.tests.stores.HtmlStore.getBooks3Store();336 337 var d = new doh.Deferred();338 function onComplete(items, request){339 t.assertEqual(items.length, 1);340 var label = store.getLabel(items[0]);341 t.assertTrue(label !== null);342 t.assertEqual("A9B57C - Title of 1 - Author of 1", label);343 d.callback(true);344 }345 function onError(error, request) {346 d.errback(error);347 }348 store.fetch({query:{name:"A9B57C - Title of 1 - Author of 1"}, onComplete: onComplete, onError: onError});349 return d;350 },351 function testReadAPI_getLabelAttributes(t){352 // summary:353 // Simple test of the getLabelAttributes function against a store set that has a label defined.354 // description:355 // Simple test of the getLabelAttributes function against a store set that has a label defined.356 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();357 358 var d = new doh.Deferred();359 function onComplete(items, request){360 t.assertEqual(items.length, 1);361 var labelList = store.getLabelAttributes(items[0]);362 t.assertTrue(labelList === null);363 d.callback(true);364 }365 function onError(error, request) {366 d.errback(error);367 }368 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});369 return d;370 },371 function testReadAPI_getValue(t){372 // summary:373 // Simple test of the getValue API374 // description:375 // Simple test of the getValue API376 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();377 var d = new doh.Deferred();378 function onComplete(items, request) {379 t.assertEqual(1, items.length);380 var item = items[0];381 t.assertTrue(store.hasAttribute(item,"isbn"));382 t.assertEqual(store.getValue(item,"isbn"), "A9B574");383 d.callback(true);384 }385 function onError(error, request) {386 d.errback(error);387 }388 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});389 return d; //Object390 },391 function testReadAPI_getValues(t){392 // summary:393 // Simple test of the getValues API394 // description:395 // Simple test of the getValues API396 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();397 var d = new doh.Deferred();398 function onComplete(items, request) {399 t.assertEqual(1, items.length);400 var item = items[0];401 t.assertTrue(store.hasAttribute(item,"isbn"));402 var values = store.getValues(item,"isbn");403 t.assertEqual(1,values.length);404 t.assertEqual("A9B574", values[0]);405 d.callback(true);406 }407 function onError(error, request) {408 d.errback(error);409 }410 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});411 return d; //Object412 },413 function testReadAPI_isItem(t){414 // summary:415 // Simple test of the isItem API416 // description:417 // Simple test of the isItem API418 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();419 var d = new doh.Deferred();420 function onComplete(items, request) {421 t.assertEqual(1, items.length);422 var item = items[0];423 t.assertTrue(store.isItem(item));424 t.assertTrue(!store.isItem({}));425 t.assertTrue(!store.isItem("Foo"));426 t.assertTrue(!store.isItem(1));427 d.callback(true);428 }429 function onError(error, request) {430 d.errback(error);431 }432 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});433 return d; //Object434 },435 function testReadAPI_isItem_multistore(t){436 // summary:437 // Simple test of the isItem API across multiple store instances.438 // description:439 // Simple test of the isItem API across multiple store instances.440 var store1 = dojox.data.tests.stores.HtmlStore.getBooksStore();441 var store2 = dojox.data.tests.stores.HtmlStore.getBooks2Store();442 var d = new doh.Deferred();443 function onComplete1(items, request) {444 t.assertEqual(1, items.length);445 var item1 = items[0];446 t.assertTrue(store1.isItem(item1));447 function onComplete2(items, request) {448 t.assertEqual(1, items.length);449 var item2 = items[0];450 t.assertTrue(store2.isItem(item2));451 t.assertTrue(!store1.isItem(item2));452 t.assertTrue(!store2.isItem(item1));453 d.callback(true);454 }455 store2.fetch({query:{isbn:"A9B574"}, onComplete: onComplete2, onError: onError});456 }457 function onError(error, request) {458 d.errback(error);459 }460 store1.fetch({query:{isbn:"1"}, onComplete: onComplete1, onError: onError});461 return d; //Object462 },463 function testReadAPI_hasAttribute(t){464 // summary:465 // Simple test of the hasAttribute API466 // description:467 // Simple test of the hasAttribute API468 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();469 var d = new doh.Deferred();470 function onComplete(items, request) {471 t.assertEqual(1, items.length);472 var item = items[0];473 t.assertTrue(store.hasAttribute(item,"isbn"));474 t.assertTrue(!store.hasAttribute(item,"bob"));475 d.callback(true);476 }477 function onError(error, request) {478 d.errback(error);479 }480 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});481 return d; //Object482 },483 function testReadAPI_containsValue(t){484 // summary:485 // Simple test of the containsValue API486 // description:487 // Simple test of the containsValue API488 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();489 var d = new doh.Deferred();490 function onComplete(items, request) {491 t.assertEqual(1, items.length);492 var item = items[0];493 t.assertTrue(store.containsValue(item,"isbn", "A9B574"));494 t.assertTrue(!store.containsValue(item,"isbn", "bob"));495 d.callback(true);496 }497 function onError(error, request) {498 d.errback(error);499 }500 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});501 return d; //Object502 },503 function testReadAPI_sortDescending(t){504 // summary:505 // Simple test of the sorting API in descending order.506 // description:507 // Simple test of the sorting API in descending order.508 var store = dojox.data.tests.stores.HtmlStore.getBooksStore();509 //Comparison is done as a string type (toString comparison), so the order won't be numeric510 //So have to compare in 'alphabetic' order.511 var order = [9,8,7,6,5,4,3,20,2,19,18,17,16,15,14,13,12,11,10,1];512 513 var d = new doh.Deferred();514 function onComplete(items, request) {515 t.assertEqual(20, items.length);516 for(var i = 0; i < items.length; i++){517 t.assertEqual(order[i], store.getValue(items[i],"isbn").toString());518 }519 d.callback(true);520 }521 function onError(error, request) {522 d.errback(error);523 }524 var sortAttributes = [{attribute: "isbn", descending: true}];525 store.fetch({query:{isbn:"*"}, sort: sortAttributes, onComplete: onComplete, onError: onError});526 return d; //Object527 },528 function testReadAPI_sortAscending(t){529 // summary:530 // Simple test of the sorting API in ascending order.531 // description:532 // Simple test of the sorting API in ascending order.533 var store = dojox.data.tests.stores.HtmlStore.getBooksStore();534 //Comparison is done as a string type (toString comparison), so the order won't be numeric535 //So have to compare in 'alphabetic' order.536 var order = [1,10,11,12,13,14,15,16,17,18,19,2,20,3,4,5,6,7,8,9];537 538 var d = new doh.Deferred();539 function onComplete(items, request) {540 t.assertEqual(20, items.length);541 var itemId = 1;542 for(var i = 0; i < items.length; i++){543 t.assertEqual(order[i], store.getValue(items[i],"isbn").toString());544 }545 d.callback(true);546 }547 function onError(error, request) {548 d.errback(error);549 }550 var sortAttributes = [{attribute: "isbn"}];551 store.fetch({query:{isbn:"*"}, sort: sortAttributes, onComplete: onComplete, onError: onError});552 return d; //Object553 },554 function testReadAPI_sortDescendingNumeric(t){555 // summary:556 // Simple test of the sorting API in descending order using a numeric comparator.557 // description:558 // Simple test of the sorting API in descending order using a numeric comparator.559 var store = dojox.data.tests.stores.HtmlStore.getBooksStore();560 //isbn should be treated as a numeric, not as a string comparison561 store.comparatorMap = {};562 store.comparatorMap["isbn"] = function(a, b){563 var ret = 0;564 if(parseInt(a.toString()) > parseInt(b.toString())){565 ret = 1;566 }else if(parseInt(a.toString()) < parseInt(b.toString())){567 ret = -1;568 }569 return ret; //int, {-1,0,1}570 };571 var d = new doh.Deferred();572 function onComplete(items, request) {573 t.assertEqual(20, items.length);574 var itemId = 20;575 for(var i = 0; i < items.length; i++){576 t.assertEqual(itemId, store.getValue(items[i],"isbn").toString());577 itemId--;578 }579 d.callback(true);580 }581 function onError(error, request) {582 d.errback(error);583 }584 var sortAttributes = [{attribute: "isbn", descending: true}];585 store.fetch({query:{isbn:"*"}, sort: sortAttributes, onComplete: onComplete, onError: onError});586 return d; //Object587 },588 function testReadAPI_sortAscendingNumeric(t){589 // summary:590 // Simple test of the sorting API in ascending order using a numeric comparator.591 // description:592 // Simple test of the sorting API in ascending order using a numeric comparator.593 var store = dojox.data.tests.stores.HtmlStore.getBooksStore();594 //isbn should be treated as a numeric, not as a string comparison595 store.comparatorMap = {};596 store.comparatorMap["isbn"] = function(a, b){597 var ret = 0;598 if(parseInt(a.toString()) > parseInt(b.toString())){599 ret = 1;600 }else if(parseInt(a.toString()) < parseInt(b.toString())){601 ret = -1;602 }603 return ret; //int, {-1,0,1}604 };605 var d = new doh.Deferred();606 function onComplete(items, request) {607 t.assertEqual(20, items.length);608 var itemId = 1;609 for(var i = 0; i < items.length; i++){610 t.assertEqual(itemId, store.getValue(items[i],"isbn").toString());611 itemId++;612 }613 d.callback(true);614 }615 function onError(error, request) {616 d.errback(error);617 }618 var sortAttributes = [{attribute: "isbn"}];619 store.fetch({query:{isbn:"*"}, sort: sortAttributes, onComplete: onComplete, onError: onError});620 return d; //Object621 },622 function testReadAPI_isItemLoaded(t){623 // summary:624 // Simple test of the isItemLoaded API625 // description:626 // Simple test of the isItemLoaded API627 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();628 var d = new doh.Deferred();629 function onComplete(items, request) {630 t.assertEqual(1, items.length);631 var item = items[0];632 t.assertTrue(store.isItemLoaded(item));633 d.callback(true);634 }635 function onError(error, request) {636 d.errback(error);637 }638 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});639 return d; //Object640 },641 function testReadAPI_getFeatures(t){642 // summary:643 // Simple test of the getFeatures function of the store644 // description:645 // Simple test of the getFeatures function of the store646 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();647 var features = store.getFeatures();648 var count = 0;649 for(i in features){650 t.assertTrue((i === "dojo.data.api.Read" || i === "dojo.data.api.Identity"));651 count++;652 }653 t.assertEqual(2, count);654 },655 function testReadAPI_getAttributes(t){656 // summary:657 // Simple test of the getAttributes API658 // description:659 // Simple test of the getAttributes API660 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();661 var d = new doh.Deferred();662 function onComplete(items, request) {663 t.assertEqual(1, items.length);664 var item = items[0];665 var attributes = store.getAttributes(item);666 t.assertEqual(3,attributes.length);667 for(var i=0; i<attributes.length; i++){668 t.assertTrue((attributes[i] === "isbn" || attributes[i] === "title" || attributes[i] === "author"));669 }670 d.callback(true);671 }672 function onError(error, request) {673 d.errback(error);674 }675 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});676 return d; //Object677 },678 function testReadAPI_functionConformance(t){679 // summary:680 // Simple test read API conformance. Checks to see all declared functions are actual functions on the instances.681 // description:682 // Simple test read API conformance. Checks to see all declared functions are actual functions on the instances.683 var testStore = dojox.data.tests.stores.HtmlStore.getBooksStore();684 var readApi = new dojo.data.api.Read();685 var passed = true;686 for(i in readApi){687 var member = readApi[i];688 //Check that all the 'Read' defined functions exist on the test store.689 if(typeof member === "function"){690 var testStoreMember = testStore[i];691 if(!(typeof testStoreMember === "function")){692 console.log("Problem with function: [" + i + "]");693 passed = false;694 break;695 }696 }697 }698 t.assertTrue(passed);699 },700/***************************************701 dojo.data.api.Identity API702***************************************/703 function testIdentityAPI_getIdentity_table(t){704 // summary:705 // Simple test of the getAttributes API706 // description:707 // Simple test of the getAttributes API708 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();709 var d = new doh.Deferred();710 function onComplete(items, request) {711 t.assertEqual(1, items.length);712 var item = items[0];713 t.assertEqual(4,store.getIdentity(item));714 d.callback(true);715 }716 function onError(error, request) {717 d.errback(error);718 }719 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});720 return d; //Object721 },722 function testIdentityAPI_getIdentity_list(t){723 // summary:724 // Simple test of the getAttributes API725 // description:726 // Simple test of the getAttributes API727 var store = dojox.data.tests.stores.HtmlStore.getBooks3Store();728 var d = new doh.Deferred();729 function onComplete(items, request) {730 t.assertEqual(1, items.length);731 var item = items[0];732 t.assertEqual("A9B57C - Title of 1 - Author of 1",store.getIdentity(item));733 d.callback(true);734 }735 function onError(error, request) {736 d.errback(error);737 }738 store.fetch({query:{name:"A9B57C - Title of 1 - Author of 1"}, onComplete: onComplete, onError: onError});739 return d; //Object740 },741 function testIdentityAPI_getIdentityAttributes(t){742 // summary:743 // Simple test of the getAttributes API744 // description:745 // Simple test of the getAttributes API746 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();747 var d = new doh.Deferred();748 function onComplete(items, request) {749 t.assertEqual(1, items.length);750 var item = items[0];751 //Should have none, as it's not a public attribute.752 var attributes = store.getIdentityAttributes(item);753 t.assertEqual(null, attributes);754 d.callback(true);755 }756 function onError(error, request) {757 d.errback(error);758 }759 store.fetch({query:{isbn:"A9B574"}, onComplete: onComplete, onError: onError});760 return d; //Object761 },762 function testIdentityAPI_fetchItemByIdentity_table(t){763 // summary:764 // Simple test of the fetchItemByIdentity API765 // description:766 // Simple test of the fetchItemByIdentity API767 var store = dojox.data.tests.stores.HtmlStore.getBooks2Store();768 var d = new doh.Deferred();769 function onItem(item, request) {770 t.assertTrue(item !== null);771 t.assertTrue(store.isItem(item));772 t.assertEqual("A9B574", store.getValue(item, "isbn"));773 d.callback(true);774 }775 function onError(error, request) {776 d.errback(error);777 }778 store.fetchItemByIdentity({identity: 4, onItem: onItem, onError: onError});779 return d; //Object780 },781 function testIdentityAPI_fetchItemByIdentity_list(t){782 // summary:783 // Simple test of the fetchItemByIdentity API784 // description:785 // Simple test of the fetchItemByIdentity API786 var store = dojox.data.tests.stores.HtmlStore.getBooks3Store();787 var d = new doh.Deferred();788 function onItem(item, request) {789 t.assertTrue(item !== null);790 t.assertTrue(store.isItem(item));791 t.assertEqual("A9B57C - Title of 1 - Author of 1", store.getValue(item, "name"));792 d.callback(true);793 }794 function onError(error, request) {795 d.errback(error);796 }797 store.fetchItemByIdentity({identity: "A9B57C - Title of 1 - Author of 1", onItem: onItem, onError: onError});798 return d; //Object799 },800 function testIdentityAPI_functionConformance(t){801 // summary:802 // Simple test identity API conformance. Checks to see all declared functions are actual functions on the instances.803 // description:804 // Simple test identity API conformance. Checks to see all declared functions are actual functions on the instances.805 var testStore = dojox.data.tests.stores.HtmlStore.getBooksStore();806 var identityApi = new dojo.data.api.Identity();807 var passed = true;808 for(i in identityApi){...

Full Screen

Full Screen

AppStore.js

Source:AppStore.js Github

copy

Full Screen

...19 function onComplete(items, request){20 t.assertEqual(8, items.length);21 d.callback(true);22 }23 function onError(error, request){24 d.errback(error);25 }26 store.fetch({query:{title:"*"}, onComplete: onComplete, onError: onError});27 return d; //Object28 },29 function testReadAPI_fetch_all_preventCache(t){30 // summary:31 // Simple test of fetching all items32 // description:33 // Simple test of fetching all items34 var store = dojox.data.tests.stores.AppStore.getStore(true);35 var d = new doh.Deferred();36 function onComplete(items, request){37 t.assertEqual(8, items.length);38 d.callback(true);39 }40 function onError(error, request){41 d.errback(error);42 }43 store.fetch({query:{title:"*"}, onComplete: onComplete, onError: onError});44 return d; //Object45 },46 function testReadAPI_fetch_one(t){47 // summary:48 // Simple test of fetching one item49 // description:50 // Simple test of fetching one item51 var store = dojox.data.tests.stores.AppStore.getStore();52 var d = new doh.Deferred();53 function onComplete(items, request){54 t.assertEqual(1, items.length);55 d.callback(true);56 }57 function onError(error, request){58 d.errback(error);59 }60 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});61 return d; //Object62 },63 function testReadAPI_fetch_paging(t){64 // summary:65 // Simple test of paging66 // description:67 // Simple test of paging68 var store = dojox.data.tests.stores.AppStore.getStore();69 70 var d = new doh.Deferred();71 function dumpFifthFetch(items, request){72 t.assertEqual(0, items.length);73 d.callback(true);74 }75 76 function dumpFourthFetch(items, request){77 t.assertEqual(6, items.length);78 request.start = 9;79 request.count = 100;80 request.onComplete = dumpFifthFetch;81 store.fetch(request);82 }83 function dumpThirdFetch(items, request){84 t.assertEqual(5, items.length);85 request.start = 2;86 request.count = 20;87 request.onComplete = dumpFourthFetch;88 store.fetch(request);89 }90 91 function dumpSecondFetch(items, request){92 t.assertEqual(1, items.length);93 request.start = 0;94 request.count = 5;95 request.onComplete = dumpThirdFetch;96 store.fetch(request);97 }98 function dumpFirstFetch(items, request){99 t.assertEqual(5, items.length);100 request.start = 3;101 request.count = 1;102 request.onComplete = dumpSecondFetch;103 store.fetch(request);104 }105 function completed(items, request){106 t.assertEqual(8, items.length);107 request.start = 1;108 request.count = 5;109 request.onComplete = dumpFirstFetch;110 store.fetch(request);111 }112 function error(errData, request){113 d.errback(errData);114 }115 store.fetch({onComplete: completed, onError: error});116 return d; //Object117 },118 function testReadAPI_fetch_pattern0(t){119 // summary:120 // Simple test of fetching one item with ? pattern match121 // description:122 // Simple test of fetching one item with ? pattern match123 var store = dojox.data.tests.stores.AppStore.getStore();124 var d = new doh.Deferred();125 function onComplete(items, request){126 t.assertEqual(1, items.length);127 d.callback(true);128 }129 function onError(error, request){130 d.errback(error);131 }132 store.fetch({query:{title:"?est Editable Entry #1"}, onComplete: onComplete, onError: onError});133 return d; //Object134 },135 function testReadAPI_fetch_pattern1(t){136 // summary:137 // Simple test of fetching one item with * pattern match138 // description:139 // Simple test of fetching one item with * pattern match140 var store = dojox.data.tests.stores.AppStore.getStore();141 var d = new doh.Deferred();142 function onComplete(items, request){143 t.assertEqual(8, items.length);144 d.callback(true);145 }146 function onError(error, request){147 d.errback(error);148 }149 store.fetch({query:{title:"*Test*"}, onComplete: onComplete, onError: onError});150 return d; //Object151 },152 function testReadAPI_fetch_pattern_caseInsensitive(t){153 // summary:154 // Simple test of fetching one item with * pattern match case insensitive155 // description:156 // Simple test of fetching one item with * pattern match case insensitive157 var store = dojox.data.tests.stores.AppStore.getStore();158 var d = new doh.Deferred();159 function onComplete(items, request){160 t.assertEqual(8, items.length);161 d.callback(true);162 }163 function onError(error, request){164 d.errback(error);165 }166 store.fetch({query:{title:"*test*"}, queryOptions: {ignoreCase: true}, onComplete: onComplete, onError: onError});167 return d; //Object168 },169 function testReadAPI_getLabel(t){170 // summary:171 // Simple test of the getLabel function against a store set that has a label defined.172 // description:173 // Simple test of the getLabel function against a store set that has a label defined.174 var store = dojox.data.tests.stores.AppStore.getStore();175 176 var d = new doh.Deferred();177 function onComplete(items, request){178 t.assertEqual(items.length, 1);179 var label = store.getLabel(items[0]);180 t.assertTrue(label !== null);181 t.assertEqual("Test Editable Entry #1", label);182 d.callback(true);183 }184 function onError(error, request){185 d.errback(error);186 }187 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});188 return d;189 },190 function testReadAPI_getLabelAttributes(t){191 // summary:192 // Simple test of the getLabelAttributes function against a store set that has a label defined.193 // description:194 // Simple test of the getLabelAttributes function against a store set that has a label defined.195 var store = dojox.data.tests.stores.AppStore.getStore();196 197 var d = new doh.Deferred();198 function onComplete(items, request){199 t.assertEqual(items.length, 1);200 var labelList = store.getLabelAttributes(items[0]);201 t.assertTrue(dojo.isArray(labelList));202 t.assertEqual("title", labelList[0]);203 d.callback(true);204 }205 function onError(error, request){206 d.errback(error);207 }208 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});209 return d;210 },211 function testReadAPI_getValue(t){212 // summary:213 // Simple test of the getValue API214 // description:215 // Simple test of the getValue API216 var store = dojox.data.tests.stores.AppStore.getStore();217 var d = new doh.Deferred();218 function onComplete(items, request){219 t.assertEqual(1, items.length);220 var item = items[0];221 t.assertTrue(store.hasAttribute(item,"id"));222 t.assertEqual(store.getValue(item,"id"), "http://example.com/samplefeedEdit.xml/entry/10");223 d.callback(true);224 }225 function onError(error, request){226 d.errback(error);227 }228 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});229 return d; //Object230 },231 function testReadAPI_getValues(t){232 // summary:233 // Simple test of the getValues API234 // description:235 // Simple test of the getValues API236 var store = dojox.data.tests.stores.AppStore.getStore();237 var d = new doh.Deferred();238 function onComplete(items, request){239 t.assertEqual(1, items.length);240 var item = items[0];241 t.assertTrue(store.hasAttribute(item,"id"));242 var values = store.getValues(item,"id");243 t.assertEqual(1,values.length);244 t.assertEqual(values[0], "http://example.com/samplefeedEdit.xml/entry/10");245 d.callback(true);246 }247 function onError(error, request){248 d.errback(error);249 }250 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});251 return d; //Object252 },253 function testReadAPI_isItem(t){254 // summary:255 // Simple test of the isItem API256 // description:257 // Simple test of the isItem API258 var store = dojox.data.tests.stores.AppStore.getStore();259 var d = new doh.Deferred();260 function onComplete(items, request){261 t.assertEqual(1, items.length);262 var item = items[0];263 t.assertTrue(store.isItem(item));264 t.assertTrue(!store.isItem({}));265 t.assertTrue(!store.isItem("Foo"));266 t.assertTrue(!store.isItem(1));267 d.callback(true);268 }269 function onError(error, request){270 d.errback(error);271 }272 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});273 return d; //Object274 },275 function testReadAPI_isItem_multistore(t){276 // summary:277 // Simple test of the isItem API across multiple store instances.278 // description:279 // Simple test of the isItem API across multiple store instances.280 var store1 = dojox.data.tests.stores.AppStore.getStore();281 var store2 = dojox.data.tests.stores.AppStore.getStore();282 var d = new doh.Deferred();283 function onError(error, request){284 d.errback(error);285 }286 function onComplete1(items, request){287 t.assertEqual(1, items.length);288 var item1 = items[0];289 t.assertTrue(store1.isItem(item1));290 function onComplete2(items, request){291 t.assertEqual(1, items.length);292 var item2 = items[0];293 t.assertTrue(store2.isItem(item2));294 t.assertTrue(!store1.isItem(item2));295 t.assertTrue(!store2.isItem(item1));296 d.callback(true);297 }298 store2.fetch({query:{title:"Test Entry #1"}, onComplete: onComplete2, onError: onError});299 }300 store1.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete1, onError: onError});301 return d; //Object302 },303 function testReadAPI_hasAttribute(t){304 // summary:305 // Simple test of the hasAttribute API306 // description:307 // Simple test of the hasAttribute API308 var store = dojox.data.tests.stores.AppStore.getStore();309 var d = new doh.Deferred();310 function onError(error, request){311 d.errback(error);312 }313 function onComplete(items, request){314 t.assertEqual(1, items.length);315 var item = items[0];316 t.assertTrue(store.hasAttribute(item,"title"));317 t.assertTrue(store.hasAttribute(item,"summary"));318 t.assertTrue(!store.hasAttribute(item,"bob"));319 d.callback(true);320 }321 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});322 return d; //Object323 },324 function testReadAPI_containsValue(t){325 // summary:326 // Simple test of the containsValue API327 // description:328 // Simple test of the containsValue API329 var store = dojox.data.tests.stores.AppStore.getStore();330 var d = new doh.Deferred();331 function onComplete(items, request){332 t.assertEqual(1, items.length);333 var item = items[0];334 t.assertTrue(store.containsValue(item,"title", "Test Editable Entry #1"));335 t.assertTrue(!store.containsValue(item,"title", "bob"));336 d.callback(true);337 }338 function onError(error, request){339 d.errback(error);340 }341 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});342 return d; //Object343 },344 function testReadAPI_sortDescending(t){345 // summary:346 // Simple test of the sorting API in descending order.347 // description:348 // Simple test of the sorting API in descending order.349 var store = dojox.data.tests.stores.AppStore.getStore();350 //Comparison is done as a string type (toString comparison), so the order won't be numeric351 //So have to compare in 'alphabetic' order.352 var order = [ "Test Entry #6",353 "Test Entry #5",354 "Test Entry #4",355 "Test Entry #3",356 "Test Entry #2",357 "Test Entry #1",358 "Test Editable Entry #2",359 "Test Editable Entry #1"];360 361 var d = new doh.Deferred();362 function onComplete(items, request){363 t.assertEqual(8, items.length);364 for(var i = 0; i < items.length; i++){365 t.assertEqual(order[i], store.getValue(items[i],"title"));366 }367 d.callback(true);368 }369 function onError(error, request){370 d.errback(error);371 }372 var sortAttributes = [{attribute: "title", descending: true}];373 store.fetch({query:{title:"*"}, sort: sortAttributes, onComplete: onComplete, onError: onError});374 return d; //Object375 },376 function testReadAPI_sortAscending(t){377 // summary:378 // Simple test of the sorting API in ascending order.379 // description:380 // Simple test of the sorting API in ascending order.381 var store = dojox.data.tests.stores.AppStore.getStore();382 //Comparison is done as a string type (toString comparison), so the order won't be numeric383 //So have to compare in 'alphabetic' order.384 var order = [ "Test Editable Entry #1",385 "Test Editable Entry #2",386 "Test Entry #1",387 "Test Entry #2",388 "Test Entry #3",389 "Test Entry #4",390 "Test Entry #5",391 "Test Entry #6"];392 393 var d = new doh.Deferred();394 function onComplete(items, request){395 t.assertEqual(8, items.length);396 var itemId = 1;397 for(var i = 0; i < items.length; i++){398 t.assertEqual(order[i], store.getValue(items[i],"title"));399 }400 d.callback(true);401 }402 function onError(error, request){403 d.errback(error);404 }405 var sortAttributes = [{attribute: "title"}];406 store.fetch({query:{title:"*"}, sort: sortAttributes, onComplete: onComplete, onError: onError});407 return d; //Object408 },409 function testReadAPI_isItemLoaded(t){410 // summary:411 // Simple test of the isItemLoaded API412 // description:413 // Simple test of the isItemLoaded API414 var store = dojox.data.tests.stores.AppStore.getStore();415 var d = new doh.Deferred();416 function onComplete(items, request){417 t.assertEqual(1, items.length);418 var item = items[0];419 t.assertTrue(store.isItemLoaded(item));420 d.callback(true);421 }422 function onError(error, request){423 d.errback(error);424 }425 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});426 return d; //Object427 },428 function testReadAPI_getFeatures(t){429 // summary:430 // Simple test of the getFeatures function of the store431 // description:432 // Simple test of the getFeatures function of the store433 var store = dojox.data.tests.stores.AppStore.getStore();434 var features = store.getFeatures();435 var count = 0;436 for(var i in features){437 t.assertTrue(( i === "dojo.data.api.Read" || i === "dojo.data.api.Write" || i === "dojo.data.api.Identity"));438 count++;439 }440 t.assertEqual(3, count);441 },442 function testReadAPI_getAttributes(t){443 // summary:444 // Simple test of the getAttributes API445 // description:446 // Simple test of the getAttributes API447 var store = dojox.data.tests.stores.AppStore.getStore();448 var d = new doh.Deferred();449 function onComplete(items, request){450 t.assertEqual(1, items.length);451 var item = items[0];452 var attributes = store.getAttributes(item);453 t.assertEqual(6,attributes.length);454 d.callback(true);455 }456 function onError(error, request){457 d.errback(error);458 }459 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});460 return d; //Object461 },462 function testWriteAPI_newItem(t){463 // summary:464 // Simple test of the newItem API465 // description:466 // Simple test of the newItem API467 var store = dojox.data.tests.stores.AppStore.getStore();468 store.newItem({title: "New entry", id: "12345", content: "This is test content", author: {name:"Bob"}});469 var d = new doh.Deferred();470 function onComplete(items, request){471 t.assertEqual(1, items.length);472 var item = items[0];473 t.assertTrue(store.containsValue(item,"title", "New entry"));474 t.assertTrue(store.containsValue(item, "content", "This is test content"));475 d.callback(true);476 }477 function onError(error, request) {478 d.errback(error);479 }480 store.fetch({query:{title:"New entry"}, onComplete: onComplete, onError: onError});481 return d; //Object482 },483 function testWriteAPI_newItemInCallback(t){484 // summary:485 // Simple test of the newItem API486 // description:487 // Simple test of the newItem API488 var store = dojox.data.tests.stores.AppStore.getStore();489 store.newItem({title: "New entry", id: "12345", content: "This is test content", author: {name:"Bob"}});490 var d = new doh.Deferred();491 function onError(error, request){492 d.errback(error);493 }494 function onComplete(items, request){495 t.assertEqual(1, items.length);496 var item = items[0];497 t.assertTrue(store.containsValue(item,"title", "New entry"));498 t.assertTrue(store.containsValue(item, "content", "This is test content"));499 store.newItem({title: "New entry2", id: "12346", content: "This is test content", author: [{name:"Bob"}]});500 501 function onComplete1(items, request){502 t.assertEqual(1, items.length);503 var item = items[0];504 t.assertTrue(store.containsValue(item, "title", "New entry2"));505 d.callback(true);506 }507 508 store.fetch({query:{title:"New entry2"}, onComplete: onComplete1, onError: onError});509 }510 store.fetch({query:{title:"New entry"}, onComplete: onComplete, onError: onError});511 return d; //Object512 },513 function testWriteAPI_deleteItem(t){514 // summary:515 // Simple test of the deleteItem API516 // description:517 // Simple test of the deleteItem API518 var store = dojox.data.tests.stores.AppStore.getStore();519 var d = new doh.Deferred();520 function onError(error, request){521 d.errback(error);522 }523 function onComplete(items, request){524 t.assertEqual(1, items.length);525 var item = items[0];526 t.assertTrue(store.containsValue(item,"title", "Test Editable Entry #1"));527 store.deleteItem(item);528 529 function onComplete1(items, request){530 t.assertEqual(0, items.length);531 d.callback(true);532 }533 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete1, onError: onError});534 }535 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});536 return d; //Object537 },538 function testWriteAPI_setValue(t){539 // summary:540 // Simple test of the setValue API541 // description:542 // Simple test of the setValue API543 var store = dojox.data.tests.stores.AppStore.getStore();544 var d = new doh.Deferred();545 function onComplete(items, request){546 t.assertEqual(1, items.length);547 var item = items[0];548 t.assertTrue(store.containsValue(item,"title", "Test Editable Entry #1"));549 store.setValue(item, "title", "Edited title");550 t.assertEqual(store.getValue(item,"title"), "Edited title");551 d.callback(true);552 }553 function onError(error, request){554 d.errback(error);555 }556 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});557 return d; //Object558 },559 function testWriteAPI_setValues(t){560 // summary:561 // Simple test of the setValues API562 // description:563 // Simple test of the setValues API564 var store = dojox.data.tests.stores.AppStore.getStore();565 var d = new doh.Deferred();566 function onComplete(items, request){567 t.assertEqual(1, items.length);568 var item = items[0];569 t.assertTrue(store.containsValue(item,"title", "Test Editable Entry #1"));570 store.setValues(item, "author", [{name: "John"}, {name: "Bill", email:"bill@example.com", uri:"http://example.com/bill"}]);571 var values = store.getValues(item,"author");572 t.assertEqual(values[0].name, "John");573 t.assertEqual(values[1].name, "Bill");574 t.assertEqual(values[1].email, "bill@example.com");575 t.assertEqual(values[1].uri, "http://example.com/bill");576 d.callback(true);577 }578 function onError(error, request){579 d.errback(error);580 }581 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});582 return d; //Object583 },584 function testWriteAPI_unsetAttribute(t){585 // summary:586 // Simple test of the unsetAttribute API587 // description:588 // Simple test of the unsetAttribute API589 var store = dojox.data.tests.stores.AppStore.getStore();590 var d = new doh.Deferred();591 function onComplete(items, request){592 t.assertEqual(1, items.length);593 var item = items[0];594 t.assertTrue(store.containsValue(item,"title", "Test Editable Entry #1"));595 store.unsetAttribute(item,"title");596 t.assertTrue(!store.hasAttribute(item,"title"));597 t.assertTrue(store.isDirty(item));598 d.callback(true);599 }600 function onError(error, request) {601 d.errback(error);602 }603 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});604 return d; //Object605 },606 function testWriteAPI_isDirty(t){607 // summary:608 // Simple test of the isDirty API609 // description:610 // Simple test of the isDirty API611 var store = dojox.data.tests.stores.AppStore.getStore();612 var d = new doh.Deferred();613 function onComplete(items, request){614 t.assertEqual(1, items.length);615 var item = items[0];616 t.assertTrue(store.containsValue(item,"title", "Test Editable Entry #1"));617 store.setValue(item, "title", "Edited title");618 t.assertEqual(store.getValue(item,"title"), "Edited title");619 t.assertTrue(store.isDirty(item));620 d.callback(true);621 }622 function onError(error, request){623 d.errback(error);624 }625 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});626 return d; //Object627 },628 function testWriteAPI_revert(t){629 // summary:630 // Simple test of the isDirty API631 // description:632 // Simple test of the isDirty API633 var store = dojox.data.tests.stores.AppStore.getStore();634 var d = new doh.Deferred();635 function onError(error, request){636 d.errback(error);637 }638 function onComplete(items, request){639 t.assertEqual(1, items.length);640 var item = items[0];641 t.assertTrue(store.containsValue(item,"title", "Test Editable Entry #1"));642 t.assertTrue(!store.isDirty(item));643 store.setValue(item, "title", "Edited title");644 t.assertEqual(store.getValue(item,"title"), "Edited title");645 t.assertTrue(store.isDirty(item));646 store.revert();647 648 //Fetch again to see if it reset the state.649 function onComplete1(items, request){650 t.assertEqual(1, items.length);651 var item = items[0];652 t.assertTrue(store.containsValue(item,"title", "Test Editable Entry #1"));653 d.callback(true);654 }655 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete1, onError: onError});656 }657 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});658 return d; //Object659 },660 function testWriteAPI_revert2(t){661 // summary:662 // Simple test of the revert API663 // description:664 // Simple test of the revert API665 var store = dojox.data.tests.stores.AppStore.getStore();666 var d = new doh.Deferred();667 function onError(error, request){668 d.errback(error);669 }670 function onComplete(items, request){671 t.assertEqual(1, items.length);672 var item = items[0];673 t.assertTrue(store.containsValue(item,"title", "Test Editable Entry #1"));674 store.deleteItem(item);675 676 function onComplete1(items, request){677 t.assertEqual(7, items.length);678 store.newItem({title: "New entry", id: "12345", content: "This is test content", author: {name:"Bob"}});679 680 function onComplete2(items, request){681 t.assertEqual(1, items.length);682 store.revert();683 684 function onComplete3(items, request){685 t.assertEqual(0, items.length);686 d.callback(true);687 }688 store.fetch({query:{title:"New entry"}, onComplete: onComplete3, onError: onError});689 }690 store.fetch({query:{title:"New entry"}, onComplete: onComplete2, onError: onError});691 }692 store.fetch({query:{title:"*"}, onComplete: onComplete1, onError: onError});693 }694 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});695 return d; //Object696 },697 function testReadAPI_getIdentity(t){698 // summary:699 // Simple test of fetching the identity of an item.700 // description:701 // Simple test of fetching the identity of an item.702 var store = dojox.data.tests.stores.AppStore.getStore();703 var d = new doh.Deferred();704 function onComplete(items, request){705 t.assertEqual(1, items.length);706 var id = store.getIdentity(items[0]);707 t.assertEqual("http://example.com/samplefeedEdit.xml/entry/10",id);708 d.callback(true);709 }710 function onError(error, request){711 d.errback(error);712 }713 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});714 return d; //Object715 },716 function testReadAPI_getIdentityAttributes(t){717 // summary:718 // Simple test of fetching the identity attributes off an item,719 // description:720 // Simple test of fetching the identity attributes off an item,721 var store = dojox.data.tests.stores.AppStore.getStore();722 var d = new doh.Deferred();723 function onComplete(items, request){724 t.assertEqual(1, items.length);725 var idAttrs = store.getIdentityAttributes(items[0]);726 t.assertEqual(1, idAttrs.length);727 t.assertEqual("id", idAttrs[0]);728 d.callback(true);729 }730 function onError(error, request){731 d.errback(error);732 }733 store.fetch({query:{title:"Test Editable Entry #1"}, onComplete: onComplete, onError: onError});734 return d; //Object735 },736 function testReadAPI_fetchItemByIdentity(t){737 // summary:738 // Simple test of fetching one atom item through its identity739 // description:740 // Simple test of fetching one atom item through its identity741 var store = dojox.data.tests.stores.AppStore.getStore();742 var d = new doh.Deferred();743 function onItem(item, request) {744 var id = store.getIdentity(item);745 t.assertEqual("http://example.com/samplefeedEdit.xml/entry/10",id);746 d.callback(true);747 }748 function onError(error, request){749 d.errback(error);750 }751 store.fetchItemByIdentity({identity: "http://example.com/samplefeedEdit.xml/entry/10", onItem: onItem, onError: onError});752 return d; //Object753 },754 function testReadAPI_fetchItemByIdentity_fails(t){755 // summary:756 // Simple test of fetching one atom item through its identity fails correctly on no id match757 // description:758 // Simple test of fetching one atom item through its identity fails correctly on no id match759 var store = dojox.data.tests.stores.AppStore.getStore();760 var d = new doh.Deferred();761 function onItem(item, request){762 t.assertTrue(item === null);763 d.callback(true);764 }765 function onError(error, request){766 d.errback(error);767 }768 store.fetchItemByIdentity({identity: "http://example.com/samplefeedEdit.xml/entry/10/none", onItem: onItem, onError: onError});769 return d; //Object770 },771 function testReadAPI_functionConformance(t){772 // summary:773 // Simple test read API conformance. Checks to see all declared functions are actual functions on the instances.774 // description:775 // Simple test read API conformance. Checks to see all declared functions are actual functions on the instances.776 var testStore = dojox.data.tests.stores.AppStore.getStore();777 var readApi = new dojo.data.api.Read();778 var passed = true;779 for(var i in readApi){...

Full Screen

Full Screen

host_native_messaging.js

Source:host_native_messaging.js Github

copy

Full Screen

...56 */57remoting.HostNativeMessaging.prototype.initialize = function(onDone, onError) {58 if (!chrome.runtime.connectNative) {59 console.log('Native Messaging API not available');60 onError(remoting.Error.UNEXPECTED);61 return;62 }63 // NativeMessaging API exists on Chrome 26.xxx but fails to notify64 // onDisconnect in the case where the Host components are not installed. Need65 // to blacklist these versions of Chrome.66 var majorVersion = navigator.appVersion.match('Chrome/(\\d+)\.')[1];67 if (!majorVersion || majorVersion <= 26) {68 console.log('Native Messaging not supported on this version of Chrome');69 onError(remoting.Error.UNEXPECTED);70 return;71 }72 try {73 this.port_ = chrome.runtime.connectNative(74 'com.google.chrome.remote_desktop');75 this.port_.onMessage.addListener(this.onIncomingMessage_.bind(this));76 this.port_.onDisconnect.addListener(this.onDisconnect_.bind(this));77 this.postMessage_({type: 'hello'}, onDone,78 onError.bind(null, remoting.Error.UNEXPECTED));79 } catch (err) {80 console.log('Native Messaging initialization failed: ',81 /** @type {*} */ (err));82 onError(remoting.Error.UNEXPECTED);83 return;84 }85};86/**87 * Verifies that |object| is of type |type|, logging an error if not.88 *89 * @param {string} name Name of the object, to be included in the error log.90 * @param {*} object Object to test.91 * @param {string} type Expected type of the object.92 * @return {boolean} Result of test.93 */94function checkType_(name, object, type) {95 if (typeof(object) !== type) {96 console.error('NativeMessaging: "' + name + '" expected to be of type "' +97 type + '", got: ' + object);98 return false;99 }100 return true;101}102/**103 * Returns |result| as an AsyncResult. If |result| is not valid, returns null104 * and logs an error.105 *106 * @param {*} result107 * @return {remoting.HostController.AsyncResult?} Converted result.108 */109function asAsyncResult_(result) {110 if (!checkType_('result', result, 'string')) {111 return null;112 }113 if (!remoting.HostController.AsyncResult.hasOwnProperty(result)) {114 console.error('NativeMessaging: unexpected result code: ', result);115 return null;116 }117 return remoting.HostController.AsyncResult[result];118}119/**120 * Returns |result| as a HostController.State. If |result| is not valid,121 * returns null and logs an error.122 *123 * @param {*} result124 * @return {remoting.HostController.State?} Converted result.125 */126function asHostState_(result) {127 if (!checkType_('result', result, 'string')) {128 return null;129 }130 if (!remoting.HostController.State.hasOwnProperty(result)) {131 console.error('NativeMessaging: unexpected result code: ', result);132 return null;133 }134 return remoting.HostController.State[result];135}136/**137 * @param {remoting.HostController.Feature} feature The feature to test for.138 * @return {boolean} True if the implementation supports the named feature.139 */140remoting.HostNativeMessaging.prototype.hasFeature = function(feature) {141 return this.supportedFeatures_.indexOf(feature) >= 0;142};143/**144 * Attaches a new ID to the supplied message, and posts it to the Native145 * Messaging port, adding |onDone| to the list of pending replies.146 * |message| should have its 'type' field set, and any other fields set147 * depending on the message type.148 *149 * @param {{type: string}} message The message to post.150 * @param {?function(...):void} onDone The callback, if any, to be triggered151 * on response.152 * @param {function(remoting.Error):void} onError The callback to be triggered153 * on error.154 * @return {void} Nothing.155 * @private156 */157remoting.HostNativeMessaging.prototype.postMessage_ =158 function(message, onDone, onError) {159 var id = this.nextId_++;160 message['id'] = id;161 this.pendingReplies_[id] = new remoting.HostNativeMessaging.PendingReply(162 message.type + 'Response', onDone, onError);163 this.port_.postMessage(message);164};165/**166 * Handler for incoming Native Messages.167 *168 * @param {Object} message The received message.169 * @return {void} Nothing.170 * @private171 */172remoting.HostNativeMessaging.prototype.onIncomingMessage_ = function(message) {173 /** @type {number} */174 var id = message['id'];175 if (typeof(id) != 'number') {176 console.error('NativeMessaging: missing or non-numeric id');177 return;178 }179 var reply = this.pendingReplies_[id];180 if (!reply) {181 console.error('NativeMessaging: unexpected id: ', id);182 return;183 }184 delete this.pendingReplies_[id];185 var onDone = reply.onDone;186 var onError = reply.onError;187 /** @type {string} */188 var type = message['type'];189 if (!checkType_('type', type, 'string')) {190 onError(remoting.Error.UNEXPECTED);191 return;192 }193 if (type != reply.type) {194 console.error('NativeMessaging: expected reply type: ', reply.type,195 ', got: ', type);196 onError(remoting.Error.UNEXPECTED);197 return;198 }199 switch (type) {200 case 'helloResponse':201 /** @type {string} */202 var version = message['version'];203 if (checkType_('version', version, 'string')) {204 this.version_ = version;205 if (message['supportedFeatures'] instanceof Array) {206 this.supportedFeatures_ = message['supportedFeatures'];207 } else {208 // Old versions of the native messaging host do not return this list.209 // Those versions don't support any new feature.210 this.supportedFeatures_ = [];211 }212 onDone();213 } else {214 onError(remoting.Error.UNEXPECTED);215 }216 break;217 case 'getHostNameResponse':218 /** @type {*} */219 var hostname = message['hostname'];220 if (checkType_('hostname', hostname, 'string')) {221 onDone(hostname);222 } else {223 onError(remoting.Error.UNEXPECTED);224 }225 break;226 case 'getPinHashResponse':227 /** @type {*} */228 var hash = message['hash'];229 if (checkType_('hash', hash, 'string')) {230 onDone(hash);231 } else {232 onError(remoting.Error.UNEXPECTED);233 }234 break;235 case 'generateKeyPairResponse':236 /** @type {*} */237 var privateKey = message['privateKey'];238 /** @type {*} */239 var publicKey = message['publicKey'];240 if (checkType_('privateKey', privateKey, 'string') &&241 checkType_('publicKey', publicKey, 'string')) {242 onDone(privateKey, publicKey);243 } else {244 onError(remoting.Error.UNEXPECTED);245 }246 break;247 case 'updateDaemonConfigResponse':248 var result = asAsyncResult_(message['result']);249 if (result != null) {250 onDone(result);251 } else {252 onError(remoting.Error.UNEXPECTED);253 }254 break;255 case 'getDaemonConfigResponse':256 /** @type {*} */257 var config = message['config'];258 if (checkType_('config', config, 'object')) {259 onDone(config);260 } else {261 onError(remoting.Error.UNEXPECTED);262 }263 break;264 case 'getUsageStatsConsentResponse':265 /** @type {*} */266 var supported = message['supported'];267 /** @type {*} */268 var allowed = message['allowed'];269 /** @type {*} */270 var setByPolicy = message['setByPolicy'];271 if (checkType_('supported', supported, 'boolean') &&272 checkType_('allowed', allowed, 'boolean') &&273 checkType_('setByPolicy', setByPolicy, 'boolean')) {274 onDone(supported, allowed, setByPolicy);275 } else {276 onError(remoting.Error.UNEXPECTED);277 }278 break;279 case 'startDaemonResponse':280 case 'stopDaemonResponse':281 var result = asAsyncResult_(message['result']);282 if (result != null) {283 onDone(result);284 } else {285 onError(remoting.Error.UNEXPECTED);286 }287 break;288 case 'getDaemonStateResponse':289 var state = asHostState_(message['state']);290 if (state != null) {291 onDone(state);292 } else {293 onError(remoting.Error.UNEXPECTED);294 }295 break;296 case 'getPairedClientsResponse':297 var pairedClients = remoting.PairedClient.convertToPairedClientArray(298 message['pairedClients']);299 if (pairedClients != null) {300 onDone(pairedClients);301 } else {302 onError(remoting.Error.UNEXPECTED);303 }304 break;305 case 'clearPairedClientsResponse':306 case 'deletePairedClientResponse':307 /** @type {boolean} */308 var success = message['result'];309 if (checkType_('success', success, 'boolean')) {310 onDone(success);311 } else {312 onError(remoting.Error.UNEXPECTED);313 }314 break;315 default:316 console.error('Unexpected native message: ', message);317 onError(remoting.Error.UNEXPECTED);318 }319};320/**321 * @return {void} Nothing.322 * @private323 */324remoting.HostNativeMessaging.prototype.onDisconnect_ = function() {325 console.error('Native Message port disconnected');326 // Notify the error-handlers of any requests that are still outstanding.327 for (var id in this.pendingReplies_) {328 this.pendingReplies_[/** @type {number} */(id)].onError(329 remoting.Error.UNEXPECTED);330 }331 this.pendingReplies_ = {};332}333/**334 * @param {function(string):void} onDone Callback to be called with the335 * local hostname.336 * @param {function(remoting.Error):void} onError The callback to be triggered337 * on error.338 * @return {void} Nothing.339 */340remoting.HostNativeMessaging.prototype.getHostName =341 function(onDone, onError) {342 this.postMessage_({type: 'getHostName'}, onDone, onError);...

Full Screen

Full Screen

Redis.js

Source:Redis.js Github

copy

Full Screen

...9});10exports._handleBlockingPopResult = function(onError, onSuccess) {11 return function(err, val) {12 if (err !== null) {13 onError(err);14 return;15 }16 if(val !== null) {17 var key = val[0], value = val[1];18 onSuccess({key: key, value: value});19 return;20 }21 onSuccess(null);22 };23};24exports.blpopImpl = function(conn) {25 return function(keys) {26 return function(timeout) {27 return function(onError, onSuccess) {28 var handler = exports._handleBlockingPopResult(onError, onSuccess);29 conn.blpopBuffer.apply(conn, [keys, timeout, handler]);30 return function(cancelError, cancelerError, cancelerSuccess) {31 cancelError();32 };33 };34 };35 };36};37exports.brpopImpl = function(conn) {38 return function(keys) {39 return function(timeout) {40 return function(onError, onSuccess) {41 var handler = exports._handleBlockingPopResult(onError, onSuccess);42 conn.brpopBuffer.apply(conn, [keys, timeout, handler]);43 return function(cancelError, cancelerError, cancelerSuccess) {44 cancelError();45 };46 };47 };48 };49};50exports.connectImpl = function(connstr) {51 return function(onError, onSuccess) {52 var redis = new ioredis(connstr);53 redis.connect(function() {54 onSuccess(redis);55 });56 return function(cancelError, cancelerError, cancelerSuccess) {57 cancelError();58 };59 };60};61exports.disconnectImpl = function(conn) {62 return function(onError, onSuccess) {63 conn.disconnect();64 onSuccess();65 return function(cancelError, cancelerError, cancelerSuccess) {66 cancelError();67 };68 };69};70exports.delImpl = function(conn) {71 return function(keys) {72 return function(onError, onSuccess) {73 if (keys.length === 0) {74 onSuccess();75 } else {76 conn.del.apply(conn, keys.concat([function(err) {77 if (err !== null) {78 onError(err);79 return;80 }81 onSuccess();82 }]));83 }84 return function(cancelError, cancelerError, cancelerSuccess) {85 cancelError();86 };87 };88 };89};90exports.flushdbImpl = function(conn) {91 return function(onError, onSuccess) {92 conn.flushdb();93 onSuccess();94 return function(cancelError, cancelerError, cancelerSuccess) {95 cancelError();96 };97 };98};99exports.getImpl = function(conn) {100 return function(key) {101 return function(onError, onSuccess) {102 conn.getBuffer(key, function(err, value) {103 if (err !== null) {104 onError(err);105 return;106 }107 onSuccess(value);108 });109 return function(cancelError, cancelerError, cancelerSuccess) {110 cancelError();111 };112 };113 };114};115exports.hgetallImpl = function(conn) {116 return function(key) {117 return function(onError, onSuccess) {118 conn.hgetallBuffer(key, function(err, value) {119 if (err !== null) {120 onError(err);121 return;122 }123 onSuccess(value);124 });125 return function(cancelError, cancelerError, cancelerSuccess) {126 cancelError();127 };128 };129 };130};131exports.hgetImpl = function(conn) {132 return function(key) {133 return function(field) {134 return function(onError, onSuccess) {135 conn.hgetBuffer(key, field, function(err, value) {136 if (err !== null) {137 onError(err);138 return;139 }140 onSuccess(value);141 });142 return function(cancelError, cancelerError, cancelerSuccess) {143 cancelError();144 };145 };146 };147 };148};149exports.hsetImpl = function(conn) {150 return function(key) {151 return function(field) {152 return function(value) {153 return function(onError, onSuccess) {154 conn.hsetBuffer(key, field, value, function(err, value) {155 if (err !== null) {156 onError(err);157 return;158 }159 onSuccess(parseInt(value));160 });161 return function(cancelError, cancelerError, cancelerSuccess) {162 cancelError();163 };164 };165 };166 };167 };168};169exports.incrImpl = function(conn) {170 return function(key) {171 return function(onError, onSuccess) {172 conn.incr(key, function(err, value) {173 if (err !== null) {174 onError(err);175 return;176 }177 onSuccess(value);178 });179 return function(cancelError, cancelerError, cancelerSuccess) {180 cancelError();181 };182 };183 };184};185exports.keysImpl = function(conn) {186 return function(pattern) {187 return function(onError, onSuccess) {188 conn.keysBuffer(pattern, function(err, value) {189 if (err !== null) {190 onError(err);191 return;192 }193 onSuccess(value);194 });195 return function(cancelError, cancelerError, cancelerSuccess) {196 cancelError();197 };198 };199 };200};201exports.lpopImpl = function(conn) {202 return function(key) {203 return function(onError, onSuccess) {204 var handler = exports._plainValueHandler(onError, onSuccess);205 conn.lpopBuffer.apply(conn, [key, handler]);206 return function(cancelError, cancelerError, cancelerSuccess) {207 cancelError();208 };209 };210 };211};212exports.lpushImpl = function(conn) {213 return function(key) {214 return function(value) {215 return function(onError, onSuccess) {216 var handler = exports._intHandler(onError, onSuccess, false);217 conn.lpushBuffer.apply(conn, [key, value, handler]);218 return function(cancelError, cancelerError, cancelerSuccess) {219 cancelError();220 };221 };222 };223 };224};225exports.rpopImpl = function(conn) {226 return function(key) {227 return function(onError, onSuccess) {228 var handler = exports._plainValueHandler(onError, onSuccess);229 conn.rpopBuffer.apply(conn, [key, handler]);230 return function(cancelError, cancelerError, cancelerSuccess) {231 cancelError();232 };233 };234 };235};236exports.rpushImpl = function(conn) {237 return function(key) {238 return function(value) {239 return function(onError, onSuccess) {240 var handler = exports._intHandler(onError, onSuccess, false);241 conn.rpushBuffer.apply(conn, [key, value, handler]);242 return function(cancelError, cancelerError, cancelerSuccess) {243 cancelError();244 };245 };246 };247 };248};249exports.lrangeImpl = function(conn) {250 return function(key) {251 return function(start) {252 return function(end) {253 return function(onError, onSuccess) {254 var handler = exports._plainValueHandler(onError, onSuccess);255 conn.lrangeBuffer.apply(conn, [key, start, end, handler]);256 return function(cancelError, cancelerError, cancelerSuccess) {257 cancelError();258 };259 };260 };261 };262 };263};264exports._plainValueHandler = function(onError, onSuccess) {265 return function(err, val) {266 if (err !== null) {267 onError(err);268 return;269 }270 onSuccess(val);271 };272};273exports._nullValueHandler = function(onError, onSuccess) {274 return function(err, val) {275 if (err !== null) {276 onError(err);277 return;278 }279 onSuccess(null);280 };281};282exports.ltrimImpl = function(conn) {283 return function(key) {284 return function(start) {285 return function(end) {286 return function(onError, onSuccess) {287 var handler = exports._nullValueHandler(onError, onSuccess);288 conn.ltrimBuffer.apply(conn, [key, start, end, handler]);289 return function(cancelError, cancelerError, cancelerSuccess) {290 cancelError();291 };292 };293 };294 };295 };296};297exports.mgetImpl = function(conn) {298 return function(keys) {299 return function(onError, onSuccess) {300 conn.mgetBuffer(keys, function(err, value) {301 if (err !== null) {302 onError(err);303 return;304 }305 onSuccess(value);306 });307 return function(cancelError, cancelerError, cancelerSuccess) {308 cancelError();309 };310 };311 };312};313exports.setImpl = function(conn) {314 return function(key) {315 return function(value) {316 return function(expire) {317 return function(write) {318 return function(onError, onSuccess) {319 var handler = function(err) {320 if (err !== null) {321 onError(err);322 return;323 }324 onSuccess();325 };326 var args = [key, value];327 if(expire !== null) {328 args.push(expire.unit);329 args.push(expire.value);330 }331 if(write !== null) {332 args.push(write);333 }334 args.push(handler);335 conn.set.apply(conn, args);336 return function(cancelError, cancelerError, cancelerSuccess) {337 cancelError();338 };339 };340 };341 };342 };343 };344};345exports.zaddImpl = function(conn) {346 return function(key) {347 return function(writeMode) {348 return function(returnMode) {349 return function(members) {350 return function(onError, onSuccess) {351 var args = [key];352 if(writeMode !== null) {353 args.push(writeMode);354 }355 if(returnMode !== null) {356 args.push(returnMode);357 }358 members.forEach(function(i) {359 args.push(i.score);360 args.push(i.member);361 });362 var handler = function(err, val) {363 if (err !== null) {364 onError(err);365 return;366 }367 onSuccess(val);368 };369 args.push(handler);370 conn.zaddBuffer.apply(conn, args);371 return function(cancelError, cancelerError, cancelerSuccess) {372 cancelError();373 };374 };375 };376 };377 };378 };379};380exports.zcardImpl = function(conn) {381 return function(key) {382 return function(onError, onSuccess) {383 conn.zcardBuffer.apply(conn, [key, exports._intHandler(onError, onSuccess, false)]);384 return function(cancelError, cancelerError, cancelerSuccess) {385 cancelError();386 };387 };388 };389};390exports.zincrbyImpl = function(conn) {391 return function(key) {392 return function(increment) {393 return function(member) {394 return function(onError, onSuccess) {395 var handler = function(err, val) {396 if (err !== null) {397 onError(err);398 return;399 }400 onSuccess(parseFloat(val));401 };402 conn.zincrbyBuffer.apply(conn, [key, increment, member, handler]);403 return function(cancelError, cancelerError, cancelerSuccess) {404 cancelError();405 };406 };407 };408 };409 };410};411exports._intHandler = function(onError, onSuccess, nullable) {412 return function(err, val) {413 if (err !== null) {414 onError(err);415 return;416 }417 if(nullable && val === null) {418 onSuccess(null);419 } else {420 onSuccess(parseInt(val));421 }422 return;423 };424};425exports._sortedSetItemsHanlder = function(onError, onSuccess) {426 return function(err, val) {427 var curr = {}, result = [];428 if (err !== null) {429 onError(err);430 return;431 }432 val.forEach(function(i) {433 if(curr.member === undefined) {434 curr.member = i;435 } else {436 // XXX: I'm not sure if this is safe parsing437 curr.score = parseFloat(i);438 result.push(curr);439 curr = {};440 }441 });442 onSuccess(result);443 };444};445exports.zrangeImpl = function(conn) {446 return function(key) {447 return function(start) {448 return function(stop) {449 return function(onError, onSuccess) {450 var handler = exports._sortedSetItemsHanlder(onError, onSuccess);451 conn.zrangeBuffer.apply(conn, [key, start, stop, 'WITHSCORES', handler]);452 return function(cancelError, cancelerError, cancelerSuccess) {453 cancelError();454 };455 };456 };457 };458 };459};460exports.zrangebyscoreImpl = function(conn) {461 return function(key) {462 return function(min) {463 return function(max) {464 return function(limit) {465 return function(onError, onSuccess) {466 var handler = exports._sortedSetItemsHanlder(onError, onSuccess),467 args =[key, min, max, 'WITHSCORES'];468 if(limit !== null) {469 args.push('LIMIT');470 args.push(limit.offset);471 args.push(limit.count);472 }473 args.push(handler);474 conn.zrangebyscoreBuffer.apply(conn, args);475 };476 };477 };478 };479 };480};481exports.zrankImpl = function(conn) {482 return function(key) {483 return function(member) {484 return function(onError, onSuccess) {485 conn.zrankBuffer.apply(conn, [key, member, exports._intHandler(onError, onSuccess, true)]);486 return function(cancelError, cancelerError, cancelerSuccess) {487 cancelError();488 };489 };490 };491 };492};493exports.zremImpl = function(conn) {494 return function(key) {495 return function(members) {496 return function(onError, onSuccess) {497 conn.zremBuffer.apply(conn, [key, members, exports._intHandler(onError, onSuccess, false)]);498 return function(cancelError, cancelerError, cancelerSuccess) {499 cancelError();500 };501 };502 };503 };504};505exports.zremrangebylexImpl = function(conn) {506 return function(key) {507 return function(min) {508 return function(max) {509 return function(onError, onSuccess) {510 conn.zremrangebylexBuffer.apply(conn, [key, min, max, exports._intHandler(onError, onSuccess, false)]);511 return function(cancelError, cancelerError, cancelerSuccess) {512 cancelError();513 };514 };515 };516 };517 };518};519exports.zremrangebyrankImpl = function(conn) {520 return function(key) {521 return function(start) {522 return function(stop) {523 return function(onError, onSuccess) {524 conn.zremrangebyrankBuffer.apply(conn, [key, start, stop, exports._intHandler(onError, onSuccess, false)]);525 return function(cancelError, cancelerError, cancelerSuccess) {526 cancelError();527 };528 };529 };530 };531 };532};533exports.zremrangebyscoreImpl = function(conn) {534 return function(key) {535 return function(min) {536 return function(max) {537 return function(onError, onSuccess) {538 conn.zremrangebyscoreBuffer.apply(conn, [key, min, max, exports._intHandler(onError, onSuccess, false)]);539 return function(cancelError, cancelerError, cancelerSuccess) {540 cancelError();541 };542 };543 };544 };545 };546};547exports.zrevrangebyscoreImpl = function(conn) {548 return function(key) {549 return function(min) {550 return function(max) {551 return function(limit) {552 return function(onError, onSuccess) {553 var handler = exports._sortedSetItemsHanlder(onError, onSuccess),554 args =[key, min, max, 'WITHSCORES'];555 if(limit !== null) {556 args.push('LIMIT');557 args.push(limit.offset);558 args.push(limit.count);559 }560 args.push(handler);561 conn.zrevrangebyscoreBuffer.apply(conn, args);562 };563 };564 };565 };566 };567};568exports.zscoreImpl = function(conn) {569 return function(key) {570 return function(member) {571 return function(onError, onSuccess) {572 var handler = function(err, val) {573 if (err !== null) {574 onError(err);575 return;576 }577 if(val !== null) {578 onSuccess(parseFloat(val));579 } else {580 onSuccess(val);581 }582 };583 conn.zscoreBuffer.apply(conn, [key, member, handler]);584 };585 };586 };...

Full Screen

Full Screen

zip-fs.js

Source:zip-fs.js Github

copy

Full Screen

1/*2 Copyright (c) 2013 Gildas Lormeau. All rights reserved.3 Redistribution and use in source and binary forms, with or without4 modification, are permitted provided that the following conditions are met:5 1. Redistributions of source code must retain the above copyright notice,6 this list of conditions and the following disclaimer.7 2. Redistributions in binary form must reproduce the above copyright 8 notice, this list of conditions and the following disclaimer in 9 the documentation and/or other materials provided with the distribution.10 3. The names of the authors may not be used to endorse or promote products11 derived from this software without specific prior written permission.12 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,13 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND14 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,15 INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,16 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT17 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,18 OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF19 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING20 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,21 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.22 */23(function() {24 "use strict";25 var CHUNK_SIZE = 512 * 1024;26 var TextWriter = zip.TextWriter, //27 BlobWriter = zip.BlobWriter, //28 Data64URIWriter = zip.Data64URIWriter, //29 Reader = zip.Reader, //30 TextReader = zip.TextReader, //31 BlobReader = zip.BlobReader, //32 Data64URIReader = zip.Data64URIReader, //33 createReader = zip.createReader, //34 createWriter = zip.createWriter;35 function ZipBlobReader(entry) {36 var that = this, blobReader;37 function init(callback) {38 that.size = entry.uncompressedSize;39 callback();40 }41 function getData(callback) {42 if (that.data)43 callback();44 else45 entry.getData(new BlobWriter(), function(data) {46 that.data = data;47 blobReader = new BlobReader(data);48 callback();49 }, null, that.checkCrc32);50 }51 function readUint8Array(index, length, callback, onerror) {52 getData(function() {53 blobReader.readUint8Array(index, length, callback, onerror);54 }, onerror);55 }56 that.size = 0;57 that.init = init;58 that.readUint8Array = readUint8Array;59 }60 ZipBlobReader.prototype = new Reader();61 ZipBlobReader.prototype.constructor = ZipBlobReader;62 ZipBlobReader.prototype.checkCrc32 = false;63 function getTotalSize(entry) {64 var size = 0;65 function process(entry) {66 size += entry.uncompressedSize || 0;67 entry.children.forEach(process);68 }69 process(entry);70 return size;71 }72 function initReaders(entry, onend, onerror) {73 var index = 0;74 function next() {75 index++;76 if (index < entry.children.length)77 process(entry.children[index]);78 else79 onend();80 }81 function process(child) {82 if (child.directory)83 initReaders(child, next, onerror);84 else {85 child.reader = new child.Reader(child.data, onerror);86 child.reader.init(function() {87 child.uncompressedSize = child.reader.size;88 next();89 });90 }91 }92 if (entry.children.length)93 process(entry.children[index]);94 else95 onend();96 }97 function detach(entry) {98 var children = entry.parent.children;99 children.forEach(function(child, index) {100 if (child.id == entry.id)101 children.splice(index, 1);102 });103 }104 function exportZip(zipWriter, entry, onend, onprogress, totalSize) {105 var currentIndex = 0;106 function process(zipWriter, entry, onend, onprogress, totalSize) {107 var childIndex = 0;108 function exportChild() {109 var child = entry.children[childIndex];110 if (child)111 zipWriter.add(child.getFullname(), child.reader, function() {112 currentIndex += child.uncompressedSize || 0;113 process(zipWriter, child, function() {114 childIndex++;115 exportChild();116 }, onprogress, totalSize);117 }, function(index) {118 if (onprogress)119 onprogress(currentIndex + index, totalSize);120 }, {121 directory : child.directory,122 version : child.zipVersion123 });124 else125 onend();126 }127 exportChild();128 }129 process(zipWriter, entry, onend, onprogress, totalSize);130 }131 function addFileEntry(zipEntry, fileEntry, onend, onerror) {132 function getChildren(fileEntry, callback) {133 var entries = [];134 if (fileEntry.isDirectory) {135 var directoryReader = fileEntry.createReader();136 (function readEntries() {137 directoryReader.readEntries(function(temporaryEntries) {138 if (!temporaryEntries.length)139 callback(entries);140 else {141 entries = entries.concat(temporaryEntries);142 readEntries();143 }144 }, onerror);145 })();146 }147 if (fileEntry.isFile)148 callback(entries);149 }150 function process(zipEntry, fileEntry, onend) {151 getChildren(fileEntry, function(children) {152 var childIndex = 0;153 function addChild(child) {154 function nextChild(childFileEntry) {155 process(childFileEntry, child, function() {156 childIndex++;157 processChild();158 });159 }160 if (child.isDirectory)161 nextChild(zipEntry.addDirectory(child.name));162 if (child.isFile)163 child.file(function(file) {164 var childZipEntry = zipEntry.addBlob(child.name, file);165 childZipEntry.uncompressedSize = file.size;166 nextChild(childZipEntry);167 }, onerror);168 }169 function processChild() {170 var child = children[childIndex];171 if (child)172 addChild(child);173 else174 onend();175 }176 processChild();177 });178 }179 if (fileEntry.isDirectory)180 process(zipEntry, fileEntry, onend);181 else182 fileEntry.file(function(file) {183 zipEntry.addBlob(fileEntry.name, file);184 onend();185 }, onerror);186 }187 function getFileEntry(fileEntry, entry, onend, onprogress, onerror, totalSize, checkCrc32) {188 var currentIndex = 0;189 function process(fileEntry, entry, onend, onprogress, onerror, totalSize) {190 var childIndex = 0;191 function addChild(child) {192 function nextChild(childFileEntry) {193 currentIndex += child.uncompressedSize || 0;194 process(childFileEntry, child, function() {195 childIndex++;196 processChild();197 }, onprogress, onerror, totalSize);198 }199 if (child.directory)200 fileEntry.getDirectory(child.name, {201 create : true202 }, nextChild, onerror);203 else204 fileEntry.getFile(child.name, {205 create : true206 }, function(file) {207 child.getData(new zip.FileWriter(file, zip.getMimeType(child.name)), nextChild, function(index) {208 if (onprogress)209 onprogress(currentIndex + index, totalSize);210 }, checkCrc32);211 }, onerror);212 }213 function processChild() {214 var child = entry.children[childIndex];215 if (child)216 addChild(child);217 else218 onend();219 }220 processChild();221 }222 if (entry.directory)223 process(fileEntry, entry, onend, onprogress, onerror, totalSize);224 else225 entry.getData(new zip.FileWriter(fileEntry, zip.getMimeType(entry.name)), onend, onprogress, checkCrc32);226 }227 function resetFS(fs) {228 fs.entries = [];229 fs.root = new ZipDirectoryEntry(fs);230 }231 function bufferedCopy(reader, writer, onend, onprogress, onerror) {232 var chunkIndex = 0;233 function stepCopy() {234 var index = chunkIndex * CHUNK_SIZE;235 if (onprogress)236 onprogress(index, reader.size);237 if (index < reader.size)238 reader.readUint8Array(index, Math.min(CHUNK_SIZE, reader.size - index), function(array) {239 writer.writeUint8Array(new Uint8Array(array), function() {240 chunkIndex++;241 stepCopy();242 });243 }, onerror);244 else245 writer.getData(onend);246 }247 stepCopy();248 }249 function addChild(parent, name, params, directory) {250 if (parent.directory)251 return directory ? new ZipDirectoryEntry(parent.fs, name, params, parent) : new ZipFileEntry(parent.fs, name, params, parent);252 else253 throw "Parent entry is not a directory.";254 }255 function ZipEntry() {256 }257 ZipEntry.prototype = {258 init : function(fs, name, params, parent) {259 var that = this;260 if (fs.root && parent && parent.getChildByName(name))261 throw "Entry filename already exists.";262 if (!params)263 params = {};264 that.fs = fs;265 that.name = name;266 that.id = fs.entries.length;267 that.parent = parent;268 that.children = [];269 that.zipVersion = params.zipVersion || 0x14;270 that.uncompressedSize = 0;271 fs.entries.push(that);272 if (parent)273 that.parent.children.push(that);274 },275 getFileEntry : function(fileEntry, onend, onprogress, onerror, checkCrc32) {276 var that = this;277 initReaders(that, function() {278 getFileEntry(fileEntry, that, onend, onprogress, onerror, getTotalSize(that), checkCrc32);279 }, onerror);280 },281 moveTo : function(target) {282 var that = this;283 if (target.directory) {284 if (!target.isDescendantOf(that)) {285 if (that != target) {286 if (target.getChildByName(that.name))287 throw "Entry filename already exists.";288 detach(that);289 that.parent = target;290 target.children.push(that);291 }292 } else293 throw "Entry is a ancestor of target entry.";294 } else295 throw "Target entry is not a directory.";296 },297 getFullname : function() {298 var that = this, fullname = that.name, entry = that.parent;299 while (entry) {300 fullname = (entry.name ? entry.name + "/" : "") + fullname;301 entry = entry.parent;302 }303 return fullname;304 },305 isDescendantOf : function(ancestor) {306 var entry = this.parent;307 while (entry && entry.id != ancestor.id)308 entry = entry.parent;309 return !!entry;310 }311 };312 ZipEntry.prototype.constructor = ZipEntry;313 var ZipFileEntryProto;314 function ZipFileEntry(fs, name, params, parent) {315 var that = this;316 ZipEntry.prototype.init.call(that, fs, name, params, parent);317 that.Reader = params.Reader;318 that.Writer = params.Writer;319 that.data = params.data;320 if (params.getData) {321 that.getData = params.getData;322 }323 }324 ZipFileEntry.prototype = ZipFileEntryProto = new ZipEntry();325 ZipFileEntryProto.constructor = ZipFileEntry;326 ZipFileEntryProto.getData = function(writer, onend, onprogress, onerror) {327 var that = this;328 if (!writer || (writer.constructor == that.Writer && that.data))329 onend(that.data);330 else {331 if (!that.reader)332 that.reader = new that.Reader(that.data, onerror);333 that.reader.init(function() {334 writer.init(function() {335 bufferedCopy(that.reader, writer, onend, onprogress, onerror);336 }, onerror);337 });338 }339 };340 ZipFileEntryProto.getText = function(onend, onprogress, checkCrc32, encoding) {341 this.getData(new TextWriter(encoding), onend, onprogress, checkCrc32);342 };343 ZipFileEntryProto.getBlob = function(mimeType, onend, onprogress, checkCrc32) {344 this.getData(new BlobWriter(mimeType), onend, onprogress, checkCrc32);345 };346 ZipFileEntryProto.getData64URI = function(mimeType, onend, onprogress, checkCrc32) {347 this.getData(new Data64URIWriter(mimeType), onend, onprogress, checkCrc32);348 };349 var ZipDirectoryEntryProto;350 function ZipDirectoryEntry(fs, name, params, parent) {351 var that = this;352 ZipEntry.prototype.init.call(that, fs, name, params, parent);353 that.directory = true;354 }355 ZipDirectoryEntry.prototype = ZipDirectoryEntryProto = new ZipEntry();356 ZipDirectoryEntryProto.constructor = ZipDirectoryEntry;357 ZipDirectoryEntryProto.addDirectory = function(name) {358 return addChild(this, name, null, true);359 };360 ZipDirectoryEntryProto.addText = function(name, text) {361 return addChild(this, name, {362 data : text,363 Reader : TextReader,364 Writer : TextWriter365 });366 };367 ZipDirectoryEntryProto.addBlob = function(name, blob) {368 return addChild(this, name, {369 data : blob,370 Reader : BlobReader,371 Writer : BlobWriter372 });373 };374 ZipDirectoryEntryProto.addData64URI = function(name, dataURI) {375 return addChild(this, name, {376 data : dataURI,377 Reader : Data64URIReader,378 Writer : Data64URIWriter379 });380 };381 ZipDirectoryEntryProto.addFileEntry = function(fileEntry, onend, onerror) {382 addFileEntry(this, fileEntry, onend, onerror);383 };384 ZipDirectoryEntryProto.addData = function(name, params) {385 return addChild(this, name, params);386 };387 ZipDirectoryEntryProto.importBlob = function(blob, onend, onerror) {388 this.importZip(new BlobReader(blob), onend, onerror);389 };390 ZipDirectoryEntryProto.importText = function(text, onend, onerror) {391 this.importZip(new TextReader(text), onend, onerror);392 };393 ZipDirectoryEntryProto.importData64URI = function(dataURI, onend, onerror) {394 this.importZip(new Data64URIReader(dataURI), onend, onerror);395 };396 ZipDirectoryEntryProto.exportBlob = function(onend, onprogress, onerror) {397 this.exportZip(new BlobWriter("application/zip"), onend, onprogress, onerror);398 };399 ZipDirectoryEntryProto.exportText = function(onend, onprogress, onerror) {400 this.exportZip(new TextWriter(), onend, onprogress, onerror);401 };402 ZipDirectoryEntryProto.exportFileEntry = function(fileEntry, onend, onprogress, onerror) {403 this.exportZip(new zip.FileWriter(fileEntry, "application/zip"), onend, onprogress, onerror);404 };405 ZipDirectoryEntryProto.exportData64URI = function(onend, onprogress, onerror) {406 this.exportZip(new Data64URIWriter("application/zip"), onend, onprogress, onerror);407 };408 ZipDirectoryEntryProto.importZip = function(reader, onend, onerror) {409 var that = this;410 createReader(reader, function(zipReader) {411 zipReader.getEntries(function(entries) {412 entries.forEach(function(entry) {413 var parent = that, path = entry.filename.split("/"), name = path.pop();414 path.forEach(function(pathPart) {415 parent = parent.getChildByName(pathPart) || new ZipDirectoryEntry(that.fs, pathPart, null, parent);416 });417 if (!entry.directory)418 addChild(parent, name, {419 data : entry,420 Reader : ZipBlobReader421 });422 });423 onend();424 });425 }, onerror);426 };427 ZipDirectoryEntryProto.exportZip = function(writer, onend, onprogress, onerror) {428 var that = this;429 initReaders(that, function() {430 createWriter(writer, function(zipWriter) {431 exportZip(zipWriter, that, function() {432 zipWriter.close(onend);433 }, onprogress, getTotalSize(that));434 }, onerror);435 }, onerror);436 };437 ZipDirectoryEntryProto.getChildByName = function(name) {438 var childIndex, child, that = this;439 for (childIndex = 0; childIndex < that.children.length; childIndex++) {440 child = that.children[childIndex];441 if (child.name == name)442 return child;443 }444 };445 function FS() {446 resetFS(this);447 }448 FS.prototype = {449 remove : function(entry) {450 detach(entry);451 this.entries[entry.id] = null;452 },453 find : function(fullname) {454 var index, path = fullname.split("/"), node = this.root;455 for (index = 0; node && index < path.length; index++)456 node = node.getChildByName(path[index]);457 return node;458 },459 getById : function(id) {460 return this.entries[id];461 },462 importBlob : function(blob, onend, onerror) {463 resetFS(this);464 this.root.importBlob(blob, onend, onerror);465 },466 importText : function(text, onend, onerror) {467 resetFS(this);468 this.root.importText(text, onend, onerror);469 },470 importData64URI : function(dataURI, onend, onerror) {471 resetFS(this);472 this.root.importData64URI(dataURI, onend, onerror);473 },474 exportBlob : function(onend, onprogress, onerror) {475 this.root.exportBlob(onend, onprogress, onerror);476 },477 exportText : function(onend, onprogress, onerror) {478 this.root.exportText(onend, onprogress, onerror);479 },480 exportFileEntry : function(fileEntry, onend, onprogress, onerror) {481 this.root.exportFileEntry(fileEntry, onend, onprogress, onerror);482 },483 exportData64URI : function(onend, onprogress, onerror) {484 this.root.exportData64URI(onend, onprogress, onerror);485 }486 };487 zip.fs = {488 FS : FS,489 ZipDirectoryEntry : ZipDirectoryEntry,490 ZipFileEntry : ZipFileEntry491 };492 zip.getMimeType = function() {493 return "application/octet-stream";494 };...

Full Screen

Full Screen

host_dispatcher.js

Source:host_dispatcher.js Github

copy

Full Screen

...103 case remoting.HostDispatcher.State.NPAPI:104 try {105 this.npapiHost_.getHostName(onDone);106 } catch (err) {107 onError(remoting.Error.MISSING_PLUGIN);108 }109 break;110 }111};112/**113 * @param {string} hostId114 * @param {string} pin115 * @param {function(string):void} onDone116 * @param {function(remoting.Error):void} onError117 * @return {void}118 */119remoting.HostDispatcher.prototype.getPinHash =120 function(hostId, pin, onDone, onError) {121 switch (this.state_) {122 case remoting.HostDispatcher.State.UNKNOWN:123 this.pendingRequests_.push(124 this.getPinHash.bind(this, hostId, pin, onDone, onError));125 break;126 case remoting.HostDispatcher.State.NATIVE_MESSAGING:127 this.nativeMessagingHost_.getPinHash(hostId, pin, onDone, onError);128 break;129 case remoting.HostDispatcher.State.NPAPI:130 try {131 this.npapiHost_.getPinHash(hostId, pin, onDone);132 } catch (err) {133 onError(remoting.Error.MISSING_PLUGIN);134 }135 break;136 }137};138/**139 * @param {function(string, string):void} onDone140 * @param {function(remoting.Error):void} onError141 * @return {void}142 */143remoting.HostDispatcher.prototype.generateKeyPair = function(onDone, onError) {144 switch (this.state_) {145 case remoting.HostDispatcher.State.UNKNOWN:146 this.pendingRequests_.push(147 this.generateKeyPair.bind(this, onDone, onError));148 break;149 case remoting.HostDispatcher.State.NATIVE_MESSAGING:150 this.nativeMessagingHost_.generateKeyPair(onDone, onError);151 break;152 case remoting.HostDispatcher.State.NPAPI:153 try {154 this.npapiHost_.generateKeyPair(onDone);155 } catch (err) {156 onError(remoting.Error.MISSING_PLUGIN);157 }158 break;159 }160};161/**162 * @param {Object} config163 * @param {function(remoting.HostController.AsyncResult):void} onDone164 * @param {function(remoting.Error):void} onError165 * @return {void}166 */167remoting.HostDispatcher.prototype.updateDaemonConfig =168 function(config, onDone, onError) {169 switch (this.state_) {170 case remoting.HostDispatcher.State.UNKNOWN:171 this.pendingRequests_.push(172 this.updateDaemonConfig.bind(this, config, onDone, onError));173 break;174 case remoting.HostDispatcher.State.NATIVE_MESSAGING:175 this.nativeMessagingHost_.updateDaemonConfig(config, onDone, onError);176 break;177 case remoting.HostDispatcher.State.NPAPI:178 try {179 this.npapiHost_.updateDaemonConfig(JSON.stringify(config), onDone);180 } catch (err) {181 onError(remoting.Error.MISSING_PLUGIN);182 }183 break;184 }185};186/**187 * @param {function(Object):void} onDone188 * @param {function(remoting.Error):void} onError189 * @return {void}190 */191remoting.HostDispatcher.prototype.getDaemonConfig = function(onDone, onError) {192 /**193 * Converts the config string from the NPAPI plugin to an Object, to pass to194 * |onDone|.195 * @param {string} configStr196 * @return {void}197 */198 function callbackForNpapi(configStr) {199 var config = jsonParseSafe(configStr);200 if (typeof(config) != 'object') {201 onError(remoting.Error.UNEXPECTED);202 } else {203 onDone(/** @type {Object} */ (config));204 }205 }206 switch (this.state_) {207 case remoting.HostDispatcher.State.UNKNOWN:208 this.pendingRequests_.push(209 this.getDaemonConfig.bind(this, onDone, onError));210 break;211 case remoting.HostDispatcher.State.NATIVE_MESSAGING:212 this.nativeMessagingHost_.getDaemonConfig(onDone, onError);213 break;214 case remoting.HostDispatcher.State.NPAPI:215 try {216 this.npapiHost_.getDaemonConfig(callbackForNpapi);217 } catch (err) {218 onError(remoting.Error.MISSING_PLUGIN);219 }220 break;221 }222};223/**224 * @param {function(string):void} onDone225 * @param {function(remoting.Error):void} onError226 * @return {void}227 */228remoting.HostDispatcher.prototype.getDaemonVersion = function(onDone, onError) {229 switch (this.state_) {230 case remoting.HostDispatcher.State.UNKNOWN:231 this.pendingRequests_.push(232 this.getDaemonVersion.bind(this, onDone, onError));233 break;234 case remoting.HostDispatcher.State.NATIVE_MESSAGING:235 onDone(this.nativeMessagingHost_.getDaemonVersion());236 break;237 case remoting.HostDispatcher.State.NPAPI:238 try {239 this.npapiHost_.getDaemonVersion(onDone);240 } catch (err) {241 onError(remoting.Error.MISSING_PLUGIN);242 }243 break;244 }245};246/**247 * @param {function(boolean, boolean, boolean):void} onDone248 * @param {function(remoting.Error):void} onError249 * @return {void}250 */251remoting.HostDispatcher.prototype.getUsageStatsConsent =252 function(onDone, onError) {253 switch (this.state_) {254 case remoting.HostDispatcher.State.UNKNOWN:255 this.pendingRequests_.push(256 this.getUsageStatsConsent.bind(this, onDone, onError));257 break;258 case remoting.HostDispatcher.State.NATIVE_MESSAGING:259 this.nativeMessagingHost_.getUsageStatsConsent(onDone, onError);260 break;261 case remoting.HostDispatcher.State.NPAPI:262 try {263 this.npapiHost_.getUsageStatsConsent(onDone);264 } catch (err) {265 onError(remoting.Error.MISSING_PLUGIN);266 }267 break;268 }269};270/**271 * @param {Object} config272 * @param {boolean} consent273 * @param {function(remoting.HostController.AsyncResult):void} onDone274 * @param {function(remoting.Error):void} onError275 * @return {void}276 */277remoting.HostDispatcher.prototype.startDaemon =278 function(config, consent, onDone, onError) {279 switch (this.state_) {280 case remoting.HostDispatcher.State.UNKNOWN:281 this.pendingRequests_.push(282 this.startDaemon.bind(this, config, consent, onDone, onError));283 break;284 case remoting.HostDispatcher.State.NATIVE_MESSAGING:285 this.nativeMessagingHost_.startDaemon(config, consent, onDone, onError);286 break;287 case remoting.HostDispatcher.State.NPAPI:288 try {289 this.npapiHost_.startDaemon(JSON.stringify(config), consent, onDone);290 } catch (err) {291 onError(remoting.Error.MISSING_PLUGIN);292 }293 break;294 }295};296/**297 * @param {function(remoting.HostController.AsyncResult):void} onDone298 * @param {function(remoting.Error):void} onError299 * @return {void}300 */301remoting.HostDispatcher.prototype.stopDaemon = function(onDone, onError) {302 switch (this.state_) {303 case remoting.HostDispatcher.State.UNKNOWN:304 this.pendingRequests_.push(this.stopDaemon.bind(this, onDone, onError));305 break;306 case remoting.HostDispatcher.State.NATIVE_MESSAGING:307 this.nativeMessagingHost_.stopDaemon(onDone, onError);308 break;309 case remoting.HostDispatcher.State.NPAPI:310 try {311 this.npapiHost_.stopDaemon(onDone);312 } catch (err) {313 onError(remoting.Error.MISSING_PLUGIN);314 }315 break;316 }317};318/**319 * @param {function(remoting.HostController.State):void} onDone320 * @param {function(remoting.Error):void} onError321 * @return {void}322 */323remoting.HostDispatcher.prototype.getDaemonState = function(onDone, onError) {324 switch (this.state_) {325 case remoting.HostDispatcher.State.UNKNOWN:326 this.pendingRequests_.push(327 this.getDaemonState.bind(this, onDone, onError));328 break;329 case remoting.HostDispatcher.State.NATIVE_MESSAGING:330 this.nativeMessagingHost_.getDaemonState(onDone, onError);331 break;332 case remoting.HostDispatcher.State.NPAPI:333 // Call the callback directly, since NPAPI exposes the state directly as334 // a field member, rather than an asynchronous method.335 var state = this.npapiHost_.daemonState;336 if (state === undefined) {337 onError(remoting.Error.MISSING_PLUGIN);338 } else {339 onDone(state);340 }341 break;342 }343};344/**345 * @param {function(Array.<remoting.PairedClient>):void} onDone346 * @param {function(remoting.Error):void} onError347 * @return {void}348 */349remoting.HostDispatcher.prototype.getPairedClients = function(onDone, onError) {350 /**351 * Converts the JSON string from the NPAPI plugin to Array.<PairedClient>, to352 * pass to |onDone|.353 * @param {string} pairedClientsJson354 * @return {void}355 */356 function callbackForNpapi(pairedClientsJson) {357 var pairedClients = remoting.PairedClient.convertToPairedClientArray(358 jsonParseSafe(pairedClientsJson));359 if (pairedClients != null) {360 onDone(pairedClients);361 } else {362 onError(remoting.Error.UNEXPECTED);363 }364 }365 switch (this.state_) {366 case remoting.HostDispatcher.State.UNKNOWN:367 this.pendingRequests_.push(368 this.getPairedClients.bind(this, onDone, onError));369 break;370 case remoting.HostDispatcher.State.NATIVE_MESSAGING:371 this.nativeMessagingHost_.getPairedClients(onDone, onError);372 break;373 case remoting.HostDispatcher.State.NPAPI:374 try {375 this.npapiHost_.getPairedClients(callbackForNpapi);376 } catch (err) {377 onError(remoting.Error.MISSING_PLUGIN);378 }379 break;380 }381};382/**383 * The pairing API returns a boolean to indicate success or failure, but384 * the JS API is defined in terms of onDone and onError callbacks. This385 * function converts one to the other.386 *387 * @param {function():void} onDone Success callback.388 * @param {function(remoting.Error):void} onError Error callback.389 * @param {boolean} success True if the operation succeeded; false otherwise.390 * @private391 */392remoting.HostDispatcher.runCallback_ = function(onDone, onError, success) {393 if (success) {394 onDone();395 } else {396 onError(remoting.Error.UNEXPECTED);397 }398};399/**400 * @param {function():void} onDone401 * @param {function(remoting.Error):void} onError402 * @return {void}403 */404remoting.HostDispatcher.prototype.clearPairedClients =405 function(onDone, onError) {406 var callback =407 remoting.HostDispatcher.runCallback_.bind(null, onDone, onError);408 switch (this.state_) {409 case remoting.HostDispatcher.State.UNKNOWN:410 this.pendingRequests_.push(411 this.clearPairedClients.bind(this, onDone, onError));412 break;413 case remoting.HostDispatcher.State.NATIVE_MESSAGING:414 this.nativeMessagingHost_.clearPairedClients(callback, onError);415 break;416 case remoting.HostDispatcher.State.NPAPI:417 try {418 this.npapiHost_.clearPairedClients(callback);419 } catch (err) {420 onError(remoting.Error.MISSING_PLUGIN);421 }422 break;423 }424};425/**426 * @param {string} client427 * @param {function():void} onDone428 * @param {function(remoting.Error):void} onError429 * @return {void}430 */431remoting.HostDispatcher.prototype.deletePairedClient =432 function(client, onDone, onError) {433 var callback =434 remoting.HostDispatcher.runCallback_.bind(null, onDone, onError);435 switch (this.state_) {436 case remoting.HostDispatcher.State.UNKNOWN:437 this.pendingRequests_.push(438 this.deletePairedClient.bind(this, client, onDone, onError));439 break;440 case remoting.HostDispatcher.State.NATIVE_MESSAGING:441 this.nativeMessagingHost_.deletePairedClient(client, callback, onError);442 break;443 case remoting.HostDispatcher.State.NPAPI:444 try {445 this.npapiHost_.deletePairedClient(client, callback);446 } catch (err) {447 onError(remoting.Error.MISSING_PLUGIN);448 }449 break;450 }...

Full Screen

Full Screen

methods.js

Source:methods.js Github

copy

Full Screen

1import uuid from "uuid";2import { getFileInfo, readFile, writeFile } from "./storage";3import products from "../data/products.json";4import users from "../data/users.json";5// Create6export async function addUser(data, onSuccess=null, onError=null){7 try {8 const users_ = await getAllUsers();9 await writeFile("users.json", [data, ...users_])10 onSuccess?.("User added successfully!")11 } catch (e) {12 console.log(e)13 onError?.(e)14 }15}16export async function addProduct(data, onSuccess=null, onError=null){17 try {18 const productss = await getAllProducts();19 await writeFile("products.json", [{...data, id: uuid.v4()}, ...productss])20 onSuccess?.("Product added successfully!")21 } catch (e) {22 console.log(e)23 onError?.(e)24 }25}26export async function addOrder(email, cart, onSuccess=null, onError=null){27 const order = {28 id: uuid.v4(),29 user: email,30 time: (new Date()).toString(),31 products: cart,32 status: "placed",33 }34 try {35 const orders = await getAllOrders();36 await writeFile("orders.json", [order, ...orders])37 onSuccess?.("Order added successfully!")38 } catch (e) {39 console.log(e)40 onError?.(e)41 }42}43// Read44export async function getAllUsers(onSuccess=null, onError=null){45 try {46 const fileInfo = await getFileInfo("users.json")47 if (!fileInfo.exists) {48 await writeFile("users.json", users)49 }50 const data = await readFile("users.json")51 onSuccess?.(data)52 return data53 } catch (e){54 console.log(e)55 onError?.(e)56 }57}58export async function getAllProducts(onSuccess=null, onError=null){59 try {60 const fileInfo = await getFileInfo("products.json")61 if (!fileInfo.exists) {62 await writeFile("products.json", products)63 }64 const data = await readFile("products.json")65 onSuccess?.(data)66 return data67 } catch (e){68 onError?.(e)69 }70}71export async function getUser(email, onSuccess=null, onError=null){72 try {73 const user = (await getAllUsers()).filter(user => user.email === email)74 if (user.length === 1) {75 onSuccess?.(user[0])76 return user[0]77 } else onError?.("User not found")78 } catch (e) {79 console.log(e)80 onError?.(e)81 }82}83export async function getProduct(id, onSuccess=null, onError=null){84 try {85 const product = (await getAllProducts()).filter(product => product.id === id)86 if (product.length === 1) {87 onSuccess?.(product[0])88 return product[0]89 } else onError?.("Product not found")90 } catch (e) {91 console.log(e)92 onError?.(e)93 }94}95export async function getOrder(id, onSuccess=null, onError=null){96 try {97 const order = (await getAllOrders()).filter(order => order.id === id)98 if (product.length === 1) {99 onSuccess?.(product[0])100 return product[0]101 } else onError?.("Order not found")102 } catch (e) {103 console.log(e)104 onError?.(e)105 }106}107export async function getFruits(onSuccess=null, onError=null){108 try {109 const products_ = await getAllProducts();110 onSuccess?.(products_.filter(product => product.category === 'fruits'))111 } catch (e) {112 onError?.(e);113 }114}115export async function getVegetables(onSuccess=null, onError=null){116 try {117 const products_ = await getAllProducts();118 onSuccess?.(products_.filter(product => product.category === 'vegetables'))119 } catch (e) {120 onError?.(e)121 }122}123export async function getAllOrders(onSuccess=null, onError=null){124 try {125 const fileInfo = await getFileInfo("orders.json")126 if (!fileInfo.exists) {127 await writeFile("orders.json", [])128 }129 const data = await readFile("orders.json")130 onSuccess?.(data)131 return data132 } catch (e){133 onError?.(e)134 }135}136export async function getMyOrders(email, onSuccess=null, onError=null){137 try {138 const orders = (await getAllOrders()).filter(order => order.user === email)139 onSuccess?.(orders)140 return orders141 } catch (e) {142 onError?.(e);143 }144}145// Update146export async function updateProduct(id, data, onSuccess=null, onError=null){147 try {148 const others = (await getAllProducts()).filter(product => product.id !== id);149 const product = await getProduct(id);150 const updated = { ...product, ...data };151 await writeFile("products.json", [updated, ...others])152 onSuccess?.("Updated successfully!");153 } catch (e) {154 console.log(e);155 onError?.(e);156 }157}158export async function updateOrder(id, data, onSuccess=null, onError=null){159 try {160 const others = (await getAllOrders()).filter(order => order.id !== id);161 const order = (await getAllOrders()).filter(order => order.id === id)[0];162 const updated = { ...order, ...data };163 await writeFile("orders.json", [updated, ...others])164 onSuccess?.("Updated successfully!");165 } catch (e) {166 console.log(e);167 onError?.(e);168 }169}170// Delete171export async function deleteProduct(id, onSuccess = null, onError = null){172 try {173 const products = (await getAllProducts()).filter(product => product.id !== id);174 await writeFile("products.json", products);175 onSuccess?.("Deleted successfully!");176 } catch (e){177 console.log(e)178 onError?.(e);179 }180}181export async function deleteOrder(id, onSuccess = null, onError = null){182 try {183 const orders = (await getAllOrders()).filter(order => order.id !== id);184 await writeFile("orders.json", orders);185 onSuccess?.("Deleted successfully!");186 } catch (e){187 console.log(e)188 onError?.(e);189 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var stub = sinon.stub(obj, 'method').onError();2var spy = sinon.spy(obj, 'method').onError();3var mock = sinon.mock(obj).expects('method').onError();4sinon.assert.onError();5sinon.test.onError();6sinon.testCase.onError();7sinon.sandbox.onError();8sinon.assert.fail.onError();9sinon.assert.pass.onError();

Full Screen

Using AI Code Generation

copy

Full Screen

1var spy = sinon.spy();2spy('arg1', 'arg2');3spy('arg1', 'arg2');4spy('arg1', 'arg2');5spy.reset();6spy('arg1', 'arg2');7var spy = sinon.spy();8spy('arg1', 'arg2');9spy('arg1', 'arg2');10spy('arg1', 'arg2');11spy.reset();12spy('arg1', 'arg2');13var spy = sinon.spy();14spy('arg1', 'arg2');15spy('arg1', 'arg2');16spy('arg1', 'arg2');

Full Screen

Using AI Code Generation

copy

Full Screen

1var server = sinon.fakeServer.create();2var xhr = new XMLHttpRequest();3xhr.onerror = function () {4 console.log("error");5};6xhr.send();7xhr.onreadystatechange = function () {8 if (xhr.readyState === 4) {9 console.log(xhr.responseText);10 console.log(xhr.status);11 }12};13server.respond();14var server = sinon.fakeServer.create();15var xhr = new XMLHttpRequest();16xhr.send();

Full Screen

Using AI Code Generation

copy

Full Screen

1var spy = sinon.spy();2spy("foo", "bar");3spy("baz", "quux");4spy("quux", "baz");5assert(spy.calledWith("foo"));6assert(spy.calledWith("baz"));7assert(spy.calledWith("quux"));8assert(!spy.calledWith("bar"));9assert(!spy.calledWith("quuux"));10assert(!spy.calledWith("bazquux"));11var stub = sinon.stub();12stub("foo", "bar");13stub("baz", "quux");14stub("quux", "baz");15assert(stub.calledWith("foo"));16assert(stub.calledWith("baz"));17assert(stub.calledWith("quux"));18assert(!stub.calledWith("bar"));19assert(!stub.calledWith("quuux"));20assert(!stub.calledWith("bazquux"));21var mock = sinon.mock();22mock.expects("foo").withArgs("foo", "bar");23mock.expects("foo").withArgs("baz", "quux");24mock.expects("foo").withArgs("quux", "baz");25mock.verify();26sinon.assert.calledWith(spy, "foo");27sinon.assert.calledWith(spy, "baz");28sinon.assert.calledWith(spy, "quux");29sinon.assert.neverCalledWith(spy, "bar");30sinon.assert.neverCalledWith(spy, "quuux");31sinon.assert.neverCalledWith(spy, "bazquux");32sinon.assert.calledWith(stub, "foo");33sinon.assert.calledWith(stub, "baz");34sinon.assert.calledWith(stub, "quux");35sinon.assert.neverCalledWith(stub, "bar");36sinon.assert.neverCalledWith(stub, "quuux");37sinon.assert.neverCalledWith(stub, "bazquux");38sinon.assert.calledWith(mock, "foo");39sinon.assert.calledWith(mock, "baz");40sinon.assert.calledWith(mock, "quux");41sinon.assert.neverCalledWith(mock, "bar");42sinon.assert.neverCalledWith(mock, "quuux");43sinon.assert.neverCalledWith(mock, "bazquux");44sinon.assert.calledWith(s

Full Screen

Using AI Code Generation

copy

Full Screen

1var spy = sinon.spy();2spy("some", "arguments");3spy("some", "other", "arguments");4assert(spy.calledThrice);5assert(spy.calledWith("some", "arguments"));6assert(spy.calledWith("some", "other", "arguments"));7assert(spy.calledWithMatch("some", "other"));8assert(spy.neverCalledWith("some", "other", "arguments", "not"));9assert(spy.alwaysCalledWithMatch("some", "other"));10assert(spy.firstCall.calledWith("some", "arguments"));11assert(spy.secondCall.calledWith("some", "other", "arguments"));12assert(spy.thirdCall.calledWith("some", "other", "arguments"));13assert(spy.callCount === 2);14assert(spy.calledOn(someObject));15assert(spy.calledWithNew());16assert(spy.calledBefore(anotherSpy));17assert(spy.calledAfter(anotherSpy));18assert(spy.calledImmediatelyBefore(anotherSpy));19assert(spy.calledImmediatelyAfter(anotherSpy));20var spy = sinon.spy();21spy("some", "arguments");22spy("some", "other", "arguments");23assert(spy.calledThrice);24assert(spy.calledWith("some", "arguments"));25assert(spy.calledWith("some", "other", "arguments"));26assert(spy.calledWithMatch("some", "other"));27assert(spy.neverCalledWith("some", "other", "arguments", "not"));28assert(spy.alwaysCalledWithMatch("some", "other"));29assert(spy.firstCall.calledWith("some", "arguments"));30assert(spy.secondCall.calledWith("some", "other", "arguments"));31assert(spy.thirdCall.calledWith("some", "other", "arguments"));32assert(spy.callCount === 2);33assert(spy.calledOn(someObject));34assert(spy.calledWithNew());35assert(spy.calledBefore(anotherSpy));36assert(spy.calledAfter(anotherSpy));37assert(spy.calledImmediatelyBefore(anotherSpy));38assert(spy.calledImmediatelyAfter(anotherSpy));39var spy = sinon.spy();40spy("some", "arguments");41spy("some", "other", "arguments");42assert(spy.calledThrice);43assert(spy.calledWith("some", "arguments"));44assert(spy.calledWith("some

Full Screen

Using AI Code Generation

copy

Full Screen

1const sinon = require('sinon');2const assert = require('assert');3const myObj = {4 myMethod: function() {5 console.log("myMethod called");6 }7};8const spy = sinon.spy(myObj, "myMethod");9spy();10assert(spy.called);11assert(spy.calledOnce);12assert(spy.calledWith());13assert(spy.calledOn(myObj));14assert(spy.calledWithExactly());15spy("foo", "bar");16assert(spy.calledWith("foo", "bar"));17assert(spy.calledWithExactly("foo", "bar"));18spy("foo", "bar", "baz");19assert(spy.calledWith("foo", "bar", "baz"));20assert(!spy.calledWithExactly("foo", "bar", "baz"));21assert(spy.calledWithMatch("foo"));22assert(!spy.calledWithMatch("quux"));23assert(spy.calledWithMatch("foo", "bar"));24assert(!spy.calledWithMatch("foo", "quux"));25assert(spy.calledWithMatch("foo", "bar", "baz"));26assert(!spy.calledWithMatch("foo", "bar", "quux"));27assert(spy.calledWithMatch(sinon.match.string));28assert(!spy.calledWithMatch(sinon.match.number));29assert(spy.calledWithMatch("foo", sinon.match.string));30assert(!spy.calledWithMatch("foo", sinon.match.number));31assert(spy.calledWithMatch(sinon.match.string, "bar"));32assert(!spy.calledWithMatch(sinon.match.number, "bar"));33assert(spy.calledWithMatch("foo", sinon.match.string, "baz"));34assert(!spy.calledWithMatch("foo", sinon.match.number, "baz"));35assert(spy.calledWithMatch(sinon.match.string, "bar", "baz"));36assert(!spy.calledWithMatch(sinon.match.number, "bar", "baz"));37spy("foo", "bar", "baz", "quux");38assert(spy.alwaysCalledWith("foo", "bar", "baz"));39assert(!spy.alwaysCalledWith("foo", "bar", "baz", "quux"));40assert(spy.alwaysCalledWithMatch("foo", "bar"));41assert(spy.alwaysCalledWithMatch("foo", sinon.match.string));42assert(spy.alwaysCalledWithMatch(sinon.match.string, "bar"));43assert(spy.alwaysCalledWithMatch("foo", sinon.match.string, "baz"));44assert(spy.alwaysCalledWithMatch(sinon.match.string, "bar

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var myObj = {3 myMethod: function () {4 throw new Error('myMethod error');5 }6};7var spy = sinon.spy(myObj, "myMethod");8var sinon = require('sinon');9var myObj = {10 myMethod: function () {11 throw new Error('myMethod error');12 }13};14var spy = sinon.spy(myObj, "myMethod");15spy.restore();16var sinon = require('sinon');17var myObj = {18 myMethod: function () {19 throw new Error('myMethod error');20 }21};22var spy = sinon.spy(myObj, "myMethod");23spy.resetHistory();24var sinon = require('sinon');25var myObj = {26 myMethod: function () {27 throw new Error('myMethod error');28 }29};30var spy = sinon.spy(myObj, "myMethod");31spy.restore();32var sinon = require('sinon');33var myObj = {34 myMethod: function () {35 throw new Error('myMethod error');

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var assert = require('assert');3var myObj = {4 myMethod: function () {5 return 42;6 }7};8var stub = sinon.stub(myObj, "myMethod").throws();9assert.throws(function () {10 myObj.myMethod();11}, Error);12var myObj2 = {13 myMethod2: function () {14 return 42;15 }16};17var stub = sinon.stub(myObj2, "myMethod2").throws(new Error("my error"));18assert.throws(function () {19 myObj2.myMethod2();20}, Error);21var myObj3 = {22 myMethod3: function () {23 return 42;24 }25};26var stub = sinon.stub(myObj3, "myMethod3").throws(new TypeError("my error"));27assert.throws(function () {28 myObj3.myMethod3();29}, TypeError);30var myObj4 = {31 myMethod4: function () {32 return 42;33 }34};35var stub = sinon.stub(myObj4, "myMethod4").throws(new TypeError("my error"));36assert.throws(function () {37 myObj4.myMethod4();38}, TypeError);39var myObj5 = {40 myMethod5: function () {41 return 42;42 }43};44var stub = sinon.stub(myObj5, "myMethod5").throws(new TypeError("my error"));45assert.throws(function () {46 myObj5.myMethod5();47}, TypeError);48var myObj6 = {49 myMethod6: function () {50 return 42;51 }52};53var stub = sinon.stub(myObj6, "myMethod6").throws(new TypeError("my error"));54assert.throws(function () {55 myObj6.myMethod6();56}, TypeError);57var myObj7 = {58 myMethod7: function () {59 return 42;60 }61};62var stub = sinon.stub(myObj7, "myMethod7").throws(new TypeError("my error"));63assert.throws(function () {64 myObj7.myMethod7();65}, TypeError);

Full Screen

Using AI Code Generation

copy

Full Screen

1test("test to use onError method of sinon fake server", function() {2 var server = sinon.fakeServer.create();3 server.respondWith("GET", "/test", [500, {"Content-Type": "application/json"}, ""]);4 server.respondWith("GET", "/test2", [500, {"Content-Type": "application/json"}, ""]);5 server.respondWith("GET", "/test3", [500, {"Content-Type": "application/json"}, ""]);6 var callback = sinon.spy();7 server.onError = callback;8 server.respond();9 assert(callback.called);10});11test("test to use respondWith method of sinon fake server", function() {12 var server = sinon.fakeServer.create();13 server.respondWith("GET", "/test", [200, {"Content-Type": "application/json"}, "{foo: 'bar'}"]);14 server.respondWith("GET", "/test2", [200, {"Content-Type": "application/json"}, "{foo: 'bar'}"]);15 server.respondWith("GET", "/test3", [200, {"Content-Type": "application/json"}, "{foo: 'bar'}"]);16 var callback = sinon.spy();17 server.respond();18 assert(callback.called);19});20test("test to use respond method of sinon fake server", function() {21 var server = sinon.fakeServer.create();22 server.respondWith("GET", "/test", [200, {"Content-Type": "application/json"}, "{foo: 'bar'}"]);23 server.respondWith("GET", "/test2", [200, {"Content-Type": "application/json"}, "{foo: 'bar'}"]);24 server.respondWith("GET", "/test3", [200, {"Content-Type": "application/json"}, "{foo: 'bar'}"]);25 var callback = sinon.spy();26 server.respond();27 assert(callback.called);28});29test("test to use getHTTPMethod method of

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run sinon automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful