Example usage for org.openqa.selenium.support.ui ExpectedConditions presenceOfElementLocated

List of usage examples for org.openqa.selenium.support.ui ExpectedConditions presenceOfElementLocated

Introduction

In this page you can find the example usage for org.openqa.selenium.support.ui ExpectedConditions presenceOfElementLocated.

Prototype

public static ExpectedCondition<WebElement> presenceOfElementLocated(final By locator) 

Source Link

Document

An expectation for checking that an element is present on the DOM of a page.

Usage

From source file:org.mousephenotype.cda.selenium.support.GenePage.java

License:Apache License

/**
 * Validates that://  w  w  w . j av a2 s. com
 * <ul>
 *     <li>There is a <b><i>Phenotype Association</i></b> section.</li>
 *     <li>Gene page title starts with <b><i>Gene:</i></b></li>
 *     <li>If there is a <b><i>genes</i></b> HTML table, validates that:
 *         <ul>
 *             <li>Each row has a p-value</li>
 *             <li>Each row has a valid graph link (the graph pages themselves
 *                 are not checked here as they take too long)</li>
 *             <li>The sex icon count matches <i>Total number of results</i> count</li>
 *             <li><b><i>TSV</i></b> and <b><i>XLS</i></b> downloads are valid</li>
 *         </ul>
 *     </li>
 *     <li>A <b><i>genes</i></b> HTML table is present if <code>
 *         genesTableRequired</code> is <code>true</code></li>
 *     <li>There are 3 buttons:</li>
 *     <ul>
 *         <li><b><i>Login to register interest</i></b></li>
 *         <li><b><i>Order</i></b></li>
 *         <li><b><i>KOMP</i></b></li>
 *     </ul>
 * </ul>
 * @param genesTableRequired If set to true, there must be a phenotype
 * HTML table or an error is logged. If false, no error is logged if there
 * is no phenotype HTML table.
 * @return validation status
 */
public RunStatus validate(boolean genesTableRequired) {
    RunStatus status = new RunStatus();

    // Validate title starts with 'Gene:'
    WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//h1[@id='top']")));
    if (!element.getText().startsWith("Gene:")) {
        status.addError("Expected gene page title to start with 'Gene:'.");
    }

    // Validate there is a 'Phenotype Association' section.
    try {
        wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//h2[@id='section-associations']")));
    } catch (Exception e) {
        status.addError("Expected 'Phenotype Association' section.");
    }

    // If there is a 'genes' HTML table, validate it.
    if (hasGenesTable) {
        geneTable.load(); // Load all of the genes table pageMap data. Use preAndPostQcList.
        List<List<String>> preAndPostQcList = geneTable.getPreAndPostQcList();
        String cell;
        int i = 0;
        for (List<String> row : preAndPostQcList) {
            if (i++ == 0)
                continue;

            //   Verify p value.
            cell = row.get(GeneTable.COL_INDEX_GENES_P_VALUE);
            if (cell == null) {
                status.addError("Missing or invalid P Value. URL: " + target);
            }

            cell = row.get(GeneTable.COL_INDEX_GENES_GRAPH_LINK);
            if ((cell == null) || (cell.trim().isEmpty())) {
                status.addError("Missing graph link. URL: " + target);
            }
        }

        // Validate the download links.
        status = validateDownload();
    } else {
        if (genesTableRequired) {
            status.addError("Expected genes HTML table but found none.");
        }
    }

    // Buttons - these are the only buttons that are guaranteed to exist.
    List<String> expectedButtons = Arrays.asList(new String[] { "Login to register interest" });
    List<String> actualButtons = new ArrayList<>();

    List<WebElement> actualButtonElements = driver
            .findElements(By.xpath("//a[contains(@class, 'btn')] | //button[contains(@class, 'btn')]"));
    for (WebElement webElement : actualButtonElements) {

        if (!webElement.getText().trim().isEmpty()) {
            actualButtons.add(webElement.getText());
        }
    }
    // ... count
    if (actualButtons.size() < expectedButtons.size()) {
        status.addError(
                "Expected at least " + expectedButtons.size() + " buttons but found " + actualButtons.size());
    }
    // ... Button text
    for (String expectedButton : expectedButtons) {
        if (!actualButtons.contains(expectedButton)) {
            status.addError("Expected button with title '" + expectedButton + "' but none was found.");
        }
    }

    return status;
}

From source file:org.mousephenotype.cda.selenium.support.GenePage.java

License:Apache License

/**
 * Waits for the gene page to load./*from www .  j a  v a  2s  . c  om*/
 */
private void load() throws TestException {
    try {
        driver.get(target);
        wait.until(ExpectedConditions
                .elementToBeClickable(By.xpath("//span[@id='summaryLinks']/following-sibling::a")));
        if (isOopsPage()) {
            throw new TestException("GenePage: Found 'Oops...' page. URL: " + target);
        }
        wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("span#enu")));
    } catch (Exception e) {
        throw new TestException(
                "GenePage: failed to load url. Reason: " + e.getLocalizedMessage() + "\nURL: " + target);
    }

    List<WebElement> elements;

    // Check for phenotype associations. If any, determine whether or not the page has graphs by looking for one or
    // more post qc links.
    elements = driver.findElements(By.xpath("//table[@id='genes']"));
    hasGenesTable = !elements.isEmpty();
    if (hasGenesTable) {
        elements = driver.findElements(By.xpath("//*[@id='phenotypesDiv']//td[@class='postQcLink']/a"));
        hasGraphs = (elements.size() > 0);
    }

    // Check for expression.

    // Check for phenotype associated images.
    elements = driver.findElements(By.xpath("//*[@id='section-images']/following-sibling::div[1]//h5"));
    if (!elements.isEmpty()) {
        String text = elements.get(0).getText().toLowerCase();
        hasImages = text.contains("legacy");
        hasImpcImages = text.contains("associated images");
    }

    // Check for disease models.
    elements = driver.findElements(By.xpath("//*[@id='predicted_diseases_table']"));
    if (!elements.isEmpty()) {
        hasDiseaseModels = !elements.isEmpty();
    }
}

From source file:org.mousephenotype.cda.selenium.support.GeneTable.java

License:Apache License

/**
 * Pulls <code>numRows</code> rows of postQc data and column access
 * variables from the gene page's 'genes' HTML table.
 *
 * @param numRows the number of postQc phenotype table rows to return,
 * including the heading row. To specify all postQc rows, set
 * <code>numRows</code> to null.
 * @return <code>numRows</code> rows of data and column access variables
 * from the gene page's 'genes' HTML table.
 *//*from  ww w.  ja  v  a 2s .c  o m*/
public GridMap load(Integer numRows) {
    if (numRows == null)
        numRows = computeTableRowCount();

    String[][] dataArray;
    postQcList = new ArrayList();
    preAndPostQcList = new ArrayList();
    String value;

    // Wait for page.
    WebElement genesTable = wait
            .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("table#genes")));

    // Grab the headings.
    List<WebElement> headings = genesTable.findElements(By.cssSelector("thead tr th"));
    numRows = Math.min(computeTableRowCount(), numRows); // Take the lesser of: actual row count in HTML table (including heading), or requested numRows.
    int numCols = headings.size();

    dataArray = new String[numRows][numCols]; // Allocate space for the data.
    int sourceColIndex = 0;
    for (WebElement heading : headings) { // Copy the heading values.
        dataArray[0][sourceColIndex] = heading.getText();
        sourceColIndex++;
    }

    postQcList.add(Arrays.asList(dataArray[0]));
    preAndPostQcList.add(Arrays.asList(dataArray[0]));
    // Loop through all of the tr objects for this page, gathering the data.
    int sourceRowIndex = 1;

    for (WebElement row : genesTable.findElements(By.xpath("//table[@id='genes']/tbody/tr"))) {
        List<WebElement> cells = row.findElements(By.cssSelector("td"));

        sourceColIndex = 0;
        boolean skipLink = false;
        boolean createMaleRow = false;
        for (WebElement cell : cells) {
            value = "";
            if (sourceColIndex == COL_INDEX_GENES_PAGE_PHENOTYPE) {
                List<WebElement> elements = cell.findElements(By.cssSelector("a"));
                if (!elements.isEmpty()) {
                    value = elements.get(0).getText();
                } else {
                    value = cell.getText();
                }
            } else if (sourceColIndex == COL_INDEX_GENES_PAGE_ALLELE) {
                String rawAllele = cell.getText();
                List<WebElement> supList = cell.findElements(By.cssSelector("sup"));
                if (supList.isEmpty()) {
                    value = rawAllele;
                } else {
                    String sup = supList.get(0).getText();
                    AlleleParser ap = new AlleleParser(rawAllele, sup);
                    value = ap.toString();
                }
            } else if (sourceColIndex == COL_INDEX_GENES_PAGE_SEX) { // Translate the male/female symbol into a string: 'male', 'female', 'both', or 'no data'.
                List<WebElement> sex = cell.findElements(By.xpath(".//img[@alt='Male' or @alt='Female']"));
                if (sex.isEmpty()) {
                    value = SexType.no_data.toString();
                } else {
                    if (sex.size() == 2) {
                        List<WebElement> bothSexesElement = cell
                                .findElements(By.xpath("./span[@class='bothSexes']"));
                        if (bothSexesElement.isEmpty()) {
                            value = SexType.female.toString();
                            createMaleRow = true;
                        } else {
                            value = SexType.both.toString();
                        }
                    } else {
                        value = sex.get(0).getAttribute("alt").toLowerCase();
                    }
                }
            } else if (sourceColIndex == COL_INDEX_GENES_PAGE_GRAPH_LINK) { // Extract the graph url from the <a> anchor and decode it.

                List<WebElement> graphLinks = cell.findElements(By.cssSelector("a"));
                value = "";
                if (!graphLinks.isEmpty()) {

                    value = graphLinks.get(0).getAttribute("href");
                } else {
                    graphLinks = cell.findElements(By.cssSelector("i"));
                    if (!graphLinks.isEmpty()) {
                        value = graphLinks.get(0).getAttribute("oldtitle");
                        if (value.contains(NO_SUPPORTING_DATA)) {
                            skipLink = true;
                        }
                    }
                }

            } else {
                value = cell.getText();
            }

            dataArray[sourceRowIndex][sourceColIndex] = value;
            sourceColIndex++;
        }

        String[] maleRow = null;
        if (createMaleRow) {
            maleRow = dataArray[sourceRowIndex].clone();
            maleRow[COL_INDEX_GENES_PAGE_SEX] = "male";
        }

        preAndPostQcList.add(Arrays.asList(dataArray[sourceRowIndex])); // Add the row to the preAndPostQc list.
        if (!skipLink) {
            postQcList.add(Arrays.asList(dataArray[sourceRowIndex])); // Add the row to the preQc list.
            if (maleRow != null) {
                postQcList.add(Arrays.asList(maleRow));
            }
            if (postQcList.size() >= numRows) { // Return when we have the number of requested rows.
                break;
            }
        }

        if (maleRow != null) {
            preAndPostQcList.add(Arrays.asList(maleRow));
        }
        sourceRowIndex++;
    }

    //        preQcList = commonUtils.expandCompoundColumns(preQcList, expandColumnList, "|");
    //        postQcList = commonUtils.expandCompoundColumns(postQcList, expandColumnList, "|");
    //        preAndPostQcList = commonUtils.expandCompoundColumns(preAndPostQcList, expandColumnList, "|");
    data = new GridMap(postQcList, target);
    return data;
}

From source file:org.mousephenotype.cda.selenium.support.GraphPage.java

License:Apache License

/**
 * Parse the tsv and xls download files. When successfully completed, the
 * map will contain two key/value pairs: one keyed "tsv" and one keyed
 * "xls". Each value contains a list of download data by section, where a
 * section is identified as starting with a column heading.
 *
 * @return two key/value pairs: one keyed "tsv" and one keyed "xls". Each
 * value contains a list of download data by section, where a section is
 * identified as starting with a column heading.
 * @throws Exception /* w w w .j  ava2 s  . c o  m*/
 */
public List<DownloadSection> loadAllDownloadData() throws Exception {
    List<DownloadSection> retVal = new ArrayList();

    // Extract the TSV data.
    // Typically baseUrl is a fully-qualified hostname and path, such as http://ves-ebi-d0:8080/mi/impc/dev/phenotype-arcihve.
    // getDownloadTargetUrlBase() typically returns a path of the form '/mi/impc/dev/phenotype-archive/export?xxxxxxx...'.
    // To create the correct url for the stream, replace everything in downloadTargetUrlBase before '/export?' with the baseUrl.
    String downloadTargetUrlBase = wait
            .until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@id='exportIconsDivGlobal']")))
            .getAttribute("data-exporturl");
    String downloadTargetTsv = testUtils.patchUrl(baseUrl, downloadTargetUrlBase + "tsv", "/export?");

    // Get the download stream data.
    List<List<List<String>>> downloadBlockTsv = new ArrayList();
    List<List<List<String>>> downloadBlockXls = new ArrayList();

    URL url;
    try {
        url = new URL(downloadTargetTsv);

    } catch (IOException e) {
        throw new TestException("EXCEPTION creating url '" + downloadTargetTsv + "': ", e);
    }

    try (DataReaderTsv dataReaderTsv = new DataReaderTsv(url)) {
        String[][] allGraphData = dataReaderTsv.getData();

        if (allGraphData.length > 0) {
            downloadBlockTsv = parseDownloadStream(allGraphData);
        }

    } catch (IOException e) {
        throw new TestException("Error parsing TSV", e);
    }
    // Extract the XLS data.
    String downloadTargetXls = testUtils.patchUrl(baseUrl, downloadTargetUrlBase + "xls", "/export?");

    try {
        url = new URL(downloadTargetXls);

    } catch (IOException e) {
        throw new TestException("EXCEPTION creating url '" + downloadTargetTsv + "': ", e);
    }

    try (DataReaderXls dataReaderXls = new DataReaderXls(url)) {
        String[][] allGraphData = dataReaderXls.getData();

        if (allGraphData.length > 0) {
            downloadBlockXls = parseDownloadStream(allGraphData);
        }

    } catch (IOException e) {
        throw new TestException("Error parsing XLS", e);
    }

    for (int i = 0; i < downloadBlockTsv.size(); i++) {
        Map<DownloadType, List<List<String>>> downloadDataMap = new HashMap();

        downloadDataMap.put(DownloadType.TSV, downloadBlockTsv.get(i));
        downloadDataMap.put(DownloadType.XLS, downloadBlockXls.get(i));
        DownloadSection downloadSection = new DownloadSection(downloadDataMap);
        retVal.add(downloadSection);
    }

    return retVal;
}

From source file:org.mousephenotype.cda.selenium.support.PhenotypePage.java

License:Apache License

/**
 *
 * @return The definition string//from w w  w.java2s.c  om
 */
public String getDefinition() {
    String definition = "";

    try {
        WebElement element = wait
                .until(ExpectedConditions.presenceOfElementLocated(By.xpath("//p[@id='definition']")));
        if (!element.getText().isEmpty()) {
            if (element.findElement(By.cssSelector("span.label")).getText().trim().equals("Definition")) {
                definition = element.getText().split("\\n")[1].trim();
            }
        }
    } catch (Exception e) {
    }

    return definition;
}

From source file:org.mousephenotype.cda.selenium.support.PhenotypePage.java

License:Apache License

/**
 *
 * @return A list of mapped hp terms. The list will be empty if there are no mapped hp terms.
 *///from   w w  w  .j  av a  2  s  .  c o m
public List<String> getMappedHpTerms() {
    List<String> mappedHpTermList = new ArrayList();

    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//p[@id='mpId']")));

    try {
        List<WebElement> mappedHpTermElements = driver
                .findElements(By.xpath("//div[@id='mappedHpTerms']/ul/li"));
        for (WebElement mappedHpTermElement : mappedHpTermElements) {
            mappedHpTermList.add(mappedHpTermElement.getText().trim());
        }

    } catch (Exception e) {
    }

    return mappedHpTermList;
}

From source file:org.mousephenotype.cda.selenium.support.PhenotypePage.java

License:Apache License

/**
 *
 * @return A list of procedures. The list will be empty if there are no procedures.
 *///from ww  w.  j  a v a 2  s  .c  o m
public List<PhenotypeProcedure> getProcedures() {
    List<PhenotypeProcedure> procedureList = new ArrayList();

    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//p[@id='mpId']")));

    try {
        List<WebElement> procedureElements = driver.findElements(By.xpath("//div[@id='procedures']/ul/li/a"));
        for (WebElement procedureElement : procedureElements) {
            PhenotypeProcedure phenotypeProcedure = new PhenotypeProcedure(procedureElement.getText(),
                    procedureElement.getAttribute("href"));
            procedureList.add(phenotypeProcedure);
        }

    } catch (Exception e) {
    }

    return procedureList;
}

From source file:org.mousephenotype.cda.selenium.support.PhenotypePage.java

License:Apache License

/**
 *
 * @return A list of synonyms. The list will be empty if there are no synonyms.
 *///from  w  w  w .  jav  a 2 s.co  m
public List<String> getSynonyms() {
    List<String> synonymList = new ArrayList();

    try {
        wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//p[@id='mpId']")));

        List<WebElement> synonymElements = driver.findElements(By.xpath("//p[@id='synonyms']"));
        for (WebElement synonymElement : synonymElements) {
            String[] synonymArray = synonymElement.getText().replace("Synonyms\n", "").split(",");
            for (String synonym : synonymArray) {
                synonymList.add(synonym.trim());
            }
        }

    } catch (Exception e) {
    }

    return synonymList;
}

From source file:org.mousephenotype.cda.selenium.support.PhenotypePage.java

License:Apache License

/**
 * Validates that:/*from  w  w  w . jav a  2  s  . c  o m*/
 * <ul>
 *     <li>MGI MP browser has a link, and title starts with <b><i>Phenotype</i></b></li>
 *     <li>There is either a <b><i>Phenotype Association</i></b> section
 *         or an <b><i>Images</i></b> or both.</li>
 *     <li>If there is a <b><i>phenotypes</i></b> HTML table, validates that:
 *         <ul>
 *             <li>Each row has a p-value</li>
 *             <li>Each row has a valid graph link (the graph pages themselves
 *                 are not checked here as they take too long)</li>
 *             <li>The sex icon count matches <i>Total number of results</i> count</li>
 *             <li><b><i>TSV</i></b> and <b><i>XLS</i></b> downloads are valid</li>
 *         </ul>
 *     </li>
 * </ul>
 * @return validation status
 */
public RunStatus validate() {
    RunStatus status = new RunStatus();

    // Validate title starts with 'Phenotype:'
    WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//h1[@id='top']")));
    if (!element.getText().startsWith("Phenotype:")) {
        status.addError("Expected phenotype page title to start with 'Phenotype:'.");
    }

    // Validate there is a 'Phenotype Association' section or at least one image.
    try {
        wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//h2[@id='gene-variants']")));
    } catch (Exception e) {
        if (!hasImages()) {
            status.addError("Expected either 'Phenotype Association' section or 'Images' section or both.");
        }
    }

    // If there is a 'phenotypes' HTML table, validate it.
    if (hasPhenotypesTable) {
        // Validate that there is a 'pheontypes' HTML table by loading it.
        phenotypeTable.load(); // Load all of the phenotypes table pageMap data.
        List<List<String>> preAndPostQcList = phenotypeTable.getPreAndPostQcList();
        String cell;
        int i = 0;
        for (List<String> row : preAndPostQcList) {
            if (i++ == 0)
                continue;

            //   Verify p value.
            cell = row.get(PhenotypeTable.COL_INDEX_PHENOTYPES_P_VALUE);
            if (cell == null) {
                status.addError("Missing or invalid P Value. URL: " + target);
            }

            // Validate that the graph link is not missing.
            cell = row.get(PhenotypeTable.COL_INDEX_PHENOTYPES_GRAPH_LINK);
            if ((cell == null) || (cell.trim().isEmpty())) {
                status.addError("Missing graph link. URL: " + target);
            }
        }

        // Validate the download links.
        //status = validateDownload(); jw set to ignore as failing for various reasons - surely we can set the code to run from the same method for display and download?
    }

    return status;
}

From source file:org.mousephenotype.cda.selenium.support.PhenotypePage.java

License:Apache License

/**
 * Waits for the pheno page to load.//from   w  w w . j a  va  2 s  .  c  om
 */
private void load() {
    final String NOT_AVAILABLE = "Phenotype associations to genes and alleles will be available once data has completed quality control.";

    driver.get(target);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//h2[@id='gene-variants']")));

    // Get results count. [NOTE: pages with no phenotype associations don't have totals]
    Integer i = null;
    List<WebElement> elements = driver.findElements(By.cssSelector("div#phenotypesDiv div.alert"));
    if (elements.isEmpty()) {
        elements = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(
                By.xpath("//div[@id='phenotypesDiv']/div[@class='container span12']/p[@class='resultCount']")));
        if (!elements.isEmpty()) {
            String totResultsString = elements.get(0).getText();
            int index = totResultsString.lastIndexOf(":");
            String count = totResultsString.substring(index + 1);
            i = commonUtils.tryParseInt(count);
        }
    }

    // Determine if this page has images.
    elements = driver.findElements(By.xpath("//*[@id='imagesSection']/div/div/div"));
    hasImages = !elements.isEmpty();

    // Determine if this page has phenotype associations.
    elements = driver.findElements(By.xpath("//table[@id='phenotypes']"));
    hasPhenotypesTable = !elements.isEmpty();

    resultsCount = (i == null ? 0 : i);
    hasGraphs = (resultsCount > 0);
}