Automation Testing

How to retrieve all options in a dropdown using…


We can retrieve all options in a dropdown using Selenium. All the options in the dropdown are stored in a list data structure. This is achieved with the help of options() which is a method under the Select class.

options() returns a list of all options under the select tag. An empty list is returned if the dropdown is not identified on the page with the help of any of the locators.

Syntax

d = Select(driver.find_element_by_id("selection"))
o = d.options()

Example

Code Implementation for getting all options in the dropdown.

from selenium import webdriver
from selenium.webdriver.support.select import Select
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")

# to maximize the browser window
driver.maximize_window()

#get method to launch the URL
driver.get("https://www.tutorialspoint.com/tutor_connect/index.php")

#to refresh the browser
driver.refresh()

#select class provide the methods to handle the options in dropdown
d = Select(driver.find_element_by_xpath("//select[@name='seltype']"))

#store the options in a list with options method
l = d.options

#to count the number of options and print in console
print(len(l))

#to get all the number of options and print in console
for i in l:
print(i.text)

#to close the browser
driver.close()

Automation Testing

How to scroll down a webpage in selenium using…


We can scroll down a webpage in Selenium using Java. Selenium is unable to handle scrolling directly. It takes the help of the Javascript Executor to perform the scrolling action up to an element.

First of all, we have to locate the element up to which we have to scroll. Next, we shall use the Javascript Executor to run the Javascript commands. The method executeScript is used to run Javascript commands in Selenium. We shall take the help of the scrollIntoView method in Javascript and pass true as an argument to the method.

Syntax −

WebElement elm = driver.findElement(By.name("name"));
((JavascriptExecutor) driver)
.executeScript("arguments[0].scrollIntoView(true);", elm);

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollAction{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      //launch application
      driver.get
      ("https://www.tutorialspoint.com/about/about_careers.htm ");
      // identify element
      WebElement n=driver.findElement(By.xpath("//*[text()='Contact']"));
      // Javascript executor
      ((JavascriptExecutor)driver)
      .executeScript("arguments[0].scrollIntoView(true);", n);
   }
}
Automation Testing

What are the differences between get() and navigate() method?


The differences between get() and navigate() methods are listed below.

sl.no.get()navigate()
1It is responsible for loading the page and waits until the page has finished loading.It is only responsible for redirecting the page and then returning immediately.
2It cannot track the history of the browser.It tracks the browser history and can perform back and forth in the browser.

Example

With get().

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class LaunchBrw {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      driver.close();
   }
}

Example

With navigate().

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class BrowserNavigation {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      // new browser will launch and navigate to the URL
      driver.navigate().to(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // refresh the current browser
      driver.navigate().refresh();
      //Using id tagname attribute combination for css expression
      driver.findElement(By.cssSelector("input[name=’search’]")). sendKeys("Selenium");
      //browser will go back to the previous page
      driver.navigate().back();
      //browser will go move to the next page
      driver.navigate().forward();
      driver.close();
   }
}
Java

Java Program to Iterate through each characters of the…

Here we will learn to iterate through each characters of the string.

To understand this example, you should have the knowledge of the following Java programming topics:

  • Java Strings
  • Java for Loop
  • Java for-each Loop

Example 1: Loop through each character of a string using for loop

class Main {
  public static void main(String[] args) {

    // create a string
    String name = "Programiz";

    System.out.println("Characters in " + name + " are:");

    // loop through each element
    for(int i = 0; i<name.length(); i++) {

      // access each character
      char a = name.charAt(i);
      System.out.print(a + ", ");
    }
  }
}

Output

Characters in Programiz are:
P, r, o, g, r, a, m, i, z,

In the above example, we have used the for-loop to access each element of the string. Here, we have used the charAt() method to access each character of the string.


Example 2: Loop through each character of a string using for-each loop

class Main {

  public static void main(String[] args) {

    // create a string
    String name = "Programiz";

    System.out.println("Characters in string \"" + name + "\":");

    // loop through each element using for-each loop
    for(char c : name.toCharArray()) {

      // access each character
      System.out.print(c + ", ");
    }

  }
}

Output

Characters in string "Programiz":
P, r, o, g, r, a, m, i, z,

In the above example, we have converted the string into a char array using the toCharArray(). We then access each element of the char array using the for-each loop.

Java

Private Constructor in Java

In Java, the constructoris a special type of method that has the same name as the class name. Internally, a constructor is always called when we create an object of the class. It is used to initialize the state of an object.

In the same way, Java also allows us to create a private constructor. In this section, we will discuss private constructors in Java, rules for creating a private constructor, and its use cases. Also, we will see its implementation.

What is a private constructor?

Java allows us to declare a constructor as private. We can declare a constructor private by using the private access specifier. Note that if a constructor is declared private, we are not able to create an object of the class. Instead, we can use this private constructor in Singleton Design Pattern.

Rules for Private Constructor

The following rules keep in mind while dealing with private constructors.

  • It does not allow a class to be sub-classed.
  • It does not allow to create an object outside the class.
  • If a class has a private constructor and when we try to extend the class, a compile-time error occurs.
  • We cannot access a private constructor from any other class.
  • If all the constant methods are there in our class, we can use a private constructor.
  • If all the methods are static then we can use a private constructor.
  • We can use a public function to call the private constructor if an object is not initialized.
  • We can return only the instance of that object if an object is already initialized.

Use Cases of Private Constructor

The main purpose of using a private constructor is to restrict object creation. We also use private constructors to implement the singleton design pattern. The use-cases of the private constructor are as follows:

  • It can be used with static members-only classes.
  • It can be used with static utilityor constant classes.
  • It can also be used to create singleton classes.
  • It can be used to assign a name, for instance, creation by utilizing factory methods.
  • It is also used to avoid sub-classing.
  • It incorporates the factory methods.

Let’s see the implementation of the private constructor.

Implementation of a Private Constructor

A.java

  1. public class A  
  2. {  
  3. //craeting a private constructor   
  4. private A()  
  5. {  
  6. }  
  7. void display()  
  8. {  
  9. System.out.println(“Private Constructor”);  
  10. }  
  11. }  
  12. private class Test  
  13. {  
  14. public static void main(String args[])  
  15. {  
  16. //compile time error  
  17. A obj = new A();   
  18. }  
  19. }  

Output:

Private Constructor in Java

PrivateConstructorDemo.java

  1. public class PrivateConstructorDemo   
  2. {  
  3. //creating an instance variable of the class Tester  
  4. private static PrivateConstructorDemo pcd;  
  5. //creating a private constructor  
  6. private PrivateConstructorDemo()  
  7. {  
  8. }  
  9. //creating a static method named getInstance()  
  10. public static PrivateConstructorDemo getInstance()  
  11. {  
  12. if(pcd == null)  
  13. {  
  14. //creating a constructor of the class      
  15. pcd = new PrivateConstructorDemo();  
  16. }  
  17. return pcd;  
  18. }  
  19. //main() method  
  20. public static void main(String args[])   
  21. {  
  22. PrivateConstructorDemo pcd = PrivateConstructorDemo.getInstance();  
  23. PrivateConstructorDemo pcd1 = PrivateConstructorDemo.getInstance();  
  24. //invokes the getInstance() method and prints the corresponding result  
  25. System.out.println(pcd.equals(pcd1));  
  26. }    
  27. }  

Output:

true
Uncategorized

Difference between HashMap and Hashtable

HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys.

But there are many differences between HashMap and Hashtable classes that are given below.

HashMapHashtable
1) HashMap is non synchronized. It is not-thread safe and can’t be shared between many threads without proper synchronization code.Hashtable is synchronized. It is thread-safe and can be shared with many threads.
2) HashMap allows one null key and multiple null values.Hashtable doesn’t allow any null key or value.
3) HashMap is a new class introduced in JDK 1.2.Hashtable is a legacy class.
4) HashMap is fast.Hashtable is slow.
5) We can make the HashMap as synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap);
Hashtable is internally synchronized and can’t be unsynchronized.
6) HashMap is traversed by Iterator.Hashtable is traversed by Enumerator and Iterator.
7) Iterator in HashMap is fail-fast.Enumerator in Hashtable is not fail-fast.
8) HashMap inherits AbstractMap class.Hashtable inherits Dictionary class.
Uncategorized

Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can’t be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract classInterface
1) Abstract class can have abstract and non-abstract methods.Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
2) Abstract class doesn’t support multiple inheritance.Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non-static variables.Interface has only static and final variables.
4) Abstract class can provide the implementation of interface.Interface can’t provide the implementation of abstract class.
5) The abstract keyword is used to declare abstract class.The interface keyword is used to declare interface.
6) An abstract class can extend another Java class and implement multiple Java interfaces.An interface can extend another Java interface only.
7) An abstract class can be extended using keyword “extends”.An interface can be implemented using keyword “implements”.
8) A Java abstract class can have class members like private, protected, etc.Members of a Java interface are public by default.
9)Example:
public abstract class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).

Example of abstract class and interface in Java

Let’s see a simple example where we are using interface and abstract class both.

  1. //Creating interface that has 4 methods  
  2. interface A{  
  3. void a();//bydefault, public and abstract  
  4. void b();  
  5. void c();  
  6. void d();  
  7. }  
  8.   
  9. //Creating abstract class that provides the implementation of one method of A interface  
  10. abstract class B implements A{  
  11. public void c(){System.out.println(“I am C”);}  
  12. }  
  13.   
  14. //Creating subclass of abstract class, now we need to provide the implementation of rest of the methods  
  15. class M extends B{  
  16. public void a(){System.out.println(“I am a”);}  
  17. public void b(){System.out.println(“I am b”);}  
  18. public void d(){System.out.println(“I am d”);}  
  19. }  
  20.   
  21. //Creating a test class that calls the methods of A interface  
  22. class Test5{  
  23. public static void main(String args[]){  
  24. A a=new M();  
  25. a.a();  
  26. a.b();  
  27. a.c();  
  28. a.d();  
  29. }} 
Uncategorized

How to Use Log4j in Selenium

What is Logging?

Logging is a process that takes applications to a newer level with information logs on how the applications may or may not have performed/executed. It gives an exact idea of software performance, including any shortcomings.

Log4j in Selenium is one such logging framework that helps in gathering information in the form of logs or log files.

What is Log4j in Selenium?

Log4j is a logging framework written in Java that provides an easy way for logging in Selenium. In a nutshell, the framework gives out information about everything that goes on during the software execution.

Log4j also provides insight into anything that may have gone wrong during software execution or automation. Overall, Log4j documents the output in the form of logs that can be examined later for purposes such as auditing small and large-scale Selenium projects.

Let’s take a look at the various components of the Log4j logging framework.

Components of Log4j

The Log4j logging framework comprises the following components:

  1. Logger
  2. Appenders
  3. Layout

Logger

The function of the logger in Log4j is basically storing and capturing all the necessary logging information that will be generated using the framework.

To truly understand its functioning, let’s dig a little deeper and discuss the logger class, and log level methods. The loggers also decide which priority is going to be captured.

  1. Logger Class – To fully use the logger, create an instance for a logger class where all the generic methods will be at the user’s disposal, required to use Log4j.
  2. Log Levels – These are the methods that will be used to print the log messages. There are primarily only a few log levels that are used in a script.
  • ALL – This level will prioritize and include everything in the logs.
  • ERROR – This level will show messages that inform users about error events that may not stop the application.
  • WARN – This level will show information regarding warnings, that may not stop the execution but may still cause problems.
  • DEBUG – This level will log debugging information.
  • INFO – This level will log the progress of the application.
  • FATAL – This will print information critical to the system that may even crash the application.

Appenders

The appender basically grabs information from the logger and writes log messages to a file or any other storage location. The following are some of the appenders one can use for Log4j:

  1. FileAppender – This will append the log messages to a file.
  2. RollingFileAppender – It will perform the same function as FileAppender, but users will be able to specify the maximum file size. Once the limit is exceeded, the appender will create another file to write the messages.
  3. DailyRollingFileAppender – It specifies the frequency by which the messages are to be written to the file.
  4. ConsoleAppender – In this, the appender will simply write the log messages in the console.

Layout

The layout is where the format in which log messages will appear is decided. There are several layouts one can use for log messages:

  1. Pattern Layout – The user must specify a conversion pattern based on which the logs will be displayed. Otherwise, it takes the default conversion pattern in case of “no pattern specified”.
  2. HTML Layout – In this layout, the format of logs will be in the form of an HTML table.
  3. XML Layout – This will show the logs in an XML format.

How to Use Log4j in Selenium

Follow the steps below to successfully run Log4j with Selenium Webdriver:

  1. Write an automation script, such as the one in the example below. It is a simple script that opens a URL, send keys to username and password, and ends the script when it clicks the login button.
  2. After creating the script, create a log4j.properties file and specify the root logger, appended, and layout information in the file.
  3. Import log4j dependencies like Logger, PropertyConfigurator, and add them to the script along with the logger class.
  4. Add the messages that will be displayed in the log file.

Now, let’s try to understand the code written below:

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;


public class Bstack01 implements driverHelp {
	static Logger log = Logger.getLogger(Bstack01.class);
	public static void main(String[] args) {
	PropertyConfigurator.configure("F:\\Work Environment\\MyProject\\QA_Round\\src\\log4j.properties");
	System.setProperty("webdriver.chrome.driver", "//path of chrome driver");
	ChromeOptions options = new ChromeOptions();
	options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
	WebDriver driver = new ChromeDriver(options);
	JavascriptExecutor js = (JavascriptExecutor)driver;
	driver.get("https://www.browserstack.com/users/sign_in");
	log.info("Open browserstack");
	driver.manage().window().maximize();
	log.info("Maximize window size");
	driver.findElement(By.id("user_email_login")).sendKeys("rbc@xyz.com");
	System.out.println("User name is etered");
	log.info("enter username");
	driver.findElement(By.id("user_password")).sendKeys("password");
	System.out.println("Password is entered");
	log.info("enter password");
	//driver.findElement(By.name("commit")).click();
	js.executeScript("document.getElementById('user_submit').click();");
	log.info("click on login");
	System.out.println("Sign in button is clicked");
	driver.close();

	}
	}

Log4j with Properties File Configuration

The properties configuration file will contain the information regarding the following:

  1. The first objective is to identify the log level and the destination where the log will be written. In this case, the log level is the DEBUG level and a file is the destination.
  2. The next step is to establish an appender. This example uses a RollingFIleAppender with a maximum capacity of 2MB and the file location is also specified in this section. The MaxBackupIndex is the number of files that will be created in case the file size is exceeded.
  3. The last section contains the layout in which a format is specified. This example uses PatternLayout. And, since we have not used a conversion pattern here, it will take the default conversion pattern into account.
#root logger
log4j.rootLogger = DEBUG, file
#appender
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File = PATH\\TO\\firstoutput.log
log4j.appender.file.MaxFileSize = 2MB
log4j.appender.file.MaxBackupIndex = 3
#layout
log4j.appender.file.layout = org.apache.log4j.PatternLayout


Automation Testing

How to perform search in amazon using selenium.

Solution:

  1. Create a new Project in Eclipse.
  2. Add the required libraries for Selenium.

Now in first you need to create an interface: driver

import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.remote.DesiredCapabilities;

public interface driver {
	
	public  WebDriver wd = new FirefoxDriver();
	public static String baseURL = "http://automationpractice.com/index.php";
	public static String driverPath = "F:\\Work Environment\\MyProject\\gekodriver\\geckodriver.exe";
	public void CallDriver();
	public static String email = "rahul@gmail.com";
	public static String password = "pass1234";
	public static Logger log  = Logger.getLogger(driver.class.getName());
	public static WebElement mainMenu = null;
	public static Action actions = null;
}

Now create a new TestNG Class and enter the following script:

import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterTest;

public class Search1 implements driver {
	public static WebElement se;
  
  @BeforeTest
  public void CallDriver() {
	  
	  System.setProperty("webdriver.gecko.driver",driverPath );
	  wd.manage().window().maximize();
	  wd.get("https://www.amazon.com/");
	  log.debug("Navigated to Amazon.com");
  }
  
  @Test
  public void TestSearch() {
	  WebElement se = wd.findElement(By.id("twotabsearchtextbox"));
	  se.sendKeys("iphone");
	  log.debug("Entered a keyword to search");
	  
	  wd.findElement(By.id("nav-search-submit-button")).click();
	  log.debug("Search button is clicked");
	  
	  
  }
  
  @Test
  public void TestSearch1() {
	  
	  String actRe = wd.getCurrentUrl();
	  String exres = "https://www.amazon.com/s?k=iphone&ref=nb_sb_noss_2";
		  Assert.assertEquals(actRe,exres);
	  se.clear();  
  }
  
  @Test
  public void TestSearch2() {
	  wd.navigate().back();
	  log.debug("nvigated back to previous page");
	 System.out.println(wd.getCurrentUrl());
  }
  

  @AfterTest
  public void afterTest() {
	  wd.quit();
  }


}

Automation Testing

Automation Code Test 1

Core Automation: 

Navigate to https://blazedemo.com/index.php  

  1. Check if the title is displayed as ` Welcome to the Simple Travel Agency!`. This is the Home Page of application 
  1. Click on ` destination of the week! The Beach!` hyperlink and see if a new tab opens in your browser & the url has string `vacation`. Navigate back to home page tab. 
  1. Purchase a ticket:  
  1. Select `Mexico City` in departure city & `London` in destination city.  
  1. Click ‘Find Flights’. Select the flight with lowest price by clicking `Choose the flight` & see if we are navigated to purchase page (This should be dynamically handled and can work for any inputs in Step 3.a) 
  1. Check if a field named ‘Total Cost’ is available with price available in xxx.xx format. Click on ‘Purchase flight’ button 
  1. Check if the user is navigated to Purchase Confirmation page & store the `Id’ in the console or test report for future reference. 

POINTS TO CONSIDER: 

  • Create a new Java, Maven, C# project with an appropriate test framework like Nunit, TestNG etc., 
  • Automate tests in Chrome browser 
  • Use parameterized data instead of hardcoded test data 
  • Use Page Object Model with Selenium 
  • Make your functions more generic and use coding best practices as much as possible 
  • Once the test is done, please zip the entire project and send it to us 

Solution:

  1. Create a new Project in Eclipse.
  2. Add the required libraries for Selenium.

Now in first you need to create an interface: driverHelp

import java.util.Properties;

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

public interface driverHelp {
	
	public static WebDriver wd = new ChromeDriver();
	public static String cd1 = "F:\\Work Environment\\MyProject\\chromedriver.exe";
	public static String url = "https://blazedemo.com/index.php";
	
}

Once you create the interface, you need to create a new class “DemoTest” and implement the interface driverHelp.

Add the following code in your class file and run as TestNG project.

import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.AfterTest;
import org.openqa.selenium.support.ui.Select;

public class DemoTest implements driverHelp {
	
	public static WebElement we1;
  
  @BeforeTest
  public void callDriver() {
	  System.setProperty("webdriver.chrome.driver", cd1);
	  wd.manage().deleteAllCookies();
	  wd.manage().window().maximize();
	  wd.get(url);
  }
  
  
  @Test
  public void Test1() {
	 System.out.println(wd.getTitle());
	 
	 String t1 = "Welcome to the Simple Travel Agency!";
	 if(t1.equals(wd.getTitle()) ) {
		 System.out.println("Title Matched the expected result");
		 
	 }
	 
  }
	 
	 @Test
	  public void Test2() {
		wd.findElement(By.linkText("destination of the week! The Beach!")).click();
		System.out.println(wd.getCurrentUrl());
		wd.navigate().back();
		System.out.println(wd.getCurrentUrl());
			 
		 } 
	 
	 @Test
	  public void Test3() {
		 
		//d.findElement(By.className("form-inline")).click();
		 //.findElement(By.partialLinkText("Mexico City")).click();
		 
		 Select scity = new Select(wd.findElement(By.className("form-inline")));
		 scity.selectByVisibleText("Mexico City");
		 scity.selectByIndex(4);
		 
		 Select ecity = new Select(wd.findElement(By.name("toPort")));
		 ecity.selectByVisibleText("London");
		 ecity.selectByIndex(2);
		 
		 wd.findElement(By.xpath("/html/body/div[3]/form/div/input")).click();
		 
		 
	 }
	 
	 @Test
	  public void Test4() {
		 
		 wd.findElement(By.xpath("/html/body/div[2]/table/tbody/tr[3]/td[1]/input")).click();
		 System.out.printf("Flight with the lowest fair",wd.getTitle());
		 
	 }
	 
	 @Test
	  public void Test5() {
		 
		if( wd.findElement(By.partialLinkText("Total Cost")).isDisplayed())
		{
			System.out.println("Total Coast is present");
		}
		 
		 
	 }
	  
	 @Test
	  public void Test6() {
		 
		wd.findElement(By.xpath("/html/body/div[2]/form/div[11]/div/input")).click();
		System.out.println(wd.getCurrentUrl());
		 
	 }
	  
	  
	 

  @AfterTest
  public void afterTest() {
	  wd.quit();
  }

}