List of usage examples for org.openqa.selenium WebElement getAttribute
String getAttribute(String name);
From source file:com.linagora.obm.ui.scenario.user.UserStepdefs.java
License:Open Source License
@Then("creation succeeds") public void creationSucceeds() { List<WebElement> okMessages = processedCreationSummaryPage.elMessagesOk(); assertThat(processedCreationSummaryPage.elMessagesInfo()).isEmpty(); assertThat(processedCreationSummaryPage.elMessagesError()).isEmpty(); assertThat(processedCreationSummaryPage.elMessagesWarning()).isEmpty(); assertThat(okMessages).hasSize(2);/*from ww w . j av a2 s . c o m*/ assertThat(okMessages.get(0).getText()).isEqualTo("Utilisateur : Insertion russie"); WebElement findElement = okMessages.get(1).findElement(By.tagName("input")); assertThat(findElement.getAttribute("value")).isEqualTo("Tlcharger la fiche utilisateur"); }
From source file:com.livejournal.uisteps.core.Browser.java
License:Apache License
public void click(WrapsElement element) { boolean needToSwitch = false; try {//from ww w . j av a2s. c o m WebElement webElement = element.getWrappedElement(); if (element instanceof Link) { String attrTarget = webElement.getAttribute("target"); needToSwitch = attrTarget != null && !attrTarget.equals("") && !attrTarget.equals("_self"); } webElement.click(); if (needToSwitch) { switchToNextWindow(); } } catch (Exception ex) { Assert.fail("Cannot click " + element + "! " + ex); } }
From source file:com.machinepublishers.jbrowserdriver.diagnostics.Test.java
License:Apache License
private void doTests() { JBrowserDriver driver = null;//from www . ja va 2 s .com Thread shutdownHook = null; try { HttpServer.launch(TEST_PORT_HTTP); final File cacheDir = Files.createTempDirectory("jbd_test_cache").toFile(); final File userDataDir = Files.createTempDirectory("jbd_test_userdata").toFile(); shutdownHook = new Thread(new Runnable() { @Override public void run() { FileUtils.deleteQuietly(cacheDir); FileUtils.deleteQuietly(userDataDir); } }); Runtime.getRuntime().addShutdownHook(shutdownHook); final String mainPage = "http://" + InetAddress.getLoopbackAddress().getHostAddress() + ":" + TEST_PORT_HTTP; final int ajaxWait = 150; final Settings.Builder builder = Settings.builder().processes(TEST_PORTS_RMI) .screen(new Dimension(1024, 768)).logger(null).logJavascript(true).ajaxWait(ajaxWait) .cacheDir(cacheDir).cache(true).ignoreDialogs(false); driver = new JBrowserDriver(builder.build()); /* * Load a page */ driver.get(mainPage); test(driver.getStatusCode() == 200); long initialRequestId = HttpServer.previousRequestId(); /* * Load page from cache */ driver.get(mainPage); test(driver.getStatusCode() == 200); test(HttpServer.previousRequestId() == initialRequestId); boolean viaHeader = false; for (String line : HttpServer.previousRequest()) { if (line.toLowerCase().startsWith("via:")) { viaHeader = true; break; } } test(!viaHeader); /* * Driver reset */ driver.reset(); driver.get(mainPage); test(driver.getStatusCode() == 200); test(HttpServer.previousRequestId() == initialRequestId); driver.reset(builder.cacheDir(null).build()); driver.get(mainPage); test(driver.getStatusCode() == 200); test(HttpServer.previousRequestId() != initialRequestId); /* * Javascript logs */ int messages = 0; for (LogEntry entry : driver.manage().logs().get("javascript").filter(Level.ALL)) { ++messages; test(!StringUtils.isEmpty(entry.getMessage())); } test(messages == 3); /* * User-data directory */ driver.findElement(By.id("populate-local-storage")).click(); driver.findElement(By.id("load-from-local-storage")).click(); test("test-value".equals(driver.findElement(By.id("local-storage-value-holder")).getText())); driver.get(mainPage); driver.findElement(By.id("load-from-local-storage")).click(); test("test-value".equals(driver.findElement(By.id("local-storage-value-holder")).getText())); driver.reset(); driver.get(mainPage); driver.findElement(By.id("load-from-local-storage")).click(); test("".equals(driver.findElement(By.id("local-storage-value-holder")).getText())); driver.reset(builder.userDataDirectory(userDataDir).build()); driver.get(mainPage); driver.findElement(By.id("populate-local-storage")).click(); driver.findElement(By.id("load-from-local-storage")).click(); test("test-value".equals(driver.findElement(By.id("local-storage-value-holder")).getText())); driver.reset(); driver.get(mainPage); driver.findElement(By.id("load-from-local-storage")).click(); test("test-value".equals(driver.findElement(By.id("local-storage-value-holder")).getText())); /* * Select DOM elements */ test("test-data-attr".equals(driver.findElement(By.id("divtext1")).getAttribute("data-selected"))); test(driver.findElement(By.id("divtext1")).getAttribute("undefinedattr") == null); test(driver.findElement(By.id("divtext1")).getAttribute("innerText").equals("test1")); test(driver.findElements(By.name("divs")).size() == 2); test(driver.findElements(By.name("divs")).get(1).getAttribute("innerText").equals("test2")); test(driver.findElementByClassName("divclass").getAttribute("id").equals("divtext1")); test(driver.findElementsByClassName("divclass").get(1).getAttribute("id").equals("divtext2")); test(driver.findElementByCssSelector("#divtext1").getAttribute("id").equals("divtext1")); test(driver.findElementsByCssSelector("html > *").get(1).getAttribute("id").equals("testbody")); test(driver.findElementById("divtext1").getTagName().equals("div")); test(driver.findElementsById("divtext1").get(0).getTagName().equals("div")); test(driver.findElementByLinkText("anchor").getAttribute("id").equals("anchor1")); test(driver.findElementsByLinkText("anchor").get(1).getAttribute("id").equals("anchor2")); test(driver.findElementByName("divs").getAttribute("id").equals("divtext1")); test(driver.findElementsByName("divs").get(1).getAttribute("id").equals("divtext2")); test(driver.findElementByPartialLinkText("anch").getAttribute("id").equals("anchor1")); test(driver.findElementsByPartialLinkText("anch").get(1).getAttribute("id").equals("anchor2")); test(driver.findElementByTagName("div").getAttribute("id").equals("divtext1")); test(driver.findElementsByTagName("div").get(1).getAttribute("id").equals("divtext2")); test(driver.findElementByXPath("//*[@id='divtext1']").getAttribute("id").equals("divtext1")); test(driver.findElementByTagName("body").findElement(By.xpath("//*[@id='divtext1']")).getAttribute("id") .equals("divtext1")); test(driver.findElementsByXPath("//html/*").get(1).getAttribute("id").equals("testbody")); test(driver.findElement(By.xpath("//a[contains(@href,'1')]")).getAttribute("id").equals("anchor1")); test(driver.findElementsByXPath("//a[contains(@href,'!!!')]").isEmpty()); test(driver.findElementsByClassName("xx").isEmpty()); test(driver.findElementsByTagName("xx").isEmpty()); test(driver.findElementsByCssSelector("#xx").isEmpty()); Throwable error = null; try { driver.findElementByTagName("xx"); } catch (NoSuchElementException e) { error = e; } test(error != null); error = null; try { driver.findElementByCssSelector("#xx"); } catch (NoSuchElementException e) { error = e; } test(error != null); error = null; try { driver.findElementsByXPath("!!!"); } catch (WebDriverException e) { error = e; } test(error != null); error = null; try { driver.findElement(By.id("divtext1")).findElements(By.cssSelector("???")); } catch (WebDriverException e) { error = e; } test(error != null); /* * WebElement Equals/HashCode */ test(driver.findElements(By.name("divs")).get(0).equals(driver.findElements(By.name("divs")).get(0))); test(driver.findElements(By.name("divs")).get(0).hashCode() == driver.findElements(By.name("divs")) .get(0).hashCode()); /* * Typing text */ driver.findElement(By.id("text-input")).sendKeys("testing"); driver.findElement(By.id("text-input")).sendKeys(""); test(driver.findElement(By.id("text-input")).getAttribute("value").equals("testing")); driver.findElement(By.id("text-input")).sendKeys(JBrowserDriver.KEYBOARD_DELETE); test(driver.findElement(By.id("text-input")).getAttribute("value") == null); driver.findElement(By.id("text-input")).sendKeys("testing"); test(driver.findElement(By.id("text-input")).getAttribute("value").equals("testing")); driver.findElement(By.id("text-input")).clear(); test(driver.findElement(By.id("text-input")).getAttribute("value") == null); /* * Clicking on elements */ test(!driver.findElement(By.id("testoption2")).isSelected()); driver.findElement(By.id("testoption2")).click(); test(driver.findElement(By.id("testoption2")).isSelected()); driver.findElement(By.id("testoption1")).click(); test(driver.findElement(By.id("testoption1")).isSelected()); driver.findElement(By.id("anchor5")).click(); test("anchor clicked".equals(driver.findElement(By.id("testspan")).getText())); /* * Execute javascript */ test(((WebElement) driver.executeScript("return arguments[0];", driver.findElement(By.id("divtext1")))) .getAttribute("innerText").equals("test1")); test(((WebElement) driver.executeScript("return arguments[0].parentNode;", driver.findElement(By.id("divtext1")))).getTagName().equals("body")); test(((WebElement) ((JavascriptExecutor) driver.findElement(By.id("divtext1"))) .executeAsyncScript("arguments[0](this);")).getAttribute("innerText").equals("test1")); test((driver.executeAsyncScript("arguments[1](arguments[0].innerText);", driver.findElement(By.id("divtext1")))).equals("test1")); Map<String, Object> map = (Map<String, Object>) driver.executeScript("return {" + "key1:['value1','value2','value3'], " + "key2:5," + "key3:function(){return 'testing';}, " + "key4:undefined, key5:null, key6:1/0, key7:0/0, key8:'', key9:[], key10:{}, key11:[{},{}]," + "key12:document.getElementById('divtext1'), " + "key13:document.getElementsByName('divs'), " + "key14:[document.getElementById('divtext1'),document.getElementsByName('divs'),{subkey1:'subval1'}]};"); test(map.size() == 14); test(((List) map.get("key1")).size() == 3); test(((List) map.get("key1")).get(2).equals("value3")); test(((List) map.get("key1")).get(2) instanceof String); test(map.get("key2").equals(new Long(5))); test("function () {return 'testing';}".equals(map.get("key3")) || "function (){return 'testing';}".equals(map.get("key3"))); test(map.get("key4") == null); test(map.get("key5") == null); test(Double.isInfinite(((Double) map.get("key6")).doubleValue())); test(Double.isNaN(((Double) map.get("key7")).doubleValue())); test("".equals(map.get("key8"))); test(map.get("key9") instanceof List); test(map.get("key10") instanceof Map); test(((List) map.get("key11")).size() == 2); test(((Map) ((List) map.get("key11")).get(1)).isEmpty()); test("test1".equals(((WebElement) map.get("key12")).getAttribute("innerText"))); test(((List<WebElement>) map.get("key13")).size() == 2); test(((List<WebElement>) map.get("key13")).get(1).getAttribute("innerText").equals("test2")); test(((List) map.get("key14")).size() == 3); test(((List) ((List) map.get("key14")).get(1)).size() == 2); test(((WebElement) ((List) ((List) map.get("key14")).get(1)).get(1)).getAttribute("innerText") .equals("test2")); test(((Map) ((List) map.get("key14")).get(2)).size() == 1); test("subval1".equals(((Map) ((List) map.get("key14")).get(2)).get("subkey1"))); test(((List) driver.executeScript("return [];")).isEmpty()); test(((Map) driver.executeScript("return {};")).isEmpty()); error = null; try { driver.executeScript("invalid.execute()"); } catch (WebDriverException e) { error = e; } test(error != null); /* * DOM element properties */ WebElement element = driver.findElement(By.id("divtext1")); Point point = element.getLocation(); test(point.getX() > 0); test(point.getY() > 0); Dimension dimension = element.getSize(); test(dimension.width > 0); test(dimension.height > 0); Rectangle rect = element.getRect(); test(rect.x == point.getX()); test(rect.y == point.getY()); test(rect.width == dimension.getWidth()); test(rect.height == dimension.getHeight()); test("Testing\ntext.".equals(driver.findElement(By.id("text-node1")).getText())); test("".equals(driver.findElement(By.id("text-node2")).getText())); test("".equals(driver.findElement(By.id("text-node3")).getText())); List<WebElement> options = driver.findElementsByCssSelector("#testselect option"); test(options.size() == 2); test(options.get(0).isSelected()); test(!options.get(1).isSelected()); test(driver.findElementById("checkbox1").isSelected()); test(!driver.findElementById("checkbox2").isSelected()); /* * Cookie manager */ driver.manage().addCookie(new Cookie("testname", "testvalue")); Cookie cookie = driver.manage().getCookieNamed("testname"); test(cookie.getValue().equals("testvalue")); test(InetAddress.getLoopbackAddress().getHostAddress().equals(cookie.getDomain())); /* * Screenshots */ test(driver.getScreenshotAs(OutputType.BYTES).length > 0); /* * File Input Type */ driver.findElement(By.id("upload")).sendKeys("some-file"); test("event-test".equals(driver.findElement(By.id("file-input-onchange")).getText())); test(driver.findElement(By.id("upload")).getAttribute("value").endsWith("some-file")); /* * Javascript alerts */ driver.findElement(By.tagName("button")).click(); test(driver.switchTo().alert().getText().equals("test-alert")); driver.switchTo().alert().dismiss(); test(driver.switchTo().alert().getText().equals("test-confirm")); driver.switchTo().alert().dismiss(); test(driver.switchTo().alert().getText().equals("test-prompt")); driver.switchTo().alert().sendKeys("test-input"); driver.switchTo().alert().accept(); test(driver.findElement(By.id("testspan")).getAttribute("innerHTML").equals("test-input")); /* * Request headers */ List<String> request = HttpServer.previousRequest(); if (TEST_PORT_HTTP != 443 && TEST_PORT_HTTP != 80) { test(request.get(1).endsWith(":" + TEST_PORT_HTTP)); } test(request.size() > 1); Set<String> headers = new HashSet<String>(); for (String line : request) { if (line.contains(":")) { headers.add(line.split(":")[0].toLowerCase()); } } test(request.size() - 2 == headers.size()); /* * HTTP Post */ driver.findElement(By.id("form-submit")).click(); test(driver.getStatusCode() == 201); test("form-field=test-form-value" .equals(HttpServer.previousRequest().get(HttpServer.previousRequest().size() - 1))); /* * Frames */ driver.switchTo().frame(driver.findElementByTagName("iframe")); test(driver.findElementById("iframebody") != null); driver.switchTo().parentFrame(); test(driver.findElementById("testbody") != null); driver.switchTo().frame(0); test(driver.findElementById("iframebody") != null); driver.switchTo().defaultContent(); driver.switchTo().frame("testiframe"); test(driver.findElementById("iframebody") != null); driver.get(mainPage); test(driver.getPageSource() != null); driver.switchTo().frame(driver.findElementByTagName("iframe")); test(driver.findElementById("iframebody") != null); driver.switchTo().parentFrame(); driver.findElement(By.id("anchor3")).click(); test(driver.getPageSource() != null); driver.switchTo().frame(driver.findElementByTagName("iframe")); driver.findElement(By.id("iframe-anchor")).click(); //TODO iframe coord offset needed on any other methods? driver.pageWait(); test(HttpServer.previousRequest().get(0).startsWith("GET /iframe.htm?param=fromiframe")); driver.get(mainPage); driver.switchTo().frame(driver.findElementByTagName("iframe")); Actions actions = new Actions(driver); actions.moveToElement(driver.findElement(By.id("iframe-anchor"))); actions.click(); actions.build().perform(); driver.pageWait(); test(HttpServer.previousRequest().get(0).startsWith("GET /iframe.htm?param=fromiframe")); driver.get(mainPage); driver.switchTo().frame(driver.findElementByTagName("iframe")); driver.getMouse().click(((Locatable) driver.findElement(By.id("iframe-anchor"))).getCoordinates()); driver.getMouse().mouseMove(((Locatable) driver.findElement(By.id("iframe-anchor"))).getCoordinates(), 5, 5); driver.pageWait(); test(HttpServer.previousRequest().get(0).startsWith("GET /iframe.htm?param=fromiframe")); //TODO fingerprinting //System.out.println(driver.findElement(By.id("iframe-useragent")).getAttribute("innerHTML")); //System.out.println(driver.findElement(By.id("iframe-nested-useragent")).getAttribute("innerHTML")); /* * Redirects and cookies */ driver.get(mainPage + "/redirect/site1#testfragment"); test(HttpServer.previousRequestId() != initialRequestId); test(driver.getStatusCode() == 200); test(driver.getCurrentUrl().endsWith("/redirect/site2#testfragment")); cookie = driver.manage().getCookieNamed("JSESSIONID"); test(cookie.getValue().equals("ABC123")); test(InetAddress.getLoopbackAddress().getHostAddress().equals(cookie.getDomain())); /* * Cookies set by Javascript */ test("jsCookieValue1".equals(driver.manage().getCookieNamed("jsCookieName1").getValue())); test("jsCookieValue2".equals(driver.manage().getCookieNamed("jsCookieName2").getValue())); test("jsCookieValue3".equals(driver.manage().getCookieNamed("jsCookieName3").getValue())); test("jsCookieValue4".equals(driver.manage().getCookieNamed("jsCookieName4").getValue())); /* * Window size and position */ driver.manage().window().setSize(new Dimension(5000, 5000)); test(driver.manage().window().getSize().getWidth() == 1024); test(driver.manage().window().getSize().getHeight() == 768); driver.manage().window().setSize(new Dimension(800, 600)); test(driver.manage().window().getSize().getWidth() == 800); test(driver.manage().window().getSize().getHeight() == 600); driver.manage().window().setPosition(new Point(5000, 5000)); test(driver.manage().window().getPosition().getX() == 224); test(driver.manage().window().getPosition().getY() == 168); driver.manage().window().setPosition(new Point(20, 50)); test(driver.manage().window().getPosition().getX() == 20); test(driver.manage().window().getPosition().getY() == 50); driver.manage().window().maximize(); test(driver.manage().window().getPosition().getX() == 0); test(driver.manage().window().getPosition().getY() == 0); test(driver.manage().window().getSize().getWidth() == 1024); test(driver.manage().window().getSize().getHeight() == 768); driver.manage().window().setSize(new Dimension(800, 600)); driver.manage().window().setPosition(new Point(20, 50)); driver.manage().window().fullscreen(); test(driver.manage().window().getPosition().getX() == 0); test(driver.manage().window().getPosition().getY() == 0); test(driver.manage().window().getSize().getWidth() == 1024); test(driver.manage().window().getSize().getHeight() == 768); driver.manage().window().fullscreen(); test(driver.manage().window().getPosition().getX() == 20); test(driver.manage().window().getPosition().getY() == 50); test(driver.manage().window().getSize().getWidth() == 800); test(driver.manage().window().getSize().getHeight() == 600); driver.manage().window().setSize(new Dimension(400, 200)); driver.manage().window().setPosition(new Point(10, 30)); test(driver.manage().window().getPosition().getX() == 10); test(driver.manage().window().getPosition().getY() == 30); test(driver.manage().window().getSize().getWidth() == 400); test(driver.manage().window().getSize().getHeight() == 200); driver.manage().window().setSize(new Dimension(1024, 768)); test(driver.manage().window().getPosition().getX() == 0); test(driver.manage().window().getPosition().getY() == 0); test(driver.manage().window().getSize().getWidth() == 1024); test(driver.manage().window().getSize().getHeight() == 768); /* * Element visibility */ test(driver.findElement(By.id("iframe-anchor")).isDisplayed()); test(!driver.findElement(By.id("anchor-visibility-hidden")).isDisplayed()); test(!driver.findElement(By.id("anchor-display-none")).isDisplayed()); error = null; try { driver.findElement(By.id("anchor-visibility-hidden")).click(); } catch (ElementNotVisibleException e) { error = e; } test(error != null); error = null; try { driver.findElement(By.id("anchor-display-none")).click(); } catch (ElementNotVisibleException e) { error = e; } test(error != null); /* * Operations on elements that no longer exist */ WebElement body = driver.findElement(By.tagName("body")); test(!StringUtils.isEmpty(body.getAttribute("outerHTML"))); driver.get("about:blank"); error = null; try { body.getAttribute("outerHTML"); } catch (StaleElementReferenceException e) { error = e; } test(error != null); /* * Timeouts */ driver.manage().timeouts().pageLoadTimeout(1, TimeUnit.MILLISECONDS); error = null; try { driver.get(mainPage + "/wait-forever"); } catch (TimeoutException e) { error = e; } test(error != null); } catch (Throwable t) { outputError(testLabel("failed", curTest + 1, t)); } finally { try { driver.quit(); } catch (Throwable t) { outputError(toString(t)); } try { HttpServer.stop(); } catch (Throwable t) { outputError(toString(t)); } try { Runtime.getRuntime().removeShutdownHook(shutdownHook); shutdownHook.run(); } catch (Throwable t) { } } }
From source file:com.machinepublishers.jbrowserdriver.JBrowserDriverServer.java
License:Apache License
/** * {@inheritDoc}/*from w w w. j av a2s . c om*/ */ @Override public String getPageSource() { init(); WebElement element = ElementServer.create(context.get().item()).findElementByTagName("html"); if (element != null) { String outerHtml = element.getAttribute("outerHTML"); if (outerHtml != null && !outerHtml.isEmpty()) { return outerHtml; } } return AppThread.exec(context.get().item().statusCode, new Sync<String>() { public String perform() { WebPage page = Accessor.getPageFor(context.get().item().engine.get()); String html = page.getHtml(page.getMainFrame()); if (html != null && !html.isEmpty()) { return html; } try { StringWriter stringWriter = new StringWriter(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(new DOMSource(context.get().item().engine.get().getDocument()), new StreamResult(stringWriter)); return stringWriter.toString(); } catch (Throwable t) { } return page.getInnerText(page.getMainFrame()); } }); }
From source file:com.mastfrog.selenium.Utils.java
License:Open Source License
/** * Wait for a page element to be refreshed. Attempts to derive a * recipe for looking up the element from its attributes. May fail. * @param el The element/* ww w . java2 s. c o m*/ */ public void waitForRefresh(final WebElement el) { By by = null; if (el.getAttribute("id") != null) { by = By.id(el.getAttribute("id")); } else if (el.getAttribute("name") != null) { by = By.name(el.getAttribute("name")); } else if (el.getAttribute("class") != null) { by = By.className(el.getAttribute("class")); } else if (el.getAttribute("style") != null) { by = By.cssSelector("style"); } else { throw new Error("No good way to look up " + el); } waitForRefresh(by); }
From source file:com.mediamelon.UserActions.java
void addAccount(WebDriver driver, List<String> formData) { //Verify if the user is logged in as Super User to create a new account. //If not, display message and return //Verify if the user is logged in String pageTitle = driver.getTitle(); Assert.assertEquals(pageTitle, "MediaMelon - Home"); String fullName = driver.findElement(By.xpath("//div[@class='row data']/div/div[1]/p[2]")).getText(); String role = driver.findElement(By.xpath("//div[@class='row data']/div/div[3]/p[2]")).getText(); if (fullName.equalsIgnoreCase("Super User") && role.equalsIgnoreCase("admin")) { System.out.println("List of Accounts is displayed"); //expand the settings menu option and click on Account Management List<WebElement> dropDownOptions = driver.findElements(By.className("dropdown-toggle")); dropDownOptions.get(0).click();//from w ww. ja v a2 s . co m WebElement accountManagement = driver.findElement(By.cssSelector(".dropdown-menu.dropdown-admin")); Assert.assertTrue(accountManagement.isDisplayed()); accountManagement.findElement(By.linkText("Account Management")).click(); Assert.assertEquals(driver.getTitle(), "List of Accounts"); WebElement accountsTable = driver.findElement(By.xpath("//div[@class='row well']/table")); Assert.assertTrue(accountsTable.isDisplayed()); WebElement addAccountBtn = driver.findElement(By.cssSelector(".btn.btn-primary")); System.out.println("Clicking on Add a new account button"); Assert.assertEquals(addAccountBtn.getText(), "Add a new Account"); addAccountBtn.click(); //Fill account add form WebElement accountForm = driver.findElement(By.tagName("form")); Assert.assertTrue(accountForm.isDisplayed()); System.out.println(accountForm.getAttribute("action")); accountForm.findElement(By.id("companyName")).sendKeys(formData.get(0)); accountForm.findElement(By.id("companyWebsite")).sendKeys(formData.get(1)); accountForm.findElement(By.id("adminName")).sendKeys(formData.get(2)); accountForm.findElement(By.id("adminEmail")).sendKeys(formData.get(3)); Select licenseType = new Select(driver.findElement(By.id("licenseType"))); licenseType.selectByVisibleText(formData.get(4)); Select services = new Select(driver.findElement(By.id("services"))); String requiredServices = formData.get(5); String multipleSel[] = formData.get(5).split(","); if (requiredServices.equalsIgnoreCase("All")) { services.selectByIndex(0); services.selectByIndex(1); services.selectByIndex(2); } else if (multipleSel.length > 1) { for (int i = 0; i < multipleSel.length; i++) services.selectByVisibleText(multipleSel[i]); } else services.selectByVisibleText(requiredServices); accountForm.findElement(By.id("companyName")).sendKeys(formData.get(5)); //submit the form System.out.println("Submitting the form"); accountForm.findElement(By.cssSelector("button[value='submit']")).click(); System.out.println("clicked on submit button"); accountsTable = driver.findElement(By.cssSelector("table.table-striped.table-hover.table-bordered")); Assert.assertTrue(accountsTable.isDisplayed()); System.out.println("form submitted sucessfully"); //Verify the presence of newly created account in the list of accounts System.out.println("Verifying if the newly created account is present in the list"); String tableData = accountsTable.getText(); System.out.println("Table Data: " + tableData); //findElement(By.xpath(".//*[@class='studyResultsId']/div/table/tbody/tr/td")).getText(); //Retrieving the data from the Td of table in to a string if (tableData.contains(formData.get(5))) { System.out.println("contains newly created account"); } else { System.out.println("does not contains newly created account"); } } else System.out.println("User not authorized to create an account"); }
From source file:com.mgmtp.jfunk.web.step.CheckTableCell.java
License:Apache License
private WebElement findTable(final String attributeKey, final String attributeValue) { List<WebElement> tables = getWebDriver().findElements(By.tagName(WebConstants.TABLE)); for (WebElement table : tables) { String value = table.getAttribute(attributeKey); if (StringUtils.equals(attributeValue, value)) { return table; }//from w w w. j a v a 2s. co m } throw new StepException("Could not find table [" + attributeKey + "=" + attributeValue + "]"); }
From source file:com.mgmtp.jfunk.web.step.JFunkWebElement.java
License:Apache License
/** * @throws StepException/*from w ww .j a v a 2 s .c o m*/ * <ul> * <li>if element specified by {@link By} object in the constructor cannot be found</li> * <li>if a validation error occurred while checking the value of the WebElement * against the desired value</li> * </ul> */ @Override public void execute() throws StepException { elementValue = retrieveElementValue(); final WebDriverWait wait = new WebDriverWait(getWebDriver(), WebConstants.DEFAULT_TIMEOUT); final WebElement element = wait.until(new Function<WebDriver, WebElement>() { @Override public WebElement apply(final WebDriver input) { List<WebElement> webElements = input.findElements(by); if (webElements.isEmpty()) { throw new StepException("Could not find any matching element; By=" + by.toString()); } /* * If the search using the By object does find more than one matching element we are * looping through all elements if we find at least one which matches the criteria * below. If not, an exception is thrown. */ for (WebElement webElement : webElements) { if (webElement.isDisplayed()) { if (webElement.isEnabled() || !webElement.isEnabled() && (stepMode == StepMode.CHECK_DEFAULT || stepMode == StepMode.CHECK_VALUE)) { return webElement; } } } throw new StepException("All elements matching by=" + by + " were either invisible or disabled"); } }); switch (stepMode) { case CHECK_DEFAULT: // Check only for text input and textarea if (element.getTagName().equals(WebConstants.INPUT) && element.getAttribute(WebConstants.TYPE).equals(WebConstants.TEXT) || element.getTagName().equals(WebConstants.TEXTAREA)) { log.info(toString()); String value = element.getAttribute(WebConstants.VALUE); if (!DataUtils.isDefaultValue(value)) { throw new ValidationException("Wrong default value=" + value + " of " + this); } } break; case CHECK_VALUE: String checkValue = elementValue; if (checkTrafo != null) { checkValue = checkTrafo.trafo(checkValue); } log.info(this + ", checkValue=" + checkValue); if (element.getTagName().equalsIgnoreCase(WebConstants.SELECT)) { Select select = new Select(element); String value = select.getFirstSelectedOption().getAttribute(WebConstants.VALUE); if (!Objects.equal(checkValue, value)) { String text = select.getFirstSelectedOption().getText(); if (!Objects.equal(checkValue, text)) { throw new InvalidValueException(element, checkValue, text + " (option value=" + value + ")"); } } } else if (WebConstants.INPUT.equalsIgnoreCase(element.getTagName()) && WebConstants.RADIO.equals(element.getAttribute(WebConstants.TYPE))) { List<WebElement> elements = getWebDriver().findElements(by); for (WebElement webElement : elements) { if (webElement.isDisplayed() && webElement.isEnabled()) { String elVal = webElement.getAttribute(WebConstants.VALUE); if (elVal.equals(checkValue) && !webElement.isSelected()) { throw new InvalidValueException(element, checkValue, elVal); } } } } else if (WebConstants.CHECKBOX.equals(element.getAttribute(WebConstants.TYPE))) { boolean elVal = element.isSelected(); if (elVal != Boolean.valueOf(checkValue)) { throw new InvalidValueException(element, checkValue, String.valueOf(elVal)); } } else { String value = element.getAttribute(WebConstants.VALUE); if (!Objects.equal(checkValue, value)) { throw new InvalidValueException(element, checkValue, value); } } break; case SET_VALUE: String setValue = elementValue; if (setTrafo != null) { setValue = setTrafo.trafo(setValue); } log.info(this + (setTrafo != null ? ", setValue (after trafo)=" + setValue : "")); if (element.getTagName().equalsIgnoreCase(WebConstants.SELECT)) { Select select = new Select(element); // First check if a matching value can be found List<WebElement> options = select.getOptions(); boolean found = false; for (WebElement option : options) { String optionValue = option.getAttribute(WebConstants.VALUE); if (StringUtils.equals(optionValue, setValue)) { /* * WebElement with matching value could be found --> we are finished */ found = true; select.selectByValue(setValue); break; } } if (!found) { /* * Fallback: look for a WebElement with a matching visible text */ for (WebElement option : options) { String visibleText = option.getText(); if (StringUtils.equals(visibleText, setValue)) { /* * WebElement with matching value could be found --> we are finished */ found = true; select.selectByVisibleText(setValue); break; } } } if (!found) { throw new StepException( "Could not find a matching option element in " + element + " , By: " + by.toString()); } } else if (WebConstants.INPUT.equalsIgnoreCase(element.getTagName()) && WebConstants.RADIO.equals(element.getAttribute(WebConstants.TYPE))) { List<WebElement> elements = getWebDriver().findElements(by); for (WebElement webElement : elements) { if (webElement.isDisplayed() && webElement.isEnabled()) { String elVal = webElement.getAttribute(WebConstants.VALUE); if (elVal.equals(setValue) && !webElement.isSelected()) { webElement.click(); } } } } else if (WebConstants.CHECKBOX.equals(element.getAttribute(WebConstants.TYPE))) { if (Boolean.valueOf(setValue) && !element.isSelected() || !Boolean.valueOf(setValue) && element.isSelected()) { element.click(); } } else { if (element.isDisplayed() && element.isEnabled() && (element.getAttribute("readonly") == null || element.getAttribute("readonly").equals("false"))) { element.clear(); element.sendKeys(setValue); } else { log.warn("Element is invisible or disabled, value cannot be set"); } } break; case NONE: // do nothing break; default: throw new IllegalArgumentException("Unhandled StepMode=" + stepMode); } }
From source file:com.mgmtp.jfunk.web.util.FormInputHandler.java
License:Apache License
/** * Tries to find the field and sets or checks its value depending on the {@link StepMode}. *//*from w w w . j a v a 2 s . c o m*/ public void perform() { log.info(toString()); WebElement element = finder.find(); switch (stepMode) { case CHECK_VALUE: String checkValue = retrieveValue(); if (checkTrafo != null) { checkValue = checkTrafo.trafo(checkValue); } checkValue(element, checkValue); break; case CHECK_DEFAULT: checkState(defaultsProvider != null, "No DefaultsProvider set when StepMode is CHECK_DEFAULT."); checkValue(element, defaultsProvider.get(element, dataSet, dataKey, dataIndex)); break; case SET_VALUE: String setValue = retrieveValue(); if (setTrafo != null) { setValue = setTrafo.trafo(setValue); } if (element.getTagName().equalsIgnoreCase(WebConstants.SELECT)) { Select select = new Select(element); // First check if a matching value can be found List<WebElement> options = select.getOptions(); boolean found = false; for (WebElement option : options) { String optionValue = option.getAttribute(WebConstants.VALUE); if (StringUtils.equals(optionValue, setValue)) { /* * WebElement with matching value could be found --> we are finished */ found = true; select.selectByValue(setValue); break; } } if (!found) { /* * Fallback: look for a WebElement with a matching visible text */ for (WebElement option : options) { String visibleText = option.getText(); if (StringUtils.equals(visibleText, setValue)) { /* * WebElement with matching value could be found --> we are finished */ found = true; select.selectByVisibleText(setValue); break; } } } if (!found) { throw new JFunkException( "Could not find a matching option element in " + element + " , By: " + finder.getBy()); } } else if (WebConstants.INPUT.equalsIgnoreCase(element.getTagName()) && WebConstants.RADIO.equals(element.getAttribute(WebConstants.TYPE))) { List<WebElement> elements = finder.findAll(); for (WebElement webElement : elements) { String elVal = webElement.getAttribute(WebConstants.VALUE); if (elVal.equals(setValue) && !webElement.isSelected()) { webElement.click(); } } } else if (WebConstants.CHECKBOX.equals(element.getAttribute(WebConstants.TYPE))) { if (Boolean.valueOf(setValue) && !element.isSelected() || !Boolean.valueOf(setValue) && element.isSelected()) { element.click(); } } else { if (element.getAttribute("readonly") == null || element.getAttribute("readonly").equals("false")) { element.clear(); element.sendKeys(setValue); } else { log.warn("Element is invisible or disabled, value cannot be set"); } } break; case NONE: // do nothing break; default: throw new IllegalArgumentException("Unhandled StepMode=" + stepMode); } }
From source file:com.mgmtp.jfunk.web.util.FormInputHandler.java
License:Apache License
private void checkValue(final WebElement element, final String checkValue) { String elementValue = element.getTagName().equalsIgnoreCase(WebConstants.SELECT) ? new Select(element).getFirstSelectedOption().getAttribute(WebConstants.VALUE) : element.getAttribute(WebConstants.VALUE); if (WebConstants.INPUT.equalsIgnoreCase(element.getTagName()) && WebConstants.RADIO.equals(element.getAttribute(WebConstants.TYPE))) { List<WebElement> elements = finder.findAll(); for (WebElement webElement : elements) { String elVal = webElement.getAttribute(WebConstants.VALUE); if (elVal.equals(checkValue) && !webElement.isSelected()) { throw new InvalidValueException(element, checkValue, elVal); }//from w w w .j av a 2s .c om } } else if (WebConstants.CHECKBOX.equals(element.getAttribute(WebConstants.TYPE))) { boolean elVal = element.isSelected(); if (elVal != Boolean.valueOf(checkValue)) { throw new InvalidValueException(element, checkValue, String.valueOf(elVal)); } } else { if (!Objects.equal(checkValue, elementValue)) { throw new InvalidValueException(element, checkValue, elementValue); } } }