Skip to content

Commit 5bd212e

Browse files
committed
[js] code clean-up/simplification
1 parent 5520ee7 commit 5bd212e

File tree

3 files changed

+68
-80
lines changed

3 files changed

+68
-80
lines changed

javascript/node/selenium-webdriver/lib/http.js

Lines changed: 55 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ const cmd = require('./command');
2929
const error = require('./error');
3030
const logging = require('./logging');
3131
const promise = require('./promise');
32-
const Session = require('./session').Session;
33-
const WebElement = require('./webdriver').WebElement;
32+
const {Session} = require('./session');
33+
const {WebElement} = require('./webdriver');
3434

3535
const {getAttribute, isDisplayed} = /** @suppress {undefinedVars|uselessCode} */(function() {
3636
try {
@@ -145,7 +145,7 @@ function resource(method, path) { return {method: method, path: path}; }
145145
var CommandSpec;
146146

147147

148-
/** @typedef {function(!cmd.Command): !Promise<!cmd.Command>} */
148+
/** @typedef {function(!cmd.Command): !cmd.Command} */
149149
var CommandTransformer;
150150

151151

@@ -155,21 +155,17 @@ class InternalTypeError extends TypeError {}
155155
/**
156156
* @param {!cmd.Command} command The initial command.
157157
* @param {Atom} atom The name of the atom to execute.
158-
* @return {!Promise<!cmd.Command>} The transformed command to execute.
158+
* @return {!cmd.Command} The transformed command to execute.
159159
*/
160160
function toExecuteAtomCommand(command, atom, ...params) {
161-
return new Promise((resolve, reject) => {
162-
if (typeof atom !== 'function') {
163-
reject(new InternalTypeError('atom is not a function: ' + typeof atom));
164-
return;
165-
}
161+
if (typeof atom !== 'function') {
162+
throw new InternalTypeError('atom is not a function: ' + typeof atom);
163+
}
166164

167-
let newCmd = new cmd.Command(cmd.Name.EXECUTE_SCRIPT)
168-
.setParameter('sessionId', command.getParameter('sessionId'))
169-
.setParameter('script', `return (${atom}).apply(null, arguments)`)
170-
.setParameter('args', params.map(param => command.getParameter(param)));
171-
resolve(newCmd);
172-
});
165+
return new cmd.Command(cmd.Name.EXECUTE_SCRIPT)
166+
.setParameter('sessionId', command.getParameter('sessionId'))
167+
.setParameter('script', `return (${atom}).apply(null, arguments)`)
168+
.setParameter('args', params.map(param => command.getParameter(param)));
173169
}
174170

175171

@@ -287,35 +283,13 @@ class Client {
287283
}
288284

289285

290-
const CLIENTS =
291-
/** !WeakMap<!Executor, !(Client|IThenable<!Client>)> */new WeakMap;
292-
293-
294-
/**
295-
* Sends a request using the given executor.
296-
* @param {!Executor} executor
297-
* @param {!Request} request
298-
* @return {!Promise<Response>}
299-
*/
300-
function doSend(executor, request) {
301-
const client = CLIENTS.get(executor);
302-
if (promise.isPromise(client)) {
303-
return client.then(client => {
304-
CLIENTS.set(executor, client);
305-
return client.send(request);
306-
});
307-
} else {
308-
return client.send(request);
309-
}
310-
}
311-
312286

313287
/**
314288
* @param {Map<string, CommandSpec>} customCommands
315289
* A map of custom command definitions.
316290
* @param {boolean} w3c Whether to use W3C command mappings.
317291
* @param {!cmd.Command} command The command to resolve.
318-
* @return {!Promise<!Request>} A promise that will resolve with the
292+
* @return {!Request} A promise that will resolve with the
319293
* command to execute.
320294
*/
321295
function buildRequest(customCommands, w3c, command) {
@@ -329,8 +303,8 @@ function buildRequest(customCommands, w3c, command) {
329303
spec = W3C_COMMAND_MAP.get(command.getName());
330304
if (typeof spec === 'function') {
331305
LOG.finest(() => `Transforming command for W3C: ${command.getName()}`);
332-
return spec(command)
333-
.then(newCommand => buildRequest(customCommands, w3c, newCommand));
306+
let newCommand = spec(command);
307+
return buildRequest(customCommands, w3c, newCommand);
334308
} else if (spec) {
335309
return toHttpRequest(spec);
336310
}
@@ -340,23 +314,26 @@ function buildRequest(customCommands, w3c, command) {
340314
if (spec) {
341315
return toHttpRequest(spec);
342316
}
343-
return Promise.reject(
344-
new error.UnknownCommandError(
345-
'Unrecognized command: ' + command.getName()));
317+
throw new error.UnknownCommandError(
318+
'Unrecognized command: ' + command.getName());
346319

347320
/**
348321
* @param {CommandSpec} resource
349-
* @return {!Promise<!Request>}
322+
* @return {!Request}
350323
*/
351324
function toHttpRequest(resource) {
352325
LOG.finest(() => `Building HTTP request: ${JSON.stringify(resource)}`);
353326
let parameters = command.getParameters();
354327
let path = buildPath(resource.path, parameters);
355-
return Promise.resolve(new Request(resource.method, path, parameters));
328+
return new Request(resource.method, path, parameters);
356329
}
357330
}
358331

359332

333+
const CLIENTS =
334+
/** !WeakMap<!Executor, !(Client|IThenable<!Client>)> */new WeakMap;
335+
336+
360337
/**
361338
* A command executor that communicates with the server using JSON over HTTP.
362339
*
@@ -416,36 +393,41 @@ class Executor {
416393
}
417394

418395
/** @override */
419-
execute(command) {
396+
async execute(command) {
420397
let request = buildRequest(this.customCommands_, this.w3c, command);
421-
return request.then(request => {
422-
this.log_.finer(() => `>>> ${request.method} ${request.path}`);
423-
return doSend(this, request).then(response => {
424-
this.log_.finer(() => `>>>\n${request}\n<<<\n${response}`);
425-
426-
let httpResponse = /** @type {!Response} */(response);
427-
let {isW3C, value} = parseHttpResponse(command, httpResponse);
428-
429-
if (command.getName() === cmd.Name.NEW_SESSION) {
430-
if (!value || !value.sessionId) {
431-
throw new error.WebDriverError(
432-
`Unable to parse new session response: ${response.body}`);
433-
}
434-
435-
// The remote end is a W3C compliant server if there is no `status`
436-
// field in the response.
437-
if (command.getName() === cmd.Name.NEW_SESSION) {
438-
this.w3c = this.w3c || isW3C;
439-
}
440-
441-
// No implementations use the `capabilities` key yet...
442-
let capabilities = value.capabilities || value.value;
443-
return new Session(value.sessionId, capabilities);
444-
}
398+
this.log_.finer(() => `>>> ${request.method} ${request.path}`);
399+
400+
let client = CLIENTS.get(this);
401+
if (promise.isPromise(client)) {
402+
client = await client;
403+
CLIENTS.set(this, client);
404+
}
405+
406+
let response = await client.send(request);
407+
this.log_.finer(() => `>>>\n${request}\n<<<\n${response}`);
408+
409+
let httpResponse = /** @type {!Response} */(response);
410+
let {isW3C, value} = parseHttpResponse(command, httpResponse);
411+
412+
if (command.getName() === cmd.Name.NEW_SESSION) {
413+
if (!value || !value.sessionId) {
414+
throw new error.WebDriverError(
415+
`Unable to parse new session response: ${response.body}`);
416+
}
417+
418+
// The remote end is a W3C compliant server if there is no `status`
419+
// field in the response.
420+
if (command.getName() === cmd.Name.NEW_SESSION) {
421+
this.w3c = this.w3c || isW3C;
422+
}
423+
424+
// No implementations use the `capabilities` key yet...
425+
let capabilities = value.capabilities || value.value;
426+
return new Session(
427+
/** @type {{sessionId: string}} */(value).sessionId, capabilities);
428+
}
445429

446-
return typeof value === 'undefined' ? null : value;
447-
});
448-
});
430+
return typeof value === 'undefined' ? null : value;
449431
}
450432
}
451433

javascript/node/selenium-webdriver/lib/test/index.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,11 @@ function suite(fn, options = undefined) {
5555
// GLOBAL TEST SETUP
5656

5757

58+
process.on('unhandledRejection', (reason) => {
59+
console.error('Unhandled promise rejection:', reason);
60+
});
61+
62+
5863
if (/^1|true$/i.test(process.env['SELENIUM_VERBOSE'])) {
5964
logging.installConsoleHandler();
6065
logging.getLogger('webdriver.http').setLevel(logging.Level.ALL);

javascript/node/selenium-webdriver/test/lib/http_test.js

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -118,20 +118,21 @@ describe('http', function() {
118118
});
119119
});
120120

121-
it('rejects commands missing URL parameters', function() {
121+
it('rejects commands missing URL parameters', async function() {
122122
let command =
123123
new Command(CommandName.FIND_CHILD_ELEMENT).
124124
setParameter('sessionId', 's123').
125125
// Let this be missing: setParameter('id', {'ELEMENT': 'e456'}).
126126
setParameter('using', 'id').
127127
setParameter('value', 'foo');
128128

129-
assert.throws(
130-
() => executor.execute(command),
131-
function(err) {
132-
return err instanceof error.InvalidArgumentError
133-
&& 'Missing required parameter: id' === err.message;
134-
});
129+
try {
130+
await executor.execute(command);
131+
return Promise.reject(Error('should have thrown'));
132+
} catch (err) {
133+
assert.strictEqual(err.constructor, error.InvalidArgumentError);
134+
assert.equal(err.message, 'Missing required parameter: id');
135+
}
135136
assert.ok(!send.called);
136137
});
137138

0 commit comments

Comments
 (0)