Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Allow plugins to define new locator types #228

Open
wants to merge 7 commits into
base: trunk
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions packages/selenium-ide/src/__test__/plugin/locatorResolver.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import { registerLocator, canResolveLocator, resolveLocator } from "../../plugin/locatorResolver";

describe("locator resolver", () => {
it("should register a locator", () => {
expect(registerLocator("test", new Function())).toBeUndefined();
});
it("should fail to register a locator with no key", () => {
expect(() => registerLocator()).toThrowError("Expected to receive string instead received undefined");
});
it("should fail to register a locator with a key that is not string", () => {
expect(() => registerLocator(5, new Function())).toThrowError("Expected to receive string instead received number");
});
it("should fail to register a locator with no callback", () => {
expect(() => registerLocator("test")).toThrowError("Expected to receive function instead received undefined");
});
it("should fail to register a locator with a callback that is not a function", () => {
expect(() => registerLocator("test", 1)).toThrowError("Expected to receive function instead received number");
});
it("should fail to register a locator with the same key as a previous one", () => {
const key = "testTwo";
registerLocator(key, new Function());
expect(() => registerLocator(key, new Function())).toThrowError(`A locator named ${key} already exists`);
});
it("should fail to override a default locator", () => {
expect(() => registerLocator("id", new Function())).toThrowError("Overriding default locator strategies is disallowed");
expect(() => registerLocator("name", new Function())).toThrowError("Overriding default locator strategies is disallowed");
expect(() => registerLocator("link", new Function())).toThrowError("Overriding default locator strategies is disallowed");
expect(() => registerLocator("css", new Function())).toThrowError("Overriding default locator strategies is disallowed");
expect(() => registerLocator("xpath", new Function())).toThrowError("Overriding default locator strategies is disallowed");
});
it("should check if a locator may be resolved", () => {
registerLocator("exists", new Function());
expect(canResolveLocator("exists")).toBeTruthy();
expect(canResolveLocator("nonExistent")).toBeFalsy();
});
it("should throw when resolving a locator that does not exist", () => {
const locator = "nonExistent";
expect(() => resolveLocator(locator)).toThrowError(`The locator ${locator} is not registered with any plugin`);
});
it("should successfully resolve a sync locator", () => {
const cb = () => {
return "//button";
};
registerLocator("syncLocator", cb);
expect(resolveLocator("syncLocator")).toBe("//button");
});
it("should fail to resolve a sync locator", () => {
const locator = "syncFail";
const cb = () => {
throw new Error("test error");
};
registerLocator(locator, cb);
expect(() => {
try {
resolveLocator(locator);
} catch(e) {
if (e.message !== `The locator ${locator} is not registered with any plugin`) {
throw e;
}
}
}).toThrow("test error");
});
it("should throw if the returned value is not an xpath", () => {
const locator = "xpathErr";
const cb = () => {
return 5;
};
registerLocator(locator, cb);
expect(() => {
try {
resolveLocator(locator);
} catch(e) {
if (e.message !== `The locator ${locator} is not registered with any plugin`) {
throw e;
}
}
}).toThrow(`Locator ${locator} returned an invalid response`);
});
it("should successfully resolve an async locator", () => {
registerLocator("asyncLocator", () => Promise.resolve("//button"));
expect(resolveLocator("asyncLocator")).resolves.toBe("//button");
});
it("should fail to resolve an async locator", () => {
registerLocator("asyncFail", () => Promise.reject(false));
expect(resolveLocator("asyncFail")).rejects.toBeFalsy();
});
it("should pass options to the locator resolver", () => {
registerLocator("optionsLocator", (target, options) => (options.first));
const option = "test";
expect(resolveLocator("optionsLocator", "button", { first: option })).toEqual(option);
});
});
5 changes: 5 additions & 0 deletions packages/selenium-ide/src/__test__/plugin/manager.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import Manager from "../../plugin/manager";
import { canExecuteCommand } from "../../plugin/commandExecutor";
import { canResolveLocator } from "../../plugin/locatorResolver";

describe("plugin manager", () => {
it("should have a list of active plugins", () => {
Expand All @@ -30,12 +31,16 @@ describe("plugin manager", () => {
commands: [{
id: "aCommand",
name: "do something"
}],
locators: [{
id: "aLocator"
}]
};
expect(Manager.plugins.length).toBe(0);
Manager.registerPlugin(plugin);
expect(Manager.plugins.length).toBe(1);
expect(canExecuteCommand(plugin.commands[0].id)).toBeTruthy();
expect(canResolveLocator(plugin.locators[0].id)).toBeTruthy();
});
it("should register a plugin with no commands", () => {
const plugin = {
Expand Down
1 change: 1 addition & 0 deletions packages/selenium-ide/src/api/v1/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ router.post("/register", (req, res) => {
name: req.name,
version: req.version,
commands: req.commands,
locators: req.locators,
dependencies: req.dependencies
};
Manager.registerPlugin(plugin);
Expand Down
53 changes: 39 additions & 14 deletions packages/selenium-ide/src/neo/IO/SideeX/playback.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ import FatalError from "../../../errors/fatal";
import NoResponseError from "../../../errors/no-response";
import PlaybackState, { PlaybackStates } from "../../stores/view/PlaybackState";
import UiState from "../../stores/view/UiState";
import { Commands, TargetTypes } from "../../models/Command";
import { canExecuteCommand, executeCommand } from "../../../plugin/commandExecutor";
import { canResolveLocator, resolveLocator } from "../../../plugin/locatorResolver";
import ExtCommand, { isExtCommand } from "./ext-command";
import { xlateArgument } from "./formatCommand";

Expand Down Expand Up @@ -95,7 +97,7 @@ function executionLoop() {
.then(doAjaxWait)
.then(doDomWait)
.then(doDelay)
.then(doCommand)
.then(prepDoCommand)
.then(executionLoop);
}
}
Expand Down Expand Up @@ -226,10 +228,34 @@ function doDomWait(res, domTime, domCount = 0) {
});
}

function doCommand(res, implicitTime = Date.now(), implicitCount = 0) {
function prepDoCommand() {
if (!PlaybackState.isPlaying || PlaybackState.paused) return;
const { id, command, target, value } = PlaybackState.runningQueue[PlaybackState.currentPlayingIndex];

let parseTarget = Promise.resolve(target);
if (command === "open") {
parseTarget = Promise.resolve(new URL(target, baseUrl).href);
} else if (Commands.list.get(command).type === TargetTypes.LOCATOR) {
const breakLocator = /\s*([^\s]*)\s*=\s*(.*[^\s])\s*/;
const results = target.match(breakLocator);
if (canResolveLocator(results[1])) {
parseTarget = resolveLocator(results[1], results[2], {
commandId: id,
runId: PlaybackState.runId,
testId: PlaybackState.currentRunningTest.id,
frameId: extCommand.getCurrentPlayingFrameId(),
tabId: extCommand.currentPlayingTabId,
windowId: extCommand.currentPlayingWindowId
});
}
}

return parseTarget.then((parsed) => (
doCommand(id, command, { target, parsed }, value)
));
}

function doCommand(id, command, target, value, implicitTime = Date.now(), implicitCount = 0) {
let p = new Promise(function(resolve, reject) {
let count = 0;
let interval = setInterval(function() {
Expand All @@ -247,22 +273,21 @@ function doCommand(res, implicitTime = Date.now(), implicitCount = 0) {
}, 500);
});

const parsedTarget = command === "open" ? new URL(target, baseUrl).href : target;
return p.then(() => (
canExecuteCommand(command) ?
doPluginCommand(id, command, parsedTarget, value, implicitTime, implicitCount) :
doSeleniumCommand(id, command, parsedTarget, value, implicitTime, implicitCount)
doPluginCommand(id, command, target, value, implicitTime, implicitCount) :
doSeleniumCommand(id, command, target, value, implicitTime, implicitCount)
));
}

function doSeleniumCommand(id, command, parsedTarget, value, implicitTime, implicitCount) {
function doSeleniumCommand(id, command, target, value, implicitTime, implicitCount) {
return (command !== "type"
? extCommand.sendMessage(command, xlateArgument(parsedTarget), xlateArgument(value), isWindowMethodCommand(command))
: extCommand.doType(xlateArgument(parsedTarget), xlateArgument(value), isWindowMethodCommand(command))).then(function(result) {
? extCommand.sendMessage(command, xlateArgument(target.parsed), xlateArgument(value), isWindowMethodCommand(command))
: extCommand.doType(xlateArgument(target.parsed), xlateArgument(value), isWindowMethodCommand(command))).then(function(result) {
if (result.result !== "success") {
// implicit
if (isElementNotFound(result.result)) {
return doImplicitWait(result.result, id, parsedTarget, implicitTime, implicitCount);
return doImplicitWait(result.result, id, command, target, value, implicitTime, implicitCount);
} else {
PlaybackState.setCommandState(id, /^verify/.test(command) ? PlaybackStates.Failed : PlaybackStates.Fatal, result.result);
}
Expand All @@ -273,7 +298,7 @@ function doSeleniumCommand(id, command, parsedTarget, value, implicitTime, impli
}

function doPluginCommand(id, command, target, value, implicitTime, implicitCount) {
return executeCommand(command, target, value, {
return executeCommand(command, target.parsed, value, {
commandId: id,
runId: PlaybackState.runId,
testId: PlaybackState.currentRunningTest.id,
Expand All @@ -284,7 +309,7 @@ function doPluginCommand(id, command, target, value, implicitTime, implicitCount
PlaybackState.setCommandState(id, res.status ? res.status : PlaybackStates.Passed, res && res.message || undefined);
}).catch(err => {
if (isElementNotFound(err.message)) {
return doImplicitWait(err.message, id, target, implicitTime, implicitCount);
return doImplicitWait(err.message, id, command, target, value, implicitTime, implicitCount);
} else {
PlaybackState.setCommandState(id, (err instanceof FatalError || err instanceof NoResponseError) ? PlaybackStates.Fatal : PlaybackStates.Failed, err.message);
}
Expand All @@ -295,7 +320,7 @@ function isElementNotFound(error) {
return error.match(/Element[\s\S]*?not found/);
}

function doImplicitWait(error, commandId, target, implicitTime, implicitCount) {
function doImplicitWait(error, id, command, target, value, implicitTime, implicitCount) {
if (isElementNotFound(error)) {
if (implicitTime && (Date.now() - implicitTime > 30000)) {
reportError("Implicit Wait timed out after 30000ms");
Expand All @@ -306,8 +331,8 @@ function doImplicitWait(error, commandId, target, implicitTime, implicitCount) {
if (implicitCount == 1) {
implicitTime = Date.now();
}
PlaybackState.setCommandState(commandId, PlaybackStates.Pending, `Trying to find ${target}...`);
return doCommand(false, implicitTime, implicitCount);
PlaybackState.setCommandState(id, PlaybackStates.Pending, `Trying to find ${target.target}...`);
return doCommand(id, command, target, value, implicitTime, implicitCount);
}
}
}
Expand Down
64 changes: 64 additions & 0 deletions packages/selenium-ide/src/plugin/locatorResolver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

const locators = {};

function verifyXpath(locator, response) {
if (typeof response !== "string") {
throw new Error(`Locator ${locator} returned an invalid response`);
}
return response;
}

function isDefaultLocator(locator) {
return (locator === "id" ||
locator === "name" ||
locator === "link" ||
locator === "css" ||
locator === "xpath");
}

export function registerLocator(locator, func) {
if (typeof locator !== "string") {
throw new Error(`Expected to receive string instead received ${typeof locator}`);
} else if (isDefaultLocator(locator)) {
throw new Error("Overriding default locator strategies is disallowed");
} else if (typeof func !== "function") {
throw new Error(`Expected to receive function instead received ${typeof func}`);
} else if (locators[locator]) {
throw new Error(`A locator named ${locator} already exists`);
} else {
locators[locator] = func;
}
}

export function canResolveLocator(locator) {
return locators.hasOwnProperty(locator);
}

export function resolveLocator(locator, target, options) {
if (!locators[locator]) {
throw new Error(`The locator ${locator} is not registered with any plugin`);
} else {
const response = locators[locator](target, options);

if (response instanceof Promise) {
return response.then((r) => (verifyXpath(locator, r)));
}
return verifyXpath(locator, response);
}
}
Loading