@Test public void basicPromptConfirmHandlingAcceptTest() { WebElement promptButton; WebElement promptResult; promptButton = driver.findElement(By.id("promptexample")); promptResult = driver.findElement(By.id("promptreturn")); assertEquals("pret", promptResult.getText()); promptButton.click(); String alertMessage = "I prompt you"; Alert promptAlert = driver.switchTo().alert(); if (Driver.currentDriver != Driver.BrowserName.IE) { // no point doing this in IE as we know it isn't the actual prompt assertEquals(alertMessage, promptAlert.getText()); } promptAlert.accept(); assertEquals("change me", promptResult.getText()); }
@Test public void basicPromptConfirmHandlingDismissTest() { WebElement promptButton; WebElement promptResult; promptButton = driver.findElement(By.id("promptexample")); promptResult = driver.findElement(By.id("promptreturn")); assertEquals("pret", promptResult.getText()); promptButton.click(); String alertMessage = "I prompt you"; Alert promptAlert = driver.switchTo().alert(); if (Driver.currentDriver == Driver.BrowserName.IE) { // In IE the alert always returns "Script Prompt:" and not the // actual prompt text, so this line is just to alert me if the // functionality changes if (!promptAlert.getText().equals("Script Prompt:")) { throw new RuntimeException("IE now does not do Script Prompt"); } } else { // only check the alert prompt if not in IE assertEquals(alertMessage, promptAlert.getText()); } promptAlert.dismiss(); assertEquals("pret", promptResult.getText()); }
@JavascriptEnabled @Ignore( value = {ANDROID, IPHONE, OPERA, SAFARI, SELENESE, OPERA_MOBILE}, reason = "Android/iOS/Opera Mobile: does not support contentEditable;" + "Safari/Selenium: cannot type on contentEditable with synthetic events") @Test public void testTypingIntoAnIFrameWithContentEditableOrDesignModeSet() { driver.get(pages.richTextPage); driver.switchTo().frame("editFrame"); WebElement element = driver.switchTo().activeElement(); element.sendKeys("Fishy"); driver.switchTo().defaultContent(); WebElement trusted = driver.findElement(By.id("istrusted")); WebElement id = driver.findElement(By.id("tagId")); assertThat( trusted.getText(), anyOf( equalTo("[true]"), // Chrome does not set a trusted flag. equalTo("[n/a]"), equalTo("[]"))); assertThat(id.getText(), anyOf(equalTo("[frameHtml]"), equalTo("[theBody]"))); }
@Test public void testShouldClickOnGraphVisualElements() { driver.get(pages.svgPage); WebElement svg = driver.findElement(By.cssSelector("svg")); if (isFirefox30(driver) && isNativeEventsEnabled(driver)) { System.out.println( "Not testing SVG elements with Firefox 3.0 and native events as" + " this functionality is not working."); return; } List<WebElement> groupElements = svg.findElements(By.cssSelector("g")); assertEquals(5, groupElements.size()); groupElements.get(1).click(); WebElement resultElement = driver.findElement(By.id("result")); waitFor(elementTextToEqual(resultElement, "slice_red")); assertEquals("slice_red", resultElement.getText()); groupElements.get(2).click(); resultElement = driver.findElement(By.id("result")); waitFor(elementTextToEqual(resultElement, "slice_green")); assertEquals("slice_green", resultElement.getText()); }
@JavascriptEnabled @Ignore( value = {HTMLUNIT, IPHONE, SELENESE, ANDROID}, reason = "untested user agents") @Test public void testShouldReportKeyCodeOfArrowKeysUpDownEvents() { assumeFalse( Browser.detect() == Browser.opera && TestUtilities.getEffectivePlatform().is(Platform.WINDOWS)); driver.get(pages.javascriptPage); WebElement result = driver.findElement(By.id("result")); WebElement element = driver.findElement(By.id("keyReporter")); element.sendKeys(Keys.ARROW_DOWN); assertThat(result.getText().trim(), containsString("down: 40")); assertThat(result.getText().trim(), containsString("up: 40")); element.sendKeys(Keys.ARROW_UP); assertThat(result.getText().trim(), containsString("down: 38")); assertThat(result.getText().trim(), containsString("up: 38")); element.sendKeys(Keys.ARROW_LEFT); assertThat(result.getText().trim(), containsString("down: 37")); assertThat(result.getText().trim(), containsString("up: 37")); element.sendKeys(Keys.ARROW_RIGHT); assertThat(result.getText().trim(), containsString("down: 39")); assertThat(result.getText().trim(), containsString("up: 39")); // And leave no rubbish/printable keys in the "keyReporter" assertThat(element.getAttribute("value"), is("")); }
@JavascriptEnabled @Ignore( value = {HTMLUNIT, IPHONE, SELENESE, OPERA, FIREFOX}, reason = "This is an IE only tests") @NoDriverAfterTest @NeedsLocalEnvironment @Test public void testPersistentHoverCanBeTurnedOff() throws Exception { if (!hasInputDevices()) { return; } assumeTrue(TestUtilities.isInternetExplorer(driver)); // Destroy the previous driver to make sure the hovering thread is // stopped. driver.quit(); DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability(ENABLE_PERSISTENT_HOVERING, false); WebDriverBuilder builder = new WebDriverBuilder().setDesiredCapabilities(caps); driver = builder.get(); try { driver.get(pages.javascriptPage); // Move to a different element to make sure the mouse is not over the // element with id 'item1' (from a previous test). new Actions(driver).moveToElement(driver.findElement(By.id("keyUp"))).build().perform(); WebElement element = driver.findElement(By.id("menu1")); final WebElement item = driver.findElement(By.id("item1")); assertEquals("", item.getText()); ((JavascriptExecutor) driver) .executeScript("arguments[0].style.background = 'green'", element); new Actions(driver).moveToElement(element).build().perform(); // Move the mouse somewhere - to make sure that the thread firing the events making // hover persistent is not active. Robot robot = new Robot(); robot.mouseMove(50, 50); // Intentionally wait to make sure hover DOES NOT persist. Thread.sleep(1000); waitFor( new Callable<Boolean>() { public Boolean call() throws Exception { return item.getText().equals(""); } }); assertEquals("", item.getText()); } finally { driver.quit(); } }
@Ignore( value = {ALL}, reason = "Untested except in Firefox", issues = {2825}) @Test public void testShouldBeAbleToTypeIntoContentEditableElementWithExistingValue() { driver.get(pages.readOnlyPage); WebElement editable = driver.findElement(By.id("content-editable")); String initialText = editable.getText(); editable.sendKeys(", edited"); assertThat(editable.getText(), equalTo(initialText + ", edited")); }
@JavascriptEnabled @Ignore( value = {HTMLUNIT, IPHONE, SELENESE, OPERA}, reason = "HtmlUnit: Advanced mouse actions only implemented in rendered browsers") @Test public void testHoverPersists() throws Exception { if (!hasInputDevices()) { return; } if (!TestUtilities.isNativeEventsEnabled(driver)) { System.out.println("Skipping hover test: needs native events"); return; } // This test passes on IE. When running in Firefox on Windows, the test // will fail if the mouse cursor is not in the window. Solution: Maximize. if ((TestUtilities.getEffectivePlatform().is(Platform.WINDOWS)) && TestUtilities.isFirefox(driver)) { driver.manage().window().maximize(); } driver.get(pages.javascriptPage); // Move to a different element to make sure the mouse is not over the // element with id 'item1' (from a previous test). new Actions(driver).moveToElement(driver.findElement(By.id("dynamo"))).build().perform(); WebElement element = driver.findElement(By.id("menu1")); final WebElement item = driver.findElement(By.id("item1")); assertEquals("", item.getText()); ((JavascriptExecutor) driver).executeScript("arguments[0].style.background = 'green'", element); new Actions(driver).moveToElement(element).build().perform(); // Intentionally wait to make sure hover persists. Thread.sleep(2000); waitFor( new Callable<Boolean>() { public Boolean call() throws Exception { return !item.getText().equals(""); } }); assertEquals("Item 1", item.getText()); }
public static void main(String[] args) { String baseUrl = "http://newtours.demoaut.com/"; WebDriver driver = new FirefoxDriver(); String underConsTitle = "Under Construction: Mercury Tours"; // Creates result string driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get(baseUrl); List<WebElement> linkElements = driver.findElements(By.tagName("a")); // Creates lists from <a> tags String[] linkTexts = new String[linkElements.size()]; int i = 0; // extract the link texts of each link element for (WebElement e : linkElements) { linkTexts[i] = e.getText(); i++; } // test each link by looping over them for (String t : linkTexts) { driver.findElement(By.linkText(t)).click(); if (driver.getTitle().equals(underConsTitle)) { System.out.println("\"" + t + "\"" + " is under construction."); } else { System.out.println( "\"" + t + "\"" // print results to console + " is working."); } driver.navigate().back(); } driver.quit(); }
// Returns the number of replies to a post protected int getPostRepliesCount(String strPostDataPath) { int nReplies = 0; WebElement elemPost = getPostByDataPathOrFail(strPostDataPath); String strReplies = null; setDefaultWaitTime(2); try { /* <div class="detail-entry-replies"> <i class="icon-replies" title="Replies"></i> <span class="replies-count" title="Replies">0</span> */ String strRepliesXPath = ".//span[@class='replies-count' and @title='Replies']"; WebElement elemRepliesCount = elemPost.findElement(By.xpath(strRepliesXPath)); strReplies = elemRepliesCount.getText(); } catch (NoSuchElementException ex) { fail( "Could not find the number of replies on the post with the data path " + strPostDataPath); } resetDefaultWaitTime(); try { nReplies = Integer.parseInt(strReplies); } catch (NumberFormatException ex) { fail("Could not parse an integer out of \"" + strReplies + "\": " + ex.getMessage()); } return nReplies; } // getPostRepliesCount
/** * Returns the whole chat transcript. * * @return */ public String getTranscript() { String divisionName = "logwrapper"; WebElement chatTranscript = driver.findElement(By.className(divisionName)); String transcript = chatTranscript.getText(); transcript = transcript.replaceAll(ConstantTextStrings.STRANGER_TYPING, "").trim(); return transcript; }
@Test public void testShouldGetTextWhichIsAValidJSONObject() { driver.get(pages.simpleTestPage); WebElement element = driver.findElement(By.id("simpleJsonText")); assertEquals("{a=\"b\", c=1, d=true}", element.getText()); // assertEquals("{a=\"b\", \"c\"=d, e=true, f=\\123\\\\g\\\\\"\"\"\\\'}", element.getText()); }
@JavascriptEnabled @Ignore( value = {HTMLUNIT, SELENESE, ANDROID, OPERA, OPERA_MOBILE}, reason = "untested user agents") @Test public void testChordReveseShiftHomeSelectionDeletes() { // FIXME: macs don't have HOME keys, would PGUP work? if (Platform.getCurrent().is(Platform.MAC)) { return; } driver.get(pages.javascriptPage); WebElement result = driver.findElement(By.id("result")); WebElement element = driver.findElement(By.id("keyReporter")); element.sendKeys("done" + Keys.HOME); assertThat(element.getAttribute("value"), is("done")); element.sendKeys("" + Keys.SHIFT + "ALL " + Keys.HOME); assertThat(element.getAttribute("value"), is("ALL done")); element.sendKeys(Keys.DELETE); assertThat(element.getAttribute("value"), is("done")); element.sendKeys("" + Keys.END + Keys.SHIFT + Keys.HOME); assertThat(element.getAttribute("value"), is("done")); assertThat( // Note: trailing SHIFT up here result.getText().trim(), containsString(" up: 16")); element.sendKeys("" + Keys.DELETE); assertThat(element.getAttribute("value"), is("")); }
@JavascriptEnabled @Ignore( value = {HTMLUNIT, SELENESE, ANDROID, OPERA, OPERA_MOBILE}, reason = "untested user agents") @Test public void testChordControlHomeShiftEndDelete() { // FIXME: macs don't have HOME keys, would PGUP work? if (Platform.getCurrent().is(Platform.MAC)) { return; } driver.get(pages.javascriptPage); WebElement result = driver.findElement(By.id("result")); WebElement element = driver.findElement(By.id("keyReporter")); element.sendKeys("!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFG"); element.sendKeys(Keys.HOME); element.sendKeys("" + Keys.SHIFT + Keys.END); assertThat(result.getText(), containsString(" up: 16")); element.sendKeys(Keys.DELETE); assertThat(element.getAttribute("value"), is("")); }
public void testShouldAutomaticallyUseTheFirstFrameOnAPage() { driver.get(framesetPage); // Notice that we've not switched to the 0th frame WebElement pageNumber = driver.findElement(By.xpath("//span[@id='pageNumber']")); assertThat(pageNumber.getText().trim(), equalTo("1")); }
private static void checkRecordedKeySequence(WebElement element, int expectedKeyCode) { assertThat( element.getText().trim(), anyOf( is(String.format("down: %1$d press: %1$d up: %1$d", expectedKeyCode)), is(String.format("down: %1$d up: %1$d", expectedKeyCode)))); }
@JavascriptEnabled @Ignore(OPERA) @Test public void testDragAndDropOnJQueryItems() { driver.get(pages.droppableItems); WebElement toDrag = driver.findElement(By.id("draggable")); WebElement dropInto = driver.findElement(By.id("droppable")); // Wait until all event handlers are installed. doSleep(500); new Actions(driver).dragAndDrop(toDrag, dropInto).perform(); String text = dropInto.findElement(By.tagName("p")).getText(); long waitEndTime = System.currentTimeMillis() + 15000; while (!text.equals("Dropped!") && (System.currentTimeMillis() < waitEndTime)) { doSleep(200); text = dropInto.findElement(By.tagName("p")).getText(); } assertEquals("Dropped!", text); WebElement reporter = driver.findElement(By.id("drop_reports")); // Assert that only one mouse click took place and the mouse was moved // during it. String reporterText = reporter.getText(); Pattern pattern = Pattern.compile("start( move)* down( move)+ up( move)*"); Matcher matcher = pattern.matcher(reporterText); assertTrue("Reporter text:" + reporterText, matcher.matches()); }
@JavascriptEnabled @Test public void testSendingKeysToAFocusedElementShouldNotBlurThatElement() { assumeFalse(browserNeedsFocusOnThisOs(driver)); driver.get(pages.javascriptPage); WebElement element = driver.findElement(By.id("theworks")); element.click(); // Wait until focused boolean focused = false; WebElement result = driver.findElement(By.id("result")); for (int i = 0; i < 5; ++i) { String fired = result.getText(); if (fired.contains("focus")) { focused = true; break; } try { Thread.sleep(200); } catch (InterruptedException e) { throw new RuntimeException(e); } } if (!focused) { fail("Clicking on element didn't focus it in time - can't proceed so failing"); } element.sendKeys("a"); assertEventNotFired("blur"); }
@Ignore({IE, SAFARI, CHROME}) @Test public void testShouldBeAbleToFindElementByXPathInXmlDocument() { driver.get(pages.simpleXmlDocument); WebElement element = driver.findElement(By.xpath("//foo")); assertThat(element.getText(), is("baz")); }
@Test public void testDriverShouldBeAbleToFindElementsAfterLoadingMoreThanOnePageAtATime() { driver.get(pages.formPage); driver.get(pages.xhtmlTestPage); WebElement link = driver.findElement(By.linkText("click me")); assertThat(link.getText(), is("click me")); }
@Test public void testContentEditableAreaShouldClear() { driver.get(pages.readOnlyPage); WebElement element = driver.findElement(By.id("content-editable")); element.clear(); assertEquals("", element.getText()); }
public void testGetTextWithLineBreakForInlineElement() { driver.get(simpleTestPage); WebElement label = driver.findElement(By.id("label1")); String labelText = label.getText(); assertThat(labelText, matchesPattern("foo[\\n\\r]+bar")); }
@Test @Ignore(MARIONETTE) public void testDriverCanGetLinkByLinkTestIgnoringTrailingWhitespace() { driver.get(pages.simpleTestPage); WebElement link = driver.findElement(By.linkText("link with trailing space")); assertThat(link.getAttribute("id"), is("linkWithTrailingSpace")); assertThat(link.getText(), is("link with trailing space")); }
@Ignore({IE, MARIONETTE, SAFARI}) @NotYetImplemented(HTMLUNIT) @Test public void testShouldBeAbleToFindElementByXPathWithNamespace() { driver.get(pages.svgPage); WebElement element = driver.findElement(By.xpath("//svg:svg//svg:text")); assertThat(element.getText(), is("Test Chart")); }
@Ignore({CHROME, IPHONE, SELENESE}) @Test public void testShouldNotTrimNonBreakingSpacesAtTheStartOfALineInTheMiddleOfText() { driver.get(pages.simpleTestPage); WebElement element = driver.findElement(By.id("multilinenbsp")); String text = element.getText(); assertThat(text, containsString("\n have")); }
@Ignore({CHROME, IPHONE, SELENESE}) @Test public void testShouldNotTrimTrailingNonBreakingSpacesInMultilineText() { driver.get(pages.simpleTestPage); WebElement element = driver.findElement(By.id("multilinenbsp")); String text = element.getText(); assertThat(text, endsWith("trailing NBSPs ")); }
private void saveFile(WebDriver driver) { int iteration = 0; while (iteration < 3) { try { for (WebElement el : driver.findElements(By.className("flights-container"))) { if (el.getText().contains("outbound")) { log.info( "Saving file date={} fromDest={} toDest={} fileIndex={}", today, fromDest, toDest, fileIndex); try { Path folder = Paths.get(folderLocation + "/" + today); if (!Files.exists(folder)) { Files.createDirectory(folder); } Files.write( Paths.get( folderLocation + "/" + today + "/" + fileSimpleDateFormat.format(new Date()) + "_" + fromDest.replaceAll("/", "-") + "_" + toDest.replaceAll("/", "-") + "_" + fileIndex + ".txt"), Lists.newArrayList(el.getText())); fileIndex++; return; } catch (IOException e) { log.error("Error saving file", e); } } } } catch (StaleElementReferenceException ex) { log.warn("Stale..."); iteration++; } } }
@Ignore({REMOTE}) @Test public void testLinkWithFormattingTags() { driver.get(pages.simpleTestPage); WebElement elem = driver.findElement(By.id("links")); WebElement res = elem.findElement(By.partialLinkText("link with formatting tags")); assertThat(res.getText(), is("link with formatting tags")); }
@Ignore({IPHONE, SELENESE}) public void testShouldTreatANonBreakingSpaceAsAnyOtherWhitespaceCharacterWhenCollapsingWhitespace() { driver.get(simpleTestPage); WebElement element = driver.findElement(By.id("nbspandspaces")); String text = element.getText(); assertThat(text, equalTo("This line has a non-breaking space and spaces")); }
private static WebElement findAppleElement(List<WebElement> textElements) { for (WebElement currentElement : textElements) { if (currentElement.getText().contains("Apple")) { return currentElement; } } return null; }