/** * JBoss, Home of Professional Open Source * Copyright 2016, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * <p> * 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. */ package org.arquillian.drone.browserstack.extension.webdriver; import java.util.function.Function; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; /** * Util class to make UI tests easier */ public class WebDriverUtil { protected static void checkElementIsPresent(final WebDriver driver, final By by, final String errorMsg) { new WebDriverWaitWithMessage(driver, 10).failWith(errorMsg).until(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { try { return driver.findElement(by) != null; } catch (NoSuchElementException ignored) { return false; } catch (StaleElementReferenceException ignored) { return false; } } }); } protected static void checkElementContent(final WebDriver driver, final By by, final String expectedContent, final String errorMsg) { new WebDriverWaitWithMessage(driver, 10).failWith(errorMsg).until(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { try { String text = driver.findElement(by).getText(); if (text != null) { return text.contains(expectedContent); } return false; } catch (NoSuchElementException ignored) { return false; } catch (StaleElementReferenceException ignored) { return false; } } }); } protected static class WebDriverWaitWithMessage extends WebDriverWait { private String message; public WebDriverWaitWithMessage(WebDriver driver, long timeOutInSeconds) { super(driver, timeOutInSeconds); } public WebDriverWait failWith(String message) { if (message == null || message.length() == 0) { throw new IllegalArgumentException("Error message must not be null nor empty"); } this.message = message; return this; } @Override public <V> V until(Function<? super WebDriver, V> isTrue) { if (message == null) { return super.until(isTrue); } else { try { return super.until(isTrue); } catch (TimeoutException e) { throw new TimeoutException(message, e); } } } } }