Upgrade Selenium on Rails to r140

This commit is contained in:
Eric Allen 2009-12-14 11:51:36 -05:00
parent 156862200b
commit 40074c71ad
117 changed files with 16789 additions and 8867 deletions

View file

@ -1,69 +1,69 @@
/*
* Copyright 2004 ThoughtWorks, Inc
*
* Licensed 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.
*
*/
elementFindMatchingChildren = function(element, selector) {
var matches = [];
var childCount = element.childNodes.length;
for (var i=0; i<childCount; i++) {
var child = element.childNodes[i];
if (selector(child)) {
matches.push(child);
} else {
childMatches = elementFindMatchingChildren(child, selector);
matches.push(childMatches);
}
}
return matches.flatten();
}
ELEMENT_NODE_TYPE = 1;
elementFindFirstMatchingChild = function(element, selector) {
var childCount = element.childNodes.length;
for (var i=0; i<childCount; i++) {
var child = element.childNodes[i];
if (child.nodeType == ELEMENT_NODE_TYPE) {
if (selector(child)) {
return child;
}
result = elementFindFirstMatchingChild(child, selector);
if (result) {
return result;
}
}
}
return null;
}
elementFindFirstMatchingParent = function(element, selector) {
var current = element.parentNode;
while (current != null) {
if (selector(current)) {
break;
}
current = current.parentNode;
}
return current;
}
elementFindMatchingChildById = function(element, id) {
return elementFindFirstMatchingChild(element, function(element){return element.id==id} );
}
/*
* Copyright 2004 ThoughtWorks, Inc
*
* Licensed 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.
*
*/
elementFindMatchingChildren = function(element, selector) {
var matches = [];
var childCount = element.childNodes.length;
for (var i=0; i<childCount; i++) {
var child = element.childNodes[i];
if (selector(child)) {
matches.push(child);
} else {
childMatches = elementFindMatchingChildren(child, selector);
matches.push(childMatches);
}
}
return matches.flatten();
}
ELEMENT_NODE_TYPE = 1;
elementFindFirstMatchingChild = function(element, selector) {
var childCount = element.childNodes.length;
for (var i=0; i<childCount; i++) {
var child = element.childNodes[i];
if (child.nodeType == ELEMENT_NODE_TYPE) {
if (selector(child)) {
return child;
}
result = elementFindFirstMatchingChild(child, selector);
if (result) {
return result;
}
}
}
return null;
}
elementFindFirstMatchingParent = function(element, selector) {
var current = element.parentNode;
while (current != null) {
if (selector(current)) {
break;
}
current = current.parentNode;
}
return current;
}
elementFindMatchingChildById = function(element, id) {
return elementFindFirstMatchingChild(element, function(element){return element.id==id} );
}

View file

@ -31,7 +31,7 @@ function objectExtend(destination, source) {
return destination;
}
function $() {
function sel$() {
var results = [], element;
for (var i = 0; i < arguments.length; i++) {
element = arguments[i];
@ -42,7 +42,7 @@ function $() {
return results.length < 2 ? results[0] : results;
}
function $A(iterable) {
function sel$A(iterable) {
if (!iterable) return [];
if (iterable.toArray) {
return iterable.toArray();
@ -55,9 +55,9 @@ function $A(iterable) {
}
function fnBind() {
var args = $A(arguments), __method = args.shift(), object = args.shift();
var args = sel$A(arguments), __method = args.shift(), object = args.shift();
var retval = function() {
return __method.apply(object, args.concat($A(arguments)));
return __method.apply(object, args.concat(sel$A(arguments)));
}
retval.__method = __method;
return retval;
@ -121,6 +121,46 @@ String.prototype.startsWith = function(str) {
return this.indexOf(str) == 0;
};
/**
* Given a string literal that would appear in an XPath, puts it in quotes and
* returns it. Special consideration is given to literals who themselves
* contain quotes. It's possible for a concat() expression to be returned.
*/
String.prototype.quoteForXPath = function()
{
if (/\'/.test(this)) {
if (/\"/.test(this)) {
// concat scenario
var pieces = [];
var a = "'", b = '"', c;
for (var i = 0, j = 0; i < this.length;) {
if (this.charAt(i) == a) {
// encountered a quote that cannot be contained in current
// quote, so need to flip-flop quoting scheme
if (j < i) {
pieces.push(a + this.substring(j, i) + a);
j = i;
}
c = a;
a = b;
b = c;
}
else {
++i;
}
}
pieces.push(a + this.substring(j) + a);
return 'concat(' + pieces.join(', ') + ')';
}
else {
// quote with doubles
return '"' + this + '"';
}
}
// quote with singles
return "'" + this + "'";
};
// Returns the text in this element
function getText(element) {
var text = "";
@ -171,7 +211,7 @@ function getTextContent(element, preformatted) {
}
/**
* Convert all newlines to \m
* Convert all newlines to \n
*/
function normalizeNewlines(text)
{
@ -246,7 +286,7 @@ function getInputValue(inputElement) {
/* Fire an event in a browser-compatible manner */
function triggerEvent(element, eventType, canBubble, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown) {
canBubble = (typeof(canBubble) == undefined) ? true : canBubble;
if (element.fireEvent) {
if (element.fireEvent && element.ownerDocument && element.ownerDocument.createEventObject) { // IE
var evt = createEventObject(element, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown);
element.fireEvent('on' + eventType, evt);
}
@ -299,7 +339,7 @@ function createEventObject(element, controlKeyDown, altKeyDown, shiftKeyDown, me
function triggerKeyEvent(element, eventType, keySequence, canBubble, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown) {
var keycode = getKeyCodeFromKeySequence(keySequence);
canBubble = (typeof(canBubble) == undefined) ? true : canBubble;
if (element.fireEvent) {
if (element.fireEvent && element.ownerDocument && element.ownerDocument.createEventObject) { // IE
var keyEvent = createEventObject(element, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown);
keyEvent.keyCode = keycode;
element.fireEvent('on' + eventType, keyEvent);
@ -327,7 +367,7 @@ function triggerKeyEvent(element, eventType, keySequence, canBubble, controlKeyD
}
function removeLoadListener(element, command) {
LOG.info('Removing loadListenter for ' + element + ', ' + command);
LOG.debug('Removing loadListenter for ' + element + ', ' + command);
if (window.removeEventListener)
element.removeEventListener("load", command, true);
else if (window.detachEvent)
@ -335,7 +375,7 @@ function removeLoadListener(element, command) {
}
function addLoadListener(element, command) {
LOG.info('Adding loadListenter for ' + element + ', ' + command);
LOG.debug('Adding loadListenter for ' + element + ', ' + command);
var augmentedCommand = function() {
command.call(this, element);
}
@ -373,6 +413,25 @@ function getTagName(element) {
return tagName;
}
function selArrayToString(a) {
if (isArray(a)) {
// DGF copying the array, because the array-like object may be a non-modifiable nodelist
var retval = [];
for (var i = 0; i < a.length; i++) {
var item = a[i];
var replaced = new String(item).replace(/([,\\])/g, '\\$1');
retval[i] = replaced;
}
return retval;
}
return new String(a);
}
function isArray(x) {
return ((typeof x) == "object") && (x["length"] != null);
}
function absolutify(url, baseUrl) {
/** returns a relative url in its absolute form, given by baseUrl.
*
@ -499,9 +558,30 @@ function reassembleLocation(loc) {
}
function canonicalize(url) {
if(url == "about:blank")
{
return url;
}
var tempLink = window.document.createElement("link");
tempLink.href = url; // this will canonicalize the href
return tempLink.href;
tempLink.href = url; // this will canonicalize the href on most browsers
var loc = parseUrl(tempLink.href)
if (!/\/\.\.\//.test(loc.pathname)) {
return tempLink.href;
}
// didn't work... let's try it the hard way
var originalParts = loc.pathname.split("/");
var newParts = [];
newParts.push(originalParts.shift());
for (var i = 0; i < originalParts.length; i++) {
var part = originalParts[i];
if (".." == part) {
newParts.pop();
continue;
}
newParts.push(part);
}
loc.pathname = newParts.join("/");
return reassembleLocation(loc);
}
function extractExceptionMessage(ex) {
@ -590,6 +670,20 @@ PatternMatcher.strategies = {
return this.regexp.test(actual);
};
},
regexpi: function(regexpString) {
this.regexp = new RegExp(regexpString, "i");
this.matches = function(actual) {
return this.regexp.test(actual);
};
},
regexi: function(regexpString) {
this.regexp = new RegExp(regexpString, "i");
this.matches = function(actual) {
return this.regexp.test(actual);
};
},
/**
* "globContains" (aka "wildmat") patterns, e.g. "glob:one,two,*",
@ -638,52 +732,54 @@ PatternMatcher.regexpFromGlob = function(glob) {
return "^" + PatternMatcher.convertGlobMetaCharsToRegexpMetaChars(glob) + "$";
};
var Assert = {
if (!this["Assert"]) Assert = {};
fail: function(message) {
throw new AssertionFailedError(message);
},
Assert.fail = function(message) {
throw new AssertionFailedError(message);
};
/*
* Assert.equals(comment?, expected, actual)
*/
equals: function() {
var args = new AssertionArguments(arguments);
if (args.expected === args.actual) {
return;
}
Assert.fail(args.comment +
"Expected '" + args.expected +
"' but was '" + args.actual + "'");
},
Assert.equals = function() {
var args = new AssertionArguments(arguments);
if (args.expected === args.actual) {
return;
}
Assert.fail(args.comment +
"Expected '" + args.expected +
"' but was '" + args.actual + "'");
};
Assert.assertEquals = Assert.equals;
/*
* Assert.matches(comment?, pattern, actual)
*/
matches: function() {
var args = new AssertionArguments(arguments);
if (PatternMatcher.matches(args.expected, args.actual)) {
return;
}
Assert.fail(args.comment +
"Actual value '" + args.actual +
"' did not match '" + args.expected + "'");
},
Assert.matches = function() {
var args = new AssertionArguments(arguments);
if (PatternMatcher.matches(args.expected, args.actual)) {
return;
}
Assert.fail(args.comment +
"Actual value '" + args.actual +
"' did not match '" + args.expected + "'");
}
/*
* Assert.notMtches(comment?, pattern, actual)
*/
notMatches: function() {
var args = new AssertionArguments(arguments);
if (!PatternMatcher.matches(args.expected, args.actual)) {
return;
}
Assert.fail(args.comment +
"Actual value '" + args.actual +
"' did match '" + args.expected + "'");
Assert.notMatches = function() {
var args = new AssertionArguments(arguments);
if (!PatternMatcher.matches(args.expected, args.actual)) {
return;
}
Assert.fail(args.comment +
"Actual value '" + args.actual +
"' did match '" + args.expected + "'");
}
};
// Preprocess the arguments to allow for an optional comment.
function AssertionArguments(args) {
@ -707,6 +803,17 @@ function AssertionFailedError(message) {
function SeleniumError(message) {
var error = new Error(message);
if (typeof(arguments.caller) != 'undefined') { // IE, not ECMA
var result = '';
for (var a = arguments.caller; a != null; a = a.caller) {
result += '> ' + a.callee.toString() + '\n';
if (a.caller == a) {
result += '*';
break;
}
}
error.stack = result;
}
error.isSeleniumError = true;
return error;
}
@ -749,6 +856,11 @@ function openSeparateApplicationWindow(url, suppressMozillaWarning) {
window.moveTo(window.screenX, 0);
var appWindow = window.open(url + '?start=true', 'main');
if (appWindow == null) {
var errorMessage = "Couldn't open app window; is the pop-up blocker enabled?"
LOG.error(errorMessage);
throw new Error("Couldn't open app window; is the pop-up blocker enabled?");
}
try {
var windowHeight = 500;
if (window.outerHeight) {
@ -840,3 +952,665 @@ function safeScrollIntoView(element) {
// TODO: work out how to scroll browsers that don't support
// scrollIntoView (like Konqueror)
}
/**
* Returns the absolute time represented as an offset of the current time.
* Throws a SeleniumException if timeout is invalid.
*
* @param timeout the number of milliseconds from "now" whose absolute time
* to return
*/
function getTimeoutTime(timeout) {
var now = new Date().getTime();
var timeoutLength = parseInt(timeout);
if (isNaN(timeoutLength)) {
throw new SeleniumError("Timeout is not a number: '" + timeout + "'");
}
return now + timeoutLength;
}
/**
* Returns true iff the current environment is the IDE.
*/
function is_IDE()
{
return (typeof(SeleniumIDE) != 'undefined');
}
/**
* Logs a message if the Logger exists, and does nothing if it doesn't exist.
*
* @param level the level to log at
* @param msg the message to log
*/
function safe_log(level, msg)
{
try {
LOG[level](msg);
}
catch (e) {
// couldn't log!
}
}
/**
* Displays a warning message to the user appropriate to the context under
* which the issue is encountered. This is primarily used to avoid popping up
* alert dialogs that might pause an automated test suite.
*
* @param msg the warning message to display
*/
function safe_alert(msg)
{
if (is_IDE()) {
alert(msg);
}
}
/**
* Returns true iff the given element represents a link with a javascript
* href attribute, and does not have an onclick attribute defined.
*
* @param element the element to test
*/
function hasJavascriptHref(element) {
if (getTagName(element) != 'a') {
return false;
}
if (element.onclick) {
return false;
}
if (! element.href) {
return false;
}
if (! /\s*javascript:/i.test(element.href)) {
return false;
}
return true;
}
/**
* Returns the given element, or its nearest ancestor, that satisfies
* hasJavascriptHref(). Returns null if none is found.
*
* @param element the element whose ancestors to test
*/
function getAncestorOrSelfWithJavascriptHref(element) {
if (hasJavascriptHref(element)) {
return element;
}
if (element.parentNode == null) {
return null;
}
return getAncestorOrSelfWithJavascriptHref(element.parentNode);
}
//******************************************************************************
// Locator evaluation support
/**
* Parses a Selenium locator, returning its type and the unprefixed locator
* string as an object.
*
* @param locator the locator to parse
*/
function parse_locator(locator)
{
var result = locator.match(/^([A-Za-z]+)=(.+)/);
if (result) {
return { type: result[1].toLowerCase(), string: result[2] };
}
return { type: 'implicit', string: locator };
}
/**
* Evaluates an xpath on a document, and returns a list containing nodes in the
* resulting nodeset. The browserbot xpath methods are now backed by this
* function. A context node may optionally be provided, and the xpath will be
* evaluated from that context.
*
* @param xpath the xpath to evaluate
* @param inDocument the document in which to evaluate the xpath.
* @param opts (optional) An object containing various flags that can
* modify how the xpath is evaluated. Here's a listing of
* the meaningful keys:
*
* contextNode:
* the context node from which to evaluate the xpath. If
* unspecified, the context will be the root document
* element.
*
* namespaceResolver:
* the namespace resolver function. Defaults to null.
*
* xpathLibrary:
* the javascript library to use for XPath. "ajaxslt" is
* the default. "javascript-xpath" is newer and faster,
* but needs more testing.
*
* allowNativeXpath:
* whether to allow native evaluate(). Defaults to true.
*
* ignoreAttributesWithoutValue:
* whether it's ok to ignore attributes without value
* when evaluating the xpath. This can greatly improve
* performance in IE; however, if your xpaths depend on
* such attributes, you can't ignore them! Defaults to
* true.
*
* returnOnFirstMatch:
* whether to optimize the XPath evaluation to only
* return the first match. The match, if any, will still
* be returned in a list. Defaults to false.
*/
function eval_xpath(xpath, inDocument, opts)
{
if (!opts) {
var opts = {};
}
var contextNode = opts.contextNode
? opts.contextNode : inDocument;
var namespaceResolver = opts.namespaceResolver
? opts.namespaceResolver : null;
var xpathLibrary = opts.xpathLibrary
? opts.xpathLibrary : null;
var allowNativeXpath = (opts.allowNativeXpath != undefined)
? opts.allowNativeXpath : true;
var ignoreAttributesWithoutValue = (opts.ignoreAttributesWithoutValue != undefined)
? opts.ignoreAttributesWithoutValue : true;
var returnOnFirstMatch = (opts.returnOnFirstMatch != undefined)
? opts.returnOnFirstMatch : false;
// Trim any trailing "/": not valid xpath, and remains from attribute
// locator.
if (xpath.charAt(xpath.length - 1) == '/') {
xpath = xpath.slice(0, -1);
}
// HUGE hack - remove namespace from xpath for IE
if (browserVersion && browserVersion.isIE) {
xpath = xpath.replace(/x:/g, '')
}
var nativeXpathAvailable = inDocument.evaluate;
var useNativeXpath = allowNativeXpath && nativeXpathAvailable;
var useDocumentEvaluate = useNativeXpath;
// When using the new and faster javascript-xpath library,
// we'll use the TestRunner's document object, not the App-Under-Test's document.
// The new library only modifies the TestRunner document with the new
// functionality.
if (xpathLibrary == 'javascript-xpath' && !useNativeXpath) {
documentForXpath = document;
useDocumentEvaluate = true;
} else {
documentForXpath = inDocument;
}
var results = [];
// this is either native xpath or javascript-xpath via TestRunner.evaluate
if (useDocumentEvaluate) {
try {
// Regarding use of the second argument to document.evaluate():
// http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/a59ce20639c74ba1/a9d9f53e88e5ebb5
var xpathResult = documentForXpath
.evaluate((contextNode == inDocument ? xpath : '.' + xpath),
contextNode, namespaceResolver, 0, null);
}
catch (e) {
throw new SeleniumError("Invalid xpath: " + extractExceptionMessage(e));
}
finally{
if (xpathResult == null) {
// If the result is null, we should still throw an Error.
throw new SeleniumError("Invalid xpath: " + xpath);
}
}
var result = xpathResult.iterateNext();
while (result) {
results.push(result);
result = xpathResult.iterateNext();
}
return results;
}
// If not, fall back to slower JavaScript implementation
// DGF set xpathdebug = true (using getEval, if you like) to turn on JS XPath debugging
//xpathdebug = true;
var context;
if (contextNode == inDocument) {
context = new ExprContext(inDocument);
}
else {
// provide false values to get the default constructor values
context = new ExprContext(contextNode, false, false,
contextNode.parentNode);
}
context.setCaseInsensitive(true);
context.setIgnoreAttributesWithoutValue(ignoreAttributesWithoutValue);
context.setReturnOnFirstMatch(returnOnFirstMatch);
var xpathObj;
try {
xpathObj = xpathParse(xpath);
}
catch (e) {
throw new SeleniumError("Invalid xpath: " + extractExceptionMessage(e));
}
var xpathResult = xpathObj.evaluate(context);
if (xpathResult && xpathResult.value) {
for (var i = 0; i < xpathResult.value.length; ++i) {
results.push(xpathResult.value[i]);
}
}
return results;
}
/**
* Returns the full resultset of a CSS selector evaluation.
*/
function eval_css(locator, inDocument)
{
return cssQuery(locator, inDocument);
}
/**
* This function duplicates part of BrowserBot.findElement() to open up locator
* evaluation on arbitrary documents. It returns a plain old array of located
* elements found by using a Selenium locator.
*
* Multiple results may be generated for xpath and CSS locators. Even though a
* list could potentially be generated for other locator types, such as link,
* we don't try for them, because they aren't very expressive location
* strategies; if you want a list, use xpath or CSS. Furthermore, strategies
* for these locators have been optimized to only return the first result. For
* these types of locators, performance is more important than ideal behavior.
*
* @param locator a locator string
* @param inDocument the document in which to apply the locator
* @param opt_contextNode the context within which to evaluate the locator
*
* @return a list of result elements
*/
function eval_locator(locator, inDocument, opt_contextNode)
{
locator = parse_locator(locator);
var pageBot;
if (typeof(selenium) != 'undefined' && selenium != undefined) {
if (typeof(editor) == 'undefined' || editor.state == 'playing') {
safe_log('info', 'Trying [' + locator.type + ']: '
+ locator.string);
}
pageBot = selenium.browserbot;
}
else {
if (!UI_GLOBAL.mozillaBrowserBot) {
// create a browser bot to evaluate the locator. Hand it the IDE
// window as a dummy window, and cache it for future use.
UI_GLOBAL.mozillaBrowserBot = new MozillaBrowserBot(window)
}
pageBot = UI_GLOBAL.mozillaBrowserBot;
}
var results = [];
if (locator.type == 'xpath' || (locator.string.charAt(0) == '/' &&
locator.type == 'implicit')) {
results = eval_xpath(locator.string, inDocument,
{ contextNode: opt_contextNode });
}
else if (locator.type == 'css') {
results = eval_css(locator.string, inDocument);
}
else {
var element = pageBot
.findElementBy(locator.type, locator.string, inDocument);
if (element != null) {
results.push(element);
}
}
return results;
}
//******************************************************************************
// UI-Element
/**
* Escapes the special regular expression characters in a string intended to be
* used as a regular expression.
*
* Based on: http://simonwillison.net/2006/Jan/20/escape/
*/
RegExp.escape = (function() {
var specials = [
'/', '.', '*', '+', '?', '|', '^', '$',
'(', ')', '[', ']', '{', '}', '\\'
];
var sRE = new RegExp(
'(\\' + specials.join('|\\') + ')', 'g'
);
return function(text) {
return text.replace(sRE, '\\$1');
}
})();
/**
* Returns true if two arrays are identical, and false otherwise.
*
* @param a1 the first array, may only contain simple values (strings or
* numbers)
* @param a2 the second array, same restricts on data as for a1
* @return true if the arrays are equivalent, false otherwise.
*/
function are_equal(a1, a2)
{
if (typeof(a1) != typeof(a2))
return false;
switch(typeof(a1)) {
case 'object':
// arrays
if (a1.length) {
if (a1.length != a2.length)
return false;
for (var i = 0; i < a1.length; ++i) {
if (!are_equal(a1[i], a2[i]))
return false
}
}
// associative arrays
else {
var keys = {};
for (var key in a1) {
keys[key] = true;
}
for (var key in a2) {
keys[key] = true;
}
for (var key in keys) {
if (!are_equal(a1[key], a2[key]))
return false;
}
}
return true;
default:
return a1 == a2;
}
}
/**
* Create a clone of an object and return it. This is a deep copy of everything
* but functions, whose references are copied. You shouldn't expect a deep copy
* of functions anyway.
*
* @param orig the original object to copy
* @return a deep copy of the original object. Any functions attached,
* however, will have their references copied only.
*/
function clone(orig) {
var copy;
switch(typeof(orig)) {
case 'object':
copy = (orig.length) ? [] : {};
for (var attr in orig) {
copy[attr] = clone(orig[attr]);
}
break;
default:
copy = orig;
break;
}
return copy;
}
/**
* Emulates php's print_r() functionality. Returns a nicely formatted string
* representation of an object. Very useful for debugging.
*
* @param object the object to dump
* @param maxDepth the maximum depth to recurse into the object. Ellipses will
* be shown for objects whose depth exceeds the maximum.
* @param indent the string to use for indenting progressively deeper levels
* of the dump.
* @return a string representing a dump of the object
*/
function print_r(object, maxDepth, indent)
{
var parentIndent, attr, str = "";
if (arguments.length == 1) {
var maxDepth = Number.MAX_VALUE;
} else {
maxDepth--;
}
if (arguments.length < 3) {
parentIndent = ''
var indent = ' ';
} else {
parentIndent = indent;
indent += ' ';
}
switch(typeof(object)) {
case 'object':
if (object.length != undefined) {
if (object.length == 0) {
str += "Array ()\r\n";
}
else {
str += "Array (\r\n";
for (var i = 0; i < object.length; ++i) {
str += indent + '[' + i + '] => ';
if (maxDepth == 0)
str += "...\r\n";
else
str += print_r(object[i], maxDepth, indent);
}
str += parentIndent + ")\r\n";
}
}
else {
str += "Object (\r\n";
for (attr in object) {
str += indent + "[" + attr + "] => ";
if (maxDepth == 0)
str += "...\r\n";
else
str += print_r(object[attr], maxDepth, indent);
}
str += parentIndent + ")\r\n";
}
break;
case 'boolean':
str += (object ? 'true' : 'false') + "\r\n";
break;
case 'function':
str += "Function\r\n";
break;
default:
str += object + "\r\n";
break;
}
return str;
}
/**
* Return an array containing all properties of an object. Perl-style.
*
* @param object the object whose keys to return
* @return array of object keys, as strings
*/
function keys(object)
{
var keys = [];
for (var k in object) {
keys.push(k);
}
return keys;
}
/**
* Emulates python's range() built-in. Returns an array of integers, counting
* up (or down) from start to end. Note that the range returned is up to, but
* NOT INCLUDING, end.
*.
* @param start integer from which to start counting. If the end parameter is
* not provided, this value is considered the end and start will
* be zero.
* @param end integer to which to count. If omitted, the function will count
* up from zero to the value of the start parameter. Note that
* the array returned will count up to but will not include this
* value.
* @return an array of consecutive integers.
*/
function range(start, end)
{
if (arguments.length == 1) {
var end = start;
start = 0;
}
var r = [];
if (start < end) {
while (start != end)
r.push(start++);
}
else {
while (start != end)
r.push(start--);
}
return r;
}
/**
* Parses a python-style keyword arguments string and returns the pairs in a
* new object.
*
* @param kwargs a string representing a set of keyword arguments. It should
* look like <tt>keyword1=value1, keyword2=value2, ...</tt>
* @return an object mapping strings to strings
*/
function parse_kwargs(kwargs)
{
var args = new Object();
var pairs = kwargs.split(/,/);
for (var i = 0; i < pairs.length;) {
if (i > 0 && pairs[i].indexOf('=') == -1) {
// the value string contained a comma. Glue the parts back together.
pairs[i-1] += ',' + pairs.splice(i, 1)[0];
}
else {
++i;
}
}
for (var i = 0; i < pairs.length; ++i) {
var splits = pairs[i].split(/=/);
if (splits.length == 1) {
continue;
}
var key = splits.shift();
var value = splits.join('=');
args[key.trim()] = value.trim();
}
return args;
}
/**
* Creates a python-style keyword arguments string from an object.
*
* @param args an associative array mapping strings to strings
* @param sortedKeys (optional) a list of keys of the args parameter that
* specifies the order in which the arguments will appear in
* the returned kwargs string
*
* @return a kwarg string representation of args
*/
function to_kwargs(args, sortedKeys)
{
var s = '';
if (!sortedKeys) {
var sortedKeys = keys(args).sort();
}
for (var i = 0; i < sortedKeys.length; ++i) {
var k = sortedKeys[i];
if (args[k] != undefined) {
if (s) {
s += ', ';
}
s += k + '=' + args[k];
}
}
return s;
}
/**
* Returns true if a node is an ancestor node of a target node, and false
* otherwise.
*
* @param node the node being compared to the target node
* @param target the target node
* @return true if node is an ancestor node of target, false otherwise.
*/
function is_ancestor(node, target)
{
while (target.parentNode) {
target = target.parentNode;
if (node == target)
return true;
}
return false;
}
//******************************************************************************
// parseUri 1.2.1
// MIT License
/*
Copyright (c) 2007 Steven Levithan <stevenlevithan.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
*/
function parseUri (str) {
var o = parseUri.options,
m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
uri = {},
i = 14;
while (i--) uri[o.key[i]] = m[i] || "";
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) uri[o.q.name][$1] = $2;
});
return uri;
};
parseUri.options = {
strictMode: false,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};

View file

@ -1,79 +1,72 @@
<script language="JavaScript">
if (window["selenium_has_been_loaded_into_this_window"]==null)
{
__SELENIUM_JS__
// Some background on the code below: broadly speaking, where we are relative to other windows
// when running in proxy injection mode depends on whether we are in a frame set file or not.
//
// In regular HTML files, the selenium JavaScript is injected into an iframe called "selenium"
// in order to reduce its impact on the JavaScript environment (through namespace pollution,
// etc.). So in regular HTML files, we need to look at the parent of the current window when we want
// a handle to, e.g., the application window.
//
// In frame set files, we can't use an iframe, so we put the JavaScript in the head element and share
// the window with the frame set. So in this case, we need to look at the current window, not the
// parent when looking for, e.g., the application window. (TODO: Perhaps I should have just
// assigned a regular frame for selenium?)
//
BrowserBot.prototype.getContentWindow = function() {
if (window["seleniumInSameWindow"] != null) return window;
return window.parent;
};
BrowserBot.prototype.getTargetWindow = function(windowName) {
if (window["seleniumInSameWindow"] != null) return window;
return window.parent;
};
BrowserBot.prototype.getCurrentWindow = function() {
if (window["seleniumInSameWindow"] != null) return window;
return window.parent;
};
LOG.openLogWindow = function(message, className) {
// disable for now
};
BrowserBot.prototype.relayToRC = function(name) {
var object = eval(name);
var s = 'state:' + serializeObject(name, object) + "\n";
sendToRC(s,"state=true");
}
BrowserBot.prototype.relayBotToRC = function(s) {
this.relayToRC("selenium." + s);
}
function selenium_frameRunTest(oldOnLoadRoutine) {
if (oldOnLoadRoutine) {
eval(oldOnLoadRoutine);
}
runSeleniumTest();
}
function seleniumOnLoad() {
injectedSessionId = @SESSION_ID@;
window["selenium_has_been_loaded_into_this_window"] = true;
runSeleniumTest();
}
function seleniumOnUnload() {
sendToRC("OK"); // just in case some poor PI server thread is waiting for a response
}
if (window.addEventListener) {
window.addEventListener("load", seleniumOnLoad, false); // firefox
window.addEventListener("unload", seleniumOnUnload, false); // firefox
} else if (window.attachEvent){
window.attachEvent("onload", seleniumOnLoad); // IE
window.attachEvent("onunload", seleniumOnUnload); // IE
}
else {
throw "causing a JavaScript error to tell the world that I did not arrange to be run on load";
}
injectedSessionId = @SESSION_ID@;
}
</script>
<script language="JavaScript">
if (window["selenium_has_been_loaded_into_this_window"]==null)
{
__SELENIUM_JS__
// Some background on the code below: broadly speaking, where we are relative to other windows
// when running in proxy injection mode depends on whether we are in a frame set file or not.
//
// In regular HTML files, the selenium JavaScript is injected into an iframe called "selenium"
// in order to reduce its impact on the JavaScript environment (through namespace pollution,
// etc.). So in regular HTML files, we need to look at the parent of the current window when we want
// a handle to, e.g., the application window.
//
// In frame set files, we can't use an iframe, so we put the JavaScript in the head element and share
// the window with the frame set. So in this case, we need to look at the current window, not the
// parent when looking for, e.g., the application window. (TODO: Perhaps I should have just
// assigned a regular frame for selenium?)
//
BrowserBot.prototype.getContentWindow = function() {
return window;
};
BrowserBot.prototype.getTargetWindow = function(windowName) {
return window;
};
BrowserBot.prototype.getCurrentWindow = function() {
return window;
};
LOG.openLogWindow = function(message, className) {
// disable for now
};
BrowserBot.prototype.relayToRC = function(name) {
var object = eval(name);
var s = 'state:' + serializeObject(name, object) + "\n";
sendToRC(s,"state=true");
}
function selenium_frameRunTest(oldOnLoadRoutine) {
if (oldOnLoadRoutine) {
eval(oldOnLoadRoutine);
}
runSeleniumTest();
}
function seleniumOnLoad() {
injectedSessionId = "@SESSION_ID@";
window["selenium_has_been_loaded_into_this_window"] = true;
runSeleniumTest();
}
function seleniumOnUnload() {
sendToRC("Current window or frame is closed!", "closing=true");
}
if (window.addEventListener) {
window.addEventListener("load", seleniumOnLoad, false); // firefox
window.addEventListener("unload", seleniumOnUnload, false); // firefox
} else if (window.attachEvent){
window.attachEvent("onload", seleniumOnLoad); // IE
window.attachEvent("onunload", seleniumOnUnload); // IE
}
else {
throw "causing a JavaScript error to tell the world that I did not arrange to be run on load";
}
injectedSessionId = "@SESSION_ID@";
proxyInjectionMode = true;
}
</script>

View file

@ -1,7 +0,0 @@
<script language="JavaScript">
// Ideally I would avoid polluting the namespace by enclosing this snippet with
// curly braces, but I want to make it easy to look at what URL I used for anyone
// who is interested in looking into http://jira.openqa.org/browse/SRC-101:
var _sel_url_ = "http://" + location.host + "/selenium-server/core/scripts/injection.html";
document.write('<iframe name="selenium" width=0 height=0 id="selenium" src="' + _sel_url_ + '"></iframe>');
</script>

View file

@ -1,70 +0,0 @@
/*
This is an experiment in using the Narcissus JavaScript engine
to allow Selenium scripts to be written in plain JavaScript.
The 'jsparse' function will compile each high level block into a Selenium table script.
TODO:
1) Test! (More browsers, more sample scripts)
2) Stepping and walking lower levels of the parse tree
3) Calling Selenium commands directly from JavaScript
4) Do we want comments to appear in the TestRunner?
5) Fix context so variables don't have to be global
For now, variables defined with "var" won't be found
if used later on in a script.
6) Fix formatting
*/
function jsparse() {
var script = document.getElementById('sejs')
var fname = 'javascript script';
parse_result = parse(script.text, fname, 0);
var x2 = new ExecutionContext(GLOBAL_CODE);
ExecutionContext.current = x2;
var new_test_source = '';
var new_line = '';
for (i=0;i<parse_result.$length;i++){
var the_start = parse_result[i].start;
var the_end;
if ( i == (parse_result.$length-1)) {
the_end = parse_result.tokenizer.source.length;
} else {
the_end = parse_result[i+1].start;
}
var script_fragment = parse_result.tokenizer.source.slice(the_start,the_end)
new_line = '<tr><td style="display:none;" class="js">getEval</td>' +
'<td style="display:none;">currentTest.doNextCommand()</td>' +
'<td style="white-space: pre;">' + script_fragment + '</td>' +
'<td></td></tr>\n';
new_test_source += new_line;
//eval(script_fragment);
};
execute(parse_result,x2)
// Create HTML Table
body = document.body
body.innerHTML += "<table class='selenium' id='se-js-table'>"+
"<tbody>" +
"<tr><td>// " + document.title + "</td></tr>" +
new_test_source +
"</tbody" +
"</table>";
//body.innerHTML = "<pre>" + parse_result + "</pre>"
}

View file

@ -1,175 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Narcissus JavaScript engine.
*
* The Initial Developer of the Original Code is
* Brendan Eich <brendan@mozilla.org>.
* Portions created by the Initial Developer are Copyright (C) 2004
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* Narcissus - JS implemented in JS.
*
* Well-known constants and lookup tables. Many consts are generated from the
* tokens table via eval to minimize redundancy, so consumers must be compiled
* separately to take advantage of the simple switch-case constant propagation
* done by SpiderMonkey.
*/
// jrh
//module('JS.Defs');
GLOBAL = this;
var tokens = [
// End of source.
"END",
// Operators and punctuators. Some pair-wise order matters, e.g. (+, -)
// and (UNARY_PLUS, UNARY_MINUS).
"\n", ";",
",",
"=",
"?", ":", "CONDITIONAL",
"||",
"&&",
"|",
"^",
"&",
"==", "!=", "===", "!==",
"<", "<=", ">=", ">",
"<<", ">>", ">>>",
"+", "-",
"*", "/", "%",
"!", "~", "UNARY_PLUS", "UNARY_MINUS",
"++", "--",
".",
"[", "]",
"{", "}",
"(", ")",
// Nonterminal tree node type codes.
"SCRIPT", "BLOCK", "LABEL", "FOR_IN", "CALL", "NEW_WITH_ARGS", "INDEX",
"ARRAY_INIT", "OBJECT_INIT", "PROPERTY_INIT", "GETTER", "SETTER",
"GROUP", "LIST",
// Terminals.
"IDENTIFIER", "NUMBER", "STRING", "REGEXP",
// Keywords.
"break",
"case", "catch", "const", "continue",
"debugger", "default", "delete", "do",
"else", "enum",
"false", "finally", "for", "function",
"if", "in", "instanceof",
"new", "null",
"return",
"switch",
"this", "throw", "true", "try", "typeof",
"var", "void",
"while", "with",
// Extensions
"require", "bless", "mixin", "import"
];
// Operator and punctuator mapping from token to tree node type name.
// NB: superstring tokens (e.g., ++) must come before their substring token
// counterparts (+ in the example), so that the opRegExp regular expression
// synthesized from this list makes the longest possible match.
var opTypeNames = {
'\n': "NEWLINE",
';': "SEMICOLON",
',': "COMMA",
'?': "HOOK",
':': "COLON",
'||': "OR",
'&&': "AND",
'|': "BITWISE_OR",
'^': "BITWISE_XOR",
'&': "BITWISE_AND",
'===': "STRICT_EQ",
'==': "EQ",
'=': "ASSIGN",
'!==': "STRICT_NE",
'!=': "NE",
'<<': "LSH",
'<=': "LE",
'<': "LT",
'>>>': "URSH",
'>>': "RSH",
'>=': "GE",
'>': "GT",
'++': "INCREMENT",
'--': "DECREMENT",
'+': "PLUS",
'-': "MINUS",
'*': "MUL",
'/': "DIV",
'%': "MOD",
'!': "NOT",
'~': "BITWISE_NOT",
'.': "DOT",
'[': "LEFT_BRACKET",
']': "RIGHT_BRACKET",
'{': "LEFT_CURLY",
'}': "RIGHT_CURLY",
'(': "LEFT_PAREN",
')': "RIGHT_PAREN"
};
// Hash of keyword identifier to tokens index. NB: we must null __proto__ to
// avoid toString, etc. namespace pollution.
var keywords = {__proto__: null};
// Define const END, etc., based on the token names. Also map name to index.
var consts = " ";
for (var i = 0, j = tokens.length; i < j; i++) {
if (i > 0)
consts += "; ";
var t = tokens[i];
if (/^[a-z]/.test(t)) {
consts += t.toUpperCase();
keywords[t] = i;
} else {
consts += (/^\W/.test(t) ? opTypeNames[t] : t);
}
consts += " = " + i;
tokens[t] = i;
}
eval(consts + ";");
// Map assignment operators to their indexes in the tokens array.
var assignOps = ['|', '^', '&', '<<', '>>', '>>>', '+', '-', '*', '/', '%'];
for (i = 0, j = assignOps.length; i < j; i++) {
t = assignOps[i];
assignOps[t] = tokens[t];
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,63 +0,0 @@
/*
This is an experiment in creating a "selenese" parser that drastically
cuts down on the line noise associated with writing tests in HTML.
The 'parse' function will accept the follow sample commands.
test-cases:
//comment
command "param"
command "param" // comment
command "param" "param2"
command "param" "param2" // this is a comment
TODO:
1) Deal with multiline parameters
2) Escape quotes properly
3) Determine whether this should/will become the "preferred" syntax
for delivered Selenium self-test scripts
*/
function separse(doc) {
// Get object
script = doc.getElementById('testcase')
// Split into lines
lines = script.text.split('\n');
var command_pattern = / *(\w+) *"([^"]*)" *(?:"([^"]*)"){0,1}(?: *(\/\/ *.+))*/i;
var comment_pattern = /^ *(\/\/ *.+)/
// Regex each line into selenium command and convert into table row.
// eg. "<command> <quote> <quote> <comment>"
var new_test_source = '';
var new_line = '';
for (var x=0; x < lines.length; x++) {
result = lines[x].match(command_pattern);
if (result != null) {
new_line = "<tr><td>" + (result[1] || '&nbsp;') + "</td>" +
"<td>" + (result[2] || '&nbsp;') + "</td>" +
"<td>" + (result[3] || '&nbsp;') + "</td>" +
"<td>" + (result[4] || '&nbsp;') + "</td></tr>\n";
new_test_source += new_line;
}
result = lines[x].match(comment_pattern);
if (result != null) {
new_line = '<tr><td rowspan="1" colspan="4">' +
(result[1] || '&nbsp;') +
'</td></tr>';
new_test_source += new_line;
}
}
// Create HTML Table
body = doc.body
body.innerHTML += "<table class='selenium' id='testtable'>"+
new_test_source +
"</table>";
}

File diff suppressed because it is too large Load diff

View file

@ -24,6 +24,14 @@
var BrowserVersion = function() {
this.name = navigator.appName;
if (navigator.userAgent.indexOf('Mac OS X') != -1) {
this.isOSX = true;
}
if (navigator.userAgent.indexOf('Windows NT 6') != -1) {
this.isVista = true;
}
if (window.opera != null) {
this.browser = BrowserVersion.OPERA;
this.isOpera = true;
@ -85,9 +93,12 @@ var BrowserVersion = function() {
self.isHTA = false;
}
}
if (navigator.appVersion.match(/MSIE 6.0/)) {
this.isIE6 = true;
}
if ("0" == navigator.appMinorVersion) {
this.preSV1 = true;
if (navigator.appVersion.match(/MSIE 6.0/)) {
if (this.isIE6) {
this.appearsToBeBrokenInitialIE6 = true;
}
}

View file

@ -136,6 +136,7 @@ objectExtend(CommandHandlerFactory.prototype, {
// is true when the value returned by the accessor matches the specified value.
return function(target, value) {
var accessorResult = accessBlock(target);
accessorResult = selArrayToString(accessorResult);
if (PatternMatcher.matches(value, accessorResult)) {
return new PredicateResult(true, "Actual value '" + accessorResult + "' did match '" + value + "'");
} else {
@ -150,6 +151,7 @@ objectExtend(CommandHandlerFactory.prototype, {
// is true when the value returned by the accessor matches the specified value.
return function(value) {
var accessorResult = accessBlock();
accessorResult = selArrayToString(accessorResult);
if (PatternMatcher.matches(value, accessorResult)) {
return new PredicateResult(true, "Actual value '" + accessorResult + "' did match '" + value + "'");
} else {

View file

@ -79,7 +79,7 @@ TestLoop.prototype = {
this.continueTestWhenConditionIsTrue();
} catch (e) {
if (!this._handleCommandError(e)) {
this._testComplete();
this.testComplete();
} else {
this.continueTest();
}
@ -119,10 +119,8 @@ TestLoop.prototype = {
_handleCommandError : function(e) {
if (!e.isSeleniumError) {
LOG.exception(e);
var msg = "Selenium failure. Please report to selenium-dev@openqa.org, with error details from the log window.";
if (e.message) {
msg += " The error message is: " + e.message;
}
var msg = "Command execution failure. Please search the forum at http://clearspace.openqa.org for error details from the log window.";
msg += " The error message is: " + extractExceptionMessage(e);
return this.commandError(msg);
} else {
LOG.error(e.message);

View file

@ -19,11 +19,24 @@ var Logger = function() {
}
Logger.prototype = {
logLevels: {
debug: 0,
info: 1,
warn: 2,
error: 3,
off: 999
},
pendingMessages: new Array(),
threshold: "info",
setLogLevelThreshold: function(logLevel) {
this.pendingLogLevelThreshold = logLevel;
this.show();
this.threshold = logLevel;
var logWindow = this.getLogWindow()
if (logWindow && logWindow.setThresholdLevel) {
logWindow.setThresholdLevel(logLevel);
}
// NOTE: log messages will be discarded until the log window is
// fully loaded.
},
@ -32,23 +45,12 @@ Logger.prototype = {
if (this.logWindow && this.logWindow.closed) {
this.logWindow = null;
}
if (this.logWindow && this.pendingLogLevelThreshold && this.logWindow.setThresholdLevel) {
this.logWindow.setThresholdLevel(this.pendingLogLevelThreshold);
// can't just directly log because that action would loop back
// to this code infinitely
var pendingMessage = new LogMessage("info", "Log level programmatically set to " + this.pendingLogLevelThreshold + " (presumably by driven-mode test code)");
this.pendingMessages.push(pendingMessage);
this.pendingLogLevelThreshold = null; // let's only go this way one time
}
return this.logWindow;
},
openLogWindow: function() {
this.logWindow = window.open(
getDocumentBase(document) + "SeleniumLog.html", "SeleniumLog",
getDocumentBase(document) + "SeleniumLog.html?startingThreshold="+this.threshold, "SeleniumLog",
"width=600,height=1000,bottom=0,right=0,status,scrollbars,resizable"
);
this.logWindow.moveTo(window.screenX + 1210, window.screenY + window.outerHeight - 1400);
@ -66,33 +68,39 @@ Logger.prototype = {
if (! this.getLogWindow()) {
this.openLogWindow();
}
setTimeout(function(){LOG.info("Log window displayed");}, 500);
setTimeout(function(){LOG.error("Log window displayed. Logging events will now be recorded to this window.");}, 500);
},
logHook: function(className, message) {
logHook: function(logLevel, message) {
},
log: function(className, message) {
log: function(logLevel, message) {
if (this.logLevels[logLevel] < this.logLevels[this.threshold]) {
return;
}
this.logHook(logLevel, message);
var logWindow = this.getLogWindow();
this.logHook(className, message);
if (logWindow) {
if (logWindow.append) {
if (logWindow.disabled) {
logWindow.callBack = fnBind(this.setLogLevelThreshold, this);
logWindow.enableButtons();
}
if (this.pendingMessages.length > 0) {
logWindow.append("info: Appending missed logging messages", "info");
logWindow.append("info("+(new Date().getTime())+"): Appending missed logging messages", "info");
while (this.pendingMessages.length > 0) {
var msg = this.pendingMessages.shift();
logWindow.append(msg.type + ": " + msg.msg, msg.type);
logWindow.append(msg.type + "("+msg.timestamp+"): " + msg.msg, msg.type);
}
logWindow.append("info: Done appending missed logging messages", "info");
logWindow.append("info("+(new Date().getTime())+"): Done appending missed logging messages", "info");
}
logWindow.append(className + ": " + message, className);
logWindow.append(logLevel + "("+(new Date().getTime())+"): " + message, logLevel);
}
} else {
// uncomment this to turn on background logging
/* these logging messages are never flushed, which creates
an enormous array of strings that never stops growing. Only
turn this on if you need it for debugging! */
//this.pendingMessages.push(new LogMessage(className, message));
// TODO these logging messages are never flushed, which creates
// an enormous array of strings that never stops growing.
// there should at least be a way to clear the messages!
this.pendingMessages.push(new LogMessage(logLevel, message));
}
},
@ -136,4 +144,5 @@ var LOG = new Logger();
var LogMessage = function(type, msg) {
this.type = type;
this.msg = msg;
this.timestamp = (new Date().getTime());
}

View file

@ -22,16 +22,23 @@ workingColor = "#DEE7EC";
doneColor = "#FFFFCC";
var injectedSessionId;
var cmd1 = document.createElement("div");
var cmd2 = document.createElement("div");
var cmd3 = document.createElement("div");
var cmd4 = document.createElement("div");
var postResult = "START";
var debugMode = false;
var relayToRC = null;
var proxyInjectionMode = false;
var uniqueId = 'sel_' + Math.round(100000 * Math.random());
var seleniumSequenceNumber = 0;
var cmd8 = "";
var cmd7 = "";
var cmd6 = "";
var cmd5 = "";
var cmd4 = "";
var cmd3 = "";
var cmd2 = "";
var cmd1 = "";
var lastCmd = "";
var lastCmdTime = new Date();
var RemoteRunnerOptions = classCreate();
objectExtend(RemoteRunnerOptions.prototype, URLConfiguration.prototype);
@ -51,8 +58,12 @@ objectExtend(RemoteRunnerOptions.prototype, {
return this._getQueryParameter("driverUrl");
},
// requires per-session extension Javascript as soon as this Selenium
// instance becomes aware of the session identifier
getSessionId: function() {
return this._getQueryParameter("sessionId");
var sessionId = this._getQueryParameter("sessionId");
requireExtensionJs(sessionId);
return sessionId;
},
_acquireQueryString: function () {
@ -62,7 +73,7 @@ objectExtend(RemoteRunnerOptions.prototype, {
if (args.length < 2) return null;
this.queryString = args[1];
} else if (proxyInjectionMode) {
this.queryString = selenium.browserbot.getCurrentWindow().location.search.substr(1);
this.queryString = window.location.search.substr(1);
} else {
this.queryString = top.location.search.substr(1);
}
@ -77,8 +88,8 @@ function runSeleniumTest() {
if (runOptions.isMultiWindowMode()) {
testAppWindow = openSeparateApplicationWindow('Blank.html', true);
} else if ($('myiframe') != null) {
var myiframe = $('myiframe');
} else if (sel$('selenium_myiframe') != null) {
var myiframe = sel$('selenium_myiframe');
if (myiframe) {
testAppWindow = myiframe.contentWindow;
}
@ -95,7 +106,7 @@ function runSeleniumTest() {
debugMode = runOptions.isDebugMode();
}
if (proxyInjectionMode) {
LOG.log = logToRc;
LOG.logHook = logToRc;
selenium.browserbot._modifyWindow(testAppWindow);
}
else if (debugMode) {
@ -108,13 +119,6 @@ function runSeleniumTest() {
currentTest = new RemoteRunner(commandFactory);
if (document.getElementById("commandList") != null) {
document.getElementById("commandList").appendChild(cmd4);
document.getElementById("commandList").appendChild(cmd3);
document.getElementById("commandList").appendChild(cmd2);
document.getElementById("commandList").appendChild(cmd1);
}
var doContinue = runOptions.getContinue();
if (doContinue != null) postResult = "OK";
@ -130,21 +134,18 @@ function buildDriverUrl() {
var slashPairOffset = s.indexOf("//") + "//".length
var pathSlashOffset = s.substring(slashPairOffset).indexOf("/")
return s.substring(0, slashPairOffset + pathSlashOffset) + "/selenium-server/driver/";
//return "http://localhost" + uniqueId + "/selenium-server/driver/";
}
function logToRc(logLevel, message) {
if (logLevel == null) {
logLevel = "debug";
}
if (debugMode) {
sendToRC("logLevel=" + logLevel + ":" + message.replace(/[\n\r\015]/g, " ") + "\n", "logging=true");
if (logLevel == null) {
logLevel = "debug";
}
sendToRCAndForget("logLevel=" + logLevel + ":" + message.replace(/[\n\r\015]/g, " ") + "\n", "logging=true");
}
}
function isArray(x) {
return ((typeof x) == "object") && (x["length"] != null);
}
function serializeString(name, s) {
return name + "=unescape(\"" + escape(s) + "\");";
}
@ -176,7 +177,7 @@ function serializeObject(name, x)
function relayBotToRC(s) {
}
// seems like no one uses this, but in fact it is called using eval from server-side PI mode code; however,
// seems like no one uses this, but in fact it is called using eval from server-side PI mode code; however,
// because multiple names can map to the same popup, assigning a single name confuses matters sometimes;
// thus, I'm disabling this for now. -Nelson 10/21/06
function setSeleniumWindowName(seleniumWindowName) {
@ -204,33 +205,44 @@ objectExtend(RemoteRunner.prototype, {
commandStarted : function(command) {
this.commandNode = document.createElement("div");
var innerHTML = command.command + '(';
var cmdText = command.command + '(';
if (command.target != null && command.target != "") {
innerHTML += command.target;
cmdText += command.target;
if (command.value != null && command.value != "") {
innerHTML += ', ' + command.value;
cmdText += ', ' + command.value;
}
}
innerHTML += ")";
if (innerHTML.length >40) {
innerHTML = innerHTML.substring(0,40);
innerHTML += "...";
if (cmdText.length > 70) {
cmdText = cmdText.substring(0, 70) + "...\n";
} else {
cmdText += ")\n";
}
this.commandNode.innerHTML = innerHTML;
this.commandNode.style.backgroundColor = workingColor;
if (document.getElementById("commandList") != null) {
document.getElementById("commandList").removeChild(cmd1);
document.getElementById("commandList").removeChild(cmd2);
document.getElementById("commandList").removeChild(cmd3);
document.getElementById("commandList").removeChild(cmd4);
if (cmdText == lastCmd) {
var rightNow = new Date();
var msSinceStart = rightNow.getTime() - lastCmdTime.getTime();
var sinceStart = msSinceStart + "ms";
if (msSinceStart > 1000) {
sinceStart = Math.round(msSinceStart / 1000) + "s";
}
cmd1 = "Same command (" + sinceStart + "): " + lastCmd;
} else {
lastCmdTime = new Date();
cmd8 = cmd7;
cmd7 = cmd6;
cmd6 = cmd5;
cmd5 = cmd4;
cmd4 = cmd3;
cmd3 = cmd2;
cmd2 = cmd1;
cmd1 = this.commandNode;
document.getElementById("commandList").appendChild(cmd4);
document.getElementById("commandList").appendChild(cmd3);
document.getElementById("commandList").appendChild(cmd2);
document.getElementById("commandList").appendChild(cmd1);
cmd1 = cmdText;
}
lastCmd = cmdText;
if (! proxyInjectionMode) {
var commandList = document.commands.commandList;
commandList.value = cmd8 + cmd7 + cmd6 + cmd5 + cmd4 + cmd3 + cmd2 + cmd1;
commandList.scrollTop = commandList.scrollHeight;
}
},
@ -250,7 +262,9 @@ objectExtend(RemoteRunner.prototype, {
if (result.result == null) {
postResult = "OK";
} else {
postResult = "OK," + result.result;
var actualResult = result.result;
actualResult = selArrayToString(actualResult);
postResult = "OK," + actualResult;
}
this.commandNode.style.backgroundColor = doneColor;
}
@ -259,7 +273,7 @@ objectExtend(RemoteRunner.prototype, {
commandError : function(message) {
postResult = "ERROR: " + message;
this.commandNode.style.backgroundColor = errorColor;
this.commandNode.title = message;
this.commandNode.titcle = message;
},
testComplete : function() {
@ -270,16 +284,26 @@ objectExtend(RemoteRunner.prototype, {
},
_HandleHttpResponse : function() {
// When request is completed
if (this.xmlHttpForCommandsAndResults.readyState == 4) {
// OK
if (this.xmlHttpForCommandsAndResults.status == 200) {
if (this.xmlHttpForCommandsAndResults.responseText=="") {
LOG.error("saw blank string xmlHttpForCommandsAndResults.responseText");
return;
}
var command = this._extractCommand(this.xmlHttpForCommandsAndResults);
this.currentCommand = command;
this.continueTestAtCurrentCommand();
} else {
if (command.command == 'retryLast') {
setTimeout(fnBind(function() {
sendToRC("RETRY", "retry=true", fnBind(this._HandleHttpResponse, this), this.xmlHttpForCommandsAndResults, true);
}, this), 1000);
} else {
this.currentCommand = command;
this.continueTestAtCurrentCommand();
}
}
// Not OK
else {
var s = 'xmlHttp returned: ' + this.xmlHttpForCommandsAndResults.status + ": " + this.xmlHttpForCommandsAndResults.statusText;
LOG.error(s);
this.currentCommand = null;
@ -290,7 +314,15 @@ objectExtend(RemoteRunner.prototype, {
},
_extractCommand : function(xmlHttp) {
var command;
var command, text, json;
text = command = xmlHttp.responseText;
if (/^json=/.test(text)) {
eval(text);
if (json.rest) {
eval(json.rest);
}
return json;
}
try {
var re = new RegExp("^(.*?)\n((.|[\r\n])*)");
if (re.exec(xmlHttp.responseText)) {
@ -364,21 +396,68 @@ function sendToRC(dataToBePosted, urlParms, callback, xmlHttpObject, async) {
if (urlParms) {
url += urlParms;
}
url += "&localFrameAddress=" + (proxyInjectionMode ? makeAddressToAUTFrame() : "top");
url += getSeleniumWindowNameURLparameters();
url += "&uniqueId=" + uniqueId;
url = addUrlParams(url);
url += "&sequenceNumber=" + seleniumSequenceNumber++;
var postedData = "postedData=" + encodeURIComponent(dataToBePosted);
if (callback == null) {
callback = function() {
};
}
url += buildDriverParams() + preventBrowserCaching();
//xmlHttpObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttpObject.open("POST", url, async);
xmlHttpObject.onreadystatechange = callback;
xmlHttpObject.send(dataToBePosted);
if (callback) xmlHttpObject.onreadystatechange = callback;
xmlHttpObject.send(postedData);
return null;
}
function addUrlParams(url) {
return url + "&localFrameAddress=" + (proxyInjectionMode ? makeAddressToAUTFrame() : "top")
+ getSeleniumWindowNameURLparameters()
+ "&uniqueId=" + uniqueId
+ buildDriverParams() + preventBrowserCaching()
}
function sendToRCAndForget(dataToBePosted, urlParams) {
var url;
if (!(browserVersion.isChrome || browserVersion.isHTA)) {
// DGF we're behind a proxy, so we can send our logging message to literally any host, to avoid 2-connection limit
var protocol = "http:";
if (window.location.protocol == "https:") {
// DGF if we're in HTTPS, use another HTTPS url to avoid security warning
protocol = "https:";
}
// we don't choose a super large random value, but rather 1 - 16, because this matches with the pre-computed
// tunnels waiting on the Selenium Server side. This gives us higher throughput than the two-connection-per-host
// limitation, but doesn't require we generate an extremely large ammount of fake SSL certs either.
url = protocol + "//" + Math.floor(Math.random()* 16 + 1) + ".selenium.doesnotexist/selenium-server/driver/?" + urlParams;
} else {
url = buildDriverUrl() + "?" + urlParams;
}
url = addUrlParams(url);
var method = "GET";
if (method == "POST") {
// DGF submit a request using an iframe; we can't see the response, but we don't need to
// TODO not using this mechanism because it screws up back-button
var loggingForm = document.createElement("form");
loggingForm.method = "POST";
loggingForm.action = url;
loggingForm.target = "seleniumLoggingFrame";
var postedDataInput = document.createElement("input");
postedDataInput.type = "hidden";
postedDataInput.name = "postedData";
postedDataInput.value = dataToBePosted;
loggingForm.appendChild(postedDataInput);
document.body.appendChild(loggingForm);
loggingForm.submit();
document.body.removeChild(loggingForm);
} else {
var postedData = "&postedData=" + encodeURIComponent(dataToBePosted);
var scriptTag = document.createElement("script");
scriptTag.src = url + postedData;
document.body.appendChild(scriptTag);
document.body.removeChild(scriptTag);
}
}
function buildDriverParams() {
var params = "";
@ -402,7 +481,7 @@ function preventBrowserCaching() {
//
// In selenium, the main (i.e., first) window's name is a blank string.
//
// Additional pop-ups are associated with either 1.) the name given by the 2nd parameter to window.open, or 2.) the name of a
// Additional pop-ups are associated with either 1.) the name given by the 2nd parameter to window.open, or 2.) the name of a
// property on the opening window which points at the window.
//
// An example of #2: if window X contains JavaScript as follows:
@ -420,11 +499,13 @@ function getSeleniumWindowNameURLparameters() {
return s;
}
if (w["seleniumWindowName"] == null) {
s += 'generatedSeleniumWindowName_' + Math.round(100000 * Math.random());
}
else {
s += w["seleniumWindowName"];
if (w.name) {
w["seleniumWindowName"] = w.name;
} else {
w["seleniumWindowName"] = 'generatedSeleniumWindowName_' + Math.round(100000 * Math.random());
}
}
s += w["seleniumWindowName"];
var windowOpener = w.opener;
for (key in windowOpener) {
var val = null;
@ -432,7 +513,7 @@ function getSeleniumWindowNameURLparameters() {
val = windowOpener[key];
}
catch(e) {
}
}
if (val==w) {
s += "&jsWindowNameVar=" + key; // found a js variable in the opener referring to this window
}
@ -464,3 +545,151 @@ function makeAddressToAUTFrame(w, frameNavigationalJSexpression)
}
return null;
}
Selenium.prototype.doSetContext = function(context) {
/**
* Writes a message to the status bar and adds a note to the browser-side
* log.
*
* @param context
* the message to be sent to the browser
*/
//set the current test title
var ctx = document.getElementById("context");
if (ctx != null) {
ctx.innerHTML = context;
}
};
/**
* Adds a script tag referencing a specially-named user extensions "file". The
* resource handler for this special file (which won't actually exist) will use
* the session ID embedded in its name to retrieve per-session specified user
* extension javascript.
*
* @param sessionId
*/
function requireExtensionJs(sessionId) {
var src = 'scripts/user-extensions.js[' + sessionId + ']';
if (document.getElementById(src) == null) {
var scriptTag = document.createElement('script');
scriptTag.language = 'JavaScript';
scriptTag.type = 'text/javascript';
scriptTag.src = src;
scriptTag.id = src;
var headTag = document.getElementsByTagName('head')[0];
headTag.appendChild(scriptTag);
}
}
Selenium.prototype.doAttachFile = function(fieldLocator,fileLocator) {
/**
* Sets a file input (upload) field to the file listed in fileLocator
*
* @param fieldLocator an <a href="#locators">element locator</a>
* @param fileLocator a URL pointing to the specified file. Before the file
* can be set in the input field (fieldLocator), Selenium RC may need to transfer the file
* to the local machine before attaching the file in a web page form. This is common in selenium
* grid configurations where the RC server driving the browser is not the same
* machine that started the test.
*
* Supported Browsers: Firefox ("*chrome") only.
*
*/
// This doesn't really do anything on the JS side; we let the Selenium Server take care of this for us!
};
Selenium.prototype.doCaptureScreenshot = function(filename) {
/**
* Captures a PNG screenshot to the specified file.
*
* @param filename the absolute path to the file to be written, e.g. "c:\blah\screenshot.png"
*/
// This doesn't really do anything on the JS side; we let the Selenium Server take care of this for us!
};
Selenium.prototype.doCaptureScreenshotToString = function() {
/**
* Capture a PNG screenshot. It then returns the file as a base 64 encoded string.
*
* @return string The base 64 encoded string of the screen shot (PNG file)
*/
// This doesn't really do anything on the JS side; we let the Selenium Server take care of this for us!
};
Selenium.prototype.doCaptureEntirePageScreenshotToString = function(kwargs) {
/**
* Downloads a screenshot of the browser current window canvas to a
* based 64 encoded PNG file. The <em>entire</em> windows canvas is captured,
* including parts rendered outside of the current view port.
*
* Currently this only works in Mozilla and when running in chrome mode.
*
* @param kwargs A kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD". This may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas dimension to fail and a black background is exposed (possibly obscuring black text).
*
* @return string The base 64 encoded string of the page screenshot (PNG file)
*/
// This doesn't really do anything on the JS side; we let the Selenium Server take care of this for us!
};
Selenium.prototype.doShutDownSeleniumServer = function(keycode) {
/**
* Kills the running Selenium Server and all browser sessions. After you run this command, you will no longer be able to send
* commands to the server; you can't remotely start the server once it has been stopped. Normally
* you should prefer to run the "stop" command, which terminates the current browser session, rather than
* shutting down the entire server.
*
*/
// This doesn't really do anything on the JS side; we let the Selenium Server take care of this for us!
};
Selenium.prototype.doRetrieveLastRemoteControlLogs = function() {
/**
* Retrieve the last messages logged on a specific remote control. Useful for error reports, especially
* when running multiple remote controls in a distributed environment. The maximum number of log messages
* that can be retrieve is configured on remote control startup.
*
* @return string The last N log messages as a multi-line string.
*/
// This doesn't really do anything on the JS side; we let the Selenium Server take care of this for us!
};
Selenium.prototype.doKeyDownNative = function(keycode) {
/**
* Simulates a user pressing a key (without releasing it yet) by sending a native operating system keystroke.
* This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing
* a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and
* metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular
* element, focus on the element first before running this command.
*
* @param keycode an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes!
*/
// This doesn't really do anything on the JS side; we let the Selenium Server take care of this for us!
};
Selenium.prototype.doKeyUpNative = function(keycode) {
/**
* Simulates a user releasing a key by sending a native operating system keystroke.
* This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing
* a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and
* metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular
* element, focus on the element first before running this command.
*
* @param keycode an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes!
*/
// This doesn't really do anything on the JS side; we let the Selenium Server take care of this for us!
};
Selenium.prototype.doKeyPressNative = function(keycode) {
/**
* Simulates a user pressing and releasing a key by sending a native operating system keystroke.
* This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing
* a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and
* metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular
* element, focus on the element first before running this command.
*
* @param keycode an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes!
*/
// This doesn't really do anything on the JS side; we let the Selenium Server take care of this for us!
};

View file

@ -45,6 +45,10 @@ objectExtend(HtmlTestRunner.prototype, {
},
loadSuiteFrame: function() {
var logLevel = this.controlPanel.getDefaultLogLevel();
if (logLevel) {
LOG.setLogLevelThreshold(logLevel);
}
if (selenium == null) {
var appWindow = this._getApplicationWindow();
try { appWindow.location; }
@ -76,7 +80,7 @@ objectExtend(HtmlTestRunner.prototype, {
if (this.controlPanel.isMultiWindowMode()) {
return this._getSeparateApplicationWindow();
}
return $('myiframe').contentWindow;
return sel$('selenium_myiframe').contentWindow;
},
_getSeparateApplicationWindow: function () {
@ -87,6 +91,7 @@ objectExtend(HtmlTestRunner.prototype, {
},
_onloadTestSuite:function () {
suiteFrame = new HtmlTestSuiteFrame(getSuiteFrame());
if (! this.getTestSuite().isAvailable()) {
return;
}
@ -97,7 +102,12 @@ objectExtend(HtmlTestRunner.prototype, {
addLoadListener(this._getApplicationWindow(), fnBind(this._startSingleTest, this));
this._getApplicationWindow().src = this.controlPanel.getAutoUrl();
} else {
this.getTestSuite().getSuiteRows()[0].loadTestCase();
var testCaseLoaded = fnBind(function(){this.testCaseLoaded=true;},this);
var testNumber = 0;
if (this.controlPanel.getTestNumber() != null){
var testNumber = this.controlPanel.getTestNumber() - 1;
}
this.getTestSuite().getSuiteRows()[testNumber].loadTestCase(testCaseLoaded);
}
},
@ -134,6 +144,8 @@ objectExtend(HtmlTestRunner.prototype, {
//todo: move testFailed and storedVars to TestCase
this.testFailed = false;
storedVars = new Object();
storedVars.nbsp = String.fromCharCode(160);
storedVars.space = ' ';
this.currentTest = new HtmlRunnerTestLoop(testFrame.getCurrentTestCase(), this.metrics, this.commandFactory);
currentTest = this.currentTest;
this.currentTest.start();
@ -157,6 +169,10 @@ objectExtend(SeleniumFrame.prototype, {
addLoadListener(this.frame, fnBind(this._handleLoad, this));
},
getWindow : function() {
return this.frame.contentWindow;
},
getDocument : function() {
return this.frame.contentWindow.document;
},
@ -166,7 +182,6 @@ objectExtend(SeleniumFrame.prototype, {
this._onLoad();
if (this.loadCallback) {
this.loadCallback();
this.loadCallback = null;
}
},
@ -187,10 +202,12 @@ objectExtend(SeleniumFrame.prototype, {
// this works in every browser (except Firefox in chrome mode)
var styleSheetPath = window.location.pathname.replace(/[^\/\\]+$/, "selenium-test.css");
if (browserVersion.isIE && window.location.protocol == "file:") {
styleSheetPath = "file://" + styleSheetPath;
styleSheetPath = "file:///" + styleSheetPath;
}
styleLink.href = styleSheetPath;
}
// DGF You're only going to see this log message if you set defaultLogLevel=debug
LOG.debug("styleLink.href="+styleLink.href);
head.appendChild(styleLink);
},
@ -205,7 +222,8 @@ objectExtend(SeleniumFrame.prototype, {
var isChrome = browserVersion.isChrome || false;
var isHTA = browserVersion.isHTA || false;
// DGF TODO multiWindow
location += "?thisIsChrome=" + isChrome + "&thisIsHTA=" + isHTA;
location += (location.indexOf("?") == -1 ? "?" : "&");
location += "thisIsChrome=" + isChrome + "&thisIsHTA=" + isHTA;
if (browserVersion.isSafari) {
// safari doesn't reload the page when the location equals to current location.
// hence, set the location to blank so that the page will reload automatically.
@ -246,7 +264,7 @@ objectExtend(HtmlTestFrame.prototype, SeleniumFrame.prototype);
objectExtend(HtmlTestFrame.prototype, {
_onLoad: function() {
this.currentTestCase = new HtmlTestCase(this.getDocument(), htmlTestRunner.getTestSuite().getCurrentRow());
this.currentTestCase = new HtmlTestCase(this.getWindow(), htmlTestRunner.getTestSuite().getCurrentRow());
},
getCurrentTestCase: function() {
@ -265,19 +283,19 @@ var suiteFrame;
var testFrame;
function getSuiteFrame() {
var f = $('testSuiteFrame');
var f = sel$('testSuiteFrame');
if (f == null) {
f = top;
// proxyInjection mode does not set myiframe
// proxyInjection mode does not set selenium_myiframe
}
return f;
}
function getTestFrame() {
var f = $('testFrame');
var f = sel$('testFrame');
if (f == null) {
f = top;
// proxyInjection mode does not set myiframe
// proxyInjection mode does not set selenium_myiframe
}
return f;
}
@ -290,9 +308,9 @@ objectExtend(HtmlTestRunnerControlPanel.prototype, {
this.runInterval = 0;
this.highlightOption = $('highlightOption');
this.pauseButton = $('pauseTest');
this.stepButton = $('stepTest');
this.highlightOption = sel$('highlightOption');
this.pauseButton = sel$('pauseTest');
this.stepButton = sel$('stepTest');
this.highlightOption.onclick = fnBindAsEventListener((function() {
this.setHighlightOption();
@ -342,7 +360,7 @@ objectExtend(HtmlTestRunnerControlPanel.prototype, {
},
reset: function() {
// this.runInterval = this.speedController.value;
this.runInterval = this.speedController.value;
this._switchContinueButtonToPause();
},
@ -352,7 +370,7 @@ objectExtend(HtmlTestRunnerControlPanel.prototype, {
},
_switchPauseButtonToContinue: function() {
$('stepTest').disabled = false;
sel$('stepTest').disabled = false;
this.pauseButton.className = "cssContinueTest";
this.pauseButton.onclick = fnBindAsEventListener(this.continueCurrentTest, this);
},
@ -378,6 +396,10 @@ objectExtend(HtmlTestRunnerControlPanel.prototype, {
return this._getQueryParameter("test");
},
getTestNumber: function() {
return this._getQueryParameter("testNumber");
},
getSingleTestName: function() {
return this._getQueryParameter("singletest");
},
@ -385,6 +407,10 @@ objectExtend(HtmlTestRunnerControlPanel.prototype, {
getAutoUrl: function() {
return this._getQueryParameter("autoURL");
},
getDefaultLogLevel: function() {
return this._getQueryParameter("defaultLogLevel");
},
getResultsUrl: function() {
return this._getQueryParameter("resultsUrl");
@ -574,7 +600,9 @@ objectExtend(HtmlTestSuite.prototype, {
initialize: function(suiteDocument) {
this.suiteDocument = suiteDocument;
this.suiteRows = this._collectSuiteRows();
this.titleRow = new TitleRow(this.getTestTable().rows[0]);
var testTable = this.getTestTable();
if (!testTable) return;
this.titleRow = new TitleRow(testTable.rows[0]);
this.reset();
},
@ -593,7 +621,7 @@ objectExtend(HtmlTestSuite.prototype, {
},
getTestTable: function() {
var tables = $A(this.suiteDocument.getElementsByTagName("table"));
var tables = sel$A(this.suiteDocument.getElementsByTagName("table"));
return tables[0];
},
@ -603,15 +631,16 @@ objectExtend(HtmlTestSuite.prototype, {
_collectSuiteRows: function () {
var result = [];
var tables = $A(this.suiteDocument.getElementsByTagName("table"));
var tables = sel$A(this.suiteDocument.getElementsByTagName("table"));
var testTable = tables[0];
if (!testTable) return;
for (rowNum = 1; rowNum < testTable.rows.length; rowNum++) {
var rowElement = testTable.rows[rowNum];
result.push(new HtmlTestSuiteRow(rowElement, testFrame, this));
}
// process the unsuited rows as well
for (var tableNum = 1; tableNum < $A(this.suiteDocument.getElementsByTagName("table")).length; tableNum++) {
for (var tableNum = 1; tableNum < sel$A(this.suiteDocument.getElementsByTagName("table")).length; tableNum++) {
testTable = tables[tableNum];
for (rowNum = 1; rowNum < testTable.rows.length; rowNum++) {
var rowElement = testTable.rows[rowNum];
@ -652,7 +681,7 @@ objectExtend(HtmlTestSuite.prototype, {
_onTestSuiteComplete: function() {
this.markDone();
new TestResult(this.failed, this.getTestTable()).post();
new SeleniumTestResult(this.failed, this.getTestTable()).post();
},
updateSuiteWithResultOfPreviousTest: function() {
@ -676,8 +705,8 @@ objectExtend(HtmlTestSuite.prototype, {
});
var TestResult = classCreate();
objectExtend(TestResult.prototype, {
var SeleniumTestResult = classCreate();
objectExtend(SeleniumTestResult.prototype, {
// Post the results to a servlet, CGI-script, etc. The URL of the
// results-handler defaults to "/postResults", but an alternative location
@ -713,7 +742,7 @@ objectExtend(TestResult.prototype, {
form.id = "resultsForm";
form.method = "post";
form.target = "myiframe";
form.target = "selenium_myiframe";
var resultsUrl = this.controlPanel.getResultsUrl();
if (!resultsUrl) {
@ -766,11 +795,22 @@ objectExtend(TestResult.prototype, {
}
}
form.createHiddenField("numTestTotal", rowNum);
form.createHiddenField("numTestTotal", rowNum-1);
// Add HTML for the suite itself
form.createHiddenField("suite", this.suiteTable.parentNode.innerHTML);
var logMessages = [];
while (LOG.pendingMessages.length > 0) {
var msg = LOG.pendingMessages.shift();
logMessages.push(msg.type);
logMessages.push(": ");
logMessages.push(msg.msg);
logMessages.push('\n');
}
var logOutput = logMessages.join("");
form.createHiddenField("log", logOutput);
if (this.controlPanel.shouldSaveResultsToFile()) {
this._saveToFile(resultsUrl, form);
} else {
@ -788,22 +828,50 @@ objectExtend(TestResult.prototype, {
for (var i = 0; i < form.elements.length; i++) {
inputs[form.elements[i].name] = form.elements[i].value;
}
var objFSO = new ActiveXObject("Scripting.FileSystemObject")
// DGF get CSS
var styles = "";
try {
var styleSheetPath = window.location.pathname.replace(/[^\/\\]+$/, "selenium-test.css");
if (window.location.protocol == "file:") {
var stylesFile = objFSO.OpenTextFile(styleSheetPath, 1);
styles = stylesFile.ReadAll();
} else {
var xhr = XmlHttp.create();
xhr.open("GET", styleSheetPath, false);
xhr.send("");
styles = xhr.responseText;
}
} catch (e) {}
var scriptFile = objFSO.CreateTextFile(fileName);
scriptFile.WriteLine("<html><body>\n<h1>Test suite results </h1>" +
"\n\n<table>\n<tr>\n<td>result:</td>\n<td>" + inputs["result"] + "</td>\n" +
"</tr>\n<tr>\n<td>totalTime:</td>\n<td>" + inputs["totalTime"] + "</td>\n</tr>\n" +
"<tr>\n<td>numTestPasses:</td>\n<td>" + inputs["numTestPasses"] + "</td>\n</tr>\n" +
"<tr>\n<td>numTestFailures:</td>\n<td>" + inputs["numTestFailures"] + "</td>\n</tr>\n" +
"<tr>\n<td>numCommandPasses:</td>\n<td>" + inputs["numCommandPasses"] + "</td>\n</tr>\n" +
"<tr>\n<td>numCommandFailures:</td>\n<td>" + inputs["numCommandFailures"] + "</td>\n</tr>\n" +
"<tr>\n<td>numCommandErrors:</td>\n<td>" + inputs["numCommandErrors"] + "</td>\n</tr>\n" +
"<tr>\n<td>" + inputs["suite"] + "</td>\n<td>&nbsp;</td>\n</tr>");
scriptFile.WriteLine("<html><head><title>Test suite results</title><style>");
scriptFile.WriteLine(styles);
scriptFile.WriteLine("</style>");
scriptFile.WriteLine("<body>\n<h1>Test suite results</h1>" +
"\n\n<table>\n<tr>\n<td>result:</td>\n<td>" + inputs["result"] + "</td>\n" +
"</tr>\n<tr>\n<td>totalTime:</td>\n<td>" + inputs["totalTime"] + "</td>\n</tr>\n" +
"<tr>\n<td>numTestTotal:</td>\n<td>" + inputs["numTestTotal"] + "</td>\n</tr>\n" +
"<tr>\n<td>numTestPasses:</td>\n<td>" + inputs["numTestPasses"] + "</td>\n</tr>\n" +
"<tr>\n<td>numTestFailures:</td>\n<td>" + inputs["numTestFailures"] + "</td>\n</tr>\n" +
"<tr>\n<td>numCommandPasses:</td>\n<td>" + inputs["numCommandPasses"] + "</td>\n</tr>\n" +
"<tr>\n<td>numCommandFailures:</td>\n<td>" + inputs["numCommandFailures"] + "</td>\n</tr>\n" +
"<tr>\n<td>numCommandErrors:</td>\n<td>" + inputs["numCommandErrors"] + "</td>\n</tr>\n" +
"<tr>\n<td>" + inputs["suite"] + "</td>\n<td>&nbsp;</td>\n</tr></table><table>");
var testNum = inputs["numTestTotal"];
for (var rowNum = 1; rowNum < testNum; rowNum++) {
for (var rowNum = 1; rowNum <= testNum; rowNum++) {
scriptFile.WriteLine("<tr>\n<td>" + inputs["testTable." + rowNum] + "</td>\n<td>&nbsp;</td>\n</tr>");
}
scriptFile.WriteLine("</table></body></html>");
scriptFile.WriteLine("</table><pre>");
var log = inputs["log"];
log=log.replace(/&/gm,"&amp;").replace(/</gm,"&lt;").replace(/>/gm,"&gt;").replace(/"/gm,"&quot;").replace(/'/gm,"&apos;");
scriptFile.WriteLine(log);
scriptFile.WriteLine("</pre></body></html>");
scriptFile.Close();
}
});
@ -812,14 +880,22 @@ objectExtend(TestResult.prototype, {
var HtmlTestCase = classCreate();
objectExtend(HtmlTestCase.prototype, {
initialize: function(testDocument, htmlTestSuiteRow) {
if (testDocument == null) {
throw "testDocument should not be null";
initialize: function(testWindow, htmlTestSuiteRow) {
if (testWindow == null) {
throw "testWindow should not be null";
}
if (htmlTestSuiteRow == null) {
throw "htmlTestSuiteRow should not be null";
}
this.testDocument = testDocument;
this.testWindow = testWindow;
this.testDocument = testWindow.document;
this.pathname = "'unknown'";
try {
if (this.testWindow.location) {
this.pathname = this.testWindow.location.pathname;
}
} catch (e) {}
this.htmlTestSuiteRow = htmlTestSuiteRow;
this.headerRow = new TitleRow(this.testDocument.getElementsByTagName("tr")[0]);
this.commandRows = this._collectCommandRows();
@ -829,11 +905,11 @@ objectExtend(HtmlTestCase.prototype, {
_collectCommandRows: function () {
var commandRows = [];
var tables = $A(this.testDocument.getElementsByTagName("table"));
var tables = sel$A(this.testDocument.getElementsByTagName("table"));
var self = this;
for (var i = 0; i < tables.length; i++) {
var table = tables[i];
var tableRows = $A(table.rows);
var tableRows = sel$A(table.rows);
for (var j = 0; j < tableRows.length; j++) {
var candidateRow = tableRows[j];
if (self.isCommandRow(candidateRow)) {
@ -959,11 +1035,11 @@ objectExtend(Metrics.prototype, {
},
printMetrics: function() {
setText($('commandPasses'), this.numCommandPasses);
setText($('commandFailures'), this.numCommandFailures);
setText($('commandErrors'), this.numCommandErrors);
setText($('testRuns'), this.numTestPasses + this.numTestFailures);
setText($('testFailures'), this.numTestFailures);
setText(sel$('commandPasses'), this.numCommandPasses);
setText(sel$('commandFailures'), this.numCommandFailures);
setText(sel$('commandErrors'), this.numCommandErrors);
setText(sel$('testRuns'), this.numTestPasses + this.numTestFailures);
setText(sel$('testFailures'), this.numTestFailures);
this.currentTime = new Date().getTime();
@ -973,7 +1049,7 @@ objectExtend(Metrics.prototype, {
var minutes = Math.floor(totalSecs / 60);
var seconds = totalSecs % 60;
setText($('elapsedTime'), this._pad(minutes) + ":" + this._pad(seconds));
setText(sel$('elapsedTime'), this._pad(minutes) + ":" + this._pad(seconds));
},
// Puts a leading 0 on num if it is less than 10
@ -1020,9 +1096,7 @@ objectExtend(HtmlRunnerTestLoop.prototype, {
this.metrics = metrics;
this.htmlTestCase = htmlTestCase;
se = selenium;
global.se = selenium;
LOG.info("Starting test " + htmlTestCase.pathname);
this.currentRow = null;
this.currentRowIndex = 0;
@ -1034,17 +1108,6 @@ objectExtend(HtmlRunnerTestLoop.prototype, {
this.expectedFailureType = null;
this.htmlTestCase.reset();
this.sejsElement = this.htmlTestCase.testDocument.getElementById('sejs');
if (this.sejsElement) {
var fname = 'Selenium JavaScript';
parse_result = parse(this.sejsElement.innerHTML, fname, 0);
var x2 = new ExecutionContext(GLOBAL_CODE);
ExecutionContext.current = x2;
execute(parse_result, x2)
}
},
_advanceToNextRow: function() {
@ -1069,7 +1132,7 @@ objectExtend(HtmlRunnerTestLoop.prototype, {
},
commandStarted : function() {
$('pauseTest').disabled = false;
sel$('pauseTest').disabled = false;
this.currentRow.select();
this.metrics.printMetrics();
},
@ -1141,8 +1204,8 @@ objectExtend(HtmlRunnerTestLoop.prototype, {
},
testComplete : function() {
$('pauseTest').disabled = true;
$('stepTest').disabled = true;
sel$('pauseTest').disabled = true;
sel$('stepTest').disabled = true;
if (htmlTestRunner.testFailed) {
this.htmlTestCase.markFailed();
this.metrics.numTestFailures += 1;
@ -1231,6 +1294,24 @@ Selenium.prototype.doEcho = function(message) {
currentTest.currentRow.setMessage(message);
}
/*
* doSetSpeed and getSpeed are already defined in selenium-api.js,
* so we're defining these functions in a tricky way so that doc.js doesn't
* try to read API doc from the function definitions here.
*/
Selenium.prototype._doSetSpeed = function(value) {
var milliseconds = parseInt(value);
if (milliseconds < 0) milliseconds = 0;
htmlTestRunner.controlPanel.speedController.setValue(milliseconds);
htmlTestRunner.controlPanel.setRunInterval(milliseconds);
}
Selenium.prototype.doSetSpeed = Selenium.prototype._doSetSpeed;
Selenium.prototype._getSpeed = function() {
return htmlTestRunner.controlPanel.runInterval;
}
Selenium.prototype.getSpeed = Selenium.prototype._getSpeed;
Selenium.prototype.assertSelected = function(selectLocator, optionLocator) {
/**
* Verifies that the selected option of a drop-down satisfies the optionSpecifier. <i>Note that this command is deprecated; you should use assertSelectedLabel, assertSelectedValue, assertSelectedIndex, or assertSelectedId instead.</i>

View file

@ -1,5 +1,5 @@
Selenium.version = "0.8.2";
Selenium.revision = "1727";
Selenium.version = "1.0-beta-2";
Selenium.revision = "2330";
window.top.document.title += " v" + Selenium.version + " [" + Selenium.revision + "]";

View file

@ -0,0 +1,803 @@
<html>
<head>
<title>Selenium UI-Element Reference</title>
<style type="text/css">
body {
margin-left: 5%;
margin-right: 5%;
}
dt {
font-weight: bolder;
}
dd {
margin-top: 10px;
margin-bottom: 10px;
}
pre {
margin: 10px;
padding: 10px;
background-color: #eaeaea;
}
code {
padding: 2px;
background-color: #dfd;
}
table {
border-collapse: collapse;
border: solid 1px black;
}
th, td {
border: solid 1px grey;
padding: 5px;
}
.highlight {
background-color: #eea;
}
.deprecated {
font-style: italic;
color: #c99;
}
</style>
</head>
<body>
<h1>Selenium UI-Element Reference</h1>
<h2>Introduction</h2>
<p>UI-Element is a Selenium feature that makes it possible to define a mapping between semantically meaningful names of elements on webpages, and the elements themselves. The mapping is defined using <a href="http://en.wikipedia.org/wiki/JSON">JavaScript Object Notation</a>, and may be shared both by the IDE and tests run via Selenium RC. It also offers a single point of update should the user interface of the application under test change.</p>
<h2>Terminology</h2>
<dl>
<dt>Page</dt>
<dd>A unique URL, and the contents available by accessing that URL. A page typically consists of several interactive page elements. A page may also be considered a DOM document object, complete with URL information.</dd>
<dt>Page element</dt>
<dd>An element on the actual webpage. Generally speaking, an element is anything the user might interact with, or anything that contains meaningful content. More specifically, an element is realized as a <a href="http://en.wikipedia.org/wiki/Document_Object_Model">Document Object Model (DOM)</a> node and its contents. So when we refer to a page element, we mean both of the following, at the same time:
<ul>
<li>something on the page</li>
<li>its DOM representation, including its relationship with other page elements</li>
</ul>
</dd>
<dt>Pageset</dt>
<dd>A set of pages that share some set of common page elements. For example, I might be able to log into my application from several different pages. If certain page elements on each of those pages appear similarly (i.e. their DOM representations are identical), those pages can be grouped into a pageset with respect to these page elements. There is no restriction on how many pagesets a given page can be a member of. Similarly, a UI element belong to multiple pagesets. A pageset is commonly represented by a <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> which matches the URL's that uniquely identify pages; however, there are cases when the page content must be considered to determine pageset membership. A pageset also has a name.</dd>
<dt>UI element</dt>
<dd>A mapping between a meaningful name for a page element, and the means to locate that page element's DOM node. The page element is located via a locator. UI elements belong to pagesets.</dd>
<dt>UI argument</dt>
<dd>An optional piece of logic that determines how the locator is generated by a UI element. Typically used when similar page elements appear multiple times on the same page, and you want to address them all with a single UI element. For example, if a page presents 20 clickable search results, the index of the search result might be a UI argument.</dd>
<dt>UI map</dt>
<dd>A collection of pagesets, which in turn contain UI elements. The UI map is the medium for translating between UI specifier strings, page elements, and UI elements.</dd>
<dt>UI specifier string</dt>
<dd>A bit of text containing a pageset name, a UI element name, and optionally arguments that modify the way a locator is constructed by the UI element. UI specifier strings are intended to be the human-readable identifier for page elements.</dd>
<dt>Rollup rule</dt>
<dd>Logic that describes how one or more Selenium commands can be grouped into a single command, and how that single command may be expanded into its component Selenium commands. The single command is referred to simply as a "rollup".</dd>
<dt>Command matcher</dt>
<dd>Typically folded into a rollup rule, it matches one or more Selenium commands and optionally sets values for rollup arguments based on the matched commands. A rollup rule usually has one or more command matchers.</dd>
<dt>Rollup argument</dt>
<dd>An optional piece of logic that modifies the command expansion of a rollup.</dd>
</dl>
<h2>The Basics</h2>
<h3>Getting Motivated</h3>
<p>Question: Why use UI-Element? Answer: So your testcases can look like this (boilerplate code omitted):</p>
<pre>
&lt;tr&gt;
&lt;td&gt;open&lt;/td&gt;
&lt;td&gt;/&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;clickAndWait&lt;/td&gt;
&lt;td&gt;<span class="highlight">ui=allPages::section(section=topics)</span>&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;clickAndWait&lt;/td&gt;
&lt;td&gt;<span class="highlight">ui=topicListingPages::topic(topic=Process)</span>&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;clickAndWait&lt;/td&gt;
&lt;td&gt;<span class="highlight">ui=subtopicListingPages::subtopic(subtopic=Creativity)</span>&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;click&lt;/td&gt;
&lt;td&gt;<span class="highlight">ui=subtopicArticleListingPages::article(index=2)</span>&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
</pre>
<h3>Including the Right Files</h3>
<p>UI-Element is now fully integrated with Selenium. The only additional file that needs to be specified is your map definitions file. In the IDE, add it to the comma-delimited <em>Selenium Core extensions</em> field of the IDE options. A sample definition file created for the website <a href="http://alistapart.com">alistapart.com</a> is included in the distribution and is available here:</p>
<pre><a href="chrome://selenium-ide/content/selenium/scripts/ui-map-sample.js">chrome://selenium-ide/content/selenium/scripts/ui-map-sample.js</a></pre>
<p>You might want to experiment with the sample map to get a feel for UI-Element. For the Selenium RC, you have two options. The map file may be included in the <code>user-extensions.js</code> file specified at startup with the <code>-userExtensions</code> switch. Or, you may load it dynamically with the variant of the <code>setUserExtensionJs</code> command in your driver language, before the browser is started.</p>
<h3>Map Definitions File Syntax</h3>
<p>This is the general format of a map file:</p>
<pre>
var map = new UIMap();
map.addPageset({
name: 'aPageset'
, ...
});
map.addElement('aPageset', { ... });
map.addElement('aPageset', { ... });
...
map.addPageset({
name: 'anotherPageset'
, ...
});
...
</pre>
<p>The map object is initialized by creating a new <code>UIMap</code> object. Next, a pageset is defined. Then one or more UI elements are defined for that pageset. More pagesets are defined, each with corresponding UI elements. That's it!</p>
<h3>Pageset Shorthand</h3>
<p>The method signature of <code>addPageset()</code> is <em>(pagesetShorthand)</em>. <em>pagesetShorthand</em> is a JSON description of the pageset. Here's a minimal example:</p>
<pre>
map.addPageset({
name: 'allPages'
, description: 'contains elements common to all pages'
, pathRegexp: '.*'
});
</pre>
<p>Here's a table containing information about the attributes of the Pageset object. The conditionally required or unrequired items are for IDE recording support only.</p>
<table>
<tr><th>Name</th>
<th>Required?</th>
<th>Description</th>
<th>Example</th>
</tr>
<tr><td>name</td>
<td>Yes</td>
<td>(String) the name of the pageset. This should be unique within the map.</td>
<td><pre>name: 'shopPages'</pre></td>
</tr>
<tr><td>description</td>
<td>Yes</td>
<td>(String) a description of the pageset. Ideally, this will give the reader an idea of what types of UI elements the pageset will have.</td>
<td><pre>description: 'all pages displaying product'</pre></td>
</tr>
<tr><td>pathPrefix</td>
<td>No</td>
<td>(String) the path of the URL of all included pages in this pageset will contain this prefix. For example, if all pages are of the form http://www.example.com/<span class="highlight">gallery/</span>light-show/, the page prefix might be <code>gallery/</code> .</td>
<td><pre>pathPrefix: 'gallery/'</pre></td>
</tr>
<tr><td>paths<br />pathRegexp</td>
<td>Conditional</td>
<td>(Array | String) either a list of path strings, or a string that represents a regular expression. One or the other should be defined, but not both. If an array, it enumerates pages that are included in the pageset. If a regular expression, any pages whose URL paths match the expression are considered part of the pageset. In either case, the part of the URL being matched (called the <em>path</em>) is the part following the domain, less any training slash, and not including the CGI parameters. For example:
<ul>
<li>http://www.example.com/<span class="highlight">articles/index.php</span></li>
<li>http://www.example.com/<span class="highlight">articles/2579</span>?lang=en_US</li>
<li>http://www.example.com/<span class="highlight">articles/selenium</span>/</li>
</ul>
The entire path must match (however, <code>pathPrefix</code> is taken into account if specified). If specified as a regular expression, the two regular expression characters <code>^</code> and <code>$</code> marking the start and end of the matched string are included implicitly, and should not be specified in this string. Please notice too that backslashes must be backslash-escaped in javascript strings.</td>
<td><pre>paths: [
'gotoHome.do'
, 'gotoAbout.do'
, 'gotoFaq.do'
]</pre>
<pre>pathRegexp: 'goto(Home|About|Faq)\\.do'</pre>
</tr>
<tr><td>paramRegexps</td>
<td>No</td>
<td>(Object) a mapping from URL parameter names to regular expression strings which must match their values. If specified, the set of pages potentially included in this pageset will be further filtered by URL parameter values. There is no filtering by parameter value by default.</td>
<td><pre>paramRegexps: {
dept: '^[abcd]$'
, team: 'marketing'
}</pre></td>
</tr>
<tr><td>pageContent</td>
<td>Conditional</td>
<td><p>(Function) a function that tests whether a page, represented by its document object, is contained in the pageset, and returns true if and only if this is the case. If specified, the set of pages potentially included in this pageset will be further filtered by content, after URL and URL parameter filtering.</p>
<p>Since the URL is available from the document object (<code>document.location.href</code>), you may encode the logic used for the <code>paths</code> and <code>pathRegexp</code> attributes all into the definition of <code>pageContent</code>. Thus, you may choose to omit the former if and only if using <code>pageContent</code>. Of course, you may continue to use them for clarity.</td>
<td><pre>pageContent: function(doc) {
var id = 'address-tab';
return doc.getElementById(id) != null;
}</pre></td>
</tr>
</table>
<h3><a name="ui-element-shorthand">UI-Element Shorthand</a></h3>
<p>The method signature of <code>addElement()</code> is <em>(pagesetName, uiElementShorthand)</em>. <em>pagesetName</em> is the name of the pageset the UI element is being added to. <em>uiElementShorthand</em> is a complete JSON description of the UI element object in shorthand notation.</p>
<p>In its simplest form, a UI element object looks like this:</p>
<pre>
map.addElement('allPages', {
name: 'about_link'
, description: 'link to the about page'
, locator: "//a[contains(@href, 'about.php')]"
});
</pre>
<p>Here's a table containing information about the attributes of the UI element object. The asterisk (<code>*</code>) means any string:</p>
<table>
<tr><th>Name</th>
<th>Required?</th>
<th>Description</th>
<th>Example</th>
</tr>
<tr><td>name</td>
<td>Yes</td>
<td>(String) the name of the UI element</td>
<td><pre>name: 'article'</pre></td>
</tr>
<tr><td>description</td>
<td>Yes</td>
<td>(String) a description of the UI element. This is the main documentation for this UI element, so the more detailed, the better.</td>
<td><pre>description: 'front or issue page link to article'</pre></td>
</tr>
<tr><td>args</td>
<td>No</td>
<td>(Array) a list of arguments that modify the <code>getLocator()</code> method. If unspecified, it will be treated as an empty list.</td>
<td><pre>[
{ name: 'index'
, description: 'the index of the author, by article'
, defaultValues: range(1, 5) }
]</pre><em>See section below elaborating on attributes of argument objects.</em></td>
</tr>
<tr><td>locator<br />getLocator()<br /><span class="deprecated">xpath</span<br /><span class="deprecated">getXPath()</span></td>
<td>Yes</td>
<td><p>(String | Function) either a fixed locator string, or a function that returns a locator string given a set of arguments. One or the other should be defined, but not both. Under the sheets, the <code>locator</code> attribute eventually gets transcripted as a <code>getLocator()</code> function.</p><p><span class="deprecated">As of ui0.7, <code>xpath</code> and <code>getXPath()</code> have been deprecated. They are still supported for backward compatibility.</span></p></td>
<td><pre>locator: 'submit'</pre>
<pre>getLocator: function(args) {
return 'css=div.item:nth-child(' + args.index + ')'
+ ' > h5 > a';
}</pre>
<pre>getLocator: function(args) {
var label = args.label;
var id = this._idMap[label];
return '//input[@id=' + id.quoteForXPath() + ']';
}</pre></td>
<tr><td>genericLocator<br />getGenericLocator</td>
<td>No</td>
<td><p>(String | Function) either a fixed locator string, or a function that returns a locator string. If a function, it should take no arguments.</p><p>You may experience some slowdown when recording on pages where individual UI elements have many default locators (due to many permutations of default values over multiple arguments). This is because each default locator is potentially evaluated and matched against the interacted page element. This becomes especially problematic if several UI elements have this characteristic.</p><p>By specifying a generic locator, you give the matching engine a chance to skip over UI elements that definitely don't match. The default locators for skipped elements will not be evaluated unless the generic locator matches the interacted page element..</p></td>
<td><pre>genericLocator: "//table[@class='ctrl']"
+ "/descendant::input"</pre>
<pre>getGenericLocator: function() {
return this._xpathPrefix + '/descendant::a';
}</pre>
</tr>
<tr><td>getOffsetLocator</td>
<td>No</td>
<td><p>(Function) a function that returns an offset locator. The locator is offset from the element identified by a UI specifier string. The function should take this element, and the interacted page element, as arguments, and have the method signature <code>getOffsetLocator(locatedElement, pageElement)</code>. If an offset locator can't be found, a value that evaluates to <code>false</code> must be returned.</p><p>A convenient default function <code>UIElement.defaultOffsetLocatorStrategy</code> is provided so you don't have to define your own. It uses several typical strategies also employed by the IDE recording when recording normally. See the Advanced Topics section below for more information on offset locators.</p></td>
<td><pre>getOffsetLocator: <span class="highlight">UIElement.defaultOffsetLocatorStrategy</span></pre>
<pre>getOffsetLocator:
function(locatedElement, pageElement) {
if (pageElement.parentNode == locatedElement) {
return '/child::' + pageElement.nodeName;
}
return null;
}</pre></td>
<tr><td>testcase*</td>
<td>No</td>
<td>(Object) a testcase for testing the implementation of the <code>getLocator()</code> method. As many testcases as desired may be defined for each UI element. They must all start with the string "testcase".</td>
<td><pre>testcase1: {
xhtml: '&lt;div class="item"&gt;&lt;h5&gt;'
+ '&lt;a expected-result="1" /&gt;&lt;/h5&gt;&lt;/div&gt;'
}</pre><em>See section below elaborating on testcases.</em></td>
</tr>
<tr><td>_*</td>
<td>No</td>
<td>(Any data type) a "local variable" declared for the UI element. This variable will be available both within the <code>getLocator()</code> method of the UI element, and any <code>getDefaultValues()</code> methods of the arguments via the <code>this</code> keyword. They must all start with an underscore "_".</td>
<td><pre>_labelMap: {
'Name': 'user'
, 'Email': 'em'
, 'Phone': 'tel'
}</pre></td>
</tr>
</table>
<h3>UI-Argument Shorthand</h3>
<p>UI arguments are defined as part of UI elements, and help determine how an XPath is generated. A list of arguments may be defined within the UI element JSON shorthand. Here's an example of how that might look:</p>
<pre>
map.addElement('searchPages', {
name: 'result'
, description: 'link to a result page'
, args: [
{
name: 'index'
, description: 'the index of the search result'
, defaultValues: range(1, 21)
}
, {
name: 'type'
, description: 'the type of result page'
, defaultValues: [ 'summary', 'detail' ]
}
]
, getLocator: function(args) {
var index = args['index'];
var type = args['type'];
return "//div[@class='result'][" + index + "]"
+ "/descendant::a[@class='" + type + "']";
}
});
</pre>
<p>In the above example, two arguments are defined, <code>index</code> and <code>type</code>. Metadata is provided to describe them, and default values are also specified. FInally, the <code>getLocator()</code> method is defined. The behavior of the method depends on the values of the arguments that are passed in.</p>
<p>Default values come into play when recording tests using the Selenium IDE. When you interact with a page element in recording mode, the IDE uses all the locator strategies at its disposal to deduce an appropriate locator string for that element. UI-Element introduces a new <code>ui</code> locator strategy. When applying this strategy using a particular UI element, Selenium generates a list of XPaths to try by permuting the arguments of that UI element over all default values. Here, the default values <em>{ 1, 2, 3, 4 .. 20 }</em> are given for the <code>index</code> argument using the special <code>range()</code> function, and the values <em>{ summary, detail }</em> are given for the <code>type</code> argument in standard javascript array notation. If you don't intend to use the IDE, go ahead and set the default values to the empty array <code>[]</code>.</p>
<p>Here's a table containing information about the attributes of the UI argument object.</p>
<table>
<tr><th>Name</th>
<th>Required?</th>
<th>Description</th>
<th>Example</th>
</tr>
<tr><td>name</td>
<td>Yes</td>
<td>(String) the name of the argument. This will be the name of the property of the object passed into the parent UI element's <code>getLocator()</code> method containing the argument value.</td>
<td><pre>name: 'index'</pre></td>
</tr>
<tr><td>description</td>
<td>Yes</td>
<td>(String) a description for the argument.</td>
<td><pre>description: 'the index of the article'</pre></td>
</tr>
<tr><td>defaultValues<br/>getDefaultValues()</td>
<td>Yes</td>
<td><p>(Array | Function) either an array of string or numerical values, or a function that returns an array of string or numerical values. One or the other should be defined, but not both. Under the sheets, the <code>defaultValues</code> attribute eventually gets transcripted as a <code>getDefaultValues()</code> function.</p><p>The method signature of the function is <code>getDefaultValues(inDocument)</code>. <code>inDocument</code> is the current document object of the page at time of recording. In cases where the default values are known a priori, <code>inDocument</code> need not be used. If the default values of all arguments of a UI element are known a priori, the list of default locators for the element may be precalculated, resulting in better performance. If <code>inDocument</code> is used, in cases where the current document is inspected for valid values, the element's default locators are calculated once for every recordable event.</p></td>
<td><pre>defaultValues: [ 'alpha', 'beta', 'unlimited' ]</pre>
<pre>getDefaultValues: function() {
return keys(this._idMap);
}</pre>
<pre>getDefaultValues: function(inDocument) {
var defaultValues = [];
var links = inDocument
.getElementsByTagName('a');
for (var i = 0; i < links.length; ++i) {
var link = links[i];
if (link.className == 'category') {
defaultValues.push(link.innerHTML);
}
}
return defaultValues;
}</pre></td>
</tr>
</table>
<h3>About <code>this</code></h3>
<p>You may have noticed usage of the <code>this</code> keyword in the examples above, specifically in the <code>getLocator()</code> and <code>getDefaultValues()</code> methods. Well, what exactly is <code>this</code>?</p>
<p>The answer is: it depends. The object referred to by <code>this</code> changes depending on the context in which it is being evaluated. At the time of object creation using <code>addPageset()</code> or <code>addElement()</code>, it refers to the <code>window</code> object of the Selenium IDE, which isn't useful at all. However, subsequently any time <code>getLocator()</code> is called, its <code>this</code> references the UI element object it's attached too. Thus, using <code>this</code>, any "local variables" defined for the UI element may be accessed. Similarly, when <code>getDefaultValues()</code> is called, its <code>this</code> references the UI argument object it's attached too. But ... what "local variables" are accessible by the from <code>getDefaultValues()</code>?</p>
<p>There's a little magic here. If you defined your local variables as prescribed in the above <a href="#ui-element-shorthand">UI-Element Shorthand</a> section, starting with an underscore, those variable are automatically made available to the UI argument via its <code>this</code> keyword. Note that this isn't standard javascript behavior. It's implemented this way to clear out clutter in the method definitions and to avoid the use of global variables for lists and maps used within the methods. It is sometimes useful, for example, to define an object that maps human-friendly argument values to DOM element <code>id</code>'s. In such a case, <code>getDefaultValues()</code> can be made to simply return the <code>keys()</code> (or property names) of the map, while the <code>getLocator()</code> method uses the map to retrieve the associated <code>id</code> to involve in the locator.</p>
<p>Also note that <code>this</code> only behaves this way in the two mentioned methods, <code>getLocator()</code> and <code>getDefaultValues()</code>; in other words you can't reference the UI element's local variables using <code>this</code> outside of methods.</p>
<p>If you're interested, here's some <a href="http://www.digital-web.com/articles/scope_in_javascript/">additional reading on javascript scope</a>.</p>
<h2>Advanced Topics</h2>
<h3>Testcases</h3>
<p>You can write testcases for your UI element implementations that are run every time the Selenium IDE is started. Any testcases that fail are reported on. The dual purpose of writing testcases is to both validate the <code>getLocator()</code> method against a representation of the real page under test, and to give a visual example of what the DOM context of a page element is expected to be.</p>
<p>A testcase is an object with a required <code>xhtml</code> property (String), and a required <code>args</code> property (Object). An example is due:</p>
<pre>
testcase1: {
args: { line: 2, column: 3 }
, xhtml: '&lt;table id="scorecard"&gt;'
+ '&lt;tr class="line" /&gt;'
+ '&lt;tr class="line"&gt;&lt;td /&gt;&lt;td /&gt;&lt;td expected-result="1" /&gt;&lt;/tr&gt;'
+ '&lt;/table&gt;'
}
</pre>
<p>The <code>args</code> property specifies the object to be passed into the UI element's <code>getLocator()</code> method to generate the test locator, which is then applied to the <code>xhtml</code>. If evaluating the locator on the XHTML document returns a DOM node with the <code>expected-result</code> attribute, the testcase is considered to have passed.</p>
<p>The <code>xhtml</code> property must represent a complete XML document, sans <code>&lt;html&gt;</code> tags, which are automatically added. The reason this is necessary is that the text is being converted into an XPath evaluable DOM tree via Mozilla's native XML parser. Unfortunately, there is no way to generate a simple HTML document, only XML documents. This means that the content of the <code>xhtml</code> must be well-formed. <span class="highlight">Tags should also be specified in lowercase.</span></p>
<h3>Fuzzy Matching</h3>
<p>Here's a real-world example of where fuzzy matching is important:</p>
<pre>
&lt;table&gt;
&lt;tr onclick="showDetails(0)"&gt;
&lt;td&gt;Brahms&lt;/td&gt;
&lt;td&gt;Viola Quintet&lt;/td&gt;
&lt;/tr&gt;
&lt;tr onclick="showDetails(1)"&gt;
&lt;td&gt;Saegusa&lt;/td&gt;
&lt;td&gt;Cello 88&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
</pre>
<p>Imagine I'm recording in the IDE. Let's say I click on "Cello 88". The IDE would create locator for this action like <code>//table/tr[2]/td[2]</code>. Does that mean that my <code>getLocator()</code> method should return the same XPath?</p>
<p>Clearly not. Clicking on either of the table cells for the second row has the same result. I would like my UI element generated XPath to be <code>//table/tr[2]</code> . However, when recording, the page element that was identified as being acted upon was the table cell, which doesn't match my UI element XPath, so the <code>ui</code> locator strategy will fail to auto-populate. What to do?</p>
<p>Fuzzy matching to the rescue! Fuzzy matching is realized as a fuzzy matcher function that returns true if a target DOM element is considered to be equivalent to a reference DOM element. The reference DOM element would be the element specified by the UI element's generated XPath. Currently, the fuzzy matcher considers it a match if:
<ul>
<li>the elements are the same element,</li>
<li>the reference element is an anchor (<code>&lt;a&gt;</code>) element, and the target element is a descendant of it; or</li>
<li>the reference element has an <code>onclick</code> attribute, and the target element is a descendant of it.</li>
</ul>
<p>This logic may or may not be sufficient for you. The good news is, it's very easy to modify. Look for the definition of <code>BrowserBot.prototype.locateElementByUIElement.is_fuzzy_match</code> in <code>ui-element.js</code> .</p>
<h3>Offset Locators</h3>
<p>Offset locators are locators that are appended to UI specifier strings to form composite locators. They can be automatically deduced by the IDE recorder for UI elements that have specified a <code>getOffsetLocator</code> function. This feature may be useful if your pages contain too many elements to write UI elements for. In this case, offset locators allow you to define UI elements that "anchor" other elements. Given the following markup:</p>
<pre>&lt;form name="contact_info"&gt;
&lt;input type="text" name="foo" /&gt;
&lt;textarea name="bar"&gt;&lt;/textarea&gt;
&lt;input type="submit" value="baz" /&gt;
&lt;/form&gt;</pre>
<p>Assume that a UI element has been defined for the form element. Then the following locators containing offset locators and "anchored" off this element would be recorded using the default offset locator function (<code>UIElement.defaultOffsetLocatorStrategy</code>):</p>
<pre>ui=contactPages::contact_form()<span class="highlight">->//input[@name='foo']</span>
ui=contactPages::contact_form()<span class="highlight">->//textarea[@name='bar']</span>
ui=contactPages::contact_form()<span class="highlight">->//input[@value='baz']</span></pre>
<p>The character sequence <code>-&gt;</code> serves to delimit the offset locator from the main locator. For this reason, the sequence should not appear in the main locator, or else ambiguity will result.</p>
<p>When recording with the IDE, no preference is given to matching plain vanilla UI specifier strings over ones that have offset locators. In other words, if a page element could be specified both by a UI specifier string for one UI element, and by one augmented by an offset locator for a different UI element, there is no guarantee that one or the other locator will be recorded.</p>
<p>Currently, <span class="highlight">only XPath is supported as an offset locator type</span>, as it is the only locator for which a context node can be specified at evaluation time. Other locator strategies may be supported in the future.</p>
<h3>Rollup Rules</h3>
<p>Question: Why use rollup rules? Answer: Remember the testcase from the "Getting Motivated" section above? With rollups, that testcase can be condensed into this:</p>
<pre>
&lt;tr&gt;
&lt;td&gt;open&lt;/td&gt;
&lt;td&gt;/&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;rollup&lt;/td&gt;
&lt;td&gt;<span class="highlight">navigate_to_subtopic_article</span>&lt;/td&gt;
&lt;td&gt;<span class="highlight">index=2, subtopic=Creativity</span>&lt;/td&gt;
&lt;/tr&gt;
</pre>
<p>It's inevitable that certain sequences of Selenium commands will appear in testcases over and over again. When this happens, you might wish to group several fine-grained commands into a single coarser, more semantically meaningful action. In doing so, you would abstract out the execution details for the action, such that if they were to change at some point, you would have a single point of update. In UI-Element, such actions are given their own command, called <code>rollup</code>. In a sense, rollups are a natural extension of the <code>ui</code> locator.</p>
<p>UI-Element is designed with the belief that the IDE can be a useful tool for writing testcases, and need not be shunned for lack of functionality. A corollary belief is that you should be able to drive your RC test in the language of your choice. The execution of the <code>rollup</code> command by the Selenium testrunner produces the component commands, which are executed in a new context, like a function call. The logic of the rollup "expansion" is written in javascript. Corresponding logic for inferring a rollup from a list of commands is also written in javascript. Thus, the logic can be incorporated into any of the family of Selenium products as a user extension. Most notably, the IDE is made viable as a testcase creation tool that understands both how rollups expand to commands, and also how rollup rules can be "applied" to commands to reduce them to rollups.</p>
<p>Rollup rule definitions appear in this general format:</p>
<pre>
var manager = new RollupManager();
manager.addRollupRule({ ... });
manager.addRollupRule({ ... });
...
</pre>
<p>In a relatively simple form, a rollup rule looks like this:</p>
<pre>
manager.addRollupRule({
name: 'do_search'
, description: 'performs a search'
, args: [
name: 'term'
, description: 'the search term'
]
, commandMatchers: [
{
command: 'type'
, target: 'ui=searchPages::search_box\\(.+'
, updateArgs: function(command, args) {
var uiSpecifier = new UISpecifier(command.target);
args.term = uiSpecifier.args.term;
return args;
}
}
, {
command: 'click.+'
, target: 'ui=searchPages::search_go\\(.+'
}
]
, getExpandedCommands: function(args) {
var commands = [];
var uiSpecifier = new UISpecifier(
'searchPages'
, 'search_box'
, { term: args.term });
commands.push({
command: 'type'
, target: 'ui=' + uiSpecifier.toString()
});
commands.push({
command: 'clickAndWait'
, target: 'ui=searchPages::search_go()'
});
return commands;
}
});
</pre>
<p>In the above example, a rollup rule is defined for performing a search. The rule can be "applied" to two consecutive commands that match the <code>commandMatchers</code>. The rollup takes one argument, <code>term</code>, and expands back to the original two commands. One thing to note is that the second command matcher will match all commands starting with <code>click</code>. The rollup will expand that command to a <code>clickAndWait</code>.</p>
<p>Here's a table containing information about the attributes of the rollup rule object.</p>
<table>
<tr><th>Name</th>
<th>Required?</th>
<th>Description</th>
<th>Example</th>
</tr>
<tr><td>name</td>
<td>Yes</td>
<td>(String) the name of the rollup rule. This will be the target of the resulting <code>rollup</code> command.</td>
<td><pre>name: 'do_login'</pre></td>
</tr>
<tr><td>description</td>
<td>Yes</td>
<td>(String) a description for the rollup rule.</td>
<td><pre>description: 'logs into the application'</pre></td>
</tr>
<tr><td>alternateCommand</td>
<td>No</td>
<td>(String) specifies an alternate usage of rollup rules to replace commands. This string is used to replace the command name of the first matched command.</td>
<td><pre>alternateCommand: 'clickAndWait'</pre></td>
</tr>
<tr><td>pre</td>
<td>No</td>
<td>(String) a detailed summary of the preconditions that must be satisfied for the rollup to execute successfully. This metadata is easily viewable in the IDE when the rollup command is selected.</td>
<td><pre>pre: 'the page contains login widgets'</pre></td>
</tr>
<tr><td>post</td>
<td>No</td>
<td>(String) a detailed summary of the postconditions that will exist after the rollup has been executed.</td>
<td><pre>post: 'the user is logged in, or is \
directed to a login error page'</pre></td>
</tr>
<tr><td>args</td>
<td>Conditional</td>
<td><p>(Array) a list of arguments that are used to modify the rollup expansion. These are similar to UI arguments, with the exception that <code>exampleValues</code> are provided, instead of <code>defaultValues</code>. Here, example values are used for reference purposes only; they are displayed in the rollup pane in the IDE.</p><p>This attribute may be omitted if no <code>updateArgs()</code> functions are defined for any command matchers.</td>
<td><pre>args: {
name: 'user'
, description: 'the username to login as'
, exampleValues: [
'John Doe'
, 'Jane Doe'
]
}</pre></td>
</tr>
<tr><td>commandMatchers<br />getRollup()</td>
<td>Yes</td>
<td><p>(Array | Function) a list of command matcher definitions, or a function that, given a list of commands, returns either 1) a rollup command if the rule is considered to match the commands (starting at the first command); or 2) false. If a function, it should have the method signature <code>getRollup(commands)</code>, and the returned rollup command (if any) must have the <code>replacementIndexes</code> attribute, which is a list of array indexes indicating which commands in the <code>commands</code> parameter are to be replaced.</p>
<p>If you don't intend on using the IDE with your rollups, go ahead and set this to the empty array <code>[]</code>.</p></td>
<td><pre>commandMatchers: [
{
command: 'type'
, target: 'ui=loginPages::user\\(.+'
, value: '.+'
, minMatches: 1
, maxMatches: 1
, updateArgs:
function(command, args) {
args.user = command.value;
return args;
}
}
]</pre>
<pre>// this is a simplistic example, roughy
// equivalent to the commandMatchers
// example above. The <span class="highlight">to_kwargs()</span> function
// is used to turn an arguments object into
// a keyword-arguments string.
getRollup: function(commands) {
var command = commands[0];
var re = /^ui=loginPages::user\(.+/;
if (command.command == 'type' &&
re.test(command.target) &&
command.value) {
var args = { user: command.value };
return {
command: 'rollup'
, target: this.name
, value: to_kwargs(args)
, replacementIndexes: [ 0 ]
};
}
return false;
}</pre><em>See section below elaborating on command matcher objects.</em></td>
</tr>
<tr><td>expandedCommands<br />getExpandedCommands()</td>
<td>Yes</td>
<td><p>(Array | Function) a list of commands the rollup command expands into, or a function that, given an argument object mapping argument names to values, returns a list of expanded commands. If a function, it should have the method signature <code>getExpandedCommands(args)</code>.</p><p>Each command in the list of expanded commands should contain a <code>command</code> attribute, which is the name of the command, and optionally <code>target</code> and <code>value</code> attributes, depending on the type of command.</p><p>It is expected that providing a fixed list of expanded commands will be of limited use, as rollups will typically contain commands that have arguments, requiring more sophisticated logic to expand.</td>
<td><pre>expandedCommands: [
{
command: 'check'
, target: 'ui=termsPages::agree\\(.+'
}
, {
command: 'clickAndWait'
, target: 'ui=termsPages::submit\\(.+'
}
]</pre>
<pre>getExpandedCommands: function(args) {
var commands = [];
commands.push({
command: 'type'
, target: 'ui=loginPages::user()'
, value: args.user
});
commands.push({
command: 'type'
, target: 'ui=loginPages::pass()'
, value: args.pass
});
commands.push({
command: 'clickAndWait'
, target: 'ui=loginPages::submit()'
});
commands.push({
command: 'verifyLocation'
, target: 'regexp:.+/home'
});
return commands;
}</pre>
<pre>// if using alternateCommand
expandedCommands: []
</pre></td>
</tr>
</table>
<p>The user should be able to freely record commands in the IDE, which can be collapsed into rollups at any point by applying the defined rollup rules. Healthy usage of the <code>ui</code> locator makes commands easy to match using command matcher definitions. Command matchers simplify the specification of a command match. In basic usage, for a rollup rule, you might specify 3 command matchers: <em>M1</em>, <em>M2</em>, and <em>M3</em>, that you intend to match 3 corresponding commands, <em>C1</em>, <em>C2</em>, and <em>C3</em>. In more complex usage, a single command matcher might match more than one command. For example, <em>M1</em> matches <em>C1</em> and <em>C2</em>, <em>M2</em> matches <em>C3</em>, and <em>M3</em> matches <em>C4</em>, <em>C5</em>, and <em>C6</em>. In the latter case, you would want to track the matches by updating argument values in the command matchers' <code>updateArgs()</code> methods.</p>
<p>Here are the required and optional fields for command matcher objects:</p>
<table>
<tr><th>Name</th>
<th>Required?</th>
<th>Description</th>
<th>Example</th>
</tr>
<tr><td>command</td>
<td>Yes</td>
<td>(String) a simplified regular expression string that matches the command name of a command. The special regexp characters <code>^</code> and <code>$</code> are automatically included at the beginning and end of the string, and therefore should not be explicitly provided.</td>
<td><pre>command: 'click.+'</pre>
<pre>command: 'rollup'</pre></td>
</tr>
<tr><td>target</td>
<td>Yes</td>
<td>(String) a simplified regular expression string that matches the target of a command. Same rules as for the <code>command</code> attribute.</td>
<td><pre>target: 'btnG'</pre>
<pre>// special regexp characters must be
// escaped in regexp strings. Backslashes
// always need to be escaped in javascript
// strings.
target: 'ui=loginPages::user\\(.+'
</pre></td>
</tr>
<tr><td>value</td>
<td>No</td>
<td>(String) a simplified regular expression string that matches the value of a command. Same rules as for the <code>command</code> attribute.</td>
<td><pre>value: '\\d+'</pre>
<pre>value: (?:foo|bar)</pre></td>
</tr>
<tr><td>minMatches</td>
<td>No</td>
<td>(Number) the minimum number of times this command matcher must match consecutive commands for the rollup rule to match a set of commands. If unspecified, the default is 1. If <code>maxMatches</code> is also specified, <code>minMatches</code> must be less than or equal to it.</td>
<td><pre>minMatches: 2</pre></td>
</tr>
<tr><td>maxMatches</td>
<td>No</td>
<td>(Number) the maximum number of times this command matcher is allowed to match consecutive commands for the rollup rule. If unspecified, the default is 1.</td>
<td><pre>maxMatches: 2</pre></td>
</tr>
<tr><td>updateArgs()</td>
<td>No</td>
<td><p>(Function) updates an arguments object when a match has been found, and returns the updated arguments object. This method is used to keep track of the way in which one or more commands were matched. When a rollup rule is successfully applied, any argument name-value pairs are stored as the rollup command's value. At time of expanding the rollup command, the command's value is converted back to an arguments object, which is passed to the rollup rule's <code>getExpandedCommands()</code> method.</p><p>This method must have the following method signature: <code>updateArgs(command, args)</code>, where <code>command</code> is the command object that was just matched, and <code>args</code> is the arguments object for the current trial application of the parent rollup rule.</td>
<td><pre>// reused from above
updateArgs: function(command, args) {
args.user = command.value;
return args;
}</pre>
<pre>// for multiple matches
updateArgs: function(command, args) {
if (!args.clickCount) {
args.clickCount = 0;
}
++args.clickCount;
return args;
}</pre>
<pre>// another example from above (modified).
// If you need to parse a UI specifier,
// instantiate a new <span class="highlight">UISpecifier</span> object with the
// locator. To do it by the book, you should
// first strip off the "ui=" prefix. If you just
// want to inspect the UI specifier's args, you
// can safely skip this step.
updateArgs: function(command, args) {
var s = command.target.replace(/^ui=/, '');
var uiSpecifier = new UISpecifier(s);
args.term = uiSpecifier.args.term;
return args;
}</pre>
<pre>// example from sample map file. If you're
// matching a rollup command that has arguments,
// you'll want to parse them. The easiest way
// to do this is with the <span class="highlight">parse_kwargs()</span>
// function, which has its roots in python.
updateArgs: function(command, args) {
var args1 = parse_kwargs(command.value);
args.subtopic = args1.subtopic;
return args;
}</pre></td>
</tr>
</table>
<p>Too much mumbo jumbo?</p>
<p>To see rollup rules in action in the IDE, use the included sample map with UI-Element (see instructions above in the "Including the Right Files" section), and grab the listing of 4 commands from the "Getting Motivated" section, above. Under the <em>Source</em> tab of the IDE, paste the commands in between the <code>&lt;tbody&gt;</code> and <code>&lt;/tbody&gt;</code> tags. Now switch back to the <em>Table</em> tab, and click the new <span class="highlight">purple spiral button</span>; this is the "Apply rollup rules" button. If done correctly, you should be prompted when rollup rule matches are found. Go ahead - go to the <a href="http://alistapart.com">alistapart.com</a> site and try executing the rollups!</p>
<h2>Release Notes</h2>
<h3>Core-1.0</h3>
<ul>
<li>UI-Element is now completely integrated into Selenium Core.</li>
<li>Added offset locators. Modified the delimiter to be <code>-&gt;</code>.</li>
<li><code>getDefaultValues()</code> can dynamically construct a list of values and assume that a <code>document</code> object is being passed in.</li>
<li>Arguments in UI specifier strings are presented in the same order as they are defined in the mapping file (no longer alphabetically).</li>
<li>Allow generic locators to be specified, potentially improving recording performance when there are many UI arguments.</li>
<li>Updated documentation.</li>
<li>Many other fixes.</li>
</ul>
<h3>ui0.7</h3>
<ul>
<li>Changed extensions id and homepage to avoid conflicting with standard Selenium IDE distribution.</li>
<li>Added rollup button.</li>
<li>Added UI-Element and Rollup panes, with beautiful colors and formatting.</li>
<li>Updated referenced version of Selenium Core to 0.8.3, and RC to 0.9.2 .</li>
<li>Added <code>quoteForXPath()</code> to <code>String</code> prototype.</li>
<li>Made XPath uppercasing much more robust. It is now backed by the ajaxslt library. Uppercasing is no longer required by UI-Element. It is used to demonstrate how XPath transformations may be used to improve XPath evaluation performance when using the javascript engine. See <a href="http://groups.google.com/group/google-ajax-discuss/browse_thread/thread/f7a7a2014a6415d4">this thread on XPath performance</a>.
<li>Added new <code>rollup</code> Selenium command and associated functionality with the RollupManager object.</li>
<li>Deprecated <code>getXPath()</code> and <code>xpath</code> in favor of <code>getLocator()</code> and <code>locator</code> in the UI-Element shorthand. Testcases now work with locator types other than XPath (implicit, CSS, etc.).</li>
<li>UI element testcases are now truly XHTML. All content is considered inner HTML of the html element, which is automatically generated. This supports the use of alternate locator types described in the above bullet.</li>
<li>Global variables introduced by UI-Element are now properties of the variable <code>GLOBAL</code>. You can now name your map <code>uiMap</code> if you wish.</li>
<li>Updated the sample map, including demonstration of implicit and CSS locators, Rollup Rules, and usage of <code>quoteForXPath()</code>.</li>
<li>Improved auto-population of target dropdown with UI element locators and rollup names. The population logic is as follows: when a command is loaded from a file or inserted without having been recorded, all UI element locators are shown. After a command recorded or executed, only UI element locators for pagesets that match the page at time of recording or execution will be shown.</li>
<li>Made UI element testcase args mandatory. This reduces the startup time for the IDE, and improves testcase readability.</li>
<li>Updated documentation. Added this release notes section.</li>
</ul>
<h2>Final Thoughts</h2>
<p>Catch UI-Element news in the <a href="http://ttwhy.org/home/blog/category/selenium/">Selenium category of my blog</a>. You can also find me on the <a href="http://clearspace.openqa.org/people/gyrm">OpenQA Forums</a>.</p>
<p><em>- Haw-Bin Chai</em></p>
</body>
</html>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,979 @@
// sample UI element mapping definition. This is for http://alistapart.com/,
// a particularly well structured site on web design principles.
// in general, the map should capture structural aspects of the system, instead
// of "content". In other words, interactive elements / assertible elements
// that can be counted on to always exist should be defined here. Content -
// for example text or a link that appears in a blog entry - is always liable
// to change, and will not be fun to represent in this way. You probably don't
// want to be testing specific content anyway.
// create the UI mapping object. THIS IS THE MOST IMPORTANT PART - DON'T FORGET
// TO DO THIS! In order for it to come into play, a user extension must
// construct the map in this way.
var myMap = new UIMap();
// any values which may appear multiple times can be defined as variables here.
// For example, here we're enumerating a list of top level topics that will be
// used as default argument values for several UI elements. Check out how
// this variable is referenced further down.
var topics = [
'Code',
'Content',
'Culture',
'Design',
'Process',
'User Science'
];
// map subtopics to their parent topics
var subtopics = {
'Browsers': 'Code'
, 'CSS': 'Code'
, 'Flash': 'Code'
, 'HTML and XHTML': 'Code'
, 'Scripting': 'Code'
, 'Server Side': 'Code'
, 'XML': 'Code'
, 'Brand Arts': 'Content'
, 'Community': 'Content'
, 'Writing': 'Content'
, 'Industry': 'Culture'
, 'Politics and Money': 'Culture'
, 'State of the Web': 'Culture'
, 'Graphic Design': 'Design'
, 'User Interface Design': 'Design'
, 'Typography': 'Design'
, 'Layout': 'Design'
, 'Business': 'Process'
, 'Creativity': 'Process'
, 'Project Management and Workflow': 'Process'
, 'Accessibility': 'User Science'
, 'Information Architecture': 'User Science'
, 'Usability': 'User Science'
};
// define UI elements common for all pages. This regular expression does the
// trick. '^' is automatically prepended, and '$' is automatically postpended.
// Please note that because the regular expression is being represented as a
// string, all backslashes must be escaped with an additional backslash. Also
// note that the URL being matched will always have any trailing forward slash
// stripped.
myMap.addPageset({
name: 'allPages'
, description: 'all alistapart.com pages'
, pathRegexp: '.*'
});
myMap.addElement('allPages', {
name: 'masthead'
// the description should be short and to the point, usually no longer than
// a single line
, description: 'top level image link to site homepage'
// make sure the function returns the XPath ... it's easy to leave out the
// "return" statement by accident!
, locator: "xpath=//*[@id='masthead']/a/img"
, testcase1: {
xhtml: '<h1 id="masthead"><a><img expected-result="1" /></a></h1>'
}
});
myMap.addElement('allPages', {
// be VERY CAREFUL to include commas in the correct place. Missing commas
// and extra commas can cause lots of headaches when debugging map
// definition files!!!
name: 'current_issue'
, description: 'top level link to issue currently being browsed'
, locator: "//div[@id='ish']/a"
, testcase1: {
xhtml: '<div id="ish"><a expected-result="1"></a></div>'
}
});
myMap.addElement('allPages', {
name: 'section'
, description: 'top level link to articles section'
, args: [
{
name: 'section'
, description: 'the name of the section'
, defaultValues: [
'articles'
, 'topics'
, 'about'
, 'contact'
, 'contribute'
, 'feed'
]
}
]
// getXPath has been deprecated by getLocator, but verify backward
// compatability here
, getXPath: function(args) {
return "//li[@id=" + args.section.quoteForXPath() + "]/a";
}
, testcase1: {
args: { section: 'feed' }
, xhtml: '<ul><li id="feed"><a expected-result="1" /></li></ul>'
}
});
myMap.addElement('allPages', {
name: 'search_box'
, description: 'site search input field'
// xpath has been deprecated by locator, but verify backward compatability
, xpath: "//input[@id='search']"
, testcase1: {
xhtml: '<input id="search" expected-result="1" />'
}
});
myMap.addElement('allPages', {
name: 'search_discussions'
, description: 'site search include discussions checkbox'
, locator: 'incdisc'
, testcase1: {
xhtml: '<input id="incdisc" expected-result="1" />'
}
});
myMap.addElement('allPages', {
name: 'search_submit'
, description: 'site search submission button'
, locator: 'submit'
, testcase1: {
xhtml: '<input id="submit" expected-result="1" />'
}
});
myMap.addElement('allPages', {
name: 'topics'
, description: 'sidebar links to topic categories'
, args: [
{
name: 'topic'
, description: 'the name of the topic'
, defaultValues: topics
}
]
, getLocator: function(args) {
return "//div[@id='topiclist']/ul/li" +
"/a[text()=" + args.topic.quoteForXPath() + "]";
}
, testcase1: {
args: { topic: 'foo' }
, xhtml: '<div id="topiclist"><ul><li>'
+ '<a expected-result="1">foo</a>'
+ '</li></ul></div>'
}
});
myMap.addElement('allPages', {
name: 'copyright'
, description: 'footer link to copyright page'
, getLocator: function(args) { return "//span[@class='copyright']/a"; }
, testcase1: {
xhtml: '<span class="copyright"><a expected-result="1" /></span>'
}
});
// define UI elements for the homepage, i.e. "http://alistapart.com/", and
// magazine issue pages, i.e. "http://alistapart.com/issues/234".
myMap.addPageset({
name: 'issuePages'
, description: 'pages including magazine issues'
, pathRegexp: '(issues/.+)?'
});
myMap.addElement('issuePages', {
name: 'article'
, description: 'front or issue page link to article'
, args: [
{
name: 'index'
, description: 'the index of the article'
// an array of default values for the argument. A default
// value is one that is passed to the getXPath() method of
// the container UIElement object when trying to build an
// element locator.
//
// range() may be used to count easily. Remember though that
// the ending value does not include the right extreme; for
// example range(1, 5) counts from 1 to 4 only.
, defaultValues: range(1, 5)
}
]
, getLocator: function(args) {
return "//div[@class='item'][" + args.index + "]/h4/a";
}
});
myMap.addElement('issuePages', {
name: 'author'
, description: 'article author link'
, args: [
{
name: 'index'
, description: 'the index of the author, by article'
, defaultValues: range(1, 5)
}
]
, getLocator: function(args) {
return "//div[@class='item'][" + args.index + "]/h5/a";
}
});
myMap.addElement('issuePages', {
name: 'store'
, description: 'alistapart.com store link'
, locator: "//ul[@id='banners']/li/a[@title='ALA Store']/img"
});
myMap.addElement('issuePages', {
name: 'special_article'
, description: "editor's choice article link"
, locator: "//div[@id='choice']/h4/a"
});
myMap.addElement('issuePages', {
name: 'special_author'
, description: "author link of editor's choice article"
, locator: "//div[@id='choice']/h5/a"
});
// define UI elements for the articles page, i.e.
// "http://alistapart.com/articles"
myMap.addPageset({
name: 'articleListPages'
, description: 'page with article listings'
, paths: [ 'articles' ]
});
myMap.addElement('articleListPages', {
name: 'issue'
, description: 'link to issue'
, args: [
{
name: 'index'
, description: 'the index of the issue on the page'
, defaultValues: range(1, 10)
}
]
, getLocator: function(args) {
return "//h2[@class='ishinfo'][" + args.index + ']/a';
}
, genericLocator: "//h2[@class='ishinfo']/a"
});
myMap.addElement('articleListPages', {
name: 'article'
, description: 'link to article, by issue and article number'
, args: [
{
name: 'issue_index'
, description: "the index of the article's issue on the page; "
+ 'typically five per page'
, defaultValues: range(1, 6)
}
, {
name: 'article_index'
, description: 'the index of the article within the issue; '
+ 'typically two per issue'
, defaultValues: range(1, 5)
}
]
, getLocator: function(args) {
var xpath = "//h2[@class='ishinfo'][" + (args.issue_index || 1) + ']'
+ "/following-sibling::div[@class='item']"
+ '[' + (args.article_index || 1) + "]/h3[@class='title']/a";
return xpath;
}
, genericLocator: "//h2[@class='ishinfo']"
+ "/following-sibling::div[@class='item']/h3[@class='title']/a"
});
myMap.addElement('articleListPages', {
name: 'author'
, description: 'article author link, by issue and article'
, args: [
{
name: 'issue_index'
, description: "the index of the article's issue on the page; \
typically five per page"
, defaultValues: range(1, 6)
}
, {
name: 'article_index'
, description: "the index of the article within the issue; \
typically two articles per issue"
, defaultValues: range(1, 3)
}
]
// this XPath uses the "following-sibling" axis. The div elements for
// the articles in an issue are not children, but siblings of the h2
// element identifying the article.
, getLocator: function(args) {
var xpath = "//h2[@class='ishinfo'][" + (args.issue_index || 1) + ']'
+ "/following-sibling::div[@class='item']"
+ '[' + (args.article_index || 1) + "]/h4[@class='byline']/a";
return xpath;
}
, genericLocator: "//h2[@class='ishinfo']"
+ "/following-sibling::div[@class='item']/h4[@class='byline']/a"
});
myMap.addElement('articleListPages', {
name: 'next_page'
, description: 'link to next page of articles (older)'
, locator: "//a[contains(text(),'Next page')]"
});
myMap.addElement('articleListPages', {
name: 'previous_page'
, description: 'link to previous page of articles (newer)'
, locator: "//a[contains(text(),'Previous page')]"
});
// define UI elements for specific article pages, i.e.
// "http://alistapart.com/articles/culturalprobe"
myMap.addPageset({
name: 'articlePages'
, description: 'pages for actual articles'
, pathRegexp: 'articles/.+'
});
myMap.addElement('articlePages', {
name: 'title'
, description: 'article title loop-link'
, locator: "//div[@id='content']/h1[@class='title']/a"
});
myMap.addElement('articlePages', {
name: 'author'
, description: 'article author link'
, locator: "//div[@id='content']/h3[@class='byline']/a"
});
myMap.addElement('articlePages', {
name: 'article_topics'
, description: 'links to topics under which article is published, before \
article content'
, args: [
{
name: 'topic'
, description: 'the name of the topic'
, defaultValues: keys(subtopics)
}
]
, getLocator: function(args) {
return "//ul[@id='metastuff']/li/a"
+ "[@title=" + args.topic.quoteForXPath() + "]";
}
});
myMap.addElement('articlePages', {
name: 'discuss'
, description: 'link to article discussion area, before article content'
, locator: "//ul[@id='metastuff']/li[@class='discuss']/p/a"
});
myMap.addElement('articlePages', {
name: 'related_topics'
, description: 'links to topics under which article is published, after \
article content'
, args: [
{
name: 'topic'
, description: 'the name of the topic'
, defaultValues: keys(subtopics)
}
]
, getLocator: function(args) {
return "//div[@id='learnmore']/p/a"
+ "[@title=" + args.topic.quoteForXPath() + "]";
}
});
myMap.addElement('articlePages', {
name: 'join_discussion'
, description: 'link to article discussion area, after article content'
, locator: "//div[@class='discuss']/p/a"
});
myMap.addPageset({
name: 'topicListingPages'
, description: 'top level listing of topics'
, paths: [ 'topics' ]
});
myMap.addElement('topicListingPages', {
name: 'topic'
, description: 'link to topic category'
, args: [
{
name: 'topic'
, description: 'the name of the topic'
, defaultValues: topics
}
]
, getLocator: function(args) {
return "//div[@id='content']/h2/a"
+ "[text()=" + args.topic.quoteForXPath() + "]";
}
});
myMap.addElement('topicListingPages', {
name: 'subtopic'
, description: 'link to subtopic category'
, args: [
{
name: 'subtopic'
, description: 'the name of the subtopic'
, defaultValues: keys(subtopics)
}
]
, getLocator: function(args) {
return "//div[@id='content']" +
"/descendant::a[text()=" + args.subtopic.quoteForXPath() + "]";
}
});
// the following few subtopic page UI elements are very similar. Define UI
// elements for the code page, which is a subpage under topics, i.e.
// "http://alistapart.com/topics/code/"
myMap.addPageset({
name: 'subtopicListingPages'
, description: 'pages listing subtopics'
, pathPrefix: 'topics/'
, paths: [
'code'
, 'content'
, 'culture'
, 'design'
, 'process'
, 'userscience'
]
});
myMap.addElement('subtopicListingPages', {
name: 'subtopic'
, description: 'link to a subtopic category'
, args: [
{
name: 'subtopic'
, description: 'the name of the subtopic'
, defaultValues: keys(subtopics)
}
]
, getLocator: function(args) {
return "//div[@id='content']/h2" +
"/a[text()=" + args.subtopic.quoteForXPath() + "]";
}
});
// subtopic articles page
myMap.addPageset({
name: 'subtopicArticleListingPages'
, description: 'pages listing the articles for a given subtopic'
, pathRegexp: 'topics/[^/]+/.+'
});
myMap.addElement('subtopicArticleListingPages', {
name: 'article'
, description: 'link to a subtopic article'
, args: [
{
name: 'index'
, description: 'the index of the article'
, defaultValues: range(1, 51) // the range seems unlimited ...
}
]
, getLocator: function(args) {
return "//div[@id='content']/div[@class='item']"
+ "[" + args.index + "]/h3/a";
}
, testcase1: {
args: { index: 2 }
, xhtml: '<div id="content"><div class="item" /><div class="item">'
+ '<h3><a expected-result="1" /></h3></div></div>'
}
});
myMap.addElement('subtopicArticleListingPages', {
name: 'author'
, description: "link to a subtopic article author's page"
, args: [
{
name: 'article_index'
, description: 'the index of the authored article'
, defaultValues: range(1, 51)
}
, {
name: 'author_index'
, description: 'the index of the author when there are multiple'
, defaultValues: range(1, 4)
}
]
, getLocator: function(args) {
return "//div[@id='content']/div[@class='item'][" +
args.article_index + "]/h4/a[" +
(args.author_index ? args.author_index : '1') + ']';
}
});
myMap.addElement('subtopicArticleListingPages', {
name: 'issue'
, description: 'link to issue a subtopic article appears in'
, args: [
{
name: 'index'
, description: 'the index of the subtopic article'
, defaultValues: range(1, 51)
}
]
, getLocator: function(args) {
return "//div[@id='content']/div[@class='item']"
+ "[" + args.index + "]/h5/a";
}
});
myMap.addPageset({
name: 'aboutPages'
, description: 'the website about page'
, paths: [ 'about' ]
});
myMap.addElement('aboutPages', {
name: 'crew'
, description: 'link to site crew member bio or personal website'
, args: [
{
name: 'role'
, description: 'the role of the crew member'
, defaultValues: [
'ALA Crew'
, 'Support'
, 'Emeritus'
]
}
, {
name: 'role_index'
, description: 'the index of the member within the role'
, defaultValues: range(1, 20)
}
, {
name: 'member_index'
, description: 'the index of the member within the role title'
, defaultValues: range(1, 5)
}
]
, getLocator: function(args) {
// the first role is kind of funky, and requires a conditional to
// build the XPath correctly. Its header looks like this:
//
// <h3>
// <span class="caps">ALA 4</span>.0 <span class="caps">CREW</span>
// </h3>
//
// This kind of complexity is a little daunting, but you can see
// how the format can handle it relatively easily and concisely.
if (args.role == 'ALA Crew') {
var selector = "descendant::text()='CREW'";
}
else {
var selector = "text()=" + args.role.quoteForXPath();
}
var xpath =
"//div[@id='secondary']/h3[" + selector + ']' +
"/following-sibling::dl/dt[" + (args.role_index || 1) + ']' +
'/a[' + (args.member_index || '1') + ']';
return xpath;
}
});
myMap.addPageset({
name: 'searchResultsPages'
, description: 'pages listing search results'
, paths: [ 'search' ]
});
myMap.addElement('searchResultsPages', {
name: 'result_link'
, description: 'search result link'
, args: [
{
name: 'index'
, description: 'the index of the search result'
, defaultValues: range(1, 11)
}
]
, getLocator: function(args) {
return "//div[@id='content']/ul[" + args.index + ']/li/h3/a';
}
});
myMap.addElement('searchResultsPages', {
name: 'more_results_link'
, description: 'next or previous results link at top or bottom of page'
, args: [
{
name: 'direction'
, description: 'next or previous results page'
// demonstrate a method which acquires default values from the
// document object. Such default values may contain EITHER commas
// OR equals signs, but NOT BOTH.
, getDefaultValues: function(inDocument) {
var defaultValues = [];
var divs = inDocument.getElementsByTagName('div');
for (var i = 0; i < divs.length; ++i) {
if (divs[i].className == 'pages') {
break;
}
}
var links = divs[i].getElementsByTagName('a');
for (i = 0; i < links.length; ++i) {
defaultValues.push(links[i].innerHTML
.replace(/^\xab\s*/, "")
.replace(/\s*\bb$/, "")
.replace(/\s*\d+$/, ""));
}
return defaultValues;
}
}
, {
name: 'position'
, description: 'position of the link'
, defaultValues: ['top', 'bottom']
}
]
, getLocator: function(args) {
return "//div[@id='content']/div[@class='pages']["
+ (args.position == 'top' ? '1' : '2') + ']'
+ "/a[contains(text(), "
+ (args.direction ? args.direction.quoteForXPath() : undefined)
+ ")]";
}
});
myMap.addPageset({
name: 'commentsPages'
, description: 'pages listing comments made to an article'
, pathRegexp: 'comments/.+'
});
myMap.addElement('commentsPages', {
name: 'article_link'
, description: 'link back to the original article'
, locator: "//div[@id='content']/h1[@class='title']/a"
});
myMap.addElement('commentsPages', {
name: 'comment_link'
, description: 'same-page link to comment'
, args: [
{
name: 'index'
, description: 'the index of the comment'
, defaultValues: range(1, 11)
}
]
, getLocator: function(args) {
return "//div[@class='content']/div[contains(@class, 'comment')]" +
'[' + args.index + ']/h4/a[2]';
}
});
myMap.addElement('commentsPages', {
name: 'paging_link'
, description: 'links to more pages of comments'
, args: [
{
name: 'dest'
, description: 'the destination page'
, defaultValues: ['next', 'prev'].concat(range(1, 16))
}
, {
name: 'position'
, description: 'position of the link'
, defaultValues: ['top', 'bottom']
}
]
, getLocator: function(args) {
var dest = args.dest;
var xpath = "//div[@id='content']/div[@class='pages']" +
'[' + (args.position == 'top' ? '1' : '2') + ']/p';
if (dest == 'next' || dest == 'prev') {
xpath += "/a[contains(text(), " + dest.quoteForXPath() + ")]";
}
else {
xpath += "/a[text()=" + dest.quoteForXPath() + "]";
}
return xpath;
}
});
myMap.addPageset({
name: 'authorPages'
, description: 'personal pages for each author'
, pathRegexp: 'authors/[a-z]/.+'
});
myMap.addElement('authorPages', {
name: 'article'
, description: "link to article written by this author.\n"
+ 'This description has a line break.'
, args: [
{
name: 'index'
, description: 'index of the article on the page'
, defaultValues: range(1, 11)
}
]
, getLocator: function(args) {
var index = args.index;
// try out the CSS locator!
//return "//h4[@class='title'][" + index + "]/a";
return 'css=h4.title:nth-child(' + index + ') > a';
}
, testcase1: {
args: { index: '2' }
, xhtml: '<h4 class="title" /><h4 class="title">'
+ '<a expected-result="1" /></h4>'
}
});
// test the offset locator. Something like the following can be recorded:
// ui=qaPages::content()//a[contains(text(),'May I quote from your articles?')]
myMap.addPageset({
name: 'qaPages'
, description: 'question and answer pages'
, pathRegexp: 'qa'
});
myMap.addElement('qaPages', {
name: 'content'
, description: 'the content pane containing the q&a entries'
, locator: "//div[@id='content' and "
+ "child::h1[text()='Questions and Answers']]"
, getOffsetLocator: UIElement.defaultOffsetLocatorStrategy
});
myMap.addElement('qaPages', {
name: 'last_updated'
, description: 'displays the last update date'
// demonstrate calling getLocator() for another UI element within a
// getLocator(). The former must have already been added to the map. And
// obviously, you can't randomly combine different locator types!
, locator: myMap.getUIElement('qaPages', 'content').getLocator() + '/p/em'
});
//******************************************************************************
var myRollupManager = new RollupManager();
// though the description element is required, its content is free form. You
// might want to create a documentation policy as given below, where the pre-
// and post-conditions of the rollup are spelled out.
//
// To take advantage of a "heredoc" like syntax for longer descriptions,
// add a backslash to the end of the current line and continue the string on
// the next line.
myRollupManager.addRollupRule({
name: 'navigate_to_subtopic_article_listing'
, description: 'drill down to the listing of articles for a given subtopic \
from the section menu, then the topic itself.'
, pre: 'current page contains the section menu (most pages should)'
, post: 'navigated to the page listing all articles for a given subtopic'
, args: [
{
name: 'subtopic'
, description: 'the subtopic whose article listing to navigate to'
, exampleValues: keys(subtopics)
}
]
, commandMatchers: [
{
command: 'clickAndWait'
, target: 'ui=allPages::section\\(section=topics\\)'
// must escape parentheses in the the above target, since the
// string is being used as a regular expression. Again, backslashes
// in strings must be escaped too.
}
, {
command: 'clickAndWait'
, target: 'ui=topicListingPages::topic\\(.+'
}
, {
command: 'clickAndWait'
, target: 'ui=subtopicListingPages::subtopic\\(.+'
, updateArgs: function(command, args) {
// don't bother stripping the "ui=" prefix from the locator
// here; we're just using UISpecifier to parse the args out
var uiSpecifier = new UISpecifier(command.target);
args.subtopic = uiSpecifier.args.subtopic;
return args;
}
}
]
, getExpandedCommands: function(args) {
var commands = [];
var topic = subtopics[args.subtopic];
var subtopic = args.subtopic;
commands.push({
command: 'clickAndWait'
, target: 'ui=allPages::section(section=topics)'
});
commands.push({
command: 'clickAndWait'
, target: 'ui=topicListingPages::topic(topic=' + topic + ')'
});
commands.push({
command: 'clickAndWait'
, target: 'ui=subtopicListingPages::subtopic(subtopic=' + subtopic
+ ')'
});
commands.push({
command: 'verifyLocation'
, target: 'regexp:.+/topics/.+/.+'
});
return commands;
}
});
myRollupManager.addRollupRule({
name: 'replace_click_with_clickAndWait'
, description: 'replaces commands where a click was detected with \
clickAndWait instead'
, alternateCommand: 'clickAndWait'
, commandMatchers: [
{
command: 'click'
, target: 'ui=subtopicArticleListingPages::article\\(.+'
}
]
, expandedCommands: []
});
myRollupManager.addRollupRule({
name: 'navigate_to_subtopic_article'
, description: 'navigate to an article listed under a subtopic.'
, pre: 'current page contains the section menu (most pages should)'
, post: 'navigated to an article page'
, args: [
{
name: 'subtopic'
, description: 'the subtopic whose article listing to navigate to'
, exampleValues: keys(subtopics)
}
, {
name: 'index'
, description: 'the index of the article in the listing'
, exampleValues: range(1, 11)
}
]
, commandMatchers: [
{
command: 'rollup'
, target: 'navigate_to_subtopic_article_listing'
, value: 'subtopic\\s*=.+'
, updateArgs: function(command, args) {
var args1 = parse_kwargs(command.value);
args.subtopic = args1.subtopic;
return args;
}
}
, {
command: 'clickAndWait'
, target: 'ui=subtopicArticleListingPages::article\\(.+'
, updateArgs: function(command, args) {
var uiSpecifier = new UISpecifier(command.target);
args.index = uiSpecifier.args.index;
return args;
}
}
]
/*
// this is pretty much equivalent to the commandMatchers immediately above.
// Seems more verbose and less expressive, doesn't it? But sometimes you
// might prefer the flexibility of a function.
, getRollup: function(commands) {
if (commands.length >= 2) {
command1 = commands[0];
command2 = commands[1];
var args1 = parse_kwargs(command1.value);
try {
var uiSpecifier = new UISpecifier(command2.target
.replace(/^ui=/, ''));
}
catch (e) {
return false;
}
if (command1.command == 'rollup' &&
command1.target == 'navigate_to_subtopic_article_listing' &&
args1.subtopic &&
command2.command == 'clickAndWait' &&
uiSpecifier.pagesetName == 'subtopicArticleListingPages' &&
uiSpecifier.elementName == 'article') {
var args = {
subtopic: args1.subtopic
, index: uiSpecifier.args.index
};
return {
command: 'rollup'
, target: this.name
, value: to_kwargs(args)
, replacementIndexes: [ 0, 1 ]
};
}
}
return false;
}
*/
, getExpandedCommands: function(args) {
var commands = [];
commands.push({
command: 'rollup'
, target: 'navigate_to_subtopic_article_listing'
, value: to_kwargs({ subtopic: args.subtopic })
});
var uiSpecifier = new UISpecifier(
'subtopicArticleListingPages'
, 'article'
, { index: args.index });
commands.push({
command: 'clickAndWait'
, target: 'ui=' + uiSpecifier.toString()
});
commands.push({
command: 'verifyLocation'
, target: 'regexp:.+/articles/.+'
});
return commands;
}
});