How to use plugin.updateServer method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

Run Appium Base Driver automation tests on LambdaTest cloud grid

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

pugin-specs.js

Source: pugin-specs.js Github

copy
1import OpentelemetryPlugin from '../../index';
2import chai from 'chai';
3import chaiAsPromised from 'chai-as-promised';
4
5chai.use(chaiAsPromised);
6const should = chai.should();
7
8describe('Opentelemetry plugin', function () {
9  it('should exist', function () {
10    should.exist(OpentelemetryPlugin);
11  });
12  it('should define its name', function () {
13    const p = new OpentelemetryPlugin('foo');
14    p.name.should.eql('foo');
15  });
16  it('should create a logger', function () {
17    const p = new OpentelemetryPlugin('foo');
18    should.exist(p.logger);
19  });
20  it('should define no server update method', function () {
21    should.exist(OpentelemetryPlugin.updateServer);
22  });
23  it('should define a default list of no new methods', function () {
24    OpentelemetryPlugin.newMethodMap.should.eql({});
25  });
26});
27
Full Screen

server.js

Source: server.js Github

copy
1import _ from 'lodash';
2import path from 'path';
3import express from 'express';
4import http from 'http';
5import favicon from 'serve-favicon';
6import bodyParser from 'body-parser';
7import methodOverride from 'method-override';
8import log from './logger';
9import { startLogFormatter, endLogFormatter } from './express-logging';
10import {
11  allowCrossDomain, fixPythonContentType, defaultToJSONContentType,
12  catchAllHandler, allowCrossDomainAsyncExecute, handleIdempotency,
13  catch404Handler,
14} from './middleware';
15import { guineaPig, guineaPigScrollable, guineaPigAppBanner, welcome, STATIC_DIR } from './static';
16import { produceError, produceCrash } from './crash';
17import {
18  addWebSocketHandler, removeWebSocketHandler, removeAllWebSocketHandlers,
19  getWebSocketHandlers
20} from './websocket';
21import B from 'bluebird';
22import { DEFAULT_BASE_PATH } from '../constants';
23import { EventEmitter } from 'events';
24
25
26const KEEP_ALIVE_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes
27
28
29async function server (opts = {}) {
30  const {
31    routeConfiguringFunction,
32    port,
33    hostname = null,
34    allowCors = true,
35    basePath = DEFAULT_BASE_PATH,
36    plugins = [],
37    keepAliveTimeout = KEEP_ALIVE_TIMEOUT_MS,
38  } = opts;
39
40  // create the actual http server
41  const app = express();
42  const httpServer = http.createServer(app);
43  return await new B(async (resolve, reject) => {
44    // we put an async function as the promise constructor because we want some things to happen in
45    // serial (application of plugin updates, for example). But we still need to use a promise here
46    // because some elements of server start failure only happen in httpServer listeners. So the
47    // way we resolve it is to use an async function here but to wrap all the inner logic in
48    // try/catch so any errors can be passed to reject.
49    try {
50      configureHttp({httpServer, reject, keepAliveTimeout});
51      configureServer({app, addRoutes: routeConfiguringFunction, allowCors, basePath, plugins});
52      await configureServerPlugins({app, httpServer, plugins});
53
54      // once all configurations and plugins have been applied, make sure to set up a catchall
55      // handler so that anything unknown 404s. But do this after everything else since we don't
56      // want to block plugins' ability to add routes if they want.
57      app.all('*', catch404Handler);
58
59      await startServer({httpServer, hostname, port, keepAliveTimeout});
60      resolve(httpServer);
61    } catch (err) {
62      reject(err);
63    }
64  });
65
66}
67
68function configureServer ({
69  app,
70  addRoutes,
71  allowCors = true,
72  basePath = DEFAULT_BASE_PATH,
73  plugins = [],
74}) {
75  basePath = normalizeBasePath(basePath);
76
77  app.use(endLogFormatter);
78
79  // set up static assets
80  app.use(favicon(path.resolve(STATIC_DIR, 'favicon.ico')));
81  app.use(express.static(STATIC_DIR));
82
83  // crash routes, for testing
84  app.use(`${basePath}/produce_error`, produceError);
85  app.use(`${basePath}/crash`, produceCrash);
86
87  // add middlewares
88  if (allowCors) {
89    app.use(allowCrossDomain);
90  } else {
91    app.use(allowCrossDomainAsyncExecute(basePath));
92  }
93  app.use(handleIdempotency);
94  app.use(fixPythonContentType(basePath));
95  app.use(defaultToJSONContentType);
96  app.use(bodyParser.urlencoded({extended: true}));
97  app.use(methodOverride());
98  app.use(catchAllHandler);
99
100  // make sure appium never fails because of a file size upload limit
101  app.use(bodyParser.json({limit: '1gb'}));
102
103  // set up start logging (which depends on bodyParser doing its thing)
104  app.use(startLogFormatter);
105
106  const extraMethods = plugins.filter((p) => {
107    if (!_.isPlainObject(p.newMethodMap)) {
108      log.warn(`Tried to apply newMethodMap from plugin '${p.name}' but it was invalid. Will ` +
109               `skip adding these methods to the method map.`);
110      return false;
111    }
112    return true;
113  }).map((p) => p.newMethodMap);
114  addRoutes(app, {basePath, extraMethods});
115
116  // dynamic routes for testing, etc.
117  app.all('/welcome', welcome);
118  app.all('/test/guinea-pig', guineaPig);
119  app.all('/test/guinea-pig-scrollable', guineaPigScrollable);
120  app.all('/test/guinea-pig-app-banner', guineaPigAppBanner);
121}
122
123function configureHttp ({httpServer, reject, keepAliveTimeout}) {
124  const serverState = {
125    notifier: new EventEmitter(),
126    closed: false,
127  };
128  httpServer.addWebSocketHandler = addWebSocketHandler;
129  httpServer.removeWebSocketHandler = removeWebSocketHandler;
130  httpServer.removeAllWebSocketHandlers = removeAllWebSocketHandlers;
131  httpServer.getWebSocketHandlers = getWebSocketHandlers;
132
133  // http.Server.close() only stops new connections, but we need to wait until
134  // all connections are closed and the `close` event is emitted
135  const close = httpServer.close.bind(httpServer);
136  httpServer.close = async () => await new B((resolve, reject) => {
137    // https://github.com/nodejs/node-v0.x-archive/issues/9066#issuecomment-124210576
138    serverState.closed = true;
139    serverState.notifier.emit('shutdown');
140    log.info('Waiting until the server is closed');
141    httpServer.on('close', () => {
142      log.info('Received server close event');
143      resolve();
144    });
145    close((err) => {
146      if (err) reject(err); // eslint-disable-line curly
147    });
148  });
149
150  httpServer.on('error', (err) => {
151    if (err.code === 'EADDRNOTAVAIL') {
152      log.error('Could not start REST http interface listener. ' +
153                'Requested address is not available.');
154    } else {
155      log.error('Could not start REST http interface listener. The requested ' +
156                'port may already be in use. Please make sure there is no ' +
157                'other instance of this server running already.');
158    }
159    reject(err);
160  });
161
162  httpServer.on('connection', (socket) => {
163    socket.setTimeout(keepAliveTimeout);
164    socket.on('error', reject);
165
166    function destroy () {
167      socket.destroy();
168    }
169    socket._openReqCount = 0;
170    socket.once('close', () => serverState.notifier.removeListener('shutdown', destroy));
171    serverState.notifier.once('shutdown', destroy);
172  });
173
174  httpServer.on('request', function (req, res) {
175    const socket = req.connection || req.socket;
176    socket._openReqCount++;
177    res.on('finish', function () {
178      socket._openReqCount--;
179      if (serverState.closed && socket._openReqCount === 0) {
180        socket.destroy();
181      }
182    });
183  });
184}
185
186async function configureServerPlugins ({plugins, app, httpServer}) {
187  // allow plugins to update the app and http server objects
188  for (const plugin of plugins.filter((p) => p.updatesServer)) {
189    log.info(`Allowing plugin ${plugin.name} to modify the Appium server`);
190    try {
191      // wrap this in error handling in case the plugin forgot to mark the function async or
192      // forgot to implement it
193      await plugin.updateServer(app, httpServer);
194    } catch (err) {
195      log.error(`Plugin '${plugin.name}' tried to update the server but the updateServer ` +
196                `method was not implemented, did not return a promise, or threw an ` +
197                `error. Original message: ${err}.`);
198      throw err;
199    }
200  }
201}
202
203async function startServer ({httpServer, port, hostname, keepAliveTimeout}) {
204  const serverArgs = [port];
205  if (hostname) {
206    // If the hostname is omitted, the server will accept
207    // connections on any IP address
208    serverArgs.push(hostname);
209  }
210  const startPromise = B.promisify(httpServer.listen, {context: httpServer})(...serverArgs);
211  httpServer.keepAliveTimeout = keepAliveTimeout;
212  // headers timeout must be greater than keepAliveTimeout
213  httpServer.headersTimeout = keepAliveTimeout + 5 * 1000;
214  await startPromise;
215}
216
217function normalizeBasePath (basePath) {
218  if (!_.isString(basePath)) {
219    throw new Error(`Invalid path prefix ${basePath}`);
220  }
221
222  // ensure the path prefix does not end in '/', since our method map
223  // starts all paths with '/'
224  basePath = basePath.replace(/\/$/, '');
225
226  // likewise, ensure the path prefix does always START with /, unless the path
227  // is empty meaning no base path at all
228  if (basePath !== '' && basePath[0] !== '/') {
229    basePath = `/${basePath}`;
230  }
231
232  return basePath;
233}
234
235export { server, configureServer, normalizeBasePath };
236
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Appium Base Driver on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)