How to use fakeDriver method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

device_test.js

Source:device_test.js Github

copy

Full Screen

1/**2 * This file contains unit tests for testing functions in the3 * LabJackDriver/device.js file. Using "rewire" it replaces the4 * driver_wrapper.js library with a virtual device for testing purposes.5 *6 * @author Chris Johnson (chrisjohn404)7 *8 * Module Dependencies:9 * rewire, can be installed using "npm install rewire"10 * device, should be located relatively "../labJackDriver/device.js"11 * test_driver_wrapper, should be located relatively12 * "./TestObjects/test_driver_wrapper"13 */14var rewire = require('rewire');15var q = require('q');16var ref = require('ref');17var fakeDriver = require('./TestObjects/test_driver_wrapper');18var fakeLJM = new fakeDriver.getDriver();19// console.log('F-LJM', Object.keys(fakeLJM));20var driver_wrapper = rewire('../lib/driver_wrapper');21// NEW:22var driverManager = rewire('../lib/driver');23driverManager.__set__('driverLib',fakeDriver);24var deviceManager = rewire('../lib/device');25deviceManager.__set__('driverLib',fakeDriver);26// OLD:27var deviceManager = rewire('../lib/device');28deviceManager.__set__('driverLib',fakeDriver);29var driver_const = require('ljswitchboard-ljm_driver_constants');30var asyncRun = require('./UtilityCode/asyncUtility');31var syncRun = require('./UtilityCode/syncUtility');32var callSequenceChecker = require('./call_sequence_checker');33var ljs_mm = require('ljswitchboard-modbus_map');34var ljm_modbus_map = ljs_mm.getConstants();35var dev;36var autoOpen = false;37var autoClose = false;38var testVal = 69;39module.exports = {40 setUp: function(callback) {41 //this.mockDevice = new MockDevice();42 if(autoOpen) {43 dev = new deviceManager.labjack(fakeLJM);44 dev.open(function(res) {45 console.log("Err-Setup/Teardown!!!");46 },47 function(res) {48 fakeDriver.clearLastFunctionCall();49 callback();50 });51 }52 else {53 callback();54 }55 },56 tearDown: function (callback) {57 // clean up58 fakeDriver.setExpectedResult(0);59 if(autoClose) {60 dev.close(function(res) {61 console.log("Err-Setup/Teardown!!!",res);62 },63 function(res) {64 fakeDriver.clearLastFunctionCall();65 fakeDriver.setExpectedResult(0);66 fakeDriver.clearArgumentsList();67 asyncRun.clearResults();68 syncRun.clearResults();69 callback();70 });71 }72 else {73 fakeDriver.clearLastFunctionCall();74 fakeDriver.clearArgumentsList();75 fakeDriver.setExpectedResult(0);76 asyncRun.clearResults();77 syncRun.clearResults();78 callback();79 }80 },81 /**82 * Tests the standard LJM open call.83 * 1. The LJM function "Open" should be called.84 * 2. A handle acquired.85 * 3. The device information saved.86 * 4. Function should succede at opening a device.87 * 5. Close a Device88 *89 * @param {[type]} test90 * @return {[type]}91 */92 testOpen: function(test) {93 var device = new deviceManager.labjack(fakeLJM);94 device.open(95 driver_const.LJM_DT_ANY,96 driver_const.LJM_CT_ANY,97 "LJM_idANY",98 function(res) {99 console.log("Opening Error");100 },101 function(res) {102 //get the handle & make sure it isn't zero103 test.notStrictEqual(device.handle, null);104 test.notEqual(device.handle, 0);105 //Make sure that LJM_OpenSAsync was called106 assert.equal(fakeDriver.getLastFunctionCall().length,1);107 assert.equal(fakeDriver.getLastFunctionCall()[0],"LJM_OpenAsync");108 //Make sure that dtAny, ctAny, and idAny were used as variables109 assert.equal(device.deviceType,driver_const.LJM_DT_ANY);110 assert.equal(device.connectionType,driver_const.LJM_CT_ANY);111 assert.equal(device.identifier,"LJM_idANY");112 //Close the Device113 device.close(114 function(res) {115 console.log("Closing Error");116 },117 function(res) {118 assert.strictEqual(device.handle, null);119 assert.strictEqual(device.deviceType,null);120 assert.strictEqual(device.connectionType,null);121 assert.strictEqual(device.identifier,null);122 assert.equal(123 fakeDriver.getLastFunctionCall()[1],124 "LJM_CloseAsync"125 );126 done();127 });128 });129 },130 testOpenWeirdA: function(test) {131 var device = new deviceManager.labjack(fakeLJM);132 device.open(133 "LJM_dtANY", //Will be converted to an integer134 driver_const.LJM_CT_ANY,135 "LJM_idANY",136 function(res) {137 console.log("Opening Error");138 },139 function(res) {140 //get the handle & make sure it isn't zero141 test.notStrictEqual(device.handle, null);142 test.notEqual(device.handle, 0);143 //Make sure that LJM_OpenSAsync was called144 assert.equal(fakeDriver.getLastFunctionCall().length,1);145 assert.equal(fakeDriver.getLastFunctionCall()[0],"LJM_OpenAsync");146 //Make sure that dtAny, ctAny, and idAny were used as variables147 assert.equal(device.deviceType,driver_const.LJM_DT_ANY);148 assert.equal(device.connectionType,driver_const.LJM_CT_ANY);149 assert.equal(device.identifier,"LJM_idANY");150 //Close the Device151 device.close(152 function(res) {153 console.log("Closing Error");154 },155 function(res) {156 assert.strictEqual(device.handle, null);157 assert.strictEqual(device.deviceType,null);158 assert.strictEqual(device.connectionType,null);159 assert.strictEqual(device.identifier,null);160 assert.equal(161 fakeDriver.getLastFunctionCall()[1],162 "LJM_CloseAsync"163 );164 done();165 });166 });167 },168 testOpenWeirdB: function(test) {169 var device = new deviceManager.labjack(fakeLJM);170 device.open(171 driver_const.LJM_DT_ANY,172 "LJM_ctANY", //Will be converted to an integer173 "LJM_idANY",174 function(res) {175 console.log("Opening Error");176 },177 function(res) {178 //get the handle & make sure it isn't zero179 test.notStrictEqual(device.handle, null);180 test.notEqual(device.handle, 0);181 //Make sure that LJM_OpenSAsync was called182 assert.equal(fakeDriver.getLastFunctionCall().length,1);183 assert.equal(fakeDriver.getLastFunctionCall()[0],"LJM_OpenAsync");184 //Make sure that dtAny, ctAny, and idAny were used as variables185 assert.equal(device.deviceType,driver_const.LJM_DT_ANY);186 assert.equal(device.connectionType,driver_const.LJM_CT_ANY);187 assert.equal(device.identifier,"LJM_idANY");188 //Close the Device189 device.close(190 function(res) {191 console.log("Closing Error");192 },193 function(res) {194 assert.strictEqual(device.handle, null);195 assert.strictEqual(device.deviceType,null);196 assert.strictEqual(device.connectionType,null);197 assert.strictEqual(device.identifier,null);198 assert.equal(199 fakeDriver.getLastFunctionCall()[1],200 "LJM_CloseAsync"201 );202 done();203 });204 });205 },206 testOpenWeirdC: function(test) {207 var device = new deviceManager.labjack(fakeLJM);208 var param = "0";209 var paramB = param;210 device.open(211 paramB, //Will be converted to an integer212 driver_const.LJM_CT_ANY,213 "LJM_idANY",214 function(res) {215 console.log("Opening Error");216 },217 function(res) {218 //get the handle & make sure it isn't zero219 test.notStrictEqual(device.handle, null);220 test.notEqual(device.handle, 0);221 //Make sure that LJM_OpenSAsync was called222 assert.equal(fakeDriver.getLastFunctionCall().length,1);223 assert.equal(fakeDriver.getLastFunctionCall()[0],"LJM_OpenAsync");224 //Make sure that dtAny, ctAny, and idAny were used as variables225 assert.equal(device.deviceType,driver_const.LJM_DT_ANY);226 assert.equal(device.connectionType,driver_const.LJM_CT_ANY);227 assert.equal(device.identifier,"LJM_idANY");228 //Close the Device229 device.close(230 function(res) {231 console.log("Closing Error");232 },233 function(res) {234 assert.strictEqual(device.handle, null);235 assert.strictEqual(device.deviceType,null);236 assert.strictEqual(device.connectionType,null);237 assert.strictEqual(device.identifier,null);238 assert.equal(239 fakeDriver.getLastFunctionCall()[1],240 "LJM_CloseAsync"241 );242 done();243 });244 });245 },246 testOpenWeirdD: function(test) {247 var device = new deviceManager.labjack(fakeLJM);248 var param = "0";249 device.open(250 driver_const.LJM_DT_ANY,251 param, //Will be converted to an integer252 "LJM_idANY",253 function(res) {254 console.log("Opening Error");255 },256 function(res) {257 //get the handle & make sure it isn't zero258 test.notStrictEqual(device.handle, null);259 test.notEqual(device.handle, 0);260 //Make sure that LJM_OpenSAsync was called261 assert.equal(fakeDriver.getLastFunctionCall().length,1);262 assert.equal(fakeDriver.getLastFunctionCall()[0],"LJM_OpenAsync");263 //Make sure that dtAny, ctAny, and idAny were used as variables264 assert.equal(device.deviceType,driver_const.LJM_DT_ANY);265 assert.equal(device.connectionType,driver_const.LJM_CT_ANY);266 assert.equal(device.identifier,"LJM_idANY");267 //Close the Device268 device.close(269 function(res) {270 console.log("Closing Error");271 },272 function(res) {273 assert.strictEqual(device.handle, null);274 assert.strictEqual(device.deviceType,null);275 assert.strictEqual(device.connectionType,null);276 assert.strictEqual(device.identifier,null);277 assert.equal(278 fakeDriver.getLastFunctionCall()[1],279 "LJM_CloseAsync"280 );281 done();282 });283 });284 },285 /**286 * Tests the string-open feature of the device class.287 * 1. The LJM function "OpenS" should be called.288 * 2. A handle acquired.289 * 3. The device information saved.290 * 4. Function should succede at opening a device.291 *292 * @param {[type]} test293 * @return {[type]}294 */295 testOpenS: function(test) {296 var device = new deviceManager.labjack(fakeLJM);297 device.open("LJM_dtT7","LJM_ctUSB","LJM_idANY",298 function(res) {299 console.log("Opening Error");300 },301 function(res) {302 //get the handle & make sure it isn't zero303 test.notStrictEqual(device.handle, null);304 test.notEqual(device.handle, 0);305 //Make sure that LJM_OpenSAsync was called306 assert.equal(fakeDriver.getLastFunctionCall().length,1);307 assert.equal(fakeDriver.getLastFunctionCall()[0],"LJM_OpenSAsync");308 //Make sure that dtAny, ctAny, and idAny were used as variables309 assert.equal(device.deviceType,"LJM_dtT7");310 assert.equal(device.connectionType,"LJM_ctUSB");311 assert.equal(device.identifier,"LJM_idANY");312 //Close the Device313 device.close(314 function(res) {315 console.log("Closing Error");316 },317 function(res) {318 assert.strictEqual(device.handle, null);319 assert.strictEqual(device.deviceType,null);320 assert.strictEqual(device.connectionType,null);321 assert.strictEqual(device.identifier,null);322 assert.equal(323 fakeDriver.getLastFunctionCall()[1],324 "LJM_CloseAsync"325 );326 done();327 });328 });329 },330 /**331 * Tests the open feature when no information is passed to the driver. A332 * device should be opened using the Open LJM function with commands:333 * 1. DeviceType any334 * 2. ConnectionTypeπ any335 * 3. Identifier any336 * @param {[type]} test337 * @return {[type]}338 */339 testOpenEmpty: function(test) {340 var device = new deviceManager.labjack(fakeLJM);341 device.open(342 function(res) {343 console.log("Opening Error");344 },345 function(res) {346 //get the handle & make sure it isn't zero347 test.notStrictEqual(device.handle, null);348 test.notEqual(device.handle, 0);349 //Make sure that LJM_OpenSAsync was called350 assert.equal(fakeDriver.getLastFunctionCall().length,1);351 assert.equal(fakeDriver.getLastFunctionCall()[0],"LJM_OpenSAsync");352 //Make sure that dtAny, ctAny, and idAny were used as variables353 assert.equal(device.deviceType,"LJM_dtANY");354 assert.equal(device.connectionType,"LJM_ctANY");355 assert.equal(device.identifier,"LJM_idANY");356 //Close the Device357 device.close(358 function(res) {359 console.log("Closing Error");360 },361 function(res) {362 assert.strictEqual(device.handle, null);363 assert.strictEqual(device.deviceType,null);364 assert.strictEqual(device.connectionType,null);365 assert.strictEqual(device.identifier,null);366 assert.equal(367 fakeDriver.getLastFunctionCall()[1],368 "LJM_CloseAsync"369 );370 done();371 });372 });373 },374 /**375 * Tests the error-reporting features of the open command in Async-mode.376 * 1. An error should be reported via the onError function.377 * 2. No device information should be saved.378 * 3. There should be no device handle saved.379 *380 * @param {[type]} test381 */382 testOpenNoDeviceFail: function(test) {383 //Force the open call to fail w/ error code 1384 var erCode = 1;385 fakeDriver.setExpectedResult(erCode);386 var device = new deviceManager.labjack(fakeLJM);387 device.open("LJM_dtANY","LJM_ctANY","LJM_idANY",388 function(res) {389 assert.equal(res,erCode);390 assert.strictEqual(device.handle, null);391 assert.strictEqual(device.deviceType,null);392 assert.strictEqual(device.connectionType,null);393 assert.strictEqual(device.identifier,null);394 //Try closing a device even though one has never been opened395 device.close(396 function(res) {397 assert.equal(res,"Device Never Opened");398 autoOpen = true; //Request that the test enviro. auto-open399 done();400 },401 function(res) {402 console.log("CloseSuccess, ERROR!! NOT SUPPOSED TO HAPPEN");403 });404 },405 function(res) {406 console.log("OpenSuccess, ERROR!!!!!!! NOT SUPPOSED TO HAPPEN");407 });408 },409 /**410 * Tests the getHandleInfo function411 * @param {[type]} test412 */413 testGetHandleInfo: function(test) {414 autoClose = true;//Request that the test enviro. auto-close415 dev.getHandleInfo(function(res) {416 console.log('ErrGetHandleInfo');417 },418 function(res) {419 //Test the return values420 assert.equal(res.deviceType,driver_const.LJM_DT_T7);421 assert.equal(res.connectionType,driver_const.LJM_CT_USB);422 assert.equal(res.serialNumber,12345678);423 assert.equal(res.ipAddress,"1.2.3.4");424 assert.equal(res.port,2468);425 assert.equal(res.maxBytesPerMB,testVal);426 assert.equal(fakeDriver.getLastFunctionCall()[0],"LJM_GetHandleInfoAsync");427 done();428 });429 },430 /**431 * This test tests the LJM_eReadRaw asynchronous function call of LJM.432 * @param {[type]} test The test object.433 */434 testReadRaw: function(test) {435 var data=[0,0,0,0,0,0,0,0,0,0];436 var testBuf = new Buffer(data.length);437 testBuf.fill(testVal);//Fill buffer with success data438 dev.readRaw(data,function(res) {439 //Error440 console.log("!!!!ReadRaw ERROR!!!!");441 },442 function(res) {443 //Success444 var i;445 for(i = 0; i < res.length; i++) {446 assert.equal(testBuf.readUInt8(i),res.readUInt8(i));447 }448 assert.equal(fakeDriver.getLastFunctionCall()[0],"LJM_ReadRawAsync");449 done();450 });451 },452 /**453 * This test tests the LJM_eReadName, LJM_eReadAddress, LJM_eReadNameString,454 * and LJM_eReadAddressString asynchronous function calls of LJM.455 * @param {[type]} test The test object.456 */457 testRead: function(test) {458 fakeDriver.setResultArg(testVal);459 asyncRun.config(dev,null);460 syncRun.config(dev,null);461 var testList = [462 'read(0)',463 'read("AIN0")',464 'read(60500)',465 'read("DEVICE_NAME_DEFAULT")'466 ];467 var expectedFunctionList = [468 'LJM_eReadAddress',469 'LJM_eReadAddress',470 'LJM_eReadAddressString',471 'LJM_eReadAddressString',472 'LJM_eReadAddressAsync',473 'LJM_eReadAddressAsync',474 'LJM_eReadAddressStringAsync',475 'LJM_eReadAddressStringAsync'476 ];477 var expectedResultList = [478 testVal,479 testVal,480 testVal.toString(),481 testVal.toString(),482 testVal,483 testVal,484 testVal.toString(),485 testVal.toString(),486 ];487 syncRun.run(testList);488 asyncRun.run(testList,489 function(res) {490 //Error, should never be called.... isn't ever used... woops....491 }, function(res) {492 //Success493 var funcs = fakeDriver.getLastFunctionCall();494 var results = asyncRun.getResults();495 var args = fakeDriver.getArgumentsList();496 var i;497 for(i = 0; i < testList.length*2; i++) {498 assert.equal(funcs[i], expectedFunctionList[i]);499 assert.equal(results[i], expectedResultList[i]);500 }501 //Test to make sure the address-to-type conversion worked (sync)502 assert.equal(args[1][2],driver_const.LJM_FLOAT32);503 //Test to make sure the address-to-type conversion worked(async)504 assert.equal(args[5][2],driver_const.LJM_FLOAT32);505 done();506 });507 },508 /**509 * This test tests the LJM_eReadName, LJM_eReadAddress, LJM_eReadNameString,510 * and LJM_eReadAddressString asynchronous function calls of LJM.511 * & makes sure that they properly return error codes.512 * @param {[type]} test The test object.513 */514 testReadFail: function(test) {515 fakeDriver.setResultArg(testVal);516 //Configure running-engines517 asyncRun.config(dev,null);518 syncRun.config(dev,null);519 //Force the driver to produce an error code520 var erCode = 1;521 fakeDriver.setExpectedResult(erCode);522 var testList = [523 'read(-1)',//Test for invalid address524 'read("AIN999")',//Test for invalid name525 'read(49350)',//test for write only address-number read526 'read("WIFI_PASSWORD_DEFAULT")',//Test for write only address-name read527 'read(0)',528 'read("AIN0")',529 ];530 var expectedFunctionList = [531 'LJM_eReadAddress',532 'LJM_eReadName',533 'LJM_eReadAddressAsync',534 'LJM_eReadNameAsync',535 ];536 var expectedResultList = [537 'Invalid Address',538 'Invalid Address',539 'Invalid Read Attempt',540 'Invalid Read Attempt',541 erCode,542 erCode,543 'Invalid Address',544 'Invalid Address',545 'Invalid Read Attempt',546 'Invalid Read Attempt',547 erCode,548 erCode,549 ];550 syncRun.run(testList);551 asyncRun.run(testList,552 function(res) {553 //Error, should never be called.... isn't ever used... woops....554 }, function(res) {555 //Success556 var funcs = fakeDriver.getLastFunctionCall();557 var results = asyncRun.getResults();558 var args = fakeDriver.getArgumentsList();559 //console.log(args)560 var i;561 // console.log("Functions Called",funcs);562 // console.log("Results",results);563 //Test to make sure that the proper number of commands have been564 //executed & results returned:565 assert.equal(funcs.length, expectedFunctionList.length);566 assert.equal(results.length, expectedResultList.length);567 //Make sure that the proper LJM functions were called568 for(i = 0; i < testList.length*2; i++) {569 assert.equal(results[i], expectedResultList[i]);570 }571 done();572 });573 },574 /**575 * This test tests the LJM_eReadNames, and LJM_eReadAddresses asynchronous576 * function calls of LJM.577 * @param {[type]} test The test object.578 */579 testReadMany: function(test) {580 var resArray = [testVal,testVal+1];581 var numArgs = resArray.length;582 fakeDriver.setResultArg(resArray);583 asyncRun.config(dev,null);584 syncRun.config(dev,null);585 var testList = [586 'readMany([0,2])',587 'readMany(["AIN0","AIN1"])',588 ];589 //Expected info combines both sync & async590 var expectedFunctionList = [591 'LJM_eReadAddresses',592 'LJM_eReadNames',593 'LJM_eReadAddressesAsync',594 'LJM_eReadAddressesAsync',595 ];596 //Expected info combines both sync & async597 var expectedResultList = [598 resArray,599 resArray,600 resArray,601 resArray,602 ];603 syncRun.run(testList,false,false);604 asyncRun.run(testList,605 function(res) {606 //Error607 }, function(res) {608 //Success609 var funcs = fakeDriver.getLastFunctionCall();610 var results = asyncRun.getResults();611 var argList = fakeDriver.getArgumentsList();612 var i,j;613 var offsetSync = 1;614 console.log("Functions Called",funcs);615 console.log("Results",results);616 //Figure out how many function calls should have been made:617 var numDriverCalls = testList.length * 2;618 //Test to make sure that the proper number of commands have been619 //executed & results returned:620 assert.equal(funcs.length, expectedFunctionList.length);621 assert.equal(results.length, expectedResultList.length);622 //Test to make sure that the expected driver calls is actually623 //what happened:624 for(i = 0; i < numDriverCalls; i++) {625 assert.equal(funcs[i],expectedFunctionList[i]);626 }627 //Test to make sure that the proper results came back for each628 //call starting with sync then async629 for(i = 0; i < numDriverCalls; i++) {630 for(j = 0; j < resArray.length; j++) {631 assert.equal(results[i][j],expectedResultList[i][j]);632 }633 }634 //Test to make sure that each function got passed the proper635 //arguments636 // console.log(funcs)637 // console.log('argList length:',argList.length);638 // console.log('argList:',argList);639 for(i = 0; i < numDriverCalls; i++) {640 if(expectedFunctionList[i] == 'LJM_eReadAddressesAsync') {641 assert.equal(argList[i+offsetSync][1], numArgs);642 assert.equal(argList[i+offsetSync][2].length, numArgs*4);643 assert.equal(argList[i+offsetSync][3].length, numArgs*4);644 assert.equal(argList[i+offsetSync][4].length, numArgs*8);645 assert.equal(argList[i+offsetSync][5].length, 4);646 } else if(expectedFunctionList[i] == 'LJM_eReadNamesAsync'){647 assert.equal(argList[i+offsetSync][1], numArgs);648 assert.equal(argList[i+offsetSync][3].length, numArgs*8);649 assert.equal(argList[i+offsetSync][4].length, 4);650 } else if(expectedFunctionList[i] == 'LJM_eReadAddresses') {651 assert.equal(argList[i+offsetSync][1], numArgs);652 assert.equal(argList[i+offsetSync][2].length, numArgs*4);653 assert.equal(argList[i+offsetSync][3].length, numArgs*4);654 assert.equal(argList[i+offsetSync][4].length, numArgs*8);655 assert.equal(argList[i+offsetSync][5].length, 4);656 } else if (expectedFunctionList[i] == 'LJM_eReadNames'){657 assert.equal(argList[i+offsetSync][1], numArgs);658 assert.equal(argList[i+offsetSync][3].length, numArgs*8);659 assert.equal(argList[i+offsetSync][4].length, 4);660 } else {661 }662 }663 done();664 });665 },666 /**667 * This test tests the LJM_eReadNames, and LJM_eReadAddresses asynchronous668 * function calls of LJM and their methidologies for reporting errors.669 * @param {[type]} test The test object.670 */671 testReadManyFail: function(test) {672 var resArray = [testVal,testVal+1];673 var numArgs = resArray.length;674 fakeDriver.setResultArg(resArray);675 //Force the driver to produce an error code676 var erCode = 1;677 fakeDriver.setExpectedResult(erCode);678 //Configure running-engines679 asyncRun.config(dev, null);680 syncRun.config(dev, null);681 //Create test-variables682 var testList = [683 'readMany([-1,2])',684 'readMany(["AI999","AIN1"])',685 'readMany([0,49350])',686 'readMany(["AIN0","WIFI_PASSWORD_DEFAULT"])',687 'readMany([0,2])',688 'readMany(["AIN0","AIN1"])',689 ];690 //Expected info combines both sync & async691 var expectedFunctionList = [692 'LJM_eReadNames',693 'LJM_eReadNames',694 'LJM_eReadAddresses',695 'LJM_eReadNames',696 'LJM_eReadAddressesAsync',697 'LJM_eReadAddressesAsync',698 ];699 //Expected info combines both sync & async700 var expectedResultList = [701 // Errors for Sync:702 { retError: 'Invalid Address', errFrame: 0 },703 { retError: erCode, errFrame: 99 },704 { retError: 'Invalid Read Attempt', errFrame: 1 },705 { retError: erCode, errFrame: 99 },706 { retError: erCode, errFrame: 99 },707 { retError: erCode, errFrame: 99 },708 // Errors for Async709 { retError: 'Invalid Address', errFrame: 0 },710 { retError: 'Invalid Address', errFrame: 0 },711 { retError: 'Invalid Read Attempt', errFrame: 1 },712 { retError: 'Invalid Read Attempt', errFrame: 1 },713 { retError: erCode, errFrame: 99 },714 { retError: erCode, errFrame: 99 },715 ];716 //Run the desired commands717 syncRun.run(testList);718 asyncRun.run(testList,719 function(res) {720 //Error721 }, function(res) {722 //Success723 var funcs = fakeDriver.getLastFunctionCall();724 var results = asyncRun.getResults();725 var argList = fakeDriver.getArgumentsList();726 var i,j;727 var offsetSync = 1;728 // console.log('Function Calls',funcs);729 // console.log('Results',results);730 // console.log('arguments',argList);731 //Figure out how many function calls should have been made:732 var numDriverCalls = testList.length * 2;733 //Test to make sure that the proper number of commands have been734 //executed & results returned:735 assert.equal(results.length, expectedResultList.length);736 //Test to make sure that the expected driver calls is actually737 //what happened:738 assert.deepEqual(expectedFunctionList,funcs);739 //Make sure that the errors are being returned properly & stored740 //in the results array741 for(i = 0; i < numDriverCalls; i++) {742 assert.equal(results[i] instanceof Object,true);743 assert.equal(744 results[i].retError,745 expectedResultList[i].retError746 );747 assert.equal(748 results[i].errFrame,749 expectedResultList[i].errFrame750 );751 }752 done();753 });754 },755 /**756 * This test tests the LJM_eWriteRaw asynchronous function call of LJM.757 * @param {[type]} test The test object.758 */759 testWriteRaw: function(test) {760 var resArray = [9,8,7,6,5,4,3,2,1];761 fakeDriver.setResultArg(resArray);762 //Configure running-engines763 asyncRun.config(dev, null);764 syncRun.config(dev, null);765 //Create test-variables766 var testList = [767 'writeRaw([1,2,3,4,5,6,7,8,9])',768 ];769 //Expected info combines both sync & async770 var expectedFunctionList = [771 'LJM_WriteRaw',772 'LJM_WriteRawAsync',773 ];774 //Expected info combines both sync & async775 var expectedResultList = [776 resArray,777 resArray,778 ];779 //Run the desired commands780 syncRun.run(testList);781 asyncRun.run(testList,782 function(res) {783 //Error784 }, function(res) {785 //Success786 var funcs = fakeDriver.getLastFunctionCall();787 var results = asyncRun.getResults();788 var argList = fakeDriver.getArgumentsList();789 var i,j;790 var offsetSync = 1;791 // console.log("Function Calls", funcs);792 // console.log("Results",results);793 // console.log("Arguments",argList);794 //Make sure we called the proper test-driver functions795 assert.deepEqual(expectedFunctionList,funcs);796 //Make sure the results array's are what we expected797 for(i = 0; i < expectedResultList.length; i++) {798 for(j = 0; j < expectedResultList[i].length; j++) {799 assert.equal(expectedResultList[i][j],results[i][j]);800 }801 }802 done();803 });804 },805 /**806 * This test tests the LJM_eWriteName, LJM_eWriteAddress,807 * LJM_eWriteNameString, and LJM_eWriteAddressString asynchronous function808 * calls of LJM.809 * @param {[type]} test The test object.810 */811 testWrite: function(test) {812 //Configure running-engines813 asyncRun.config(dev, null);814 syncRun.config(dev, null);815 //Create test-variables816 var testList = [817 'write(1000,2.5)',818 'write("DAC0",2.5)',819 'write(60500,"Mine")',820 'write("DEVICE_NAME_DEFAULT","Mine")'821 ];822 //Expected info combines both sync & async823 var expectedFunctionList = [824 'LJM_eWriteAddress',825 'LJM_eWriteName',826 'LJM_eWriteAddressString',827 'LJM_eWriteNameString',828 'LJM_eWriteAddressAsync',829 'LJM_eWriteNameAsync',830 'LJM_eWriteAddressStringAsync',831 'LJM_eWriteNameStringAsync',832 ];833 //Expected info combines both sync & async834 var expectedResultList = [835 0,0,0,0, //Return vars for sync836 'SUCCESS','SUCCESS','SUCCESS','SUCCESS', //Return vars for async837 ];838 //Run the desired commands839 syncRun.run(testList);840 asyncRun.run(testList,841 function(res) {842 //Error843 }, function(res) {844 //Success845 var funcs = fakeDriver.getLastFunctionCall();846 var results = asyncRun.getResults();847 var argList = fakeDriver.getArgumentsList();848 var i,j;849 var offsetSync = 1;850 // console.log("Function Calls", funcs);851 // console.log("Results",results);852 //console.log("Arguments",argList);853 //Make sure we called the proper test-driver functions854 assert.deepEqual(expectedFunctionList,funcs);855 //Make sure we get the proper results back856 assert.deepEqual(expectedResultList,results);857 done();858 });859 },860 /**861 * This test tests the device's capability to fail gracefully on write862 * function calls.863 *864 * @param {[type]} test The test object.865 */866 testWriteFail: function(test) {867 //Force the driver to produce an error code868 var erCode = 1;869 fakeDriver.setExpectedResult(erCode);870 //Configure running-engines871 asyncRun.config(dev, null);872 syncRun.config(dev, null);873 //Create test-variables874 var testList = [875 'write(-1,2.5)',//Test for invalid address876 'write("AIN999",2.5)',//Test for invalid name877 'write(0,2.5)',//Test for Read only address-number878 'write("AIN0",2.5)',//Test for read only address-n.879 'write(1000,2.5)',//Test for driver-reported errors880 'write("DAC0",2.5)',//Test for driver-reported errors881 'write(60500,"Mine")',//Test for driver-reported errors882 'write("DEVICE_NAME_DEFAULT","Mine")',//again...883 ];884 //Expected info combines both sync & async885 var expectedFunctionList = [886 'LJM_eWriteAddress',887 'LJM_eWriteName',888 'LJM_eWriteAddressString',889 'LJM_eWriteNameString',890 'LJM_eWriteAddressAsync',891 'LJM_eWriteNameAsync',892 'LJM_eWriteAddressStringAsync',893 'LJM_eWriteNameStringAsync',894 ];895 //Expected info combines both sync & async896 var expectedResultList = [897 'Invalid Address',898 'Invalid Address',899 'Invalid Write Attempt',900 'Invalid Write Attempt',901 erCode,902 erCode,903 erCode,904 erCode,905 'Invalid Address',906 'Invalid Address',907 'Invalid Write Attempt',908 'Invalid Write Attempt',909 erCode,910 erCode,911 erCode,912 erCode,913 ];914 //Run the desired commands915 syncRun.run(testList);916 asyncRun.run(testList,917 function(res) {918 //Error919 }, function(res) {920 //Success921 var funcs = fakeDriver.getLastFunctionCall();922 var results = asyncRun.getResults();923 var argList = fakeDriver.getArgumentsList();924 var i,j;925 var offsetSync = 1;926 // console.log("Function Calls", funcs);927 // console.log("Results",results);928 //console.log("Arguments",argList);929 //Make sure we called the proper test-driver functions930 assert.deepEqual(expectedFunctionList,funcs);931 //Make sure we get the proper results back932 assert.deepEqual(expectedResultList,results);933 done();934 });935 },936 /**937 * This test tests the LJM_eWriteNames, and LJM_eWriteAddresses asynchronous938 * function calls of LJM.939 * @param {[type]} test The test object.940 */941 testWriteMany: function(test) {942 //Configure running-engines943 asyncRun.config(dev, null);944 syncRun.config(dev, null);945 var numAddresses = [2, 2, 2, 2];946 //Create test-variables947 var writtenValuesList = [2.5,2.5];948 var addressesList = [1000,1002];949 var typesList = [3,3];950 var namesList = ["DAC0","DAC1"];951 var testList = [952 'writeMany([1000,1002],[2.5,2.5])',953 'writeMany(["DAC0","DAC1"],[2.5,2.5])',954 ];955 //Expected info combines both sync & async956 var expectedFunctionList = [957 'LJM_eWriteAddresses',958 'LJM_eWriteNames',959 'LJM_eWriteAddressesAsync',960 'LJM_eWriteNamesAsync',961 ];962 //Expected info combines both sync & async963 var expectedResultList = [964 0,0,965 'SUCCESS','SUCCESS',966 ];967 //Run the desired commands968 syncRun.run(testList);969 asyncRun.run(testList,970 function(res) {971 //Error972 }, function(res) {973 //Success974 var funcs = fakeDriver.getLastFunctionCall();975 var results = asyncRun.getResults();976 var argList = fakeDriver.getArgumentsList();977 var i,j;978 var offsetSync = 1;979 // console.log("Function Calls", funcs);980 // console.log("Results",results);981 // console.log("Arguments",argList);982 //Test to make sure the proper functions were called983 assert.deepEqual(expectedFunctionList,funcs);984 //test to make sure the proper results were acquired985 assert.deepEqual(expectedResultList,results);986 var paramsDict = {987 'handle': [null, null, null, null],988 'length': numAddresses,989 'addresses': [addressesList,addressesList],990 'types': [typesList,typesList],991 'values': [writtenValuesList, writtenValuesList, writtenValuesList, writtenValuesList],992 'error': [4, 4, 4, 4],993 'callback': [null, null],994 'names': [namesList, namesList],995 };996 var checker = callSequenceChecker.createCallSequenceChecker(997 expectedFunctionList,998 paramsDict999 );1000 checker(test, funcs, argList.slice(1,argList.length));1001 done();1002 });1003 },1004 testWriteManyFail: function(test) {1005 //Force the driver to produce an error code1006 var erCode = 1;1007 fakeDriver.setExpectedResult(erCode);1008 //Configure running-engines1009 asyncRun.config(dev, null);1010 syncRun.config(dev, null);1011 var numAddresses = 2;1012 //Create test-variables1013 var testList = [1014 'writeMany([0,2],[2.5,2.5])',1015 'writeMany([-1,2],[2.5,2.5])',1016 'writeMany(["AIN0","AIN2"],[2.5,2.5])',1017 'writeMany(["AIN999","AIN2"],[2.5,2.5])',1018 ];1019 //Expected info combines both sync & async1020 var expectedFunctionList = [1021 'LJM_eWriteNames',1022 'LJM_eWriteNames',1023 'LJM_eWriteNamesAsync',1024 'LJM_eWriteNamesAsync'1025 ];1026 //Expected info combines both sync & async1027 var expectedResultList = [1028 { retError: 'Invalid Write Attempt', errFrame: 0 },1029 { retError: 'Invalid Address', errFrame: 0 },1030 { retError: 1, errFrame: 0 },1031 { retError: 1, errFrame: 0 },1032 { retError: 'Invalid Read Attempt', errFrame: 0 },1033 { retError: 'Invalid Address', errFrame: 0 },1034 { retError: 1, errFrame: 0 },1035 { retError: 1, errFrame: 0 }1036 ];1037 //Run the desired commands1038 syncRun.run(testList);1039 asyncRun.run(testList,1040 function(res) {1041 //Error1042 }, function(res) {1043 //Success1044 var funcs = fakeDriver.getLastFunctionCall();1045 var results = asyncRun.getResults();1046 var argList = fakeDriver.getArgumentsList();1047 var i,j;1048 var offsetSync = 1;1049 // console.log("Function Calls", funcs);1050 // console.log("Results",results);1051 // console.log("Arguments",argList);1052 //Test to make sure the proper functions were called1053 assert.deepEqual(expectedFunctionList,funcs);1054 //test to make sure the proper results were acquired1055 assert.deepEqual(expectedResultList,results);1056 done();1057 });1058 },1059 /**1060 * This test tests the LJM_eAddresses, and LJM_eNames asynchronous function1061 * calls of LJM.1062 * @param {[type]} test [description]1063 */1064 testRWMany: function(test) {1065 var highestReadVal = 9;1066 fakeDriver.setResultArg(highestReadVal);1067 //Configure running-engines1068 asyncRun.config(dev, null);1069 syncRun.config(dev, null);1070 var numAddresses = 2;1071 //Create test-variables1072 //rwMany(numFrames,addresses,directions,numValues,values1073 var testList = [1074 'rwMany([0,2],[0,0],[1,1],[null,null])', // #11075 'rwMany(["AIN0","AIN2"],[0,0],[1,1],[null,null])', // #21076 'rwMany([0,2,1000],[0,0,1],[1,1,1],[null,null,2.5])', // #31077 'rwMany([0,1000],[0,1],[2,1],[null,null,2.5])', // #41078 'rwMany([0,1000],[0,1],[1,1],[null,2.5])', // #51079 'rwMany([1000,0],[1,0],[1,1],[2.5,null])', // #61080 'rwMany([1000,0],[1,0],[2,1],[2.5,2.5,null])', // #71081 'rwMany(["DAC0","AIN0"],[1,0],[2,2],[2.5,2.5,null,null])', // #81082 'rwMany([5120],[1],[6],[0x11,0x00,0xDE,0xAD,0xBE,0xEF])', // #91083 'rwMany(["AIN0"],[0],[6],[0x11,0x00,0xDE,0xAD,0xBE,0xEF])' // #101084 ];1085 //Expected info combines both sync & async1086 var expectedFunctionList = [1087 //Synchronous Results:1088 'LJM_eAddresses', // #11089 'LJM_eNames', // #21090 'LJM_eAddresses', // #31091 'LJM_eAddresses', // #41092 'LJM_eAddresses', // #51093 'LJM_eAddresses', // #61094 'LJM_eAddresses', // #71095 'LJM_eNames', // #81096 'LJM_eAddresses', // #91097 'LJM_eNames', // #101098 //Asynchronous Results:1099 'LJM_eAddressesAsync', // #11100 'LJM_eNamesAsync', // #21101 'LJM_eAddressesAsync', // #31102 'LJM_eAddressesAsync', // #41103 'LJM_eAddressesAsync', // #51104 'LJM_eAddressesAsync', // #61105 'LJM_eAddressesAsync', // #71106 'LJM_eNamesAsync', // #81107 'LJM_eAddressesAsync', // #91108 'LJM_eNamesAsync', // #101109 ];1110 //Expected info combines both sync & async1111 var expectedResultList = [1112 //Synchronous Results:1113 [ 9, 8 ],1114 [ 9, 8 ],1115 [ 9, 8 ],1116 [ 9, 8 ],1117 [ 9 ],1118 [ 8 ],1119 [ 7 ],1120 [ 7, 6 ],1121 [],1122 [ 9, 8, 7, 6, 5, 4 ],1123 //Asynchronous Results:1124 [ 9, 8 ],1125 [ 9, 8 ],1126 [ 9, 8 ],1127 [ 9, 8 ],1128 [ 9 ],1129 [ 8 ],1130 [ 7 ],1131 [ 7, 6 ],1132 [],1133 [ 9, 8, 7, 6, 5, 4 ]1134 ];1135 //Run the desired comman1136 // console.log('Starting Sync');1137 syncRun.run(testList);1138 // console.log('Starting Async');1139 asyncRun.run(testList,1140 function(res) {1141 console.log('errorReported');1142 //Error1143 }, function(res) {1144 // console.log('finisned');1145 //Success1146 var funcs = fakeDriver.getLastFunctionCall();1147 var results = asyncRun.getResults();1148 var argList = fakeDriver.getArgumentsList();1149 var i,j;1150 var offsetSync = 1;1151 // console.log("Function Calls", funcs);1152 // console.log("Results",results);1153 var tNum = 0;1154 // console.log("Arguments",argList.slice(testList.length-tNum,testList.length+1-tNum));1155 // console.log("Arguments",argList.slice(2*testList.length-tNum,2*testList.length+1-tNum));1156 // console.log('lenOrig',argList.length)1157 // console.log('lenNew',argList.slice(1,argList.length).length)1158 // ljmArgs = argList.slice(1+testList.length,2+testList.length);1159 //console.log('LJM-Args',argList)1160 //Test to make sure the proper functions were called1161 expectedFunctionList.forEach(function(element, index, array) {1162 // console.log(element,funcs[index]);1163 assert.deepEqual(element,funcs[index]);1164 });1165 assert.deepEqual(expectedFunctionList,funcs);1166 //test to make sure the proper results were acquired1167 expectedResultList.forEach(function(element, index, array) {1168 // console.log(element,results[index]);1169 assert.deepEqual(element,results[index]);1170 });1171 assert.deepEqual(expectedResultList,results);1172 done();1173 });1174 },1175 readUINT64: function(test){1176 // asyncRun.config(dev, driver,driver_const);1177 // syncRun.config(dev, driver,driver_const);1178 //Configure running-engines1179 asyncRun.config(dev, null);1180 syncRun.config(dev, null);1181 //Create test-variables1182 var testList = [1183 'readUINT64("WIFI_MAC")',1184 ];1185 //Expected function list:1186 var expectedFunctionList = [1187 'readUINT64',1188 'readUINT64',1189 ];1190 //Run the desired commands1191 syncRun.run(testList,false,false);1192 asyncRun.run(testList,1193 function(res) {1194 console.log('Error',res);1195 }, function(res) {1196 //Report that test finished1197 done();1198 },false,false1199 );1200 },1201 'streaming': function(test) {1202 //Configure running-engines1203 asyncRun.config(dev, null);1204 syncRun.config(dev, null);1205 var testList = [1206 'streamStart(100, ["AIN0"], 1000)',1207 'streamRead()',1208 'streamStop()'1209 ];1210 var callbackIndex = [4,5,4,1];1211 var bufferIndicies = [1212 null,1213 [3,4],1214 [1,2,3],1215 null1216 ];1217 var resultBufferLength = 100 * 8;1218 var bufferSizes = [1219 null,1220 [4,8],1221 [resultBufferLength,4,4],1222 null1223 ];1224 var expectedFunctionList = [1225 'LJM_eStreamStartAsync',1226 'LJM_eStreamReadAsync',1227 'LJM_eStreamStopAsync',1228 // 'LJM_CloseAsync'1229 ];1230 asyncRun.run(testList,1231 function(err) {1232 console.log('Error', err);1233 }, function(res) {1234 // Test to make sure the appropriate LJM functions were called1235 var funcs = fakeDriver.getLastFunctionCall();1236 assert.deepEqual(funcs, expectedFunctionList);1237 // Test to make sure that the functions were called with the1238 // appropriate arguments1239 var argList = fakeDriver.getArgumentsList();1240 var msg = 'argument descrepency, console.log(argList) for details.';1241 argList.forEach(function(argI, i) {1242 // Test for callback function locations1243 assert.strictEqual(typeof(argI[callbackIndex[i]]), 'function', msg);1244 // Test for buffer indicies1245 if(bufferIndicies[i]) {1246 bufferIndicies[i].forEach(function(bufferIndicy, j) {1247 var type = Buffer.isBuffer(argI[bufferIndicy]);1248 assert.strictEqual(type, true, msg);1249 var size = argI[bufferIndicy].length;1250 var expectedSize = bufferSizes[i][j];1251 assert.strictEqual(size, expectedSize, msg);1252 });1253 }1254 });1255 var results = asyncRun.getResults();1256 msg = 'results descrepency';1257 assert.strictEqual(results.length, 3, msg);1258 var tRes = results[1];1259 var tResKeys = [1260 'rawData',1261 'deviceBacklog',1262 'ljmBacklog',1263 'numVals',1264 'scansPerRead',1265 'dataOffset',1266 'time',1267 'timeIncrement',1268 'numAddresses',1269 'scanList'1270 ];1271 assert.deepEqual(Object.keys(tRes), tResKeys, msg);1272 assert.strictEqual(tRes.rawData.length, resultBufferLength, msg);1273 // console.log("HERE!");1274 // console.log(results);1275 // console.log(argList);1276 done();1277 }, false, false);1278 },1279 readArray: function(test){1280 // asyncRun.config(dev, driver,driver_const);1281 // syncRun.config(dev, driver,driver_const);1282 //Configure running-engines1283 asyncRun.config(dev, null);1284 syncRun.config(dev, null);1285 //Create test-variables1286 var testList = [1287 'readArray("LUA_DEBUG_DATA", 10)',1288 'readArray("AIN0", 10)',1289 ];1290 var successData = function(){1291 var str = 'DEADBEEF\r\n';1292 var len = str.length;1293 var retData = [];1294 for(var i = 0; i < len; i++) {1295 retData.push(str.charCodeAt(i));1296 }1297 return retData;1298 }();1299 var errorText = 'Tried to read an array from a register that is not a buffer';1300 var expectedData = [1301 successData,1302 ljm_modbus_map.errorsByName.LJN_INVALID_IO_ATTEMPT.error,1303 successData,1304 ljm_modbus_map.errorsByName.LJN_INVALID_IO_ATTEMPT.error1305 ];1306 //Expected function list:1307 var expectedFunctionList = [1308 'LJM_eReadAddressArray',1309 'LJM_eReadAddressArrayAsync',1310 ];1311 //Run the desired commands1312 syncRun.run(testList,false,false);1313 asyncRun.run(testList,1314 function(res) {1315 console.log('Error',res);1316 }, function(res) {1317 //Report that test finished1318 // console.log('Finished!', res);1319 // Test to make sure the appropriate LJM functions were called1320 var funcs = fakeDriver.getLastFunctionCall();1321 assert.deepEqual(funcs, expectedFunctionList);1322 // Test to make sure the proper results were acquired1323 var results = asyncRun.getResults();1324 assert.deepEqual(results, expectedData);1325 // console.log('Results', results);1326 var argList = fakeDriver.getArgumentsList();1327 var actualArgs = argList.splice(1, argList.length);1328 // console.log('Args', actualArgs[0]);1329 done();1330 },false,false1331 );1332 },1333 writeArray: function(test) {1334 //Configure running-engines1335 asyncRun.config(dev, null);1336 syncRun.config(dev, null);1337 //Create test-variables1338 var testList = [1339 'writeArray("LUA_SOURCE_WRITE", "DEADBEEF\\r\\n")',1340 'writeArray("LUA_SOURCE_WRITE", [68, 69, 65, 68, 66, 69, 69, 70, 13, 10])',1341 'writeArray("LUA_SOURCE_WRITE", "")',1342 'writeArray("LUA_SOURCE_WRITE", [])',1343 ];1344 var successData = function(){1345 var str = 'DEADBEEF\r\n';1346 var len = str.length;1347 var retData = [];1348 for(var i = 0; i < len; i++) {1349 retData.push(str.charCodeAt(i));1350 }1351 return retData;1352 }();1353 var expectedData = [1354 successData,successData,[],[],1355 successData,successData,[],[]1356 ];1357 //Expected function list:1358 var expectedFunctionList = [1359 'LJM_eWriteAddressArray',1360 'LJM_eWriteAddressArray',1361 'LJM_eWriteAddressArray',1362 'LJM_eWriteAddressArray',1363 'LJM_eWriteAddressArrayAsync',1364 'LJM_eWriteAddressArrayAsync',1365 'LJM_eWriteAddressArrayAsync',1366 'LJM_eWriteAddressArrayAsync',1367 ];1368 var interpretWriteArrayData = function(handle, address, type, numValues, aValues) {1369 var data = [];1370 var offset = 0;1371 for(var i = 0; i < numValues; i ++) {1372 data.push(aValues.readDoubleLE(offset));1373 offset += 8;1374 }1375 return data;1376 };1377 var interpretFunctionArgs = function(functionArgs, index) {1378 var argArray = [];1379 var keys = Object.keys(functionArgs);1380 keys.forEach(function(key) {1381 argArray.push(functionArgs[key]);1382 });1383 var retData = interpretWriteArrayData.apply(this, argArray);1384 var expectedRetData = expectedData[index];1385 assert.deepEqual(retData, expectedRetData, 'written data was not encoded properly');1386 };1387 //Run the desired commands1388 syncRun.run(testList,false,false);1389 asyncRun.run(testList,1390 function(res) {1391 console.log('Error',res);1392 }, function(res) {1393 //Report that test finished1394 // console.log('Finished!', res);1395 // Test to make sure the appropriate LJM functions were called1396 var funcs = fakeDriver.getLastFunctionCall();1397 // console.log('funcs:', funcs);1398 assert.deepEqual(funcs, expectedFunctionList);1399 var argList = fakeDriver.getArgumentsList();1400 var actualArgs = argList.splice(1, argList.length);1401 // console.log('Args', actualArgs[0]);1402 actualArgs.forEach(interpretFunctionArgs);1403 // Test to make sure the proper results were acquired1404 var results = asyncRun.getResults();1405 // console.log('results:', results);1406 // assert.deepEqual(results, expectedData);1407 done();1408 },false,false1409 );1410 },1411 /**1412 * This test tests the LJM_IsAuth synchronous and1413 * LJM_IsAuth asynchronous function calls of LJM.1414 * @param {[type]} test The test object.1415 */1416 IsAuthorized: function(test) {1417 //Configure running-engines1418 asyncRun.config(dev, null);1419 syncRun.config(dev, null);1420 //Create test-variables1421 var testList = [1422 'isAuthorized()',1423 ];1424 //Expected info combines both sync & async1425 var expectedFunctionList = [1426 'LJM_IsAuth',1427 'LJM_IsAuthAsync',1428 ];1429 //Run the desired commands1430 syncRun.run(testList);1431 asyncRun.run(testList,1432 function(res) {1433 //Error1434 }, function(res) {1435 //Success1436 var funcs = fakeDriver.getLastFunctionCall();1437 var results = asyncRun.getResults();1438 var argList = fakeDriver.getArgumentsList();1439 var i,j;1440 var offsetSync = 1;1441 // console.log("Function Calls", funcs);1442 // console.log("Results",results);1443 // console.log("Arguments",argList);1444 //Make sure we called the proper test-driver functions1445 assert.deepEqual(expectedFunctionList,funcs);1446 //Make sure we get the proper results back1447 // assert.deepEqual(expectedResultList,results);1448 done();1449 });1450 },1451 /**1452 * This test tests the asynchronous function call of LJM.1453 * @param {[type]} test The test object.1454 *1455 * DEPRECIATED IN LJM 2.46????????? skipping for now1456 */1457 // testResetConnection: function(test) {1458 // done();1459 // }...

Full Screen

Full Screen

DriverProvider.test.js

Source:DriverProvider.test.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3require("jest");4const Sinon = require("sinon");5const NajsBinding = require("najs-binding");6const DriverProvider_1 = require("../../lib/providers/DriverProvider");7const DriverProviderFacade_1 = require("../../lib/facades/global/DriverProviderFacade");8class FakeDriver {9 createStaticMethods() { }10}11FakeDriver.className = 'FakeDriver';12describe('DriverProvider', function () {13 it('implements IAutoload under name "NajsEloquent.Provider.DriverProvider"', function () {14 const instance = new DriverProvider_1.DriverProvider();15 expect(instance.getClassName()).toEqual('NajsEloquent.Provider.DriverProvider');16 });17 describe('.register()', function () {18 it('registers class to ClassRegistry by using najs-binding if the driver is a function', function () {19 const registerSpy = Sinon.spy(NajsBinding, 'register');20 const chainable = DriverProviderFacade_1.DriverProvider.register(FakeDriver, 'fake');21 expect(chainable === DriverProviderFacade_1.DriverProvider).toBe(true);22 expect(registerSpy.calledWith(FakeDriver)).toBe(true);23 expect(NajsBinding.ClassRegistry.has(FakeDriver.className)).toBe(true);24 expect(DriverProviderFacade_1.DriverProvider['drivers']['fake']).toEqual({25 driverClassName: 'FakeDriver',26 isDefault: false27 });28 DriverProviderFacade_1.DriverProvider.register(FakeDriver, 'fake', true);29 expect(DriverProviderFacade_1.DriverProvider['drivers']['fake']).toEqual({30 driverClassName: 'FakeDriver',31 isDefault: true32 });33 registerSpy.restore();34 });35 it('registers class to ClassRegistry by using najs-binding if the driver is a function', function () {36 const registerSpy = Sinon.spy(NajsBinding, 'register');37 DriverProviderFacade_1.DriverProvider.register('FakeDriver', 'fake');38 expect(registerSpy.calledWith(FakeDriver)).toBe(false);39 registerSpy.restore();40 });41 });42 describe('protected .findDefaultDriver()', function () {43 it('returns a empty string if there is no drivers registered', function () {44 DriverProviderFacade_1.DriverProvider['drivers'] = {};45 expect(DriverProviderFacade_1.DriverProvider['findDefaultDriver']()).toEqual('');46 });47 it('returns a the first driver if there is no item with isDefault = true', function () {48 DriverProviderFacade_1.DriverProvider['drivers'] = {49 'test-1': {50 driverClassName: 'Test1',51 isDefault: false52 },53 'test-2': {54 driverClassName: 'Test2',55 isDefault: false56 }57 };58 expect(DriverProviderFacade_1.DriverProvider['findDefaultDriver']()).toEqual('Test1');59 });60 it('returns a driver with isDefault = true', function () {61 DriverProviderFacade_1.DriverProvider['drivers'] = {62 'test-1': {63 driverClassName: 'Test1',64 isDefault: false65 },66 fake: {67 driverClassName: 'FakeDriver',68 isDefault: true69 },70 'test-2': {71 driverClassName: 'Test2',72 isDefault: false73 }74 };75 expect(DriverProviderFacade_1.DriverProvider['findDefaultDriver']()).toEqual('FakeDriver');76 });77 });78 describe('protected .createDriver()', function () {79 it('calls "najs-binding".make() to create an instance of driver, model is passed in param', function () {80 const model = {};81 const makeStub = Sinon.stub(NajsBinding, 'make');82 makeStub.callsFake(() => ({83 createStaticMethods() { }84 }));85 DriverProviderFacade_1.DriverProvider['createDriver'](model, 'DriverClass');86 expect(makeStub.calledWith('DriverClass', [model]));87 makeStub.restore();88 });89 it('just create instance of driver 1 time', function () {90 const model = {};91 const driver = {};92 DriverProviderFacade_1.DriverProvider['driverInstances']['test'] = driver;93 const result = DriverProviderFacade_1.DriverProvider['createDriver'](model, 'test');94 expect(driver === result).toBe(true);95 expect(DriverProviderFacade_1.DriverProvider['createDriver'](model, 'test') === result).toBe(true);96 });97 });98 describe('.findDriverClassName()', function () {99 it('returns .findDefaultDriver() if there is no binding of model', function () {100 const findDefaultDriverSpy = Sinon.spy(DriverProviderFacade_1.DriverProvider, 'findDefaultDriver');101 DriverProviderFacade_1.DriverProvider.findDriverClassName('not-bind-yet');102 expect(DriverProviderFacade_1.DriverProvider.findDriverClassName('not-bind-yet')).toEqual('FakeDriver');103 expect(findDefaultDriverSpy.called).toBe(true);104 findDefaultDriverSpy.restore();105 });106 it('returns .findDefaultDriver() if driver of model is not exists', function () {107 const findDefaultDriverSpy = Sinon.spy(DriverProviderFacade_1.DriverProvider, 'findDefaultDriver');108 DriverProviderFacade_1.DriverProvider.bind('bound-but-not-found', 'not-found');109 DriverProviderFacade_1.DriverProvider.findDriverClassName('bound-but-not-found');110 expect(findDefaultDriverSpy.called).toBe(true);111 findDefaultDriverSpy.restore();112 });113 it('returns driverClassName if has binding and driver exists', function () {114 const findDefaultDriverSpy = Sinon.spy(DriverProviderFacade_1.DriverProvider, 'findDefaultDriver');115 DriverProviderFacade_1.DriverProvider.bind('model', 'fake');116 expect(DriverProviderFacade_1.DriverProvider.findDriverClassName('model')).toEqual('FakeDriver');117 expect(findDefaultDriverSpy.called).toBe(false);118 findDefaultDriverSpy.restore();119 });120 });121 describe('.bind()', function () {122 it('simply assigns driver and model to private binding variable', function () {123 DriverProviderFacade_1.DriverProvider['binding'] = {};124 expect(DriverProviderFacade_1.DriverProvider['binding']).toEqual({});125 const chainable = DriverProviderFacade_1.DriverProvider.bind('model', 'driver');126 expect(chainable === DriverProviderFacade_1.DriverProvider).toBe(true);127 expect(DriverProviderFacade_1.DriverProvider['binding']).toEqual({ model: 'driver' });128 DriverProviderFacade_1.DriverProvider.bind('model', 'driver-override');129 expect(DriverProviderFacade_1.DriverProvider['binding']).toEqual({ model: 'driver-override' });130 });131 });132 describe('.has()', function () {133 it('returns false if the driver is not register under any name', function () {134 class AnyDriver {135 }136 AnyDriver.className = 'AnyDriver';137 expect(DriverProviderFacade_1.DriverProvider.has(AnyDriver)).toBe(false);138 });139 it('returns true if the given driver is registered under any name', function () {140 class RegisteredDriver {141 }142 RegisteredDriver.className = 'RegisteredDriver';143 DriverProviderFacade_1.DriverProvider.register(RegisteredDriver, 'any');144 expect(DriverProviderFacade_1.DriverProvider.has(RegisteredDriver)).toBe(true);145 });146 });147 describe('.create()', function () {148 it('creates a driver instance with class name provided by .findDriverClassName()', function () {149 const createDriverSpy = Sinon.spy(DriverProviderFacade_1.DriverProvider, 'createDriver');150 const findDriverClassNameSpy = Sinon.spy(DriverProviderFacade_1.DriverProvider, 'findDriverClassName');151 class Model {152 }153 Model.className = 'Test';154 const model = new Model();155 const instance = DriverProviderFacade_1.DriverProvider.create(model);156 expect(findDriverClassNameSpy.calledWith(model)).toBe(true);157 expect(createDriverSpy.calledWith(model, 'FakeDriver')).toBe(true);158 expect(instance).toBeInstanceOf(FakeDriver);159 findDriverClassNameSpy.restore();160 createDriverSpy.restore();161 });162 });...

Full Screen

Full Screen

adapterSpec.js

Source:adapterSpec.js Github

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var common = require('./common.js');3/**4 * Tests for the WebDriverJS Jasmine-Node Adapter. These tests use5 * WebDriverJS's control flow and promises without setting up the whole6 * webdriver.7 */8var fakeDriver = common.getFakeDriver();9describe('webdriverJS Jasmine adapter plain', function() {10 it('should pass normal synchronous tests', function() {11 expect(true).toBe(true);12 });13 it('should allow an empty it block and mark as pending');14 xit('should allow a spec marked as pending with xit', function() {15 expect(true).toBe(false);16 });17});18describe('context', function() {19 beforeEach(function() {20 this.foo = 0;21 });22 it('can use the `this` to share state', function() {23 expect(this.foo).toEqual(0);24 this.bar = 'test pollution?';25 });26 it('prevents test pollution by having an empty `this` created for the next spec', function() {27 expect(this.foo).toEqual(0);28 expect(this.bar).toBe(undefined);29 });30});31describe('webdriverJS Jasmine adapter', function() {32 // Shorten this and you should see tests timing out.33 jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;34 var beforeEachMsg;35 beforeEach(function() {36 jasmine.addMatchers(common.getMatchers());37 });38 beforeEach(function() {39 fakeDriver.setUp().then(function(value) {40 beforeEachMsg = value;41 });42 });43 afterEach(function() {44 beforeEachMsg = '';45 });46 it('should only allow initializing once', function() {47 expect(require('../index.js').init).toThrow(48 Error('JasmineWd already initialized when init() was called'));49 });50 it('should pass normal synchronous tests', function() {51 expect(true).toEqual(true);52 });53 it('should compare a promise to a primitive', function() {54 expect(fakeDriver.getValueA()).toEqual('a');55 expect(fakeDriver.getValueB()).toEqual('b');56 });57 it('beforeEach should wait for control flow', function() {58 expect(beforeEachMsg).toEqual('setup done');59 });60 it('should wait till the expect to run the flow', function() {61 var promiseA = fakeDriver.getValueA();62 expect(common.isPending(promiseA)).toBe(true);63 expect(promiseA).toEqual('a');64 expect(common.isPending(promiseA)).toBe(true);65 });66 it('should compare a promise to a promise', function() {67 expect(fakeDriver.getValueA()).toEqual(fakeDriver.getOtherValueA());68 });69 it('should still allow use of the underlying promise', function() {70 var promiseA = fakeDriver.getValueA();71 promiseA.then(function(value) {72 expect(value).toEqual('a');73 });74 });75 it('should allow scheduling of tasks', function() {76 fakeDriver.sleep(300);77 expect(fakeDriver.getValueB()).toEqual('b');78 });79 it('should allow the use of custom matchers', function() {80 expect(500).toBeLotsMoreThan(3);81 expect(fakeDriver.getBigNumber()).toBeLotsMoreThan(33);82 expect(fakeDriver.getBigNumber()).toBeLotsMoreThan(fakeDriver.getSmallNumber());83 expect(fakeDriver.getSmallNumber()).not.toBeLotsMoreThan(fakeDriver.getBigNumber());84 });85 it('should allow custom matchers to return a promise', function() {86 expect(fakeDriver.getDisplayedElement()).toBeDisplayed();87 expect(fakeDriver.getHiddenElement()).not.toBeDisplayed();88 });89 it('should pass multiple arguments to matcher', function() {90 // Passing specific precision91 expect(fakeDriver.getDecimalNumber()).toBeCloseTo(3.1, 1);92 expect(fakeDriver.getDecimalNumber()).not.toBeCloseTo(3.1, 2);93 // Using default precision (2)94 expect(fakeDriver.getDecimalNumber()).not.toBeCloseTo(3.1);95 expect(fakeDriver.getDecimalNumber()).toBeCloseTo(3.14);96 });97 it('should allow iterating through arrays', function() {98 // This is a convoluted test which shows a real issue which99 // cropped up in version changes to the selenium-webdriver module.100 // See https://github.com/angular/protractor/pull/2263101 var checkTexts = function(webElems) {102 var texts = webElems.then(function(arr) {103 var results = arr.map(function(webElem) {104 return webElem.getText();105 });106 return webdriver.promise.all(results);107 });108 expect(texts).not.toContain('e');109 return true;110 };111 fakeDriver.getValueList().then(function(list) {112 var result = list.map(function(webElem) {113 var webElemsPromise = webdriver.promise.when(webElem).then(function(webElem) {114 return [webElem];115 });116 return webdriver.promise.fullyResolved(checkTexts(webElemsPromise));117 });118 return webdriver.promise.all(result);119 });120 });121 describe('not', function() {122 it('should still pass normal synchronous tests', function() {123 expect(4).not.toEqual(5);124 });125 it('should compare a promise to a primitive', function() {126 expect(fakeDriver.getValueA()).not.toEqual('b');127 });128 it('should compare a promise to a promise', function() {129 expect(fakeDriver.getValueA()).not.toEqual(fakeDriver.getValueB());130 });131 it('should allow custom matchers to return a promise when actual is not a promise', function() {132 expect(fakeDriver.displayedElement).toBeDisplayed();133 expect(fakeDriver.hiddenElement).not.toBeDisplayed();134 });135 });136 it('should throw an error with a WebElement actual value', function() {137 var webElement = new webdriver.WebElement(fakeDriver, 'idstring');138 expect(function() {139 expect(webElement).toEqual(4);140 }).toThrow(Error('expect called with WebElement argument, expected a Promise. ' +141 'Did you mean to use .getText()?'));142 });143 it('should pass after the timed out tests', function() {144 expect(fakeDriver.getValueA()).toEqual('a');145 });146 describe('should work for both synchronous and asynchronous tests', function() {147 var x;148 beforeEach(function() {149 x = 0;150 });151 afterEach(function() {152 expect(x).toBe(1);153 });154 it('should execute a synchronous test', function() {155 x = 1;156 });157 it('should execute an asynchronous test', function(done) {158 setTimeout(function(){159 x = 1;160 done();161 }, 500);162 });163 });164 describe('beforeAll and afterAll', function() {165 var asyncValue, setupMsg;166 beforeAll(function(done) {167 setTimeout(function() {168 asyncValue = 5;169 done();170 }, 500);171 });172 beforeAll(function() {173 fakeDriver.setUp().then(function(msg) {174 setupMsg = msg;175 });176 });177 afterAll(function() {178 setupMsg = '';179 });180 it('should have set asyncValue', function() {181 expect(asyncValue).toEqual(5);182 });183 it('should wait for control flow', function() {184 expect(setupMsg).toEqual('setup done');185 });186 });187 describe('it return value', function() {188 var spec1 = it('test1');189 var spec2 = it('test2', function() {});190 var spec3 = it('test3', function() {}, 1);191 it('should return the spec', function() {192 expect(spec1.description).toBe('test1');193 expect(spec2.description).toBe('test2');194 expect(spec3.description).toBe('test3');195 });196 });197 describe('native promises', function() {198 it('should have done argument override return returned promise', function(done) {199 var ret = new Promise(function() {});200 done();201 return ret;202 }); 203 var currentTest = null;204 it('should wait for webdriver events sent from native promise', function() {205 currentTest = 'A';206 return new Promise(function(resolve) {207 setTimeout(function() {208 fakeDriver.sleep(100).then(function() {209 expect(currentTest).toBe('A');210 });211 resolve();212 }, 100);213 });214 });215 it('should not start a test before another finishes', function(done) {216 currentTest = 'B';217 setTimeout(done, 200);218 });219 });...

Full Screen

Full Screen

errorSpec.js

Source:errorSpec.js Github

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var common = require('./common.js');3/**4 * Error tests for the WebDriverJS Jasmine-Node Adapter. These tests use5 * WebDriverJS's control flow and promises without setting up the whole6 * webdriver.7 */8var fakeDriver = common.getFakeDriver();9describe('Timeout cases', function() {10 it('should timeout after 200ms', function(done) {11 expect(fakeDriver.getValueA()).toEqual('a');12 }, 200);13 14 it('should timeout after 300ms', function() {15 fakeDriver.sleep(9999);16 expect(fakeDriver.getValueB()).toEqual('b');17 }, 300);18 it('should pass after the timed out tests', function() {19 expect(true).toEqual(true);20 });21});22describe('things that should fail', function() {23 beforeEach(function() {24 jasmine.addMatchers(common.getMatchers());25 });26 it('should pass errors from done callback', function(done) {27 done.fail('an error from done.fail');28 });29 it('should error asynchronously in promise callbacks', function() {30 fakeDriver.sleep(50).then(function() {31 expect(true).toEqual(false);32 });33 });34 it('should error asynchronously within done callback', function(done) {35 setTimeout(function() {36 expect(false).toEqual(true);37 done();38 }, 200);39 });40 it('should fail normal synchronous tests', function() {41 expect(true).toBe(false);42 });43 it('should fail when an error is thrown', function() {44 throw new Error('I am an intentional error');45 });46 it('should compare a promise to a primitive', function() {47 expect(fakeDriver.getValueA()).toEqual('d');48 expect(fakeDriver.getValueB()).toEqual('e');49 });50 it('should wait till the expect to run the flow', function() {51 var promiseA = fakeDriver.getValueA();52 expect(promiseA.isPending()).toBe(true);53 expect(promiseA).toEqual('a');54 expect(promiseA.isPending()).toBe(false);55 });56 it('should compare a promise to a promise', function() {57 expect(fakeDriver.getValueA()).toEqual(fakeDriver.getValueB());58 });59 it('should still allow use of the underlying promise', function() {60 var promiseA = fakeDriver.getValueA();61 promiseA.then(function(value) {62 expect(value).toEqual('b');63 });64 });65 it('should allow scheduling of tasks', function() {66 fakeDriver.sleep(300);67 expect(fakeDriver.getValueB()).toEqual('c');68 });69 it('should allow the use of custom matchers', function() {70 expect(1000).toBeLotsMoreThan(999);71 expect(fakeDriver.getBigNumber()).toBeLotsMoreThan(1110);72 expect(fakeDriver.getBigNumber()).not.toBeLotsMoreThan(fakeDriver.getSmallNumber());73 expect(fakeDriver.getSmallNumber()).toBeLotsMoreThan(fakeDriver.getBigNumber());74 });75 it('should allow custom matchers to return a promise', function() {76 expect(fakeDriver.getDisplayedElement()).not.toBeDisplayed();77 expect(fakeDriver.getHiddenElement()).toBeDisplayed();78 });79 it('should pass multiple arguments to matcher', function() {80 // Passing specific precision81 expect(fakeDriver.getDecimalNumber()).toBeCloseTo(3.5, 1);82 // Using default precision (2)83 expect(fakeDriver.getDecimalNumber()).toBeCloseTo(3.1);84 expect(fakeDriver.getDecimalNumber()).not.toBeCloseTo(3.14);85 });86 describe('native promises', function() {87 it('should time out if done argument is never called, even if promise is returned',88 function(done) {89 return new Promise(function() {});90 }91 ); 92 var testADone = false;93 it('should handle rejection from native promise', function() {94 return new Promise(function(resolve, reject) {95 setTimeout(function() {96 fakeDriver.sleep(100).then(function() {97 testADone = true;98 });99 reject('Rejected promise');100 }, 100);101 });102 });103 it('should not start a test before another finishes', function(done) {104 expect(testADone).toBe(true); // this test actually passes105 setTimeout(done, 200);106 });107 });...

Full Screen

Full Screen

storage.js

Source:storage.js Github

copy

Full Screen

1const mockExit = jest.spyOn(process, "exit").mockImplementation(() => {2 throw new Error();3});4const mockError = jest.spyOn(console, "error").mockImplementation(() => {});5describe("Storage", () => {6 beforeEach(() => {7 jest.disableAutomock();8 jest.resetModules();9 mockExit.mockClear();10 mockError.mockClear();11 });12 test("loads and initialises driver", async () => {13 require("../config");14 jest.mock("../config", () => {15 return {16 storageDriver: "fakedriver",17 storageOptions: {18 test: true19 }20 };21 });22 jest.mock(23 "../storageDrivers/fakedriver",24 () => {25 return jest.fn().mockImplementation(function fakedriver() {26 this.init = jest.fn();27 return this;28 });29 },30 { virtual: true }31 );32 const fakedriver = require("../storageDrivers/fakedriver");33 const storage = await require("../storage");34 expect(fakedriver).toBeCalledWith({ test: true });35 expect(storage).toBeInstanceOf(fakedriver);36 });37 test("throws an error and exits the process if driver couldn't be loaded", async () => {38 require("../config");39 jest.mock("../config", () => {40 return {41 storageDriver: "missingdriver",42 storageOptions: {43 test: true44 }45 };46 });47 try {48 await require("../storage");49 } catch (e) {}50 expect(mockError).toBeCalledWith(51 "Storage driver missingdriver could not be loaded"52 );53 expect(mockExit).toHaveBeenCalled();54 });55 test("throws an error and exits the process if driver couldn't be initialised", async () => {56 require("../config");57 jest.mock("../config", () => {58 return {59 storageDriver: "errordriver",60 storageOptions: {61 test: true62 }63 };64 });65 jest.mock(66 "../storageDrivers/errordriver",67 () => {68 return jest.fn().mockImplementation(function errordriver() {69 this.init = jest.fn();70 throw new Error();71 return this;72 });73 },74 { virtual: true }75 );76 const errordriver = require("../storageDrivers/errordriver");77 try {78 await require("../storage");79 } catch (e) {}80 expect(errordriver).toBeCalledWith({ test: true });81 expect(mockError).toBeCalledWith(82 "Storage driver errordriver could not be initialised"83 );84 expect(mockExit).toHaveBeenCalled();85 });...

Full Screen

Full Screen

driver.js

Source:driver.js Github

copy

Full Screen

1import B from 'bluebird';2import _ from 'lodash';3import { BaseDriver, errors } from 'appium-base-driver';4import { FakeApp } from './fake-app';5import commands from './commands';6class FakeDriver extends BaseDriver {7 constructor () {8 super();9 this.appModel = null;10 this.curContext = 'NATIVE_APP';11 this.elMap = {};12 this.focusedElId = null;13 this.maxElId = 0;14 this.caps = {};15 this.fakeThing = null;16 this.desiredCapConstraints = {17 app: {18 presence: true,19 isString: true20 }21 };22 }23 async createSession (desiredCaps, requiredCaps, capabilities, otherSessionData = []) {24 // TODO add validation on caps.app that we will get for free from25 // BaseDriver26 // check to see if any other sessions have set uniqueApp. If so, emulate27 // not being able to start a session because of system resources28 for (let d of otherSessionData) {29 if (d.isUnique) {30 throw new errors.SessionNotCreatedError('Cannot start session; another ' +31 'unique session is in progress that requires all resources');32 }33 }34 let [sessionId, caps] = await super.createSession(desiredCaps, requiredCaps, capabilities, otherSessionData);35 this.appModel = new FakeApp();36 if (_.isArray(caps) === true && caps.length === 1) {37 caps = caps[0];38 }39 this.caps = caps;40 await this.appModel.loadApp(caps.app);41 return [sessionId, caps];42 }43 get driverData () {44 return {45 isUnique: !!this.caps.uniqueApp46 };47 }48 async getFakeThing () {49 await B.delay(1);50 return this.fakeThing;51 }52 async setFakeThing (thing) {53 await B.delay(1);54 this.fakeThing = thing;55 return null;56 }57 static newMethodMap = {58 '/session/:sessionId/fakedriver': {59 GET: {command: 'getFakeThing'},60 POST: {command: 'setFakeThing', payloadParams: {required: ['thing']}}61 },62 };63 static fakeRoute (req, res) {64 res.send(JSON.stringify({fakedriver: 'fakeResponse'}));65 }66 static async updateServer (expressApp/*, httpServer*/) { // eslint-disable-line require-await67 expressApp.all('/fakedriver', FakeDriver.fakeRoute);68 }69}70for (let [cmd, fn] of _.toPairs(commands)) {71 FakeDriver.prototype[cmd] = fn;72}...

Full Screen

Full Screen

driver-specs.js

Source:driver-specs.js Github

copy

Full Screen

1// transpile:mocha2import _ from 'lodash';3import chai from 'chai';4import chaiAsPromised from 'chai-as-promised';5import { FakeDriver } from '..';6import { DEFAULT_CAPS } from './helpers';7import { baseDriverUnitTests } from 'appium-base-driver/build/test/basedriver';8chai.use(chaiAsPromised);9chai.should();10// test the same things as for base driver11baseDriverUnitTests(FakeDriver, DEFAULT_CAPS);12describe('FakeDriver', function () {13 it('should not start a session when a unique session is already running', async function () {14 let d1 = new FakeDriver();15 let caps1 = _.clone(DEFAULT_CAPS);16 caps1.uniqueApp = true;17 let [uniqueSession] = await d1.createSession(caps1, {});18 uniqueSession.should.be.a('string');19 let d2 = new FakeDriver();20 let otherSessionData = [d1.driverData];21 await d2.createSession(DEFAULT_CAPS, {}, null, otherSessionData)22 .should.eventually.be.rejectedWith(/unique/);23 await d1.deleteSession(uniqueSession);24 });25 it('should start a new session when another non-unique session is running', async function () {26 let d1 = new FakeDriver();27 let [session1Id] = await d1.createSession(DEFAULT_CAPS, {});28 session1Id.should.be.a('string');29 let d2 = new FakeDriver();30 let otherSessionData = [d1.driverData];31 let [session2Id] = await d2.createSession(DEFAULT_CAPS, {}, null, otherSessionData);32 session2Id.should.be.a('string');33 session1Id.should.not.equal(session2Id);34 await d1.deleteSession(session1Id);35 await d2.deleteSession(session2Id);36 });...

Full Screen

Full Screen

manager.test.js

Source:manager.test.js Github

copy

Full Screen

1'use strict'2const transactionPoolManager = require('../lib/manager')3class FakeDriver {4 make () {5 return this6 }7}8describe('Transaction Pool Manager', () => {9 it('should be an object', () => {10 expect(transactionPoolManager).toBeObject()11 })12 describe('connection', () => {13 it('should be a function', () => {14 expect(transactionPoolManager.connection).toBeFunction()15 })16 it('should return the drive-connection', async () => {17 await transactionPoolManager.makeConnection(new FakeDriver())18 expect(transactionPoolManager.connection()).toBeInstanceOf(FakeDriver)19 })20 it('should return the drive-connection for a different name', async () => {21 await transactionPoolManager.makeConnection(new FakeDriver(), 'testing')22 expect(transactionPoolManager.connection('testing')).toBeInstanceOf(FakeDriver)23 })24 })25 describe('makeConnection', () => {26 it('should be a function', () => {27 expect(transactionPoolManager.makeConnection).toBeFunction()28 })29 })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var fakeDriver = require('appium-base-driver').fakeDriver;2var driver = fakeDriver();3var fakeElement = require('appium-base-driver').fakeElement;4var element = fakeElement();5driver.execute('mobile: scroll', {direction: 'down'});6driver.execute('mobile: scroll', {direction: 'up'});7driver.execute('mobile: scroll', {direction: 'left'});8driver.execute('mobile: scroll', {direction: 'right'});9driver.execute('mobile: swipe', {direction: 'down'});10driver.execute('mobile: swipe', {direction: 'up'});11driver.execute('mobile: swipe', {direction: 'left'});12driver.execute('mobile: swipe', {direction: 'right'});13driver.execute('mobile: pinchClose');14driver.execute('mobile: pinchOpen');15driver.execute('mobile: zoom');16driver.execute('mobile: tap', {x: 10, y: 10});17driver.execute('mobile: tap', {element: element});18driver.execute('mobile: doubleTap', {element: element});19driver.execute('mobile: doubleTap', {x: 10, y: 10});20driver.execute('mobile: longPress', {element: element});21driver.execute('mobile: longPress', {x: 10, y: 10});22driver.execute('mobile: dragFromToForDuration', {duration: 2.0, fromX: 50, fromY: 50, toX: 100, toY: 100});23driver.execute('mobile: dragFromToForDuration', {duration: 2.0, element: element, toX: 100, toY: 100});24driver.execute('mobile: scroll', {direction: 'down'});25driver.execute('mobile: scroll', {direction: 'up'});26driver.execute('mobile: scroll', {direction: 'left'});27driver.execute('mobile: scroll', {direction: 'right'});28driver.execute('mobile: flick', {speed: 1000, xspeed: 1000, yspeed: 1000});29driver.execute('mobile: flick', {element: element, xspeed: 1000, yspeed: 1000});30driver.execute('mobile: shake');31driver.execute('mobile: getDeviceTime');32driver.execute('mobile: launchApp');33driver.execute('mobile: terminate

Full Screen

Using AI Code Generation

copy

Full Screen

1var fakeDriver = require('appium-base-driver').fakeDriver;2var driver = fakeDriver({3 startSession: function (caps) {4 return Promise.resolve();5 },6 stopSession: function () {7 return Promise.resolve();8 }9});10driver.init({}).then(function () {11 console.log('Session started');12 return driver.quit();13}).then(function () {14 console.log('Session stopped');15}).catch(function (err) {16 console.log('Error: ' + err);17});18var fakeDriver = require('appium-base-driver').fakeDriver;19var driver = fakeDriver({20 startSession: function (caps) {21 return Promise.resolve();22 },23 stopSession: function () {24 return Promise.resolve();25 },26 click: function (element) {27 return Promise.resolve();28 }29});30driver.init({}).then(function () {31 console.log('Session started');32 return driver.click();33}).then(function () {34 console.log('Clicked');35 return driver.quit();36}).then(function () {37 console.log('Session stopped');38}).catch(function (err) {39 console.log('Error: ' + err);40});

Full Screen

Using AI Code Generation

copy

Full Screen

1this.fakeDriver = function() {2 this.fakeDriver = function() {3 this.fakeDriver = function() {4 this.fakeDriver = function() {5 this.fakeDriver = function() {6 }7 }8 }9 }10}11this.fakeDriver = function() {12 this.fakeDriver = function() {13 this.fakeDriver = function() {14 this.fakeDriver = function() {15 this.fakeDriver = function() {16 }17 }18 }19 }20}21this.fakeDriver = function() {22 this.fakeDriver = function() {

Full Screen

Using AI Code Generation

copy

Full Screen

1var AppiumBaseDriver = require('appium-base-driver');2var fakeDriver = AppiumBaseDriver.prototype.fakeDriver;3fakeDriver();4var AppiumBaseDriver = require('appium-base-driver');5var fakeDriver = AppiumBaseDriver.prototype.fakeDriver;6fakeDriver();7Your name to display (optional):8Your name to display (optional):9Your name to display (optional):

Full Screen

Using AI Code Generation

copy

Full Screen

1const AppiumBaseDriver = require('appium-base-driver');2const B = require('bluebird');3const fakeDriver = require('appium-fake-driver');4const fakeDriverMethods = fakeDriver.methods;5const fakeDriverArgs = fakeDriver.args;6const EXTENDED_TIMEOUT = 60 * 1000;7class MyDriver extends AppiumBaseDriver {8 constructor (opts) {9 super(opts);10 this.desiredCapConstraints = {11 platformName: {12 },13 };14 this.jwpProxyActive = false;15 }16 async createSession (caps) {17 this.opts = caps;18 await fakeDriverMethods.createSession.call(this, caps);19 return [null, {20 warnings: {},21 }];22 }23 async deleteSession () {24 await fakeDriverMethods.deleteSession.call(this);25 return [null, null];26 }27 async setUrl (url) {28 await fakeDriverMethods.setUrl.call(this, url);29 return [null, null];30 }31 async getUrl () {32 const url = await fakeDriverMethods.getUrl.call(this);33 return [null, url];34 }35 async getTitle () {36 const title = await fakeDriverMethods.getTitle.call(this);37 return [null, title];38 }39 async findElement (strategy, selector) {40 const elementId = await fakeDriverMethods.findElement.call(this, strategy, selector);41 return [null, {ELEMENT: elementId}];42 }43 async findElements (strategy, selector) {44 const elementIds = await fakeDriverMethods.findElements.call(this, strategy, selector);45 return [null, elementIds.map((elementId) => ({ELEMENT: elementId}))];46 }47 async click (elementId) {48 await fakeDriverMethods.click.call(this, elementId);49 return [null, null];50 }51 async clear (elementId) {52 await fakeDriverMethods.clear.call(this, elementId);53 return [null, null];54 }55 async setValue (elementId, value) {56 await fakeDriverMethods.setValue.call(this, elementId, value);

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const _ = require('lodash');3const AppiumDriver = require('appium-base-driver').AppiumDriver;4const FakeDriver = require('./fakeDriver');5const driver = new AppiumDriver();6const fakeDriver = new FakeDriver();7const serverConfig = {8};9const desiredCaps = {10};11async function main () {12 await driver.createSession(desiredCaps, serverConfig);13 await fakeDriver.createSession(desiredCaps, serverConfig);14}15main();16const _ = require('lodash');17const { BaseDriver } = require('appium-base-driver');18const { util } = require('appium-support');19const commands = {};20class FakeDriver extends BaseDriver {21 constructor (opts = {}) {22 super(opts);23 this.locatorStrategies = ['xpath', 'id', 'name', 'class name', 'accessibility id', '-android uiautomator', '-ios uiautomation'];24 this.desiredCapConstraints = {25 platformName: {26 },27 deviceName: {28 },29 app: {30 }31 };32 }33 async createSession (caps) {34 this.caps = _.defaults({}, caps, this.defaultCaps);35 const validationError = util.hasValue(this.validateDesiredCaps(this.caps));36 if (validationError) {37 throw new Error(validationError);38 }39 this.sessionId = util.uuidV4();40 this.opts = Object.assign({}, this.caps, {sessionId: this.sessionId});41 this.setNewCommandTimeout(this.opts.newCommandTimeout);42 this.configureAppiumCommands();43 return [this.sessionId, this.opts];44 }45}46Object.assign(FakeDriver.prototype, commands);47module.exports = FakeDriver;

Full Screen

Using AI Code Generation

copy

Full Screen

1var fakeDriver = require('./fakeDriver.js');2fakeDriver.fakeDriverMethod();3var fakeDriver = {};4fakeDriver.fakeDriverMethod = function() {5 console.log("I am in fakeDriverMethod");6};7module.exports = fakeDriver;

Full Screen

Using AI Code Generation

copy

Full Screen

1await driver.fakeDriverMethod('fakeDriverMethod1', 'fakeDriverMethod2');2await this.fakeDriverMethod('fakeDriverMethod1', 'fakeDriverMethod2');3await this.fakeDriverMethod('fakeDriverMethod1', 'fakeDriverMethod2');4await this.fakeDriverMethod('fakeDriverMethod1', 'fakeDriverMethod2');5await this.fakeDriverMethod('fakeDriverMethod1', 'fakeDriverMethod2');6await this.fakeDriverMethod('fakeDriverMethod1', 'fakeDriverMethod2');

Full Screen

Using AI Code Generation

copy

Full Screen

1var Appium = require('appium');2var fakeDriver = Appium.fakeDriver;3var driver = fakeDriver();4driver.elementByAccessibilityId('someId').click().then(function(){5 console.log('clicked');6});7var Appium = require('appium');8var fakeDriver = Appium.fakeDriver;9var driver = fakeDriver();10driver.elementByAccessibilityId('someId').click().then(function(){11 console.log('clicked');12});13var Appium = require('appium');14var fakeDriver = Appium.fakeDriver;15var driver = fakeDriver();16driver.elementByAccessibilityId('someId').click().then(function(){17 console.log('clicked');18});19var Appium = require('appium');20var fakeDriver = Appium.fakeDriver;21var driver = fakeDriver();22driver.elementByAccessibilityId('someId').click().then(function(){23 console.log('clicked');24});25var Appium = require('appium');26var fakeDriver = Appium.fakeDriver;27var driver = fakeDriver();28driver.elementByAccessibilityId('someId').click().then(function(){29 console.log('clicked');30});31var Appium = require('appium');32var fakeDriver = Appium.fakeDriver;33var driver = fakeDriver();34driver.elementByAccessibilityId('someId').click().then(function(){35 console.log('clicked');36});37var Appium = require('appium');38var fakeDriver = Appium.fakeDriver;39var driver = fakeDriver();40driver.elementByAccessibilityId('someId').click().then(function(){41 console.log('clicked');42});43var Appium = require('appium');44var fakeDriver = Appium.fakeDriver;45var driver = fakeDriver();46driver.elementByAccessibilityId('someId').click().then(function(){47 console.log('clicked

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 Appium Base Driver 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