Automation QA Testing Course Content

Showing posts with label Selenium WebDriver. Show all posts
Showing posts with label Selenium WebDriver. Show all posts

Automating File Downloads with Selenium WebDriver Using Fluent Waits

 In test automation, handling file downloads can be a bit tricky, especially when you want to dynamically handle different file names. Instead of hardcoding the file name, it's much more flexible to detect the latest downloaded file, ensuring your script works regardless of the file name.

Here's an approach to achieve this using Selenium WebDriver in Java.

How to Approach it with Logic?

1. Set Up Chrome Preferences:

- We first configure Chrome using ChromeOptions to ensure that downloads go to a specific directory, without any browser popups or interruptions.

- The safebrowsing.enabled option is set to true to handle potentially insecure downloads.

2. Use FluentWait:

- To detect when the file download completes, we use a FluentWait on the download folder. This wait continuously checks if the file has been downloaded by monitoring changes in the folder.

3. Sort Files by Modification Time:

- Once the download starts, the files in the download directory are sorted based on their last modified timestamp. The latest modified file is assumed to be the newly downloaded one.

4. Ensure File Completeness:

- The script ensures that the file is fully downloaded by checking if the file is readable.

Automation Script Code:

package LambdaTest_PlagroundSolution;

import Selenium_Utilities.PageLocatorActions;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.FluentWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.File;
import java.time.Duration;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;

public class DownloadFileDemo_Test extends PageLocatorActions {

    private static String URL = "https://www.lambdatest.com/selenium-playground/download-file-demo";
    // To get the current working directory -System.getProperty("user.dir")
    private static String downloadFilePath = System.getProperty("user.dir") + "\\src\\main\\resources\\downloads";

    @BeforeTest
    public void setup() {

        HashMap<String, Object> chromePrefs = new HashMap<>();
        chromePrefs.put("profile.default_content_settings.popups", 0);
        chromePrefs.put("download.default_directory",downloadFilePath); // For changing defualt download folder path
        //Enable safe download - if you have issue while downloading like - "download blocked" or "unverified downlaod b"
        chromePrefs.put("safebrowsing.enabled", "true");
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("prefs", chromePrefs);
        //Disable notifications
        options.addArguments("--disable-notifications");
        //Downloading the file
        // To handle insecure file download warning - pop-up in Selenium
        // Use chrome options - "--unsafely-treat-insecure-origin-as-secure= <Your Domain Name>"
       // options.addArguments("--unsafely-treat-insecure-origin-as-secure=https://www.lambdatest.com/selenium-playground/download-file-demo");

        options.addArguments("--start-maximized");
        driver=new ChromeDriver(options);
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
        driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(25));
        driver.manage().deleteAllCookies();

    }

    @AfterTest
    public void teardown() {
        if (driver!=null) {
            driver.quit();
        }
    }

    @Test
    public void verifyDownloadFileDemo() {
        driver.get(URL);

        // Wait until the download link is clickable
        waitAndClickOnElementByXpath("//button[normalize-space()='Download File']");

        File file = new File(downloadFilePath);
        FluentWait<File> wait = new FluentWait<>(file)
                .withTimeout(Duration.ofMinutes(5))
                .pollingEvery(Duration.ofSeconds(5))
                .ignoring(Exception.class)
                .withMessage("File is not downloaded completely...");

        File downloadedFile = null;

        try {
            // Wait until the newest file is detected
            downloadedFile = wait.until(dir -> {
                File[] files = dir.listFiles();
                if (files != null && files.length > 0) {
                    // Sort the files by last modified date to get the latest one
                    return Arrays.stream(files)
                            .filter(File::canRead)  // Ensure the file can be read
                            .max(Comparator.comparingLong(File::lastModified))  // Get the latest file
                            .orElse(null);
                }
                return null;
            });
        } catch (Exception e) {
            System.out.println("File is not downloaded successfully...");
        }

        // If the file is downloaded, print the name of the file
        if (downloadedFile != null) {
            System.out.println("File " + downloadedFile.getName() + " is downloaded successfully..");
        } else {
            System.out.println("No file was downloaded.");
        }
    }
}

Key Points:

- Dynamic File Detection: No need to hardcode the file name. The script dynamically detects the most recently downloaded file in the specified directory.

- Handling Downloads with ChromeOptions: By modifying the default Chrome preferences, we ensure files are downloaded automatically to the desired location.

- Polling with FluentWait: FluentWait helps to check continuously until the file download is completed, ensuring a more robust test case.

How to handle browser level notification using Selenium Webdriver

 

I am Automating some test cases using Selenium Webdriver and core Java,in chrome browser for one test case on clicking button I am getting browser level notification 'Show notifications with options Allow and Block'. I want to select Allow option. Can anyone know how to handle this kind of notifications using Selenium webdriver. please refer following snapshot for more details


For Old Chrome Version (<50):

//Create a instance of ChromeOptions class
ChromeOptions options = new ChromeOptions();

//Add chrome switch to disable notification - "**--disable-notifications**"
options.addArguments("--disable-notifications");

//Set path for driver exe 
System.setProperty("webdriver.chrome.driver","path/to/driver/exe");

//Pass ChromeOptions instance to ChromeDriver Constructor
WebDriver driver =new ChromeDriver(options);

For New Chrome Version (>50):

//Create a map to store  preferences 
Map<String, Object> prefs = new HashMap<String, Object>();

//add key and value to map as follow to switch off browser notification
//Pass the argument 1 to allow and 2 to block
prefs.put("profile.default_content_setting_values.notifications", 2);

//Create an instance of ChromeOptions 
ChromeOptions options = new ChromeOptions();

// set ExperimentalOption - prefs 
options.setExperimentalOption("prefs", prefs);

//Now Pass ChromeOptions instance to ChromeDriver Constructor to initialize chrome driver which will switch off this browser notification on the chrome browser
WebDriver driver = new ChromeDriver(options);

For Firefox :

    WebDriver driver ;
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("permissions.default.desktop-notification", 1);
    DesiredCapabilities capabilities=DesiredCapabilities.firefox();
    capabilities.setCapability(FirefoxDriver.PROFILE, profile);
    driver = new FirefoxDriver(capabilities);
    driver.get("http://google.com");


WebDriverUtility Methods

package basicprograms;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WrapsDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.NoSuchFrameException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

public class WebDriverUtils {

WebDriver driver;

public WebDriverUtils(WebDriver driver) {
this.driver = driver;
}

/**
* Taking the entire browser screenshot
* @param screenName
* @throws IOException
*/
public void captureScreenshot(String screenName) throws IOException {

// take screenshot
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

// create Object for Date class
Date d = new Date();
screenName = screenName + "-" + d.toString().replace(":", "-").replace(" ", "-") + ".jpg";

// copy the file name under project directory
FileUtils.copyFile(src, new File(System.getProperty("user.dir") + "\\src\\screenshots\\" + screenName));

}

/**
* taking the element screenshot
* @param element
* @param screenName
* @throws IOException
*/
public void captureScreenshot(WebElement element, String screenName) throws IOException {

// take screenshot
File src = ((TakesScreenshot) element).getScreenshotAs(OutputType.FILE);

// create Object for Date class
Date d = new Date();
screenName = screenName + "-" + d.toString().replace(":", "-").replace(" ", "-") + ".jpg";

// copy the file name under project directory
FileUtils.copyFile(src, new File(System.getProperty("user.dir") + "\\src\\screenshots\\" + screenName));

}

public void switchToFrame(int frame) {
try {
driver.switchTo().frame(frame);
System.out.println("Navigated to frame with id " + frame);
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with id " + frame + e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to frame with id " + frame + e.getStackTrace());
}
}

public void switchToFrame(String frame) {
try {
driver.switchTo().frame(frame);
System.out.println("Navigated to frame with name " + frame);
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with id " + frame + e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to frame with id " + frame + e.getStackTrace());
}
}

public void switchToFrame(WebElement frameElement) {
try {
if (frameElement.isDisplayed()) {
driver.switchTo().frame(frameElement);
System.out.println("Navigated to frame with element " + frameElement);
} else {
System.out.println("Unable to navigate to frame with element " + frameElement);
}
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with element " + frameElement + e.getStackTrace());
} catch (StaleElementReferenceException e) {
System.out.println(
"Element with " + frameElement + "is not attached to the page document" + e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to frame with element " + frameElement + e.getStackTrace());
}
}

public void switchToFrame(String ParentFrame, String ChildFrame) {
try {
driver.switchTo().frame(ParentFrame).switchTo().frame(ChildFrame);
System.out.println("Navigated to innerframe with id " + ChildFrame + "which is present on frame with id"
+ ParentFrame);
} catch (NoSuchFrameException e) {
System.out
.println("Unable to locate frame with id " + ParentFrame + " or " + ChildFrame + e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to innerframe with id " + ChildFrame
+ "which is present on frame with id" + ParentFrame + e.getStackTrace());
}
}

public void switchtoDefaultFrame() {
try {
driver.switchTo().defaultContent();
System.out.println("Navigated back to webpage from frame");
} catch (Exception e) {
System.out.println("unable to navigate back to main webpage from frame" + e.getStackTrace());
}
}

// File upload by Robot Class
/**
* below method will upload given file location using Java Robot class
* @param filePath
*/
public static void uploadFileWithRobot(String filePath) {
// create object for StringSelection
StringSelection stringSelection = new StringSelection(filePath);
// copying the file location to system clipboard
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
// Create Object for robot class
Robot robot = null;

try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}

robot.delay(250);
// pressing the ENTER key and releasing
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
// pressing the CONTROL+V key and releasing the CONTROL+V
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
// pressing the ENTER key and releasing
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(150);
robot.keyRelease(KeyEvent.VK_ENTER);
}

/**
* this method downloads the files in firefox browser
* @param path
*/

public static FirefoxOptions downloadFileUsingFirefox(String path) {
// create object for FirefoxOptions class
FirefoxOptions options = new FirefoxOptions();
options.addPreference("browser.download.folderList", 2);
options.addPreference("browser.download.dir", path);

// File type of the downloaded file
options.addPreference("browser.helperApps.neverAsk.saveToDisk",
"image/jpeg, application/pdf, application/octet-stream,application/zip");
options.addPreference("browser.download.manager.showWhenStarting", false);
options.addPreference("pdfjs.disabled", true);
return options;
}

/**
* this method download the file using chrome browse
* @param path
* @return
*/

public static ChromeOptions downloadFileUsingChrome(String path) {
// DOWLOADD CODE
// craete object for ChromeOptions class
ChromeOptions options = new ChromeOptions();
// create HashMap object
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_settings.popups", true);
prefs.put("download.default_directory", path);
options.setExperimentalOption("prefs", prefs);
// set the chromedriver.exe path
return options;
}

/**
* this method highlights the given element
* @param driver
* @param element
* @throws InterruptedException
*/
public static void highLightElement1(WebDriver driver, WebElement element) throws InterruptedException {
JavascriptExecutor js = (JavascriptExecutor) driver; // downcasting

js.executeScript("arguments[0].setAttribute('style','background: yellow; border: solid 5px red')", element);

Thread.sleep(5000);

js.executeScript("arguments[0].setAttribute('style','border: solid 2px white')", element);

}

/**
* this method types given keyword without using sendKeys()
* @param element
* @param attributeName
* @param value
*/
public static void setAttribute(WebElement element, String attributeName, String value) {
WrapsDriver wrappedElement = (WrapsDriver) element;
JavascriptExecutor js = (JavascriptExecutor) wrappedElement.getWrappedDriver();
js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])", element, attributeName, value);
}

public static void scrollForElement(WebDriver driver, WebElement elementname) {
// scroll for this element
JavascriptExecutor jsx = (JavascriptExecutor) driver;
jsx.executeScript("arguments[0].scrollIntoView(true);", elementname);
}

public static void safeJavaScriptClick(WebDriver driver, WebElement element) {

try {
if (element.isEnabled() && element.isDisplayed()) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);
}

} catch (StaleElementReferenceException se) {
System.out.println("Element is no more attached to the DOM:");
se.printStackTrace();
} catch (NoSuchElementException ne) {
System.out.println("No Element present in the DOM:");
ne.printStackTrace();

} catch (Exception e) {
System.out.println("Exception is different:");
e.printStackTrace();
}

}

}

AutoIt Tool Usage


                                 AutoIt


Ø  Mouse Over on AUTOIT menu


Ø  Click on Downloads menu option

Ø  Click on Download AutoIt button


Ø  Mouse Over on AUTOIT EDITOR Menu

Ø  Click on Editor Downloads option
Ø  Click on Below Exe file

After downloading the AutoIt and AutoIt Editor
Click on each setup files & Complete the installation

Click on Next button

Keep the default installation location & Click on Install button


Click on Second SciTEAutoIt exe file and complete the installation process

GO to Help Section & Click on Index


We are going to use three commands
1)ControlFocus():


2)ControlSetText():

3)ControlClick():


Launch the AutoIt Editor & Identifier Tool From c:/program files (x.86)/AutoIt


Launch by clicking on AutoItInfo to open Identifier Tool

GO to C:/program files x 86/AutoIt/SciTE àClick on SciTE àEditor will lanuch


SCITE editor will launch



Click on Upload/browse icons in your application àThen window will open



Identify the File name field with Finder Toolàit will give title, class and instance values of the file name editbox





Identify the Open button


Script is ready now


Save the above file  --Go to File MenuàSave As


Save in one Folder AutoIt in Desired location


Right Click on FileàCompile the Script


After Compilation we will get one more application file


Write the selenium code and give the autoit script path using RunTime class getRuntime().exec(“path of the AutoItScript”)

 RunTime.getRunTime().exe("C:\\AutoItScript\\FileUploadFirefox.exe");

if you want to run on chrome generate new AutoItScript and compile then give that exe file path
 Runtime.getRuntime().exec("C:\\AutoItScript\\FileUploadchrome.exe");

-----------------------------------------------------------------------------------------------------------------
Step1)
AutoItScript for Chrome
copy and past below code in notepad
save filename:: AutoitScriptForChrome.au3
Select Save As option: All Types
----------------------------------------------------------------------------------------------------------------
WinWait("Open","",1000);
ControlFocus("Open","","Edit1");
ControlSetText("Open","","Edit1","C:\Users\rames\Downloads\Ramesh-stateID.pdf");
WinWait("Open","",1000);
ControlClick("Open","","Button1");

-----------------------------------------------------------------------------------------------------------------------
AutoItScript for Firefox
Copy and paste the below code in notepad
and save the filename:: AutoitScriptForFirefox.au3
Select Save As an option: All Types
------------------------------------------------------------------------------------------------------
WinWait("File Upload","",1000);
ControlFocus("File Upload","","Edit1");
ControlSetText("File Upload","","Edit1","C:\Users\rames\Downloads\Ramesh-stateID.pdf");
WinWait("File Upload","",1000);
ControlClick("File Upload","","Button1");
-------------------------------------------------------------------------------------------------------------
Step2:
Convert the filename.au3 as a .exe file 
right click on the filename.au3 -->select compile Script(x64)-->this will generate the AutoitScriptForFirefox.exe/AutoitScriptForChrome.exe
===================================================================
Step3: write an Automation script for uploading files

AutoIt Upload Files Programs:
package testngprograms;

package testngprograms;

import org.testng.annotations.Test;

import basicprograms.WebDriverUtils;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;

import java.io.IOException;
import java.time.Duration;
import java.util.LinkedList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;


public class FileUploadUsingAutoIt {
WebDriver driver = null;
WebDriverWait wait = null;
WebDriverUtils wutils = null;
//String fpath = "C:\\Users\\rames\\Downloads\\How to access Workday.pdf";
@Parameters({ "browser" })
@Test
public void fileUploadByAutoItTest(String browser) throws InterruptedException, IOException {
Reporter.log("open the url:https://easyupload.io/", true);
driver.get("https://easyupload.io/");
Reporter.log("verify the page title Easyupload.io - Upload files for free and transfer big files easily.", true);
wait.until(ExpectedConditions.titleContains("Easyupload.io - Upload files for free and transfer big files easily."));
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("body > main > div > div.upload > h1")));
String headerTxt = driver.findElement(By.cssSelector("body > main > div > div.upload > h1")).getText();
Assert.assertEquals("Upload and share files for free", headerTxt);
Reporter.log("click on cclick here or drop files to upload button", true);
driver.findElement(By.xpath("//*[@id='dropzone']/div[2]/button")).click();
Reporter.log("call the robotclass method to handle uplaod file", true);
//
if(browser.equalsIgnoreCase("chrome")) {
Runtime.getRuntime().exec("C:\\Users\\rames\\OneDrive\\Documents\\AutoitScript\\AutoItScriptForChrome.exe");
}else if(browser.equalsIgnoreCase("firefox")) {
Runtime.getRuntime().exec("C:\\Users\\rames\\OneDrive\\Documents\\AutoitScript\\AutoItScriptForFirefox.exe");
}
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("upload")));
Thread.sleep(1000);
Reporter.log("click on Upload button", true);
driver.findElement(By.id("upload")).click();
Reporter.log("File uploaded message assertions", true);
wait.until(ExpectedConditions.presenceOfElementLocated(By.className("upload-success")));
Assert.assertTrue(driver.findElement(By.xpath("//div[@class='upload-success']/h5")).isDisplayed(), "file is not uploaded");
Assert.assertEquals("Your file has been uploaded successfully.",driver.findElement(By.xpath("//div[@class='upload-success']/h5")).getText());
Thread.sleep(2000);
}
@Parameters({ "browser" })
@BeforeClass(alwaysRun = true)
public void beforeClass(String browser) {
if (browser.equalsIgnoreCase("chrome")) {
ChromeOptions opt = new ChromeOptions();
opt.setAcceptInsecureCerts(true);
driver = new ChromeDriver(opt);
Reporter.log("chromebrowser is launched", true);
} else if (browser.equalsIgnoreCase("firefox")) {

FirefoxOptions opt = new FirefoxOptions();
opt.setAcceptInsecureCerts(true);
// opt.setBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
// interface refvar=new implementedclass();
driver = new FirefoxDriver(opt);
Reporter.log("firefox browser is launched", true);
} else if (browser.equalsIgnoreCase("edge")) {
EdgeOptions opt = new EdgeOptions();
opt.setAcceptInsecureCerts(true);
driver = new EdgeDriver(opt);
Reporter.log("edge browser is launched", true);
}
Reporter.log("maximize the window", true);
driver.manage().window().maximize();
Reporter.log("add implicitwait", true);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));
Reporter.log("add explicitwait object", true);
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
Reporter.log("creating Object for WebDriverUtils class", true);
wutils = new WebDriverUtils(driver);
}

@AfterClass
public void afterClass() {
System.out.println("I am in AfterClass block");
// close the browser
driver.close();
}

}
--------------------------------------------------------------------
ActionsTestNG.xml file format
---------------------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="ActionsSuite">
  <test thread-count="5" name="ActionsTest">
  <parameter name="browser" value="firefox"></parameter>
    <classes>
      <!-- class name="testngprograms.DragAndDropTest"/ -->
      <!-- class name="testngprograms.DragAndDropByTest"></class -->
      <!-- class name="testngprograms.FlipKartMenuHandlingTest"></class -->
      <!-- class name="testngprograms.ActionsMethodsDemo"></class -->
      <!-- class name="testngprograms.OpenLinkNewTabAndNewWindowTest"></class -->
      <!-- class name="testngprograms.HandlingWebTableTest"></class -->
      <!-- class name="testngprograms.JqueryDatePickerTest"></class -->
      <!-- class name="testngprograms.FileUploadUsingRobot"></class -->
      <class name="testngprograms.FileUploadUsingAutoIt"></class>
    </classes>
  </test> <!-- ActionsTest -->
</suite> <!-- ActionsSuite -->
-----------------------------------------------------