How to perform Cookies testing with Selenium WebDriver?

You visit some sites most often. After your first login to that site, it directly leads you to the account page which means you are already logged in and it didn’t ask you to login again. You are remain logged in and it happens with the help of Cookies of that site which stored in your browser after the first login. Today we are going to discuss Cookies testing with Selenium WebDriver. In our agenda, we will discuss addition, deletion, cookie data retrieve and some other operations on web cookies through Selenium automation testing.

Recommended Article:

What is a Cookie?

A cookie is a text file which contains personalized user information that is stored in the user’s system through the web host. This information is given back to the server as a backend response when the browser requests a new page.

In a simple manner, cookies help to reduce the time gap between client and host and it quickly provides the information to the browser. Hence, cookies store personal information like user name and password, web page details, navigation details, etc. These cookies are mainly used in e-commerce portal, Shopping cart portal, gathering of heat map data, Retargeting and Marketing, User session recording and handling, etc.

Types of Cookies

Cookies mainly consist of two types, which are listed as follows:

  • Session Cookies: When we open a browser that is counted as one session, hence, Session cookies are available until the user opened the browser. Post browser closer, it expires.
  • Persistent Cookies: When cookies last for a lifetime or longer period of time then it is called, Persistent cookies.

What are the cookie’s contents we can retrieve with Selenium?

Selenium WebDriver helps us to get following information about the cookies, these information are helpful in Cookies testing with Selenium WebDriver:

  • It returns a list of all the cookies
  • Selenium returns a particular cookie by its name
  • We add cookies with Selenium
  • Selenium cookies handling helps to delete the specific cookie by its name and other identification.
  • It also supports the deletion of all the cookies at a time
  • We retrieve name, value, domain name, path and expiry date of the cookie with Selenium

Where are Cookies stored in our System?

We can navigate to the path of the cookies. Different browsers have a different path. Just, for example, Open settings of your Chrome browser and type cookie. Searches related to Cookies will appear then click on Cookies then click on See all cookies and site data. You see a list of all the cookies and details related to them. See image below.

Selenium Cookies Testing

Why do we need to perform cookies testing?

A cookie contains the name, value, domain name, path, creation date, expiry date, and Secure socket check. A server needs to parse these values to validate the client. Cookies testing with Selenium mainly involves the creation, update, and deletion of cookies.

Cookies reduce time and steps while performing automation testing. For example, we have to perform end to end testing of the shopping activity at e-commerce portal. Suppose every page requires a login so we can add cookies for login action so each time we don’t need to pass the user name and password, Cookies will handle this action. Cookies directly manage some part of the browser and server session.

What are Cookies testing commands in Selenium?

In order to perform cookies testing in Selenium, we have some methods as commands already written in Selenium library. We just need to call them and use them as required.

  • manage().addCookie(arg);
  • manage().getCookies(arg);
  • manage().getCookieNamed(arg);
  • manage().deleteCookie(arg);
  • manage().deleteCookieNamed(arg);
  • manage().deleteAllCookies();

Selenium stores Cookie data in key value pair.

A scenario of Cookies testing with Selenium WebDriver

First, we will store login details in a cookie file and further that cookie file will be used for the next level of testing. Then, in the Second test scenario, we will retrieve the cookie’s data and use such data to login into the application.

How to store cookie information using Selenium WebDriver

Following sample code let you store cookie information to your project.

package Test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class StoreCookieDemo {

	public static void main(String[] args) throws InterruptedException {
		System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver.exe");
		 
		WebDriver  driver  = new ChromeDriver();
		
		 driver.get("http://www.memotome.com/login.asp?display=reminder");
	  	  
	  	  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		  
	  	  driver.manage().window().maximize();
	  	  
	  	  driver.findElement(By.name("LoginName")).sendKeys("testselenium");
	  	  
	  	  Thread.sleep(1000);
	  	  
	  	 driver.findElement(By.name("Password")).sendKeys("test@123");
	  	 
	  	 Thread.sleep(1000);
	  	  
		 driver.findElement(By.xpath("(//INPUT[@type='submit'])[2]")).click();
		 
		 Thread.sleep(1000);
		 
		 //Defining cookie file
		 File file = new File("LoginCookies.data");
		 
		 try{
		 //First delete old cookie file with same name
		 file.delete();
		 
		 //Create new file
		 file.createNewFile();
		 
		 //Writing character in streams
		 FileWriter fw = new FileWriter(file);
		 
		 //Writing texts to the above cookie file name
		 BufferedWriter bw = new BufferedWriter(fw);
		 
		 //Get all cookies
		 Set<Cookie> cookie = driver.manage().getCookies();
		 
		 //Run in look to get cookies information
		 for(Cookie cki : cookie){
			 bw.write(cki.getName()+","+cki.getValue()+","+cki.getDomain()+","+cki.getPath()+","+cki.getExpiry()+","+cki.isSecure());
			 bw.newLine();
			 System.out.println("Name cki- "+cki.getName()+"\n Value cki- "+cki.getValue()+"\n Domain cki- "+cki.getDomain()+"\n Path cki- "+cki.getPath()+"\n Expiry cki- "+cki.getExpiry()+"\n Secure cki- "+cki.isSecure());
		 }
		 //Closing the BufferedWrite
		 bw.close();
		 
		 //Closing the file
		 fw.close();
		 }catch(Exception e){
			 e.printStackTrace();
		 }
		 
		 driver.close();
		 driver.quit();

	}
	
	

}

After the execution of above code, a new file gets added to your project hierarchy.

Cookie File Created for cookies testing

How to use the stored cookie to login to the application

Following code helps you login with the stored cookies.

package Test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import com.itextpdf.text.log.SysoCounter;

public class LoginWithCookies {

	public static void main(String[] args) {
		System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver.exe");
		 
		 WebDriver  driver  = new ChromeDriver();
		
		  driver.get("http://www.memotome.com/login.asp?display=reminder");
	  	  
	      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		  
	  	  driver.manage().window().maximize();
	  	  
		 File file = new File("LoginCookies.data");
		 
		 try{
		 FileReader fr = new FileReader(file);
		 
		 BufferedReader br = new BufferedReader(fr);
		 
		 String dataLine, name=null, value=null, domain=null, expiry=null, secure=null, path=null;
		 Date exp=null, nextYearExp = null;
		 
		 while((dataLine = br.readLine())!=null){
			 String[] cookieData = dataLine.split(",");
			  name = cookieData[0];
			  value = cookieData[1];
			  domain = cookieData[2];
			  path = cookieData[3];
			  expiry = cookieData[4];
			  secure = cookieData[5];
			  
			 
			 if(!(expiry==null)){
				//Set any random day value
				 exp = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
				sdf.setTimeZone(TimeZone.getTimeZone("IST"));
				sdf.format(exp);
				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.YEAR, 1);
				nextYearExp = cal.getTime();
				 System.out.println("Exp- "+nextYearExp);
				 
			 }
		 }
		 
		 Boolean isSecure = new Boolean(secure);
		
		 System.out.println(nextYearExp);
		 //Set value to new cookie
		 Cookie cookie = new Cookie(name, value, domain, path, nextYearExp, isSecure);
		 System.out.println(cookie);
		 driver.manage().addCookie(cookie);
		 Thread.sleep(1000);
		 driver.get("http://www.memotome.com/login.asp?display=reminder");
	  	  
	  	  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		  
	  	  driver.manage().window().maximize();

	}catch(Exception e){
		e.printStackTrace();
	}

}
}

That’s all about Cookies testing with Selenium. You can post your queries and don’t forget to join our Facebook group for Automation.

Join Inviul fb group

Leave a Reply