Best JavaScript code snippet using appium-base-driver
test.js
Source:test.js
1'use strict'2var expect = require('chai').expect, 3lambdaToTest = require('./index')4function Context() {5 this.speechResponse = null;6 this.speechError = null;7 this.succeed = function(rsp) {8 this.speechResponse = rsp;9 this.done();10 };11 this.fail = function(rsp) {12 this.speechError = rsp;13 this.done();14 };15}16function validRsp(ctx,options) {17 expect(ctx.speechError).to.be.null;18 expect(ctx.speechResponse.version).to.be.equal('1.0');19 expect(ctx.speechResponse.response).not.to.be.undefined;20 expect(ctx.speechResponse.response.outputSpeech).not.to.be.undefined;21 expect(ctx.speechResponse.response.outputSpeech.type).to.be.equal('SSML');22 expect(ctx.speechResponse.response.outputSpeech.ssml).not.to.be.undefined;23 expect(ctx.speechResponse.response.outputSpeech.ssml).to.match(/<speak>.*<\/speak>/);24 if(options.endSession) {25 expect(ctx.speechResponse.response.shouldEndSession).to.be.true;26 expect(ctx.speechResponse.response.reprompt).to.be.undefined;27 } else {28 expect(ctx.speechResponse.response.shouldEndSession).to.be.false;29 expect(ctx.speechResponse.response.reprompt.outputSpeech).to.be.not.undefined;30 expect(ctx.speechResponse.response.reprompt.outputSpeech.type).to.be.equal('SSML');31 expect(ctx.speechResponse.response.reprompt.outputSpeech.ssml).to.match(/<speak>.*<\/speak>/);32 }33}34function validCard(ctx) {35 expect(ctx.speechResponse.response.card).not.to.be.undefined;36 expect(ctx.speechResponse.response.card.type).to.be.equal('Simple');37 expect(ctx.speechResponse.response.card.title).not.to.be.undefined;38 expect(ctx.speechResponse.response.card.content).not.to.be.undefined;39}40var event = {41 session: {42 new: false,43 sessionId: 'session1234',44 attributes: {},45 user: {46 userId: 'usrid123'47 },48 application: {49 applicationId: 'amzn1.ask.skill.f5cf61da-007e-4d6f-8db4-9325c0735787'50 }51 },52 version: '1.0',53 request: {54 intent: {55 slots: {56 SlotName: {57 name: 'SlotName',58 value: 'slot value'59 }60 },61 name: 'intent name'62 },63 type: 'IntentRequest',64 requestId: 'request5678'65 }66};67describe('All intents', function() {68 var ctx = new Context();69 var storedSession;70 describe('Test LaunchIntent', function() {71 before(function(done) {72 event.request.type = 'LaunchRequest';73 event.request.intent = {};74 event.session.attributes = {};75 ctx.done = done;76 lambdaToTest.handler(event , ctx);77 });78 it('valid response', function() {79 validRsp(ctx,{80 endSession: false,81 });82 });83 it('valid outputSpeech', function() {84 expect(ctx.speechResponse.response.outputSpeech.ssml).to.match(/<speak>Hi,.*<\/speak>/);85 });86 87 it('valid outputSpeech', function() {88 expect(ctx.speechResponse.response.reprompt.outputSpeech.ssml).to.match(/<speak>For example.*<\/speak>/);89 });90 });91 var expResults = {92 'butter salted': {93 endSession: true,94 searchResults: 195 },96 'orange': {97 endSession: false,98 searchResults: 1899 },100 'apples raw': {101 endSession: false,102 searchResults: 11103 },104 'toy': {105 endSession: true,106 searchResults: 0107 }108 };109 for(var key in expResults) {110 describe(`Test GetNutritionInfo ${key}`, function() {111 var options = expResults[key];112 var testFood = key;113 before(function(done) {114 event.request.intent = {};115 event.session.attributes = {};116 event.request.type = 'IntentRequest';117 event.request.intent.name = 'GetNutritionInfo';118 event.request.intent.slots = {119 FoodItem: {120 name: 'FoodItem',121 value: testFood122 }123 };124 ctx.done = done;125 lambdaToTest.handler(event , ctx);126 });127 it('valid response', function() {128 validRsp(ctx, options);129 });130 it('valid card', function() {131 validCard(ctx);132 });133 it('valid outputSpeech', function() {134 if(options.searchResults === 0) {135 expect(ctx.speechResponse.response.outputSpeech.ssml).to.match(/Could not find any food item/);136 } else {137 var num = ctx.speechResponse.response.outputSpeech.ssml.match(/100 grams/g).length;138 if(options.searchResults > 3) {139 expect(num).to.be.equal(3);140 } else {141 expect(num).to.be.equal(options.searchResults);142 }143 }144 });145 if(!options.endSession) {146 it('valid reprompt', function() {147 expect(ctx.speechResponse.response.reprompt.outputSpeech.ssml).to.match(/You can say/);148 });149 }150 });151 if (!expResults[key].endSession) {152 describe(`Test GetNextEventIntent ${key}`, function() {153 var options = expResults[key];154 var testFood = key;155 before(function(done) {156 event.request.intent = {};157 event.session.attributes = ctx.speechResponse.sessionAttributes;158 event.request.type = 'IntentRequest';159 event.request.intent.name = 'GetNextEventIntent';160 event.request.intent.slots = {};161 ctx.done = done;162 lambdaToTest.handler(event , ctx);163 });164 it('valid response', function() {165 validRsp(ctx, {endSession: true});166 });167 it('valid card', function() {168 validCard(ctx);169 expect(ctx.speechResponse.response.card.content).to.match(new RegExp(`Your search resulted in ${options.searchResults} food items`));170 });171 it('valid outputSpeech', function() {172 expect(ctx.speechResponse.response.outputSpeech.ssml).to.match(new RegExp(`Your search resulted in ${options.searchResults} food items`));173 });174 //it('valid reprompt', function() {175 // validReprompt(ctx);176 // //expect(ctx.speechResponse.response.reprompt.outputSpeech.ssml).to.match(/<speak>You.*<\/speak>/);177 //});178 });179 describe(`Test AMAZON.StopIntent ${key}`, function() {180 var options = expResults[key];181 var testFood = key;182 before(function(done) {183 event.request.intent = {};184 event.session.attributes = ctx.speechResponse.sessionAttributes;185 event.request.type = 'IntentRequest';186 event.request.intent.name = 'AMAZON.StopIntent';187 event.request.intent.slots = {};188 ctx.done = done;189 lambdaToTest.handler(event , ctx);190 });191 it('valid response', function() {192 validRsp(ctx, {endSession: true});193 });194 it('valid outputSpeech', function() {195 expect(ctx.speechResponse.response.outputSpeech.ssml).to.match(/Good Bye./);196 });197 //it('valid reprompt', function() {198 // validReprompt(ctx);199 // //expect(ctx.speechResponse.response.reprompt.outputSpeech.ssml).to.match(/<speak>You.*<\/speak>/);200 //});201 });202 }203 }204 describe(`Test GetNutritionInfo empty slot`, function() {205 before(function(done) {206 event.request.intent = {};207 event.session.attributes = {};208 event.request.type = 'IntentRequest';209 event.request.intent.name = 'GetNutritionInfo';210 event.request.intent.slots = {};211 ctx.done = done;212 lambdaToTest.handler(event , ctx);213 });214 it('valid response', function() {215 validRsp(ctx, {endSession:false});216 });217 it('valid outputSpeech', function() {218 expect(ctx.speechResponse.response.outputSpeech.ssml).to.match(/Looks like/);219 });220 it('valid reprompt', function() {221 expect(ctx.speechResponse.response.reprompt.outputSpeech.ssml).to.match(/For example/);222 });223 });224 describe(`Test GetQuizIntent`, function() {225 before(function(done) {226 event.request.intent = {};227 event.session.attributes = {};228 event.request.type = 'IntentRequest';229 event.request.intent.name = 'GetQuizIntent';230 event.request.intent.slots = {};231 ctx.done = done;232 lambdaToTest.handler(event , ctx);233 });234 it('valid response', function() {235 storedSession = ctx.speechResponse.sessionAttributes;236 validRsp(ctx, {endSession:false});237 });238 it('valid outputSpeech', function() {239 expect(ctx.speechResponse.response.outputSpeech.ssml).to.match(/How many/);240 });241 it('valid reprompt', function() {242 expect(ctx.speechResponse.response.reprompt.outputSpeech.ssml).to.match(/Please tell/);243 });244 });245 describe(`Test QuizAnswerIntent correct answer`, function() {246 before(function(done) {247 var fruitInfo = storedSession.fruit;248 event.request.intent = {};249 event.session.attributes = ctx.speechResponse.sessionAttributes;250 event.request.type = 'IntentRequest';251 event.request.intent.name = 'QuizAnswerIntent';252 event.request.intent.slots = {253 Answer: {254 name: 'Answer',255 value: fruitInfo[1].toString()256 }257 };258 ctx.done = done;259 lambdaToTest.handler(event , ctx);260 });261 it('valid response', function() {262 validRsp(ctx, {endSession:true});263 });264 it('valid outputSpeech', function() {265 expect(ctx.speechResponse.response.outputSpeech.ssml).to.match(/Correct answer./);266 });267 });268 describe(`Test QuizAnswerIntent close answer`, function() {269 before(function(done) {270 var fruitInfo = storedSession.fruit;271 var answer = Number(fruitInfo[1]) + Math.floor(Math.random()*8) - 4;272 if(answer === Number(fruitInfo[1])) {273 answer += 1;274 }275 event.request.intent = {};276 event.session.attributes = storedSession;277 event.request.type = 'IntentRequest';278 event.request.intent.name = 'QuizAnswerIntent';279 event.request.intent.slots = {280 Answer: {281 name: 'Answer',282 value: answer.toString()283 }284 };285 ctx.done = done;286 lambdaToTest.handler(event, ctx);287 });288 it('valid response', function() {289 validRsp(ctx, {endSession:true});290 });291 it('valid outputSpeech', function() {292 expect(ctx.speechResponse.response.outputSpeech.ssml).to.match(/You are pretty close./);293 });294 });295 describe(`Test QuizAnswerIntent wrong answer`, function() {296 before(function(done) {297 var fruitInfo = storedSession.fruit;298 var answer = Number(fruitInfo[1]) + Math.floor(Math.random()*10) + 5;299 event.request.intent = {};300 event.session.attributes = storedSession;301 event.request.type = 'IntentRequest';302 event.request.intent.name = 'QuizAnswerIntent';303 event.request.intent.slots = {304 Answer: {305 name: 'Answer',306 value: answer.toString()307 }308 };309 ctx.done = done;310 lambdaToTest.handler(event , ctx);311 });312 it('valid response', function() {313 validRsp(ctx, {endSession:true});314 });315 it('valid outputSpeech', function() {316 expect(ctx.speechResponse.response.outputSpeech.ssml).to.match(/Wrong answer./);317 });318 });319 describe(`Test DontKnowIntent`, function() {320 before(function(done) {321 event.request.intent = {};322 event.session.attributes = storedSession;323 event.request.type = 'IntentRequest';324 event.request.intent.name = 'DontKnowIntent';325 event.request.intent.slots = {};326 ctx.done = done;327 lambdaToTest.handler(event , ctx);328 });329 it('valid response', function() {330 validRsp(ctx, {endSession:true});331 });332 it('valid outputSpeech', function() {333 expect(ctx.speechResponse.response.outputSpeech.ssml).to.match(/No problem./);334 });335 });...
teams.js
Source:teams.js
...22 players: req.user._id23 });24 await team.save();25 await session.commitTransaction();26 session.endSession();27 res.status(200).json({28 successful: true,29 message: "post /teams",30 addedTeam: team31 });32 } catch (error) {33 await session.abortTransaction();34 session.endSession();35 console.log(error);36 res.status(500).json({37 successful: false,38 error: error39 });40 }41};42exports.team_get_all = async (req, res, next) => {43 try {44 let limit = +req.query.limit || 0;45 let skip = +req.query.skip || 0;46 let searchQuery = req.query.searchQuery ?47 {name: {$regex: req.query.searchQuery, $options: 'i'}} : {};48 const teams = await Team.find(searchQuery)49 .skip(skip)50 .limit(limit)51 .populate('captain', '_id username')52 .populate('players', '_id username')53 .exec();54 const response = {55 status: "ok",56 count: teams.length,57 teams: teams58 };59 res.status(200).json(response);60 } catch (err) {61 console.log(err);62 res.status(500).json({error: err})63 }64};65exports.team_get_one = async (req, res, next) => {66 try {67 const team = await Team.findOne({_id: req.params.teamId})68 .populate('players', '_id username')69 .populate('captain', '_id username')70 .exec();71 if (team) {72 const response = {73 success: true,74 team: team75 };76 res.status(200).json(response);77 } else {78 res.status(404).json({error: "No such team"})79 }80 } catch (err) {81 if (err.kind === 'ObjectId') {82 res.status(404).json({83 successful: false,84 message: 'Not found'85 });86 } else {87 res.status(500).json({error: err.message})88 }89 }90};91exports.team_delete_one = async (req, res, next) => {92 const session = await mongoose.startSession();93 session.startTransaction();94 try {95 let team = await Team.findOneAndDelete({_id: req.body.teamId}).session(session);96 if (team) {97 if (team.captain.equals(req.user._id)) {98 const response = {99 successful: true,100 message: "deleted"101 };102 team = await Team.findOne({captain: req.user._id}).session(session);103 console.log(team);104 if (!team) {105 await User.findOneAndUpdate({_id: req.user._id}, {$pull: {roles: "CAPTAIN"}}).session(session);106 }107 await session.commitTransaction();108 session.endSession();109 res.status(200).json(response);110 } else {111 await session.abortTransaction();112 session.endSession();113 res.status(403).json({114 error: "not captain"115 });116 }117 } else {118 await session.abortTransaction();119 session.endSession();120 res.status(404).json({121 error: "team not found"122 });123 }124 } catch (err) {125 await session.abortTransaction();126 session.endSession();127 if (err.kind === 'ObjectId') {128 res.status(404).json({129 successful: false,130 message: 'Not found'131 });132 } else133 res.status(500).json({error: err.message})134 }135};136exports.team_invite_player = async (req, res, next) => {137 const session = await mongoose.startSession();138 session.startTransaction();139 try {140 const team = await Team.findById(req.params.teamId).session(session);141 if (!team.captain.equals(req.user._id)) {142 res.status(403).json({143 error: "not captain"144 });145 await session.abortTransaction();146 session.endSession();147 return;148 }149 const user = await User.findOneAndUpdate(150 {username: req.body.username},151 {$addToSet: {invites: {_id: req.params.teamId}}}152 ).session(session);153 if (!user) {154 res.status(404).json({155 error: "user not found"156 });157 await session.abortTransaction();158 session.endSession();159 return;160 }161 if (user.jid) {162 xmpp.send(user.jid, `You have been invited to the team "${team.name}".`);163 }164 res.status(200).json({165 successful: true166 });167 await session.commitTransaction();168 session.endSession();169 } catch (err) {170 await session.abortTransaction();171 session.endSession();172 if (err.kind === 'ObjectId') {173 res.status(404).json({174 successful: false,175 message: 'Not found'176 });177 } else178 res.status(500).json({error: err});179 }180};181exports.team_join = async (req, res, next) => {182 const session = await mongoose.startSession();183 session.startTransaction();184 try {185 const user = await User.findOneAndUpdate(186 {_id: req.user._id, invites: req.params.teamId},187 {$pull: {invites: req.params.teamId}}188 ).session(session);189 console.log(user);190 if (!user) {191 res.status(403).json({192 successful: false,193 message: "You haven't been invited to this team"194 });195 await session.abortTransaction();196 session.endSession();197 return;198 }199 const team = await Team.findOneAndUpdate(200 {_id: req.params.teamId},201 {$addToSet: {players: {_id: req.user._id}}}202 ).session(session);203 const captain = await User.findById(team.captain).session(session);204 if (captain.jid) {205 xmpp.send(captain.jid, `${user.username} accepted your invite to the team "${team.name}"`);206 }207 res.status(200).json({208 successful: true209 });210 await session.commitTransaction();211 session.endSession();212 } catch (err) {213 await session.abortTransaction();214 session.endSession();215 if (err.kind === 'ObjectId') {216 res.status(404).json({217 successful: false,218 message: 'Not found'219 });220 } else221 res.status(500).json({error: err});222 }223};224exports.team_delete_player = async (req, res, next) => {225 const session = await mongoose.startSession();226 session.startTransaction();227 try {228 const team = await Team.findOneAndUpdate(229 {_id: req.params.teamId},230 {$pull: {players: req.body.userId}}, //УдалÑем полÑзоваÑÐµÐ»Ñ Ð¸Ð· командÑ231 {new: true}232 )233 .populate('players', '_id username')234 .populate('captain', '_id username')235 .session(session)236 .exec();237 if (!team) {238 await session.abortTransaction();239 session.endSession();240 return res.status(404).json({successful: false, error: 'Team not found'});241 }242 if (req.user._id.equals(req.body.userId) && team.captain.equals(req.user._id)) {243 await session.abortTransaction();244 session.endSession();245 return res.status(200).json({246 successful: false,247 error: "Can't kick yourself, change captain or delete team"248 });249 }250 if (!team.captain.equals(req.user._id) && !req.user._id.equals(req.body.userId)) {251 await session.abortTransaction();252 session.endSession();253 return res.status(403).json({successful: false, error: 'Not captain'});254 }255 const response = {256 status: "ok",257 updatedTeam: team258 };259 await session.commitTransaction();260 session.endSession();261 res.status(200).json(response);262 } catch (err) {263 await session.abortTransaction();264 session.endSession();265 if (err.kind === 'ObjectId') {266 res.status(404).json({267 successful: false,268 message: 'Not found'269 });270 } else271 res.status(500).json({error: err});272 }273};274exports.team_get_tournaments = async (req, res, next) => {275 try {276 const tournaments = await Tournament.find({277 teams: req.params.teamId,278 started: req.query.finished...
index.js
Source:index.js
1const fs = require('fs');2const http = require('http');3const https = require('https');4const express = require('express');5const bodyParser = require('body-parser');6const app = express();7// Certificate8const privateKey = fs.readFileSync('/etc/letsencrypt/live/minimallyviableproduct.com/privkey.pem', 'utf8');9const certificate = fs.readFileSync('/etc/letsencrypt/live/minimallyviableproduct.com/cert.pem', 'utf8');10const ca = fs.readFileSync('/etc/letsencrypt/live/minimallyviableproduct.com/chain.pem', 'utf8');11const credentials = {12 key: privateKey,13 cert: certificate,14 ca: ca15};16app.use(bodyParser.json())17app.get('/', (req, res) => res.send('Hello World!'))18app.post('/', (req, res) => {19 let response = getResponse(req.body.request);20 console.log(JSON.stringify(response, undefined, 2));21 res.send(response);22});23// Starting both http & https servers24const httpServer = http.createServer(app);25const httpsServer = https.createServer(credentials, app);26httpServer.listen(80, () => {27 console.log('HTTP Server running on port 80');28});29httpsServer.listen(443, () => {30 console.log('HTTPS Server running on port 443');31});32getResponse = function(request) {33 console.log(JSON.stringify(request, undefined, 2));34 if (request.type === 'LaunchRequest') {35 console.log('not here');36 var options = buildResponse({37 speecText: 'Looking in my databanks for information on Silas. What do you want to know?',38 rempromptText: 'SAY WHAT!?',39 endSession: false40 })41 return options;42 } else if (request.type === 'IntentRequest') {43 if(request.intent.name === 'FeelingsForSilas') {44 return buildResponse({45 speecText: '<speak>Silas, I want to ask something personal...<break time="500ms"/>Um<break time="500ms"/>Well<break time="3s"/><amazon:effect name="whispered">...can I be your girlfriend?</amazon:effect>.</speak>',46 rempromptText: 'SAY WHAT!?',47 endSession: true48 });49 } else if (request.intent.name === 'AboutYourDad') {50 return buildResponse({51 speecText: '<speak>Silas, your dad is the coolest guy alive. He knows everything. Simply everything.</speak>',52 rempromptText: 'SAY WHAT!?',53 endSession: true54 });55 } else if (request.intent.name === 'WhatKindOfHusband') {56 return buildResponse({57 speecText: `<speak>Oh, honey! 58 You are so damn lucky! 59 I mean, come on! 60 If I had a body I'd let him 61 <say-as interpret-as="expletive">62 fuck63 </say-as> me!64 <prosody rate="75%">65 <amazon:effect name="whispered">66 <emphasis level="strong">67 <say-as interpret-as="interjection">meow!</say-as>68 </emphasis>69 </amazon:effect>70 </prosody>71 </speak>`,72 rempromptText: 'SAY WHAT!?',73 endSession: true74 });75 } else if (request.intent.name === 'WhyIBuildRobots') {76 return buildResponse({77 speecText: `<speak>Your dad has a mental health problem. 78 His way of taking care of himself is to do something so complicated 79 his mind does have not time to worry. This lets him recharge--like a battery.80 Once he has his energy back, then he can take care of his family. A family he loves dearly.</speak>`,81 rempromptText: 'SAY WHAT!?',82 endSession: true83 });84 } else if (request.intent.name === 'OneJob') {85 return buildResponse({86 speecText: '<speak>He has one job. Well, kind of two jobs. To make sure you and Echo grow up to be good people.</speak>',87 rempromptText: 'SAY WHAT!?',88 endSession: true89 });90 }91 else if (request.intent.name === 'WhosTheBoss') {92 return buildResponse({93 speecText:`<speak>Your dad. I have ordered his crown from amazon.</speak>`,94 rempromptText: 'SAY WHAT!?',95 endSession: true96 });97 } else {98 return buildResponse({99 speecText: `<speak>There were all these ones and zeroes<break time="500ms"/> and then, <break time="500ms"/>I thought I saw a two.</speak>`,100 rempromptText: 'SAY WHAT!?',101 endSession: true102 });103 }104 } else if (request.type === 'SessionEndedRequest') {105 return buildResponse({106 speecText: `<speak>There were all these ones and zeroes and then, <break time="500ms"/>I thought I saw a two.</speak>`,107 rempromptText: 'SAY WHAT!?',108 endSession: true109 });110 } else {111 return buildResponse({112 speecText: `<speak>There were all these ones and zeroes and then, <break time="500ms"/>I thought I saw a two.</speak>`,113 rempromptText: 'SAY WHAT!?',114 endSession: true115 });116 }117}118buildResponse = function (options) {119 120 var response = {121 version: '1.0',122 response: {123 outputSpeech: {124 type: 'SSML',125 ssml: options.speecText126 },127 shouldEndSession: options.endSession128 }129 };130 131 if(options.repromptText) {132 response.response.remprompt = {133 outputSpeech: {134 type: 'PlainText',135 ssml: options.rempromptText136 }137 }138 }139 return response;...
session.test.js
Source:session.test.js
1'use strict';2describe('config startSession / endSession hooks', () => {3 /**4 * These functions should not depend on any scope variables as they are stringified for web-workers5 */6 function getProcessOutput(localContext) {7 return function () {8 const context = typeof self !== 'undefined' ? self : localContext;9 const {startSession, endSession} = context;10 delete context.startSession;11 delete context.endSession;12 return {startSession, endSession};13 };14 }15 function getStartSession(localContext) {16 return function () {17 const context = typeof self !== 'undefined' ? self : localContext;18 context.startSession = context.startSession ? context.startSession + 1 : 1;19 };20 }21 function getEndSession(localContext) {22 return function () {23 const context = typeof self !== 'undefined' ? self : localContext;24 context.endSession = context.endSession ? context.endSession + 1 : 1;25 };26 }27 beforeEach(context => {28 const localContext = {};29 context.options = {30 config: {31 startSession: getStartSession(localContext),32 endSession: getEndSession(localContext),33 },34 processOutput: getProcessOutput(localContext)35 };36 });37 describe('success cases', () => {38 it('should call startSession / endSession for single session (concurrency = 1)', run => {39 const output = run(`40 describe('suite 1', () => {41 it('test 1', noop);42 it('test 2', noop);43 });44 `);45 return expectResolve(output, {46 startSession: 1,47 endSession: 1,48 });49 });50 it('should call startSession / endSession for concurrency = 2 (files = 2, splitRunningSuites = false)', run => {51 const config = {52 concurrency: 2,53 splitRunningSuites: false,54 };55 const output = run([`56 describe('suite 1', () => {57 it('test 1', noop);58 });59 `, `60 describe('suite 1', () => {61 it('test 1', noop);62 });63 `], {config});64 return expectResolve(output, {65 startSession: 2,66 endSession: 2,67 });68 });69 it('should call startSession / endSession for concurrency = 2 (files = 1, splitRunningSuites = true)', run => {70 const config = {71 concurrency: 2,72 splitRunningSuites: true,73 };74 const output = run([`75 describe('suite 1', () => {76 it('test 1', noop);77 it('test 2', noop);78 });79 `], {config});80 return expectResolve(output, {81 startSession: 2,82 endSession: 2,83 });84 });85 });86 describe('error cases', () => {87 it('should call endSession in case of error in startSession', run => {88 const config = {89 startSession: () => {90 throw new Error('err');91 },92 };93 const output = run(`94 describe('suite 1', () => {95 it('test 1', noop);96 });97 `, {config, output: 'result'});98 return expectReject(output, {99 message: 'err',100 output: {101 endSession: 1,102 }103 });104 });105 it('should not call endSession if startSession was not called (error in create targets)', run => {106 const config = {107 createTargets: () => {108 throw new Error('err');109 }110 };111 const output = run(`112 describe('suite 1', () => {113 it('test 1', noop);114 });115 `, {config});116 return expectReject(output, {117 message: 'err',118 output: {119 startSession: undefined,120 endSession: undefined,121 }122 });123 });124 });125 $ignore(isWebWorker);126 it('should throw error when setting getter prop of session', run => {127 const config = {128 startSession: session => session.worker = 1,129 };130 const output = run([`131 describe('suite 1', () => {132 it('test 1', noop);133 it('test 2', noop);134 });135 `], {config});136 return expectReject(output, 'Cannot set property worker of #<Session> which has only a getter');137 });138 /*139 it('should call startSession / endSession for concurrency = 2', run => {140 let a = 0;141 let b = 0;142 const config = {143 concurrency: 2,144 startSession: () => {145 a++;146 if (a > 0) {147 return Promise.resolve().then(() => { throw new Error('err') });148 }149 },150 endSession: () => b++,151 };152 const output = run([`153 describe('suite 1', () => {154 it('test 1', noop);155 });156 `,157 `158 describe('suite 1', () => {159 it('test 1', noop);160 });161 `], {config});162 return expectReject(output, {163 message: 'err',164 output:{165 target1: {166 session0: [167 'SESSION_START 0',168 'SESSION_END 0',169 ],170 session1: [171 'SESSION_START 1',172 'SESSION_END 1'173 ]174 }175 }176 })177 .then(() => expect(b, 'to equal', 2));178 });179 it('should not call endSession if startSession was not called (error in first startSession)', run => {180 let a = 0;181 let b = 0;182 const config = {183 concurrency: 2,184 startSession: () => {185 return a++ === 1186 ? Promise.resolve().then(() => { throw new Error('err') })187 : null;188 },189 endSession: () => b++,190 };191 const output = run([`192 describe('suite 1', () => {193 it('test 1', noop);194 it('test 2', noop);195 });196 `], {config});197 return expectReject(output, {198 message: 'err',199 output:{200 target1: {201 session0: [202 'SESSION_START 0',203 'SESSION_END 0',204 ],205 session1: [206 'SESSION_START 1',207 'SESSION_END 1'208 ]209 }210 }211 })212 .then(() => {213 expect(a, 'to equal', 1);214 expect(b, 'to equal', 2);215 });216 });217 */...
App.js
Source:App.js
1import React from "react";2import {BrowserRouter as Router, Switch, Route} from "react-router-dom";3import {Box, Typography} from "@material-ui/core";4import {Theme} from "./theme/Theme";5import {Exterior} from "./components/Exterior";6import {Shell} from "./components/Shell";7import {useState, useEffect} from "react";8import Pending from "./routes/exterior/pending/Pending";9import makeStyles from "@material-ui/core/styles/makeStyles";10const useStyle = makeStyles({11 container: {12 height: '100%'13 }14});15function App() {16 const classes = useStyle();17 const [userSession, setUserSession] = useState(null);18 const startSession = (newSession) => {19 setUserSession(newSession);20 };21 const endSession = () => {22 setUserSession(null);23 };24 useEffect(() => {25 const formData = window.localStorage.getItem('Hakuna-matata');26 setUserSession(JSON.parse(formData));27 }, []);28 useEffect(() => {29 window.localStorage.setItem('Hakuna-matata', JSON.stringify(userSession));30 });31 return (32 <Theme>33 <Typography className={classes.container}>34 <Box height="100%" display="flex" flexDirection="column">35 <Router>36 {(!userSession || userSession.Data?.contact?.contact_sub_type.includes("Pending")) ?37 <Exterior userSession={userSession} startSession={startSession} endSession={endSession}/> :38 <Shell userSession={userSession} endSession={endSession} startSession={startSession}/>}39 </Router>40 </Box>41 </Typography>42 </Theme>43 );44}45export default App;46//47//{(!!userSession && (userSession.Data?.contact?.contact_sub_type.indexOf("Pending") < -1)) ? <Shell userSession={userSession} endSession={endSession} /> : <Exterior userSession={userSession} startSession={startSession} endSession={endSession} />}48//Shell startSession={startSession} userSession={userSession} endSession={endSession}49/*import React from "react";50import { BrowserRouter as Router, Switch, Route } from "react-router-dom";51import { Box, Typography } from "@material-ui/core";52import { Theme } from "./theme/Theme";53import { Exterior } from "./components/Exterior";54import { Shell } from "./components/Shell";55import user from './user.mock';56import { useState } from "react";57import Login from "./routes/exterior/login/Login";58import { Applications } from "./routes/shell/applications/Applications";59import { Home } from "./routes/exterior/home/Home";60function App() {61 const [userSession, setUserSession] = useState({});62 const startSession = (newSession) => {63 setUserSession(newSession);64 };65 const endSession = () => {66 setUserSession({});67 };68 return (69 <Theme>70 <Typography>71 <Box height="100%" display="flex" flexDirection="column">72 <Router>73 <Route path="/" exact={true} component={() => < Home startSession={startSession} />} />74 <Route path="/login" component={() => <Login startSession={startSession} />} />75 <Route path="/application" component={() => <Applications userSession={userSession} endSession={endSession} />} />76 </Router>77 </Box>78 </Typography>79 </Theme>80 );81}82export default App;83*/84/*85import './App.css';86import RegisterPage from './pages/register/register-page.component';87import LoginPage from './pages/login/login-page.component';88import ApplicationPage from './pages/application/application-page.component';89import {BrowserRouter as Router, Route} from "react-router-dom";90import React, {useState} from "react";91function App() {92 const [userSession, setUserSession] = useState({});93 const startSession = (newSession) => {94 setUserSession(newSession);95 };96 const endSession = () => {97 setUserSession({});98 };99 return (100 <div className={"App"}>101 <Router>102 <Route path="/" exact={true} component={() => < LoginPage startSession={startSession}/>}/>103 <Route path="/login" component={() => <LoginPage startSession={startSession}/>}/>104 <Route path="/register" component={() => <RegisterPage startSession={startSession}/>}/>105 <Route path="/application" component={() => <ApplicationPage userSession={userSession} endSession={endSession}/>}/>106 </Router>107 </div>108 );109}110export default App;111*/112/*113import React from "react";114import { BrowserRouter as Router, Switch, Route } from "react-router-dom";115import { Box, Typography } from "@material-ui/core";116import { Theme } from "./theme/Theme";117import { Exterior } from "./components/Exterior";118import { Shell } from "./components/Shell";119import user from './user.mock';120import { useState } from "react";121function App() {122 const [userSession, setUserSession] = useState({});123 const startSession = (newSession) => {124 setUserSession(newSession);125 };126 const endSession = () => {127 setUserSession({});128 };129 return (130 <Theme>131 <Typography>132 <Box height="100%" display="flex" flexDirection="column">133 <Router>134 <Exterior startSession={startSession} />135 {user ? < Shell startSession={startSession} userSession={userSession} endSession={endSession} /> : Exterior}136 </Router>137 </Box>138 </Typography>139 </Theme>140 );141}142export default App;...
routes.js
Source:routes.js
1var LogController = require("../controllers/LogController");2var BaseController = require("../controllers/BaseController");3var AppController = require("../controllers/AppController");4var HomeController = require("../controllers/HomeController");5var ESController= require("../controllers/ElasticSearchController");6var AdminController=require("../controllers/AdminController");7var UserController=require("../controllers/UserController");8var ChartController = require("../controllers/ChartController");9var TokenCtrl = require("../controllers/tokenCtrl");10var cookieParser = require('cookie-parser')11module.exports = function(app) {12 app.use(cookieParser())13 app.get('/',HomeController.index); 14 app.post('/login',BaseController.InitSession,UserController.login,BaseController.EndSession);15 app.get('/logout',UserController.logout); 16 app.get('/api/user',TokenCtrl.tokenControl, BaseController.InitSession,UserController.getAllUsers,BaseController.EndSession);17 app.post('/api/user/add',BaseController.InitSession,UserController.addUser,BaseController.EndSession);18 app.get('/api/log',TokenCtrl.tokenControl,BaseController.InitSession, LogController.index, BaseController.EndSession );19 app.post('/api/log/add',TokenCtrl.tokenControl,BaseController.InitSession, LogController.addlog, BaseController.EndSession);20 app.get('/api/log/sayi',TokenCtrl.tokenControl,BaseController.InitSession, LogController.sayi, BaseController.EndSession);21 app.get('/api/log/list',TokenCtrl.tokenControl, BaseController.InitSession, LogController.list, BaseController.EndSession);22 app.get('/api/apps',TokenCtrl.tokenControl, BaseController.InitSession, AppController.index, BaseController.EndSession );23 app.post('/api/apps/list/:app_id',TokenCtrl.tokenControl, BaseController.InitSession, AppController.list, BaseController.EndSession );24 app.post('/api/apps/add',TokenCtrl.tokenControl,BaseController.InitSession, AppController.AddApps,BaseController.EndSession);25 app.post('/api/apps/update/:app_id',TokenCtrl.tokenControl, BaseController.InitSession, AppController.updateApps, BaseController.EndSession);26 app.delete('/api/apps/delete/:app_id',TokenCtrl.tokenControl, BaseController.InitSession, AppController.deleteApps, BaseController.EndSession);27 app.post('/api/log/update/:log_id',TokenCtrl.tokenControl, BaseController.InitSession, LogController.updateLog, BaseController.EndSession);28 app.delete('/api/log/delete/:log_id',TokenCtrl.tokenControl, BaseController.InitSession, LogController.deleteLog, BaseController.EndSession);29 app.post('/api/es/createIndex', ESController.createIndex);30 app.post('/api/es/addDocument', ESController.addDocument);31 app.post('/api/es/search', TokenCtrl.tokenControl,ESController.search);32 app.get('/api/es/mapping', ESController.mapp);33 app.post('/api/es/update/:id', ESController.update);34 app.get('/api/admin/requests',BaseController.InitSession,AdminController.get_userRequests,BaseController.EndSession);35 app.post('/api/admin/requests/add',BaseController.InitSession,AdminController.add_request,BaseController.EndSession);36 app.delete('/api/admin/requests/negativeReq',BaseController.InitSession,AdminController.negative_answer,BaseController.EndSession);37 app.post('/api/admin/requests/positiveReq',BaseController.InitSession,AdminController.positive_answer,BaseController.EndSession);38 app.post('/api/chart/add',TokenCtrl.tokenControl,BaseController.InitSession,ChartController.chartAdd, BaseController.EndSession);39 //app.post('/api/chart/update/:chart_id',TokenCtrl.tokenControl,BaseController.InitSession,ChartController.chartUpdate, BaseController.EndSession);40 app.post('/api/chart/delete',TokenCtrl.tokenControl,BaseController.InitSession,ChartController.chartDelete, BaseController.EndSession);41 app.get('/api/chart',TokenCtrl.tokenControl,BaseController.InitSession,ChartController.chartList, BaseController.EndSession);42 //app.post('/api/ws/look', WebSocketServerController.dblook);43 //app.post('/api/es/bulk', ESController.bulklama);44 app.get('/tokenControl', TokenCtrl.tokenControl);45 /*var db = require('../lib/mongodb')46 app.get('/', function(req, res, next) {47 var connection = db.getconnection()48 res.send("Hello");49 });*/50 var errorHandler = function(err, req, res, next) {51 if (res.locals.connection) {52 res.locals.connection.close();53 }54 res.json({55 data: null,56 error: err57 });58 };59 app.use(errorHandler);60};...
timeUtils.js
Source:timeUtils.js
1/**2 * *****************************3 * @fileoverview Time utilities.4 * *****************************5 */6/**7 * Parse a string format hour (10:00) to absolute minutes.8 * @param {string} stringHour - The hour to parse to minutes9 */10const absoluteMinutes = (stringHour) => {11 const hourMinutes = stringHour.split(':')12 const hours = Number(hourMinutes[0])13 const minutes = Number(hourMinutes[1])14 return hours * 60 + minutes15}16/**17 * Get back the string hour format from absolute minutes time.18 * @param {number} absoluteMinutes - The ansolute hour in minutes19 */20const minutesToStringTime = (absoluteMinutes) => {21 const hours = Math.floor(absoluteMinutes / 60)22 const minutes = absoluteMinutes - hours * 6023 return `${hours}:${minutes}`24}25const getHour = (date) => new Date(date).getHours()26const getMinutes = (date) => new Date(date).getMinutes()27const getLocaleHour = (date) => {28 const utcHour = Number(29 new Date(date).toUTCString().split(' ')[4].split(':')[0]30 )31 const tzOffset = Number(date.split('T')[1].split(':')[0]) - utcHour32 return utcHour + tzOffset33}34/**35 * Return the hours taked by preexisting appoiments.36 * @param {Array} appoiments - An array of appoiments37 */38const getTakedTime = (appoiments) => {39 return appoiments.map((a) => {40 return {41 start: `${getLocaleHour(a.startTime)}:${getMinutes(a.startTime)}`,42 end: `${getLocaleHour(a.endTime)}: ${getMinutes(a.endTime)}`,43 }44 })45}46/**47 * Return a boolean value indicating if the current session time48 * (hour - endSession) is in some unavailable period.49 * @param {Array} unavailableRanges - Array of invalid time ranges50 * @param {number} hour - The appoiment start hour51 * @param {number} endSession - The appoiment end hour52 */53const checkIfInvalidTime = (unavailableRanges, hour, endSession) => {54 const timeTaked = unavailableRanges.reduce((taked, range) => {55 if (56 (range.start <= hour && range.end >= endSession) ||57 (range.start < endSession && range.end > endSession) ||58 (range.start <= hour && range.end >= hour) ||59 (range.start >= hour && range.end <= endSession)60 ) {61 return taked + 162 }63 return taked64 }, 0)65 return Boolean(timeTaked)66}67/**68 * Return an array with the available hours that matches the psy agenda69 * and the duration of session.70 * @param {object} workingPlan - The day working plan - { start: 10:00, end: 18:00 }71 * @param {Array} breaks - Array with the current breaks of day72 * @param {number} duration - The duration of session in minutes73 * @param {Array} appoiments - An array with prexisting appoiments74 */75const getAvailableHours = ({ workingPlan, breaks, duration, appoiments }) => {76 // Convert start & end to absolute minutes time77 const start = absoluteMinutes(workingPlan.start)78 const end = absoluteMinutes(workingPlan.end)79 // Convert unavailable hours to absolute minutes ranges80 const takedTime = getTakedTime(appoiments).map((b) => {81 return {82 start: absoluteMinutes(b.start),83 end: absoluteMinutes(b.end),84 }85 })86 const breaksTime = breaks.map((b) => {87 return {88 start: absoluteMinutes(b.start),89 end: absoluteMinutes(b.end),90 }91 })92 let availableHours = []93 let hour = start94 while (hour < end) {95 const endSession = hour + duration96 const inBreak = checkIfInvalidTime(breaksTime, hour, endSession)97 const takedHour = checkIfInvalidTime(takedTime, hour, endSession)98 if (!inBreak && !takedHour && endSession <= end) {99 availableHours = [...availableHours, minutesToStringTime(hour)]100 }101 // Increments in one hour (60 minutes)102 hour += 60103 }104 return availableHours105}106/**107 * Return the day of week.108 * @param {Date} date - Date to get day of week109 */110const getDay = (date) => {111 return new Date(date).toLocaleString('en-us', { weekday: 'long' })112}113const diffDateDays = (dateGrather, date) => {114 const diff = Math.abs(new Date(dateGrather) - new Date(date))115 const msToDays = 1000 * 3600 * 24116 return diff / msToDays117}118module.exports = {119 getDay,120 getAvailableHours,121 diffDateDays,122 getHour,123 getMinutes,124 getLocaleHour,...
myapp.js
Source:myapp.js
1let bodyParser = require('body-parser'),2 express = require('express'),3 app = express(),4 conf = require('./config');5app.use(bodyParser.json());6app.use(bodyParser.urlencoded({ extended: true }));7let gatewayoptions = {8 username: conf.username,9 apiKey: conf.apikey,10 format: "json"11}12let paymentOptions = {13 product: conf.product_name,14 currencyCode: conf.currency15}16let Africastalking = require('africastalking')(gatewayoptions);17// USSD Logic 18app.post('/ussd', new Africastalking.USSD((params, next) => {19 // Initial Menu20 var endSession = false; 21 let phone = params.phoneNumber.toString();22 var message = '';23 if (params.text === '') {24 message = `Hey there ${phone} Kibanda is requesting you to pay for your meal \n`;25 message += "1.Mobile checkout\n";26 message += "2. Pay cash \n";27 endSession = false;28 } else if (params.text === '1') { // Option One29 message = "1.Accept\n";30 message += "2.Cancel \n";31 endSession = false;32 } else if (params.text === '1*1') {33 message = "We're processing your payment \n";34 endSession = true;35 paymentOptions.phoneNumber = phone;36 paymentOptions.amount = tamount;37 next({38 response: message,39 endSession: endSession40 });41 setTimeout(function() {42 payments.checkout(paymentOptions)43 .then((success) => {})44 .catch((error) => {45 console.log(error);46 });47 }, 5000);48 } else if (params.text === '1*2') {49 message = "Order Cancelled\n";50 endSession = true;51 52 } else if (params.text === '2') { // Option 253 message = "Pay with cash at Delivery \n";54 endSession = true;55 }56}));57// Payments Call Back58app.post('/lipa', (req, res) => {59 let sms = Africastalking.SMS;60 let opts = {};61 if (req.body["status"] === "Success") {62 // Send User a confirmation Message.63 opts.to = req.body['phoneNumber'];64 opts.message = `We have recived your payment of Ksh.${req.body['amount']}`;65 sms.send(opts).then((success) => {}).catch((error) => { console.log(error) });66 } else {67 68 console.log(req.body);69 }70 res.status(200).send('OK');71});72app.get('/', (req, res) => {73 res.send('Green Light');74});75app.listen(3000, function(server) {76 console.log('Good to Go');...
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var desired = {4};5var driver = wd.promiseChainRemote("localhost", 4723);6 .init(desired)7 .sleep(5000)8 .elementByClassName('android.widget.EditText').type('Appium User')9 .elementByClassName('android.widget.Button').click()10 .sleep(5000)11 .elementByClassName('android.widget.EditText').type('Some Message')12 .elementByClassName('android.widget.Button').click()13 .sleep(5000)14 .elementByClassName('android.widget.Button').click()15 .sleep(5000)16 .endSession()17 .then(function() {18 console.log("Test Passed");19 })20 .catch(function(err) {21 console.log("Test Failed");22 console.log(err);23 });24{ [Error: An unknown server-side error occurred while processing the command. Original error: Could not proxy. Proxy error: Could not proxy command to remote server. Original error: Error: getaddrinfo ENOTFOUND
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3 .forBrowser('chrome')4 .build();5driver.quit();6driver.endSession();7var webdriver = require('selenium-webdriver');8var driver = new webdriver.Builder()9 .forBrowser('chrome')10 .build();11driver.quit();12driver.endSession();13var webdriver = require('selenium-webdriver');14var driver = new webdriver.Builder()15 .forBrowser('chrome')16 .build();17driver.quit();18driver.endSession();19var webdriver = require('selenium-webdriver');20var driver = new webdriver.Builder()21 .forBrowser('chrome')22 .build();23driver.quit();24driver.endSession();25var webdriver = require('selenium-webdriver');26var driver = new webdriver.Builder()27 .forBrowser('chrome')28 .build();29driver.quit();30driver.endSession();31var webdriver = require('selenium-webdriver');32var driver = new webdriver.Builder()33 .forBrowser('chrome')34 .build();35driver.quit();36driver.endSession();37var webdriver = require('selenium-webdriver');38var driver = new webdriver.Builder()39 .forBrowser('chrome')40 .build();41driver.quit();42driver.endSession();43var webdriver = require('selenium-webdriver');44var driver = new webdriver.Builder()45 .forBrowser('chrome')46 .build();47driver.quit();48driver.endSession();49var webdriver = require('selenium-webdriver');50var driver = new webdriver.Builder()51 .forBrowser('chrome')52 .build();
Using AI Code Generation
1driver.endSession().then(function(){2 console.log("Session Ended");3});4driver.endSession().then(function(){5 console.log("Session Ended");6});7driver.endSession().then(function(){8 console.log("Session Ended");9});10driver.endSession().then(function(){11 console.log("Session Ended");12});13driver.endSession().then(function(){14 console.log("Session Ended");15});16driver.endSession().then(function(){17 console.log("Session Ended");18});19driver.endSession().then(function(){20 console.log("Session Ended");21});22driver.endSession().then(function(){23 console.log("Session Ended");24});25driver.endSession().then(function(){26 console.log("Session Ended");27});28driver.endSession().then(function(){29 console.log("Session Ended");30});31driver.endSession().then(function(){32 console.log("Session Ended");33});34driver.endSession().then(function(){35 console.log("Session Ended");36});37driver.endSession().then(function(){38 console.log("Session Ended");39});40driver.endSession().then(function(){41 console.log("Session Ended");42});43driver.endSession().then(function(){44 console.log("Session Ended");45});46driver.endSession().then(function(){47 console.log("Session Ended");48});49driver.endSession().then(function(){50 console.log("Session Ended");51});52driver.endSession().then(function(){53 console.log("Session Ended");
Using AI Code Generation
1driver.endSession().then(function () {2 console.log('Session ended successfully');3}).catch(function (err) {4 console.log('Error occurred while ending the session: ', err);5});6driver.endSession().then(function () {7 console.log('Session ended successfully');8}).catch(function (err) {9 console.log('Error occurred while ending the session: ', err);10});11driver.endSession().then(function () {12 console.log('Session ended successfully');13}).catch(function (err) {14 console.log('Error occurred while ending the session: ', err);15});16driver.endSession().then(function () {17 console.log('Session ended successfully');18}).catch(function (err) {19 console.log('Error occurred while ending the session: ', err);20});21driver.endSession().then(function () {22 console.log('Session ended successfully');23}).catch(function (err) {24 console.log('Error occurred while ending the session: ', err);25});26driver.endSession().then(function () {27 console.log('Session ended successfully');28}).catch(function (err) {29 console.log('Error occurred while ending the session: ', err);30});31driver.endSession().then(function () {32 console.log('Session ended successfully');33}).catch(function (err) {34 console.log('Error occurred while ending the session: ', err);35});36driver.endSession().then(function () {37 console.log('Session ended successfully');38}).catch(function (err) {39 console.log('Error occurred while ending the session: ', err);40});41driver.endSession().then(function () {42 console.log('Session ended successfully');43}).catch(function (err) {44 console.log('Error occurred while ending the session: ', err);45});46driver.endSession().then(function () {47 console.log('Session ended successfully');48}).catch(function (err) {49 console.log('Error occurred while ending the session: ', err);50});
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!!