Best JavaScript code snippet using appium-android-driver
JavascriptFormatter.js
Source:JavascriptFormatter.js
1/// <reference path="typings/node.d.ts" />2var Command = require("./testCase").Command;3var Comment = require("./testCase").Comment;4var jsbute = require('js-beautify').js_beautify;5var fs = require('fs');6var log = console;7log.debug = log.info;8var app = {};9var options = {};10/**11 * Format TestCase and return the source.12 *13 * @param {string} testCase TestCase to format14 * @param {object} opts Custom options15 * {string} .testCaseName16 * The name of the test case. It will be used to embed17 * title into the source, and write screenshot files.18 * Default: 'Untitled'19 * {number} .timeout20 * Default number of msecs before timing out in test21 * cases with timeouts, and when creating auto-retrying22 * test cases.23 * Default: 30,00024 * {number} .retries25 * How many times to retry test cases when they fail.26 * If retries are enabled, each generated test case27 * will be wrapped in a retry function.28 * Default: 0 (disabled)29 * {string} .extensions30 * User extensions javascript file:31 * Default: __dirname + 'extensions/user-extensions.js'32 *33 * @return {string} The formatted test case.34 */35function format(testCase, opts) {36 if (!opts || typeof opts !== 'object')37 opts = {};38 log.info("Formatting testCase: " + opts.testCaseName);39 var result = '';40 var header = "";41 var footer = "";42 var extension, extensions = opts.extensions || __dirname + '/extensions/user-extensions.js';43 app.commandCharIndex = 0;44 app.testCaseName = opts.testCaseName || '';45 app.screenshotsCount = 0;46 options.testCaseName = opts.testCaseName || 'Untitled';47 options.timeout = typeof opts.timeout === 'number' && !isNaN(opts.timeout) ? opts.timeout : 30000;48 options.retries = typeof opts.retries === 'number' && !isNaN(opts.retries) ? opts.retries : 0;49 options.screenshotFolder = 'screenshots/' + app.testCaseName;50 options.baseUrl = opts.baseUrl || '${baseURL}';51 options.extensions = {};52 log.info('Importing user extensions from %s ...', extensions);53 extensions = require(extensions);54 for (extension in extensions) {55 if (extensions.hasOwnProperty(extension)) {56 log.info('Adding command %s', extension);57 options.extensions[extension] = extensions[extension];58 }59 }60 header = formatHeader(testCase);61 result += header;62 app.commandCharIndex = header.length;63 testCase.formatLocal(app.name).header = header;64 result += formatCommands(testCase.commands);65 footer = formatFooter(testCase);66 footer += '\n\n/* User extensions */\n\n';67 for (extension in options.extensions) {68 footer += options.extensions[extension].toString().replace(/^function/, 'function ' + extension) + '\n\n';69 }70 result += footer;71 testCase.formatLocal(app.name).footer = footer;72 return jsbute(result, opts.jsBeautifierOptions || { max_preserve_newlines: 2 });73}74exports.format = format;75function setLogger(logger) {76 log = logger;77}78exports.setLogger = setLogger;79/**80 * Generates a variable name for storing temporary values in generated scripts.81 */82function getTempVarName() {83 if (!app.tmpVarsCount)84 app.tmpVarsCount = 1;85 return "var" + app.tmpVarsCount++;86}87function retryWrap(code) {88 var wrapped = "withRetry(function () {\n";89 code.split('\n').forEach(function (line) {90 wrapped += line + '\n';91 });92 wrapped += "});";93 return wrapped;94}95function andWait(code) {96 var wrapped = "doAndWait(function () {\n";97 code.split('\n').forEach(function (line) {98 wrapped += line + '\n';99 });100 wrapped += "});";101 return wrapped;102}103function filterForRemoteControl(commands) {104 return app.postFilter ? app.postFilter(commands) : commands;105}106function formatCommands(commands) {107 commands = filterForRemoteControl(commands);108 var result = '';109 var line = null;110 var command;111 var commandName;112 var hasAndWaitSuffix;113 for (var i = 0; i < commands.length; i++) {114 command = commands[i];115 app.currentlyParsingCommand = command;116 if (command.type == 'line') {117 line = command.line;118 }119 else if (command.type == 'command') {120 commandName = command.command;121 hasAndWaitSuffix = !!commandName.match(/AndWait$/);122 if (hasAndWaitSuffix) {123 command.command = commandName.replace(/AndWait$/, '');124 }125 line = formatCommand(command);126 /* If retries are enabled, wrap the code block in a retry wrapper, unless the command is of the waiting type */127 if (options.retries && !commandName.match(/(^waitFor)|(AndWait$)/)) {128 line = retryWrap(line);129 }130 else if (hasAndWaitSuffix) {131 line = andWait(line);132 }133 /* For debugging test failures and for screenshotting, we use currentCommand to keep track of what last ran: */134 line = 'currentCommand = \'' + commandName + '(' + '"' + command.target.replace(/(['\\])/g, "\\$1").replace(/\n/g, '\\n') + '", ' + '"' + command.value.replace(/(['\\])/g, "\\$1").replace(/\n/g, '\\n') + '")\';\n' + line + '\n';135 command.line = line;136 }137 else if (command.type == 'comment') {138 line = formatComment(command);139 command.line = line;140 }141 command.charIndex = app.commandCharIndex;142 if (line != null) {143 line = line + "\n";144 result += line;145 app.commandCharIndex += line.length;146 }147 app.previouslyParsedCommand = command;148 }149 return result;150}151/* @override152 * This function filters the command list and strips away the commands we no longer need153 * or changes the command to another one.154 * NOTE: do not change the existing command directly or it will also change in the test case.155 */156app.postFilter = function (originalCommands) {157 var commands = [];158 var commandsToSkip = {};159 var rc;160 for (var i = 0; i < originalCommands.length; i++) {161 var c = originalCommands[i];162 if (c.type == 'command') {163 if (commandsToSkip[c.command] && commandsToSkip[c.command] == 1) {164 }165 else if (rc = SeleneseMapper.remap(c)) {166 //Remap167 commands.push.apply(commands, rc);168 }169 else {170 commands.push(c);171 }172 }173 else {174 commands.push(c);175 }176 }177 return commands;178};179/* SeleneseMapper changes one Selenese command to another that is more suitable for WebDriver export180 */181var SeleneseMapper = function () {182};183SeleneseMapper.remap = function (cmd) {184 /*185 for (var mapper in SeleneseMapper) {186 if (SeleneseMapper.hasOwnProperty(mapper) && typeof SeleneseMapper.mapper.isDefined === 'function' && typeof SeleneseMapper.mapper.convert === 'function') {187 if (SeleneseMapper.mapper.isDefined(cmd)) {188 return SeleneseMapper.mapper.convert(cmd);189 }190 }191 }192 */193 // NOTE The above code is useful if there are more than one mappers, since there is just one, it is more efficient to call it directly194 if (SeleneseMapper.IsTextPresent.isDefined(cmd)) {195 return SeleneseMapper.IsTextPresent.convert(cmd);196 }197 return null;198};199SeleneseMapper.IsTextPresent = {200 isTextPresentRegex: /^(assert|verify|waitFor)Text(Not)?Present$/,201 isPatternRegex: /^(regexp|regexpi|regex):/,202 exactRegex: /^exact:/,203 isDefined: function (cmd) {204 return this.isTextPresentRegex.test(cmd.command);205 },206 convert: function (cmd) {207 if (this.isTextPresentRegex.test(cmd.command)) {208 var pattern = cmd.target;209 if (!this.isPatternRegex.test(pattern)) {210 if (this.exactRegex.test(pattern)) {211 //TODO how to escape wildcards in an glob pattern?212 pattern = pattern.replace(this.exactRegex, 'glob:*') + '*';213 }214 else {215 //glob216 pattern = pattern.replace(/^(glob:)?\*?/, 'glob:*');217 if (!/\*$/.test(pattern)) {218 pattern += '*';219 }220 }221 }222 var remappedCmd = new Command(cmd.command.replace(this.isTextPresentRegex, "$1$2Text"), 'css=BODY', pattern);223 remappedCmd.remapped = cmd;224 return [new Comment('Warning: ' + cmd.command + ' may require manual changes'), remappedCmd];225 }226 }227};228function formatHeader(testCase) {229 var className = testCase.getTitle();230 if (!className) {231 className = "NewTest";232 }233 className = testClassName(className);234 var formatLocal = testCase.formatLocal(app.name);235 var methodName = testMethodName(className.replace(/Test$/i, "").replace(/^Test/i, "").replace(/^[A-Z]/, function (str) {236 return str.toLowerCase();237 }));238 var header = (options.getHeader()).239 replace(/\$\{className\}/g, className).240 replace(/\$\{methodName\}/g, methodName).241 replace(/\$\{baseURL\}/g, testCase.getBaseURL()).242 replace(/\$\{([a-zA-Z0-9_]+)\}/g, function (str, name) {243 return options[name];244 });245 formatLocal.header = header;246 return formatLocal.header;247}248function formatFooter(testCase) {249 var formatLocal = testCase.formatLocal(app.name);250 formatLocal.footer = options.footer;251 return formatLocal.footer;252}253function capitalize(string) {254 return string.replace(/^[a-z]/, function (str) {255 return str.toUpperCase();256 });257}258function underscore(text) {259 return text.replace(/[A-Z]/g, function (str) {260 return '_' + str.toLowerCase();261 });262}263function notOperator() {264 return "!";265}266function logicalAnd(conditions) {267 return conditions.join(" && ");268}269function equals(e1, e2) {270 return new Equals(e1, e2);271}272function Equals(e1, e2) {273 this.e1 = e1;274 this.e2 = e2;275}276Equals.prototype.invert = function () {277 return new NotEquals(this.e1, this.e2);278};279function NotEquals(e1, e2) {280 this.e1 = e1;281 this.e2 = e2;282 this.negative = true;283}284NotEquals.prototype.invert = function () {285 return new Equals(this.e1, this.e2);286};287function RegexpMatch(pattern, expression) {288 this.pattern = pattern;289 this.expression = expression;290}291RegexpMatch.prototype.invert = function () {292 return new RegexpNotMatch(this.pattern, this.expression);293};294RegexpMatch.prototype.assert = function () {295 return assertTrue(this.toString());296};297RegexpMatch.prototype.verify = function () {298 return verifyTrue(this.toString());299};300function RegexpNotMatch(pattern, expression) {301 this.pattern = pattern;302 this.expression = expression;303 this.negative = true;304}305RegexpNotMatch.prototype.invert = function () {306 return new RegexpMatch(this.pattern, this.expression);307};308RegexpNotMatch.prototype.toString = function () {309 return notOperator() + RegexpMatch.prototype.toString.call(this);310};311RegexpNotMatch.prototype.assert = function () {312 return assertFalse(this.invert());313};314RegexpNotMatch.prototype.verify = function () {315 return verifyFalse(this.invert());316};317function seleniumEquals(type, pattern, expression) {318 if (type == 'String[]') {319 return seleniumEquals('String', pattern.replace(/\\,/g, ','), joinExpression(expression));320 }321 else if (type == 'String' && pattern.match(/^regexp:/)) {322 return new RegexpMatch(pattern.substring(7), expression);323 }324 else if (type == 'String' && pattern.match(/^regex:/)) {325 return new RegexpMatch(pattern.substring(6), expression);326 }327 else if (type == 'String' && (pattern.match(/^glob:/) || pattern.match(/[\*\?]/))) {328 pattern = pattern.replace(/^glob:/, '');329 pattern = pattern.replace(/([\]\[\\\{\}\$\(\).])/g, "\\$1");330 pattern = pattern.replace(/\?/g, "[\\s\\S]");331 pattern = pattern.replace(/\*/g, "[\\s\\S]*");332 return new RegexpMatch("^" + pattern + "$", expression);333 }334 else {335 pattern = pattern.replace(/^exact:/, '');336 return new Equals(xlateValue(type, pattern), expression);337 }338}339function concatString(array) {340 return array.filter(function (e) { return e; }).join(" + ");341}342function toArgumentList(array) {343 return array.join(", ");344}345// function keyVariable(key) {346// return variableName(key);347// }348app.sendKeysMaping = {};349function xlateKeyVariable(variable) {350 var r;351 if ((r = /^KEY_(.+)$/.exec(variable))) {352 var key = app.sendKeysMaping[r[1]];353 if (key) {354 return keyVariable(key);355 }356 }357 return null;358}359function xlateArgument(value, type) {360 value = value.replace(/^\s+/, '');361 value = value.replace(/\s+$/, '');362 var r;363 var r2;364 var parts = [];365 if ((r = /^javascript\{([\d\D]*)\}$/.exec(value))) {366 var js = r[1];367 var prefix = "";368 while ((r2 = /storedVars\[['"](.*?)['"]\]/.exec(js))) {369 parts.push(string(prefix + js.substring(0, r2.index) + "'"));370 parts.push(variableName(r2[1]));371 js = js.substring(r2.index + r2[0].length);372 prefix = "'";373 }374 parts.push(string(prefix + js));375 return new CallSelenium("getEval", [concatString(parts)]);376 }377 else if ((r = /\$\{/.exec(value))) {378 var regexp = /\$\{(.*?)\}/g;379 var lastIndex = 0;380 while (r2 = regexp.exec(value)) {381 var key = xlateKeyVariable(r2[1]);382 if (key || (app.declaredVars && app.declaredVars[r2[1]])) {383 if (r2.index - lastIndex > 0) {384 parts.push(string(value.substring(lastIndex, r2.index)));385 }386 parts.push(key ? key : variableName(r2[1]));387 lastIndex = regexp.lastIndex;388 }389 else if (r2[1] == "nbsp") {390 if (r2.index - lastIndex > 0) {391 parts.push(string(value.substring(lastIndex, r2.index)));392 }393 parts.push(nonBreakingSpace());394 lastIndex = regexp.lastIndex;395 }396 }397 if (lastIndex < value.length) {398 parts.push(string(value.substring(lastIndex, value.length)));399 }400 return (type && type.toLowerCase() == 'args') ? toArgumentList(parts) : concatString(parts);401 }402 else if (type && type.toLowerCase() == 'number') {403 return value;404 }405 else {406 return string(value);407 }408}409function xlateArrayElement(value) {410 return value.replace(/\\(.)/g, "$1");411}412function xlateValue(type, value) {413 if (type == 'String[]') {414 return array(parseArray(value));415 }416 else {417 return xlateArgument(value, type);418 }419}420function parseArray(value) {421 var start = 0;422 var list = [];423 for (var i = 0; i < value.length; i++) {424 if (value.charAt(i) == ',') {425 list.push(xlateArrayElement(value.substring(start, i)));426 start = i + 1;427 }428 else if (value.charAt(i) == '\\') {429 i++;430 }431 }432 list.push(xlateArrayElement(value.substring(start, value.length)));433 return list;434}435function addDeclaredVar(variable) {436 if (app.declaredVars == null) {437 app.declaredVars = {};438 }439 app.declaredVars[variable] = true;440}441function newVariable(prefix, index) {442 if (index == null)443 index = 1;444 if (app.declaredVars && app.declaredVars[prefix + index]) {445 return newVariable(prefix, index + 1);446 }447 else {448 addDeclaredVar(prefix + index);449 return prefix + index;450 }451}452function variableName(value) {453 return value;454}455function string(value) {456 if (value != null) {457 //value = value.replace(/^\s+/, '');458 //value = value.replace(/\s+$/, '');459 value = value.replace(/\\/g, '\\\\');460 value = value.replace(/\"/g, '\\"');461 value = value.replace(/\r/g, '\\r');462 value = value.replace(/\n/g, '\\n');463 return '"' + value + '"';464 }465 else {466 return '""';467 }468}469var CallSelenium = function (message, args, rawArgs) {470 this.message = message;471 if (args) {472 this.args = args;473 }474 else {475 this.args = [];476 }477 if (rawArgs) {478 this.rawArgs = rawArgs;479 }480 else {481 this.rawArgs = [];482 }483};484CallSelenium.prototype.invert = function () {485 var call = new CallSelenium(this.message);486 call.args = this.args;487 call.rawArgs = this.rawArgs;488 call.negative = !this.negative;489 return call;490};491CallSelenium.prototype.toString = function () {492 log.info('Processing ' + this.message);493 var result = '';494 var adaptor = new SeleniumWebDriverAdaptor(this.rawArgs);495 if (this.message.match(/^(getEval|runScript)/)) {496 adaptor.rawArgs = this.args;497 }498 if (adaptor[this.message]) {499 var codeBlock = adaptor[this.message].call(adaptor);500 if (adaptor.negative) {501 this.negative = !this.negative;502 }503 if (this.negative) {504 result += notOperator();505 }506 result += codeBlock;507 }508 else {509 //unsupported510 throw 'ERROR: Unsupported command [' + this.message + ' | ' + (this.rawArgs.length > 0 && this.rawArgs[0] ? this.rawArgs[0] : '') + ' | ' + (this.rawArgs.length > 1 && this.rawArgs[1] ? this.rawArgs[1] : '') + ']';511 }512 return result;513};514function formatCommand(command) {515 var line = null;516 try {517 var call;518 var i;519 var eq;520 var method;521 if (command.type == 'command') {522 /* Definitions are extracted from the iedoc-core.xml doc */523 var def = command.getDefinition();524 if (def && def.isAccessor) {525 call = new CallSelenium(def.name);526 for (i = 0; i < def.params.length; i++) {527 call.rawArgs.push(command.getParameterAt(i));528 call.args.push(xlateArgument(command.getParameterAt(i)));529 }530 var extraArg = command.getParameterAt(def.params.length);531 if (def.name.match(/^is/)) {532 if (command.command.match(/^assert/) ||533 (app.assertOrVerifyFailureOnNext && command.command.match(/^verify/))) {534 line = (def.negative ? assertFalse : assertTrue)(call);535 }536 else if (command.command.match(/^verify/)) {537 line = (def.negative ? verifyFalse : verifyTrue)(call);538 }539 else if (command.command.match(/^store/)) {540 addDeclaredVar(extraArg);541 line = statement(assignToVariable('boolean', extraArg, call));542 }543 else if (command.command.match(/^waitFor/)) {544 line = waitFor(def.negative ? call.invert() : call);545 }546 }547 else {548 if (command.command.match(/^(verify|assert)/)) {549 eq = seleniumEquals(def.returnType, extraArg, call);550 if (def.negative)551 eq = eq.invert();552 method = (!app.assertOrVerifyFailureOnNext && command.command.match(/^verify/)) ? 'verify' : 'assert';553 line = eq[method]();554 }555 else if (command.command.match(/^store/)) {556 addDeclaredVar(extraArg);557 line = statement(assignToVariable(def.returnType, extraArg, call));558 }559 else if (command.command.match(/^waitFor/)) {560 eq = seleniumEquals(def.returnType, extraArg, call);561 if (def.negative)562 eq = eq.invert();563 line = waitFor(eq);564 }565 else if (command.command.match(/^(getEval|runScript)/)) {566 call = new CallSelenium(def.name, xlateArgument(command.getParameterAt(0)), command.getParameterAt(0));567 line = statement(call, command);568 }569 }570 }571 else if (command.command.match(/setWindowSize|dragAndDrop/)) {572 call = new CallSelenium(command.command);573 call.rawArgs.push(command.getParameterAt(0));574 call.rawArgs.push(command.getParameterAt(1));575 line = statement(call, command);576 }577 else if ('pause' == command.command) {578 line = pause(command.target);579 }580 else if (app.echo && 'echo' == command.command) {581 line = echo(command.target);582 }583 else if ('store' == command.command) {584 addDeclaredVar(command.value);585 line = statement(assignToVariable('String', command.value, xlateArgument(command.target)));586 }587 else if (command.command.match(/^(assert|verify)Selected$/)) {588 var optionLocator = command.value;589 var flavor = 'Label';590 var value = optionLocator;591 var r = /^(index|label|value|id)=(.*)$/.exec(optionLocator);592 if (r) {593 flavor = r[1].replace(/^[a-z]/, function (str) {594 return str.toUpperCase();595 });596 value = r[2];597 }598 method = (!app.assertOrVerifyFailureOnNext && command.command.match(/^verify/)) ? 'verify' : 'assert';599 call = new CallSelenium("getSelected" + flavor);600 call.rawArgs.push(command.target);601 call.args.push(xlateArgument(command.target));602 eq = seleniumEquals('String', value, call);603 line = statement(eq[method]());604 }605 else if (def) {606 if (def.name.match(/^(assert|verify)(Error|Failure)OnNext$/)) {607 app.assertOrVerifyFailureOnNext = true;608 app.assertFailureOnNext = def.name.match(/^assert/);609 app.verifyFailureOnNext = def.name.match(/^verify/);610 }611 else {612 call = new CallSelenium(def.name);613 if ("open" == def.name && options.urlSuffix && !command.target.match(/^\w+:\/\//)) {614 // urlSuffix is used to translate core-based test615 call.rawArgs.push(options.urlSuffix + command.target);616 call.args.push(xlateArgument(options.urlSuffix + command.target));617 }618 else {619 for (i = 0; i < def.params.length; i++) {620 call.rawArgs.push(command.getParameterAt(i));621 call.args.push(xlateArgument(command.getParameterAt(i)));622 }623 }624 line = statement(call, command);625 }626 }627 else if (options.extensions[command.command]) {628 var commandName = command.command;629 command.command = 'userCommand';630 call = new CallSelenium(command.command);631 call.rawArgs.push(command.getParameterAt(0));632 call.rawArgs.push(command.getParameterAt(1));633 call.rawArgs.push(commandName);634 line = statement(call, command);635 }636 else {637 log.info("Unknown command: <" + command.command + ">");638 throw 'Unknown command [' + command.command + ']';639 }640 }641 }642 catch (e) {643 log.error("Caught exception: [" + e + "]. Stack:\n" + e.stack);644 // TODO645 // var call = new CallSelenium(command.command);646 // if ((command.target != null && command.target.length > 0)647 // || (command.value != null && command.value.length > 0)) {648 // call.rawArgs.push(command.target);649 // call.args.push(string(command.target));650 // if (command.value != null && command.value.length > 0) {651 // call.rawArgs.push(command.value);652 // call.args.push(string(command.value));653 // }654 // }655 // line = formatComment(new Comment(statement(call)));656 line = formatComment(new Comment('ERROR: Caught exception [' + e + ']'));657 }658 if (line && app.assertOrVerifyFailureOnNext) {659 line = assertOrVerifyFailure(line, app.assertFailureOnNext);660 app.assertOrVerifyFailureOnNext = false;661 app.assertFailureOnNext = false;662 app.verifyFailureOnNext = false;663 }664 //TODO: convert array to newline separated string -> if(array) return array.join"\n"665 if (command.type == 'command' && options.showSelenese && options.showSelenese == 'true') {666 if (command.remapped) {667 line = formatComment(new Comment(command.remapped.command + ' | ' + command.remapped.target + ' | ' + command.remapped.value)) + "\n" + line;668 }669 else {670 line = formatComment(new Comment(command.command + ' | ' + command.target + ' | ' + command.value)) + "\n" + line;671 }672 }673 return line;674}675app.remoteControl = true;676app.playable = false;677function parse_locator(locator) {678 var result = locator.match(/^([A-Za-z]+)=.+/);679 if (result) {680 var type = result[1].toLowerCase();681 var actualLocator = locator.substring(type.length + 1);682 return { type: type, string: actualLocator };683 }684 return { type: 'implicit', string: locator };685}686var SeleniumWebDriverAdaptor = function (rawArgs) {687 this.rawArgs = rawArgs;688 this.negative = false;689};690// Returns locator.type and locator.string691SeleniumWebDriverAdaptor.prototype._elementLocator = function (sel1Locator) {692 var locator = parse_locator(sel1Locator);693 if (sel1Locator.match(/^\/\//) || locator.type == 'xpath') {694 locator.type = 'xpath';695 return locator;696 }697 if (locator.type == 'css') {698 return locator;699 }700 if (locator.type == 'id') {701 return locator;702 }703 if (locator.type == 'link') {704 locator.string = locator.string.replace(/^exact:/, '');705 return locator;706 }707 if (locator.type == 'name') {708 return locator;709 }710 if (sel1Locator.match(/^document/) || locator.type == 'dom') {711 throw 'Error: Dom locators are not implemented yet!';712 }713 if (locator.type == 'ui') {714 throw 'Error: UI locators are not supported!';715 }716 if (locator.type == 'identifier') {717 throw 'Error: locator strategy [identifier] has been deprecated. To rectify specify the correct locator strategy id or name explicitly.';718 }719 if (locator.type == 'implicit') {720 throw 'Error: locator strategy either id or name must be specified explicitly.';721 }722 throw 'Error: unknown strategy [' + locator.type + '] for locator [' + sel1Locator + ']';723};724// Returns locator.elementLocator and locator.attributeName725SeleniumWebDriverAdaptor.prototype._attributeLocator = function (sel1Locator) {726 var attributePos = sel1Locator.lastIndexOf("@");727 var elementLocator = sel1Locator.slice(0, attributePos);728 var attributeName = sel1Locator.slice(attributePos + 1);729 return { elementLocator: elementLocator, attributeName: attributeName };730};731SeleniumWebDriverAdaptor.prototype._selectLocator = function (sel1Locator) {732 //Figure out which strategy to use733 var locator = { type: 'label', string: sel1Locator };734 // If there is a locator prefix, use the specified strategy735 var result = sel1Locator.match(/^([a-zA-Z]+)=(.*)/);736 if (result) {737 locator.type = result[1];738 locator.string = result[2];739 }740 //alert(locatorType + ' [' + locatorValue + ']');741 if (locator.type == 'index') {742 return locator;743 }744 if (locator.type == 'label') {745 return locator;746 }747 if (locator.type == 'value') {748 return locator;749 }750 throw 'Error: unknown or unsupported strategy [' + locator.type + '] for locator [' + sel1Locator + ']';751};752// Returns an object with a toString method753SeleniumWebDriverAdaptor.SimpleExpression = function (expressionString) {754 this.str = expressionString;755};756SeleniumWebDriverAdaptor.SimpleExpression.prototype.toString = function () {757 return this.str;758};759//helper method to simplify the ifCondition760SeleniumWebDriverAdaptor.ifCondition = function (conditionString, stmtString) {761 return ifCondition(new SeleniumWebDriverAdaptor.SimpleExpression(conditionString), function () {762 return statement(new SeleniumWebDriverAdaptor.SimpleExpression(stmtString)) + "\n";763 });764};765SeleniumWebDriverAdaptor.prototype.check = function (elementLocator) {766 var locator = this._elementLocator(this.rawArgs[0]);767 var driver = new WDAPI.Driver();768 var webElement = driver.findElement(locator.type, locator.string);769 return SeleniumWebDriverAdaptor.ifCondition(notOperator() + webElement.isSelected(), webElement.click());770};771SeleniumWebDriverAdaptor.prototype.click = function (elementLocator) {772 var locator = this._elementLocator(this.rawArgs[0]);773 var driver = new WDAPI.Driver();774 return driver.findElement(locator.type, locator.string).click();775};776SeleniumWebDriverAdaptor.prototype.close = function () {777 var driver = new WDAPI.Driver();778 return driver.close();779};780SeleniumWebDriverAdaptor.prototype.waitForPageToLoad = function () {781 var driver = new WDAPI.Driver();782 return driver.waitForPageToLoad();783};784SeleniumWebDriverAdaptor.prototype.openWindow = function () {785 var driver = new WDAPI.Driver();786 var url = this.rawArgs[0];787 var name = this.rawArgs[1];788 return driver.openWindow(url, name);789};790SeleniumWebDriverAdaptor.prototype.selectWindow = function () {791 var driver = new WDAPI.Driver();792 var name = this.rawArgs[0];793 return driver.selectWindow(name);794};795SeleniumWebDriverAdaptor.prototype.userCommand = function () {796 var driver = new WDAPI.Driver();797 var commandName = this.rawArgs[2];798 var locator;799 try {800 locator = this._elementLocator(this.rawArgs[0]);801 locator = WDAPI.Driver.searchContext(locator.type, locator.string);802 }803 catch (ignore) { }804 return driver.userCommand(commandName, this.rawArgs[0], this.rawArgs[1], locator);805};806/* wd does not support the windowFocus command. window(), called by selectWindow, both selects and focuses a window, so if the previously parsed command was selectWindow, we should be good. */807SeleniumWebDriverAdaptor.prototype.windowFocus = function () {808 if (app.previouslyParsedCommand.command !== 'selectWindow') {809 throw new Error('windowFocus is not supported by wd.');810 }811 /* Ignoring windowFocus command, as window focusing is handled implicitly in the previous wd command. */812 return "";813};814/* Custom user extension: Resize browser window directly via wd's browser object. */815SeleniumWebDriverAdaptor.prototype.setWindowSize = function () {816 var dimensions = this.rawArgs[0].split(/[^0-9]+/);817 var driver = new WDAPI.Driver();818 return driver.setWindowSize(dimensions[0], dimensions[1]);819};820SeleniumWebDriverAdaptor.prototype.deleteAllVisibleCookies = function () {821 var driver = new WDAPI.Driver();822 return driver.deleteAllCookies();823};824SeleniumWebDriverAdaptor.prototype.dragAndDrop = function (elementLocator, offset) {825 var locator = this._elementLocator(this.rawArgs[0]);826 var driver = new WDAPI.Driver();827 return driver.dragAndDrop(locator, this.rawArgs[1]);828};829SeleniumWebDriverAdaptor.prototype.focus = function (elementLocator) {830 var locator = this._elementLocator(this.rawArgs[0]);831 var driver = new WDAPI.Driver();832 return driver.focus(locator);833};834SeleniumWebDriverAdaptor.prototype.keyUp = function (elementLocator, key) {835 var locator = this._elementLocator(this.rawArgs[0]);836 var driver = new WDAPI.Driver();837 return driver.keyEvent(locator, 'keyup', this.rawArgs[1]);838};839SeleniumWebDriverAdaptor.prototype.keyDown = function (elementLocator, key) {840 var locator = this._elementLocator(this.rawArgs[0]);841 var driver = new WDAPI.Driver();842 return driver.keyEvent(locator, 'keydown', this.rawArgs[1]);843};844SeleniumWebDriverAdaptor.prototype.keyPress = function (elementLocator, key) {845 var locator = this._elementLocator(this.rawArgs[0]);846 var driver = new WDAPI.Driver();847 return driver.keyEvent(locator, 'keypress', this.rawArgs[1]);848};849SeleniumWebDriverAdaptor.prototype.captureEntirePageScreenshot = function () {850 var driver = new WDAPI.Driver();851 var fileName = this.rawArgs[0];852 return driver.captureEntirePageScreenshot(fileName);853};854SeleniumWebDriverAdaptor.prototype.getAttribute = function (attributeLocator) {855 var attrLocator = this._attributeLocator(this.rawArgs[0]);856 var locator = this._elementLocator(attrLocator.elementLocator);857 var driver = new WDAPI.Driver();858 var webElement = driver.findElement(locator.type, locator.string);859 return webElement.getAttribute(attrLocator.attributeName);860};861SeleniumWebDriverAdaptor.prototype.getBodyText = function () {862 var driver = new WDAPI.Driver();863 return driver.findElement('tag_name', 'BODY').getText();864};865SeleniumWebDriverAdaptor.prototype.getCssCount = function (elementLocator) {866 var locator = this._elementLocator(this.rawArgs[0]);867 var driver = new WDAPI.Driver();868 return driver.findElements(locator.type, locator.string).getSize();869};870SeleniumWebDriverAdaptor.prototype.getLocation = function () {871 var driver = new WDAPI.Driver();872 return driver.getCurrentUrl();873};874SeleniumWebDriverAdaptor.prototype.getText = function (elementLocator) {875 var locator = this._elementLocator(this.rawArgs[0]);876 var driver = new WDAPI.Driver();877 return driver.findElement(locator.type, locator.string).getText();878};879SeleniumWebDriverAdaptor.prototype.getTitle = function () {880 var driver = new WDAPI.Driver();881 return driver.getTitle();882};883SeleniumWebDriverAdaptor.prototype.getAlert = function () {884 var driver = new WDAPI.Driver();885 return driver.getAlert();886};887SeleniumWebDriverAdaptor.prototype.isAlertPresent = function () {888 return WDAPI.Utils.isAlertPresent();889};890SeleniumWebDriverAdaptor.prototype.getConfirmation = function () {891 var driver = new WDAPI.Driver();892 return driver.getAlert();893};894SeleniumWebDriverAdaptor.prototype.isConfirmationPresent = function () {895 return WDAPI.Utils.isAlertPresent();896};897SeleniumWebDriverAdaptor.prototype.chooseOkOnNextConfirmation = function () {898 var driver = new WDAPI.Driver();899 return driver.chooseOkOnNextConfirmation();900};901SeleniumWebDriverAdaptor.prototype.chooseCancelOnNextConfirmation = function () {902 var driver = new WDAPI.Driver();903 return driver.chooseCancelOnNextConfirmation();904};905SeleniumWebDriverAdaptor.prototype.getValue = function (elementLocator) {906 var locator = this._elementLocator(this.rawArgs[0]);907 var driver = new WDAPI.Driver();908 return driver.findElement(locator.type, locator.string).getAttribute('value');909};910SeleniumWebDriverAdaptor.prototype.getXpathCount = function (elementLocator) {911 var locator = this._elementLocator(this.rawArgs[0]);912 var driver = new WDAPI.Driver();913 return driver.findElements(locator.type, locator.string).getSize();914};915SeleniumWebDriverAdaptor.prototype.goBack = function () {916 var driver = new WDAPI.Driver();917 return driver.back();918};919SeleniumWebDriverAdaptor.prototype.isChecked = function (elementLocator) {920 var locator = this._elementLocator(this.rawArgs[0]);921 var driver = new WDAPI.Driver();922 return driver.findElement(locator.type, locator.string).isSelected();923};924SeleniumWebDriverAdaptor.prototype.isElementPresent = function (elementLocator) {925 var locator = this._elementLocator(this.rawArgs[0]);926 //var driver = new WDAPI.Driver();927 //TODO: enough to just find element, but since this is an accessor, we will need to make a not null comparison928 //return driver.findElement(locator.type, locator.string);929 return WDAPI.Utils.isElementPresent(locator.type, locator.string);930};931SeleniumWebDriverAdaptor.prototype.isVisible = function (elementLocator) {932 var locator = this._elementLocator(this.rawArgs[0]);933 var driver = new WDAPI.Driver();934 return driver.findElement(locator.type, locator.string).isDisplayed();935};936SeleniumWebDriverAdaptor.prototype.open = function (url) {937 //TODO process the relative and absolute urls938 var absUrl = xlateArgument(this.rawArgs[0]);939 var driver = new WDAPI.Driver();940 return driver.get(absUrl);941};942SeleniumWebDriverAdaptor.prototype.refresh = function () {943 var driver = new WDAPI.Driver();944 return driver.refresh();945};946SeleniumWebDriverAdaptor.prototype.submit = function (elementLocator) {947 var locator = this._elementLocator(this.rawArgs[0]);948 var driver = new WDAPI.Driver();949 return driver.findElement(locator.type, locator.string).submit();950};951SeleniumWebDriverAdaptor.prototype.type = function (elementLocator, text) {952 var locator = this._elementLocator(this.rawArgs[0]);953 var driver = new WDAPI.Driver();954 var webElement = driver.findElement(locator.type, locator.string);955 return statement(new SeleniumWebDriverAdaptor.SimpleExpression(webElement.clear())) + "\n" + webElement.sendKeys(this.rawArgs[1]);956};957SeleniumWebDriverAdaptor.prototype.sendKeys = function (elementLocator, text) {958 var locator = this._elementLocator(this.rawArgs[0]);959 var driver = new WDAPI.Driver();960 return driver.findElement(locator.type, locator.string).sendKeys(this.rawArgs[1]);961};962SeleniumWebDriverAdaptor.prototype.uncheck = function (elementLocator) {963 var locator = this._elementLocator(this.rawArgs[0]);964 var driver = new WDAPI.Driver();965 var webElement = driver.findElement(locator.type, locator.string);966 return SeleniumWebDriverAdaptor.ifCondition(webElement.isSelected(), webElement.click());967};968SeleniumWebDriverAdaptor.prototype.select = function (elementLocator, label) {969 var locator = this._elementLocator(this.rawArgs[0]);970 var driver = new WDAPI.Driver();971 return driver.findElement(locator.type, locator.string).select(this._selectLocator(this.rawArgs[1]));972};973SeleniumWebDriverAdaptor.prototype.getEval = SeleniumWebDriverAdaptor.prototype.runScript = function (script) {974 var driver = new WDAPI.Driver();975 return driver.eval(this.rawArgs[0]);976};977var WDAPI = function () {978};979/*980 * Formatter for Selenium 2 / WebDriver JavaScript client.981 */982function useSeparateEqualsForArray() {983 return true;984}985function testClassName(testName) {986 return testName.split(/[^0-9A-Za-z]+/).map(function (x) { return capitalize(x); }).join('');987}988function testMethodName(testName) {989 return "test" + testClassName(testName);990}991function nonBreakingSpace() {992 return "\"\\u00a0\"";993}994function array(value) {995 return JSON.stringify(value);996}997Equals.prototype.toString = function () {998 return this.e1.toString() + " === " + this.e2.toString();999};1000Equals.prototype.assert = function () {1001 var varA = getTempVarName();1002 var varB = getTempVarName();1003 return "var " + varA + " = " + this.e1.toString() + ";\n" + "var " + varB + " = " + this.e2.toString() + ";\n"1004 + "assert.equal(" + varA + ", " + varB + ", 'Assertion error: Expected: ' + " + varA + " + ', got: ' + " + varB + ");";1005};1006Equals.prototype.verify = function () {1007 return verify(this.assert());1008};1009NotEquals.prototype.toString = function () {1010 return this.e1.toString() + " !== " + this.e2.toString();1011};1012NotEquals.prototype.assert = function () {1013 return "assert.notEqual(" + this.e1.toString() + ", " + this.e2.toString()1014 + ", 'Assertion error: Expected: " + this.e1.toString() + ", Actual: ' + "1015 + this.e2.toString() + ");";1016};1017NotEquals.prototype.verify = function () {1018 return verify(this.assert());1019};1020function joinExpression(expression) {1021 return expression.toString() + ".join(',')";1022}1023function statement(expression, command) {1024 var s = expression.toString();1025 if (s.length === 0) {1026 return null;1027 }1028 return s.substr(-1) !== ';' && s.substr(-2) !== '*/' ? s + ';' : s;1029}1030function assignToVariable(type, variable, expression) {1031 return "/* @type " + type + " */\r\nvar " +1032 variable + " = " + expression.toString();1033}1034function ifCondition(expression, callback) {1035 return "if (" + expression.toString() + ") {\n" + callback() + "}";1036}1037function assertTrue(expression) {1038 return "assert.strictEqual(!!" + expression.toString() + ", true"1039 + ", 'Assertion error: Expected: true, got: ' + "1040 + expression.toString() + " + \" [ Command: " + app.currentlyParsingCommand.toString().replace(/"/g, '\\"') + " ]\");";1041}1042function assertFalse(expression) {1043 return "assert.strictEqual(!!" + expression.toString() + ", false"1044 + ", 'Assertion error: Expected: false, got: ' + "1045 + expression.toString() + " + \" [ Command: " + app.currentlyParsingCommand.toString().replace(/"/g, '\\"') + " ]\");";1046}1047function verify(statement) {1048 return "try {\n" +1049 statement + "\n" +1050 "} catch (e) {\n" +1051 "options.verificationErrors && options.verificationErrors.push(e.toString());\n" +1052 "}";1053}1054function verifyTrue(expression) {1055 return verify(assertTrue(expression));1056}1057function verifyFalse(expression) {1058 return verify(assertFalse(expression));1059}1060RegexpMatch.prototype.toString = function () {1061 return this.expression + ".match(" + string(this.pattern) + ")";1062};1063function waitFor(expression) {1064 return "waitFor(function() {\n"1065 + (expression.setup ? expression.setup() + "\n" : "")1066 + "return " + expression.toString() + ";\n"1067 + "}, '" + expression.toString().replace(/'/g, "\\'") + "');\n";1068}1069function assertOrVerifyFailure(line, isAssert) {1070 return "assert.throws(" + line + ")";1071}1072function pause(milliseconds) {1073 return "browser.sleep(" + parseInt(milliseconds, 10) + ");";1074}1075function echo(message) {1076 return "console.log(" + xlateArgument(message) + ");";1077}1078function formatComment(comment) {1079 /* Some people tend to write Selenium comments as JS block comments, so check if that's the case first, or we'll end up with a broken script: */1080 if (comment.comment.match(/^\/\*.+\*\//))1081 return comment.comment;1082 return comment.comment.replace(/.+/mg, function (str) {1083 return "/* " + str + " */";1084 });1085}1086function keyVariable(key) {1087 return "Keys." + key;1088}1089app.sendKeysMaping = {1090 BKSP: "BACK_SPACE",1091 BACKSPACE: "BACK_SPACE",1092 TAB: "TAB",1093 ENTER: "ENTER",1094 SHIFT: "SHIFT",1095 CONTROL: "CONTROL",1096 CTRL: "CONTROL",1097 ALT: "ALT",1098 PAUSE: "PAUSE",1099 ESCAPE: "ESCAPE",1100 ESC: "ESCAPE",1101 SPACE: "SPACE",1102 PAGE_UP: "PAGE_UP",1103 PGUP: "PAGE_UP",1104 PAGE_DOWN: "PAGE_DOWN",1105 PGDN: "PAGE_DOWN",1106 END: "END",1107 HOME: "HOME",1108 LEFT: "LEFT",1109 UP: "UP",1110 RIGHT: "RIGHT",1111 DOWN: "DOWN",1112 INSERT: "INSERT",1113 INS: "INSERT",1114 DELETE: "DELETE",1115 DEL: "DELETE",1116 SEMICOLON: "SEMICOLON",1117 EQUALS: "EQUALS",1118 NUMPAD0: "NUMPAD0",1119 N0: "NUMPAD0",1120 NUMPAD1: "NUMPAD1",1121 N1: "NUMPAD1",1122 NUMPAD2: "NUMPAD2",1123 N2: "NUMPAD2",1124 NUMPAD3: "NUMPAD3",1125 N3: "NUMPAD3",1126 NUMPAD4: "NUMPAD4",1127 N4: "NUMPAD4",1128 NUMPAD5: "NUMPAD5",1129 N5: "NUMPAD5",1130 NUMPAD6: "NUMPAD6",1131 N6: "NUMPAD6",1132 NUMPAD7: "NUMPAD7",1133 N7: "NUMPAD7",1134 NUMPAD8: "NUMPAD8",1135 N8: "NUMPAD8",1136 NUMPAD9: "NUMPAD9",1137 N9: "NUMPAD9",1138 MULTIPLY: "MULTIPLY",1139 MUL: "MULTIPLY",1140 ADD: "ADD",1141 PLUS: "ADD",1142 SEPARATOR: "SEPARATOR",1143 SEP: "SEPARATOR",1144 SUBTRACT: "SUBTRACT",1145 MINUS: "SUBTRACT",1146 DECIMAL: "DECIMAL",1147 PERIOD: "DECIMAL",1148 DIVIDE: "DIVIDE",1149 DIV: "DIVIDE",1150 F1: "F1",1151 F2: "F2",1152 F3: "F3",1153 F4: "F4",1154 F5: "F5",1155 F6: "F6",1156 F7: "F7",1157 F8: "F8",1158 F9: "F9",1159 F10: "F10",1160 F11: "F11",1161 F12: "F12",1162 META: "META",1163 COMMAND: "COMMAND"1164};1165// not implemented, edit late // fish1166/**1167 * Returns a string representing the suite for this formatter language.1168 *1169 * @param testSuite the suite to format1170 * @param filename the file the formatted suite will be saved as1171 */1172/*function formatSuite(testSuite, filename) {1173 var suiteClass = /^(\w+)/.exec(filename)[1];1174 suiteClass = suiteClass[0].toUpperCase() + suiteClass.substring(1);1175 var formattedSuite = "var " + suiteClass + " = { 'tests' : {}};\n";1176 for (var i = 0; i < testSuite.tests.length; ++i) {1177 var testClass = testSuite.tests[i].getTitle();1178 formattedSuite += suiteClass + ".tests['" + testClass + "'] = require('./" + testClass + ".js');\n";1179 }1180 formattedSuite += "\n"1181 + suiteClass + ".run = function " + suiteClass + "_run() {\n"1182 + "var webdriver = require('selenium-webdriver');\n"1183 + "\n"1184 + "var driver = new webdriver.Builder().\n"1185 + "withCapabilities(webdriver.Capabilities.firefox()).\n"1186 + "build();\n"1187 + 'var baseUrl = "";\n'1188 + "var acceptNextAlert = true;\n"1189 + "var verificationErrors = [];\n"1190 + "\n"1191 + "Object.keys(" + suiteClass + ".tests).forEach(function (v,k,a) {\n"1192 + suiteClass + ".tests[v](webdriver, driver, baseUrl, acceptNextAlert, verificationErrors);\n"1193 + "});\n"1194 + "}\n"1195 + "\n"1196 + "module.exports = " + suiteClass + ";\n"1197 + "//" + suiteClass + ".run();";1198 return formattedSuite;1199}*/1200options = {1201 showSelenese: 'false',1202 defaultExtension: "js"1203};1204function defaultExtension() {1205 return options.defaultExtension;1206}1207options.getHeader = function () {1208 return '"use strict";\n'1209 + "/* jslint node: true */\n\n"1210 + "var assert = require('assert');\n\n"1211 + "var browser, element, currentCommand = '', options = { timeout: " + options.timeout + ", retries: " + options.retries + ", screenshotFolder: '" + options.screenshotFolder + "', baseUrl: '" + options.baseUrl + "' };\n\n"1212 + "module.exports = function ${methodName} (_browser, _options) {\n\n"1213 + "browser = _browser;\n"1214 + "var acceptNextAlert = true;\n"1215 + "getRuntimeOptions(_options);\n"1216 + "try {\n";1217};1218var fs = require("fs");1219var ideFunc = fs.readFileSync(__dirname + "/selenium-utils.js", "utf-8");1220options.footer = "} catch(e) {\n"1221 + "var failedScreenShot = options.screenshotFolder + '/Exception@' + currentCommand.replace(/\\(.+/, '') + '.png';\n"1222 + "try {\n"1223 + "createFolderPath(options.screenshotFolder);\n"1224 + "browser.saveScreenshot(failedScreenShot);\n"1225 + "} catch (e) {\n"1226 + "e.message = 'Failure in Selenium command \"' + currentCommand + '\": ' + e.message + ' (Could not save screenshot after failure occured)';\n"1227 + "throw e;\n"1228 + "}\n"1229 + "e.message = 'Failure in Selenium command \"' + currentCommand + '\": ' + e.message + ' (Screenshot was saved to ' + failedScreenShot + ')';\n"1230 + "throw e;\n"1231 + "}\n"1232 + "\n};\n\n" + ideFunc;1233/* no used in node, but should be used in selenium-ide, obsoleted1234app.configForm =1235 '<description>Header</description>' +1236 '<textbox id="options_header" multiline="true" flex="1" rows="4"/>' +1237 '<description>Footer</description>' +1238 '<textbox id="options_footer" multiline="true" flex="1" rows="4"/>' +1239 '<description>Indent</description>' +1240 '<menulist id="options_indent"><menupopup>' +1241 '<menuitem label="Tab" value="tab"/>' +1242 '<menuitem label="1 space" value="1"/>' +1243 '<menuitem label="2 spaces" value="2"/>' +1244 '<menuitem label="3 spaces" value="3"/>' +1245 '<menuitem label="4 spaces" value="4"/>' +1246 '<menuitem label="5 spaces" value="5"/>' +1247 '<menuitem label="6 spaces" value="6"/>' +1248 '<menuitem label="7 spaces" value="7"/>' +1249 '<menuitem label="8 spaces" value="8"/>' +1250 '</menupopup></menulist>' +1251 '<checkbox id="options_showSelenese" label="Show Selenese"/>';*/1252app.name = "Node (wd-sync)";1253app.testcaseExtension = ".js";1254app.suiteExtension = ".js";1255app.webdriver = true;1256WDAPI.Driver = function () {1257 this.ref = 'browser';1258};1259WDAPI.Driver.searchContext = function (locatorType, locator) {1260 var locatorString = xlateArgument(locator);1261 switch (locatorType) {1262 case 'xpath':1263 return 'browser.elementByXPath(' + locatorString + ')';1264 case 'css':1265 return 'browser.elementByCssSelector(' + locatorString + ')';1266 case 'id':1267 return 'browser.elementById(' + locatorString + ')';1268 case 'link':1269 return 'browser.elementByLinkText(' + locatorString + ')';1270 case 'name':1271 return 'browser.elementByName(' + locatorString + ')';1272 case 'tag_name':1273 return 'browser.elementByTagName(' + locatorString + ')';1274 }1275 throw 'Error: unknown strategy [' + locatorType + '] for locator [' + locator + ']';1276};1277WDAPI.Driver.prototype.back = function () {1278 return this.ref + ".back()";1279};1280/**1281 * Closing a window is safe as long as it's a popup. Closing the main window,1282 * however, will break the browser object and prevent subsequent tests from1283 * running as the Selenium server won't have a window to run them on. In the1284 * IDE a test writer might add a close statement, and it'll work fine so long1285 * as there are more tabs to spend. We safeguard against it here.1286 */1287WDAPI.Driver.prototype.close = function () {1288 return "if (browser.windowHandles().length > 1) {\n"1289 + this.ref + ".close();\n"1290 + "refocusWindow();\n"1291 + "}";1292};1293WDAPI.Driver.prototype.waitForPageToLoad = function () {1294 return "waitForPageToLoad(" + this.ref + ");\n";1295};1296WDAPI.Driver.prototype.openWindow = function (url, name) {1297 url = url ? "'" + url + "'" : "null";1298 name = name ? "'" + name + "'" : "null";1299 return this.ref + ".newWindow(addBaseUrl(" + url + "), " + name + ")";1300};1301WDAPI.Driver.prototype.selectWindow = function (name) {1302 name = name ? "'" + name + "'" : "null";1303 return this.ref + ".window(" + name + ")";1304};1305WDAPI.Driver.prototype.userCommand = function (command, target, value, locator) {1306 target = '"' + ('' + target).replace(/"/g, '\\"') + '"';1307 value = '"' + ('' + value).replace(/"/g, '\\"') + '"';1308 return command + '(' + target + ', ' + value + ', ' + locator + ')\n';1309};1310WDAPI.Driver.prototype.setWindowSize = function (width, height) {1311 return this.ref + '.setWindowSize(' + width + ', ' + height + ')';1312};1313WDAPI.Driver.prototype.focus = function (locator) {1314 return 'element = ' + WDAPI.Driver.searchContext(locator.type, locator.string) + ';\n'1315 + 'browser.execute("arguments[0].focus()", [element.rawElement]);\n';1316};1317WDAPI.Driver.prototype.keyEvent = function (locator, event, key) {1318 var code = 0;1319 /* If we have a key string, check if it's an escaped ASCII keycode: */1320 if (typeof key === 'string') {1321 var escapedASCII = key.match(/^\\+([0-9]+)$/);1322 if (escapedASCII) {1323 code = +escapedASCII[1];1324 }1325 else {1326 /* Otherwise get the code: */1327 code = key.charCodeAt(0);1328 }1329 }1330 return 'keyEvent(' + WDAPI.Driver.searchContext(locator.type, locator.string) + ', "' + event + '", ' + code + ');';1331};1332WDAPI.Driver.prototype.dragAndDrop = function (locator, offset) {1333 offset = offset.split(/[^0-9\-]+/);1334 return 'element = ' + WDAPI.Driver.searchContext(locator.type, locator.string) + ';\n'1335 + 'element.moveTo();\n'1336 + this.ref + '.buttonDown();\n'1337 + 'element.moveTo(' + offset[0] + ',' + offset[1] + ');\n'1338 + this.ref + '.buttonUp();';1339};1340WDAPI.Driver.prototype.deleteAllCookies = function () {1341 return this.ref + '.deleteAllCookies()';1342};1343WDAPI.Driver.prototype.captureEntirePageScreenshot = function (fileName) {1344 var screenshotFolder = 'screenshots/' + app.testCaseName;1345 if (typeof fileName === 'undefined' || fileName === '') {1346 fileName = ('00000' + (++app.screenshotsCount)).slice(-5);1347 }1348 else {1349 // Strip any folders and file extension that might be given with the file name from the test case:1350 fileName = fileName.replace(/.+[/\\]([^/\\]+)$/, '$1').replace(/\.(png|jpg|jpeg|bmp|tif|tiff|gif)/i, '');1351 }1352 var screenshotFileVar = getTempVarName();1353 return 'var ' + screenshotFileVar + ' = "' + fileName + '.png";\n'1354 + 'createFolderPath(options.screenshotFolder);\n'1355 + this.ref + '.saveScreenshot(options.screenshotFolder + "/" + ' + screenshotFileVar + ')';1356};1357WDAPI.Driver.prototype.findElement = function (locatorType, locator) {1358 return new WDAPI.Element(WDAPI.Driver.searchContext(locatorType, locator));1359};1360WDAPI.Driver.prototype.findElements = function (locatorType, locator) {1361 return new WDAPI.ElementList(WDAPI.Driver.searchContext(locatorType, locator).replace("element", "elements"));1362};1363WDAPI.Driver.prototype.getCurrentUrl = function () {1364 return this.ref + ".url()";1365};1366WDAPI.Driver.prototype.get = function (url) {1367 return this.ref + ".get(addBaseUrl(" + url + "))";1368};1369WDAPI.Driver.prototype.getTitle = function () {1370 return this.ref + ".title()";1371};1372WDAPI.Driver.prototype.getAlert = function () {1373 return "closeAlertAndGetItsText(acceptNextAlert);\n"1374 + "acceptNextAlert = true";1375};1376WDAPI.Driver.prototype.chooseOkOnNextConfirmation = function () {1377 return "acceptNextAlert = true";1378};1379WDAPI.Driver.prototype.chooseCancelOnNextConfirmation = function () {1380 return "acceptNextAlert = false";1381};1382WDAPI.Driver.prototype.refresh = function () {1383 return this.ref + ".refresh()";1384};1385WDAPI.Driver.prototype.eval = function (script) {1386 return this.ref + ".safeEval(" + script + ")";1387};1388WDAPI.Element = function (ref) {1389 this.ref = ref;1390};1391WDAPI.Element.prototype.clear = function () {1392 return this.ref + ".clear()";1393};1394WDAPI.Element.prototype.click = function () {1395 return this.ref + ".click()";1396};1397WDAPI.Element.prototype.getAttribute = function (attributeName) {1398 return this.ref + ".getAttribute(" + xlateArgument(attributeName) + ")";1399};1400WDAPI.Element.prototype.getText = function () {1401 return this.ref + ".text()";1402};1403WDAPI.Element.prototype.isDisplayed = function () {1404 return this.ref + ".isDisplayed()";1405};1406WDAPI.Element.prototype.isSelected = function () {1407 return this.ref + ".isSelected()";1408};1409WDAPI.Element.prototype.sendKeys = function (text) {1410 return this.ref + ".sendKeys(" + xlateArgument(text) + ")";1411};1412WDAPI.Element.prototype.submit = function () {1413 return this.ref + ".submit()";1414};1415WDAPI.Element.prototype.select = function (selectLocator) {1416 if (selectLocator.type == 'index') {1417 return this.ref + ".elementByXPath('option[" + ((parseInt(selectLocator.string) + 1) || 1) + "]').click()";1418 }1419 if (selectLocator.type == 'value') {1420 return this.ref + ".elementByXPath('option[@value=" + xlateArgument(selectLocator.string) + "][1]').click()";1421 }1422 return this.ref + ".elementByXPath('option[text()=" + xlateArgument(selectLocator.string) + "][1]').click()";1423};1424WDAPI.ElementList = function (ref) {1425 this.ref = ref;1426};1427WDAPI.ElementList.prototype.getItem = function (index) {1428 return this.ref + "[" + index + "]";1429};1430WDAPI.ElementList.prototype.getSize = function () {1431 return this.ref + ".length";1432};1433WDAPI.ElementList.prototype.isEmpty = function () {1434 return "isEmptyArray(" + this.ref + ")";1435};1436WDAPI.Utils = function () {1437};1438WDAPI.Utils.isElementPresent = function (how, what) {1439 return WDAPI.Driver.searchContext(how, what).replace("element", "hasElement");1440};1441WDAPI.Utils.isAlertPresent = function () {1442 return "isAlertPresent()";...
actions-specs.js
Source:actions-specs.js
...25 });26 describe('keyevent', function () {27 it('shoudle be able to execute keyevent via pressKeyCode', async function () {28 sandbox.stub(driver, 'pressKeyCode');29 await driver.keyevent('66', 'meta');30 driver.pressKeyCode.calledWithExactly('66', 'meta').should.be.true;31 });32 it('should set metastate to null by default', async function () {33 sandbox.stub(driver, 'pressKeyCode');34 await driver.keyevent('66');35 driver.pressKeyCode.calledWithExactly('66', null).should.be.true;36 });37 });38 describe('pressKeyCode', function () {39 it('shoudle be able to press key code', async function () {40 await driver.pressKeyCode('66', 'meta');41 driver.bootstrap.sendAction42 .calledWithExactly('pressKeyCode', {keycode: '66', metastate: 'meta'})43 .should.be.true;44 });45 it('should set metastate to null by default', async function () {46 await driver.pressKeyCode('66');47 driver.bootstrap.sendAction48 .calledWithExactly('pressKeyCode', {keycode: '66', metastate: null})...
notifications-e2e-specs.js
Source:notifications-e2e-specs.js
...41 }42 text.should.include('Mood ring');43 });44 // go back to the app45 await driver.keyevent(4);46 await driver.getText(el.ELEMENT).should.become(':-|');47 });...
Using AI Code Generation
1var webdriver = require('selenium-webdriver'),2 until = webdriver.until;3var driver = new webdriver.Builder()4 .forBrowser('chrome')5 .build();6driver.findElement(By.name('q')).sendKeys('webdriver');7driver.findElement(By.name('btnG')).click();8driver.wait(until.titleIs('webdriver - Google Search'), 1000);9driver.quit();10driver.keyevent(82);11driver.keyevent(3);12driver.quit();13driver.keyevent(4);14driver.quit();15driver.keyevent(111);16driver.quit();17driver.keyevent(112);18driver.quit();19driver.keyevent(113);20driver.quit();21driver.keyevent(114);22driver.quit();23driver.keyevent(115);24driver.quit();25driver.keyevent(116);26driver.quit();27driver.keyevent(122);28driver.quit();29driver.keyevent(123);30driver.quit();31driver.keyevent(124);32driver.quit();33driver.keyevent(126);34driver.quit();35driver.keyevent(127);36driver.quit();37driver.keyevent(128);38driver.quit();39driver.keyevent(129);40driver.quit();41driver.keyevent(130);42driver.quit();43driver.keyevent(164);
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var driver = wd.promiseChainRemote("localhost", 4723);4var desired = {5};6 .init(desired)7 .setImplicitWaitTimeout(10000)8 .then(function() {9 return driver.keyevent(26);10 })11 .then(function() {12 return driver.sleep(5000);13 })14 .then(function() {15 return driver.quit();16 })17 .done();18 .init(desired)19 .setImplicitWaitTimeout(10000)20 .then(function() {21 return driver.keyevent(26, 0);22 })23 .then(function() {24 return driver.sleep(5000);25 })26 .then(function() {27 return driver.quit();28 })29 .done();30 .init(desired)31 .setImplicitWaitTimeout(10000)32 .then(function() {33 return driver.keyevent(26, 1);34 })35 .then(function() {36 return driver.sleep(5000);37 })38 .then(function() {39 return driver.quit();40 })41 .done();42 .init(desired)
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2 .withCapabilities({browserName: 'chrome'}).build();3driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');4driver.findElement(webdriver.By.name('btnG')).click();5driver.sleep(5000).then(function() {6 driver.quit();7});8driver.keyevent(3);9driver.quit();10I've tried to use the driver.keyevent() method on the Appium Android Driver, but I get the following error:11I've tried to use the driver.keyevent() method on the Appium Android Driver, but I get the following error:12I've tried to use the driver.keyevent() method on the Appium Android Driver, but I get the following error:13I've tried to use the driver.keyevent() method on the Appium Android Driver, but I get the following error:14I've tried to use the driver.keyevent() method on the Appium Android Driver, but I
Using AI Code Generation
1driver.currentActivity().then(function (activity) {2 console.log(activity);3});4driver.startActivity('io.appium.android.apis', '.ApiDemos');5driver.installApp('C:\\Users\\user\\Downloads\\ApiDemos-debug.apk');6driver.removeApp('io.appium.android.apis');7driver.isAppInstalled('io.appium.android.apis').then(function (isInstalled) {8 console.log(isInstalled);9});10driver.backgroundApp(5);11driver.openNotifications();12driver.getDeviceTime().then(function (deviceTime) {13 console.log(deviceTime);14});15driver.hideKeyboard();16driver.resetApp();17driver.shake();
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var driver = wd.promiseChainRemote('localhost', 4723);4var desiredCaps = {5};6 .init(desiredCaps)7 .sleep(2000)8 .keyevent(4)9 .sleep(2000)10 .quit();11var wd = require('wd');12var assert = require('assert');13var driver = wd.promiseChainRemote('localhost', 4723);14var desiredCaps = {15};16 .init(desiredCaps)17 .sleep(2000)18 .keyevent(4)19 .sleep(2000)20 .quit();
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!!