Friday 26 October 2018

How to use browser options to run in headless mode?

How to use browser options to run in headless mode?



First of all let us understand what is the meaning of headless mode. Headless mode is when you don't see browser GUI appearing but execution would go on in the back end. Where this would be useful?

1> When you want to only test the functionality of application and less care about GUI.
2> Also let's say there is huge data to be created using GUI and you don't want to see the browser GUI as it would be faster in headless mode.
3> You are running your tests in Jenkins CI machine where you don't want browser GUI to appear.


Chrome in headless mode: 

3.x version of Selenium allows using ChomeOptions class to pass headless options as given below:


ChromeOptions options = new ChromeOptions();
// option for headless mode
options.addArguments("--headless");

OR

options.setHeadless(true);

This options reference variable you will have to pass in ChromeDriver object like this:

WebDriver driver = new ChromeDriver(options);


Then, whatever code you have underneath, it will execute in backend and no longer open chrome browser GUI.

Firefox in headless mode: 


3.x version of Selenium allows using FirefoxOptions class to pass headless options as given below:


FirefoxOptions options = new FirefoxOptions ();
// option for headless mode
options.addArguments("--headless");

OR

options.setHeadless(true);

This options reference variable you will have to pass in FirefoxDriver object like this:

WebDriver driver = new FirefoxDriver (options);


Then, whatever code you have underneath, it will execute in backend and no longer open chrome browser GUI.

Internet Explorer in headless mode: 

Helium uses Selenium's InternetExplorerDriver to drive IE. Unfortunately Microsoft has not yet made IE11 fully compatible with this driver. So options like headless mode is not available in IE. It has to be run in GUI mode only. 




If you have any questions about this do write in comment below. 

Hope this blog has been useful to you. If yes do follow my blogs by entering your email by 
clicking on "Follow" (blue) button. 

You can as well explore my 

Youtube Channel: https://www.youtube.com/user/srinivaskinik

And 

facebook page: https://www.facebook.com/srinivaskinikalmady/

Thank you.

Thursday 25 October 2018

How to run Selenium scripts using batch file and schedule every day?

How to run Selenium scripts using batch file and schedule every day?


Generally we would like to have our automation suite to be scheduled so that it runs based on the scheduler settings. So I am assuming you will have TestNG suite (.xml) which you are planning to run. 

To achieve scheduling dividing tasks as below: 

1. Create batch file for the TestNG xml executed. 

We can create batch file with following content: 

set classpath=C:\Sel_WS\MySelenium\bin;C:\Srinivas Kini\Selenium_New\libs\*;C:\Srinivas Kini\Selenium Installers\eclipse-jee-mars-1-win32\eclipse\plugins\org.testng.eclipse_6.11.0.201703011520\lib\*;

java org.testng.TestNG TestNG.xml

pause


Here TestNG.xml is the TestNG suite we would like to execute. 



2. Add suite in OS scheduler. For windows, steps are given below: 

Open Task Scheduler from Start --> Programs

click on "Create Basic Task"


click Next and provide name to your task


Select Schedule interval and time and other parameters


Select "Start a Program" radio

Browse to the batch files path and select it


click on Finish. 


Now your program is scheduled to run :-). 

If you have any questions about this do write in comment below. 

Hope this blog has been useful to you. If yes do follow my blogs by entering your email by 
clicking on "Follow" (blue) button. 

You can as well explore my 

Youtube Channel: https://www.youtube.com/user/srinivaskinik

And 

facebook page: https://www.facebook.com/srinivaskinikalmady/

Thank you.











Friday 19 October 2018

How to attach screenshot image / link to Test NG report?

How to attach screenshot image / link to Test NG report?

First of all, let us know that Reporter.log() can be used to write additional text to Test NG HTML log file.

For eg: Reporter.log("msg");


To attach screenshot link to Test NG Report, simply we can define <a tag inside Reporter log
like this:

Reporter.log("<a href='" + new File(filePath+".png").getAbsolutePath() + "'>screenshot</a>");

Here, filePath is the exact path of file image to be attached.

This would be the sample output:


Note: It attached image hyperlink and when clicked on it, it would show the image. 


To attach directly image to Test NG report, we can define tag <img with src= file path as below: 

String path = "<img src=\"file://" + filePath2 + "\" alt=\"\"/>";
Reporter.log(path);

Here, filePath2 is the exact path of file image to be attached. 

This would be the sample output: 


Note: It attached image directly to Test NG report. 



if you have any questions about this do write in comment below. 

Hope this blog has been useful to you. If yes do follow my blogs by entering your email by 
clicking on "Follow" (blue) button. 

You can as well explore my 

Youtube Channel: https://www.youtube.com/user/srinivaskinik

And 

facebook page: https://www.facebook.com/srinivaskinikalmady/

Thank you.





Wednesday 17 October 2018

How to verify part of image in full image using Sikuli?

How to verify part of image in full image using Sikuli?



Let us assume in the application under test, we have a sub image / icon which needs to be verified for presence in main page. Here we want to verify image and not image attributes like src and so on. For verifying src attributes we can use getAttribute() method of Selenium and check whether it is containing expected value. 

To verify exact image presence we can use Sikuli tool. 

Sikuli is image recognition tool. Let us assume we have 2 file images. 

1. sub image / icon. 
2. main image

To use Sikuli, we need Sikuli libs imported in eclipse project. For eg: sikulixapi.1.1.3.jar (http://www.sikuli.org/)

(i) First we can define the Pattern ref object using Pattern class in Sikuli. 
String file_loc ="C:\\Images";
Pattern subImage= new Pattern(file_loc+"\\subImage2.PNG");

(ii) Using Finder class of Sikuli we can create object related to main image:

Finder finder = new Finder(ImageIO.read(new File(file_loc+"\\mainImage.png")));

(iii) And using find() method of Finder class we will know whether subimage is present in main image or not.

finder.find(subImage);

if(finder.hasNext())
{
System.out.println("Found the subImage");
}
else
{
System.out.println("Didnt Found the subImage");
}

Note: This similar logic can be used to compare 2 images whether they are equal or not.

Also, if your project requirement is to check whether 2 images are exactly equal.

Then you can use exact() at the pattern like this:

subImage.exact(); // which will verify for exact image presence in main image / other image. 

Similarly if your requirement is to check 70% image match or x percentage, then you can use similar(0.7f) or any floating value. For eg:

subImage.similar(0.7f); // will check for 70% match in main image / other image. 

if you have any questions about this do write in comment below. 

Hope this blog has been useful to you. If yes do follow my blogs by entering your email by 
clicking on "Follow" (blue) button. 

You can as well explore my 

Youtube Channel: https://www.youtube.com/user/srinivaskinik

And 

facebook page: https://www.facebook.com/srinivaskinikalmady/

Thank you.


Saturday 13 October 2018

How to get exact element screenshot captured in Selenium?

How to get exact element screenshot captured in Selenium?


In Selenium, we can capture full screenshot using TakesScreenshot Interface. 

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

screenshot will contain the full screenshot. We could copy that file to any location we want using FileUtils (Apache commons - https://commons.apache.org/). 

File destFile = new File("C:\\Images\\dest.png");
FileUtils.copyFile(screenshot, destFile);


Now to be able to capture exact element screenshot, we need to get dimension of element first. 

let us consider this is the element we have. 

WebElement ele = driver.findElement(By.id("hplogo"));

getLocation() will give us x and y coordinates of element. 
getWidth() and getHeight() will give us width and height of element rectangle respectively. 

// Get the location of element on the page
Point point = ele.getLocation();

// Get width and height of the element
int eleWidth = ele.getSize().getWidth();
int eleHeight = ele.getSize().getHeight();


To capture element screenshot, we need to get portion of image from full screenshot.

// Get entire page screenshot
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage  fullImg = ImageIO.read(screenshot);

Now, fullImg contains, full screenshot.

We can use getSubimage() method to get portion of it as given below:


// Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),
    eleWidth, eleHeight);
ImageIO.write(eleScreenshot, "png", screenshot);

// Copy the element screenshot to disk
File screenshotLocation = new File("C:\\Images\\Test.png");
FileUtils.copyFile(screenshot, screenshotLocation);


This way, we can capture exact element screenshot.

Very Imp Note: If you are working on OS like windows 10, where zoom level is 125% or something, you may not get exact screenshot of element due to zoom level set. So set zoom level to 100% which will give proper screenshot. 


if you have any questions about this do write in comment below. 

Hope this blog has been useful to you. If yes do follow my blogs by entering your email by 
clicking on "Follow" (blue) button. 

You can as well explore my 

Youtube Channel: https://www.youtube.com/user/srinivaskinik

And 

facebook page: https://www.facebook.com/srinivaskinikalmady/

Thank you.

Wednesday 10 October 2018

How to handle unexpected popup / alert in Selenium

How to handle unexpected popup / alert in Selenium?



Here, what I mean by unexpected popup / alert is you will see in some applications popups come unexpectedly and you can't expect the sequence of step when it will come in Application under test. So this is the challenge we have to handle that comes any time in the screen. 

We can handle unexpected popup / alerts using Selenium Listeners. Below steps can be followed. 

1. Create a class with any name for eg: WebListen.java implementing WebDriverEventListener (Interface)
2. Create method related to popupHandler / alertHandler in the same class that is created in (1 - WebListen.java ). 

public void checkAlert() {
    try {
        WebDriverWait wait = new WebDriverWait(driver, 2);
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        alert.accept();
    } catch (Exception e) {
        //exception handling
    e.printStackTrace();
    System.out.println("In alert hanlder");
    }
}

OR
public void checkPopup(WebDriver driver) {
    try {
        WebDriverWait wait = new WebDriverWait(driver,5);
        WebElement skip_link= driver.findElement(By.linkText("Skip"));
        wait.until(ExpectedConditions.elementToBeClickable(skip_link));
        skip_link.click();
    } catch (Exception e) {
        //exception handling
    System.out.println(e.getMessage());
    System.out.println("In popup hanlder");
    }
}

Depending on your project requirement / scenario based on the alert / popup object properties you have. 

Now call these methods in overridden methods wherever you think is applicable. 

For eg: afterChangeValueOf(), beforeChangeValueOf ()

as below: 

@Override
public void afterChangeValueOf(WebElement arg0, WebDriver arg1, CharSequence[] arg2) {
// TODO Auto-generated method stub
System.out.println("afterChangeValueOf");
checkPopup(driver);
}

@Override
public void beforeChangeValueOf(WebElement arg0, WebDriver arg1, CharSequence[] arg2) {
// TODO Auto-generated method stub
System.out.println("beforeChangeValueOf");
checkPopup(driver);
}
or any other method like beforeClick, beforeAlert and so on. 

What this means is beforeClick / beforeAlert or any other event is going to be occurred first you want to check whether alert or popup is there. If yes, you want to handle it and then move ahead. 


Now we need to use this listener in our test class. 

3. Use EventFiringWebDriver which is a class to register listener events. 

EventFiringWebDriver event1= new EventFiringWebDriver(driver);

// where driver is your driver instance. 

WebListen listen= new WebListen (event1);

// where WebListen is the class implementing WebDriverEventListener

event1.register(listen);

// use event1 ref variable going forward. 

event1.get("http://www.sample.demo.com");
event1.manage().window().maximize();
event1.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
event1.findElement(By.cssSelector("input[id = 'LoginForm_username']")).sendKeys("admin");
// here internally check for popup / alert will happen
event1.findElement(By.cssSelector("input[id = 'LoginForm_password']")).sendKeys("admin");
// here internally check for popup / alert will happen
event1.findElement(By.cssSelector("#Login > span.z-label")).click();

event1.unregister(listen);

This way your code will handle any popup / alert that is coming in AUT. 

if you have any questions about this do write in comment below. 

Hope this blog has been useful to you. If yes do follow my blogs by entering your email by 
clicking on "Follow" (blue) button. 

You can as well explore my 

Youtube Channel: https://www.youtube.com/user/srinivaskinik

And 

facebook page: https://www.facebook.com/srinivaskinikalmady/


Thank you. 

Sunday 7 October 2018

Using Verify statements instead of Assert in Test NG

Using Verify statements instead of Assert in Test NG


Often we see, when we use Assert statement of TestNG... if test fails it terminates there and starts new test.
If we have requirement to continue executing test even verification failed (marking overall result as failed), then we can use Verify statements.  It can be accomplished as follows. 

First create a Class - TestMethodErrorBuffer with following methods. 

Mainly to get, set and remove testErrorBuffer. 



// thread safe while running tests in parallel
    private static ThreadLocal<List<Throwable>> testErrorBuffer = 
new ThreadLocal<List<Throwable>>();
     
    static List<Throwable> get(){
        return testErrorBuffer.get();
    }
     
    static void set(List<Throwable> errorBuffer){
        testErrorBuffer.set(errorBuffer);
    }
     
    static void remove(){
        testErrorBuffer.remove();
    }

Secondly create a class called "Verify" - define all methods related to Verify. 
Note here: for every method for eg:- verifyTrue() we are internally calling Assert method 
inside try catch block and if there is a exception we are adding it to ErrorBuffer. 

import org.testng.Assert;

public class Verify {
 
    protected Verify() {
        // hide constructor
    }
 
    static public void verifyTrue(boolean condition, String message) {        
        try{
            Assert.assertTrue(condition, message);
        }catch(AssertionError e){
            addToErrorBuffer(e);
        }         
    }
 
    static public void verifyFalse(boolean condition, String message) {
        try{
            Assert.assertFalse(condition, message);
        }catch(AssertionError e){
            addToErrorBuffer(e);
        }
    }
 
    static public void verifyEquals(Object actual, Object expected, String message) {
        try{
            Assert.assertEquals(actual, expected, message);
        }catch(AssertionError e){
            addToErrorBuffer(e);
        }
    }
 
    public static void verifyNotSame(Object actual1, Object actual2, String message) {
        try{
            Assert.assertNotSame(actual1,actual2,message);
        }catch(AssertionError e){
            addToErrorBuffer(e);
        }
    }
    
    public static void verifySame(Object actual1, Object actual2, String message) {
        try{
            Assert.assertSame(actual1,actual2,message);
        }catch(AssertionError e){
            addToErrorBuffer(e);
        }
    }
    
    public static void verifyNotNull(Object object, String message) {
        try{
            Assert.assertNotNull(object,message);
        }catch(AssertionError e){
            addToErrorBuffer(e);
        }
    }
    
    public static void verifyNull(Object object,  String message) {
        try{
            Assert.assertNull(object,message);
        }catch(AssertionError e){
            addToErrorBuffer(e);
        }
    }
 
    
 
    private static void addToErrorBuffer(AssertionError e){   
 
        try{                
 
            VerificationError verificationError = new VerificationError(e.getMessage());
 
            verificationError.setStackTrace(e.getStackTrace());
 
            TestMethodErrorBuffer.get().add(verificationError);
 
        }catch(NullPointerException ex){
 
            throw new RuntimeException("Exception at " + TestMethodListener.class.getName() );
        }
 
    }
}

Thirdly create a class called TestMethodListener implements IInvokedMethodListener
Here, in beforeInvocation we are going to define new ErrorBuffer for every test method. 
in afterInvocation set result and append all the results obtained from verify failures. 


import java.util.ArrayList;
import java.util.List;
 
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
import org.testng.internal.Utils;
 
public class TestMethodListener implements IInvokedMethodListener{
 
    
    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
 
        if(method.isTestMethod()){  
             
            if(TestMethodErrorBuffer.get()!=null){
                throw new RuntimeException("Stale error buffer detected!");
            }
             
            TestMethodErrorBuffer.set(new ArrayList<Throwable>()); 
// each test method will have its own error buffer
        }
 
    }
 
   
    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
 
        if(method.isTestMethod()){
 
            List<Throwable> lThrowable = TestMethodErrorBuffer.get();
 
            /* if there are verification failures */
            if(lThrowable.size() > 0){
 
                /* set test result to failure */
                testResult.setStatus(ITestResult.FAILURE);
 
                /* if there is assertion error/exception then add it to throwable list */
                if(testResult.getThrowable() != null){
                    lThrowable.add(testResult.getThrowable());
                }
 
                int size = lThrowable.size();
 
                /* if there is only one throwable then set it directly to test result */
                if(size == 1){
                    testResult.setThrowable(lThrowable.get(0));
                }else{
 
                    StringBuffer failureMessage = new StringBuffer("Multiple failures (")
.append(size).append(")\n");
                    StringBuffer fullStack = new StringBuffer();
 
                    for(int i =0 ; i < size-1; i++){ 
                        failureMessage.append("(").append(i+1).append(")")
.append(lThrowable.get(i).getClass().getName()).append(":").append(lThrowable.get(i).
getMessage()).append("\n");                      
                        fullStack.append("Failure ").append(i+1).append(" of ").
append(size).append("\n");  
                        fullStack.append(Utils.stackTrace(lThrowable.get(i),false)[1]).
append("\n");
                    }
 
                    fullStack.append("Failure ").append(size).append(" of ").
append(size).append("\n");
                    Throwable last = lThrowable.get(size-1);                    
                    failureMessage.append("(").append(size).append(")").
append(last.getClass().getName()).append(":").append(last.getMessage()).append("\n\n");
                     
                    fullStack.append(last.toString());
 
                    testResult.setThrowable(new Throwable(failureMessage.toString() + 
fullStack.toString()));
                    testResult.getThrowable().setStackTrace(last.getStackTrace());
                }
 
            }
             
            TestMethodErrorBuffer.remove(); // remove stale
             
        }
    }
 
}

Finally create a class called VerificationError  which extends Error 


public class VerificationError extends Error{
 
    private static final long serialVersionUID = 8247563849457669512L;
 
    public VerificationError(String message){
        super(message);
    }
     
}


Now you can use TestMethodListener in Test NG class by providing @Listeners annotation 
or in Test NG XML

@Listeners(TestMethodListener.class)
public class TestNG {
 
 @Test
 public void test1()
 {
  Verify.verifyFalse(true, "msg1");
  
  Verify.verifyEquals("tes1", "test2", "test2 doesn't match"); 
 }
 
 @Test
 public void test2()
 {
  Verify.verifyFalse(true, "msg2");
  
  Verify.verifyEquals("tes3", "test4", "test4 doesn't match"); 
 }

}

This will be the sample output for above test class. 

FAILED: test1
java.lang.Throwable: Multiple failures (2)
(1)listeners.VerificationError:msg1 expected [false] but found [true]
(2)listeners.VerificationError:test2 doesn't match expected [test2] but found [tes1]

FAILED: test2
java.lang.Throwable: Multiple failures (2)
(1)listeners.VerificationError:msg2 expected [false] but found [true]
(2)listeners.VerificationError:test4 doesn't match expected [test4] but found [tes3]

Note in the output, even though one verification got failed from verify other verify statement also 
got executed unlike Assert. And finally result "failed" is set on Test method. 

Hope this blog has been useful to you. If yes do follow my blogs by entering your email by 
clicking on "Follow" (blue) button. 

You can as well explore my 

Youtube Channel: https://www.youtube.com/user/srinivaskinik

And 

facebook page: https://www.facebook.com/srinivaskinikalmady/




Thursday 4 October 2018

How to run 2 testNG xml suites in sequential mode or parallel mode using batch file


How to run 2 testNG xml suites in sequential mode or parallel mode using batch file?





Let us consider below to be the content of 2 Test NG xmls

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="mySuite1"  thread-count="3">
<test name = "myTest">
<classes>
<class name="testNG.Test1"/>
</classes>
</test>
</suite>



<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="mySuite2"  thread-count="3">
<test name = "myTest2">
<classes>
<class name="testNG.Test2"/>
</classes>
</test>
</suite>


To run these 2 xmls in sequence, we can write a batch file with below content: 

set classpath="Path of Test NG libs\*;
cd directory classpath of TestNG class files
java org.testng.TestNG  TestNG_Parallel.xml TestNG_Parallel2.xml


Note here command java org.testng.TestNG xml1 xml2 will run suites in sequence. 

classpath = Here you need to set path of all libs that you are using in project. 
cd  directory must point to the class files path. 


Here is the sample output: 

Thread ID ------------1
test1

===============================================
mySuite1
Total tests run: 1, Failures: 0, Skips: 0
===============================================

Thread ID ------------1
test2
Thread ID ------------1
test3

===============================================
mySuite2
Total tests run: 2, Failures: 0, Skips: 0
===============================================

Note the Thread ID same for all tests because same thread was used for execution (Sequential). 

Now to run 2 xml suites in parallel just add -suitethreadpoolsize 2 option. So batch file would like like this: 

set classpath="Path of Test NG libs\*;
cd directory classpath of TestNG class files
java org.testng.TestNG   -suitethreadpoolsize 2 TestNG_Parallel.xml TestNG_Parallel2.xml

Below is the sample output: 

Thread ID ------------9
Thread ID ------------8
test1
test2
Thread ID ------------9
test3

===============================================
mySuite2
Total tests run: 2, Failures: 0, Skips: 0
===============================================


===============================================
mySuite1
Total tests run: 1, Failures: 0, Skips: 0
===============================================


Note the Thread ID is different for some tests because execution happened in parallel ( 8 and 9 ). 


Hope this blog has been useful to you.

Youtube channel: https://www.youtube.com/user/srinivaskinik
Facebook page: https://www.facebook.com/srinivaskinikalmady/

How to schedule RFT (Rational Functional Tester) scripts to run using Jenkins / schedule

How to schedule RFT (Rational Functional Tester) scripts to run using Jenkins / schedule 1. Create a batch file with following content ...