How to use server.getWebSocketHandlers method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

ah1.js

Source:ah1.js Github

copy

Full Screen

...583helpers.removeAllSessionWebSocketHandlers = async function (server, sessionId) {584 if (!server || !_.isFunction(server.getWebSocketHandlers)) {585 return;586 }587 const activeHandlers = await server.getWebSocketHandlers(sessionId);588 for (const pathname of _.keys(activeHandlers)) {589 await server.removeWebSocketHandler(pathname);590 }591};592/**593 * Takes a desired capability and tries to JSON.parse it as an array,594 * and either returns the parsed array or a singleton array.595 *596 * @param {any} cap A desired capability597 */598helpers.parseArray = function (cap) {599 let parsedCaps;600 try {601 parsedCaps = JSON.parse(cap);...

Full Screen

Full Screen

android-helpers.js

Source:android-helpers.js Github

copy

Full Screen

...534helpers.removeAllSessionWebSocketHandlers = async function (server, sessionId) {535 if (!server || !_.isFunction(server.getWebSocketHandlers)) {536 return;537 }538 const activeHandlers = await server.getWebSocketHandlers(sessionId);539 for (const pathname of _.keys(activeHandlers)) {540 await server.removeWebSocketHandler(pathname);541 }542};543/**544 * Takes a desired capability and tries to JSON.parse it as an array,545 * and either returns the parsed array or a singleton array.546 *547 * @param {any} cap A desired capability548 */549helpers.parseArray = function (cap) {550 let parsedCaps;551 try {552 parsedCaps = JSON.parse(cap);...

Full Screen

Full Screen

utils.js

Source:utils.js Github

copy

Full Screen

...297async function removeAllSessionWebSocketHandlers (server, sessionId) {298 if (!server || !_.isFunction(server.getWebSocketHandlers)) {299 return;300 }301 const activeHandlers = await server.getWebSocketHandlers(sessionId);302 for (const pathname of _.keys(activeHandlers)) {303 await server.removeWebSocketHandler(pathname);304 }305}306/**307 * @typedef {Object} PlatformOpts308 *309 * @property {boolean} isSimulator - Whether the destination platform is a Simulator310 * @property {boolean} isTvOS - Whether the destination platform is a Simulator311 */312/**313 * Verify whether the given application is compatible to the314 * platform where it is going to be installed and tested.315 *...

Full Screen

Full Screen

log.js

Source:log.js Github

copy

Full Screen

...59 * as soon as they are visible to Appium.60 */61extensions.mobileStartLogsBroadcast = async function () {62 const pathname = WEBSOCKET_ENDPOINT(this.sessionId);63 if (!_.isEmpty(await this.server.getWebSocketHandlers(pathname))) {64 log.debug(`The system logs broadcasting web socket server is already listening at ${pathname}`);65 return;66 }67 log.info(`Assigning system logs broadcasting web socket server to ${pathname}`);68 // https://github.com/websockets/ws/blob/master/doc/ws.md69 const wss = new WebSocket.Server({70 noServer: true,71 });72 wss.on('connection', (ws, req) => {73 if (req) {74 const remoteIp = _.isEmpty(req.headers['x-forwarded-for'])75 ? req.connection.remoteAddress76 : req.headers['x-forwarded-for'];77 log.debug(`Established a new system logs listener web socket connection from ${remoteIp}`);78 } else {79 log.debug('Established a new system logs listener web socket connection');80 }81 if (_.isEmpty(this._syslogWebsocketListener)) {82 this._syslogWebsocketListener = (logRecord) => {83 if (ws && ws.readyState === WebSocket.OPEN) {84 ws.send(logRecord.message);85 }86 };87 }88 this.logs.syslog.on('output', this._syslogWebsocketListener);89 ws.on('close', (code, reason) => {90 if (!_.isEmpty(this._syslogWebsocketListener)) {91 this.logs.syslog.removeListener('output', this._syslogWebsocketListener);92 this._syslogWebsocketListener = null;93 }94 let closeMsg = 'System logs listener web socket is closed.';95 if (!_.isEmpty(code)) {96 closeMsg += ` Code: ${code}.`;97 }98 if (!_.isEmpty(reason)) {99 closeMsg += ` Reason: ${reason}.`;100 }101 log.debug(closeMsg);102 });103 });104 await this.server.addWebSocketHandler(pathname, wss);105};106/**107 * Stops the previously started syslog broadcasting wesocket server.108 * This method will return immediately if no server is running.109 */110extensions.mobileStopLogsBroadcast = async function () {111 const pathname = WEBSOCKET_ENDPOINT(this.sessionId);112 if (_.isEmpty(await this.server.getWebSocketHandlers(pathname))) {113 return;114 }115 log.debug('Stopping the system logs broadcasting web socket server');116 await this.server.removeWebSocketHandler(pathname);117};...

Full Screen

Full Screen

server.js

Source:server.js Github

copy

Full Screen

1import path from 'path';2import express from 'express';3import http from 'http';4import favicon from 'serve-favicon';5import bodyParser from 'body-parser';6import methodOverride from 'method-override';7import log from './logger';8import { startLogFormatter, endLogFormatter } from './express-logging';9import { allowCrossDomain, fixPythonContentType, defaultToJSONContentType,10 catchAllHandler, catch404Handler, catch4XXHandler,11 allowCrossDomainAsyncExecute} from './middleware';12import { guineaPig, guineaPigScrollable, guineaPigAppBanner, welcome, STATIC_DIR } from './static';13import { produceError, produceCrash } from './crash';14import { addWebSocketHandler, removeWebSocketHandler, removeAllWebSocketHandlers,15 getWebSocketHandlers } from './websocket';16import B from 'bluebird';17async function server (configureRoutes, port, hostname = null, allowCors = true) {18 // create the actual http server19 const app = express();20 let httpServer = http.createServer(app);21 httpServer.addWebSocketHandler = addWebSocketHandler;22 httpServer.removeWebSocketHandler = removeWebSocketHandler;23 httpServer.removeAllWebSocketHandlers = removeAllWebSocketHandlers;24 httpServer.getWebSocketHandlers = getWebSocketHandlers;25 // http.Server.close() only stops new connections, but we need to wait until26 // all connections are closed and the `close` event is emitted27 const close = httpServer.close.bind(httpServer);28 httpServer.close = async () => {29 return await new B((resolve, reject) => {30 httpServer.on('close', resolve);31 close((err) => {32 if (err) reject(err); // eslint-disable-line curly33 });34 });35 };36 return await new B((resolve, reject) => {37 httpServer.on('error', (err) => {38 if (err.code === 'EADDRNOTAVAIL') {39 log.error('Could not start REST http interface listener. ' +40 'Requested address is not available.');41 } else {42 log.error('Could not start REST http interface listener. The requested ' +43 'port may already be in use. Please make sure there is no ' +44 'other instance of this server running already.');45 }46 reject(err);47 });48 httpServer.on('connection', (socket) => {49 socket.setTimeout(600 * 1000); // 10 minute timeout50 socket.on('error', reject);51 });52 configureServer(app, configureRoutes, allowCors);53 let serverArgs = [port];54 if (hostname) {55 // If the hostname is omitted, the server will accept56 // connections on any IP address57 serverArgs.push(hostname);58 }59 httpServer.listen(...serverArgs, (err) => {60 if (err) {61 reject(err);62 }63 resolve(httpServer);64 });65 });66}67function configureServer (app, configureRoutes, allowCors = true) {68 app.use(endLogFormatter);69 // set up static assets70 app.use(favicon(path.resolve(STATIC_DIR, 'favicon.ico')));71 app.use(express.static(STATIC_DIR));72 // crash routes, for testing73 app.use('/wd/hub/produce_error', produceError);74 app.use('/wd/hub/crash', produceCrash);75 // add middlewares76 if (allowCors) {77 app.use(allowCrossDomain);78 } else {79 app.use(allowCrossDomainAsyncExecute);80 }81 app.use(fixPythonContentType);82 app.use(defaultToJSONContentType);83 app.use(bodyParser.urlencoded({extended: true}));84 app.use(methodOverride());85 app.use(catch4XXHandler);86 app.use(catchAllHandler);87 // make sure appium never fails because of a file size upload limit88 app.use(bodyParser.json({limit: '1gb'}));89 // set up start logging (which depends on bodyParser doing its thing)90 app.use(startLogFormatter);91 configureRoutes(app);92 // dynamic routes for testing, etc.93 app.all('/welcome', welcome);94 app.all('/test/guinea-pig', guineaPig);95 app.all('/test/guinea-pig-scrollable', guineaPigScrollable);96 app.all('/test/guinea-pig-app-banner', guineaPigAppBanner);97 // catch this last, so anything that falls through is 404ed98 app.use(catch404Handler);99}...

Full Screen

Full Screen

websockets-e2e-specs.js

Source:websockets-e2e-specs.js Github

copy

Full Screen

1import _ from 'lodash';2import { server, routeConfiguringFunction,3 DEFAULT_WS_PATHNAME_PREFIX } from '../..';4import { FakeDriver } from '../protocol/fake-driver';5import chai from 'chai';6import chaiAsPromised from 'chai-as-promised';7import WebSocket from 'ws';8import B from 'bluebird';9chai.use(chaiAsPromised);10describe('Websockets (e2e)', function () {11 let baseServer;12 let driver;13 const SESSION_ID = 'foo';14 const WS_DATA = 'Hello';15 const PORT = 8181;16 before(async function () {17 driver = new FakeDriver();18 driver.sessionId = SESSION_ID;19 baseServer = await server({20 routeConfiguringFunction: routeConfiguringFunction(driver),21 port: PORT,22 });23 });24 after(async function () {25 await baseServer.close();26 });27 describe('web sockets support', function () {28 it('should be able to add websocket handler and remove it', async function () {29 const wss = new WebSocket.Server({30 noServer: true,31 });32 wss.on('connection', (ws) => {33 if (ws && ws.readyState === WebSocket.OPEN) {34 ws.send(WS_DATA);35 }36 });37 const previousListenerCount = baseServer.listenerCount('upgrade');38 const endpoint = `${DEFAULT_WS_PATHNAME_PREFIX}/hello`;39 const timeout = 5000;40 await baseServer.addWebSocketHandler(endpoint, wss);41 baseServer.listenerCount('upgrade').should.be.above(previousListenerCount);42 _.keys(await baseServer.getWebSocketHandlers()).length.should.eql(1);43 await new B((resolve, reject) => {44 const client = new WebSocket(`ws://localhost:${PORT}${endpoint}`);45 client.on('connection', (ws, req) => {46 ws.should.not.be.empty;47 req.connection.remoteAddress.should.not.be.empty;48 });49 client.on('message', (data) => {50 data.toString().should.eql(WS_DATA);51 resolve();52 });53 client.on('error', reject);54 setTimeout(() => reject(new Error('No websocket messages have been received after the timeout')),55 timeout);56 });57 (await baseServer.removeWebSocketHandler(endpoint)).should.be.true;58 _.keys(await baseServer.getWebSocketHandlers()).length.should.eql(0);59 await new B((resolve, reject) => {60 const client = new WebSocket(`ws://localhost:${PORT}${endpoint}`);61 client.on('message', (data) =>62 reject(new Error(`No websocket messages are expected after the handler ` +63 `has been removed. '${data?.toString()}' is received instead. `))64 );65 client.on('error', resolve);66 setTimeout(resolve, timeout);67 });68 baseServer.listenerCount('upgrade').should.be.above(previousListenerCount);69 });70 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var chai = require('chai');3var chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5var expect = chai.expect;6var desired = {7};8var serverConfig = {9};10var driver = wd.promiseChainRemote(serverConfig);11driver.init(desired).then(function () {12 return driver.getWebSocketHandlers();13}).then(function (wsHandlers) {14 console.log(wsHandlers);15 return driver.quit();16}).catch(function (err) {17 console.log(err);18});19var wd = require('wd');20var chai = require('chai');21var chaiAsPromised = require('chai-as-promised');22chai.use(chaiAsPromised);23var expect = chai.expect;24var desired = {25};26var serverConfig = {27};28var driver = wd.promiseChainRemote(serverConfig);29driver.init(desired).then(function () {30 return driver.getWebSocketHandlers();31}).then(function (wsHandlers) {32 console.log(wsHandlers);33 return driver.quit();34}).catch(function (err) {35 console.log(err);36});37var wd = require('wd');

Full Screen

Using AI Code Generation

copy

Full Screen

1var handlers = server.getWebSocketHandlers();2console.log(handlers);3var handlers = server.getWebSocketHandlers();4console.log(handlers);5var handlers = server.getWebSocketHandlers();6console.log(handlers);7var handlers = server.getWebSocketHandlers();8console.log(handlers);9var handlers = server.getWebSocketHandlers();10console.log(handlers);11var handlers = server.getWebSocketHandlers();12console.log(handlers);13var handlers = server.getWebSocketHandlers();14console.log(handlers);15var handlers = server.getWebSocketHandlers();16console.log(handlers);17var handlers = server.getWebSocketHandlers();18console.log(handlers);19var handlers = server.getWebSocketHandlers();20console.log(handlers);21var handlers = server.getWebSocketHandlers();22console.log(handlers);23var handlers = server.getWebSocketHandlers();24console.log(handlers);25var handlers = server.getWebSocketHandlers();26console.log(handlers);27var handlers = server.getWebSocketHandlers();28console.log(handlers);29var handlers = server.getWebSocketHandlers();30console.log(handlers);

Full Screen

Using AI Code Generation

copy

Full Screen

1const express = require('express');2const app = express();3const port = 3000;4const { AppiumDriver } = require('appium-xcuitest-driver');5const { attachToAppium } = require('appium-base-driver');6const { server, routeConfiguringFunction } = attachToAppium(new AppiumDriver());7app.use(routeConfiguringFunction);8app.listen(port, () => console.log(`Appium listening on port ${port}!`));9server.getWebSocketHandlers();10const express = require('express');11const app = express();12const port = 3000;13const { AppiumDriver } = require('appium-mjsonwp-driver');14const { attachToAppium } = require('appium-base-driver');15const { server, routeConfiguringFunction } = attachToAppium(new AppiumDriver());16app.use(routeConfiguringFunction);17app.listen(port, () => console.log(`Appium listening on port ${port}!`));18server.getWebSocketHandlers();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var asserters = wd.asserters;3var server = require('appium-xcuitest-driver').server;4var appium = require('appium');5var path = require('path');6var fs = require('fs');7var driver = wd.promiseChainRemote('localhost', 4723);8var desired = {9};10var server = appium.main(server.address(), server.port());11driver.init(desired).then(function () {12 console.log('Appium session created');13 return driver.getWebSocketHandlers();14}).then(function (handlers) {15 console.log('Handlers: ', handlers);16 return driver.quit();17}).then(function () {18 console.log('Appium session terminated');19 server.close();20}).catch(function (err) {21 console.log('Error: ', err);22 server.close();23});24var wd = require('wd');25var asserters = wd.asserters;26var server = require('appium-xcuitest-driver').server;27var appium = require('appium');28var path = require('path');29var fs = require('fs');30var driver = wd.promiseChainRemote('localhost', 4723);31var desired = {32};33var server = appium.main(server.address(), server.port());34driver.init(desired).then(function () {35 console.log('Appium session created');36 return driver.getWebSocketHandlers();37}).then(function (handlers) {38 console.log('Handlers: ', handlers);39 return driver.quit();40}).then(function () {41 console.log('Appium session terminated');42 server.close();43}).catch(function (err) {44 console.log('Error: ', err);45 server.close();46});47var wd = require('wd');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { AppiumDriver, startServer } = require('appium');2const server = startServer({3 defaultCapabilities: {4 },5});6server.getWebSocketHandlers()7const { AppiumDriver, startServer } = require('appium');8const server = startServer({9 defaultCapabilities: {10 },11});12server.getWebSocketHandlers()13const { AppiumDriver, startServer } = require('appium');14const server = startServer({15 defaultCapabilities: {16 },

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var chai = require('chai');3var chaiAsPromised = require('chai-as-promised');4var should = chai.should();5chai.use(chaiAsPromised);6var server = require('appium').server;7var XCUITestDriver = require('appium-xcuitest-driver');8describe('appium-xcuitest-driver', function () {9 it('should get list of web socket handlers', function (done) {10 var xcuitestdriver = new XCUITestDriver({11 });12 xcuitestdriver.start();13 var wsHandlers = xcuitestdriver.server.getWebSocketHandlers();14 wsHandlers.should.be.a('object');15 wsHandlers.should.have.property('status');16 wsHandlers.should.have.property('createSession');17 wsHandlers.should.have.property('getSession');18 wsHandlers.should.have.property('deleteSession');19 wsHandlers.should.have.property('execute');20 wsHandlers.should.have.property('executeAsync');21 wsHandlers.should.have.property('getTimeouts');22 wsHandlers.should.have.property('setTimeouts');23 wsHandlers.should.have.property('implicitWait');24 wsHandlers.should.have.property('getLogTypes');25 wsHandlers.should.have.property('getLog');26 wsHandlers.should.have.property('getLogs');27 wsHandlers.should.have.property('getSessions');28 wsHandlers.should.have.property('getScreenOrientation');29 wsHandlers.should.have.property('setScreenOrientation');30 wsHandlers.should.have.property('getDeviceTime');31 wsHandlers.should.have.property('getGeoLocation');32 wsHandlers.should.have.property('setGeoLocation');33 wsHandlers.should.have.property('getAppStrings');34 wsHandlers.should.have.property('getAlertText');35 wsHandlers.should.have.property('setAlertText');

Full Screen

Using AI Code Generation

copy

Full Screen

1const AppiumXCUITestDriver = require('appium-xcuitest-driver').Driver;2const { server } = require('appium-express');3const WebSocket = require('ws');4const driver = new AppiumXCUITestDriver({});5driver.createSession({6}).then(function() {7 const webSocketHandlers = server.getWebSocketHandlers();8 const webSocket = new WebSocket(webSocketHandlers[0].url);9 webSocket.on('open', function open() {10 webSocket.send('{"name":"getPageSource"}');11 });12 webSocket.on('message', function incoming(data) {13 console.log(data);14 });15});

Full Screen

Using AI Code Generation

copy

Full Screen

1const request = require('request');2const server = require('http').createServer();3const WebSocket = require('ws');4const wss = new WebSocket.Server({ server });5const port = 3000;6const appiumPort = 4723;7server.on('request', (req, res) => {8 res.end('Hello');9});10server.listen(port, () => {11 console.log('Server listening on port: ' + port);12});13wss.on('connection', (ws) => {14 console.log('Client connected');15});16wss.on('listening', () => {17 console.log('WebSocket server listening on port: ' + port);18});19const getWebSocketHandlers = () => {20 return new Promise((resolve, reject) => {21 if (err) {22 reject(err);23 } else {24 resolve(body);25 }26 });27 });28};29getWebSocketHandlers().then((body) => {30 const url = JSON.parse(body).value;31 const ws = new WebSocket(url);32 ws.on('open', () => {33 console.log('Websocket connected');34 });35 ws.on('message', (data) => {36 console.log('Received: ' + data);37 });38});39 ws.onopen = function () {40 console.log('Websocket connected');41 };42 ws.onmessage = function (event) {43 console.log('Received: ' + event.data);44 };

Full Screen

Using AI Code Generation

copy

Full Screen

1var ws = require('ws');2var ws_client = new ws(ws_url);3ws_client.on('open', function() {4 ws_client.send('{"method":"GET","url":"/orientation","id":1}');5 console.log("Message sent");6});7ws_client.on('message', function(data, flags) {8 console.log("Message received: " + data);9});10ws_client.on('close', function() {11 console.log("Websocket connection closed");12});13ws_client.on('error', function(err) {14 console.log("Error: " + err);15});

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Appium Xcuitest Driver automation tests on LambdaTest cloud grid

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

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful