Thursday, September 12, 2019

Selenium WebDriver Methods And Locators

Hi, As we all learned the Introduction to selenium WebDriver and Architecture of selenium WebDriver in previous blogs. Now we mainly concentrate on different types of selenium web driver methods and Locators.

Following are different selenium WebDriver methods used to perform the different actions on the web page.

  1. get().
  2. getCurrentUrl().
  3. findElement().
  4. findElements().
  5. getTitle().
  6. close().
  7. quit().
  8. naviagte().
  9. manage().
  10. swithTo().
  11. click().
  12. clear().

Now, We learn each method syntax and which action can be performed using these methods.

1. Method Name:- get().
    Syntax:- get(URL).
    Example:- driver.get("https://easylearn29.blogspot.com").
    Purpose:- This method used to load the web page in the browser window, this will be done using HTTP get method.
    Parameter:- Parameter should be a fully qualified URL.

2. Method Name:- getCurrentUrl().
    Syntax:- getCurrentUrl().
    Example:- driver.getCurrentUrl().
    Purpose:- This method used to fetch the current URL of the web page displayed in the browser window and the returned data will be in String data type.
    
3. Method Name:- getTitle().
    Syntax:- getTitle().
    Example:- driver.getTitle().
    Purpose:- This method used to fetch or retrieve the Title of the web page displayed in the browser window and the returned data will be in String data type.

4. Method Name:- findElements().
    Syntax:- findElements(By by).
    Example:- driver.findElements(By.xpath("//div[1]\div[0]").
    Purpose:- This method used to find all the web elements in the currently displayed web page and this method will return an Array of WebElement.
    Parameter:- We use different types of the locator to find the element, we will discuss the Locator section briefly in the later part of the blog.
    
5. Method Name:- findElement().
    Syntax:-WebElement findElement(By by).
    Example:- driver.findElement(By.xpath("//div[1]\div[0]").
    Purpose:- This method used to find the web element in the currently displayed web page and this method will return a data of  WebElement data type. 
    Parameter:- We use different types of locator to find the element.
    
NOTE: 
  • This will only fetch the first element it has matched the locator we have specified. Even though there are multiple elements matches.

6. Method Name:- close().
    Syntax:- void close().
    Example:- driver.close().
    Purpose:- This method used to close the current window displayed in the browser.

NOTE: 
  • If the multiple windows are opened in the browser, It will close only the one window which is currently displayed.  
  • If the single window is opened in the browser, It will act as quit() method.

7. Method Name:- quit().
    Syntax:- void quit().
    Example:- driver.quit().
    Purpose:- This method used to close all the window opened in the browser and close the browser. 
Interview Question:
1. What is the difference between close () and quit() method?
2. Give me anyone real-time example when we use quit() over close() and vice-versa?
8. Method Name:- navigate().
    Syntax:- Webdriver.Navigation naviagte().
    Example:- driver.navigate.to(URL).
    Purpose:- This method used to move in between the module of the web page.

9. Method Name:- manage().
    Syntax:- Webdriver.options manage().
    Example:- driver.manage().
    Purpose:- This method provides a set of the optional interface, Which will have sub-method to perform action window, browser, and a Web page which we will discuss in later chapters.

10. Method Name:- switchTo().
      Syntax:- swicthTo().     
      Example:- driver.switchTo(URL).
      Purpose:- This method used to switch between the frames of the window, it mostly used when we need to handle the Dialog box, Popup, Upload file window, etc

11. Method Name:- click().
      Syntax:-  WebElement.click().
      Purpose:- This method used to right-click on the web element which displayed in the window of the browser.

12. Method Name:- clear().
      Syntax:-  WebElement.clear().
      Purpose:- This method used to clear the data entered in the web element of the web page like text boxes.


All these methods are helpful to perform an action on webElement that are displayed on the web page.

To before using these method we need to find those web element for web page, we can find the web element using findElement() method, which needs locators to find the element. 


What are Locators?

             Locators are the commands which inform the selenium IDE on which web element the particular action should be performed.


Following are different types of locators used in Selenium. 

  1. Id.
  2. Name.
  3. Tag Name.
  4. Link Text.
  5. Partial Link Text.
  6. Xpath.


1. Id:-

             Id locator is most preferred and used locator to find the web element. 
             Id's are always unique for each web element in the selected web page.
             It is fast and safe among all locators.

 Syntax to use Id locator in findElement().

                  WebElement testElement = driver.findElement(By.id ("testId"));

We need to replace the testId by real Id of the element, Id for the element can be found by inspecting the web page.






2. Name:-

                  Name Locator is the name of the webElement
                  It is used when Id of the element not found and present
                  We can not rely on this locator more because some times Web page can have multiple elements which have same name.
                   In the above case, if we use the Name locator to find the element, the method will find the first element which matches the locator value.

Syntax to use Name locator in findElement().

                  WebElement testElement = driver.findElement(By.name("testName"));

We need to replace the testName by real name of the element, Name for the element can be found by inspecting the web page.







3. Tag Name:- 
                 
                       In this locator, we use the Tag name to find the element.
                       We can't rely on the Tag name as it also used multiple-element in web page.
                       As we all know there are different tags in the HTML and each element in web page should have any one of the tag
                        
Syntax to use Tag Name locator in findElement().

                  WebElement testElement = driver.findElement(By.tagName("testTagName"));

We need to replace the testTagName by real tag name of the element like "label", Tag name for the element can be found by inspecting the web page.


  




4. Link Text:- 

                         This locater can be used to identify the elements if it is a hyper link.
                         It works only for an element has a hyperlink  Ex: Social media links displayed at the bottom of every webpage.

Syntax to use Link Text locator in findElement().

                  WebElement testElement = driver.findElement(By.linkText("testLinkText"));

We need to replace the testLinkText with a real link text value.


5. Partial Link Text:-
               
          This is same as Link text locater but in this case, we can give link text value partial 
          It will find an element which has link text value mentioned in find element method
                          
Syntax to use Partial Link Text locator in findElement().

WebElement testElement = driver.findElement(By.partialLinkText("testPartialLinkText"));

We need to replace the testPartialLinkText with a real Partial link text value.



6. Xpath:-

                 Xpath Locator is least preferred and very complex locater among all locaters
                 To use this locator we need to drive the traverse path for the element in the web.                       It is very difficult to for a web page like Amazon, Facebook, etc
                 Xpath Locator is slow among all locators.
                 To find the XPath for the element we use the Plugins  "Fire Bug" and "Fire Path" and also in chrome, we have copy XPath option to copy XPath of the inspected element.
                           
Syntax to use Xpath locator in findElement().

                  WebElement testElement = driver.findElement(By.xPath("testXpath"));

We need to replace the testXpath with a real Xpath value.


   NOTE:  

  • We can give both Absolute and Relative path as Xpath.



In the next blog, We will learn the difference between Absolute and Relative path also Learn Handling Text box Web elements



Tuesday, July 23, 2019

REST Assured API Automation Setup and Understanding Basic


What is REST Assured?

REST assured is Java DSL  for simplifying testing of REST-based services built on top of HTTP builder, It supports POST, GET, PUT, DELETE, OPTIONS, PATCH, and HEAD requests and can be used to validate and verify the response of the request.


       1. Download the Java if you don’t have the java installed in your system using the following link. Java Download link

      2. Setup the environmental variable path in the system

      3. Download the eclipse from given link Eclipse Download
 
      4. Download REST assured jars from given link REST assured Jar links

      5. Setup Java Project in Eclipse and configure jars in the build path




Basic Program :-


package TestFramework;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

import org.testng.annotations.Test;



public class basics {

@Test
public void getPlaceAPI()
{
// TODO Auto-generated method stub

//BaseURL or Host
RestAssured.baseURI="https://maps.googleapis.com";

given().
       param("location","-33.8670522,151.1957362").
       param("radius","500").
       param("key","AIzaSyDIQgAh0B4p0SdyYkyW8tlG-y0yJMfss5Y").
       when().
       get("/maps/api/place/nearbysearch/json").
       then().assertThat().statusCode(200).and().contentType(ContentType.JSON).and().
       body("results[0].name",equalTo("Sydney")).and().
       body("results[0].place_id", equalTo("ChIJP3Sa8ziYEmsRUKgyFmh9AQM")).and().
       header("Server","pablo");

}

}

   
In the above example program,

We are using RestAssured.baseURI, RestAssured is the class which has the base URI ()  method, baseURI () method will accept a string, we need to pass the base part of API we need to automate in above example “https://maps.googleapis.com" is the base part of the API we are automating.

Before to analyze the remaining code of lines we need to know there are 4 blocks in API automation there are.

1. Given ()
2. When ()
3. Then ()
4. Extract ()



Given (): Given block is nothing but request head, as we discussed earlier different part of endpoint the request in that header, input parameters are sent and in Given block itself

            NOTE: All the parameters are sent in the Given block as Key and Value format, it may be POST or GET request, But the method used to pass parameters will be different will discuss in the next topic.

In the above example,

        We have Given () class which has the param () method, which accepts the value in Key and Value Format where both should be string data type.

        “Key”  value always will be the name of the Parameter input we are passing.
           
       “Value” value always will be the value we need to pass for that parameter input.

In the above basic program “Location” is an example for “Key” and  “-33.8670522,151.1957362”  is an example for “Value”.


When ():  When block always has the Resource part of the API request we are automating.
In the above example “/maps/api/place/nearbysearch/json” is resource, We call the get method to pass the resource API.


Then (): Then block is used to validate the response using assert () functions. This part of scripting is also called as validation

In the above basic program,
         
          We are validation response status, content type, name, place_ID, and server value is correct or wrong, If any one of the above is not matched with actual data we get any exception.
“java.lang.assertionerror”.  And test case will fail if any one of the assertions fails.

       NOTE: We can validate both “Body data” and “Header data”, just we have to call the respective method. Which are the body () and header ().


Extract (): Extract block always used to extract the response we got from the server, we can extract response writing below line code
Extract (). response ();

       NOTE: We can store response in Variable of the type response

        The response we get it will always be in raw format, so we need to convert the raw data to JSON or XML format based on the requirement. To follow the above scenarios  we have following steps

 
   We have to give a response in string format using the following line of code

                  String resstring = res.asstring();

   Where “res” is the variable name, In which we stored the response of extracted form extract method. asString () is a built-in method which will convert given data into the string format.
   
   Now, We have to convert the response which is in string format to the JSON format using the following line of code

            Jsonpath  js= new jsonpath (resstring);

    Where the JSON path is the inbuilt method which accepts the string value and converts the data into  JSON format and returns it back.

     Now our extracted data is converted to JSON format, We converted the data in JSON format because, If we want to integrate the two API request in one request where one API response value is input of another API in this scenario we need to extract the value which we need to pass as the response, We can’t do if the given response is String or Raw because we can’t traverse through response and fetch the value we need we can only do traverse if the data is in JSON format.

Now we will discuss about the different parameters we pass as input for an API request

There are 3 types of API request

   1.Path parameter
   2.Query parameter
   3.Header parameter

1. Path parameter: Parameter will be in request URL itself but these parameters will be separated by  “?” question mark symbol form API request link, these will be separated by forwarding slash (“/”)

           Ex: www.exaple.com/book/bookid.

To pass this type of parameter we can just use the prama () method.


2. Query parameter: Parameter will be in request URL but these parameters will be separated by “?” question mark symbol from API request link.

Ex: www.google.com/maps?place=0.2342

To pass this type of parameter we must use queryprama() method.

Header parameter:- Parameter will be in the header part of the API request,

  To pass this type of parameter we can just use prama () method.


NOTE: While calling POST API request, we need to be very clear sending the parameter. We have to use the respective parameter method to pass the parameter in the API.


Here, We discuss the REST API automation for POST request, the above example for GET request as it did not have a body part in the request

Here is sample code Automation code for POST API request,

package TestFramework;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import static org.hamcrest.Matchers.equalTo;

public class basics2 {


@Test
public void createPlaceAPI()
{
RestAssured.baseURI="https://maps.googleapis.com";
given().

queryParam("key","AIzaSyDIQgAh0B4p0SdyYkyW8tlG-y0yJMfss5Y").
body("{"+
  "\"location\": {"+
    "\"lat\": -33.8669710,"+
    "\"lng\": 151.1958750"+
  "},"+
  "\"accuracy\": 50,"+
  "\"name\": \"Google Shoes!\","+
  "\"phone_number\": \"(02) 9374 4000\","+
  "\"address\": \"48 Pirrama Road, Pyrmont, NSW 2009, Australia\","+
  "\"types\": [\"shoe_store\"],"+
  "\"website\": \"http://www.google.com.au/\","+
  "\"language\": \"en-AU\""+
"}").
when().
post("/maps/api/place/add/json").
then().assertThat().statusCode(200).and().contentType(ContentType.JSON).and().
body("status",equalTo("OK"));

// Create a place =response (place id)

// delete Place = (Request - Place id)


}
}


In the above Automation code and previously discussed automation code, there is the only difference is Body data of API we are passing in the request

Any POST API request always have the Body data to be passed, we pass the body data using the following method, body (String s); it is the inbuilt function which only accepts the String value as input parameter, In this case, we come across challenge How to pass the String which has the double quote as a parameter to a method which accepts the string as a parameter?  - Most commonly asked question in interviews.

We can handle the above scenario,

We need to add the forward-slash (/) in front of the double quote we have in a string value, it makes the java compiler to understand that double quote is a string value.


In the next blog, we will discuss the Optimization above-mentioned script with centralized data

                                                                                                       
                                                                                                               Thank you.

Thursday, July 11, 2019

REST Assured API Automation

 

  • Key points to know before testing  REST API 

1. How to send the Call to REST API?
2. What are Endpoints?
3. What are the types of REST request?
4. What is header/ Cookies?

  • End Points: Endpoints divided into the following parts

1.Base URL
2.Resource 
                 3.Parameters

1. Base URL: It is also known as host URL, The Website link itself is base URL.

Ex: https://www.google.com

2. Resource: It is mentioned after the Base URL in the link, which is the different module in the given host like
as above example in Google there are many modules, we have to write the module name
we want to hit.

Ex: https://www.google.com/maps,Here the “maps” is the resource we are using for Google or
we want to use the map module of the google website.

3. Parameters: These are the input values passed along the API call, To know what all parameters to be
passed for particular API, we need to go through the API doc they provided.
Every API we will have different parameters.  

Ex:  https://www.google.com/maps?place = ‘Bangalore’

In the above example we are passing the input parameter “Place“, 
it is one of the input to be passed according to the Google API Document 

NOTE: Parameters passed in two different ways, they are mentioned below

1. Parameters passed in the API URL itself.  
2. Parameters passed in the Body of the API. 

Above mentioned way depends upon the API request, we are calling to get the data 


There are 4 different types of REST API request can be used to communicate with Server,
they are mentioned below:


1.GET
2.POST
3.PUT
4.DELETE

Let's learn one by one,


1. GET: This type of request only used to retrieve or fetch the data from the Server.
It is more like asking a question or sending the query to the server, Once the server get the
GET request it analyses the request and sends the data in JSON or XML format.

In GET request, Input parameters passed in the API URL itself.


2. POST: This type of request used to add or create the data in the server, If the user wants to add the data to
existing server DB, he needs to call  POST request, When the server gets POST request it analyses
the request and create or add the data accordingly in the server DB and sends the
Response to the user in XML or JSON format.


In POST request, Input parameters passed in the Body of XML or JSON request,
nothing but passing the parameters in the body of the request.


NOTE: If we pass the required parameters wrongly, then the server will return the error message,
to get the correct response we need to pass the right parameters.


3. PUT: This type of request used to update the data already present in the server DB, It is also known as
a subset of POST request because If we can use the POST request itself to update the data in the
server DB, Hence In IT industry most companies only use the GET and POST
methods to communicate with the server.



In PUT request also we need to send the input parameters should be passed in the body of the API request.



4. DELETE: This type of request used to delete the data already present in the server DB,
it is also a subset of POST request as I have already told POST request is used to create,
update and delete the data from the server DB.

In DELETE request also we need to send the input parameters should be passed
in the body of the API request.


Headers: It is another part of the API request, headers are mainly used to Authentication and define
the content type we need to get the data.


Content-type: As mentioned above points the data will be received in XML or JSON format.

Hence there are two types of the format we can get data
1. XML
2. JSON

To make sure we want the data in the format we need it will be decided in the header of the API request,
in the header we mention the content type, the format which we need the response from the server 

Ex: Content type = JSON

In the above example, If we send the API request to the server, the server will first analyze the header of
the request first because header always has the major part of the request which is Authentication, once
it sees the content type has value JSON, Sever will understand that data it will send the response in
JSON format.


Authentication: This will always be part of request header, It plays an important role in API request,
As server will only process the request and send the data once the response is sent,
the system will keep track of the user recent query and verify the user.
the user who is accessing data is valid or intruder for that application
To prevent all this API request use the Authentication in the header of the request 

As Server receives the API request, It will authenticate the API request is form valid user or not,

We can use the  following way to authenticate 

1.Basic Authentication.
2.Digest Authentication.
3.OAuthentication 1.0
4.OAuthentication 2.0
5.Hawk Authentication
6.AWS signature

For currently, we are learning the only Authentication using the Header which is an easy way to do,
In our case, the API should have sent with X-token which is the randomly generated the token and
present in the server DB and also linked with one user.


We need the following scenario to explain the above point
  • Consider a User login into the Website we hosted, To login, Our Web app will call the Login API which needs two parameters
1. User name
2. Password and
3. UserID.

  • Once the Login API called the user is searched in Server DB and identify the User and validate the Username and Password sent by the Web app matches with the Username and Password linked with that userID
  • Once the Username and Password are matched, Server will create the hexadecimal token we called it as X-token or key, which always will be unique for every user when they log in every time they log in to the system and old x-token or key will be deleted automatically once they logged out or expire once the specified time period is over.
  • The above X-token is sent as the response for Login API and x-token get stored in the web browser as the Cookie which will store all session data in local memory for the web browser. 
  • Every time user make any request the API response will have the X-token in the player header, through x-token server identify the User is the valid user or not and also identify and remember the previous query the user had made to the server 
We can do the manual testing of REST API using the following API tools, 

1.Postman
2.Jmeter
3.SoapUI   
4.Katalon 


There are many tools available for manual testing one of the most popular and commonly used tool across
the industry is Postman. 


In the next blog,
We will discuss What is REST assured? and How to setup REST assured in the system?

                                                                                                                                     Thank you.




Saturday, April 6, 2019

Architecture of Selenium WebDriver

Hi, welcome back to Easy Learn


Today, We will learn about the architecture of selenium web-driver, It is nothing but learning how our selenium works internally.



  • Selenium language bindings:-  It is the language supported by the selenium, Test scripts are written in using these programming languages, The most common and popular used are Java and Python for automation scripting.

  • Web drivers:-  Web drivers are the web automation frameworks, which will allow the user to execute the automation scripts against the browsers.

  • Web browser:- Web browser is a software application for accessing the information on the World Wide Web but commonly known as a browser.


  • JSON Wire Protocol:-  Our Selenium Web driver will JSON (JavaScript Object Notation) Wire Protocol is used to write an read the data on web, JSON wire protocol is widely used in World Wide Web , As it support  Most common and popular used data structure like object and Array, Also It is easy to read and write data from JSON, and JSON serves the REST Web services   


To Understand flow We need to write some sample script, Assuming as you all installed the Selenium web driver in your personal laptop,  if your not installed please follow the previous blog for instruction Introduction to selenium


We are writing the Sample Selenium Script which will Open the Google chrome browser, Go to Easy learn page  and Close the browser.


package testscripts;

import org.openqa.selenium.chrome.ChromeDriver;

public class DemoEasy {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
//Above line will set the path of web driver 
ChromeDriver driver = new ChromeDriver();
//Creating the object for chrome driver
driver.get("https://easylearn29.blogspot.com");
//To open the 
System.out.println("Easy learn 29 website is opened");
//To print output
driver.close();
// Close the webdriver  
}
}



When above code is compiled, Compiler will find the path of WebDriver in the system because 
the WebDriver  are the like instructor to the browser and Our code is like instruction menu, 

The path is set by using the Set property, Remember if you provide the path value wrong or set property code line is not written, Compiler throw the "java.lang.illegalstateexception


Once path has been successfully set, Compiler will be create the object reference for Chrome driver, Using that object reference we can call and utilize the method in the Chrome driver class. 

Here we are only using get () method there are many methods used commonly will be disscussed in future blogs

What is get () method?

Above method only accept the String data and return type is void, it will try to load the string data that has passed in chrome browser 

NOTE: You can load the web page even using navigate () method


Next line of code will print the output in the console like printf in C program, at last Close () is the method it will exit WebDriver and clear driver instance data.


Here is an assignment, Write the script to load the Google page and Close the browser in Firefox browser 

Hint: You may need geekodriver instance to load the page in Fire Fox browser


In the next blog, We will discuss about the different types of Web Driver method and different type of locators