@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 @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"); }
@JavascriptEnabled @Ignore( value = {SAFARI, MARIONETTE}, reason = " Safari: issue 4061. Other platforms: not properly tested") @Test public void testChangeEventIsFiredAppropriatelyWhenFocusIsLost() { driver.get(pages.javascriptPage); WebElement input = driver.findElement(By.id("changeable")); input.sendKeys("test"); moveFocus(); assertThat( driver.findElement(By.id("result")).getText().trim(), Matchers.<String>either(is("focus change blur")).or(is("focus blur change"))); input.sendKeys(Keys.BACK_SPACE, "t"); moveFocus(); // I weep. assertThat( driver.findElement(By.id("result")).getText().trim(), Matchers.<String>either(is("focus change blur focus blur")) .or(is("focus blur change focus blur")) .or(is("focus blur change focus blur change")) .or(is("focus change blur focus change blur"))); // What Chrome does }
@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")); }
// odi.614 Able to generate reports for time range public void search() { String dmName = "US_AIRWAYS"; gotoreports(dmName); try { driver.findElement(By.id("PARAM_START_DATE")).clear(); Alert alert = driver.switchTo().alert(); alert.dismiss(); driver.findElement(By.id("PARAM_START_DATE")).sendKeys("8/11/2013"); driver.findElement(By.id("PARAM_END_DATE")).clear(); alert.dismiss(); driver.findElement(By.id("PARAM_END_DATE")).sendKeys("9/11/2013"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); new WebDriverWait(driver, 10) .until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("reportContent")); WebElement page = new WebDriverWait(driver, 10) .until(ExpectedConditions.visibilityOfElementLocated(By.id("CrystalViewer"))); WebElement rangeStart = page.findElement(By.xpath("//*[contains(text(),'8/11/2013')]")); WebElement rangeEnd = page.findElement(By.xpath("//*[contains(text(),'9/11/2013')]")); if (rangeStart != null && rangeEnd != null) { System.out.println("Report for selected range is showed"); } ReportFile = new WriteXmlFile(); driver.switchTo().defaultContent(); ReportFile.addTestCase("ODI6.x-614:CSSR-Search", "ODI6.x-614:CSSR-Search => Pass"); } catch (Exception e) { System.out.print("trace: "); e.printStackTrace(); } // driver.quit(); ReportFile.WriteToFile(); }
@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 testShouldBeAbleToFindASingleElementByCompoundCssSelector() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.cssSelector("div.extraDiv, div.content")); assertThat(element.getTagName().toLowerCase(), is("div")); assertThat(element.getAttribute("class"), is("content")); }
public File takeScreenshot(WebElement element) { if (!WebDriverRunner.hasWebDriverStarted()) { log.warning("Cannot take screenshot because browser is not started"); return null; } WebDriver webdriver = getWebDriver(); if (!(webdriver instanceof TakesScreenshot)) { log.warning("Cannot take screenshot because browser does not support screenshots"); return null; } File screen = ((TakesScreenshot) webdriver).getScreenshotAs(OutputType.FILE); Point p = element.getLocation(); Dimension elementSize = element.getSize(); try { BufferedImage img = ImageIO.read(screen); BufferedImage dest = img.getSubimage(p.getX(), p.getY(), elementSize.getWidth(), elementSize.getHeight()); ImageIO.write(dest, "png", screen); File screenshotOfElement = new File(generateScreenshotFileName()); FileUtils.copyFile(screen, screenshotOfElement); return screenshotOfElement; } catch (IOException e) { printOnce("takeScreenshotImage", e); return null; } }
// 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
@Test @Ignore( "I would love for this to work consistently but it fails too often between releases to use as an example") public void multiSelectWithUserInteractions() { WebElement multiSelect; multiSelect = driver.findElement(By.cssSelector("select[multiple='multiple']")); List<WebElement> multiSelectOptions = multiSelect.findElements(By.tagName("option")); // in real life, clicking on a multi select item without holding down // CTRL will deselect all others and select only that one item Actions actions = new Actions(driver); actions .click(multiSelectOptions.get(0)) .click(multiSelectOptions.get(1)) .click(multiSelectOptions.get(2)) .perform(); clickSubmitButton(); new WebDriverWait(driver, 10).until(ExpectedConditions.titleIs("Processed Form Details")); assertEquals( "Expected only 1 match", 1, driver.findElements(By.cssSelector("[id^='_valuemultipleselect']")).size()); }
/** * 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(expected = ElementNotVisibleException.class) public void throwExceptionWhenInteractingWithInvisibleElement() { server.setGetHandler( new HttpRequestCallback() { @Override public void call(HttpServletRequest req, HttpServletResponse res) throws IOException { res.getOutputStream() .println( "<!DOCTYPE html>" + "<html>" + " <head>\n" + " <title>test</title>\n" + " </head>\n" + " <body>\n" + " <input id=\"visible\">\n" + " <input style=\"display:none\" id=\"invisible\">\n" + " </body>" + "</html>"); } }); WebDriver d = getDriver(); d.get(server.getBaseUrl()); WebElement visibleInput = d.findElement(By.id("visible")); WebElement invisibleInput = d.findElement(By.id("invisible")); String textToType = "text to type"; visibleInput.sendKeys(textToType); assertEquals(textToType, visibleInput.getAttribute("value")); invisibleInput.sendKeys(textToType); }
private boolean clickNext(WebDriver driver) { while (true) { boolean clicked = false; int iteration = 0; By by = By.className("show-next"); clickCloseModalIfAny(driver); for (WebElement el : driver.findElements(by)) { try { waitdriver.until(ExpectedConditions.elementToBeClickable(by)); el.click(); clicked = true; return true; } catch (Exception ex) { } } if (!clicked) { iteration++; continue; } if (!clicked && iteration > 3) { log.error("Element not clickable"); return false; } } }
@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()); }
@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()); }
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(); }
// Q: what happens if I send text to alert? // A: ElementNotVisibleException in Firefox // A: in Chrome the text is sent @Test public void basicAlertHandlingKeysTest() { WebElement alertButton; WebElement alertResult; alertButton = driver.findElement(By.id("alertexamples")); alertButton.click(); String alertMessage = "I am an alert box!"; assertEquals(alertMessage, driver.switchTo().alert().getText()); if (Driver.currentDriver == Driver.BrowserName.FIREFOX) { try { driver.switchTo().alert().sendKeys("Hello keys Accept"); fail("expected a ElementNotVisibleException thrown"); } catch (ElementNotVisibleException e) { assertTrue("Expected to get an exception", true); } } if (Driver.currentDriver == Driver.BrowserName.GOOGLECHROME) { // chrome seems happy to send in text to an alert driver.switchTo().alert().sendKeys("Hello keys Accept"); } driver.switchTo().alert().accept(); }
/* * (non-Javadoc) * * @see * qc.automation.framework.widget.IEditableField#setValue(java.lang.String) */ @Override public void setValue(Object value) throws WidgetException { try { if (value instanceof String) { boolean selected = false; List<WebElement> elements = findElements(); for (WebElement we : elements) { if (we.getAttribute("value").equals(value)) { we.click(); selected = true; break; } } if (!selected) throw new WidgetException("Could not find desired option to select", getLocator()); } else { throw new WidgetException( "Invalid type. 'value' must be a 'String' type of desired option to select", getLocator()); } } catch (Exception e) { throw new WidgetException("Error while selecting option on radio group", getLocator(), e); } }
@Ignore({IE, SAFARI, CHROME}) @Test public void testShouldBeAbleToFindElementByXPathInXmlDocument() { driver.get(pages.simpleXmlDocument); WebElement element = driver.findElement(By.xpath("//foo")); assertThat(element.getText(), is("baz")); }
/*Admin Login*/ public void admin(String userAd, String passAd) { driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); siteAdmin.click(); userFieldAdmin.sendKeys(userAd); passFieldAdmin.sendKeys(passAd); loginButtonAdmin.click(); }
@Test @Ignore(MARIONETTE) public void testShouldBeAbleToFindASingleElementByNumericId() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.id("2")); assertThat(element.getAttribute("id"), is("2")); }
@JavascriptEnabled @Test public void shouldBeAbleToExecuteAsynchronousScripts() { driver.get(pages.ajaxyPage); WebElement typer = driver.findElement(By.name("typer")); typer.sendKeys("bob"); assertEquals("bob", typer.getAttribute("value")); driver.findElement(By.id("red")).click(); driver.findElement(By.name("submit")).click(); assertEquals( "There should only be 1 DIV at this point, which is used for the butter message", 1, getNumDivElements()); driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS); String text = (String) executor.executeAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.registerListener(arguments[arguments.length - 1]);"); assertEquals("bob", text); assertEquals("", typer.getAttribute("value")); assertEquals( "There should be 1 DIV (for the butter message) + 1 DIV (for the new label)", 2, getNumDivElements()); }
@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 testCanClickOnSuckerFishMenuItem() throws Exception { if (!hasInputDevices()) { return; } driver.get(pages.javascriptPage); WebElement element = driver.findElement(By.id("menu1")); if (!TestUtilities.isNativeEventsEnabled(driver)) { System.out.println("Skipping hover test: needs native events"); return; } new Actions(driver).moveToElement(element).build().perform(); WebElement target = driver.findElement(By.id("item1")); assertTrue(target.isDisplayed()); target.click(); String text = driver.findElement(By.id("result")).getText(); assertTrue(text.contains("item 1")); }
private boolean isAFormElement(WebElement webElement) { if ((webElement == null) || (webElement.getTagName() == null)) { return false; } String tag = webElement.getTagName().toLowerCase(); return HTML_FORM_TAGS.contains(tag); }
@Test public void testWritableTextAreaShouldClear() { driver.get(pages.readOnlyPage); WebElement element = driver.findElement(By.id("writableTextArea")); element.clear(); assertEquals("", element.getAttribute("value")); }
public static List<Image> getPictureElements( WebDriver driver, WebElement webElementSet, int componentNo) { List<WebElement> elements = new ArrayList<WebElement>(); for (String selector : imageCssLocators) { elements.addAll( WebPageHelpers.createWebElementsList(driver, webElementSet, By.cssSelector(selector))); } // Add to the list if the webElementSet is an image it's self if (webElementSet.getTagName().equals("img")) { elements.add(0, webElementSet); } List<Image> Images = new ArrayList<Image>(); // Iterate elements list to populate imageBeans list ImageBeans if (WebPageHelpers.testWebElementListNotEmpty(elements)) { for (WebElement element : elements) { Image image = new Image( element.getAttribute("src"), element.getAttribute("width"), element.getAttribute("height")); Images.add(image); } } if (Images.isEmpty()) { return null; } else { return Images; } }
@Test public void testContentEditableAreaShouldClear() { driver.get(pages.readOnlyPage); WebElement element = driver.findElement(By.id("content-editable")); element.clear(); assertEquals("", element.getText()); }
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")); }
@JavascriptEnabled @Ignore( value = {HTMLUNIT, IPHONE, SELENESE, ANDROID}, reason = "untested user agents") @Test public void testNumberpadKeys() { driver.get(pages.javascriptPage); WebElement element = driver.findElement(By.id("keyReporter")); element.sendKeys( "abcd" + Keys.MULTIPLY + Keys.SUBTRACT + Keys.ADD + Keys.DECIMAL + Keys.SEPARATOR + Keys.NUMPAD0 + Keys.NUMPAD9 + Keys.ADD + Keys.SEMICOLON + Keys.EQUALS + Keys.DIVIDE + Keys.NUMPAD3 + "abcd"); assertThat(element.getAttribute("value"), is("abcd*-+.,09+;=/3abcd")); }