Skip to content
Browse files

Quality: removed unnecessary blank lines and used spaces for indents …

…in stead of tabs
  • Loading branch information...
1 parent bd91233 commit 0d0446b088d54627302fb5190c8cd2afcc500d4a awulder committed Feb 26, 2013
Showing with 2,113 additions and 2,142 deletions.
  1. +3 −3 src/main/java/com/xebia/incubator/xebium/AssertionAndStopTestError.java
  2. +3 −3 src/main/java/com/xebia/incubator/xebium/ConfigurableWebDriverSupplier.java
  3. +95 −96 src/main/java/com/xebia/incubator/xebium/DefaultWebDriverSupplier.java
  4. +341 −343 src/main/java/com/xebia/incubator/xebium/ExtendedSeleniumCommand.java
  5. +47 −49 src/main/java/com/xebia/incubator/xebium/FitNesseUtil.java
  6. +66 −81 src/main/java/com/xebia/incubator/xebium/HttpCommandProcessorAdapter.java
  7. +36 −37 src/main/java/com/xebia/incubator/xebium/LocatorCheck.java
  8. +62 −64 src/main/java/com/xebia/incubator/xebium/RemoteWebDriverSupplier.java
  9. +148 −151 src/main/java/com/xebia/incubator/xebium/ScreenCapture.java
  10. +63 −63 src/main/java/com/xebia/incubator/xebium/SeleneseScriptFixture.java
  11. +447 −447 src/main/java/com/xebia/incubator/xebium/SeleniumDriverFixture.java
  12. +50 −50 src/main/java/com/xebia/incubator/xebium/SeleniumServerFixture.java
  13. +3 −6 src/main/java/org/openqa/selenium/firefox/PreferencesWrapper.java
  14. +367 −367 src/test/java/com/xebia/fitnesse/selenium/JavascriptTestCase.java
  15. +198 −198 src/test/java/com/xebia/incubator/xebium/ExtendedSeleniumCommandTest.java
  16. +8 −8 src/test/java/com/xebia/incubator/xebium/FitNesseUtilTest.java
  17. +23 −23 src/test/java/com/xebia/incubator/xebium/RemoteWebDriverBuilderTest.java
  18. +22 −22 src/test/java/com/xebia/incubator/xebium/SeleneseScriptFixtureTest.java
  19. +45 −45 src/test/java/com/xebia/incubator/xebium/SeleniumDriverFixtureIntegrationTest.java
  20. +38 −38 src/test/java/com/xebia/incubator/xebium/SeleniumDriverFixtureTest.java
  21. +48 −48 src/test/java/com/xebia/incubator/xebium/WebDriverTest.java
View
6 src/main/java/com/xebia/incubator/xebium/AssertionAndStopTestError.java
@@ -19,8 +19,8 @@
public class AssertionAndStopTestError extends AssertionError {
- public AssertionAndStopTestError(Object detailMessage) {
- super(detailMessage);
- }
+ public AssertionAndStopTestError(Object detailMessage) {
+ super(detailMessage);
+ }
}
View
6 src/main/java/com/xebia/incubator/xebium/ConfigurableWebDriverSupplier.java
@@ -25,9 +25,9 @@
*/
public interface ConfigurableWebDriverSupplier {
- public void setBrowser(String browser);
+ public void setBrowser(String browser);
- public void setCustomProfilePreferencesFile(File customProfilePreferencesFile);
+ public void setCustomProfilePreferencesFile(File customProfilePreferencesFile);
- public void setProfileDirectory(File profileDirectory);
+ public void setProfileDirectory(File profileDirectory);
}
View
191 src/main/java/com/xebia/incubator/xebium/DefaultWebDriverSupplier.java
@@ -40,59 +40,58 @@
public class DefaultWebDriverSupplier implements ConfigurableWebDriverSupplier {
- private static final Logger LOG = LoggerFactory.getLogger(SeleniumDriverFixture.class);
+ private static final Logger LOG = LoggerFactory.getLogger(SeleniumDriverFixture.class);
- private String browser;
+ private String browser;
private File customProfilePreferencesFile;
- private File profileDirectory;
-
- public DefaultWebDriverSupplier() {
- }
-
- public WebDriver newWebDriver() {
- WebDriver driver;
- if ("firefox".equalsIgnoreCase(browser)) {
- FirefoxProfile profile;
- // Load FireFox-profile if present
- if (profileDirectory != null) {
- profile = new FirefoxProfile(profileDirectory);
- LOG.info("Firefox profile successfully loaded");
- }
- else {
- profile = new FirefoxProfile();
- }
-
- if (customProfilePreferencesFile != null) {
- PreferencesWrapper prefs = loadFirefoxPreferences();
-
- prefs.addTo(profile);
- try {
- StringWriter writer = new StringWriter(512);
- prefs.writeTo(writer);
- LOG.info("Added properties to firefox profile: " + writer.toString());
- } catch (IOException e) {
- LOG.error("Unable to log firefox profile settings", e);
- }
- }
-
- // Ensure we deal with untrusted and unverified hosts.
- profile.setAcceptUntrustedCertificates(true);
- profile.setAssumeUntrustedCertificateIssuer(true);
-
- driver = new FirefoxDriver(profile);
- } else if ("iexplore".equalsIgnoreCase(browser)) {
- driver = new InternetExplorerDriver();
- } else if ("chrome".equalsIgnoreCase(browser)) {
- driver = new ChromeDriver();
- } else if ("safari".equalsIgnoreCase(browser)) {
- driver = new SafariDriver();
- } else if ("htmlUnit".equalsIgnoreCase(browser)) {
- driver = new HtmlUnitDriver();
- } else if ("htmlUnit+js".equalsIgnoreCase(browser)) {
- driver = new HtmlUnitDriver(true);
- } else if ("opera".equalsIgnoreCase(browser)) {
+ private File profileDirectory;
+
+ public DefaultWebDriverSupplier() {
+ }
+
+ public WebDriver newWebDriver() {
+ WebDriver driver;
+ if ("firefox".equalsIgnoreCase(browser)) {
+ FirefoxProfile profile;
+ // Load FireFox-profile if present
+ if (profileDirectory != null) {
+ profile = new FirefoxProfile(profileDirectory);
+ LOG.info("Firefox profile successfully loaded");
+ } else {
+ profile = new FirefoxProfile();
+ }
+
+ if (customProfilePreferencesFile != null) {
+ PreferencesWrapper prefs = loadFirefoxPreferences();
+
+ prefs.addTo(profile);
+ try {
+ StringWriter writer = new StringWriter(512);
+ prefs.writeTo(writer);
+ LOG.info("Added properties to firefox profile: " + writer.toString());
+ } catch (IOException e) {
+ LOG.error("Unable to log firefox profile settings", e);
+ }
+ }
+
+ // Ensure we deal with untrusted and unverified hosts.
+ profile.setAcceptUntrustedCertificates(true);
+ profile.setAssumeUntrustedCertificateIssuer(true);
+
+ driver = new FirefoxDriver(profile);
+ } else if ("iexplore".equalsIgnoreCase(browser)) {
+ driver = new InternetExplorerDriver();
+ } else if ("chrome".equalsIgnoreCase(browser)) {
+ driver = new ChromeDriver();
+ } else if ("safari".equalsIgnoreCase(browser)) {
+ driver = new SafariDriver();
+ } else if ("htmlUnit".equalsIgnoreCase(browser)) {
+ driver = new HtmlUnitDriver();
+ } else if ("htmlUnit+js".equalsIgnoreCase(browser)) {
+ driver = new HtmlUnitDriver(true);
+ } else if ("opera".equalsIgnoreCase(browser)) {
driver = new OperaDriver();
} else if ("opera-mobile-tablet".equalsIgnoreCase(browser)) {
DesiredCapabilities capabilities = DesiredCapabilities.opera();
@@ -112,52 +111,52 @@ public WebDriver newWebDriver() {
driver = new OperaDriver(capabilities);
} else if ("phantomjs".equalsIgnoreCase(browser)) {
driver = new PhantomJSDriver(DesiredCapabilities.phantomjs());
- } else {
- try {
- driver = new RemoteWebDriverSupplier(browser).get();
- } catch (Exception e) {
- throw new RuntimeException("Unknown browser type. Should be one of 'firefox', 'iexplore', 'chrome', " +
+ } else {
+ try {
+ driver = new RemoteWebDriverSupplier(browser).get();
+ } catch (Exception e) {
+ throw new RuntimeException("Unknown browser type. Should be one of 'firefox', 'iexplore', 'chrome', " +
"'opera', 'opera-mobile-tablet', 'opera-mobile-phone', 'htmlUnit' or 'htmlUnit+js'", e);
- }
- }
- return driver;
- }
-
- private PreferencesWrapper loadFirefoxPreferences() {
- PreferencesWrapper prefs;
- FileReader reader;
- try {
- reader = new FileReader(customProfilePreferencesFile);
- } catch (FileNotFoundException e) {
- throw new RuntimeException(e);
- }
- try {
- prefs = new PreferencesWrapper(reader);
- } finally {
- try {
- reader.close();
- } catch (IOException e) {
- LOG.error("Unable to close firefox profile settings file", e);
- }
- }
- return prefs;
- }
-
- public void setBrowser(String browser) {
- this.browser = browser;
- }
-
- public void setCustomProfilePreferencesFile(
- File customProfilePreferencesFile) {
- this.customProfilePreferencesFile = customProfilePreferencesFile;
- }
-
- public void setProfileDirectory(File profileDirectory) {
- this.profileDirectory = profileDirectory;
- }
-
- @Override
- public String toString() {
- return getClass().getName();
- }
+ }
+ }
+ return driver;
+ }
+
+ private PreferencesWrapper loadFirefoxPreferences() {
+ PreferencesWrapper prefs;
+ FileReader reader;
+ try {
+ reader = new FileReader(customProfilePreferencesFile);
+ } catch (FileNotFoundException e) {
+ throw new RuntimeException(e);
+ }
+ try {
+ prefs = new PreferencesWrapper(reader);
+ } finally {
+ try {
+ reader.close();
+ } catch (IOException e) {
+ LOG.error("Unable to close firefox profile settings file", e);
+ }
+ }
+ return prefs;
+ }
+
+ public void setBrowser(String browser) {
+ this.browser = browser;
+ }
+
+ public void setCustomProfilePreferencesFile(
+ File customProfilePreferencesFile) {
+ this.customProfilePreferencesFile = customProfilePreferencesFile;
+ }
+
+ public void setProfileDirectory(File profileDirectory) {
+ this.profileDirectory = profileDirectory;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getName();
+ }
}
View
684 src/main/java/com/xebia/incubator/xebium/ExtendedSeleniumCommand.java
@@ -27,145 +27,144 @@
/**
* This class provides calls to all operations defined in the Selenium IDE.
- *
- * @author arjan
*
+ * @author arjan
*/
public class ExtendedSeleniumCommand {
- private static final String GET = "get";
-
- private static final String IS = "is";
-
- private static final String STORE = "store";
-
- private static final String VERIFY = "verify";
-
- private static final String ASSERT = "assert";
-
- private static final String WAIT_FOR = "waitFor";
-
- private static final String AND_WAIT = "AndWait";
-
- // Matching types
- private static final String REGEXP = "regexp:";
- private static final String REGEXPI = "regexpi:";
- private static final String EXACT = "exact:";
- private static final String GLOB = "glob:";
-
- // keywords copied from org.openqa.selenium.WebDriverCommandProcessor
- private static final Set<String> WEB_DRIVER_COMMANDS = new HashSet<String>(Arrays.asList(new String[] {
- "addLocationStrategy",
- "addSelection", // loc
- "altKeyDown",
- "altKeyUp",
- "assignId", // loc
- "attachFile",
- "captureScreenshotToString",
- "click", // loc
- "check", // loc
- "chooseCancelOnNextConfirmation",
- "chooseOkOnNextConfirmation",
- "close",
- "createCookie",
- "controlKeyDown",
- "controlKeyUp",
- "deleteAllVisibleCookies",
- "deleteCookie",
- "doubleClick", // loc
- "dragdrop", // loc
- "dragAndDrop", // loc
- "dragAndDropToObject", // loc, loc
- "fireEvent",
- "focus", // loc
- "getAlert",
- "getAllButtons", // arr
- "getAllFields", // arr
- "getAllLinks", // arr
- "getAllWindowTitles", // arr
- "getAttribute",
- "getAttributeFromAllWindows", // arr
- "getBodyText",
- "getConfirmation",
- "getCookie",
- "getCookieByName",
- "getCssCount", // num
- "getElementHeight", // num
- "getElementIndex", // num
- "getElementPositionLeft", // num
- "getElementPositionTop", // num
- "getElementWidth", // num
- "getEval",
- "getExpression",
- "getHtmlSource",
- "getLocation",
- "getSelectedId",
- "getSelectedIds", // arr
- "getSelectedIndex",
- "getSelectedIndexes", // arr
- "getSelectedLabel",
- "getSelectedLabels", // arr
- "getSelectedValue",
- "getSelectedValues", // arr
- "getSelectOptions", // arr
- "getSpeed",
- "getTable",
- "getText",
- "getTitle",
- "getValue",
- "getXpathCount",
- "goBack",
- "highlight", // loc
- "isAlertPresent",
- "isChecked",
- "isConfirmationPresent",
- "isCookiePresent",
- "isEditable",
- "isElementPresent",
- "isOrdered",
- "isSomethingSelected",
- "isTextPresent",
- "isVisible",
- "keyDown",
- "keyPress",
- "keyUp",
- "metaKeyDown",
- "metaKeyUp",
- "mouseOver",
- "mouseOut",
- "mouseDown",
- "mouseDownAt",
- "mouseMove",
- "mouseMoveAt",
- "mouseUp",
- "mouseUpAt",
- "open",
- "openWindow",
- "refresh",
- "removeAllSelections",
- "removeSelection", // loc
- "runScript",
- "select", // loc
- "selectFrame",
- "selectWindow",
- "setBrowserLogLevel",
- "setContext",
- "setSpeed",
- "setTimeout",
- "shiftKeyDown",
- "shiftKeyUp",
- "submit", // loc
- "type", // loc
- "typeKeys", // loc
- "uncheck", // loc
- "useXpathLibrary",
- "waitForCondition",
- "waitForFrameToLoad",
- "waitForPageToLoad",
- "waitForPopUp",
- "windowFocus",
- "windowMaximize"
- }));
+ private static final String GET = "get";
+
+ private static final String IS = "is";
+
+ private static final String STORE = "store";
+
+ private static final String VERIFY = "verify";
+
+ private static final String ASSERT = "assert";
+
+ private static final String WAIT_FOR = "waitFor";
+
+ private static final String AND_WAIT = "AndWait";
+
+ // Matching types
+ private static final String REGEXP = "regexp:";
+ private static final String REGEXPI = "regexpi:";
+ private static final String EXACT = "exact:";
+ private static final String GLOB = "glob:";
+
+ // keywords copied from org.openqa.selenium.WebDriverCommandProcessor
+ private static final Set<String> WEB_DRIVER_COMMANDS = new HashSet<String>(Arrays.asList(new String[] {
+ "addLocationStrategy",
+ "addSelection", // loc
+ "altKeyDown",
+ "altKeyUp",
+ "assignId", // loc
+ "attachFile",
+ "captureScreenshotToString",
+ "click", // loc
+ "check", // loc
+ "chooseCancelOnNextConfirmation",
+ "chooseOkOnNextConfirmation",
+ "close",
+ "createCookie",
+ "controlKeyDown",
+ "controlKeyUp",
+ "deleteAllVisibleCookies",
+ "deleteCookie",
+ "doubleClick", // loc
+ "dragdrop", // loc
+ "dragAndDrop", // loc
+ "dragAndDropToObject", // loc, loc
+ "fireEvent",
+ "focus", // loc
+ "getAlert",
+ "getAllButtons", // arr
+ "getAllFields", // arr
+ "getAllLinks", // arr
+ "getAllWindowTitles", // arr
+ "getAttribute",
+ "getAttributeFromAllWindows", // arr
+ "getBodyText",
+ "getConfirmation",
+ "getCookie",
+ "getCookieByName",
+ "getCssCount", // num
+ "getElementHeight", // num
+ "getElementIndex", // num
+ "getElementPositionLeft", // num
+ "getElementPositionTop", // num
+ "getElementWidth", // num
+ "getEval",
+ "getExpression",
+ "getHtmlSource",
+ "getLocation",
+ "getSelectedId",
+ "getSelectedIds", // arr
+ "getSelectedIndex",
+ "getSelectedIndexes", // arr
+ "getSelectedLabel",
+ "getSelectedLabels", // arr
+ "getSelectedValue",
+ "getSelectedValues", // arr
+ "getSelectOptions", // arr
+ "getSpeed",
+ "getTable",
+ "getText",
+ "getTitle",
+ "getValue",
+ "getXpathCount",
+ "goBack",
+ "highlight", // loc
+ "isAlertPresent",
+ "isChecked",
+ "isConfirmationPresent",
+ "isCookiePresent",
+ "isEditable",
+ "isElementPresent",
+ "isOrdered",
+ "isSomethingSelected",
+ "isTextPresent",
+ "isVisible",
+ "keyDown",
+ "keyPress",
+ "keyUp",
+ "metaKeyDown",
+ "metaKeyUp",
+ "mouseOver",
+ "mouseOut",
+ "mouseDown",
+ "mouseDownAt",
+ "mouseMove",
+ "mouseMoveAt",
+ "mouseUp",
+ "mouseUpAt",
+ "open",
+ "openWindow",
+ "refresh",
+ "removeAllSelections",
+ "removeSelection", // loc
+ "runScript",
+ "select", // loc
+ "selectFrame",
+ "selectWindow",
+ "setBrowserLogLevel",
+ "setContext",
+ "setSpeed",
+ "setTimeout",
+ "shiftKeyDown",
+ "shiftKeyUp",
+ "submit", // loc
+ "type", // loc
+ "typeKeys", // loc
+ "uncheck", // loc
+ "useXpathLibrary",
+ "waitForCondition",
+ "waitForFrameToLoad",
+ "waitForPageToLoad",
+ "waitForPopUp",
+ "windowFocus",
+ "windowMaximize"
+ }));
// GetCssCount.java
// GetElementHeight.java
@@ -175,213 +174,212 @@
// GetElementWidth.java
// GetXpathCount.java
- // Commands that return
- private static final Set<String> ARRAY_COMMANDS = new HashSet<String>(Arrays.asList(new String[] {
- "getAllButtons", // arr
- "getAllFields", // arr
- "getAllLinks", // arr
- "getAllWindowTitles", // arr
- "getAttributeFromAllWindows", // arr
- "getSelectedIds", // arr
- "getSelectedIndexes", // arr
- "getSelectedLabels", // arr
- "getSelectedValues", // arr
- "getSelectOptions" // arr
- }));
-
- private String methodName;
-
- // The real selenium command name, assigned by getSeleniumCommand() on first invocation.
- private String seleniumCommandName;
-
- public ExtendedSeleniumCommand(String methodName) {
- this.methodName = methodName;
- }
-
- public static boolean isSupportedByWebDriver(String methodName) {
- return WEB_DRIVER_COMMANDS.contains(methodName);
- }
-
- public boolean isWaitForCommand() {
- return methodName.startsWith(WAIT_FOR) && !isSupportedByWebDriver(methodName);
- }
-
- /**
- * Command is a "waitFor-" command, but is not supported natively by Selenium,
- * hence it should act as "verify-" command and in case of failure retries
- * should be done.
- *
- * @return
- */
- public boolean requiresPolling() {
- return isWaitForCommand() && !isSupportedByWebDriver(methodName);
- }
-
- public boolean isAndWaitCommand() {
- return methodName.endsWith(AND_WAIT);
- }
-
- // TODO: process this in JS
- public boolean isNegateCommand() {
- return methodName.matches(".*[a-z]Not[A-Z].*");
- }
-
- public boolean isAssertCommand() {
- return methodName.startsWith(ASSERT);
- }
-
- public boolean isVerifyCommand() {
- return methodName.startsWith(VERIFY);
- }
-
- public boolean isStoreCommand() {
- return methodName.startsWith(STORE);
- }
-
- public boolean isCaptureEntirePageScreenshotCommand() {
- return methodName.startsWith("captureEntirePageScreenshot");
- }
-
- public boolean isBooleanCommand() {
- return getSeleniumCommand().startsWith(IS);
- }
-
- public String getSeleniumCommand() {
-
- // fast track: once resolved return the previous value.
- if (seleniumCommandName != null) {
- return seleniumCommandName;
- }
-
- // for commands like "waitForCondition"
- if (isSupportedByWebDriver(methodName)) {
- seleniumCommandName = methodName;
- return methodName;
- }
-
- String seleniumName = methodName;
-
- if (isAssertCommand() || isVerifyCommand() || isStoreCommand() || isWaitForCommand()) {
- String noun = seleniumName;
-
- if (isNegateCommand()) {
- //noun = noun.substring(0, noun.length() - NOT_PRESENT.length()) + "Present";
- noun = noun.replaceAll("([a-z])Not([A-Z])", "$1$2");
- }
-
- // ASSERT.length() == VERIFY.length()
- noun = noun.substring(isStoreCommand() ? STORE.length() :
- (isWaitForCommand() ? WAIT_FOR.length() : ASSERT.length()));
-
- if (isSupportedByWebDriver(IS + noun)) {
- seleniumName = IS + noun;
- } else if (isSupportedByWebDriver(GET + noun)) {
- seleniumName = GET + noun;
- }
- } else if (isCaptureEntirePageScreenshotCommand()) {
- seleniumName = "captureScreenshotToString";
- }
-
- if (isAndWaitCommand()) {
- seleniumName = seleniumName.substring(0, seleniumName.length() - AND_WAIT.length());
- }
-
- seleniumCommandName = seleniumName;
-
- return seleniumName;
- }
-
- /**
- * <p><i>(From the Selenium docs)</i></p>
- * <p>
- * Various Pattern syntaxes are available for matching string values:
- * </p>
- * <ul>
- * <li><strong>glob:</strong><em>pattern</em>: Match a string against a
- * "glob" (aka "wildmat") pattern. "Glob" is a kind of limited
- * regular-expression syntax typically used in command-line shells. In a
- * glob pattern, "*" represents any sequence of characters, and "?"
- * represents any single character. Glob patterns match against the entire
- * string.</li>
- * <li><strong>regexp:</strong><em>regexp</em>: Match a string using a
- * regular-expression. The full power of JavaScript regular-expressions is
- * available.</li>
- * <li><strong>regexpi:</strong><em>regexpi</em>: Match a string using a
- * case-insensitive regular-expression.</li>
- * <li><strong>exact:</strong><em>string</em>:
- *
- * Match a string exactly, verbatim, without any of that fancy wildcard
- * stuff.</li>
- * </ul>
- * <p>
- * If no pattern prefix is specified, Selenium assumes that it's a "glob"
- * pattern.
- * </p>
- * <p>
- * For commands that return multiple values (such as verifySelectOptions),
- * the string being matched is a comma-separated list of the return values,
- * where both commas and backslashes in the values are backslash-escaped.
- * When providing a pattern, the optional matching syntax (i.e. glob,
- * regexp, etc.) is specified once, as usual, at the beginning of the
- * pattern.
- * </p>
- *
- * @param expected expected result, optionally prefixed
- * @param actual Actual result coming from Selenium
- * @return is it a match?
- */
- public boolean matches(String expected, String actual) {
- boolean result;
-
- // Be graceful with empty strings
- if (actual == null) {
- actual = "";
- }
-
- if (isBooleanCommand()) {
- result = "true".equals(actual);
-
- } else if (expected.startsWith(REGEXP)) {
- final String regex = trim(removeStartIgnoreCase(expected, REGEXP));
- result = Pattern.compile(regex, Pattern.DOTALL).matcher(actual).matches();
-
- } else if (expected.startsWith(REGEXPI)) {
- final String regex = trim(removeStartIgnoreCase(expected, REGEXPI));
- result = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE).matcher(actual).matches();
-
- } else if (expected.startsWith(EXACT)){
- final String str = trim(removeStartIgnoreCase(expected, EXACT));
- result = str.equals(actual);
-
- } else {
- // "glob:"
- final String pattern;
- if (expected.startsWith(GLOB)) {
- pattern = trim(removeStartIgnoreCase(expected, GLOB));
- } else {
- pattern = expected;
- }
- result = globToRegExp(pattern).matcher(actual).matches();
- }
- if (isNegateCommand()) {
- result = !result;
- }
- return result;
- }
-
- private Pattern globToRegExp(String glob) {
- return Pattern.compile(
- "^\\Q"
- + glob.replace("*", "\\E.*\\Q")
- .replace("?", "\\E.\\Q")
- + "\\E$", Pattern.DOTALL);
- }
-
- /**
- * @return true if an array is returned.
- */
- public boolean returnTypeIsArray() {
- return ARRAY_COMMANDS.contains(getSeleniumCommand());
- }
+ // Commands that return
+ private static final Set<String> ARRAY_COMMANDS = new HashSet<String>(Arrays.asList(new String[] {
+ "getAllButtons", // arr
+ "getAllFields", // arr
+ "getAllLinks", // arr
+ "getAllWindowTitles", // arr
+ "getAttributeFromAllWindows", // arr
+ "getSelectedIds", // arr
+ "getSelectedIndexes", // arr
+ "getSelectedLabels", // arr
+ "getSelectedValues", // arr
+ "getSelectOptions" // arr
+ }));
+
+ private String methodName;
+
+ // The real selenium command name, assigned by getSeleniumCommand() on first invocation.
+ private String seleniumCommandName;
+
+ public ExtendedSeleniumCommand(String methodName) {
+ this.methodName = methodName;
+ }
+
+ public static boolean isSupportedByWebDriver(String methodName) {
+ return WEB_DRIVER_COMMANDS.contains(methodName);
+ }
+
+ public boolean isWaitForCommand() {
+ return methodName.startsWith(WAIT_FOR) && !isSupportedByWebDriver(methodName);
+ }
+
+ /**
+ * Command is a "waitFor-" command, but is not supported natively by Selenium,
+ * hence it should act as "verify-" command and in case of failure retries
+ * should be done.
+ *
+ * @return
+ */
+ public boolean requiresPolling() {
+ return isWaitForCommand() && !isSupportedByWebDriver(methodName);
+ }
+
+ public boolean isAndWaitCommand() {
+ return methodName.endsWith(AND_WAIT);
+ }
+
+ // TODO: process this in JS
+ public boolean isNegateCommand() {
+ return methodName.matches(".*[a-z]Not[A-Z].*");
+ }
+
+ public boolean isAssertCommand() {
+ return methodName.startsWith(ASSERT);
+ }
+
+ public boolean isVerifyCommand() {
+ return methodName.startsWith(VERIFY);
+ }
+
+ public boolean isStoreCommand() {
+ return methodName.startsWith(STORE);
+ }
+
+ public boolean isCaptureEntirePageScreenshotCommand() {
+ return methodName.startsWith("captureEntirePageScreenshot");
+ }
+
+ public boolean isBooleanCommand() {
+ return getSeleniumCommand().startsWith(IS);
+ }
+
+ public String getSeleniumCommand() {
+
+ // fast track: once resolved return the previous value.
+ if (seleniumCommandName != null) {
+ return seleniumCommandName;
+ }
+
+ // for commands like "waitForCondition"
+ if (isSupportedByWebDriver(methodName)) {
+ seleniumCommandName = methodName;
+ return methodName;
+ }
+
+ String seleniumName = methodName;
+
+ if (isAssertCommand() || isVerifyCommand() || isStoreCommand() || isWaitForCommand()) {
+ String noun = seleniumName;
+
+ if (isNegateCommand()) {
+ //noun = noun.substring(0, noun.length() - NOT_PRESENT.length()) + "Present";
+ noun = noun.replaceAll("([a-z])Not([A-Z])", "$1$2");
+ }
+
+ // ASSERT.length() == VERIFY.length()
+ noun = noun.substring(isStoreCommand() ? STORE.length() :
+ (isWaitForCommand() ? WAIT_FOR.length() : ASSERT.length()));
+
+ if (isSupportedByWebDriver(IS + noun)) {
+ seleniumName = IS + noun;
+ } else if (isSupportedByWebDriver(GET + noun)) {
+ seleniumName = GET + noun;
+ }
+ } else if (isCaptureEntirePageScreenshotCommand()) {
+ seleniumName = "captureScreenshotToString";
+ }
+
+ if (isAndWaitCommand()) {
+ seleniumName = seleniumName.substring(0, seleniumName.length() - AND_WAIT.length());
+ }
+
+ seleniumCommandName = seleniumName;
+
+ return seleniumName;
+ }
+
+ /**
+ * <p><i>(From the Selenium docs)</i></p>
+ * <p>
+ * Various Pattern syntaxes are available for matching string values:
+ * </p>
+ * <ul>
+ * <li><strong>glob:</strong><em>pattern</em>: Match a string against a
+ * "glob" (aka "wildmat") pattern. "Glob" is a kind of limited
+ * regular-expression syntax typically used in command-line shells. In a
+ * glob pattern, "*" represents any sequence of characters, and "?"
+ * represents any single character. Glob patterns match against the entire
+ * string.</li>
+ * <li><strong>regexp:</strong><em>regexp</em>: Match a string using a
+ * regular-expression. The full power of JavaScript regular-expressions is
+ * available.</li>
+ * <li><strong>regexpi:</strong><em>regexpi</em>: Match a string using a
+ * case-insensitive regular-expression.</li>
+ * <li><strong>exact:</strong><em>string</em>:
+ *
+ * Match a string exactly, verbatim, without any of that fancy wildcard
+ * stuff.</li>
+ * </ul>
+ * <p>
+ * If no pattern prefix is specified, Selenium assumes that it's a "glob"
+ * pattern.
+ * </p>
+ * <p>
+ * For commands that return multiple values (such as verifySelectOptions),
+ * the string being matched is a comma-separated list of the return values,
+ * where both commas and backslashes in the values are backslash-escaped.
+ * When providing a pattern, the optional matching syntax (i.e. glob,
+ * regexp, etc.) is specified once, as usual, at the beginning of the
+ * pattern.
+ * </p>
+ *
+ * @param expected expected result, optionally prefixed
+ * @param actual Actual result coming from Selenium
+ * @return is it a match?
+ */
+ public boolean matches(String expected, String actual) {
+ boolean result;
+
+ // Be graceful with empty strings
+ if (actual == null) {
+ actual = "";
+ }
+
+ if (isBooleanCommand()) {
+ result = "true".equals(actual);
+
+ } else if (expected.startsWith(REGEXP)) {
+ final String regex = trim(removeStartIgnoreCase(expected, REGEXP));
+ result = Pattern.compile(regex, Pattern.DOTALL).matcher(actual).matches();
+
+ } else if (expected.startsWith(REGEXPI)) {
+ final String regex = trim(removeStartIgnoreCase(expected, REGEXPI));
+ result = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE).matcher(actual).matches();
+
+ } else if (expected.startsWith(EXACT)) {
+ final String str = trim(removeStartIgnoreCase(expected, EXACT));
+ result = str.equals(actual);
+
+ } else {
+ // "glob:"
+ final String pattern;
+ if (expected.startsWith(GLOB)) {
+ pattern = trim(removeStartIgnoreCase(expected, GLOB));
+ } else {
+ pattern = expected;
+ }
+ result = globToRegExp(pattern).matcher(actual).matches();
+ }
+ if (isNegateCommand()) {
+ result = !result;
+ }
+ return result;
+ }
+
+ private Pattern globToRegExp(String glob) {
+ return Pattern.compile(
+ "^\\Q" +
+ glob.replace("*", "\\E.*\\Q").replace("?", "\\E.\\Q") +
+ "\\E$", Pattern.DOTALL);
+ }
+
+ /**
+ * @return true if an array is returned.
+ */
+ public boolean returnTypeIsArray() {
+ return ARRAY_COMMANDS.contains(getSeleniumCommand());
+ }
}
View
96 src/main/java/com/xebia/incubator/xebium/FitNesseUtil.java
@@ -21,55 +21,53 @@
public class FitNesseUtil {
- private FitNesseUtil() {
- // Static class
- }
+ private FitNesseUtil() {
+ // Static class
+ }
- /**
- * scriptName is something like
- * '<a href="http://some.url/files/selenium/Suite">http://files/selenium/Suite</a>'.
- *
- * @param scriptName
- * @return
- */
- public static String removeAnchorTag(String scriptName) {
- if (scriptName.startsWith("<a") && scriptName.endsWith("</a>")) {
- scriptName = scriptName.split(">", 2)[1].split("<", 2)[0];
- }
- return scriptName;
- }
-
-
- /**
- * Obtain the script name from a wiki url. The URL may be in the format
- * <code>http://files/selenium/Suite</code> and
- * <code>&lt;a href="/files/selenium/Suite"&gt;http://files/selenium/Suite&lt;/a&gt;</code>
- *
- * @param scriptName
- * @return a sane path name. Relative to the CWD.
- */
- public static File asFile(final String scriptName) {
- String fileName = removeAnchorTag(scriptName).replaceAll("http:/", "FitNesseRoot");
-
- return new File(fileName);
- }
+ /**
+ * scriptName is something like
+ * '<a href="http://some.url/files/selenium/Suite">http://files/selenium/Suite</a>'.
+ *
+ * @param scriptName
+ * @return
+ */
+ public static String removeAnchorTag(String scriptName) {
+ if (scriptName.startsWith("<a") && scriptName.endsWith("</a>")) {
+ scriptName = scriptName.split(">", 2)[1].split("<", 2)[0];
+ }
+ return scriptName;
+ }
+
+ /**
+ * Obtain the script name from a wiki url. The URL may be in the format
+ * <code>http://files/selenium/Suite</code> and
+ * <code>&lt;a href="/files/selenium/Suite"&gt;http://files/selenium/Suite&lt;/a&gt;</code>
+ *
+ * @param scriptName
+ * @return a sane path name. Relative to the CWD.
+ */
+ public static File asFile(final String scriptName) {
+ String fileName = removeAnchorTag(scriptName).replaceAll("http:/", "FitNesseRoot");
+
+ return new File(fileName);
+ }
+
+ /**
+ * Construct a <code>String</code> representation of a <code>String[]</code> the same way Selenium IDE does.
+ */
+ public static String stringArrayToString(String[] stringArray) {
+ StringBuilder b = new StringBuilder(64);
+ boolean comma = false;
+ for (String s : stringArray) {
+ if (comma) {
+ b.append(',');
+ } else {
+ comma = true;
+ }
+ b.append(s.replace("\\", "\\\\").replace(",", "\\,"));
+ }
+ return b.toString();
+ }
-
- /**
- * Construct a <code>String</code> representation of a <code>String[]</code> the same way Selenium IDE does.
- */
- public static String stringArrayToString(String[] stringArray) {
- StringBuilder b = new StringBuilder(64);
- boolean comma = false;
- for (String s: stringArray) {
- if (comma) {
- b.append(',');
- } else {
- comma = true;
- }
- b.append(s.replace("\\", "\\\\").replace(",", "\\,"));
- }
- return b.toString();
- }
-
}
View
147 src/main/java/com/xebia/incubator/xebium/HttpCommandProcessorAdapter.java
@@ -30,85 +30,70 @@
*/
public class HttpCommandProcessorAdapter implements CommandProcessor {
- private HttpCommandProcessor httpCommandProcessor;
-
-
- public HttpCommandProcessorAdapter(HttpCommandProcessor httpCommandProcessor) {
- super();
- this.httpCommandProcessor = httpCommandProcessor;
- }
-
-
- private String removeStatusCode(String output) {
- if (output.startsWith("OK,")) {
- return output.substring(3);
- }
- return output;
- }
-
-
- public String doCommand(String commandName, String[] args) {
- String output = httpCommandProcessor.doCommand(commandName, args);
- return removeStatusCode(output);
- }
-
-
- public boolean getBoolean(String command, String[] args) {
- return httpCommandProcessor.getBoolean(command, args);
- }
-
-
- public boolean[] getBooleanArray(String command, String[] args) {
- return httpCommandProcessor.getBooleanArray(command, args);
- }
-
-
- public Number getNumber(String command, String[] args) {
- return httpCommandProcessor.getNumber(command, args);
- }
-
-
- public Number[] getNumberArray(String command, String[] args) {
- return httpCommandProcessor.getNumberArray(command, args);
- }
-
-
- public String getRemoteControlServerLocation() {
- return httpCommandProcessor.getRemoteControlServerLocation();
- }
-
-
- public String getString(String command, String[] args) {
- return httpCommandProcessor.getString(command, args);
- }
-
-
- public String[] getStringArray(String command, String[] args) {
- return httpCommandProcessor.getStringArray(command, args);
- }
-
-
- public void setExtensionJs(String extensionJs) {
- httpCommandProcessor.setExtensionJs(extensionJs);
- }
-
-
- public void start() {
- httpCommandProcessor.start();
- }
-
-
- public void start(String optionsString) {
- httpCommandProcessor.start(optionsString);
- }
-
-
- public void start(Object optionsObject) {
- httpCommandProcessor.start(optionsObject);
- }
-
-
- public void stop() {
- httpCommandProcessor.stop();
- }
+ private HttpCommandProcessor httpCommandProcessor;
+
+ public HttpCommandProcessorAdapter(HttpCommandProcessor httpCommandProcessor) {
+ super();
+ this.httpCommandProcessor = httpCommandProcessor;
+ }
+
+ private String removeStatusCode(String output) {
+ if (output.startsWith("OK,")) {
+ return output.substring(3);
+ }
+ return output;
+ }
+
+ public String doCommand(String commandName, String[] args) {
+ String output = httpCommandProcessor.doCommand(commandName, args);
+ return removeStatusCode(output);
+ }
+
+ public boolean getBoolean(String command, String[] args) {
+ return httpCommandProcessor.getBoolean(command, args);
+ }
+
+ public boolean[] getBooleanArray(String command, String[] args) {
+ return httpCommandProcessor.getBooleanArray(command, args);
+ }
+
+ public Number getNumber(String command, String[] args) {
+ return httpCommandProcessor.getNumber(command, args);
+ }
+
+ public Number[] getNumberArray(String command, String[] args) {
+ return httpCommandProcessor.getNumberArray(command, args);
+ }
+
+ public String getRemoteControlServerLocation() {
+ return httpCommandProcessor.getRemoteControlServerLocation();
+ }
+
+ public String getString(String command, String[] args) {
+ return httpCommandProcessor.getString(command, args);
+ }
+
+ public String[] getStringArray(String command, String[] args) {
+ return httpCommandProcessor.getStringArray(command, args);
+ }
+
+ public void setExtensionJs(String extensionJs) {
+ httpCommandProcessor.setExtensionJs(extensionJs);
+ }
+
+ public void start() {
+ httpCommandProcessor.start();
+ }
+
+ public void start(String optionsString) {
+ httpCommandProcessor.start(optionsString);
+ }
+
+ public void start(Object optionsObject) {
+ httpCommandProcessor.start(optionsObject);
+ }
+
+ public void stop() {
+ httpCommandProcessor.stop();
+ }
}
View
73 src/main/java/com/xebia/incubator/xebium/LocatorCheck.java
@@ -28,44 +28,43 @@
public class LocatorCheck {
- private static final Logger LOG = LoggerFactory.getLogger(LocatorCheck.class);
+ private static final Logger LOG = LoggerFactory.getLogger(LocatorCheck.class);
- // keywords copied from org.openqa.selenium.WebDriverCommandProcessor
- private static final Set<String> LOCATOR_COMMANDS = new HashSet<String>(Arrays.asList(new String[] {
- "addSelection", // loc
- "assignId", // loc
- "click", // loc
- "check", // loc
- "doubleClick", // loc
- "dragdrop", // loc
- "dragAndDrop", // loc
- "dragAndDropToObject", // loc, loc
- "focus", // loc
- "highlight", // loc
- "removeSelection", // loc
- "select", // loc
- "submit", // loc
- "type", // loc
- "typeKeys", // loc
- "uncheck" // loc
- }));
+ // keywords copied from org.openqa.selenium.WebDriverCommandProcessor
+ private static final Set<String> LOCATOR_COMMANDS = new HashSet<String>(Arrays.asList(new String[] {
+ "addSelection", // loc
+ "assignId", // loc
+ "click", // loc
+ "check", // loc
+ "doubleClick", // loc
+ "dragdrop", // loc
+ "dragAndDrop", // loc
+ "dragAndDropToObject", // loc, loc
+ "focus", // loc
+ "highlight", // loc
+ "removeSelection", // loc
+ "select", // loc
+ "submit", // loc
+ "type", // loc
+ "typeKeys", // loc
+ "uncheck" // loc
+ }));
- private CommandProcessor commandProcessor;
-
-
- public LocatorCheck(CommandProcessor commandProcessor) {
- super();
- this.commandProcessor = commandProcessor;
- }
+ private CommandProcessor commandProcessor;
- boolean verifyElementPresent(final ExtendedSeleniumCommand command, final String[] values) {
- final String methodName = command.getSeleniumCommand();
-
- if (LOCATOR_COMMANDS.contains(methodName)
- && !commandProcessor.getBoolean("isElementPresent", new String[] { values[0] })) {
- LOG.warn("Element " + values[0] + " is not found.");
- return false;
- }
- return true;
- }
+ public LocatorCheck(CommandProcessor commandProcessor) {
+ super();
+ this.commandProcessor = commandProcessor;
+ }
+
+ boolean verifyElementPresent(final ExtendedSeleniumCommand command, final String[] values) {
+ final String methodName = command.getSeleniumCommand();
+
+ if (LOCATOR_COMMANDS.contains(methodName)
+ && !commandProcessor.getBoolean("isElementPresent", new String[] {values[0]})) {
+ LOG.warn("Element " + values[0] + " is not found.");
+ return false;
+ }
+ return true;
+ }
}
View
126 src/main/java/com/xebia/incubator/xebium/RemoteWebDriverSupplier.java
@@ -36,69 +36,67 @@
public class RemoteWebDriverSupplier implements Supplier<WebDriver> {
- private static final String REMOTE = "remote";
-
- private String remote;
- private Map<String, String> capabilities;
-
- public RemoteWebDriverSupplier(String json) {
- JSONObject jsonObject;
- try {
- jsonObject = new JSONObject(json);
- } catch (JSONException e) {
- throw new RuntimeException("Unable to interpret browser information", e);
- }
-
- try {
- remote = jsonObject.getString(REMOTE);
- jsonObject.remove(REMOTE);
- capabilities = jsonObjectToMap(jsonObject);
- } catch (JSONException e) {
- throw new RuntimeException("Unable to fetch required fields from json string", e);
- }
- }
-
- private Map<String, String> jsonObjectToMap(JSONObject jsonObject) throws JSONException {
- // Assume you have a Map<String, String> in JSONObject
- @SuppressWarnings("unchecked")
- Iterator<String> nameItr = jsonObject.keys();
- Map<String, String> outMap = new HashMap<String, String>();
- while(nameItr.hasNext()) {
- String name = nameItr.next();
- outMap.put(name, jsonObject.getString(name));
- }
-
- String platform = outMap.get(PLATFORM);
- if (platform != null) {
- outMap.put(PLATFORM, platform.toUpperCase());
- }
-
- return outMap;
- }
-
-
- public URL getRemote() {
- try {
- return new URL(remote);
- } catch (MalformedURLException e) {
- throw new RuntimeException("URL '" + remote + "' is not a valid URL");
- }
- }
-
- public Capabilities getCapabilities() {
- return new DesiredCapabilities(capabilities);
- }
-
- /**
- * Create a new remote-webdriver. It can be configured according to the specs on
- * https://saucelabs.com/docs/ondemand/additional-config.
- *
- * @return a fresh RemoteWebDriver instance
- * @throws RuntimeException in case of any error
- */
- public WebDriver get() {
- return new RemoteWebDriver(getRemote(), getCapabilities());
- }
-
+ private static final String REMOTE = "remote";
+
+ private String remote;
+ private Map<String, String> capabilities;
+
+ public RemoteWebDriverSupplier(String json) {
+ JSONObject jsonObject;
+ try {
+ jsonObject = new JSONObject(json);
+ } catch (JSONException e) {
+ throw new RuntimeException("Unable to interpret browser information", e);
+ }
+
+ try {
+ remote = jsonObject.getString(REMOTE);
+ jsonObject.remove(REMOTE);
+ capabilities = jsonObjectToMap(jsonObject);
+ } catch (JSONException e) {
+ throw new RuntimeException("Unable to fetch required fields from json string", e);
+ }
+ }
+
+ private Map<String, String> jsonObjectToMap(JSONObject jsonObject) throws JSONException {
+ // Assume you have a Map<String, String> in JSONObject
+ @SuppressWarnings("unchecked")
+ Iterator<String> nameItr = jsonObject.keys();
+ Map<String, String> outMap = new HashMap<String, String>();
+ while (nameItr.hasNext()) {
+ String name = nameItr.next();
+ outMap.put(name, jsonObject.getString(name));
+ }
+
+ String platform = outMap.get(PLATFORM);
+ if (platform != null) {
+ outMap.put(PLATFORM, platform.toUpperCase());
+ }
+
+ return outMap;
+ }
+
+ public URL getRemote() {
+ try {
+ return new URL(remote);
+ } catch (MalformedURLException e) {
+ throw new RuntimeException("URL '" + remote + "' is not a valid URL");
+ }
+ }
+
+ public Capabilities getCapabilities() {
+ return new DesiredCapabilities(capabilities);
+ }
+
+ /**
+ * Create a new remote-webdriver. It can be configured according to the specs on
+ * https://saucelabs.com/docs/ondemand/additional-config.
+ *
+ * @return a fresh RemoteWebDriver instance
+ * @throws RuntimeException in case of any error
+ */
+ public WebDriver get() {
+ return new RemoteWebDriver(getRemote(), getCapabilities());
+ }
}
View
299 src/main/java/com/xebia/incubator/xebium/ScreenCapture.java
@@ -39,156 +39,153 @@
*/
class ScreenCapture {
- enum ScreenshotPolicy {
- NONE,
- ASSERTION,
- FAILURE,
- STEP
- }
-
-
- private static final Logger LOG = LoggerFactory.getLogger(ScreenCapture.class);
-
- private static final String PATH_SEP = System.getProperty("file.separator");
-
- private static final int INITIAL_STEP_NUMBER = 1;
-
- // ensure step indexes are maintained among ScreenCapture instances
- private static Map<String, Integer> stepNumbers = new HashMap<String, Integer>();
-
- // screenshotBaseDir is guaranteed to have a trailing path separtor.
- private String screenshotBaseDir = "FitNesseRoot/files/testResults/screenshots/".replace("/", PATH_SEP);
-
- private CommandProcessor commandProcessor;
-
- private ScreenshotPolicy screenshotPolicy = ScreenshotPolicy.ASSERTION;
-
-
- void setCommandProcessor(CommandProcessor commandProcessor) {
- this.commandProcessor = commandProcessor;
- }
-
- void setScreenshotBaseDir(String screenshotBaseDir) {
- this.screenshotBaseDir = asFile(screenshotBaseDir).getAbsolutePath();
- if (!this.screenshotBaseDir.endsWith(PATH_SEP)) {
- this.screenshotBaseDir += PATH_SEP;
- }
- }
-
- void setScreenshotPolicy(String policy) {
- if ("none".equals(policy) || "nothing".equals(policy)) {
- screenshotPolicy = ScreenshotPolicy.NONE;
- } else if ("failure".equals(policy) || "error".equals(policy)) {
- screenshotPolicy =ScreenshotPolicy.FAILURE;
- } else if ("step".equals(policy) || "every step".equals(policy)) {
- screenshotPolicy = ScreenshotPolicy.STEP;
- } else if ("assertion".equals(policy) || "every assertion".equals(policy)) {
- screenshotPolicy = ScreenshotPolicy.ASSERTION;
- }
- LOG.info("Screenshot policy set to " + screenshotPolicy);
- }
-
- /**
- * Is a screenshot desired, based on the command and the test result.
- *
- * @param command
- * @param result
- * @return
- */
- boolean requireScreenshot(final ExtendedSeleniumCommand command,
- boolean result) {
- return
- (!command.isAssertCommand()
- && !command.isVerifyCommand()
- && !command.isWaitForCommand()
- && screenshotPolicy == ScreenshotPolicy.STEP)
- || (!result
- && (screenshotPolicy == ScreenshotPolicy.FAILURE
- || (command.isAssertCommand() && screenshotPolicy == ScreenshotPolicy.ASSERTION)));
- }
-
-
- void captureScreenshot(String methodName, String[] values) {
- int stepNumber = nextStepNumber();
- final File file = new File(screenshotBaseDir + String.format("%04d-%s.png", stepNumber, trim(methodName)));
- LOG.info("Storing screenshot in " + file.getAbsolutePath());
-
- try {
- String output = executeCommand("captureScreenshotToString", new String[] { });
-
- writeToFile(file, output);
-
- updateIndexFile(stepNumber, file, methodName, values);
- } catch (Exception e) {
- LOG.warn("Unable to finish screenshot capturing: " + e.getMessage());
- }
- }
-
- /**
- * @return next step number dependent on screenshot base dir.
- */
- private int nextStepNumber() {
- synchronized (stepNumbers) {
- Integer i = stepNumbers.get(screenshotBaseDir);
- if (i == null) {
- i = INITIAL_STEP_NUMBER;
- }
- stepNumbers.put(screenshotBaseDir, i + 1);
- return i;
- }
- }
-
- private String executeCommand(String methodName, final String[] values) {
- return commandProcessor.doCommand(methodName, values);
- }
-
- /**
- * <p>Provide an easy to use index.html file for viewing the screenshots.
- * </p>
- * <p>The base directory is expected to exist at this point.
- * </p>
- *
- * @param stepNumber
- * @param file
- * @param methodName
- * @param values
- * @throws IOException
- */
- private void updateIndexFile(int stepNumber, File file, String methodName,
- String[] values) throws IOException {
- final File indexFile = new File(screenshotBaseDir + "index.html");
-
- BufferedWriter w = new BufferedWriter(new FileWriter(indexFile, stepNumber > INITIAL_STEP_NUMBER));
- try {
- String title = "| " + methodName + " | " + (values.length > 0 ? values[0] : "") + " | " + (values.length > 1 ? values[1] : "") + " |";
- w.write("<h2>" + stepNumber + ". " + title + "</h2>\n");
- w.write("<img src='" + file.getName() +"' alt='" + title + "'/>\n");
- } finally {
- try {
- w.close();
- } catch (IOException e) {
- LOG.error("Unable to close screenshot file " + file.getPath(), e);
- }
- }
- }
-
- static void writeToFile(final File file, final String output) throws IOException {
- final File parent = file.getParentFile();
-
- if (parent != null && !parent.exists()) {
- parent.mkdirs();
- }
-
- FileOutputStream w = new FileOutputStream(file);
- try {
- w.write(Base64.decodeBase64(output));
- } finally {
- try {
- w.close();
- } catch (IOException e) {
- LOG.error("Unable to close screenshot file " + file.getPath(), e);
- }
- }
- }
+ enum ScreenshotPolicy {
+ NONE,
+ ASSERTION,
+ FAILURE,
+ STEP
+ }
+
+ private static final Logger LOG = LoggerFactory.getLogger(ScreenCapture.class);
+
+ private static final String PATH_SEP = System.getProperty("file.separator");
+
+ private static final int INITIAL_STEP_NUMBER = 1;
+
+ // ensure step indexes are maintained among ScreenCapture instances
+ private static Map<String, Integer> stepNumbers = new HashMap<String, Integer>();
+
+ // screenshotBaseDir is guaranteed to have a trailing path separtor.
+ private String screenshotBaseDir = "FitNesseRoot/files/testResults/screenshots/".replace("/", PATH_SEP);
+
+ private CommandProcessor commandProcessor;
+
+ private ScreenshotPolicy screenshotPolicy = ScreenshotPolicy.ASSERTION;
+
+ void setCommandProcessor(CommandProcessor commandProcessor) {
+ this.commandProcessor = commandProcessor;
+ }
+
+ void setScreenshotBaseDir(String screenshotBaseDir) {
+ this.screenshotBaseDir = asFile(screenshotBaseDir).getAbsolutePath();
+ if (!this.screenshotBaseDir.endsWith(PATH_SEP)) {
+ this.screenshotBaseDir += PATH_SEP;
+ }
+ }
+
+ void setScreenshotPolicy(String policy) {
+ if ("none".equals(policy) || "nothing".equals(policy)) {
+ screenshotPolicy = ScreenshotPolicy.NONE;
+ } else if ("failure".equals(policy) || "error".equals(policy)) {
+ screenshotPolicy = ScreenshotPolicy.FAILURE;
+ } else if ("step".equals(policy) || "every step".equals(policy)) {
+ screenshotPolicy = ScreenshotPolicy.STEP;
+ } else if ("assertion".equals(policy) || "every assertion".equals(policy)) {
+ screenshotPolicy = ScreenshotPolicy.ASSERTION;
+ }
+ LOG.info("Screenshot policy set to " + screenshotPolicy);
+ }
+
+ /**
+ * Is a screenshot desired, based on the command and the test result.
+ *
+ * @param command
+ * @param result
+ * @return
+ */
+ boolean requireScreenshot(final ExtendedSeleniumCommand command,
+ boolean result) {
+ return
+ (!command.isAssertCommand()
+ && !command.isVerifyCommand()
+ && !command.isWaitForCommand()
+ && screenshotPolicy == ScreenshotPolicy.STEP)
+ || (!result
+ && (screenshotPolicy == ScreenshotPolicy.FAILURE
+ || (command.isAssertCommand() && screenshotPolicy == ScreenshotPolicy.ASSERTION)));
+ }
+
+ void captureScreenshot(String methodName, String[] values) {
+ int stepNumber = nextStepNumber();
+ final File file = new File(screenshotBaseDir + String.format("%04d-%s.png", stepNumber, trim(methodName)));
+ LOG.info("Storing screenshot in " + file.getAbsolutePath());
+
+ try {
+ String output = executeCommand("captureScreenshotToString", new String[] {});
+
+ writeToFile(file, output);
+
+ updateIndexFile(stepNumber, file, methodName, values);
+ } catch (Exception e) {
+ LOG.warn("Unable to finish screenshot capturing: " + e.getMessage());
+ }
+ }
+
+ /**
+ * @return next step number dependent on screenshot base dir.
+ */
+ private int nextStepNumber() {
+ synchronized (stepNumbers) {
+ Integer i = stepNumbers.get(screenshotBaseDir);
+ if (i == null) {
+ i = INITIAL_STEP_NUMBER;
+ }
+ stepNumbers.put(screenshotBaseDir, i + 1);
+ return i;
+ }
+ }
+
+ private String executeCommand(String methodName, final String[] values) {
+ return commandProcessor.doCommand(methodName, values);
+ }
+
+ /**
+ * <p>Provide an easy to use index.html file for viewing the screenshots.
+ * </p>
+ * <p>The base directory is expected to exist at this point.
+ * </p>
+ *
+ * @param stepNumber
+ * @param file
+ * @param methodName
+ * @param values
+ * @throws IOException
+ */
+ private void updateIndexFile(int stepNumber, File file, String methodName,
+ String[] values) throws IOException {
+ final File indexFile = new File(screenshotBaseDir + "index.html");
+
+ BufferedWriter w = new BufferedWriter(new FileWriter(indexFile, stepNumber > INITIAL_STEP_NUMBER));
+ try {
+ String title = "| " + methodName + " | " + (values.length > 0 ? values[0] : "") + " | " + (values.length > 1 ? values[1] : "") + " |";
+ w.write("<h2>" + stepNumber + ". " + title + "</h2>\n");
+ w.write("<img src='" + file.getName() + "' alt='" + title + "'/>\n");
+ } finally {
+ try {
+ w.close();
+ } catch (IOException e) {
+ LOG.error("Unable to close screenshot file " + file.getPath(), e);
+ }
+ }
+ }
+
+ static void writeToFile(final File file, final String output) throws IOException {
+ final File parent = file.getParentFile();
+
+ if (parent != null && !parent.exists()) {
+ parent.mkdirs();
+ }
+
+ FileOutputStream w = new FileOutputStream(file);
+ try {
+ w.write(Base64.decodeBase64(output));
+ } finally {
+ try {
+ w.close();
+ } catch (IOException e) {
+ LOG.error("Unable to close screenshot file " + file.getPath(), e);
+ }
+ }
+ }
}
View
126 src/main/java/com/xebia/incubator/xebium/SeleneseScriptFixture.java
@@ -33,15 +33,15 @@
*/
public class SeleneseScriptFixture {
- private static Logger LOG = LoggerFactory.getLogger(SeleneseScriptFixture.class);
-
- private String browser = "*firefox";
- private String browserURL = "http://google.com";
- private File outputFile = new File("SeleniumScriptFixture.html");
- private int timeoutInSeconds = 30;
- private boolean multiWindow = false;
+ private static Logger LOG = LoggerFactory.getLogger(SeleneseScriptFixture.class);
- private SeleniumServer remoteControl;
+ private String browser = "*firefox";
+ private String browserURL = "http://google.com";
+ private File outputFile = new File("SeleniumScriptFixture.html");
+ private int timeoutInSeconds = 30;
+ private boolean multiWindow = false;
+
+ private SeleniumServer remoteControl;
protected String getBrowserCode(String browser) {
if ("IE".equalsIgnoreCase(browser))
@@ -55,59 +55,59 @@ protected String getBrowserCode(String browser) {
return browser;
}
- public void startServer() throws Exception {
- RemoteControlConfiguration configuration = new RemoteControlConfiguration();
- configuration.setProxyInjectionModeArg(true);
- configuration.setPort(4444);
-
- remoteControl = new SeleniumServer(configuration);
- remoteControl.start();
- }
-
- public void startServerWithBrowserOnUrl(String browser, String url) throws Exception {
- this.browser = getBrowserCode(browser);
- browserURL = removeAnchorTag(url);
-
- startServer();
- }
-
- public void setTimeoutToSeconds(int timeoutInSeconds) {
- this.timeoutInSeconds = timeoutInSeconds;
- }
-
- public void setBrowserUrl(String browserUrl) {
- this.browserURL = removeAnchorTag(browserUrl);
- }
-
- public void setOutputFile(String outputFileName) {
- this.outputFile = asFile(outputFileName);
- }
-
- public String runSuite(String scriptName) throws Exception {
- if (remoteControl == null) {
- throw new IllegalStateException("Remote control should have been started before tests are executed");
- }
-
- File suiteFile = asFile(scriptName);
-
- String result = null;
- try {
- LOG.info("Server started, launching test suite");
- HTMLLauncher launcher = new HTMLLauncher(remoteControl);
- result = launcher.runHTMLSuite(browser, browserURL, suiteFile, outputFile, timeoutInSeconds, multiWindow);
- LOG.info("Finished execution of test suite, result = " + result);
- } catch (Exception e) {
- LOG.error("Failed to run test suite", e);
- throw e;
- }
-
- LOG.debug("End of RunScript");
- return result;
- }
-
- public void stopServer() {
- remoteControl.stop();
- remoteControl = null;
- }
-
+ public void startServer() throws Exception {
+ RemoteControlConfiguration configuration = new RemoteControlConfiguration();
+ configuration.setProxyInjectionModeArg(true);
+ configuration.setPort(4444);
+
+ remoteControl = new SeleniumServer(configuration);
+ remoteControl.start();
+ }
+
+ public void startServerWithBrowserOnUrl(String browser, String url) throws Exception {
+ this.browser = getBrowserCode(browser);
+ browserURL = removeAnchorTag(url);
+
+ startServer();
+ }
+
+ public void setTimeoutToSeconds(int timeoutInSeconds) {
+ this.timeoutInSeconds = timeoutInSeconds;
+ }
+
+ public void setBrowserUrl(String browserUrl) {
+ this.browserURL = removeAnchorTag(browserUrl);
+ }
+
+ public void setOutputFile(String outputFileName) {
+ this.outputFile = asFile(outputFileName);
+ }
+
+ public String runSuite(String scriptName) throws Exception {
+ if (remoteControl == null) {
+ throw new IllegalStateException("Remote control should have been started before tests are executed");
+ }
+
+ File suiteFile = asFile(scriptName);
+
+ String result = null;
+ try {
+ LOG.info("Server started, launching test suite");
+ HTMLLauncher launcher = new HTMLLauncher(remoteControl);
+ result = launcher.runHTMLSuite(browser, browserURL, suiteFile, outputFile, timeoutInSeconds, multiWindow);
+ LOG.info("Finished execution of test suite, result = " + result);
+ } catch (Exception e) {
+ LOG.error("Failed to run test suite", e);
+ throw e;
+ }
+
+ LOG.debug("End of RunScript");
+ return result;
+ }
+
+ public void stopServer() {
+ remoteControl.stop();
+ remoteControl = null;
+ }
+
}
View
894 src/main/java/com/xebia/incubator/xebium/SeleniumDriverFixture.java
@@ -41,40 +41,40 @@
*/
public class SeleniumDriverFixture {
- private static final Logger LOG = LoggerFactory.getLogger(SeleniumDriverFixture.class);
+ private static final Logger LOG = LoggerFactory.getLogger(SeleniumDriverFixture.class);
private DefaultWebDriverSupplier defaultWebDriverSupplier = new DefaultWebDriverSupplier();
- private static final String ALIAS_PREFIX = "%";
+ private static final String ALIAS_PREFIX = "%";
- private CommandProcessor commandProcessor;
+ private CommandProcessor commandProcessor;
- private long timeout = 30000;
+ private long timeout = 30000;
- private long stepDelay = 0;
+ private long stepDelay = 0;
- private long pollDelay = 100;
+ private long pollDelay = 100;
- private boolean stopBrowserOnAssertion = true;
+ private boolean stopBrowserOnAssertion = true;
- private ScreenCapture screenCapture = new ScreenCapture();
+ private ScreenCapture screenCapture = new ScreenCapture();
- private LocatorCheck locatorCheck;
+ private LocatorCheck locatorCheck;
- private Map<String, String> aliases = new HashMap<String, String>();
+ private Map<String, String> aliases = new HashMap<String, String>();
- public SeleniumDriverFixture() {
- super();
- }
+ public SeleniumDriverFixture() {
+ super();
+ }
private WebDriver defaultWebDriverInstance() {
- return defaultWebDriverSupplier.newWebDriver();
+ return defaultWebDriverSupplier.newWebDriver();
}
private CommandProcessor startWebDriverCommandProcessor(String browserUrl, WebDriver webDriver) {
- browserUrl = removeAnchorTag(browserUrl);
- return new WebDriverCommandProcessor(browserUrl, webDriver);
- }
+ browserUrl = removeAnchorTag(browserUrl);
+ return new WebDriverCommandProcessor(browserUrl, webDriver);
+ }
/**
* Configure the custom Firefox preferences (javascript) file on the webdriver factory.
@@ -85,28 +85,28 @@ public void loadCustomBrowserPreferencesFromFile(String filename) {
defaultWebDriverSupplier.setCustomProfilePreferencesFile(new File(filename));
}
- /**
+ /**
* Configure the custom Firefox profiledirectory on the webdriver factory.
*
- * @param directory
- */
- public void loadFirefoxProfileFromDirectory(String directory) {
+ * @param directory
+ */
+ public void loadFirefoxProfileFromDirectory(String directory) {
defaultWebDriverSupplier.setCustomProfilePreferencesFile(new File(directory));
- }
+ }
- /**
- * @param browser Name of the browser, as accepted by the DefaultWebDriverSupplier.
- */
- private void setBrowser(String browser) {
+ /**
+ * @param browser Name of the browser, as accepted by the DefaultWebDriverSupplier.
+ */
+ private void setBrowser(String browser) {
defaultWebDriverSupplier.setBrowser(browser);
- }
+ }
/**
* <p><code>
* | start driver | <i>$Driver</i> | on url | <i>http://localhost</i> |
* </code></p>
*
- * @param webDriver a WebDriver instance
+ * @param webDriver a WebDriver instance
* @param browserUrl
*/
public void startDriverOnUrl(final WebDriver webDriver, final String browserUrl) {
@@ -115,424 +115,424 @@ public void startDriverOnUrl(final WebDriver webDriver, final String browserUrl)
LOG.debug("Started command processor");
}
- /**
- * <p><code>
- * | start browser | <i>firefox</i> | on url | <i>http://localhost</i> |
- * </code></p>
- *
- * @param browser
- * @param browserUrl
- */
- public void startBrowserOnUrl(final String browser, final String browserUrl) {
- setBrowser(browser);
+ /**
+ * <p><code>
+ * | start browser | <i>firefox</i> | on url | <i>http://localhost</i> |
+ * </code></p>
+ *
+ * @param browser
+ * @param browserUrl
+ */
+ public void startBrowserOnUrl(final String browser, final String browserUrl) {
+ setBrowser(browser);
startDriverOnUrl(defaultWebDriverInstance(), browserUrl);
- }
-
- /**
- * <p><code>
- * | start browser | <i>firefox</i> | on url | <i>http://localhost</i> | using remote server |
- * </code></p>
- *
- * @param browser
- * @param browserUrl
- * @deprecated This call requires a Selenium 1 server. It is advised to use WebDriver.
- */
- public void startBrowserOnUrlUsingRemoteServer(final String browser, final String browserUrl) {
- startBrowserOnUrlUsingRemoteServerOnHost(browser, browserUrl, "localhost");
- }
-
- /**
- * <p><code>
- * | start browser | <i>firefox</i> | on url | <i>http://localhost</i> | using remote server on host | <i>localhost</i> |
- * </code></p>
- *
- * @param browser
- * @param browserUrl
- * @param serverHost
- * @deprecated This call requires a Selenium 1 server. It is advised to use WebDriver.
- */
- public void startBrowserOnUrlUsingRemoteServerOnHost(final String browser, final String browserUrl, final String serverHost) {
- startBrowserOnUrlUsingRemoteServerOnHostOnPort(browser, browserUrl, serverHost, 4444);
- }
-
- /**
- * <p><code>
- * | start browser | <i>firefox</i> | on url | <i>http://localhost</i> | using remote server on host | <i>localhost</i> | on port | <i>4444</i> |
- * </code></p>
- *
- * @param browser
- * @param browserUrl
- * @param serverHost
- * @param serverPort
- * @deprecated This call requires a Selenium 1 server. It is advised to use WebDriver.
- */
- public void startBrowserOnUrlUsingRemoteServerOnHostOnPort(final String browser, final String browserUrl, final String serverHost, final int serverPort) {
- setCommandProcessor(new HttpCommandProcessorAdapter(new HttpCommandProcessor(serverHost, serverPort, browser, removeAnchorTag(browserUrl))));
- commandProcessor.start();
- setTimeoutOnSelenium();
- LOG.debug("Started HTML command processor");
- }
-
- void setCommandProcessor(CommandProcessor commandProcessor) {
- this.commandProcessor = commandProcessor;
- screenCapture.setCommandProcessor(commandProcessor);
- locatorCheck = new LocatorCheck(commandProcessor);
- LOG.info("Started new command processor (timeout: " + timeout + "ms, step delay: " + stepDelay + "ms, poll interval: " + pollDelay + "ms)");
- }
-
- /**
- * <p><code>
- * | set timeout to | 500 |
- * </code></p>
- *
- * <p>Set the timeout, both local and on the running selenium server.</p>
- *
- * @param timeout Timeout in milliseconds (ms)
- */
- public void setTimeoutTo(long timeout) {
- this.timeout = timeout;
- if (commandProcessor != null) {
- setTimeoutOnSelenium();
- }
- }
-
- /**
- * <p><code>
- * | set timeout to | 500 | seconds |
- * </code></p>
- *
- * <p>Set the timeout, both local and on the running selenium server.</p>
- *
- * @param timeout Timeout in seconds
- */
- public void setTimeoutToSeconds(long timeout) {
- setTimeoutTo(timeout * 1000);
- }
-
- /**
- * Set the default timeout on the selenium instance.
- */
- private void setTimeoutOnSelenium() {
- executeCommand("setTimeout", new String[] { "" + this.timeout });
- }
-
- /**
- * <p>Set delay between steps.</p>
- * <p><code>
- * | set step delay to | 500 |
- * | set step delay to | slow |
- * | set step delay to | fast |
- * </code></p>
- *
- * @param stepDelay delay in milliseconds
- */
- public void setStepDelayTo(String stepDelay) {
- if ("slow".equals(stepDelay)) {
- this.stepDelay = 1000;
- } else if ("fast".equals(stepDelay)) {
- this.stepDelay = 0;
- } else {
- this.stepDelay = Long.parseLong(stepDelay);
- }
- }
-
- /**
- * <p>In case of an assertion (assert* selenese command), close the browser.</p>
- * <p><code>
- * | set stop browser on assertion | true |
- * </code></p>
- *
- * @param stopBrowserOnAssertion
- */
- public void setStopBrowserOnAssertion(boolean stopBrowserOnAssertion) {
- this.stopBrowserOnAssertion = stopBrowserOnAssertion;
- }
-
- /**
- * Instruct the driver to create screenshots
- * <p><code>
- * | save screenshot after | <i>failure</i> |
- * | save screenshot after | <i>error</i> |
- * </code></p>
- *
- * <p><code>
- * | save screenshot after | <i>every step</i> |
- * | save screenshot after | <i>step</i> |
- * </code></p>
- *
- * <p><code>
- * | save screenshot after | <i>nothing</i> |
- * | save screenshot after | <i>none</i> |
- * </code></p>
- */
- public void saveScreenshotAfter(String policy) {
- screenCapture.setScreenshotPolicy(policy);
- }
-
- /**
- * <p><code>
- * | save screenshot after | <i>failure</i> | in folder | <i>http://files/testResults/screenshots/${PAGE_NAME} |
- * | save screenshot after | <i>error</i> |
- * </code></p>
- */
- public void saveScreenshotAfterInFolder(String policy, String baseDir) {
- saveScreenshotAfter(policy);
- screenCapture.setScreenshotBaseDir(removeAnchorTag(baseDir));
- }
-
- /**
- * <p><code>
- * | ensure | do | <i>open</i> | on | <i>/</i> |
- * </code></p>
- *
- * @param command
- * @param target
- * @return
- */
- public boolean doOn(final String command, final String target) {
- LOG.info("Performing | " + command + " | " + target + " |");
- return executeDoCommand(command, new String[] { unalias(target) });
- }
-
- /**
- * <p><code>
- * | ensure | do | <i>type</i> | on | <i>searchString</i> | with | <i>some text</i> |
- * </code></p>
- *
- * @param command
- * @param target
- * @param value
- * @return
- */
- public boolean doOnWith(final String command, final String target, final String value) {
- LOG.info("Performing | " + command + " | " + target + " | " + value + " |");
- return executeDoCommand(command, new String[] { unalias(target), unalias(value) });
- }
-
- /**
- * <p><code>
- * | <i>$title=</i> | is | <i>getTitle</i> |
- * </code></p>
- *
- * @param command
- * @return
- */
- public String is(final String command) {
- LOG.info("Obtain result from | " + command + " |");
- return executeCommand(new ExtendedSeleniumCommand(command), new String[] { }, stepDelay);
- }
-
- /**
- * Same as {@link #is(String)}, only with "on" statement, analog to "do-on" command.
- *
- * @param command
- * @return
- */
- public String isOn(final String command) {
- return is(command);
- }
-
- /**
- * <p><code>
- * | <i>$pageName=</i> | is | <i>getText</i> | on | <i>//span</i> |
- * </code></p>
- *
- * @param command
- * @param target
- * @return
- */
- public String isOn(final String command, final String target) {
- LOG.info("Obtain result from | " + command + " | " + target + " |");
- return executeCommand(new ExtendedSeleniumCommand(command), new String[] { unalias(target) }, stepDelay);
- }
-
- /**
- * Same as {@link #isOn(String, String)}, only with "with" statement, analog to "do-on-with" command.
- *
- * @param command
- * @param target
- * @return
- */
- public String isOnWith(final String command, final String target) {
- return isOn(command, target);
- }
-
- /**
- * Add a new locator alias to the fixture.
- *
- * @param alias
- * @param locator
- */
- public void addAliasForLocator(String alias, String locator) {
- LOG.info("Add alias: '" + alias + "' for '" + locator + "'");
- aliases.put(alias, locator);
- }
-
- /**
- * Clear the aliases table.
- */
- public void clearAliases() {
- aliases.clear();
- }