Best JavaScript code snippet using appium-android-driver
languageUnderstandingTest.js
Source:languageUnderstandingTest.js
1const cognitive = require('../../src/index.js');2const config = require('../config.js');3const promiseDelay = require('sleep-promise');4const _ = require("underscore");5const fs = require("fs");6const path = require('path');7const Promise = require("bluebird");8const pLimit = require('p-limit'); // for dealing with promise.all - turns into series9const limit = pLimit(1);10/*11You only need to set the apiKey for these tests. 12The tests create both the prebuilt domain Web and 13imports the ../asserts/LUIS/TravelAgent-import-app.json.14The tests now generally use the TravelAgent-import-app.json15because it has more of the custom entities. TBD: add phrase16list feature to TravelAgent-import-app.json that makes17sense for the domain. 18Each time the app is created, its apiKey is displayed along19with the count of training status calls. Usually, it takes more 20than 1 call to return successfully trained status. This test will 21not try more than retryCount times and wait retryInterval between tries. 22*/23describe('Language understanding (LUIS)', () => {24 const defaultVersionId = "0.1";25 const client = new cognitive.languageUnderstanding({26 apiKey: config.languageUnderstanding.apiKey,27 endpoint: config.languageUnderstanding.endpoint28 });29 var deleteTestApp = () =>{30 var body;31 return promiseDelay(client.retryInterval).then(() => {32 return client.deleteAppInfo(body,client.APPINFO.APP);33 }).then((response) => {34 response.should.not.be.undefined();35 response.should.have.only.keys('code', 'message');36 response.code.should.equal("Success");37 response.message.should.equal("Operation Successful");38 client.appId = undefined;39 return response;40 }).catch((err) => {41 throw(err);42 });43 }44 var importTrainPublishApp = (appName, appJSON) => {45 var parameters = {46 "appName":appName47 };48 return client.setLUIS(client.INFO.IMPORT, appJSON, parameters)49 .then(results =>{50 client.appId = results.substring(results.length - client.KeyLength, results.length);51 client.versionId = defaultVersionId;52 var parameters;53 var body;54 return client.setVersionInfo(parameters,body,client.VERSIONINFO.TRAIN);55 }).then(results => {56 return client.waitUntilTrained(client);57 }).then((response) => {58 return client.setAppInfo({59 "versionId": client.versionId,60 "isStaging": false,61 "region": "westus"62 },client.APPINFO.PUBLISH);63 }).catch(err => {64 throw(err);65 }); 66 }67 describe("Delete app after", () => {68 afterEach((done) => {69 deleteTestApp()70 .then((response) => {71 response.should.not.be.undefined();72 done();73 }).catch((err) => {74 done(err);75 });76 });77 it('should import app', (done) => {78 var parameters = {79 "appName":"Unit-" + new Date().toISOString()80 };81 var body = require("../assets/LUIS/TravelAgent-import-app.json");82 promiseDelay(client.retryInterval)83 .then(() => {84 return client.setLUIS(client.INFO.IMPORT,body, parameters);85 }).then((response) => {86 response.should.not.be.undefined();87 response.should.be.String().and.have.length(98);88 client.appId = response.substring(response.length - client.KeyLength, response.length);89 done();90 }).catch((err) => {91 done(err);92 });93 })94 it('should add prebuilt domain', (done) => {95 let body = {96 "domainName": "Web", 97 "culture": "en-us"98 }99 promiseDelay(client.retryInterval)100 .then(() => {101 var parameters;102 return client.setLUIS(client.INFO.CUSTOMPREBUILTDOMAINS, body, parameters);103 }).then((response) => {104 response.should.not.be.undefined();105 response.should.be.String().and.have.length(120);106 // get appId to delete in After()107 client.appId = response.substring(response.length - client.KeyLength, response.length);108 done();109 }).catch((err) => {110 done(err);111 });112 })113 }) 114 describe("Create app before, delete app after", () => {115 before((done) => {116 promiseDelay(client.retryInterval)117 .then(() => {118 119 var body = require("../assets/LUIS/TravelAgent-import-app.json");120 var name = "describe-" + new Date().toISOString();121 return importTrainPublishApp(name,body)122 }).then(results => {123 done();124 }).catch(err => {125 done(err);126 });127 });128 after((done) => {129 promiseDelay(client.retryInterval)130 .then(() => {131 return deleteTestApp();132 }).then((response) => {133 response.should.not.be.undefined();134 done();135 }).catch((err) => {136 done(err);137 });138 });139 it('should detect Intent from ENDPOINT', (done) => {140 // optional but recommended141 var parameters = {142 "log": true, // required to review suggested utterances143 "verbose": true // required to see all intents and scores144 };145 // query/utterance146 var body = "forward to frank 30 dollars through HSBC";147 promiseDelay(client.retryInterval)148 .then(() => {149 return client.detectIntent({parameters,body});150 }).then((response) => {151 response.should.not.be.undefined();152 _.keys(response).should.have.length(4);153 response.should.have.only.keys('query', 'intents', 'topScoringIntent', 'entities');154 done();155 }).catch((err) => {156 done(err);157 });158 })159 it('should get list of LUIS applications', (done) => {160 let culture;161 promiseDelay(client.retryInterval)162 .then(() => {163 return client.getLUIS(client.INFO.APPS, culture);164 }).then((response) => {165 response.should.not.be.undefined();166 response.should.be.Array;167 if (response.length > 0) {168 response[0].should.have.only.properties('id', 'name', 'description','culture','usageScenario','domain','versionsCount','createdDateTime','endpoints','endpointHitsCount','activeVersion');169 }170 done();171 }).catch((err) => {172 done(err);173 });174 })175 it('should get list of LUIS assistants', (done) => {176 promiseDelay(client.retryInterval)177 .then(() => {178 return client.getLUIS(client.INFO.ASSISTANTS);179 }).then((response) => {180 response.should.not.be.undefined();181 response.should.have.only.properties('endpointKeys', 'endpointUrls');182 done();183 }).catch((err) => {184 done(err);185 });186 })187 it('should get list of LUIS domains', (done) => {188 promiseDelay(client.retryInterval)189 .then(() => {190 return client.getLUIS(client.INFO.DOMAINS);191 }).then((response) => {192 response.should.not.be.undefined();193 response.should.be.Array;194 response.should.have.length(30);195 done();196 }).catch((err) => {197 done(err);198 });199 })200 it('should get list of LUIS usage scenarios', (done) => {201 promiseDelay(client.retryInterval)202 .then(() => {203 return client.getLUIS(client.INFO.USAGESCENARIOS);204 }).then((response) => {205 response.should.not.be.undefined();206 response.should.be.Array;207 response.should.have.length(4);208 done();209 }).catch((err) => {210 done(err);211 });212 })213 it('should get list of LUIS cultures', (done) => {214 promiseDelay(client.retryInterval)215 .then(() => {216 return client.getLUIS(client.INFO.CULTURE);217 }).then((response) => {218 response.should.not.be.undefined();219 response.should.be.Array;220 response.should.have.length(12);221 response[0].should.have.only.keys('name','code');222 done();223 }).catch((err) => {224 done(err);225 });226 })227 it('should get list of LUIS custom prebuilt domains', (done) => {228 229 promiseDelay(client.retryInterval)230 .then(() => {231 return client.getLUIS(client.INFO.CUSTOMPREBUILTDOMAINS);232 }).then((response) => {233 response.should.not.be.undefined();234 response.should.be.Array;235 response.should.have.length(client.PREBUILTDOMAINTOTALCOUNT);236 response[0].should.have.only.keys('name','culture','description','examples','intents','entities');237 response[0].intents.should.be.Array;238 response[0].entities.should.be.Array;239 response[0].intents[0].should.have.only.keys('name','description','examples');240 response[0].entities[0].should.have.only.keys('name','description','examples');241 done();242 }).catch((err) => {243 done(err);244 });245 })246 it('should get list of LUIS custom prebuilt domains for each supported culture', (done) => {247 248 promiseDelay(client.retryInterval)249 .then(() => {250 return client.getLUIS(client.INFO.CULTURE);251 }).then(cultures => {252 let arrPromises = [];253 254 cultures.forEach(culture => {255 arrPromises.push(limit(() => client.getLUIS(client.INFO.CUSTOMPREBUILTDOMAINS, culture.code)));256 arrPromises.push(limit(() => promiseDelay(2000)));257 });258 arrPromises.should.have.length(client.CULTURECOUNT*2);259 return Promise.all(arrPromises);260 }).then(returnedPromises => {261 262 // prune out the promiseDelay responses263 let responses = returnedPromises.filter(x => x!==undefined);264 responses.should.have.length(client.CULTURECOUNT);265 responses.forEach(prebuiltDomainByCulture => {266 prebuiltDomainByCulture.should.not.be.undefined();267 prebuiltDomainByCulture.should.be.Array;268 if(prebuiltDomainByCulture.length>0){269 var foundCulture = client.PREBUILTDOMAINCULTURES.find((obj) => {270 return (Object.keys(obj)[0]===prebuiltDomainByCulture[0].culture);271 });272 foundCulture.should.not.be.undefined();273 var foundCount = foundCulture[prebuiltDomainByCulture[0].culture];274 foundCount.should.not.equal(0);275 prebuiltDomainByCulture.should.have.length(foundCount);276 }277 278 });279 done();280 }).catch((err) => {281 done(err);282 });283 });284 it('should return array with endpoint queries for this APP', (done) => {285 promiseDelay(client.retryInterval)286 .then(() => {287 return client.getAppInfo(client.APPINFO.QUERYLOGS);288 }).then((response) => {289 response.should.not.be.undefined();290 response.should.be.Array;291 if (response.length > 0) {292 response[0].should.have.only.keys('Query', 'Response', 'UTC DateTime');293 }294 done();295 }).catch((err) => {296 done(err);297 });298 })299 it('should get APP', (done) => {300 var info = client.APPINFO.APP;301 promiseDelay(client.retryInterval)302 .then(() => {303 return client.getAppInfo(info);304 }).then((response) => {305 response.should.not.be.undefined();306 response.should.have.only.keys('id', 'name','description','culture','usageScenario','domain','versionsCount','createdDateTime','endpoints','endpointHitsCount','activeVersion','ownerEmail');307 done();308 }).catch((err) => {309 done(err);310 });311 })312 it('should update APP name', (done) => {313 var body = {314 "name": "mocha-" + new Date().getTime(),315 "description": "This is my first modified dummy description"316 };317 promiseDelay(client.retryInterval)318 .then(() => {319 return client.updateAppInfo(body, client.APPINFO.APP);320 }).then((response) => {321 response.should.not.be.undefined();322 response.should.be.Array;323 response.should.have.only.keys('code', 'message');324 response.code.should.equal("Success");325 response.message.should.equal("Operation Successful");326 done();327 }).catch((err) => {328 done(err);329 });330 })331 it('should update APP settings', (done) => {332 var body = {333 "public": true334 };335 promiseDelay(client.retryInterval)336 .then(() => {337 return client.updateAppInfo(body,client.APPINFO.SETTINGS);338 }).then((response) => {339 response.should.not.be.undefined();340 response.should.be.Array;341 response.should.have.only.keys('code', 'message');342 response.code.should.equal("Success");343 response.message.should.equal("Operation Successful");344 done();345 }).catch((err) => {346 done(err);347 });348 })349 it('should get APP endpoints', (done) => {350 var info = client.APPINFO.ENDPOINTS;351 promiseDelay(client.retryInterval)352 .then(() => {353 return client.getAppInfo(info);354 }).then((response) => {355 response.should.not.be.undefined();356 let filePath = path.join(__dirname,"../assets/LUIS/api_endpoints.json");357 let testData = JSON.parse(fs.readFileSync(filePath, "utf-8"));358 // compare key count - not data since app id changes 359 _.difference(_.keys(response),_.keys(testData)).should.have.length(0);360 done();361 }).catch((err) => {362 done(err);363 });364 })365 it('should get APP querylogs', (done) => {366 var info = client.APPINFO.QUERYLOGS;367 promiseDelay(client.retryInterval)368 .then(() => {369 return client.getAppInfo(info);370 }).then((response) => {371 response.should.not.be.undefined();372 // TBD: response validation373 done();374 }).catch((err) => {375 done(err);376 });377 })378 it('should get APP settings', (done) => {379 var info = client.APPINFO.SETTINGS;380 promiseDelay(client.retryInterval)381 .then(() => {382 return client.getAppInfo(info);383 }).then((response) => {384 response.should.not.be.undefined();385 response.should.have.only.keys('id', 'public');386 response.id.should.have.length(client.KeyLength);387 response.public.should.be.oneOf(true,false);388 done();389 }).catch((err) => {390 done(err);391 });392 })393 it('should get APP permissions', (done) => {394 var info = client.APPINFO.PERMISSIONS;395 promiseDelay(client.retryInterval)396 .then(() => {397 return client.getAppInfo(info);398 }).then((response) => {399 response.should.not.be.undefined();400 response.should.have.only.keys('owner', 'emails');401 response.owner.should.not.be.undefined();402 done();403 }).catch((err) => {404 done(err);405 });406 })407 it('should add email to permissions to APP', (done) => {408 var body = {409 "email":"addEmailToPermissionsTest@domain.com"410 };411 promiseDelay(client.retryInterval)412 .then(() => {413 return client.setAppInfo(body,client.APPINFO.PERMISSIONS);414 }).then((response) => {415 response.should.not.be.undefined();416 response.should.have.only.keys('code', 'message');417 response.code.should.equal("Success");418 response.message.should.equal("Operation Successful");419 done();420 }).catch((err) => {421 done(err);422 });423 })424 it('should update APP permissions', (done) => {425 var body = {426 "emails": [427 "test1@domain.com",428 "test2@domain.com"429 ]430 };431 promiseDelay(client.retryInterval)432 .then(() => {433 return client.updateAppInfo(body,client.APPINFO.PERMISSIONS);434 }).then((response) => {435 response.should.not.be.undefined();436 response.should.be.Array;437 response.should.have.only.keys('code', 'message');438 response.code.should.equal("Success");439 response.message.should.equal("Operation Successful");440 done();441 }).catch((err) => {442 done(err);443 });444 })445 it('should delete APP permissions', (done) => {446 var info = client.APPINFO.PERMISSIONS;447 var updateBody = {448 "emails": [449 "test1@domain.com",450 "test2@domain.com"451 ]452 };453 var deleteBody = {454 "email":"test1@domain.com"455 };456 promiseDelay(client.retryInterval)457 .then(() => {458 return client.updateAppInfo(updateBody,client.APPINFO.PERMISSIONS);459 }).then(() => { 460 return promiseDelay(client.retryInterval);461 }).then(() => {462 return client.deleteAppInfo(deleteBody,info);463 }).then((response) => {464 response.should.not.be.undefined();465 response.should.have.only.keys('code', 'message');466 response.code.should.equal("Success");467 response.message.should.equal("Operation Successful");468 }).then(() => { 469 return promiseDelay(client.retryInterval);470 }).then((response) => {471 return client.getAppInfo(info);472 }).then(response => {473 response.should.not.be.undefined();474 response.emails.should.have.length(1);475 response.emails[0].should.equal(updateBody.emails[1]);476 done();477 }).catch((err) => {478 done(err);479 });480 })481 it('should return application version in JSON for this VERSION', (done) => {482 // todo - if using a different app, might return:483 // bing_entities (prebuilt entities)484 // regex_features (deprecated but can still exist in older apps)485 // actions - not sure 486 promiseDelay(client.retryInterval)487 .then(() => {488 return client.getVersionInfo(client.VERSIONINFO.EXPORT);489 }).then((response) => {490 response.should.not.be.undefined();491 response.should.have.only.keys(492 'luis_schema_version', 493 'versionId',494 'name', 495 'desc', 496 'culture', 497 'intents', 498 'entities', 499 'composites', 500 'closedLists', 501 'bing_entities',502 'model_features', 503 'regex_features',504 'utterances');505 done();506 }).catch((err) => {507 done(err);508 });509 })510 // TBD - need to provide example utterances that are questionable so this list has examples511 it('should get list of example labeled utterances for this VERSION', (done) => {512 let parameters = {513 skip:0,514 take:100515 };516 promiseDelay(client.retryInterval)517 .then(() => {518 return client.getVersionInfo(client.VERSIONINFO.EXAMPLES,parameters);519 }).then((response) => {520 response.should.not.be.undefined();521 response.should.be.Array;522 if (response.length > 0) {523 response[0].should.have.only.keys('id', 'text', 'tokenizedText','intentLabel','entityLabels','intentPredictions','entityPredictions');524 }525 done();526 }).catch((err) => {527 done(err);528 });529 })530 it('should get list of entities in this VERSION', (done) => {531 /*532 can return 533 "customPrebuiltDomainName": "Camera",534 "customPrebuiltModelName": "AppName"535 */536 let parameters = {537 skip:0,538 take:100539 };540 promiseDelay(client.retryInterval)541 .then(() => {542 return client.getVersionInfo(client.VERSIONINFO.ENTITIES,parameters);543 }).then((response) => {544 response.should.not.be.undefined();545 response.should.be.Array;546 if (response.length > 0) {547 response[0].should.have.only.keys('id', 'name','typeId','readableType');548 }549 done();550 }).catch((err) => {551 done(err);552 });553 })554 it('should get list of intents in VERSION', (done) => {555 /*556 can return 557 "customPrebuiltDomainName": "Camera",558 "customPrebuiltModelName": "AppName"559 */560 let parameters = {561 skip:0,562 take:100563 };564 promiseDelay(client.retryInterval)565 .then(() => {566 return client.getVersionInfo(client.VERSIONINFO.INTENTS,parameters);567 }).then((response) => {568 response.should.not.be.undefined();569 response.should.be.Array;570 if (response.length > 0) {571 response[0].should.have.only.keys('id', 'name','typeId','readableType');572 }573 done();574 }).catch((err) => {575 done(err);576 });577 })578 it('should get APP versions', (done) => {579 var info = client.APPINFO.VERSIONS;580 promiseDelay(client.retryInterval)581 .then(() => {582 return client.getAppInfo(info);583 }).then((response) => {584 response.should.not.be.undefined();585 response.should.be.Array;586 if(response.length>0){587 _.keys(response[0]).should.have.length(12);588 response[0].should.have.only.keys('version', 'createdDateTime',"lastModifiedDateTime","lastTrainedDateTime","lastPublishedDateTime","endpointUrl","assignedEndpointKey","externalApiKeys","intentsCount","entitiesCount","endpointHitsCount","trainingStatus");589 _.keys(response[0].assignedEndpointKey).should.have.length(3);590 if(response[0].assignedEndpointKey) response[0].assignedEndpointKey.should.have.only.keys("SubscriptionKey","SubscriptionName","SubscriptionRegion");591 }592 done();593 }).catch((err) => {594 done(err);595 });596 })597 598 it('should clone VERSION', (done) => {599 var body = {"version":"0.2"};600 var params = {appId:client.appId,versionId:client.versionId};601 promiseDelay(client.retryInterval)602 .then(() => {603 return client.setVersionInfo(params, body, client.VERSIONINFO.CLONE);604 }).then((response) => {605 response.should.not.be.undefined();606 response.should.equal(0.2);607 done();608 }).catch((err) => {609 done(err);610 });611 })612 it('should get app VERSION info', (done) => {613 var info = client.VERSIONINFO.VERSION;614 promiseDelay(client.retryInterval)615 .then(() => {616 return client.getVersionInfo(info);617 }).then((response) => {618 response.should.not.be.undefined();619 response.should.be.Object;620 _.keys(response).should.have.length(12);621 response.should.have.only.keys(622 'version', 623 'createdDateTime',624 "lastModifiedDateTime",625 "lastTrainedDateTime",626 "lastPublishedDateTime",627 "endpointUrl",628 "assignedEndpointKey",629 "externalApiKeys",630 "intentsCount",631 "entitiesCount",632 "endpointHitsCount","trainingStatus");633 _.keys(response.assignedEndpointKey).should.have.length(3);634 response.assignedEndpointKey.should.have.only.keys("SubscriptionKey","SubscriptionName","SubscriptionRegion");635 done();636 }).catch((err) => {637 done(err);638 });639 })640 it(' should get VERSION features', function(done) {641 642 let parameters = {643 skip:0,644 take:100645 };646 promiseDelay(client.retryInterval)647 .then(() => {648 return client.getVersionInfo(client.VERSIONINFO.FEATURES, parameters);649 }).then((response) => {650 response.should.not.be.undefined();651 response.should.have.only.keys('phraselistFeatures', 'patternFeatures');652 response.phraselistFeatures.should.be.Array;653 response.patternFeatures.should.be.Array;654 done();655 }).catch((err) => {656 done(err);657 });658 });659 it(' should get VERSION HIERARCHICALENTITIES', function(done) {660 661 let parameters = {662 skip:0,663 take:100664 };665 promiseDelay(client.retryInterval)666 .then(() => {667 return client.getVersionInfo(client.VERSIONINFO.HIERARCHICALENTITIES, parameters);668 }).then((response) => {669 response.should.not.be.undefined();670 response.should.be.Array;671 done();672 }).catch((err) => {673 done(err);674 });675 });676 it(' should get VERSION LISTPREBUILTS', function(done) {677 678 let parameters = {679 skip:0,680 take:100681 };682 promiseDelay(client.retryInterval)683 .then(() => {684 return client.getVersionInfo(client.VERSIONINFO.LISTPREBUILTS, parameters);685 }).then((response) => {686 response.should.not.be.undefined();687 response.should.be.Array;688 response[0].should.have.only.keys('name', 'description','examples');689 let myNameArray = [];690 response.forEach((obj)=>{691 myNameArray.push(obj.name);692 });693 const listprebuiltsArray = [694 "number",695 "ordinal",696 "temperature",697 "dimension",698 "money",699 "age",700 "geography",701 "encyclopedia",702 "percentage",703 "datetime",704 "email",705 "url",706 "phonenumber",707 "datetimeV2"708 ];709 let diff = _.difference(listprebuiltsArray, myNameArray);710 diff.length.should.eql(0);711 done();712 }).catch((err) => {713 done(err);714 });715 });716 it(' should get VERSION models', function(done) {717 718 let parameters = {719 skip:0,720 take:100721 };722 promiseDelay(client.retryInterval)723 .then(() => {724 return client.getVersionInfo(client.VERSIONINFO.MODELS, parameters);725 }).then((response) => {726 response.should.not.be.undefined();727 response.should.be.Array;728 729 // not validating customPrebuiltModel Properties730 response[0].should.have.only.keys('id', 'name','typeId','readableType');731 done();732 }).catch((err) => {733 done(err);734 });735 });736 it(' should post VERSION closedlists', function(done) {737 738 let body = {739 "name": "States",740 "sublists": 741 [742 {743 "canonicalForm": "New York",744 "list": [ "NY", "New York" ]745 },746 {747 "canonicalForm": "Washington",748 "list": [ "Washington", "WA" ]749 },750 {751 "canonicalForm": "California",752 "list": [ "California", "CA", "Calif.", "Cal." ]753 }754 ]755 };756 let parameters;757 758 promiseDelay(client.retryInterval)759 .then(() => {760 return client.setVersionInfo(parameters, body, client.VERSIONINFO.CLOSEDLISTS);761 }).then((response) => {762 response.should.not.be.undefined();763 //TBD: not sure how I want to test the response764 //since the url is getting stuck on the front of it by765 //commonService.js usage of "operation-location"766 767 done();768 }).catch((err) => {769 done(err);770 });771 });772 });...
retryPolicyTests.js
Source:retryPolicyTests.js
1// Copyright (c) Microsoft Corporation. All rights reserved.2// Licensed under the MIT License. See License.txt in the project root for license information.3var assert = require('assert');4var ExponentialRetryPolicyFilter = require('../lib/filters/exponentialRetryPolicyFilter');5var SystemErrorRetryPolicyFilter = require('../lib/filters/systemErrorRetryPolicyFilter');6describe('exponentialretrypolicyfilter-unittests', function () {7 it('RetrySucceedsOnHttp408StatusCode', function (done) {8 var retryCount = 2;9 var retryInterval = 2;10 var minRetryInterval = 1;11 var maxRetryInterval = 10;12 var response = {'statusCode': 408};13 var mockNextGenerator = function() {14 var timesCalled = 0;15 return function(options, retryCallback) {16 if (timesCalled == 0) {17 timesCalled ++;18 retryCallback(true, response, null);19 } else {20 done();21 }22 };23 };24 var mockRetryPolicyFilter = new ExponentialRetryPolicyFilter(retryCount, retryInterval, minRetryInterval, maxRetryInterval);25 mockRetryPolicyFilter(null, mockNextGenerator(), function(err, result, response, body) {26 throw "Fail to retry on HTTP 408";27 });28 });29 30 it('RetrySucceedsOnHttp502StatusCode', function (done) {31 var retryCount = 2;32 var retryInterval = 2;33 var minRetryInterval = 1;34 var maxRetryInterval = 10;35 var response = {'statusCode': 502};36 var mockNextGenerator = function() {37 var timesCalled = 0;38 return function(options, retryCallback) {39 if (timesCalled == 0) {40 timesCalled ++;41 retryCallback(true, response, null);42 } else {43 done();44 }45 };46 };47 var mockRetryPolicyFilter = new ExponentialRetryPolicyFilter(retryCount, retryInterval, minRetryInterval, maxRetryInterval);48 mockRetryPolicyFilter(null, mockNextGenerator(), function(err, result, response, body) {49 throw "Fail to retry on HTTP 502";50 });51 });52 it('DoesNotRetryOnHttp404StatusCode', function (done) {53 var retryCount = 2;54 var retryInterval = 2;55 var minRetryInterval = 1;56 var maxRetryInterval = 10;57 var response = {'statusCode': 404};58 var mockNextGenerator = function() {59 var timesCalled = 0;60 return function(options, retryCallback) {61 if (timesCalled == 0) {62 timesCalled ++;63 retryCallback(true, response, null);64 } else {65 throw "Should not retry on HTTP 404";66 }67 };68 };69 var mockRetryPolicyFilter = new ExponentialRetryPolicyFilter(retryCount, retryInterval, minRetryInterval, maxRetryInterval);70 mockRetryPolicyFilter(null, mockNextGenerator(), function(err, result, response, body) {71 done();72 });73 });74 it('DoesNotRetryOnHttp501StatusCode', function (done) {75 var retryCount = 2;76 var retryInterval = 2;77 var minRetryInterval = 1;78 var maxRetryInterval = 10;79 var response = {'statusCode': 501};80 var mockNextGenerator = function() {81 var timesCalled = 0;82 return function(options, retryCallback) {83 if (timesCalled == 0) {84 timesCalled ++;85 retryCallback(true, response, null);86 } else {87 throw "Should not retry on HTTP 501";88 }89 };90 };91 var mockRetryPolicyFilter = new ExponentialRetryPolicyFilter(retryCount, retryInterval, minRetryInterval, maxRetryInterval);92 mockRetryPolicyFilter(null, mockNextGenerator(), function(err, result, response, body) {93 done();94 });95 });96 it('DoesNotRetryOnHttp505StatusCode', function (done) {97 var retryCount = 2;98 var retryInterval = 2;99 var minRetryInterval = 1;100 var maxRetryInterval = 10;101 var response = {'statusCode': 505};102 var mockNextGenerator = function() {103 var timesCalled = 0;104 return function(options, retryCallback) {105 if (timesCalled == 0) {106 timesCalled ++;107 retryCallback(true, response, null);108 } else {109 throw "Should not retry on HTTP 505";110 }111 };112 };113 var mockRetryPolicyFilter = new ExponentialRetryPolicyFilter(retryCount, retryInterval, minRetryInterval, maxRetryInterval);114 mockRetryPolicyFilter(null, mockNextGenerator(), function(err, result, response, body) {115 done();116 });117 });118});119describe('systemErrorRetrypolicyfilter-unittests', function () {120 it('DoesNotRetryOn_ENOTFOUND_ErrorCode', function (done) {121 var retryCount = 2;122 var retryInterval = 2;123 var minRetryInterval = 1;124 var maxRetryInterval = 10;125 126 var response = { 'statusCode': 502 };127 var e = new Error('ENOTFOUND');128 e.code = 'ENOTFOUND';129 e.errno = 'ENOTFOUND';130 e.syscall = 'getaddrinfo';131 e.hostname = 'testkv602.vault.azure.net';132 e.host = 'testkv602.vault.azure.net';133 e.port = 443;134 var mockNextGenerator = function () {135 var timesCalled = 0;136 return function (options, retryCallback) {137 if (timesCalled == 0) {138 timesCalled++;139 retryCallback(e, null, null);140 } else {141 throw 'Should not Retry on ENOTFOUND ErrorCode';142 143 }144 };145 };146 147 var mockRetryPolicyFilter = new SystemErrorRetryPolicyFilter(retryCount, retryInterval, minRetryInterval, maxRetryInterval);148 mockRetryPolicyFilter(null, mockNextGenerator(), function (err, result, response, body) {149 done();150 });151 });152 153 it('RetrySucceedsOn_ECONNRESET_ErrorCode', function (done) {154 var retryCount = 2;155 var retryInterval = 2;156 var minRetryInterval = 1;157 var maxRetryInterval = 10;158 159 var response = { 'statusCode': 502 };160 var e = new Error('ECONNRESET');161 e.code = 'ECONNRESET';162 e.errno = 'ECONNRESET';163 e.syscall = 'getaddrinfo';164 e.hostname = 'testkv602.vault.azure.net';165 e.host = 'testkv602.vault.azure.net';166 e.port = 443;167 var mockNextGenerator = function () {168 var timesCalled = 0;169 return function (options, retryCallback) {170 if (timesCalled == 0) {171 timesCalled++;172 retryCallback(e, null, null);173 } else {174 done();175 }176 };177 };178 179 var mockRetryPolicyFilter = new SystemErrorRetryPolicyFilter(retryCount, retryInterval, minRetryInterval, maxRetryInterval);180 mockRetryPolicyFilter(null, mockNextGenerator(), function (err, result, response, body) {181 throw 'Retry does not succeed on ECONNRESET ErrorCode';182 });183 });184 185 it('RetrySucceedsOn_ECONNREFUSED_ErrorCode', function (done) {186 var retryCount = 2;187 var retryInterval = 2;188 var minRetryInterval = 1;189 var maxRetryInterval = 10;190 191 var response = { 'statusCode': 502 };192 var e = new Error('ECONNREFUSED');193 e.code = 'ECONNREFUSED';194 e.errno = 'ECONNREFUSED';195 e.syscall = 'getaddrinfo';196 e.hostname = 'testkv602.vault.azure.net';197 e.host = 'testkv602.vault.azure.net';198 e.port = 443;199 var mockNextGenerator = function () {200 var timesCalled = 0;201 return function (options, retryCallback) {202 if (timesCalled == 0) {203 timesCalled++;204 retryCallback(e, null, null);205 } else {206 done();207 }208 };209 };210 211 var mockRetryPolicyFilter = new SystemErrorRetryPolicyFilter(retryCount, retryInterval, minRetryInterval, maxRetryInterval);212 mockRetryPolicyFilter(null, mockNextGenerator(), function (err, result, response, body) {213 throw 'Retry does not succeed on ECONNREFUSED ErrorCode';214 });215 });216 217 it('RetrySucceedsOn_ETIMEDOUT_ErrorCode', function (done) {218 var retryCount = 2;219 var retryInterval = 2;220 var minRetryInterval = 1;221 var maxRetryInterval = 10;222 223 var response = { 'statusCode': 502 };224 var e = new Error('ETIMEDOUT');225 e.code = 'ETIMEDOUT';226 e.errno = 'ETIMEDOUT';227 e.syscall = 'getaddrinfo';228 e.hostname = 'testkv602.vault.azure.net';229 e.host = 'testkv602.vault.azure.net';230 e.port = 443;231 var mockNextGenerator = function () {232 var timesCalled = 0;233 return function (options, retryCallback) {234 if (timesCalled == 0) {235 timesCalled++;236 retryCallback(e, null, null);237 } else {238 done();239 }240 };241 };242 243 var mockRetryPolicyFilter = new SystemErrorRetryPolicyFilter(retryCount, retryInterval, minRetryInterval, maxRetryInterval);244 mockRetryPolicyFilter(null, mockNextGenerator(), function (err, result, response, body) {245 throw 'Retry does not succeed on ETIMEDOUT ErrorCode';246 });247 });248 249 it('RetrySucceedsOn_ESOCKETTIMEDOUT_ErrorCode', function (done) {250 var retryCount = 2;251 var retryInterval = 2;252 var minRetryInterval = 1;253 var maxRetryInterval = 10;254 255 var response = { 'statusCode': 502 };256 var e = new Error('ESOCKETTIMEDOUT');257 e.code = 'ESOCKETTIMEDOUT';258 e.errno = 'ESOCKETTIMEDOUT';259 e.syscall = 'getaddrinfo';260 e.hostname = 'testkv602.vault.azure.net';261 e.host = 'testkv602.vault.azure.net';262 e.port = 443;263 var mockNextGenerator = function () {264 var timesCalled = 0;265 return function (options, retryCallback) {266 if (timesCalled == 0) {267 timesCalled++;268 retryCallback(e, null, null);269 } else {270 done();271 }272 };273 };274 275 var mockRetryPolicyFilter = new SystemErrorRetryPolicyFilter(retryCount, retryInterval, minRetryInterval, maxRetryInterval);276 mockRetryPolicyFilter(null, mockNextGenerator(), function (err, result, response, body) {277 throw 'Retry does not succeed on ESOCKETTIMEDOUT ErrorCode';278 });279 });...
elementWrapper.js
Source:elementWrapper.js
1const { firstElement, desc, prepareParameters, elementTypeToSelectorName } = require('./helper');2const { descEvent } = require('../eventBus');3let { getIfExists } = require('../elementSearch');4const runtimeHandler = require('../handlers/runtimeHandler');5/**6 * Wrapper object of all found elements. This list mimics the behaviour of {@link Element}7 * by exposing similar methods. The call of these methods gets delegated to first element.8 * By default, the `ElementWrapper` acts as a proxy to the first matching element and hence9 * it forwards function calls that belong to {@link Element}10 */11class ElementWrapper {12 constructor(elementType, query, attrValuePairs, _options, ...args) {13 if (attrValuePairs instanceof ElementWrapper) {14 const selectorName = elementTypeToSelectorName(elementType);15 throw new TypeError(16 'You are passing a `ElementWrapper` to a `' +17 selectorName +18 '` selector. Refer https://docs.taiko.dev/api/' +19 selectorName.toLowerCase() +20 '/ for the correct parameters',21 );22 }23 const { selector, options } = prepareParameters(attrValuePairs, _options, ...args);24 this.selector = selector;25 this._options = options;26 this._description = desc(selector, query, elementType, options);27 }28 /**29 * @deprecated Deprecated from version `1.0.3`. DOM element getter. Implicitly wait for the element to appears with timeout of 10 seconds.30 * @param {number} retryInterval Retry Interval in milliseconds (defaults to global settings).31 * @param {number} retryTimeout Retry Timeout in milliseconds (defaults to global settings).32 * @returns {Element[]} All elements mathing the selector.33 */34 async get(retryInterval, retryTimeout) {35 console.warn('DEPRECATED use .elements()');36 return this.elements(retryInterval, retryTimeout);37 }38 /**39 * @property40 * @description Describes the operation performed. The description is the same that is printed when performing the operation in REPL.41 * @returns {string} Description of the current command that fetched this element(wrapper).42 * @example43 * link('google').description // prints "'Link with text google'"44 */45 get description() {46 return this._description;47 }48 /**49 * @description Checks existence for element. `exists()` waits for `retryTimeout` before deciding that the page is loaded.50 * (NOTE: `exists()` returns boolean from version `0.4.0`)51 * @since 0.4.052 * @param {number} retryInterval Retry Interval in milliseconds (defaults to global settings).53 * @param {number} retryTimeout Retry Timeout in milliseconds (defaults to global settings).54 * @returns {boolean} true if exists, else false.55 * @example56 * // To 'short-circuit' non existence. However this should be done only if there is no network calls/reloads.57 * element.exists(0,0)58 * @example59 * link('google').exists()60 * @example61 * link('google').exists(1000)62 */63 async exists(retryInterval, retryTimeout) {64 try {65 await firstElement.apply(this, [retryInterval, retryTimeout]);66 } catch (e) {67 if (e.message === `${this._description} not found`) {68 descEvent.emit('success', 'Does not exist');69 return false;70 }71 throw e;72 }73 descEvent.emit('success', 'Exists');74 return true;75 }76 /**77 * @description Gets the [`innerText`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText) of the element78 * @returns {string} [`innerText`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText) of the element79 */80 async text() {81 const elem = await firstElement.apply(this);82 return await elem.text();83 }84 /**85 * @description Checks if element is visually visible. `isVisible()` is false when the element is overshadowed by another element,86 * or if the element is outside the viewport.87 * @param {number} retryInterval Retry Interval in milliseconds (defaults to global settings).88 * @param {number} retryTimeout Retry Timeout in milliseconds (defaults to global settings).89 * @returns {boolean} true if visible, else false.90 */91 async isVisible(retryInterval, retryTimeout) {92 const elem = await firstElement.apply(this, [retryInterval, retryTimeout]);93 async function isVisible() {94 const visibilityRatio = await new Promise((resolve) => {95 let elem = this;96 const observer = new IntersectionObserver((entries) => {97 resolve(entries[0].intersectionRatio);98 observer.disconnect();99 });100 observer.observe(elem);101 });102 return visibilityRatio === 1;103 }104 const objectId = elem.get();105 const { result } = await runtimeHandler.runtimeCallFunctionOn(isVisible, null, {106 objectId: objectId,107 awaitPromise: true,108 });109 if (result.value) {110 descEvent.emit('success', 'Element is Visible');111 return true;112 } else {113 descEvent.emit('success', 'Element is not Visible');114 return false;115 }116 }117 /**118 * @description Checks if element is disabled119 * @param {number} retryInterval Retry Interval in milliseconds (defaults to global settings).120 * @param {number} retryTimeout Retry Timeout in milliseconds (defaults to global settings).121 * @returns {boolean} true if disabled, else false.122 */123 async isDisabled(retryInterval, retryTimeout) {124 const elem = await firstElement.apply(this, [retryInterval, retryTimeout]);125 return await elem.isDisabled();126 }127 /**128 * @description Checks if element is [draggable](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/draggable).129 * @param {number} retryInterval Retry Interval in milliseconds (defaults to global settings).130 * @param {number} retryTimeout Retry Timeout in milliseconds (defaults to global settings).131 * @returns {boolean} true if disabled, else false.132 */133 async isDraggable(retryInterval, retryTimeout) {134 const elem = await firstElement.apply(this, [retryInterval, retryTimeout]);135 return await elem.isDraggable();136 }137 /**138 * @description Read attribute value of the element found.139 * @param {string} name140 * @returns {string} value of attribute141 * @example142 * link('google').attribute('alt')143 */144 async attribute(name) {145 const elem = await firstElement.apply(this);146 return await elem.getAttribute(name);147 }148 /**149 * @description DOM element getter. Implicitly wait for the element to appears with timeout of 10 seconds.150 * @param {number} retryInterval Retry Interval in milliseconds (defaults to global settings).151 * @param {number} retryTimeout Retry Timeout in milliseconds (defaults to global settings).152 * @returns {Element[]} Array of all elements matching the selector.153 * @example154 * // To loop over all the elements155 * let elements = await $('a').elements();156 * for (element of elements) {157 * console.log(await element.text());158 * }159 * @example160 * textBox('username').value()161 * (await textBox('username').elements())[0].value() # same as above162 * @example163 * $('.class').text()164 * (await $('.class').elements())[0].text() # same as above165 * @example166 * let element = await $('a').element(0);167 * console.log(await element.text());168 */169 async elements(retryInterval, retryTimeout) {170 return await getIfExists(this._get, this._description)(null, retryInterval, retryTimeout);171 }172 /**173 * @description DOM element getter. Implicitly wait for the element to appears with timeout of 10 seconds.174 * @alias elements()[0]175 * @param {number} index Zero-based index of element to return176 * @param {number} retryInterval Retry Interval in milliseconds (defaults to global settings).177 * @param {number} retryTimeout Retry Timeout in milliseconds (defaults to global settings).178 * @returns {Element} First element that matches the selector.179 */180 async element(index, retryInterval, retryTimeout) {181 const results = await getIfExists(this._get, this._description)(182 null,183 retryInterval,184 retryTimeout,185 );186 if (index > results.length - 1) {187 throw new Error(`Element index is out of range. There are only ${results.length} element(s)`);188 }189 return results[index];190 }191}...
promise.js
Source:promise.js
1/**2 * Copyright (c) 2018, Neap Pty Ltd.3 * All rights reserved.4 * 5 * This source code is licensed under the BSD-style license found in the6 * LICENSE file in the root directory of this source tree.7*/8const { obj: { merge }, math } = require('./core')9const { arities } = require('./functional')10const delay = timeout => new Promise(onSuccess => setTimeout(onSuccess, timeout))11const wait = (stopWaiting, options) => Promise.resolve(null).then(() => {12 const now = Date.now()13 const { timeout=300000, start=now, interval=2000 } = options || {}14 15 if ((now - start) > timeout)16 throw new Error('timeout')17 18 return Promise.resolve(null).then(() => stopWaiting()).then(stop => {19 if (stop)20 return21 else22 return delay(interval).then(() => wait(stopWaiting, { timeout, start, interval }))23 })24})25const check = (request, verify, options={}) => request(options.nextState).then(resp => Promise.resolve(verify(resp)).then(result => {26 const { interval=4000, timeOut=300000 } = options27 if (result === true)28 return resp29 else if (timeOut < 0)30 throw new Error('timeout')31 else if (!result || result.nextState)32 return delay(interval).then(() => check(request, verify, { interval, timeOut: timeOut - interval, nextState: result.nextState }))33 else34 return resp35}))36/**37 * [description]38 * @param {Function} fn [description]39 * @param {Function} successFn (res, options) => Returns a promise or a value. The value is a boolean or an object that determines 40 * whether a response is valid or not. If the value is an object, that object might contain41 * a 'retryInterval' which overrides the optional value. 42 * @param {Function} failureFn (Optional) (error, options) => Returns a promise or a value. The value is a boolean or an object that determines 43 * whether a response is valid or not. If the value is an object, that object might contain44 * a 'retryInterval' which overrides the optional value. 45 * @param {Number} options.retryAttempts default: 5. Number of retry46 * @param {Number} options.attemptsCount Current retry count. When that counter reaches the 'retryAttempts', the function stops.47 * @param {Number} options.timeOut If specified, 'retryAttempts' and 'attemptsCount' are ignored48 * @param {Number} options.retryInterval default: 5000. Time interval in milliseconds between each retry. It can also be a 2 items array.49 * In that case, the retryInterval is a random number between the 2 ranges (e.g., [10, 100] => 54).50 * The retry strategy increases the 'retryInterval' by a factor 1.5 after each failed attempt.51 * @param {Boolean} options.ignoreError In case of constant failure to pass the 'successFn' test, this function will either throw an error52 * or return the current result without throwing an error if this flag is set to true.53 * @param {String} options.errorMsg Customize the exception message in case of failure.54 * @param {String} options.ignoreFailure If set to true, then failure from fn will cause a retry55 * @return {[type]} [description]56 */57const retry = arities(58 'function fn, function successFn, object options={}',59 'function fn, function successFn, function failureFn, object options={}',60 ({ fn, successFn, failureFn, options={} }) => { 61 const start = Date.now()62 return Promise.resolve(null)63 .then(() => fn()).then(data => ({ error: null, data }))64 .catch(error => { 65 if (options.ignoreFailure && !failureFn)66 failureFn = () => true67 return { error, data: null }68 })69 .then(({ error, data }) => Promise.resolve(null)70 .then(() => {71 if (error && failureFn)72 return failureFn(error, options)73 else if (error)74 throw error 75 else76 return successFn(data, options)77 })78 .then(passed => {79 if (!error && passed)80 return data81 else if ((!error && !passed) || (error && passed)) {82 let { retryAttempts=5, retryInterval=5000, attemptsCount=0, timeOut=null, startTime=null } = options83 const delayFactor = (attemptsCount+1) <= 1 ? 1 : Math.pow(1.5, attemptsCount)84 if (timeOut > 0) {85 startTime = startTime || start86 if (Date.now() - startTime < timeOut) {87 const explicitRetryInterval = passed && passed.retryInterval > 0 ? passed.retryInterval : null88 const i = (!explicitRetryInterval && Array.isArray(retryInterval) && retryInterval.length > 1)89 ? (() => {90 if (typeof(retryInterval[0]) != 'number' || typeof(retryInterval[1]) != 'number')91 throw new Error(`Wrong argument exception. When 'options.retryInterval' is an array, all elements must be numbers. Current: [${retryInterval.join(', ')}].`)92 if (retryInterval[0] > retryInterval[1])93 throw new Error(`Wrong argument exception. When 'options.retryInterval' is an array, the first element must be strictly greater than the second. Current: [${retryInterval.join(', ')}].`)94 return math.randomNumber(retryInterval[0], retryInterval[1])95 })()96 : (explicitRetryInterval || retryInterval)97 const delayMs = Math.round(delayFactor*i)98 return delay(delayMs).then(() => failureFn 99 ? retry(fn, successFn, failureFn, merge(options, { startTime, attemptsCount:attemptsCount+1 }))100 : retry(fn, successFn, merge(options, { startTime, attemptsCount:attemptsCount+1 })))101 } else102 throw new Error('timeout')103 } else if (attemptsCount < retryAttempts) {104 const delayMs = Math.round(delayFactor*retryInterval)105 return delay(delayMs).then(() => failureFn106 ? retry(fn, successFn, failureFn, merge(options, { attemptsCount:attemptsCount+1 }))107 : retry(fn, successFn, merge(options, { attemptsCount:attemptsCount+1 })))108 } else if (options.ignoreError)109 return data110 else 111 throw new Error(options.errorMsg ? options.errorMsg : `${retryAttempts} attempts to retry the procedure failed to pass the test`)112 } else 113 throw error114 }))115 })116module.exports = {117 delay,118 wait,119 check,120 retry...
customDomain.js
Source:customDomain.js
1const AWS = require('aws-sdk');2const MAX_RETRIES_DEFAULT = 5;3const RETRIES_INTERVAL_DEFAULT = 90000;4const MAX_RETRIES_MESSAGE = 'Max retries attempts reached.';5const VALIDATE_DOMAIN_NAME_REQUIRED = 'DomainName parameter is required';6const VALIDATE_CERTIFICATE_ARN_REQUIRED = 'CertificateArn parameter is required';7const callCreateWithRetry = async (8 apigwClient, createParams, getParams, attempt, maxRetries, retryInterval) => {9 try {10 return await apigwClient.createDomainName(createParams).promise();11 } catch (e) {12 if (e.message && e.message === 'The domain name you provided already exists.') {13 return await apigwClient.getDomainName(getParams).promise();14 }15 console.log(e);16 if (attempt >= maxRetries) {17 console.log(MAX_RETRIES_MESSAGE);18 throw new Error(MAX_RETRIES_MESSAGE);19 }20 await new Promise(21 (resolve) => setTimeout(resolve, (1.5 ** attempt++) * retryInterval));22 return await callCreateWithRetry(23 apigwClient, createParams, getParams, attempt, maxRetries, retryInterval,24 );25 }26};27const callDeleteWithRetry = async (apigwClient, params, attempt, maxRetries, retryInterval) => {28 try {29 return await apigwClient.deleteDomainName(params).promise();30 } catch (e) {31 if (e.code && e.code === 'NotFoundException') {32 return;33 }34 console.log(e);35 if (attempt >= maxRetries) {36 console.log(MAX_RETRIES_MESSAGE);37 throw new Error(MAX_RETRIES_MESSAGE);38 }39 await new Promise(40 (resolve) => setTimeout(resolve, (1.5 ** attempt++) * retryInterval));41 return await callDeleteWithRetry(apigwClient, params, attempt, maxRetries, retryInterval);42 }43};44module.exports = {45 MAX_RETRIES_DEFAULT: MAX_RETRIES_DEFAULT,46 MAX_RETRIES_MESSAGE: MAX_RETRIES_MESSAGE,47 VALIDATE_CERTIFICATE_ARN_REQUIRED: VALIDATE_CERTIFICATE_ARN_REQUIRED,48 VALIDATE_DOMAIN_NAME_REQUIRED: VALIDATE_DOMAIN_NAME_REQUIRED,49 validate: (CfnRequestParams) => {50 if (!CfnRequestParams.DomainName) {51 return VALIDATE_DOMAIN_NAME_REQUIRED;52 }53 if (!CfnRequestParams.CertificateArn) {54 return VALIDATE_CERTIFICATE_ARN_REQUIRED;55 }56 },57 create: async (CfnRequestParams, RetryInterval) => {58 console.log('Params', CfnRequestParams);59 const ApiGateway = new AWS.APIGateway({apiVersion: '2015-07-09'});60 const customDomain = await callCreateWithRetry(ApiGateway,61 {62 domainName: CfnRequestParams.DomainName,63 certificateArn: CfnRequestParams.CertificateArn,64 endpointConfiguration: {65 types: CfnRequestParams.EndpointConfiguration.Types,66 },67 },68 {69 domainName: CfnRequestParams.DomainName,70 },71 0, MAX_RETRIES_DEFAULT, RetryInterval || RETRIES_INTERVAL_DEFAULT);72 console.log('Custom domain created/updated', customDomain);73 return {74 DomainName: customDomain.domainName,75 DistributionDomainName: customDomain.distributionDomainName,76 DistributionHostedZoneId: customDomain.distributionHostedZoneId,77 };78 },79 delete: async (CfnRequestParams, RequestPhysicalID, RetryInterval) => {80 console.log('Params', CfnRequestParams);81 const ApiGateway = new AWS.APIGateway({apiVersion: '2015-07-09'});82 const customDomain = await callDeleteWithRetry(ApiGateway,83 {84 domainName: CfnRequestParams.DomainName,85 },86 0, MAX_RETRIES_DEFAULT, RetryInterval || RETRIES_INTERVAL_DEFAULT);87 console.log('Custom domain deleted', customDomain);88 return {89 PhysicalResourceId: RequestPhysicalID || CfnRequestParams.DomainName,90 };91 },92 createV2: async (CfnRequestParams, RetryInterval) => {93 console.log('Params V2', CfnRequestParams);94 const ApiGatewayV2 = new AWS.ApiGatewayV2({apiVersion: '2018-11-29'});95 const customDomain = await callCreateWithRetry(ApiGatewayV2,96 {97 DomainName: CfnRequestParams.DomainName,98 DomainNameConfigurations: CfnRequestParams.DomainNameConfigurations,99 },100 {101 DomainName: CfnRequestParams.DomainName,102 },103 0, MAX_RETRIES_DEFAULT, RetryInterval || RETRIES_INTERVAL_DEFAULT);104 console.log('Custom domain created/updated', customDomain);105 return {106 DomainName: customDomain.DomainName,107 RegionalDomainName: customDomain.DomainNameConfigurations[0].ApiGatewayDomainName,108 };109 },110 deleteV2: async (CfnRequestParams, RequestPhysicalID, RetryInterval) => {111 console.log('Params V2', CfnRequestParams);112 const ApiGatewayV2 = new AWS.ApiGatewayV2({apiVersion: '2018-11-29'});113 const customDomain = await callDeleteWithRetry(ApiGatewayV2,114 {115 DomainName: CfnRequestParams.DomainName,116 },117 0, MAX_RETRIES_DEFAULT, RetryInterval || RETRIES_INTERVAL_DEFAULT);118 console.log('Custom domain deleted', customDomain);119 return {120 PhysicalResourceId: RequestPhysicalID || CfnRequestParams.DomainName,121 };122 },...
index.js
Source:index.js
1var request = require('request').defaults({jar: true, strictSSL :false});2var EventEmitter = require('events');3module.exports = function(host, port, options, successCallback, progressCallback) {4 // Allow for missing options5 if (options === undefined || typeof options === 'function') {6 progressCallback = successCallback;7 successCallback = options;8 options = {};9 }10 if (progressCallback === undefined) {11 // only 1 function passed in.12 // in this case we use it as a progressCallback and return a promise13 progressCallback = successCallback;14 successCallback = undefined;15 }16 // Sensible defaults17 var numRetries = options.numRetries || 10;18 var retriesRemaining = numRetries;19 var retryInterval = options.retryInterval || 1000;20 var requestTimeout = options.requestTimeout || 2500;21 var monitorFrequency = parseInt(options.monitorFrequency,10) || 0;22 var schema = options.secure ? 'https': 'http';23 // Validate the supplied options24 if (!(retriesRemaining > 0)) throw new Error('Invalid value for option "numRetries"');25 if (!(retryInterval > 0)) throw new Error('Invalid value for option "retryInterval"');26 if (!(requestTimeout > 0)) throw new Error('Invalid value for option "requestTimeout"');27 // RealityServer JSON-RPC 2.0 request to obtain version number28 var command = {29 jsonrpc: 2.0,30 method: 'get_version',31 params: {},32 id: 133 };34 function setupResult(body) {35 if (monitorFrequency <= 0) {36 return { version: body.result }37 }38 var emitter = new EventEmitter()39 var connectable = true;40 function checkRealityServer() {41 // we just want to check connectability42 request({43 method: 'GET',44 uri: schema + '://' + host + ':' + port + '/',45 timeout: requestTimeout46 }, function(error, response, body) {47 if (error) {48 if (connectable) {49 emitter.emit('disconnected')50 connectable = false;51 }52 } else if (!connectable) {53 emitter.emit('connected');54 connectable = true;55 }56 });57 }58 var timer = setInterval(checkRealityServer,monitorFrequency);59 emitter.version = body.result;60 emitter.stop = function() {61 clearInterval(timer);62 timer = undefined;63 }64 return emitter;65 }66 // Attempt to get the RealityServer version and retry on failure67 function tryToConnect() {68 request({ // Attempt to make UAC session first69 method: 'GET',70 uri: schema + '://' + host + ':' + port + '/uac/create/',71 timeout: requestTimeout 72 }, function(error, response, body) {73 if (error) {74 typeof progressCallback === 'function' && progressCallback({numRetries: numRetries, retriesRemaining: retriesRemaining, retryInterval: retryInterval});75 if (--retriesRemaining <= 0)76 return successCallback(new Error('Retry limit reached, RealityServer not available'));77 setTimeout(tryToConnect, retryInterval);78 return; 79 }80 if (retriesRemaining > 0) {81 request({82 method: 'POST',83 uri: schema + '://' + host + ':' + port + '/',84 json: command,85 timeout: requestTimeout 86 }, function(error, response, versionBody) {87 if (error || typeof versionBody.result !== 'string') {88 typeof progressCallback === 'function' && progressCallback({numRetries: numRetries, retriesRemaining: retriesRemaining, retryInterval: retryInterval});89 if (--retriesRemaining <= 0)90 return successCallback(new Error('Retry limit reached, RealityServer not available'));91 setTimeout(tryToConnect, retryInterval);92 return; 93 }94 if (retriesRemaining > 0) {95 request({96 method: 'GET',97 uri: schema + '://' + host + ':' + port + '/uac/destroy/',98 timeout: requestTimeout 99 }, function(error, response, body) {100 if (error) {101 typeof progressCallback === 'function' && progressCallback({numRetries: numRetries, retriesRemaining: retriesRemaining, retryInterval: retryInterval});102 if (--retriesRemaining <= 0)103 return successCallback(new Error('Retry limit reached, RealityServer not available'));104 setTimeout(tryToConnect, retryInterval);105 return; 106 }107 if (retriesRemaining > 0) {108 successCallback(null, setupResult(versionBody));109 }110 });111 }112 });113 }114 });115 }116 // Kick off the process117 if (successCallback === undefined) {118 if (typeof Promise !== 'function') {119 throw 'No successCallback provided but Promises are not supported';120 }121 return new Promise(function(resolve,reject) {122 successCallback = function(err,result) {123 if (err) {124 reject(err);125 } else {126 resolve(result);127 }128 }129 tryToConnect();130 });131 } else {132 tryToConnect();133 }...
exponentialretrypolicyfilter-tests.js
Source:exponentialretrypolicyfilter-tests.js
1/**2* Copyright 2011 Microsoft Corporation3*4* Licensed under the Apache License, Version 2.0 (the "License");5* you may not use this file except in compliance with the License.6* You may obtain a copy of the License at7* http://www.apache.org/licenses/LICENSE-2.08*9* Unless required by applicable law or agreed to in writing, software10* distributed under the License is distributed on an "AS IS" BASIS,11* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12* See the License for the specific language governing permissions and13* limitations under the License.14*/15var testCase = require('nodeunit').testCase;16var azure = require("../../lib/azure");17var testutil = require('../util/util');18var tabletestutil = require('../util/table-test-utils');19var ServiceClient = require('../../lib/services/serviceclient');20var ExponentialRetryPolicyFilter = require('../../lib/common/exponentialretrypolicyfilter');21var Constants = require('../../lib/util/constants');22var tableService;23var exponentialRetryPolicyFilter;24var tableNames = [];25var tablePrefix = 'expretry';26var testPrefix = 'exponentialretrypolicyfilter-tests';27module.exports = testCase(28{29 setUp: function (callback) {30 tabletestutil.setUpTest(module.exports, testPrefix, function (err, newTableService) {31 exponentialRetryPolicyFilter = new ExponentialRetryPolicyFilter();32 tableService = newTableService.withFilter(exponentialRetryPolicyFilter);33 callback();34 });35 },36 tearDown: function (callback) {37 tabletestutil.tearDownTest(module.exports, tableService, testPrefix, callback);38 },39 testRetryFailSingle: function (test) {40 var tableName = testutil.generateId(tablePrefix, tableNames, tabletestutil.isMocked);41 var retryCount = 3;42 var retryInterval = 30;43 exponentialRetryPolicyFilter.retryCount = retryCount;44 exponentialRetryPolicyFilter.retryInterval = retryInterval;45 tableService.createTable(tableName, function (err) {46 test.equal(err, null);47 tableService.createTable(tableName, function (err2) {48 test.notEqual(err2, null);49 test.equal(err2.code, Constants.TableErrorCodeStrings.TABLE_ALREADY_EXISTS);50 test.equal(err2.innerError, null);51 test.done();52 });53 });54 },55 testRetryFailMultiple: function (test) {56 var tableName = testutil.generateId(tablePrefix, tableNames, tabletestutil.isMocked);57 var retryCount = 3;58 // 30 seconds as starting time between attempts should be enough to give enough time for the59 // table creation to succeed after a deletion.60 var retryInterval = 30000;61 if (tabletestutil.isMocked && !tabletestutil.isRecording) {62 // if a playback on the mockserver is running, retryinterval can be lower63 retryInterval = 30;64 exponentialRetryPolicyFilter.minRetryInterval = 30;65 }66 exponentialRetryPolicyFilter.retryCount = retryCount;67 exponentialRetryPolicyFilter.retryInterval = retryInterval;68 // replace shouldRetry to skip return codes verification and retry on 409 (deleting)69 exponentialRetryPolicyFilter.shouldRetry = function (statusCode, retryData) {70 var currentCount = (retryData && retryData.retryCount) ? retryData.retryCount : 0;71 return (currentCount < this.retryCount);72 };73 tableService.createTable(tableName, function (err) {74 test.equal(err, null);75 tableService.deleteTable(tableName, function (err2) {76 test.equal(err2, null);77 // trying to create a table right after a delete should force retry to kick in78 // table should be created nicely79 tableService.createTable(tableName, function (err3) {80 test.equal(err3, null);81 test.done();82 });83 });84 });85 },86 testGetTablePassOnGetTable: function (test) {87 var tableName = testutil.generateId(tablePrefix, tableNames, tabletestutil.isMocked);88 var retryCount = 3;89 var retryInterval = 30;90 exponentialRetryPolicyFilter.retryCount = retryCount;91 exponentialRetryPolicyFilter.retryInterval = retryInterval;92 tableService.getTable(tableName, function (err, table) {93 test.equal(err.code, Constants.StorageErrorCodeStrings.RESOURCE_NOT_FOUND);94 test.equal(table, null);95 test.done();96 });97 }...
linearretrypolicyfilter-tests.js
Source:linearretrypolicyfilter-tests.js
1/**2* Copyright 2011 Microsoft Corporation3*4* Licensed under the Apache License, Version 2.0 (the "License");5* you may not use this file except in compliance with the License.6* You may obtain a copy of the License at7* http://www.apache.org/licenses/LICENSE-2.08*9* Unless required by applicable law or agreed to in writing, software10* distributed under the License is distributed on an "AS IS" BASIS,11* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12* See the License for the specific language governing permissions and13* limitations under the License.14*/15var testCase = require('nodeunit').testCase;16var azure = require("../../lib/azure");17var testutil = require('../util/util');18var tabletestutil = require('../util/table-test-utils');19var ServiceClient = require('../../lib/services/serviceclient');20var LinearRetryPolicyFilter = require('../../lib/common/linearretrypolicyfilter');21var Constants = require('../../lib/util/constants');22var tableService;23var linearRetryPolicyFilter;24var tableNames = [];25var tablePrefix = 'linearretry';26var testPrefix = 'linearretrypolicyfilter-tests';27module.exports = testCase(28{29 setUp: function (callback) {30 tabletestutil.setUpTest(module.exports, testPrefix, function (err, newTableService) {31 linearRetryPolicyFilter = new LinearRetryPolicyFilter();32 tableService = newTableService.withFilter(linearRetryPolicyFilter);33 callback();34 });35 },36 tearDown: function (callback) {37 tabletestutil.tearDownTest(module.exports, tableService, testPrefix, callback);38 },39 testRetryFailSingle: function (test) {40 var tableName = testutil.generateId(tablePrefix, tableNames, tabletestutil.isMocked);41 var retryCount = 3;42 var retryInterval = 30;43 linearRetryPolicyFilter.retryCount = retryCount;44 linearRetryPolicyFilter.retryInterval = retryInterval;45 tableService.createTable(tableName, function (err) {46 test.equal(err, null);47 tableService.createTable(tableName, function (err2) {48 test.notEqual(err2, null);49 test.equal(err2.code, Constants.TableErrorCodeStrings.TABLE_ALREADY_EXISTS);50 test.equal(err2.innerError, null);51 test.done();52 });53 });54 },55 testRetryFailMultiple: function (test) {56 var tableName = testutil.generateId(tablePrefix, tableNames, tabletestutil.isMocked);57 var retryCount = 3;58 // 30 seconds between attempts should be enough to give enough time for the59 // table creation to succeed after a deletion.60 var retryInterval = 30000;61 if (tabletestutil.isMocked && !tabletestutil.isRecording) {62 // if a playback on the mockserver is running, retryinterval can be lower63 retryInterval = 30;64 }65 linearRetryPolicyFilter.retryCount = retryCount;66 linearRetryPolicyFilter.retryInterval = retryInterval;67 // replace shouldRetry to skip return codes verification and retry on 409 (deleting)68 linearRetryPolicyFilter.shouldRetry = function (statusCode, retryData) {69 var currentCount = (retryData && retryData.retryCount) ? retryData.retryCount : 0;70 return (currentCount < this.retryCount);71 };72 tableService.createTable(tableName, function (err) {73 test.equal(err, null);74 tableService.deleteTable(tableName, function (err2) {75 test.equal(err2, null);76 // trying to create a table right after a delete should force retry to kick in77 // table should be created nicely78 tableService.createTable(tableName, function (err3) {79 test.equal(err3, null);80 test.done();81 });82 });83 });84 },85 testRetryPassOnGetTable: function (test) {86 var tableName = testutil.generateId(tablePrefix, tableNames, tabletestutil.isMocked);87 var retryCount = 3;88 var retryInterval = 30;89 linearRetryPolicyFilter.retryCount = retryCount;90 linearRetryPolicyFilter.retryInterval = retryInterval;91 tableService.getTable(tableName, function (err, table) {92 test.equal(err.code, Constants.StorageErrorCodeStrings.RESOURCE_NOT_FOUND);93 test.equal(table, null);94 test.done();95 });96 }...
Using AI Code Generation
1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5const should = chai.should();6const assert = chai.assert;7const expect = chai.expect;8const retryInterval = require('asyncbox').retryInterval;9const _ = require('lodash');10const { exec } = require('teen_process');11const path = require('path');12const { fs, mkdirp } = require('appium-support');13const { withRetries } = require('asyncbox');14const { retry }
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var androidDriver = require('appium-android-driver');4var driver = wd.promiseChainRemote('localhost', 4723);5driver.init({6}).then(function() {7 return driver.setImplicitWaitTimeout(5000);8}).then(function() {9 return driver.retryInterval(5000, 500, function() {10 });11}).then(function() {12 return driver.quit();13});
Using AI Code Generation
1var wd = require('wd');2var driver = wd.promiseChainRemote();3driver.init({4}).then(function() {5}).then(function() {6 return driver.title();7}).then(function(title) {8 console.log('Title is: ' + title);9}).fin(function() {10 return driver.quit();11}).done();12var wd = require('wd');13var driver = wd.promiseChainRemote();14driver.init({15}).then(function() {16}).then(function() {17 return driver.title();18}).then(function(title) {19 console.log('Title is: ' + title);20}).fin(function() {21 return driver.quit();22}).done();23var wd = require('wd');24var driver = wd.promiseChainRemote();25driver.init({26}).then(function() {27}).then(function() {28 return driver.title();29}).then(function(title) {30 console.log('Title is: ' + title);31}).fin(function() {32 return driver.quit();33}).done();34var wd = require('wd');35var driver = wd.promiseChainRemote();36driver.init({37}).then(function() {38}).then(function() {39 return driver.title();40}).then(function(title) {41 console.log('Title is: ' + title);42}).fin(function() {43 return driver.quit();44}).done();45var wd = require('wd');46var driver = wd.promiseChainRemote();47driver.init({48}).then(function() {49}).then(function() {50 return driver.title();51}).then(function(title) {52 console.log('Title is: ' + title);53}).fin(function() {54 return driver.quit();55}).done();56var wd = require('wd');57var driver = wd.promiseChainRemote();58driver.init({59}).then
Using AI Code Generation
1var wd = require('wd');2var retryInterval = 1000;3var retryTimes = 5;4var driver = wd.promiseChainRemote('localhost', 4723);5driver.init({6}).then(function () {7 return driver.waitForElementById('myButton', retryInterval, retryTimes);8}).then(function (el) {9 return el.click();10}).fin(function () {11 return driver.quit();12}).done();13waitForElement(locatorStrategy, locator, timeout, retryInterval)14waitForElement(locatorStrategy, locator, timeout, retryInterval, reverse)15waitForElement(locatorStrategy, locator, timeout, retryInterval, reverse, ignoreNonExistingElements)16waitForElement(locatorStrategy, locator, timeout, retryInterval, reverse, ignoreNonExistingElements, isGlobal)17waitForElement(locatorStrategy, locator, timeout, retryInterval, reverse, ignoreNonExistingElements, isGlobal, shouldThrow)18waitForElement(locatorStrategy, locator, timeout, retryInterval, reverse, ignoreNonExistingElements, isGlobal, shouldThrow, elementId)19waitForElement(locatorStrategy, locator, timeout, retryInterval, reverse, ignoreNonExistingElements, isGlobal, shouldThrow, elementId, context)20waitForElement(locatorStrategy, locator, timeout, retryInterval, reverse, ignoreNonExistingElements, isGlobal, shouldThrow, elementId, context, multiple)21waitForElement(locatorStrategy, locator, timeout, retryInterval, reverse, ignoreNonExistingElements, isGlobal, shouldThrow, elementId, context, multiple, waitMs)22waitForElement(locatorStrategy, locator, timeout, retryInterval, reverse, ignoreNonExistingElements, isGlobal, shouldThrow, elementId, context, multiple, waitMs, throwOnFailure)23waitForElement(locatorStrategy, locator, timeout, retryInterval, reverse, ignoreNonExistingElements, isGlobal, shouldThrow, elementId, context, multiple, waitMs, throwOnFailure, allowNoElement)24waitForElement(locator
Using AI Code Generation
1var wd = require('wd');2var retryInterval = require('wd/lib/helpers').retryInterval;3var desired = {4};5var browser = wd.promiseChainRemote('localhost', 4723);6 .init(desired)7 .elementByCssSelector("input[name='q']")8 .type("webdriver")9 .elementByCssSelector("button[name='btnG']")10 .click()11 .then(function() {12 return retryInterval(10, 1000, function() {13 .elementByCssSelector("#ires .g")14 .text()15 .should.become("webdriver - Google Search");16 });17 })18 .fin(function() { return browser.quit(); })19 .done();
Using AI Code Generation
1const wd = require('wd');2driver.init({3});4 .elementByAccessibilityId('buttonTest')5 .retryInterval(1000, 5, 1000)6 .click()7 .sleep(5000)8 .quit();9const wd = require('wd');10driver.init({11});12 .elementByAccessibilityId('buttonTest')13 .retryInterval(1000, 5, 1000)14 .click()15 .sleep(5000)16 .quit();17const wd = require('wd');18driver.init({19});20 .elementByAccessibilityId('buttonTest')21 .retryInterval(1000, 5, 1000)22 .click()23 .sleep(5000)24 .quit();
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!