How can the driver effectively pause until a specific condition becomes true before resuming if it remains false?

I am currently in the process of automating a workflow that involves generating a report. Each time the report is generated, it takes a varying amount of time (for example, anywhere from 10 to 50 seconds). I am facing difficulty in finding an effective way for the driver to wait until the report has been generated and then continue if the ExpectedCondition does not occur. Presently, although I can intentionally fail the test by instructing the driver to look for the expected condition "Your Report is complete," the issue is that the code does not proceed to the try-catch block after this line. It appears to be the final line executed.

Workflow: Starting from the main page where the report generation is initiated -> Pop-up window for the report generator (with a maximum wait time of 50 seconds) -> TWO POSSIBLE SCENARIOS: 1. "Another report is running, please try again later." 2. "Your Report is complete"

My selenium code:

//explicit wait
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'" + "Your Report is complete" + "')]")));

try{
    Assert.assertTrue(driver.getPageSource().contains("Your Report is complete."));
    log.info("Your report was successfully generated."); 
}
catch(AssertionError ex){
    log.error("Your report was not generated.");
    throw ex;
}
finally {
    driver.close();
    // change focus back to old tab
    driver.switchTo().window(oldTab);
    Thread.sleep(3000);
}

Page source code when the report is generated successfully:

<html>
    <HEAD>
        <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
        <TITLE>Generating report</TITLE>
        <style type="text/css" media="screen">
            @import url("public/css/main-new.css");
        </style>

        <script type="text/javascript" src="public/js/jquery.js"></script>

        <script type="text/javascript" src="public/js/Modal/prototype.js" ></script>
        <script type="text/javascript" src="public/js/Modal/scriptaculous.js?load=builder,effects" ></script>
        <script type="text/javascript" src="public/js/Modal/modalbox.js" ></script>
        <script type="text/javascript" src="public/js/tooltip.js" ></script>
        <link rel="stylesheet" href="public/css/modalbox.css" type="text/css" media="screen" />
        <link rel="stylesheet" href="public/css/tooltip.css" type="text/css" media="screen" />
        <script language="javascript" type="text/javascript" src="JSUtility.js"></script>

    </HEAD>
    <body style="margin: 25px;">
        <form method="post" action="LaunchReport.asp" id=form1 name=form1>
            <input type="hidden" name="REPORT" value="3diFevJrtGSy9AhdaEtY8Lh5N.xls">
            <input type="hidden" name="REPORTFINAL" value="3diFevJrtGSy9AhdaEtY8Lh5N.xls">
            <input type="hidden" name="PPVS" value="CELL5572">
            <input type="hidden" name="TYPE" value="AUDIT">
            <input type="hidden" name="CLASS" value="DEFINED">
            <input type="hidden" name="T" value="3">
            <input type="hidden" name="MT" value="540">

        </form>

            <p><b><font class="mdtext">Your Report is complete.</b></font></p>
            <p><font class="mdtext">Preparing to download....<br></font></p>
            <SCRIPT>
document.form1.submit();</SCRIPT>

    </body>
</html>

Thank you!

Answer №1

One possible solution could be utilizing the following code snippet:

WebDriverWait wait = new WebDriverWait(driver, 50);

try {
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'" + "Your Report is complete" + "')]")));
    // If this line is reached, it means the condition did not time out and the report has been generated.
    log.info("Your report has been successfully generated.");
}
catch (TimeoutException ex) {
    // The timeout occurred, indicating that the report was not generated within the specified time frame.
    log.error("The report generation process failed.");
    throw ex;
}
finally {
    driver.close();
    // Revert focus to the previous tab
    driver.switchTo().window(oldTab);
    Thread.sleep(3000);
}

In case you need to trigger an AssertionError, you can consider adding the following statement within the catch block:

catch (TimeoutException ex) {
    // Timeout happened, signaling that the report was not generated.
    log.error("The report was not created as expected.");
    Assert.assertTrue(false);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to execute various test suites based on parameters?

Currently, I have a Selenium testing code running with Junit 4.12 using @RunWith and @Suite annotations. Previously, I ran the test suite with three separate tests on a single machine. However, I now need to run my tests on multiple machines, some of which ...

Downloading a file utilizing Selenium through programming (versions 2.46 and above)

The FileDownloader class was functioning well until the upgrade to selenium 2.46: Guide on downloading files with Selenium in Java Upon running the test with selenium 2.46, I am now redirected to the login page. Has anyone else encountered this problem? ...

Struggling to resolve the issue of launching Chrome using Selenium WebDriver

Setting the system property for WebDriver to use the Chrome driver located at "C:\\Program Files (x86)\\Seleniumdriver\\chromedriver.exe"; Creating a new instance of ChromeDriver and assigning it to a WebDriver object. An er ...

Having trouble retrieving text from a class in Python using Selenium

When attempting to parse , I encountered an issue with extracting text from a specific class using the .text method. The search query being typed is "fitness". The window variable: all_cards = driver.find_elements(By.CLASS_NAME, "_1hf7139") for card_ in ...

Is it possible to merge a variable within single quotes in XPath?

Currently working with nodeJS and experimenting with the following code snippet: for (let i = 1; i <= elSize; i++) { try { let DeviceName = await driver .findElement(By.xpath("//span[@class='a-size-medium a-color-base a-text-normal ...

Leveraging sqlite memory database for selenium testing in Rails 4

Currently, my rspec tests are running smoothly using a memory sqlite database. However, when I run selenium driven tests (describe "does something", :js => true do), the web browser encounters an error stating SQLite3::SQLException: no such table: users ...

Tips for persisting a JSON Object in PostgreSQL with Hibernate in Java

Looking for a way to save a JSON object in PostgreSQL database using Hibernate with Java. Although PostgreSQL offers json and jsonb data types, Hibernate doesn't have built-in mapping for these data types. Seeking guidance on how to proceed, I came ac ...

Comparing AngularJS $http with $http.post: A Detailed Analysis

As a newcomer to AngularJS, I am experimenting with sending data to the server and mapping it to a DTO in a REST Service. Here's how I attempted to do it: saveUserUrl = "http://localhost:8080/App/rest/UserManager/saveUser"; var res ...

Encountering an error when executing cucumber tests using JUnit or TestNG

I am encountering an issue when trying to run the Cucumber TestRunner class with both TestNG and JUnit. I aim to include both TestNG and JUnit in my framework, yet I keep getting an abstract class error despite having all the necessary dependencies in my p ...

Executing JavaScript with Python in Selenium

Completely new to Selenium. I need help running a javascript snippet in this code (as commented), but struggling to do so. from selenium import webdriver import selenium from selenium.common.exceptions import NoSuchElementException from selenium.webdriver ...

Tips for implementing onclick selection in rows of a Wicket TreeTable

I'm currently using a TreeTable component (from wicket-extensions), and I have a requirement to enable row selection by clicking anywhere within the row, as opposed to just clicking on a specific cell link. I believe this can be achieved by attaching ...

Use Selenium in Python to automate filling in forms, then capture any pop-up messages that appear and clear the

Currently, I am attempting to use Selenium in Python to loop through and fill out a form. So far, I have been successful in filling the first form and receiving the popup message. However, my goal is to move on to the next element in the loop, but it seems ...

Finding the Button ID of the First Row in a List with Selenium and Razor: A Step-by-Step Guide

I am currently working with a list that has multiple rows and columns. In each row, there is a button labeled "Show Trail Details". https://i.stack.imgur.com/eiSot.png As I conduct tests, I find myself clicking twice on the "Date" column title to ensure ...

selenium.common.exceptions.InvalidSelectorException: Alert: A selector that is invalid or illegal has been provided

Currently, I am facing an issue with writing a script to manage web pages containing multiple elements. Upon clicking on one of these elements, it should open a new window. However, my current script is struggling to identify the element correctly. I requi ...

Guide to interacting with the Li element using JavaScript in Selenium

Is there a way to click on the item inside the li element using a Selenium script with JavaScript? I've tried different methods like By.cssSelector or by css, but I keep getting an ElementClickInterceptedError: element click intercepted:Other element ...

I'm having trouble finding the right xpath. Can you assist me with this?

https://i.stack.imgur.com/Y3wDn.png Can someone assist me with finding the correct xpath? ...

A method for selecting the checkbox in a mat-row that corresponds to a certain text with Selenium

I want to select the checkbox within a nested mat-row: <mat-row _ngcontent-dac-c252="" role="row" class="mat-row cdk-row ng-star-inserted"> <mat-cell _ngcontent-dac-c252="" role="cell" class=&quo ...

Issue with fingerprinting while running selenium tests concurrently

I have implemented fingerprint identification for anonymous site visitors using https://github.com/Valve/fingerprintjs2. However, I am facing an issue where I need to simulate multiple user sessions simultaneously in order to run tests. nosetests --proce ...

Steps for setting up the Selenium IDE extension in the Firefox web browser on a Windows operating

When working on my Mac or Ubuntu machine, I frequently use the Selenium IDE in Firefox. I'm now trying to figure out how to get the add-on to work in Firefox on Windows. Despite browsing through Firefox add-ons, I can't seem to find the actual S ...

Utilizing Selenium IDE and XPath to confirm that a checkbox is selected only when the associated label contains certain text

I need assistance in creating an Xpath query to validate if a specific checkbox is checked within the nested divs of the panel-body div. My goal is to ensure that a checkbox with the label "Evaluations" contains the class "checked". Below is the snippet of ...