Example usage for org.openqa.selenium WebDriver findElements

List of usage examples for org.openqa.selenium WebDriver findElements

Introduction

In this page you can find the example usage for org.openqa.selenium WebDriver findElements.

Prototype

@Override
List<WebElement> findElements(By by);

Source Link

Document

Find all elements within the current page using the given mechanism.

Usage

From source file:com.twiceagain.mywebdriver.startup.DemoBasicWebPageVisualizeElements.java

License:Open Source License

/**
 * @param args the command line arguments
 * @throws java.lang.InterruptedException
 *///w  ww. ja v a2 s . c om
public static void main(String[] args) throws InterruptedException {
    WebDriver wd = Drivers.getDriver();
    wd.get("https://news.google.com");
    //Thread.sleep(2000);
    List<WebElement> lwe = wd.findElements(By.xpath(".//div[@class='esc-body']"));
    Drivers.highlightElements(wd, lwe, "article");
    Thread.sleep(5000);// wait 5 secs
    wd.close();
}

From source file:com.vaadin.testbench.TestBenchDriverTest.java

@Test
public void testTestBenchDriverActsAsProxy() {
    FirefoxDriver mockDriver = createMock(FirefoxDriver.class);
    mockDriver.close();//from   w  ww .java2 s .c o  m
    expectLastCall().once();
    WebElement mockElement = createNiceMock(WebElement.class);
    expect(mockDriver.findElement(isA(By.class))).andReturn(mockElement);
    List<WebElement> elements = Arrays.asList(mockElement);
    expect(mockDriver.findElements(isA(By.class))).andReturn(elements);
    mockDriver.get("foo");
    expectLastCall().once();
    expect(mockDriver.getCurrentUrl()).andReturn("foo");
    expect(mockDriver.getPageSource()).andReturn("<html></html>");
    expect(mockDriver.getTitle()).andReturn("bar");
    expect(mockDriver.getWindowHandle()).andReturn("baz");
    Set<String> handles = new HashSet<String>();
    expect(mockDriver.getWindowHandles()).andReturn(handles);
    Options mockOptions = createNiceMock(Options.class);
    expect(mockDriver.manage()).andReturn(mockOptions);
    Navigation mockNavigation = createNiceMock(Navigation.class);
    expect(mockDriver.navigate()).andReturn(mockNavigation);
    mockDriver.quit();
    expectLastCall().once();
    expect(((JavascriptExecutor) mockDriver).executeScript(anyObject(String.class))).andStubReturn(true);
    TargetLocator mockTargetLocator = createNiceMock(TargetLocator.class);
    expect(mockDriver.switchTo()).andReturn(mockTargetLocator);
    replay(mockDriver);

    // TestBenchDriverProxy driver = new TestBenchDriverProxy(mockDriver);
    WebDriver driver = TestBench.createDriver(mockDriver);
    driver.close();
    By mockBy = createNiceMock(By.class);
    assertTrue(driver.findElement(mockBy) instanceof TestBenchElementCommands);
    assertTrue(driver.findElements(mockBy).get(0) instanceof TestBenchElementCommands);
    driver.get("foo");
    assertEquals("foo", driver.getCurrentUrl());
    assertEquals("<html></html>", driver.getPageSource());
    assertEquals("bar", driver.getTitle());
    assertEquals("baz", driver.getWindowHandle());
    assertEquals(handles, driver.getWindowHandles());
    assertEquals(mockOptions, driver.manage());
    assertEquals(mockNavigation, driver.navigate());
    driver.quit();
    assertEquals(mockTargetLocator, driver.switchTo());

    verify(mockDriver);
}

From source file:com.vaadin.testbench.TestBenchTestCaseTest.java

private WebDriver mockWebDriverFindElements(boolean empty) {
    WebDriver driver = EasyMock.createNiceMock(WebDriver.class);

    ArrayList<WebElement> result = new ArrayList<WebElement>();
    if (!empty) {
        result.add(EasyMock.createNiceMock(WebElement.class));
    }/*from ww w .j a  v  a2s.c o m*/
    EasyMock.expect(driver.findElements(EasyMock.isA(org.openqa.selenium.By.class))).andReturn(result);
    EasyMock.replay(driver);
    return driver;
}

From source file:com.vha.techdev.webapp.test.SimpleTest.java

License:Apache License

@Test
public void testSimple() throws Exception {
    driver.get(serverUrl + "index.html");

    // wait a bit ajax response
    new WebDriverWait(driver, 2).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver driver) {
            return driver.findElements(By.className("info").id("version")).size() > 0;
        }//w  ww .  j av a 2s .  c o m
    });
    WebElement version = driver.findElement(By.id("version"));
    Assert.assertEquals(ComponentInfo.IMPLEMENTATION.toString(), version.getText());

    String whoToSend = "foo";
    WebElement who = driver.findElement(By.id("who"));
    who.sendKeys(whoToSend);
    WebElement sendBtn = driver.findElement(By.id("send-btn"));
    sendBtn.click();
    // wait a bit ajax response
    new WebDriverWait(driver, 2)
            .until(ExpectedConditions.textToBePresentInElement(By.id("response"), whoToSend));
    WebElement response = driver.findElement(By.id("response"));
    Assert.assertEquals("Hello " + whoToSend, response.getText());
}

From source file:com.vha.techdev.webapp.test.SimpleTest.java

License:Apache License

@Test
public void testFileUpload() throws Exception {
    driver.get(serverUrl + "index.html");

    long fileLength = 16384L;
    File tempFile = createTestFile(fileLength);
    String expectedResponse = tempFile.getName() + ":application/octet-stream:" + fileLength;

    WebElement uploadFile = driver.findElement(By.id("uploadfile"));
    uploadFile.sendKeys(tempFile.getAbsolutePath());

    WebElement uploadBtn = driver.findElement(By.id("upload-btn"));
    uploadBtn.click();//from w  ww .  j  av  a 2s .  com
    // wait a bit ajax response
    new WebDriverWait(driver, 5).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver driver) {
            return driver.findElements(By.className("info").id("file-response")).size() > 0;
        }
    });
    WebElement fileResponse = driver.findElement(By.id("file-response"));
    Assert.assertEquals(expectedResponse, fileResponse.getText());
}

From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

License:Apache License

/**
 * Select an option\options from a drop-down using an option locator. <br>
 * /*from w  ww . j  a v  a2 s .  c om*/
 * Option locators provide different ways of specifying options of an HTML
 * Select element (e.g. for selecting a specific option, or for asserting
 * that the selected option satisfies a specification). There are several
 * forms of Select Option Locator.<br>
 * <br>
 * 
 * <b>label=labelPattern:</b> matches options based on their labels, i.e.
 * the visible text. (This is the default.) label=regexp:^[Oo]ther<br>
 * <b>value=valuePattern:</b> matches options based on their values.
 * value=other<br>
 * <b>id=id:</b> matches options based on their ids. id=option1<br>
 * <b>index=index:</b> matches an option based on its index (offset from
 * zero). index=2<br>
 * <br>
 * 
 * If no option locator prefix is provided, the default behaviour is to
 * match on label. <br>
 * <br>
 * 
 * @param objectName
 *            : Logical name of the web element assigned by the automation
 *            scripter <br>
 * <br>
 * @return the object count
 */
public final int getObjectCount(final String objectName) {
    int counter = getRetryCount();
    int objectCount = 0;
    String objectID = ObjectMap.getObjectSearchPath(objectName, locatorIdentifire);
    WebDriver driver = getDriver();
    try {

        /*
         * START DESCRIPTION following for loop was added to make the
         * command more consistent try the command for give amount of time
         * (can be configured through class variable RETRY) command will be
         * tried for "RETRY" amount of times or until command works. any
         * exception thrown within the tries will be handled internally.
         * 
         * can be exited from the loop under 2 conditions 1. if the command
         * succeeded 2. if the RETRY count is exceeded
         */

        while (counter > 0) {
            try {
                counter--;

                List<WebElement> elements = driver.findElements(getLocatorType(objectID));
                objectCount = elements.size();
                reportresult(true, "GET OBJECT COUNT :" + objectName + "", "PASSED",
                        "getObjectCount command :Element (" + objectName + ") [" + objectID + "] ");
                break;
            } catch (Exception e) {
                sleep(retryInterval);

                if (!(counter > 0)) {
                    e.printStackTrace();
                    reportresult(true, "GET OBJECT COUNT :" + objectName + "", "FAILED",
                            "getObjectCount command cannot access :Element (" + objectName + ") [" + objectID
                                    + "] ");
                    checkTrue(false, true, "getObjectCount command cannot access  :Element (" + objectName
                            + ") [" + objectID + "] ");
                }
            }
        }
        /*
         * END DESCRIPTION
         */
    } catch (Exception e) {
        // waiting for the maximum amount of waiting time before failing the
        // test case
        // Several checks were introduced to narrow down to the failure to
        // the exact cause.
        if (!(counter > 0)) {
            e.printStackTrace();
            reportresult(true, "SELECT :" + objectName + "", "FAILED",
                    "GET OBJECT COUNT command  :Element (" + objectName + ") [" + objectID + "] not present");
            checkTrue(false, true,
                    "GET OBJECT COUNT command  :Element (" + objectName + ") [" + objectID + "] not present");
        } else if ("Element".equalsIgnoreCase(e.getMessage())) {
            e.printStackTrace();
            reportresult(true, "GET OBJECT COUNT :" + objectName + "", "FAILED",
                    "GET OBJECT COUNT command  :Element (" + objectName + ") [" + objectID + "] not present");
            checkTrue(false, true,
                    "GET OBJECT COUNT command  :Element (" + objectName + ") [" + objectID + "] not present");

        }

    }
    return objectCount;
}

From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

License:Apache License

public final int checkSorting(final String objectName, final String identifier, final String type,
        final String pattern, final String order, boolean stopOnFailure, final Object... customError) {
    int counter = getRetryCount();
    int objectCount = 0;
    String objectID = ObjectMap.getObjectSearchPath(objectName, identifier);
    WebDriver driver = getDriver();

    ArrayList<String> list = new ArrayList<String>();
    try {//from   w ww. j a  v  a 2 s .c o m

        while (counter > 0) {
            try {
                counter--;

                List<WebElement> elements = driver.findElements(getLocatorType(objectID));
                objectCount = elements.size();

                for (int i = 0; i < elements.size(); i++) {
                    list.add(i, elements.get(i).getText());
                    //  System.out.println(list.get(i));
                    // System.out.println(list.size());
                }

                sort(list, objectName, type, pattern, order, stopOnFailure, customError);

                break;
            } catch (Exception e) {
                sleep(retryInterval);

                if (!(counter > 0)) {
                    e.printStackTrace();

                    reportresult(true, "CHECK SORTING :" + objectName + "", "FAILED",
                            "CHECK SORTING command cannot access  : Element (" + objectName + ") not present");
                    checkTrue(false, stopOnFailure,
                            "CHECK SORTING command cannot access  : Element (" + objectName + ") not present");

                }
            }
        }
        /*
         * END DESCRIPTION
         */
    } catch (Exception e) {
        // waiting for the maximum amount of waiting time before failing the
        // test case
        // Several checks were introduced to narrow down to the failure to
        // the exact cause.
        if (!(counter > 0)) {
            e.printStackTrace();

            reportresult(true, "CHECK SORTING :" + objectName + "", "FAILED",
                    "CHECK SORTING command  : Element (" + objectName + ") not present");
            checkTrue(false, stopOnFailure,
                    "CHECK SORTING command  : Element (" + objectName + ") not present");

        } else if ("Element".equalsIgnoreCase(e.getMessage())) {
            e.printStackTrace();

            reportresult(true, "CHECK SORTING :" + objectName + "", "FAILED",
                    "CHECK SORTING command  : Element (" + objectName + ") not present");
            checkTrue(false, stopOnFailure,
                    "CHECK SORTING command  : Element (" + objectName + ") not present");

        }

    }
    return objectCount;
}

From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

License:Apache License

/**
 * Checks the contents of a multi color bar chart against the expected
 * values./* w  w w.  j av a2 s  .  c  o m*/
 * 
 * @param userColumns
 * @param chartElementXpath
 * @param
 */

@SuppressWarnings("rawtypes")
private StringBuffer insightColorBarChartContentCheck(String chartName, String chartLocator,
        ArrayList<String> chartnames, ArrayList<String> chartvalues, ArrayList<String> chartpercentages,
        int startingele, int checkingColCount, HashMap<Integer, ArrayList> userColumns,
        String chartElementCapture, String chartElementXpath) {

    // Portlet content variables
    WebDriver driver = getDriver();
    ArrayList<String> chartelementnames = chartnames;
    ArrayList<String> chartelementvalues = chartvalues;
    // ArrayList<String> chartpercentage = chartpercentages;
    int startingelement = startingele;
    int arraycounter = 0;
    StringBuffer verificationErrors = new StringBuffer();
    int actCategoryCount = 0;
    int actElementCnt = 0;
    int elementOffset = 0;
    ArrayList<String> htmlElementNames = new ArrayList<String>();
    ArrayList<String> htmlElementValues = new ArrayList<String>();

    // chathura
    HashMap<Integer, ArrayList> htmlColumns = new HashMap<Integer, ArrayList>();
    ArrayList htmlColumnValues = new ArrayList();

    JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;

    Actions action = new Actions(driver);

    if (chartName.contains("text")) {

        elementOffset = 3;
    } else if (chartName.contains("img")) {

        elementOffset = 2;
    }

    List<WebElement> locateElementsThree = driver
            .findElements(By.xpath(chartName + "//child::*[position()=2 and name()='g']/child::*[position()=2 "
                    + "and name()='g']/child::*[name()='rect']"));

    actCategoryCount = locateElementsThree.size();

    List<WebElement> locateElementsFour = driver
            .findElements(By.xpath(chartName + "//child::*[position()=2 and name()='g']"));

    actElementCnt = locateElementsFour.size();

    int rectFormat = actCategoryCount / actElementCnt;
    // The first loop of the pie chart check

    for (int i = startingelement; i <= rectFormat; i++) {
        // Accessing the different colored elements in a bar
        // ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT
        // ELEMENT ELEMENT ELEMENT

        htmlElementNames = new ArrayList<String>();
        htmlElementValues = new ArrayList<String>();

        htmlColumnValues = new ArrayList<>();

        for (int colorFieldRect = i; colorFieldRect <= actCategoryCount; colorFieldRect += rectFormat) {

            try {
                try {

                    WebElement chartHeaderEle = driver.findElement(By.xpath(chartElementXpath));
                    jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');"
                            + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
                            + "arguments[0].dispatchEvent(evObj);", chartHeaderEle);

                    WebElement element = driver.findElement(By.xpath(chartName
                            + "//child::*[position()=2 and name()='g']/child::*[position()=2 and name()='g']"));
                    jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');"
                            + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
                            + "arguments[0].dispatchEvent(evObj);", element);
                    System.out.println(element);
                    Thread.sleep(500);

                    WebElement element2 = driver.findElement(By.xpath(chartName
                            + "//child::*[position()=2 and name()='g']/child::*[position()=2 and name()='g']/child::*[position()="
                            + colorFieldRect + " and name()='rect']"));
                    jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');"
                            + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
                            + "arguments[0].dispatchEvent(evObj);", element2);
                    System.out.println(element2);
                    Thread.sleep(500);

                } catch (Exception ex) {
                    if (ex.getMessage().contains("Alert")) {
                        if (ex.getMessage().contains("Alert")) {

                            WebElement element3 = driver.findElement(By.xpath(chartName
                                    + "//child::*[position()=2 and name()='g']/child::*[position()=2 and name()='g']/child::*[position()="
                                    + colorFieldRect + " and name()='rect']"));
                            jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');"
                                    + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
                                    + "arguments[0].dispatchEvent(evObj);", element3);

                        }

                    }
                }

                try {
                    driver.findElements(By.xpath(chartName + "//child::*[name()='g' and position()="
                            + (actElementCnt + elementOffset) + "]"));

                } catch (Error e) {
                    verificationErrors.append("\n" + e.toString());
                }
                try {
                    String chartstr12 =

                            driver.findElement(By.xpath(chartName
                                    + "/..//child::*[position()=1 and name()='svg']/child::*[name()='g' and position()="
                                    + (actElementCnt + elementOffset) + "]//*[name()='text' and position()=" + 1
                                    + "]")).getText();
                    System.out.println("chartstr12 : " + chartstr12);
                    htmlElementNames.add(chartstr12);

                } catch (Error e) {
                    verificationErrors.append("\n" + e.toString());
                }
                try {

                    String chartstr22 =

                            driver.findElement(By.xpath(chartName
                                    + "/..//child::*[position()=1 and name()='svg']/child::*[name()='g' and position()="
                                    + (actElementCnt + elementOffset) + "]//*[name()='text' and position()=" + 2
                                    + "]")).getText();
                    System.out.println("chartstr22 : " + chartstr22);

                    htmlElementValues.add(chartstr22);

                } catch (Error e) {
                    verificationErrors.append("\n" + e.toString());
                }
                arraycounter = arraycounter + 1;

            } catch (Error e) {
                verificationErrors.append("\n" + e.toString());
            } catch (Exception e1) {
                verificationErrors.append("\n" + e1.toString());
            }
        } // end of second for loop

        htmlColumnValues.add(htmlElementNames);
        htmlColumnValues.add(htmlElementValues);

        htmlColumns.put(i, htmlColumnValues);

    } // end of first for loop

    for (int i = 1; i <= userColumns.size(); i++) {

        int checkingHtmlColumn = -1;

        for (int j = 1; j <= htmlColumns.size(); j++) {

            if (((ArrayList) userColumns.get(i).get(0)).get(0)
                    .equals(((ArrayList) htmlColumns.get(j).get(0)).get(0))) {
                checkingHtmlColumn = j;
                break;
            }
        }
        // check if the
        if (checkingHtmlColumn < 0) {
            verificationErrors.append("\n Element :" + i + " Input column name : "
                    + ((ArrayList) userColumns.get(i).get(0)).get(0) + " cannot be found in the chart");
            continue;
        } else {
            ArrayList currUserColumnNames = ((ArrayList) userColumns.get(i).get(0));
            ArrayList currUserColumnValues = ((ArrayList) userColumns.get(i).get(1));
            ArrayList currHtmlColumnNames = ((ArrayList) htmlColumns.get(checkingHtmlColumn).get(0));
            ArrayList currHtmlColumnValues = ((ArrayList) htmlColumns.get(checkingHtmlColumn).get(1));

            for (int k = 0; k < currHtmlColumnValues.size(); k++) {
                if (currHtmlColumnValues.get(k).equals("0") || currHtmlColumnValues.get(k) == null) {

                    currHtmlColumnNames.remove(k);
                    currHtmlColumnValues.remove(k);
                    k--;
                }
            }
            // Checking the column names
            if (currHtmlColumnNames.equals(currUserColumnNames)) {

            } else {

                verificationErrors.append("\n Element :" + i + " Expected element names = "
                        + userColumns.get(i).get(0) + " are different from the " + "actual names : "
                        + htmlColumns.get(checkingHtmlColumn).get(0) + " | ");
            }
            // Checking the column values
            if (currHtmlColumnValues.equals(currUserColumnValues)) {

            } else {
                verificationErrors.append("\n Element :" + i + " Expected element values = "
                        + userColumns.get(i).get(1) + " are different from the " + "actual values : "
                        + htmlColumns.get(checkingHtmlColumn).get(1) + " | ");
            }

        }
    }

    return verificationErrors;
}

From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

License:Apache License

/**
 * Checks the contents of a bar chart against the expected values.
 *///from   www. jav a 2 s  .c om

private StringBuffer insightBarChartContentCheck(String chartName, ArrayList<String> chartnames,
        ArrayList<String> chartvalues, ArrayList<String> chartpercentages, int startingele,
        String chartElementXpath) {

    // Portlet content variables
    WebDriver driver = getDriver();
    ArrayList<String> chartelementnames = chartnames;
    ArrayList<String> chartelementvalues = chartvalues;
    ArrayList<String> chartpercentage = chartpercentages;
    int startingelement = startingele;
    int arraycounter = 0;
    StringBuffer verificationErrors = new StringBuffer();
    int actCategoryCount = 0;
    int actElementCnt = 0;
    int elementOffset = 0;
    int firstChild = 0;

    ArrayList<String> htmlElementNames = new ArrayList<String>();
    ArrayList<String> htmlElementValues = new ArrayList<String>();

    Actions action = new Actions(driver);

    jsExecutor = (JavascriptExecutor) driver;

    // Checking chart structure
    // The first loop of the pie chart check
    if (chartName.contains("text")) {

        elementOffset = 3;
        firstChild = 4;
    } else if (chartName.contains("img")) {

        elementOffset = 2;
        firstChild = 3;
    }

    List<WebElement> locateElementsThree = driver.findElements(By
            .xpath(chartName + "//child::*[position()=" + firstChild + " and name()='g']/child::*[position()=2 "
                    + "and name()='g']/child::*[position()=2 " + "and name()='g']/child::*[name()='rect']"));

    System.out.println("### :" + locateElementsThree);
    actCategoryCount = locateElementsThree.size();

    List<WebElement> locateElementsFour = driver
            .findElements(By.xpath(chartName + "//child::*[position()=2 and name()='g']"));

    actElementCnt = locateElementsFour.size();

    for (int i = startingelement; i < actCategoryCount + startingelement; i++) {

        // Accessing the elements in the pie chart
        // ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT
        // ELEMENT ELEMENT ELEMENT

        try {
            try {

                action = new Actions(driver);

                action = new Actions(driver);
                WebElement chartHeaderEle = driver.findElement(By.xpath(chartElementXpath));

                jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');"
                        + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
                        + "arguments[0].dispatchEvent(evObj);", chartHeaderEle);

                Thread.sleep(1000);

                WebElement elementTwo = driver.findElement(By.xpath(chartName + "//child::*[position()="
                        + firstChild
                        + " and name()='g']/child::*[position()=2 and name()='g']/child::*[position()=2 "
                        + "and name()='g']/child::*[position()=" + i + " and name()='rect']"));
                Thread.sleep(1000);
                jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');"
                        + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
                        + "arguments[0].dispatchEvent(evObj);", elementTwo);

                Thread.sleep(1000);

            } catch (Exception ex) {
                if (ex.getMessage().contains("Alert")) {
                    action = new Actions(driver);

                    action.moveToElement(driver.findElement(By.xpath(chartName + "//child::*[position()="
                            + firstChild
                            + " and name()='g']/child::*[position()=2 and name()='g']/child::*[position()=2 and name()='g']/child::*[position()="
                            + i + " and name()='rect']"))).build().perform();

                }

            }

            try {

                driver.findElements(By.xpath(chartName + "/child::*[name()='g' and position()="
                        + (actElementCnt + elementOffset) + "]"));
            } catch (Error e) {
                verificationErrors.append("\n" + e.toString());
            }

            try {

                String chartstr12 = driver.findElement(By.xpath(
                        chartName + "/child::*[name()='g' and position()=" + (actElementCnt + elementOffset)
                                + "]//*[name()='text' and position()=" + 1 + "]"))
                        .getText();

                htmlElementNames.add(chartstr12);

            } catch (Error e) {
                verificationErrors.append("\n" + e.toString());
            }
            try {

                String chartstr22 = driver.findElement(By.xpath(
                        chartName + "/child::*[name()='g' and position()=" + (actElementCnt + elementOffset)
                                + "]//*[name()='text' and position()=" + 2 + "]"))
                        .getText();

                htmlElementValues.add(chartstr22);

            } catch (Error e) {
                verificationErrors.append("\n" + e.toString());
            }
            arraycounter = arraycounter + 1;

        } catch (Error e) {
            verificationErrors.append("\n" + e.toString());
        } catch (Exception e1) {
            verificationErrors.append("\n" + e1.toString());
        }

    }

    for (int i = 0; i < chartelementnames.size(); i++) {
        boolean isElementNameMatched = false;
        if (htmlElementValues.contains(chartelementvalues.get(i))) {
            // Get the indexes of duplicate entries
            ArrayList<Integer> indexes = new ArrayList<Integer>();
            for (int j = 0; j < htmlElementValues.size(); j++) {
                if (htmlElementValues.get(j).equals(chartelementvalues.get(i))) {
                    indexes.add(j);

                    for (int k = 0; k < indexes.size(); k++) {
                        if (htmlElementNames.get(indexes.get(k)).equals(chartelementnames.get(i))) {
                            isElementNameMatched = true;
                            break;
                        } else {
                            continue;
                        }
                    }
                }
            }
        } else {
            verificationErrors.append("\n Element :" + i + " Element value = " + chartelementvalues.get(i)
                    + " is not present. Actual Value :- " + htmlElementValues.get(i) + "\n");
        }

        if (htmlElementNames.contains(chartelementnames.get(i))) {
            isElementNameMatched = true;
            continue;
        }

        if (!isElementNameMatched) {
            verificationErrors
                    .append("\n Element :" + i + " Expected element name = " + chartelementnames.get(i)
                            + " is different from the " + "actual names :- " + htmlElementNames);
        }

    }

    return verificationErrors;
}

From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

License:Apache License

/**
 * Checks the contents of a pie chart against the expected values.
 * /*from  w w  w.  j a v a2s.c o m*/
 * @param chartElementXpath
 */

private StringBuffer insightPieChartContentCheck(String chartName, ArrayList<String> chartnames,
        ArrayList<String> chartvalues, ArrayList<String> chartpercentages, int startingele,
        String chartElementXpath) {

    // Portlet content variables
    WebDriver driver = getDriver();
    ArrayList<String> chartelementnames = chartnames;
    ArrayList<String> chartelementvalues = chartvalues;
    ArrayList<String> chartpercentage = chartpercentages;

    ArrayList<String> chartelementnamesAct = new ArrayList<String>();
    ArrayList<String> chartelementvaluesAct = new ArrayList<String>();

    int startingelement = startingele;
    int arraycounter = 0;
    StringBuffer verificationErrors = new StringBuffer();
    int elementCount = 0;

    JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
    // Checking chart structure
    // The first loop of the pie chart check

    // Accessing the elements in the pie chart
    // ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT ELEMENT
    // ELEMENT ELEMENT ELEMENT

    try {

        int countA = 0;

        List<WebElement> locateElements = driver
                .findElements(By.xpath("" + chartName + "//*[name()='svg']/child::*[name()='g']"));
        countA = locateElements.size();

        int categories = countA - 2;
        for (int j = startingelement; j < categories + startingelement; j++) {

            System.out.println("" + chartName + "//*[name()='svg']/child::*[position()=" + (j) + "]");
            WebElement chartElement = driver.findElement(By.xpath(chartElementXpath));

            jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');"
                    + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
                    + "arguments[0].dispatchEvent(evObj);", chartElement);

            Thread.sleep(1000);

            WebElement element = driver.findElement(
                    By.xpath("" + chartName + "//*[name()='svg']/child::*[position()=" + (j) + "]"));

            jsExecutor.executeScript("var evObj = document.createEvent('MouseEvents');"
                    + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
                    + "arguments[0].dispatchEvent(evObj);", element);

            try {
                driver.findElements(By.xpath("" + chartName + "//*[name()='svg']/child::*[position()="
                        + (chartelementnames.size() + startingelement) + "]"));

            } catch (Error e) {
                verificationErrors.append("\n" + e.toString());
            }

            Thread.sleep(500);

            int countB = 0;
            List<WebElement> locateElementsTwo = driver
                    .findElements(By.xpath("" + chartName + "//*[name()='svg']/child::*[name()='g']"));
            countB = locateElementsTwo.size();

            elementCount = countB;

            if (elementChartElementPresent("" + chartName + "//*[name()='svg']/child::*[position()="
                    + (categories + 4) + "]/child::*[position()=1]/child::*[position()=4]")) {

                String xpath = "" + chartName + "//*[name()='svg']/child::*[position()=" + (categories + 4)
                        + "]/child::*[position()=1]/child::*[position()=4]";

                System.out.println("XPATH :" + xpath);
                chartelementnamesAct.add(driver
                        .findElement(By.xpath("" + chartName + "//*[name()='svg']/child::*[position()="
                                + (categories + 4) + "]/child::*[position()=1]/child::*[position()=4]"))
                        .getText());

            }
            System.out.println("chartelementnamesAct : " + chartelementnamesAct);

            if (elementChartElementPresent("" + chartName + "//*[name()='svg']/child::*[position()="
                    + (categories + 4) + "]/child::*[position()=1]/child::*[position()=5]")) {

                chartelementvaluesAct.add(driver
                        .findElement(By.xpath("" + chartName + "//*[name()='svg']/child::*[position()="
                                + (categories + 4) + "]/child::*[position()=1]/child::*[position()=5]"))
                        .getText());

                System.out.println("chartelementvaluesAct:" + chartelementvaluesAct);
            }
        }
        for (int i = 0; i < chartelementnames.size(); i++) {

            String expectedname = "" + chartelementnames.get(i) + "";
            String expectedPers = "" + chartelementvalues.get(i) + " (" + chartpercentage.get(i) + "%)";

            if (chartelementnamesAct.contains(expectedname)) {

                if (chartelementvaluesAct.contains(expectedPers)) {

                } else {

                    verificationErrors
                            .append("\n Chart comparison mismatch : percentage " + expectedPers
                                    + " is not present in the actual percentage values " + expectedname)
                            .append(chartelementvaluesAct);
                }

            } else {

                verificationErrors
                        .append("\n Chart comparison mismatch : category name " + expectedname
                                + " is not present in the actual percentage values ")
                        .append(chartelementnamesAct);
            }
        }

    } catch (Exception e) {
        verificationErrors.append("\n" + e.toString());

    }

    return verificationErrors;

}