Skip to content

Commit

Permalink
deleting all sessions when exiting the process (Ctrl+C, Close)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tin Tran committed Apr 30, 2017
1 parent f55083d commit b3fe427
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 10 deletions.
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/lib
/build/test
./.npmignore
*.log
.coveralls.yml
Expand Down
31 changes: 27 additions & 4 deletions lib/appium-proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import http from 'http';
import url from 'url';
import _ from 'lodash';
import { createProxyServer } from 'http-proxy';
import request from 'request';
import logger from './logger'
import { isCreateSession, isDeleteSession, isDeleteWindow, getCapabilities, getSessionId,
printHttpRequest, printHttpRespond, isSuccess, modifyResponse} from './utils';
Expand Down Expand Up @@ -39,8 +40,8 @@ class AppiumProxy {

let identifyKey = caps[this.opts.capabilityIdentify];
if (this.sessionMap.hasOwnProperty(identifyKey)) {
let session = this.sessionMap[identifyKey].sessionRes;
logger.debug('[handleCreatedSession] sessionRes:', session);
let session = this.sessionMap[identifyKey];
logger.debug('[handleCreatedSession] session data:', session);
res.writeHead(200, {'Content-type': 'application/json'});
res.end(JSON.stringify(session));
return true;
Expand Down Expand Up @@ -123,11 +124,33 @@ class AppiumProxy {
if (!self.opts.needDeleteSession && isCreateSession(req) && isSuccess(res)) {
let caps = getCapabilities(req.body);
let identifyKey = caps[self.opts.capabilityIdentify];
var obj = { 'sessionRes': _.cloneDeep(body) }
self.sessionMap[identifyKey] = obj;
self.sessionMap[identifyKey] = _.cloneDeep(body);
}
});
}

async close () {
let sessionIds = Object.keys(this.sessionMap).map(k => this.sessionMap[k].sessionId);
sessionIds.forEach(sessionId => {
try {
request.delete({
url: `${this.opts.realUrl}/session/${sessionId}`,
auth: url.parse(this.opts.realUrl).auth
},(err, res) => {
if (!err && res.statusCode == 200) {
logger.info(`DELETE ${sessionId} successful.`);
}
else {
logger.info(`Cannot DELETE ${sessionId} with err: ${JSON.stringify(err)}`);
}
});
}
catch (err) {
logger.info(`Cannot DELETE ${sessionId} with err: ${JSON.stringify(err)}`);
}
});
this.sessionMap = {};
}
}

export default AppiumProxy;
15 changes: 15 additions & 0 deletions lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,21 @@ async function main() {
var logMessage = 'Appium proxy listener started on ' + (args.address + ':' + args.port);
logger.info(logMessage)
});

process.on('SIGINT', async function () {
logger.info(`Received SIGINT - shutting down`);
await proxy.close();
});

process.on('SIGTERM', async function () {
logger.info(`Received SIGTERM - shutting down`);
await proxy.close();
});

process.on('SIGHUP', async function () {
logger.info(`Received SIGHUP - shutting down`);
await proxy.close();
});
}

if (require.main === module) {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"appium-proxy": "./build/lib/main.js"
},
"scripts": {
"start": "npm run-script build && node ./build/lib/main.js --real-url http://localhost:4723/wd/hub",
"build": "npm prune && babel lib -d build/lib",
"coverage": "istanbul cover ./node_modules/mocha/bin/_mocha build/test/* --report lcovonly -- -R spec",
"coveralls": "npm run-script coverage && node ./node_modules/coveralls/bin/coveralls.js < coverage/lcov.info",
Expand Down
46 changes: 40 additions & 6 deletions test/appium-proxy-specs.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import chai from 'chai';
import sinon from 'sinon';
import proxyquire from 'proxyquire';
import httpMocks from 'node-mocks-http';
import request from 'request';
import AppiumProxy from '../lib/appium-proxy';
import * as utils from '../lib/utils';
import logger from '../lib/logger'
Expand All @@ -18,7 +19,7 @@ describe('AppiumProxy', () => {
var res;
beforeEach(() => {
proxy = new AppiumProxy({
realUrl: 'http://localhost:9001',
realUrl: 'http://localhost:4723/wd/hub',
commandTimeout: '100',
capabilityIdentify: 'idtest'
});
Expand All @@ -31,17 +32,15 @@ describe('AppiumProxy', () => {
});
describe('constructor', () => {
it('should call AppiumProxy constructor with opts', () => {
proxy.opts.realUrl.should.equal('http://localhost:9001');
proxy.opts.realUrl.should.equal('http://localhost:4723/wd/hub');
proxy.opts.commandTimeout.should.equal('100');
proxy.opts.capabilityIdentify.should.equal('idtest');
});
});
describe('handleCreatedSession', () => {
var fakeSession = {
'id1': {
'sessionRes': {
'ok' : true
}
'ok' : true
}
}
it('should return false if a request is not is create session request', () => {
Expand Down Expand Up @@ -264,7 +263,42 @@ describe('AppiumProxy', () => {

proxy.proxyResFunc({}, req, res);
utils.printHttpRespond.calledOnce.should.be.true;
expect(proxy.sessionMap['abc'].sessionRes).to.deep.equal(resultBody);
expect(proxy.sessionMap['abc']).to.deep.equal(resultBody);
});
});
describe('close', () => {
beforeEach(() => {
let sessionMap = {
id1: {
sessionId: '0a085e6e-b667-498f-b27c-23af3cee41e0'
}
}
proxy.sessionMap = sessionMap;
sandbox.stub(request, 'delete');
});
afterEach(() => {
request.delete.restore();
logger.info.restore();
});
it('should send a request to delete a session', () => {
request.delete.yields(null, {statusCode: 200}, null);
proxy.close();

assert(request.delete.calledOnce);
request.delete.getCall(0).args[0].url
.should.equal('http://localhost:4723/wd/hub/session/0a085e6e-b667-498f-b27c-23af3cee41e0');
logger.info.getCall(0).args[0].should.equal('DELETE 0a085e6e-b667-498f-b27c-23af3cee41e0 successful.')
proxy.sessionMap.should.be.empty;
});
it('cannot delete a session', () => {
request.delete.yields(null, {statusCode: 404}, null);
proxy.close();

assert(request.delete.calledOnce);
request.delete.getCall(0).args[0].url
.should.equal('http://localhost:4723/wd/hub/session/0a085e6e-b667-498f-b27c-23af3cee41e0');
expect(logger.info.getCall(0).args[0]).to.contains('Cannot DELETE 0a085e6e-b667-498f-b27c-23af3cee41e0');
proxy.sessionMap.should.be.empty;
});
});
});

0 comments on commit b3fe427

Please sign in to comment.