Selenium Automation

File upload is a very common type of operation we perform on the web these days. Automating it will prompt you with a dialog box that is just out of reach for Selenium. To handle such file dialogs testers often opt for a third-party tool, like AutoIT. While meeting your short-term needs, it surely sets you up for failure later by tying you to a specific platform (e.g., AutoIT only works on Windows), limiting your ability to test this functionality on different browsers & operating systems. To avoid such outcomes, you can now resort to these test automation techniques that can handle file upload workflows in Selenium web driver, successfully. Let’s understand these four efficient techniques which testers can utilize to handle multiple file uploads.

1) Using Send Keys: Send Keys is one of the most common methods of the selenium framework for sending the absolute file paths to the browser file dialog and locating the web-elements, either by ‘id’ or ‘name.’ To make sure this approach works, the following guidelines must be fulfilled:

  • The file textbox properties must be “Enabled” & “Visible”
  • The file’s path must be the absolute path
  • Not to perform a “Click” action to launch the file dialog

Below code demonstrates multiple files upload using SendKeys:

package com.easy.upload;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class UploadFile {
static WebDriver driver;
String URL = "application URL";
@Test
public void testUpload() throws InterruptedException
{
driver = new FirefoxDriver();
driver.get(URL);
WebElement element = driver.findElement(By.name("uploadsubmit"));
//To input the filename along with path
element.sendKeys("D://seleniumuploads//file.2txt");
// To click on the submit button (Not the browse button)
driver.findElement(By.name("SubmitBtn")).click();
String checkText = driver.findElement(By.id("message")).getText();
Assert.assertEquals("File uploaded successfully", checkText);
}
}

Note: Make sure, you are not clicking on the browse button as it will open windows dialogue box where Selenium web driver would not work. We have shared the file path using the code shown above. Submit the form & check if the files are uploaded successfully.

2) Using Robot Class: The purpose of using Robot Class is to take control of the keyboard & mouse. After gaining the control, you’d be able to ‘automate’ the operations and define the sequence of ‘actions’ to simulate mouse movements & keyboard usage. It’s important to know that Robot Class is not a part of Selenium & it comes with Java. Let’s look at the steps involved: Step 1- Copy the file location in system clipboard. Step 2- Click on the upload button and use CTR+V and ENTER. Note: While using the Robot class method, each key must be pressed & released respectively. Find the example below:

package testpack1;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FileUpload_Robot {
static WebDriver driver;
public static void main(String[] args) throws Exception{
System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Softwares\\chromebrowser\\chromedriver_win32 (2)\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://toolsqa.com/automation-practice-form/");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.manage().deleteAllCookies();
driver.findElement(By.id("photo")).click();
Thread.sleep(2000);
uploadFile("C:\\Users\\rkandula\\Desktop\\ImpData.txt";
Thread.sleep(2000);
}
public static void setClipboardData(String string) {
//StringSelection is a class that can be used for copy and paste operations.
StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
public static void uploadFile(String fileLocation) {
try {
//Setting clipboard with file location
setClipboardData(fileLocation);
//native key strokes for CTRL, V and ENTER keys
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
} catch (Exception exp) {
exp.printStackTrace();
}
}
}

Methods used in Robot Class:

  • robot.keyPress(KeyEvent.VK_CONTROL); this method is used to press the ‘control’ key in the keyboard
  • robot.keyPress(KeyEvent.VK_V); this method is used to press the ‘V’ key in the keyboard (it will automatically Press (ctrl+v) on the keyboard)
  • robot.keyPress(KeyEvent.VK_CONTROL); this method is used to release the ‘control’ key in the keyboard
  • robot.keyPress(KeyEvent.VK_V); this method is used to press the ‘V’ key in the keyboard (it will Release (ctrl+v) on the keyboard & paste the file in the desired location)
  • robot.keyPress(KeyEvent.VK_ENTER) && robot.keyRelease(KeyEvent.VK_ENTER); Press and Release the ‘Enter’ button (in the popup window, if you press ‘Enter,’ it will trigger ‘Open’ button in the window)

Note: With the help of ROBOT class, we can easily upload/download files. But in the case of bulk upload, we need to recurrently perform ‘KeyPress’ or ‘Key Release’ methods, which is a limitation of this approach.

3) Using AutoIT: AutoIT helps to upload files by transferring the control from Selenium web driver to AutoIT. We need to explicitly call the AutoIT script from our program. After clicking on upload button, the focus will be moved to AutoIT and it will execute the statements which will be used to upload files. Syntax:

Runtime.getRuntime().exec("AutoIt .exe filepath");

Please find below steps:

Step 1: Download and install AutoIt: https://www.autoitscript.com/site/autoit/downloads/ and once the installation is complete Run .exe file followed by simple next. Download AutoIt Step 2: Go to your local machine path: C:\Program Files (x86)\AutoIt3 to open AutoIT SciTE Editor and Windows handling objects spy. a) Au3Info_x64 – Click on the application. It opens a small window, like the image shown below. Autoit Scite Editor b) Open editor to write code: path: C:\Program Files (x86)\AutoIt3\SciTE\SciTE.exe : click on SciTE editor Editor Once everything is ready, open the application and find the elements to upload the file.

Please find sample html code for using multiple file uploads:

Step 1: Open notepad and paste below code and save it as .html extension ex: fileuploads.html

<!DOCTYPE html>
<html>
<body>
<form action="/FileUploadsPage.php">
Select images: <input type="file" id="UploadFiles" name="img" multiple>
<input type="submit">
</form>
<p>Select 1 or more than one file, while browsing.</p>
<p><strong>Note:</strong> the input tag for multiple file uploads will not support in IE 9 browser or less than</p>
</body>
</html>

Step 2: Now open recently created file in Firefox or chrome browser. You will see sample file uploads application.

Example: File Uploads Application Step 3: Click on ‘Browse’, it will open the File Upload window.

Step 4: Open AutoIT script editor & Finder tool is used to inspect the elements and write the necessary script.

Additionally, you’d need to: a) Identify the Window Name b) Identify the File Name input box & enter the file path which is to be uploaded c) Click on ‘open’ Find below a sample code to upload the file.

ControlFocus(windowTitle,text,controlID);
ControlSetText(windowTitle, text,controlID,fielPath);
ControlClick(windowTitle, text, controlID);

Step 5: In the above three methods, the text parameter is optional, and we can leave it blank. But other parameters are imperative to be provided. Open every window, hold and drag the finder tool icon over the element to inspect/identify. Refer to the sample screenshot shared below for the same. Automation Demo Site Drag the finder tool to find properties of the element. Refer to the sample screenshot shared below. Finder Tool Step 6: Open AutoIT Editor & start preparing a script like shown below. AutoIt Editor Here’s a brief explanation: Code Explanation Note: A user can add ‘files path’ recurrently in the editor.

Step 7: Save the script to a specific location with a unique name.

Note: The script will be saved as .au3 extension by default

Step 8: To compile, right click on the file and select compile script. This will help to generate an .exe file. Complile Script or Complile Script Step 9: Now write Selenium program and add this .exe file to run the program. Selenium Program Step 10: You can run the program now

4) Using Sikuli

Sikuli is an open source Graphical User Interface automation tool. Sikuli will be used to automate anything that you can view on the screen. It uses image recognition to speak with the GUI elements. When there is no easy access to a GUI’s source code this is one of the best ways to get the appropriate response.

Below steps are used to integrate Sikuli with selenium web driver:

With the help of Sikuli setup jar file, we can integrate selenium with WebDriver. Follow the steps shown below:

  • Open Eclipse and create a sample maven project and add dependencies using pom.xml

Pom xml Note: If you add repository for SNAPSHOT in pom .xml file, you will not get ‘mismatching versions’ or ‘missing artifacts’ error. Create a java class file->Right click on src/test/java ->new->Class Use below code and change images or file locations based on your requirement.

Sample Code:

package uploads;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
public class FileUpload_Sikuli {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe");
WebDriver wd=new ChromeDriver();
wd.get("path of url");
wd.findElement(By.id("fileupload")).click();
Screen sikuliscreen=new Screen();
String file1="\"C:\\Users\\rkandula\\Desktop\\window_Textbox.png\"";
String file2="\"C:\\Users\\rkandula\\Desktop\\window_openbtn.png\"";
String mutliplefiles=file1+file2;
System.out.println(total);
Pattern window_popup_textbox=new Pattern("C:\\Users\\rkandula\\Desktop\\window_Textbox.png");
Pattern window_openbtn=new Pattern("C:\\Users\\rkandula\\Desktop\\window_openbtn.png");
sikuliscreen.wait(window_popup_textbox, 20);
sikuliscreen.type(window_popup_textbox, mutliplefiles);
sikuliscreen.click(window_openbtn);
Thread.sleep(3000);
wd.close();

Code Explanation:

Step 1: Set the chrome driver .exe file in system. setproperty.

System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe");

Step 2: Using snipping tool (to locate it in your machine, please type snipping tool in the Windows) FileTextBox Capture screenshot of ‘File textbox’ location and ‘open’ button and save it in machine.

Note: Sikuli uses the technique of Image Recognition to recognize elements on the screen. It finds elements on screen solely based on their images.

Step 3: Sikuli uses Screen & Pattern class method. Create object for Screen and Pattern and place the captured screenshot location in pattern object.

Screen sikuliscreen=new Screen();
Pattern window_popup_textbox=new Pattern("path of image\\window_Textbox.png");
Pattern window_openbtn=new Pattern("path of image\\window_openbtn.png");

Step 4: Open any browser chrome of Firefox and hit your application url.

wd.get("path of url");

Step 5: Click on ‘choose file’ or ‘upload’ button

wd.findElement(By.id("fileupload")).click();

Step 6: Wait for the windows icon to popup.

sikuliscreen.wait(window_popup_textbox, 20);

Step 7: Type the file into the text box and click ‘open.’

sikuliscreen.type(window_popup_textbox, "path of filename" );
//here you can upload single file or multiple files in my cases I added 2 files at a time
sikuliscreen.click(window_openbtn);

Step 8: Wait for the specified time and close the browser.

Thread.sleep(3000);
wd.close();

Sikuli is used to identify the ‘file input text’ box and ‘open’ button on popup using the stored images. If in case the screen resolution changes, the behavior of Sikuli would differ. So, it is advisable to run the scripts on the same resolution of the images captured. In case, a pixel size of an image changes, it throws FindFailed exception. These distinct file upload methods are tried & tested by us. They have the potential to be integrated easily with your code. Here, we have supported content with relevant images and coding to help you get a different perspective at uploading files in your Selenium projects efficiently.

Evoke’s – Software Testing Services

Our software testing services enable firms to optimize their software application quality and performance. We also provide quality assurance services that are built to ensure a seamless end-user experience with a greater focus on software performance, automation, and security. The mature software testing frameworks and processes coupled with smart testing methodologies, provided by Evoke are designed to help firms to improve their software applications and delight end-users. To know more about our world-class software testing services, contact us via our website or call us at +1 (937) 660-4923.