下面列出了org.junit.jupiter.api.extension.ParameterResolver#org.openqa.selenium.WebDriver 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* An expectation to check if js executable.
*
* Useful when you know that there should be a Javascript value or something at the stage.
*
* @param javaScript used as executable script
* @return true once javaScript executed without errors
*/
public static ExpectedCondition<Boolean> javaScriptThrowsNoExceptions(final String javaScript) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
((JavascriptExecutor) driver).executeScript(javaScript);
return true;
} catch (WebDriverException e) {
return false;
}
}
@Override
public String toString() {
return String.format("js %s to be executable", javaScript);
}
};
}
private WebElement findElementDirectlyIfNecessary(WebDriver driver, String locator) {
if (locator.startsWith("xpath=")) {
return xpathWizardry(driver, locator.substring("xpath=".length()));
}
if (locator.startsWith("//")) {
return xpathWizardry(driver, locator);
}
if (locator.startsWith("css=")) {
String selector = locator.substring("css=".length());
try {
return driver.findElement(By.cssSelector(selector));
} catch (WebDriverException e) {
return fallbackToSizzle(driver, selector);
}
}
return null;
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"10", ""})
public void clearInput() throws Exception {
final String html = "<html>\n"
+ "<body>\n"
+ "<form>\n"
+ " <input type='number' id='tester' value='10'>\n"
+ "</form>\n"
+ "</body>\n"
+ "</html>";
final WebDriver driver = loadPage2(html);
final WebElement element = driver.findElement(By.id("tester"));
assertEquals(getExpectedAlerts()[0], element.getAttribute("value"));
element.clear();
assertEquals(getExpectedAlerts()[1], element.getAttribute("value"));
}
/**
* Returns an ExpectedCondition instance that waits until an attribute's
* value contains the specified text.
*/
public static ExpectedCondition<Boolean> elementAttributeToContain(final WebElement element, String attribute, String text, boolean caseInsensitive) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
String value = element.getAttribute(attribute);
if (caseInsensitive) {
return value.toLowerCase().contains(text.toLowerCase());
} else {
return value.contains(text);
}
}
@Override
public String toString() {
return "element text to contain: " + text;
}
};
}
/**
* Regression test for bug 3017719: a 302 redirect should change the page url.
* @throws Exception if an error occurs
*/
@Test
public void redirect302ChangePageUrl() throws Exception {
final String html = "<html><body><a href='redirect.html'>redirect</a></body></html>";
final URL url = new URL(URL_FIRST, "page2.html");
getMockWebConnection().setResponse(url, html);
final List<NameValuePair> headers = new ArrayList<>();
headers.add(new NameValuePair("Location", "/page2.html"));
getMockWebConnection().setDefaultResponse("", 302, "Found", null, headers);
final WebDriver driver = loadPage2(html);
driver.findElement(By.tagName("a")).click();
assertEquals(url.toString(), driver.getCurrentUrl());
}
@Override
public void onTestFailure(ITestResult failingTest) {
try {
WebDriver driver = getDriver();
String screenshotDirectory = System.getProperty("screenshotDirectory", "target/screenshots");
String screenshotAbsolutePath = screenshotDirectory + File.separator + System.currentTimeMillis() + "_" + failingTest.getName() + ".png";
File screenshot = new File(screenshotAbsolutePath);
if (createFile(screenshot)) {
try {
writeScreenshotToFile(driver, screenshot);
} catch (ClassCastException weNeedToAugmentOurDriverObject) {
writeScreenshotToFile(new Augmenter().augment(driver), screenshot);
}
System.out.println("Written screenshot to " + screenshotAbsolutePath);
} else {
System.err.println("Unable to create " + screenshotAbsolutePath);
}
} catch (Exception ex) {
System.err.println("Unable to capture screenshot: " + ex.getCause());
}
}
@Override
public boolean _set( WebElement webElement, WebDriver webDriver, String value, String setType, String xFID )
{
List<WebElement> dropdownToggle = webElement.findElements( By.xpath( "./preceding-sibling::*[@uib-dropdown-toggle]" ) );
if ( dropdownToggle.isEmpty() )
dropdownToggle = webElement.findElements( By.xpath( "./preceding-sibling::*[@data-toggle]" ) );
if ( dropdownToggle.isEmpty() )
dropdownToggle = webElement.findElements( By.xpath( "../preceding-sibling::*[@data-toggle]" ) );
if ( !dropdownToggle.isEmpty() )
dropdownToggle.get( 0 ).click();
List<WebElement> selectList = webElement.findElements( By.xpath( "./li/a[contains( text(), '" + value + "')]" ) );
if ( selectList.isEmpty() )
selectList = webElement.findElements( By.xpath( ".//a[contains( text(), '" + value + "')]" ) );
if ( selectList.isEmpty() )
return false;
else
{
selectList.get( 0 ).click();
}
return true;
}
/**
* Site admin application configuration test.
*
* @throws Exception
* the exception
*/
@Test(timeout = 60000)
public void siteAdminApplicationConfigurationTest() throws Exception {
final WebDriver driver = getWebDriver();
assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver);
final UserPageVisit userPageVisit = new UserPageVisit(driver, browser);
loginAsAdmin(userPageVisit);
userPageVisit
.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_CONFIGURATION_VIEW_NAME, ""));
assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Application Configuration"));
clickFirstRowInGrid(userPageVisit);
userPageVisit
.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_CONFIGURATION_VIEW_NAME, ""));
userPageVisit.updateConfigurationProperty("Update Configuration.propertyValue", String.valueOf(false));
userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_CONFIGURATION_VIEW_NAME, ""));
}
/**
* Create mocked {@link WebElement} object.
*
* @param type element type
* @param value element value
* @param isCheckbox 'true' is checkbox is desired; otherwise 'false'
* @return mocked WebElement object
*/
private static WebElement mockElement(String type, String value, boolean isCheckbox) {
WebElement element = mock(WebElement.class, withSettings().extraInterfaces(WrapsDriver.TYPE));
when(element.getTagName()).thenReturn(type);
if (isCheckbox) {
when(element.getAttribute("type")).thenReturn("checkbox");
when(element.getAttribute("value")).thenReturn("isSelected: " + value);
when(element.isSelected()).thenReturn(Boolean.parseBoolean(value));
} else {
when(element.getAttribute("type")).thenReturn("text");
when(element.getAttribute("value")).thenReturn(value);
when(element.isSelected()).thenReturn(false);
}
WebDriver driver = mockDriver();
when(WrapsDriver.getWrappedDriver.apply(element)).thenReturn(driver);
return element;
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts("[object HTMLDListElement]")
public void simpleScriptable() throws Exception {
final String html = "<html><head>\n"
+ "<script>\n"
+ " function test() {\n"
+ " alert(document.getElementById('myId'));\n"
+ " }\n"
+ "</script>\n"
+ "</head><body onload='test()'>\n"
+ " <dl id='myId'>\n"
+ " <dt>Some Term</dt>\n"
+ " <dd>A description</dd>\n"
+ " </dl>\n"
+ "</body></html>";
final WebDriver driver = loadPageWithAlerts2(html);
if (driver instanceof HtmlUnitDriver) {
final HtmlPage page = (HtmlPage) getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
assertTrue(HtmlDefinitionList.class.isInstance(page.getHtmlElementById("myId")));
}
}
/**
* @throws Exception if an error occurs
*/
@Test
@Alerts({"click span1", "click check1Label", "click listItem1", "click list",
"click check1", "click check1Label",
"click listItem1", "click list", "false"})
public void triggerCheckboxComplexCaseChecked() throws Exception {
final String html =
" <ul onclick='log(\"click list\")'>\n"
+ " <li onclick='log(\"click listItem1\")'>\n"
+ " <label id='check1Label' for='check1' onclick='log(\"click check1Label\")'>\n"
+ " <span>\n"
+ " <input id='check1' name='checks' value='1' type='checkbox' checked "
+ "onclick='log(\"click check1\");'>\n"
+ " <span id='check1Span' onclick='log(\"click span1\")'>Checkbox 1</span>\n"
+ " </span>\n"
+ " </label>\n"
+ " </li>\n"
+ " </ul>\n"
+ " <button id='check' onclick='log(document.getElementById(\"check1\").checked)'>Check</button>\n";
final WebDriver driver = loadPage2(generatePage(html));
driver.findElement(By.id("check1Span")).click();
driver.findElement(By.id("check")).click();
assertTitle(driver, String.join(";", getExpectedAlerts()) + ";");
}
/**
* Regression test for Bug #655.
* @throws Exception if the test fails
*/
@Test
public void stackOverflowWithInnerHTML() throws Exception {
final String html = "<html><head><title>Recursion</title></head>\n"
+ "<body>\n"
+ "<script>\n"
+ " document.body.innerHTML = unescape(document.body.innerHTML);\n"
+ "</script></body></html>";
final WebDriver driver = loadPageWithAlerts2(html);
assertTitle(driver, "Recursion");
}
/**
* @throws Exception if an error occurs
*/
@Test
@Alerts({"keydown (target)", "keydown (body)"})
public void eventHandler() throws Exception {
final String html =
"<html>\n"
+ " <head>\n"
+ " <script>\n"
+ " function test() {\n"
+ " var target = document.getElementById('target');\n"
+ " target.onkeydown = function() {\n"
+ " alert('keydown (target)');\n"
+ " };\n"
+ " document.body.onkeydown = function() {\n"
+ " alert('keydown (body)');\n"
+ " };\n"
+ " }\n"
+ " </script>\n"
+ " </head>\n"
+ " <body onload='test()'>\n"
+ " <input id='target' type='checkbox'>\n"
+ " </body>\n"
+ "</html>";
final WebDriver driver = loadPage2(html);
driver.findElement(By.id("target")).sendKeys("a");
verifyAlerts(DEFAULT_WAIT_TIME, driver, getExpectedAlerts());
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts("c1=1; c2=2; c3=3; c4=4")
public void storedDomain1() throws Exception {
final List<NameValuePair> responseHeader = new ArrayList<>();
responseHeader.add(new NameValuePair("Set-Cookie", "c1=1; Domain=." + DOMAIN + "; Path=/"));
responseHeader.add(new NameValuePair("Set-Cookie", "c2=2; Domain=" + DOMAIN + "; Path=/"));
responseHeader.add(new NameValuePair("Set-Cookie", "c3=3; Domain=.host1." + DOMAIN + "; Path=/"));
responseHeader.add(new NameValuePair("Set-Cookie", "c4=4; Domain=host1." + DOMAIN + "; Path=/"));
responseHeader.add(new NameValuePair("Set-Cookie", "c5=5; Domain=." + DOMAIN + ":" + PORT + "; Path=/"));
responseHeader.add(new NameValuePair("Set-Cookie", "c6=6; Domain=" + DOMAIN + ":" + PORT + "; Path=/"));
responseHeader.add(new NameValuePair("Set-Cookie", "c7=7; Domain=.host1." + DOMAIN + ":" + PORT + "; Path=/"));
responseHeader.add(new NameValuePair("Set-Cookie", "c8=8; Domain=host1." + DOMAIN + ":" + PORT + "; Path=/"));
responseHeader.add(new NameValuePair("Set-Cookie", "c9=9; Domain=.org; Path=/"));
responseHeader.add(new NameValuePair("Set-Cookie", "c10=10; Domain=org; Path=/"));
responseHeader.add(new NameValuePair("Set-Cookie", "c11=11; Domain=.htmlunit; Path=/"));
responseHeader.add(new NameValuePair("Set-Cookie", "c12=12; Domain=htmlunit; Path=/"));
getMockWebConnection().setDefaultResponse(CookieManagerTest.HTML_ALERT_COOKIE, 200, "Ok",
MimeType.TEXT_HTML, responseHeader);
final WebDriver driver = loadPageWithAlerts2(new URL(URL_HOST1));
assertEquals("c1=1; path=/; domain=.htmlunit.org", driver.manage().getCookieNamed("c1").toString());
assertEquals("c2=2; path=/; domain=.htmlunit.org", driver.manage().getCookieNamed("c2").toString());
assertEquals("c3=3; path=/; domain=.host1.htmlunit.org", driver.manage().getCookieNamed("c3").toString());
assertEquals("c4=4; path=/; domain=.host1.htmlunit.org", driver.manage().getCookieNamed("c4").toString());
}
private static boolean isEdgeOrSafari(WebDriver driver) {
if (!(driver instanceof RemoteWebDriver)) {
return false;
}
String browserName = ((RemoteWebDriver) driver).getCapabilities().getBrowserName();
return BrowserType.EDGE.equals(browserName) || BrowserType.SAFARI.equals(browserName);
}
private boolean moveToElementWithJS(WebDriver driver, Element locator) {
try {
String mouseOverScript = getJSElement(driver, locator) + " if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false);" +
" elem.dispatchEvent(evObj);} else if(document.createEventObject) { elem.fireEvent('onmouseover');}";
((JavascriptExecutor) driver).executeScript(mouseOverScript);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Test
public void testShouldRecreateADriverAfterDismissAll() {
WebDriver driver = factory.getDriver(fakeCapabilities);
factory.dismissAll();
WebDriver driver2 = factory.getDriver(fakeCapabilities);
assertNotSame(driver2, driver);
assertTrue(isActive(driver2));
assertFalse(isActive(driver));
}
/**
* Test for the right event sequence when clicking.
*
* @throws Exception if the test fails
*/
@Test
@Alerts(DEFAULT = "onchange-select; onclick-option; onclick-select;",
IE = "onchange-select; onclick-select;")
@BuggyWebDriver(CHROME = "onchange-select; onclick-select;",
FF = "onchange-select; onclick-select;")
public void clickOptionEventSequence1() throws Exception {
final String html =
HtmlPageTest.STANDARDS_MODE_PREFIX_
+ "<html><head>\n"
+ "<script>\n"
+ " function log(x) {\n"
+ " document.getElementById('log_').value += x + '; ';\n"
+ " }\n"
+ "</script></head>\n"
+ "<body>\n"
+ "<form>\n"
+ " <textarea id='log_' rows='4' cols='50'></textarea>\n"
+ " <select id='s' size='2' onclick=\"log('onclick-select')\""
+ " onchange=\"log('onchange-select')\">\n"
+ " <option id='clickId' value='a' onclick=\"log('onclick-option')\""
+ " onchange=\"log('onchange-option')\">A</option>\n"
+ " </select>\n"
+ "</form>\n"
+ "</body></html>";
final WebDriver driver = loadPage2(html);
driver.findElement(By.id("clickId")).click();
final List<String> alerts = new LinkedList<>();
final WebElement log = driver.findElement(By.id("log_"));
alerts.add(log.getAttribute("value").trim());
assertEquals(getExpectedAlerts(), alerts);
}
private void waitForElementDisappearance(String xpath) {
FluentWait<WebDriver> wait =
new FluentWait<WebDriver>(seleniumWebDriver)
.withTimeout(REDRAW_UI_ELEMENTS_TIMEOUT_SEC, TimeUnit.SECONDS)
.pollingEvery(200, TimeUnit.MILLISECONDS)
.ignoring(StaleElementReferenceException.class);
wait.until(
(Function<WebDriver, Boolean>)
driver -> {
List<WebElement> elements = seleniumWebDriver.findElements(By.xpath(xpath));
return elements.isEmpty() || elements.get(0).isDisplayed();
});
}
@Override
protected Void handleSeleneseCommand(WebDriver driver, String name, String ignored) {
Cookie cookie = driver.manage().getCookieNamed(name);
if (cookie != null) {
driver.manage().deleteCookieNamed(name);
}
return null;
}
/**
* check if artifact exists
*
* @param driver WebDriver
* @param name String
* @param timeout long
* @return boolean
*/
public static boolean artifactExists(WebDriver driver, String name, long timeout) {
String url = getUrl(driver, name);
String username = getField(url, 1);
String password = getField(url, 2);
try {
return new WebDriverWait(driver, timeout).until((k) -> checkArtifactUsingHttp(url, username, password));
} catch (Exception e) {
LOGGER.debug(e);
return false;
}
}
/**
* Test the use of innerHTML to set new HTML code.
* @throws Exception if the test fails
*/
@Test
@Alerts({"Old = <b>Old innerHTML</b><!-- old comment -->",
"New = <b><i id=\"newElt\">New cell value</i></b>",
"I"})
public void getSetInnerHTMLComplex() throws Exception {
final String html = "<html>\n"
+ "<head>\n"
+ " <title>test</title>\n"
+ " <script>\n"
+ " function log(x) {\n"
+ " document.getElementById('log').value += x + '\\n';\n"
+ " }\n"
+ " function doTest() {\n"
+ " var myNode = document.getElementById('myNode');\n"
+ " log('Old = ' + myNode.innerHTML);\n"
+ " myNode.innerHTML = ' <b><i id=\"newElt\">New cell value</i></b>';\n"
+ " log('New = ' + myNode.innerHTML);\n"
+ " log(document.getElementById('newElt').tagName);\n"
+ " }\n"
+ " </script>\n"
+ "</head>\n"
+ "<body onload='doTest()'>\n"
+ " <p id='myNode'><b>Old innerHTML</b><!-- old comment --></p>\n"
+ " <textarea id='log'></textarea>\n"
+ "</body>\n"
+ "</html>";
final WebDriver driver = loadPage2(html);
final WebElement log = driver.findElement(By.id("log"));
final String text = log.getAttribute("value").trim().replaceAll("\r", "");
assertEquals(String.join("\n", getExpectedAlerts()), text);
final WebElement pElt = driver.findElement(By.id("myNode"));
assertEquals("p", pElt.getTagName());
final WebElement elt = driver.findElement(By.id("newElt"));
assertEquals("New cell value", elt.getText());
assertEquals(1, driver.getWindowHandles().size());
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"http://htmlunit.sourceforge.net/", "§§URL§§test", "§§URL§§#test",
"§§URL§§#", "§§URL§§"})
public void getDefaultValue() throws Exception {
final String html
= "<html><head><title>AnchorTest</title>\n"
+ "<script>\n"
+ " function test() {\n"
+ " alert(document.getElementById('absolute'));\n"
+ " alert(document.getElementById('relative'));\n"
+ " alert(document.getElementById('hash'));\n"
+ " alert(document.getElementById('hashOnly'));\n"
+ " alert(document.getElementById('empty'));\n"
+ " }\n</script>\n"
+ "</head>\n"
+ "<body onload='test()'>\n"
+ " <a href='http://htmlunit.sourceforge.net/' id='absolute'>bla</a>\n"
+ " <a href='test' id='relative'>bla</a>\n"
+ " <a href='#test' id='hash'>bla</a>\n"
+ " <a href='#' id='hashOnly'>bla</a>\n"
+ " <a href='' id='empty'>bla</a>\n"
+ "</body></html>";
final WebDriver driver = loadPage2(html);
expandExpectedAlertsVariables(URL_FIRST);
verifyAlerts(driver, getExpectedAlerts());
}
/**
* @throws Exception if the test fails
*/
@Test
public void clickByJSAfterHtmlForSetByJS() throws Exception {
final String html
= "<html>\n"
+ " <head>\n"
+ " <script>\n"
+ " function doTest() {\n"
+ " document.getElementById('label1').htmlFor = 'checkbox1';\n"
+ " }\n"
+ " function delegateClick() {\n"
+ " try {\n"
+ " document.getElementById('label1').click();\n"
+ " } catch (e) {}\n"
+ " }\n"
+ " </script>\n"
+ " </head>\n"
+ " <body onload='doTest()'>\n"
+ " <label id='label1'>My Label</label>\n"
+ " <input type='checkbox' id='checkbox1'><br>\n"
+ " <input type=button id='button1' value='Test' onclick='delegateClick()'>\n"
+ " </body>\n"
+ "</html>";
final WebDriver driver = loadPage2(html);
final WebElement checkbox = driver.findElement(By.id("checkbox1"));
assertFalse(checkbox.isSelected());
driver.findElement(By.id("button1")).click();
assertTrue(checkbox.isSelected());
}
public static Set<LogEntry> getFilteredLog(WebDriver driver, Collection<BrowserLogLevel> logLevelsToInclude)
{
LogEntries log = getLog(driver);
return logLevelsToInclude.stream()
.map(BrowserLogLevel::getLevel)
.flatMap(level -> filter(log, level))
.collect(Collectors.toCollection(LinkedHashSet::new));
}
/**
* Adds the webdriver to the sessionData map.
*
* @param sessionData
* @throws KiteGridException
*/
private void addToSessionMap(Map<WebDriver, Map<String, Object>> sessionData) throws KiteGridException {
Map<String, Object> map = new HashMap<>();
map.put("end_point", this);
// if (!this.isApp()) {
String node = TestUtils.getNode(
this.getPaas().getUrl(),
((RemoteWebDriver) this.getWebDriver()).getSessionId().toString());
if (node != null) {
map.put("node_host", node);
}
// }
sessionData.put(this.getWebDriver(), map);
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"load;", "2"})
public void emptyMimeType() throws Exception {
try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) {
final byte[] directBytes = IOUtils.toByteArray(is);
final URL urlImage = new URL(URL_SECOND, "img.jpg");
final List<NameValuePair> emptyList = Collections.emptyList();
getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "", emptyList);
getMockWebConnection().setDefaultResponse("Test");
}
final String html = "<html><head>\n"
+ "<script>\n"
+ " function showInfo(text) {\n"
+ " document.title += text + ';';\n"
+ " }\n"
+ "</script>\n"
+ "</head><body>\n"
+ " <img id='myImage5' src='" + URL_SECOND + "img.jpg' onload='showInfo(\"load\")' "
+ "onerror='showInfo(\"error\")'>\n"
+ "</body></html>";
final int count = getMockWebConnection().getRequestCount();
final WebDriver driver = getWebDriver();
if (driver instanceof HtmlUnitDriver) {
((HtmlUnitDriver) driver).setDownloadImages(true);
}
loadPage2(html);
assertTitle(driver, getExpectedAlerts()[0]);
assertEquals(Integer.parseInt(getExpectedAlerts()[1]), getMockWebConnection().getRequestCount() - count);
}
/**
* @throws Exception if an error occurs
*/
@Test
public void asText() throws Exception {
final String html = "<html><head><meta id='m' http-equiv='a' content='b'></head><body></body></html>";
final WebDriver driver = loadPageWithAlerts2(html);
final String text = driver.findElement(By.id("m")).getText();
assertEquals("", text);
}
public static WebDriver getFirefoxDriver(String pathToFirefoxExecutable)
{
String path = "src/test/resources/geckodriver";
System.setProperty("webdriver.gecko.driver", path);
System.setProperty("webdriver.firefox.bin", pathToFirefoxExecutable);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
capabilities.setCapability("networkConnectionEnabled", true);
capabilities.setCapability("browserConnectionEnabled", true);
WebDriver driver = new MarionetteDriver(capabilities);
return driver;
}
/**
* @throws Exception if the test fails
*/
@Test
public void asText() throws Exception {
final String html = "<html><head>\n"
+ "</head><body>\n"
+ "Hello<br/>world\n"
+ "</body></html>";
final WebDriver driver = loadPageWithAlerts2(html);
if (driver instanceof HtmlUnitDriver) {
final HtmlPage page = (HtmlPage) getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
assertEquals("Hello" + System.lineSeparator() + "world", page.getBody().asText());
}
}