Where we learn technology

Day: 2 May 2020

.gitingore file for Java projects

Different IDE will create extra files which we really don’t want to push to Git Repo at remote side. So using the .gitignore file in the root folder of your Git repository will ignore files and patterns you have mentioned. 

I have created the git ignore list of famous Java editors like Eclipse, IntelliJ, NetBeans and Visual Studio Code.

##############################
## Java
##############################
.mtj.tmp/
*.class
*.jar
*.war
*.ear
*.nar
hs_err_pid*
##############################
## Maven
##############################
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
pom.xml.bak
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
.mvn/wrapper/maven-wrapper.jar
##############################
## Gradle
##############################
bin/
build/
.gradle
.gradletasknamecache
gradle-app.setting
!gradle-wrapper.jar
##############################
## IntelliJ
##############################
out/
.idea/
.idea_modules/
*.iml
*.ipr
*.iws
##############################
## Eclipse
##############################
.settings/
bin/
tmp/
.metadata
.classpath
.project
*.tmp
*.bak
*.swp
*~.nib
local.properties
.loadpath
.factorypath
##############################
## NetBeans
##############################
nbproject/private/
build/
nbbuild/
dist/
nbdist/
nbactions.xml
nb-configuration.xml
##############################
## Visual Studio Code
##############################
.vscode/
##############################
## OS X
##############################
.DS_Store

Please comment below, if you want to have more git ignore files extensions. You can also share with other projects based out of JavaScript, NodeJS, Python, .Net etc…

References:

dedunu.info

Cheers!!

Naveen AutomationLabs

Difference between ImplicitlyWait, ExplicitWait and FluentWait in Selenium WebDriver

1.Overview

In this article, we’ll look at the most fundamental mechanism in selenium – synchronisation(wait).

2. Synchronisation in Selenium

  • Synchronisation helps the user to troubleshoot issues when launching or navigating to different web pages while executing the selenium scripts.
  • When the entire web page gets refreshed or elements are getting re-loaded there should be synchronisation between the selenium scripts, script execution speed and web application speed.
  • At times, there can be a lot of Ajax components or some images and when we want to interact with these elements it may not visible. Thus, a time fall back can be seen in such cases and we get an exception as “ElementNotVisibleException“.
  • Selenium doesn’t provide any default synchronisation but it provides synchronisation in the form of different types of waits which we will see below.

3. Different Types of waits in Selenium WebDriver

  • Implicit Wait
  • Explicit Wait
  • Fluent Wait

These waits are dynamic waits. To understand the statement let’s consider a situation when you have given a TimeOut value of 20 seconds. If the element is loaded in 5 seconds, then rest 15 seconds will be ignored.

Let’s have a look at each one of these commands:

  1. Implicit Wait

As per Selenium Documentation, An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

  • Implicit wait waits for a certain time till page gets loaded. After setting a particular time web driver will wait for that time before throwing an exception “No Such Element Exception“.
  • Implicitly wait is applied globally, which means it is always available for all the web elements throughout the driver instance.
  • Syntax: driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  • Implicitly accepts two parameters the first parameter time: 10 given as timeout wait and other is TimeUnit can be given in seconds, minutes, hours days just put dot key after TimeUnit, we can see all the options available.

Implicit Wait
 

So do I need to use Implicitly Wait? Answer is really NO..

Dis-advantages of Implicitly Wait:

  • undocumented and practically undefined behaviour.
  • runs in the remote part of selenium (the part controlling the browser).
  • only works on find element(s) methods.
  • returns either element found or (after timeout) not found.
  • if checking for absence of element must always wait until timeout.
  • cannot be customised other than global timeout.

This list is gathered from observations and reading bug reports and cursory reading of selenium source code.

Let me tell you one thing : <Always use explicit wait. Forget that implicit wait exists>                                              --Naveen Khunteta

2. Explicit Wait

Explicit wait is of two types:

a) WebDriverWait (Class) : 

b) FluentWait (Class)

Both are classes and implements Wait interface.

WebDriverWait class is an extension of FluentWait class. It doesn’t have its own methods.

  • Explicit wait waits for a certain condition till specific element is not loaded.
  • Its implementation is given by WebDriverWait Class in selenium with some expected conditions.
  • This can be useful when certain elements on the webpage are not available immediately and need some time to load for e.g when you click on some submit button after you fill some registration form, then it takes some time in processing and displaying the data on UI.
  • Selenium has its predefined conditions provided in ExpectedConditions class.
  • Below is the syntax to define explicit wait and the expected conditions to be selected based on our needs:

Expected Conditions

So do I need to use Explicit Wait? Answer is YESSSS..

  • documented and defined behaviour.
  • runs in the local part of selenium (in the language of your code).
  • works on any condition you can think of.
  • returns either success or timeout error.
  • can define absence of element as success condition.
  • can customise delay between retries and exceptions to ignore.

Fluent Wait:

As per Official Selenium API Documentation, FluentWait is:

An implementation of the Wait interface that may have its timeout and polling interval configured on the fly.

Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.

  • FluentWait is used when we can define the maximum time to wait for a condition, It also defines the frequency with which WebDriver will check if the condition appears before throwing the “ElementNotVisibleException”.
  • We can configure the wait to ignore specific types of exceptions while waiting, such as NoSuchElementException when searching for an element on the page.
  • The fluent wait is a class and an implementation of Wait interface and also parent class of WebDriverWait.
  • We can customise the below apply method to give any conditions based on our specifications.

Syntax:

Let’s below code snippet :

Code for Fluent Wait

package com.example.automation;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.*;
import java.time.Duration;
import java.util.function.Function;

/**
 * @author Mandeep Kaur
 * @Date 2 May,2020
 */
public class SeleniumConfig {
    public static void main(String[] args) {
        String path = System.getProperty("user.dir");
        System.setProperty("webdriver.chrome.silentOutput", "true");
        System.setProperty("webdriver.chrome.driver", path + "/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.facebook.com/");
        // Create object of WebDriverWait class

        Wait wait = new FluentWait(driver)
                //Wait for the condition
                .withTimeout(Duration.ofSeconds(10))
                //checking for its presenceonce every 5 seconds.
                .pollingEvery(Duration.ofSeconds(5))
                //Which will ignore the Exception
                .ignoring(Exception.class);

        WebElement element = wait.until(new Function<WebDriver, WebElement>() {
            @Override
            public WebElement apply(WebDriver driver) {
                return driver.findElement(By.name("lastname"));

            }
        });
        element.sendKeys("Martin");
    }
}

Explanation:

To put it simply, Fluent Wait looks for a web element repeatedly at regular intervals until timeout happens or until the object is found.

  • The above code defines time out value as 10 seconds and polling frequency as 5 seconds that means for every 5 seconds it keeps on checking for element.
  • It directs WebDriver to wait for a maximum of 10 seconds to verify a specific condition. If the condition occurs during those 10 seconds, it will perform the next step in the test script. If not, it will throw an “ElementNotVisibleException”.

So when should I use FluentWait?

  • When you do not see suitable expected wait condition in explicit wait.
  • To handle dynamic AJAX web elements with polling mechansim
  • You need to do more than just waiting along with Polling Mechanism, IgnoredException and when you want to create your own custom wait condition (in apply method) for non WebDriver use cases as well.
So can I use FluentWait features like, polling interval, ignoreAll with WebDriverWait? 
Ans
: Yes, of course you can do that, as I have explained earlier WebDriverWait is child class of FluentWait, so it has access on all parent class public methods.

Refer this WebDriver API on GIT:

https://github.com/SeleniumHQ/selenium/blob/master/java/client/src/org/openqa/selenium/support/ui/FluentWait.java

Final Conclusion:

a. Wait is an Interface in Selenium and having only one method declaration:

public interface Wait {

until(Function<? super F, T> isTrue);

}

b. FluentWait is a class which is implementing Wait Interface, it’s having its own methods shown above and overridden until() method from the wait Interface. 

public class FluentWait implements Wait<T> { }

c. WebDriverWait is extending FluentWait class but has no methods init except one overridden method, that is: timeoutException(){}.

WebDriverWait can use all the methods of FluentWait class – pollingEvery(), withMessage(), ignoreAll etc..

FluentWait can be used for both WebDriver and non WebDriver use cases. It just needs a condition – waitForCondition.

3. Concept of Thread.sleep()

  • It is a static wait and execution of the scripts will be on hold till specified time configured in the function.
  • Thread is a class in JAVA and sleep is static method.
  • sleep() methods accept duration in milliseconds. ( 1 s= 1000 ms).
  • It throws  IllegalArgumentException – if the value of ms is negative.
  • sleep() throws a checked exception which we must either throw or handle it using try catch like done below
  • Syntax:

try{
Thread.sleep(5000);
}
catch(InterruptedException e){
}

Note: it’s never a good idea to use thread.sleep () as unlike dynamic waits it will wait for the entire time configured in the function till the element gets loaded.

4. PageLoadTimeOut & SetScriptTimeOut property

PageLoadTimeOut

  • PageLoadTimeOut is focused on the time a webpage needs to be loaded – the page load timeout limits the time that the script allows for a web page to be displayed.
  • If the page loads within the time, then the script continues. If the page does not load within the timeout the script will be stopped by a TimeoutException.
  • The timeout is set at the driver level. After creating the driver instance with the appropriate driver capabilities.
  • Syntax :

   driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);

SetScriptTimeOut

  • From WebDriver documentation: setScriptTimeout(long time, java.util.concurrent.TimeUnit unit) sets the amount of time to wait for an asynchronous script to finish execution before throwing an error.
  • This works only for Async scripts (executeAsyncScript: calls which takes some time to respond back)
  • Syntax:

driver.manage().timeouts().setScriptTimeout(1, TimeUnit.SECONDS);

5. Conclusion:

In this article , we learnt about the various waits in selenium WebDriver.

Some References taken from:

 
Blog Contributors:
Author:  Mandeep Kaur
Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.
https://www.linkedin.com/in/mandeepkaur93
 
Reviewer: Naveen Khunteta 
https://www.linkedin.com/in/naveenkhunteta

8. Creating a Framework [Maven project] for Appium – II

What is a Framework and why we need for our Testing?

There are lots of description available for this question. If you ask me I will simply say a framework is nothing but a skeleton for any project.

Just imagine we are now going to automate a mobile app which consist of 15 activities (screens) and 500+ mobile elements. Having said that, in our Automation script

  • How we are going to manage these screens?
  • How and where you can save those mobile elements?
  • How can you easily manage all the dependent jars/binary files?
  • How can you easily manage the associated files like excel, logs and other reporting utilities?

Framework plays a major role here. It allows us to easily manage the code base, data files, Properties file, logs, Reports and everything. Because creating a script is very easy but managing those are the real challenge.

In our previous blog we have seen how to create a Maven project. Maven is also a framework, you can see the pre-defined folder structure (archType) in maven project. Having that in hand, now it’s time to set where to place what as per the best practices.

There are some types of framework available like Keyword driver, BDD, Hybrid and so on, in this tutorial we will focus on “Data Driven framework”.

I will always see framework creation in these 4 approaches,

  1. Configuration section: In this, we will configure all necessary reporting and dependencies.
    1. Maven POM file
    1. Log4J
    1. Extent Report
    1. Config.properties file
    1. Data Utility (Excel/ JSON/ XML)
  2. Implementation section:
    1. Creating a Base class and implementing drivers & initiating all files from “Configuration section”.
    1. Page Object Model for each screen/activity.
    1. Creating a reusable utility
  3. Test Case section:
    1. Creating test cases
    1. Implementing TestNG Listener on our test case class
    1. Creating TestNG XML with different parameters
  4. Execution section:
    1. Creating a .bat file for Maven command line execution

Simple right, this is all about framework guys. Going forward if anyone asks what is a framework? I hope, you can describe well.

Please find a sample image below to get an idea of how a typical framework looks like.

See, all the files are categorized and placed on its corresponding path/packages. This is framework and this is how we are going to create for our project. Along with that we will also focus on how OOPS logic’s are creating a magic here.

Importance of Configuration section:

There are must have in all project/framework, without all of these a project cannot be fulfilled like Reports, Logs, configuration file, getting input for a method from external sources, Maintaining the necessary files/Jars etc…    

What is Maven POM file?

A Project Object Model or POM is the fundamental unit of work in Maven.

It is an XML file that contains information about the project and configuration to build the project.

This XML file will have lot of tags, most importantly and frequently used tags are and ,  In tag we can specify the needed jar file details. For example,

//This dependency section is for "Log4J"

log4j
log4j
1.2.17


//This dependency section is for "Selenium client"

org.seleniumhq.selenium
selenium-java
3.141.49

Note: The tags , , and are must in a POM file. For our project values will be whatever we have given at the time of creating a Maven project.

While saving the POM file or while compiling the project, Maven will always look for the dependencies to make sure all Jars are available and those are matching with the configuration given under tag. If not, then it will automatically download the necessary Jars and installs it on our project dependency list.

So NO need to download and map them manually. This is an easy and most reliable way to maintain and keep our dependencies up-to date.

In case of any updated build received for any dependency, just a version # change on corresponding tag is all we need to do in POM file.

https://mvnrepository.com/ is the official site for downloading any maven dependencies. Search using the name of the jar we need and simply copy the dependency and paste it in POM file under parent tag.

We will see about tag at the time of configuring Maven.bat file in our future post in detail.

What is Log4J2?

Apache Log4J or Log4j2 (updated version) are used in project to create a log file. Logs are must to track and monitor the execution for current state and mainly for debugging purpose.

Consider, you are running our script in a remote machine, with the help of log files we can easily monitor the progress and errors or warnings if any. Please take a look at the below video to understand how to create a log file for our execution using Log4J.

What is Extent Report?

We all know about Extent report very well, It is one of quite famous reporting tools because it is HTML based, very light weight, elegance and easy to setup. It also allows to configure the report with lot of status for each test step.

What is Config.properties:

Config.properties file is used to store the configurable parameters of an application in the form of Key and Value pair. Main advantage of using this file is for changing configuration at any time since it is not a hardcoded value in our code. For example, we can save the proxy and Host details for Appium in this file instead of hardcoding it in our script.

https://www.youtube.com/watch?v=0XowYwfvbo8

What is DataUtility:

A common term to mention the data source. It can be an Excel sheet, a notepad file, JSON or an XML. Depends on the project need and data source we can write a utility class to fetch the data. For example if we need to fetch a data from excel and pass it to any text field, then we have to write a utility class to fetch the data from excel sheet. We can use ApachePOI or Fillo.

With all these, if we include our Base class, POM class and test class we are done with the Framework.

 

All set, it’s time to create a Mobile Testing Framework using Appium. 

 

As a first step of Framework creation process, We need to determine the dependencies in POM. Below API’s are needed for our framework

1.       Selenium Java client

2.       Appium Java client

3.       TestNG

4.       Fillo

5.       Log4j

6.       ExtentReport

7.       Apache POI

 

Please find below for the POM file with all dependencies for our project. 

 

—————————————————————————

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd”>
4.0.0

com.invoiceapp
invoiceapp-regression
0.0.1-SNAPSHOT

invoiceapp
Testing the invoiceapp using Appium





    org.seleniumhq.selenium
    selenium-java
    3.141.59




io.appium
java-client
7.0.0




org.testng
testng
6.14.3
test




com.codoid.products
fillo
1.18




log4j
log4j
1.2.17




com.aventstack
extentreports
4.0.9




org.apache.poi
poi-scratchpad
3.17

 

 

———————————————————————————–

I am excited, are you?

 

Cheers!

Naveen AutomationLabs

Blog Contributors:

Author:  Ragavendran

Ragav, having 10+ years of testing experience on which 7 years of rich experience in automation using UFT, Selenium (Java/Python). Expertise in Web and Mobile automation testing using Appium.

https://www.linkedin.com/in/Ragavendran-Ragav

Reviewer: Naveen Khunteta 

https://www.linkedin.com/in/naveenkhunteta