Record Selenium Automation Flows

BEST-AUTOMATION-TESTING-TOOLS

         We know that automation testing entirely relies on the pre-scripted test which runs automatically to compare actual results with the expected results. This helps the tester to determine whether or not an application performs as expected. Automation testing helps to reduce the effort of the regression test suite execution of manual testers.

         Everyone is familiar with Selenium test automation for Web application and the test automation framework has the capability to generate the reports in different formats like HTML, PDF. Also, the frameworks will generate a screenshot of the UI when a test fails that depends on the configuration in the Automation Listeners. In this article I would like to share the concept of video record your automation flows; even if the test case pass or fail or skip that again depends on your configuration in the Automation Listeners.

Who will help you to record video?

         Selenium has no built-in capability to record the video of the automation flow. Here I am recording the Selenium automation flow with the help of Monte Screen Recorder Java library. The Monte media library used for processing media data. Supported media formats include still images, video, audio, and meta-data. You can record your entire automation flows for future references to share the flow as a demo to your client

Why do we need a video recording?

Video recordings of Selenium test case execution can play a major role. Not only would these help in debugging issues more efficiently, but we can also use recorded videos to show test execution activities to the client or other stakeholders. Additionally, these recorded videos can be added into the project management or defect management tool while creating bugs, which helps in understanding the bug clearly.

How can we achieve the video recording?

Pre-requisites:

  • Create a Maven project.
  • Add following dependencies in pom.xml file:
    • testng
    • selenium-java
    • selenium-server
    • monte-screen-recorder (you will get it from maven repository)
  • Write sample test cases in a test class.
  • Create VideoRecordingUtility class and extends ScreenRecorder class of Monte Recorder library.

       ScreenRecorder class records mouse clicks occurring on other Java Windows running in the same JVM. Mouse clicks occurring in other JVM’s and other processes are not recorded. This ability is useful for performing in JVM recordings of an application that is being tested. This recorder uses four threads. Three capture threads for screen, mouse cursor and audio, and one output thread for the movie writer. ScreenRecorder class is a powerful class with many useful methods, here I am using two important methods of ScreenRecorder class which is start and stop. start method helps to record the screen with a defined type (in this example the type is AVI). stop method helps to stop the screen recording. Here I have created two custom methods startRecording and stopRecording. startRecording method having an argument which included in the name of the video file. You can create an object of ScreenRecorder and call start and stop methods using that object.

Following are the actual logic implementation inside startRecording method:

public static void startRecording(String methodName) throws Exception {
File file = new File(“./AutomationVideoReports/”);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = screenSize.width;
int height = screenSize.height;
Rectangle captureSize = new Rectangle(0, 0, width, height);
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
screenRecorder = new VideoRecordingUtility(gc, captureSize,
new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),
new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE, DepthKey, 24, FrameRateKey,
Rational.valueOf(15), QualityKey, 1.0f, KeyFrameIntervalKey, 15 * 60),
new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, “black”, FrameRateKey, Rational.valueOf(30)),
null, file, methodName);
screenRecorder.start();
}

Following are the actual logic implementation inside stopRecording method:

public static void stopRecording() throws Exception {
screenRecorder.stop();
}

        The video recording will store in AutomationVideoReports folder. You can use startRecording and stopRecording methods based on your convenience in automation listener class, if you are using TestNG framework then you can implement ITestListener interface and use startRecording and stopRecording inside the implemented methods of ITestListener to record the video of entire test suite flow or record pass/fail/skip cases. Try to use the above logic to record your selenium automation flows and enjoy your automation.

make it perfect!

Selenium Automation using C# (MSTest)

downloadseleniumwithC

     One day, I got an opportunity to write selenium automation using C# language and MSTest framework. Prior to scripting, I started the configuration from the scratch to achieve my selenium scripting using C# and MSTest. Here I would like to share my experience with configuration and scripting part,

Steps for install and configure Visual Studio:

Step 1: Navigate to the URL https://www.visualstudio.com/downloads/ and Click on the ‘Free download’ button displayed on Visual Studio Community 2017 tab.
Step 2: Open the exe downloaded. Click on ‘Yes’ if asked for Admin Rights.
Step 3: A popup will appear. Click on ‘Continue’ button.
Step 4: In the next screen, select the check-boxes for

  • Universal Windows Platform development
  • .Net desktop development

Click on ‘Install.’ Wait for installation of each component to complete. Files are 16GB in size and will take time.
Step 5: A pop up will be displayed. Click on ‘Restart’ button (if required).
Step 6: Once the machine is restarted, search for “Visual Studio 2017” on the start menu and click on the search result. In the next screen, Click on “Not now, maybe later” link if you do not have an existing account.
Step 7: In the next screen,

  • Select color theme of your liking
  • Click the button “Start Visual Studio'”

Step 8: Visual Studio ‘Get Started’ screen will appear.

Set up Visual Studio with Selenium WebDriver:

Step 1: Navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution
Step 2: In the next window,

  1. Search for “Selenium”.
  2. Select the first search result “Selenium.WebDriver”
  3. Check the project checkbox
  4. Select the desired version.
  5. Click on ‘Install’.
  6. Select second search result “Selenium.Support”
  7. Check the project checkbox.
  8. Select the desired version.
  9. Click on ‘Install’.

Set up Visual Studio with MSTest Framework:

Step 1: Navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution
Step 2: In the next window,

  1. Search for “MSTest”
  2. Select the search result “MSTest.TestFramework”
  3. Check the project checkbox
  4. Select the desired version.
  5. Click Install.
  6. In the same window, select search result “MSTest.TestAdapter”
  7. Check the project checkbox.
  8. Select the desired version.
  9. Click on ‘Install’.

Create a new project in Visual Studio:

Step 1: In the File Menu, Click New > Project
Step 2: In the next screen,

  1. Select the option ‘Visual C#’
  2. Click on Console App (.Net Framework)
  3. Enter project name.
  4. Click OK

Step 3: You will be able to see the created project.

     Now the configurations and project is ready, next you can add one C# class file to project and start writing your first script for automation as below. I used this class file to start my C# scripting for selenium automation,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;

namespace seleniumTestProject
{
[TestClass]
public class SeleniumTest
{
public IWebDriver driver; //declare the driver object
[TestInitialize]
public void BeforeTest()
{
driver = new ChromeDriver(“path_to_chromedriver.exe”); //initialize the ChromeDriver instance
driver.Url = “https://www.google.co.in/”; //load application URL
}

[TestMethod]
public void GoogleSearchTest()
{
driver.FindElement(By.Id(“lst-ib”)).SendKeys(“Journey of Quality”);
}

[TestCleanup]
public void AfterTest()
{
driver.Close();
}
}
}

     Try the above configuration and scripting using C# for Selenium Automation from your end.

make it perfect !

How to fetch DRIVER_EXE_PROPERTY for different browsers dynamically?

1_6KbvW_GQYI9u6Cc_S2AHLQ@2x

   In case of Selenium Automation for Web application, most of the time people needs to set DRIVER_EXE_PROPERTY in the code level prior to driver instantiation. For that we need to download the respective DRIVER_EXE and set the path of the DRIVER_EXE in the code.

  Here my piece of code explain how to fetch DRIVER_EXE_PROPERTY automatically while script execution for different browsers. I have done it for chrome, Firefox and IE in Windows system as well as chrome and Firefox in MAC system. Following are the details:

  Below code is necessary to instantiate chrome driver session. In this code I used  getWebAutomationDriver(browserName) to get the DRIVER_EXE path from the system.

System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, getWebAutomationDriver(browserName));
ChromeDriverService chromeservice = new ChromeDriverService.Builder().build();
driver = new ChromeDriver(chromeservice); 

Following is the explanation for getWebAutomationDriver(browserName) method and there again we called  getActualDriverPath(browserName) as a private method to get the actual DRIVER_EXE path,

public static String getWebAutomationDriver(String browserName) throws InterruptedException {
String driverPath = null;
final String operatingSystem = System.getProperty(“os.name“);
try {
if (getActualDriverPath(browserName) == null) {
if (operatingSystem.contains(“Windows”)) {
if (browserName.equalsIgnoreCase(“chrome”)) {
System.out.println(
“chromedriver not installed on system, go to command-line and enter ‘npm install chromedriver’. \nAlso set PATH variable ‘C:\\Users\\…..\\node_modules\\chromedriver\\lib\\chromedriver’ in your system.\nOnce it done, you may need to restart your system”);
System.exit(0);
}
if (browserName.equalsIgnoreCase(“Firefox”)) {
System.out.println(
“geckodriver not installed on system, go to command-line and enter ‘npm install geckodriver’. \nAlso set PATH variable ‘C:\\Users\\…..\\node_modules\\geckodriver’ in your system.\nOnce it done, you may need to restart your system”);
System.exit(0);
}
if (browserName.equalsIgnoreCase(“IE”) || browserName.equalsIgnoreCase(“Internet Explorer”)
|| browserName.equalsIgnoreCase(“InternetExplorer”)) {
System.out.println(
“iedriver not installed on system, go to command-line and enter ‘npm i iedriver@3.7.0’. \nAlso set PATH variable ‘C:\\Users\\…..\\node_modules\\iedriver\\lib\\iedriver64’ in your system.\nOnce it done, you may need to restart your system”);
System.exit(0);
}
} else {
if (browserName.equalsIgnoreCase(“chrome”)) {
System.out.println(
“chromedriver not installed on MAC, go to terminal and enter ‘brew install chromedriver’. \nAlso set PATH variable in Run Configurations of your project. \nSteps: Right click on your project > Run As > Run Configurations > Environment tab”);
System.exit(0);
}
if (browserName.equalsIgnoreCase(“Firefox”)) {
System.out.println(
“geckodriver not installed on MAC, go to terminal and enter ‘brew install geckodriver’. \nAlso set PATH variable in Run Configurations of your project. \nSteps: Right click on your project > Run As > Run Configurations > Environment tab”);
System.exit(0);
}
}
} else {
driverPath = getActualDriverPath(browserName);
}
} catch (Exception e) {
e.printStackTrace();
}
return driverPath;
}

    Following is the explanation for getActualDriverPath(browserName) to fetch the actual DRIVER_EXE path,

private static String getActualDriverPath(String browserName) {
String actualDriverPath = null;
try {
String command = null;
final String operatingSystem = System.getProperty(“os.name“);
if (operatingSystem.contains(“Windows”)) {
if (browserName.equalsIgnoreCase(“chrome”)) {
command = “where ” + “chromedriver”;
}
if (browserName.equalsIgnoreCase(“Firefox”)) {
command = “where ” + “geckodriver”;
}
if (browserName.equalsIgnoreCase(“IE”) || browserName.equalsIgnoreCase(“Internet Explorer”)
|| browserName.equalsIgnoreCase(“InternetExplorer”)) {
command = “where ” + “IEDriverServer”;
}
} else {
if (browserName.equalsIgnoreCase(“chrome”)) {
command = “which ” + “chromedriver”;
}
if (browserName.equalsIgnoreCase(“Firefox”)) {
command = “which ” + “geckodriver”;
}
}
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = “”;
while ((line = reader.readLine()) != null) {
actualDriverPath = line;
break;
}
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
return actualDriverPath;
}

   Try to use above methods to get the DRIVER_EXE path automatically into your automation script.

make it perfect !

Automation for Windows Desktop Applications

AAEAAQAAAAAAAAuhAAAAJDg0MTllY2JlLWJlYjUtNDllOC05M2NmLWMxNzkxMzczYjU2YQ

      There are lots of different automation tools and frameworks are available for windows applications like – Sikuli, AutoIt, Winium etc. I have gone through all of them for desktop application (windows) automation for testing. All of them have different pros and cons.

        Among all of them I found Winium the most easy and handy automation framework for desktop application. Winium is Selenium Remote WebDriver implementation for automated testing of Windows application based on WinFroms and WPF platforms. I have done a POC with Winium. Following are the details:

Prerequisites:

  • Install Microsoft .NET Framework 4.5.1
  • Create Maven Project and add following dependencies in pom.xml file
    • selenium-java
    • selenium-server
    • winium-elements-desktop
    • winium-webdriver

Here I identified notepad.exe for automation.

How can we create a Winium Driver session?

WebDriver driver = null;
String notepadApplicationPath = “C:\\Windows\\System32\\notepad.exe”;
String winiumDriverPath = “D:\\SeleniumDrivers\\Winium.Desktop.Driver.exe”;// To stop winium desktop driver before start another session
Process process = Runtime.getRuntime().exec(“taskkill /F /IM Winium.Desktop.Driver.exe”);
process.waitFor();
process.destroy();
DesktopOptions options = new DesktopOptions(); // Initiate Winium Desktop Options
options.setApplicationPath(notepadApplicationPath); // Set notepad application path
WiniumDriverService service = new WiniumDriverService.Builder().usingDriverExecutable(new File(winiumDriverPath)).usingPort(9999).withVerbose(true).withSilent(false).buildDesktopService();
service.start(); // Build and Start a Winium Driver service
Thread.sleep(5000);
driver = new WiniumDriver(service, options); // Start a winium driver
Thread.sleep(10000);

Once you get the driver you can start your automation scripts like selenium scripting,

Thread.sleep(5000);
driver.findElement(By.name(“Format”)).click();
Thread.sleep(1000);
driver.findElement(By.name(“Font…”)).click();
Thread.sleep(1000);
driver.findElement(By.name(“Bold”)).click();
Thread.sleep(1000);
driver.findElement(By.name(“OK”)).click();
Thread.sleep(1000);
driver.findElement(By.className(“Edit”)).sendKeys(“Welcome to Winium”);
Thread.sleep(1000);
driver.findElement(By.name(“File”)).click();
Thread.sleep(1000);
driver.findElement(By.name(“Save”)).click();
Thread.sleep(1000);
driver.findElement(By.name(“File name:”)).sendKeys(“NewFile”);
Thread.sleep(1000);
driver.findElement(By.name(“Save”)).click();
Thread.sleep(1000);
driver.findElement(By.name(“Close”)).click();

NOTE: 

Process process = Runtime.getRuntime().exec(“taskkill /F /IM Winium.Desktop.Driver.exe”);
process.waitFor();
process.destroy();

make it perfect !

Selenium – Sikuli

IntegrateSikuliWithSelenium

Automate anything you see using Sikuli (an interesting GUI automation tool). As said Sikuli automates anything you see on-screen using the image recognition method to identify GUI elements on the screen.

Most of the automation testing tools will not support flash object automation (E.g. Selenium). Sikuli provides extensive support to automate flash objects. And also Sikuli provides support to automate desktop applications.

Selenium-Sikuli combination provides more support for the automation engineers. Most of the time in automation for web application, we may face to identify the elements from the web UI or the locators values are getting wrong. In such situation Sikuli comes in picture, Sikuli allows to automate GUI interaction by using images of elements instead of using the xpath, id, linktext, classes etc.,

Important steps to proceed

  1. Create a Maven project in Eclipse.
  2. Add following dependencies in pom.xml file:
    1. selenium-server
    2. selenium-java
    3. sikulixapi
    4. testng
  3. Create TestNG classes.
  4. Create WebDriver object to start driver session and load website.
  5. Create a folder inside src/main/resources and store the images of web elements inside that folder.
  6. Add the sikuli scripts to perform operations on the elements (like click, type, wait, doubleClick).
  7. Create a testng.xml file for the created TestNG class and execute testng.xml.
  8. Observe the results on executions.

Below is the sample Selenium-Sikuli Maven project structure:

Capturesefsfsf

Common Sikuli Actions

Create an object for Screen class, say Screen s = new Screen(); and perform various actions:

  1. click :  s.click(<path to image>); – helps to click on web element using its image.
  2. rightClick : s.rightClick(<path to image>); – helps to right-click on web element using its image.
  3. doubleClick : s.doubleClick(<path to image>); – helps to double-click on web element that displaying in the view.
  4. find : s.find(<path to image>); –  helps to locate a web element using the image of particular web objects.
  5. exists : s.exists(<path to image>); – helps to check the web element is present on the view.
  6. type : s.type(<path to image>, <input value to edit-box>); – helps to enter value to an input field.
  7. hover : s.hover(<path to image>); – helps to mouse hover a web element in the web page.
  8. wait : s.wait(<path to image>); – helps to wait for a web element on the page until it get displayed. There another method for wait is with timeout value, it looks like s.wait(<path to image>, <timeout in seconds>);
  9. dragDrop : s.dragDrop(<source image path>, <target image path>); – helps to drag an object(source image object) from one location and drop that object over other object (target image object) at target location.

Click here to get sample Selenium – Sikuli POC project and explore more. If you have any difficulty to get the POC project, please feel free to comment here.