package testing.MavenTestNG; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.math.BigInteger; import java.net.URL; import java.net.URLConnection; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.Set; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; public class CommonFunctions { static Logger log = Logger.getLogger(CommonFunctions.class.getName()); static char specialCharacters[] = { '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '?', '/', '"', '|', '{', '[', '<', '>', ';', '`', ',', '_', '-' }; /** * Retrieve popup text message. * * @param WebDriver * driver * @return */ public static String getPopupMessage(final WebDriver driver) { String message = null; try { Alert alert = driver.switchTo().alert(); message = alert.getText(); alert.accept(); } catch (Exception e) { // Sometimes the text exist, but not the accept button. // this means the popup wasn't displayed and therefore // really never existed. // message = null; } System.out.println("message"+message); return message; } public static String cancelPopupMessageBox(final WebDriver driver) { String message = null; try { Alert alert = driver.switchTo().alert(); message = alert.getText(); alert.dismiss(); } catch (Exception e) { // Sometimes the text exist, but not the accept button. // this means the popup wasn't displayed and therefore // really never existed. // message = null; } return message; } private static SecureRandom random = new SecureRandom(); /** * Generate random string of special characters of length x * * @return */ public String getRandomSpecialString(int length) { int len = specialCharacters.length; String str = ""; Random randomGenerator = new Random(); int index; for (int i = 0; i < length; i++) { index = randomGenerator.nextInt(len - 1); str = str + specialCharacters[index]; } return str; } /** * Generate random string of length x * * @return */ public static String getRandomString(int length) { String result = new BigInteger(Long.SIZE * length, random).toString(32); return result.substring(0, length); } /** * Generate random string of length x * * @return */ public static void populateField(WebDriver driver, By locator, String value) { WebElement field = driver.findElement(locator); field.clear(); field.sendKeys(value); } /** * Check hover message text * * @param driver * @param by * * @return string */ public static String checkHoverMessage(WebDriver driver, By locator){ String tooltip = driver.findElement(locator).getAttribute("title"); return tooltip; } /** * Select radio button * * @param driver * @param by * @param value * */ public static void selectRadioButton(WebDriver driver, By locator, String value){ List<WebElement> select = driver.findElements(locator); for (WebElement radio : select){ if (radio.getAttribute("value").equalsIgnoreCase(value)){ radio.click(); }}} /** * Select multiple check boxes * * @param driver * @param by * @param value * */ public static void selectCheckboxes(WebDriver driver, By locator, String value){ List<WebElement> abc = driver.findElements(locator); List<String> list = new ArrayList<String>(Arrays.asList(value.split(","))); for (String check : list){ for (WebElement chk : abc){ if(chk.getAttribute("value").equalsIgnoreCase(check)){ chk.click(); } } } } /** * Select drop down * * @param driver * @param by * @param value * */ public static void selectDropdown(WebDriver driver, By locator, String value){ new Select (driver.findElement(locator)).selectByVisibleText(value); } /** * Select auto-suggest search drop down * * @param driver * @param by * @param value * */ public static void selectSearchDropdown(WebDriver driver, By locator, String value){ driver.findElement(locator).click(); driver.findElement(locator).sendKeys(value); driver.findElement(locator).sendKeys(Keys.TAB); } /** * Upload file * * @param driver * @param by * @param value * */ public static void uploadFile(WebDriver driver, By locator, String value){ driver.findElement(locator).sendKeys(value); } /** * Takes controls on new tab * * @param driver * */ public static void handleNewTab(WebDriver driver) { Set<String> allWindowHandles = driver.getWindowHandles(); String window0 = (String) allWindowHandles.toArray()[1]; driver.switchTo().window(window0); } /** * Helper method: looks through a list of WebElements, to find the first WebElement with matching text * * @param elements * @param text * * @return WebElement or null */ public static WebElement findElementByText(List<WebElement> elements, String text) { WebElement result = null; for (WebElement element : elements) { element.getText().trim(); if (text.equalsIgnoreCase(element.getText().trim())) { result = element; break; } } return result; } /** * Compact way to verify if an element is on the page * * @param driver * @param by * @return */ public static boolean isElementPresent(final WebDriver driver, By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } /** * Downloads a file from the defined url, and saves it into the * OutputDatafolder, using the filename defined * * @param href * @param fileName */ public static void downloadFile(String href, String fileName) throws Exception{ PropertyConfigurator.configure("config/log4j.properties"); URL url = null; URLConnection con = null; int i; url = new URL(href); con = url.openConnection(); File file = new File(".//OutputData//" + fileName); BufferedInputStream bis = new BufferedInputStream(con.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(file)); while ((i = bis.read()) != -1) { bos.write(i); } bos.flush(); bis.close(); } /** * Writes content to the excel sheet * * @param text * @param fileName */ public static void writeExcel(String text,String fileName) throws Exception { FileOutputStream file = new FileOutputStream(".//OutputData//" + fileName+".csv",true); WritableWorkbook book = Workbook.createWorkbook(file); WritableSheet sheet = book.createSheet("output", 0); Label l = new Label(0, 0, text); sheet.addCell(l); book.write(); book.close(); } }
This Blog gives good knowledge of core java concepts and selenium (Automation Testing Tool). It also includes some topics of MAVEN (Build Tool) , Jenkins (Continuous Integration Tool) and Cucumber (Behavior Driven Development)
Friday, 7 August 2015
Common Functions Used for Selenium Framework
Create logs in html format using log4j (Core JAVA)
There are two steps to create HTML log file:
1. Create log4j.properties
2. Create Log4jHtmlLayout.java (this is just java file specifies the usage of log4j)
If you want only customize logger then change "log4j.rootLogger = All, FILE, rfile" to "log4j.rootLogger = INFO, FILE, rfile"
log4j.properties
Log4jHtmlLayout.java
Below is the example HTML log file (applog.html-as specified in log4j.properties)
1. Create log4j.properties
2. Create Log4jHtmlLayout.java (this is just java file specifies the usage of log4j)
If you want only customize logger then change "log4j.rootLogger = All, FILE, rfile" to "log4j.rootLogger = INFO, FILE, rfile"
log4j.properties
# Define the root logger with appender file log4j.rootLogger = All, FILE, rfile # Define the file appender log4j.appender.FILE=org.apache.log4j.FileAppender log4j.appender.logfile.File=./TestLogs/Logfile.log # Define the layout for file appender log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.File=./TestLogs/Logfile.log log4j.appender.FILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n # Define the layout for RollingFileAppender log4j.appender.rfile=org.apache.log4j.RollingFileAppender log4j.appender.rfile.File=./TestLogs/applog.html log4j.appender.rfile.MaxFileSize=1000MB log4j.appender.rfile.Append=true log4j.appender.rfile.layout=org.apache.log4j.HTMLLayout
Log4jHtmlLayout.java
package testing.MavenTestNG; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class Log4jHtmlLayout { static Logger log = Logger.getLogger(Log4jHtmlLayout.class); public static void main(String[] args) { PropertyConfigurator.configure("config/log4j.properties"); log.debug("Sample debug message"); log.info("Sample info message"); log.error("Sample error message"); } }
Below is the example HTML log file (applog.html-as specified in log4j.properties)
Friday, 31 July 2015
Input text to text field with and without sendkeys
Input text to text field:
1. sendkeys()
2. javascript
1. sendkeys()
2. javascript
package automation.selenium; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class test1 { public static void main(String[] args) { WebDriver drv=new FirefoxDriver(); drv.navigate().to("http://www.google.com/"); try{ // WITH SENDKEYS //drv.findElement(By.id("lst-ib")).sendKeys("big data"); // WITHOUT SENDKEYS JavascriptExecutor jse = (JavascriptExecutor)drv; //jse.executeScript("document.getElementById('lst-ib').value='big data';"); // OR jse.executeScript("document.getElementById('lst-ib').setAttribute('value', 'big data');"); drv.findElement(By.id("lst-ib")).submit(); } catch(Exception e){ e.printStackTrace(); } } }
Tuesday, 14 July 2015
Convert PDF to text file (Core JAVA)
If you are using maven then add dependency for itextpdf from below link or add itextpdf jars to your project:
Maven Dependency itextpdf
Download sample pdf from below link and and save it in your d drive as examplePDF.pdf:
Download Sample PDF (examplePDF.pdf)
Save exampleText.txt in your d drive.
If you want in other format like word document, just change the file name for OUTPUT i.e. "exampleText.doc"
Maven Dependency itextpdf
Download sample pdf from below link and and save it in your d drive as examplePDF.pdf:
Download Sample PDF (examplePDF.pdf)
Save exampleText.txt in your d drive.
If you want in other format like word document, just change the file name for OUTPUT i.e. "exampleText.doc"
package automation.prac; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; //iText imports import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.parser.PdfReaderContentParser; import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy; import com.itextpdf.text.pdf.parser.TextExtractionStrategy; public class pdfToText { public void partPdf(String pdf, String txt) throws IOException { PdfReader reader = new PdfReader(pdf); PdfReaderContentParser parser = new PdfReaderContentParser(reader); PrintWriter out = new PrintWriter(new FileOutputStream(txt)); TextExtractionStrategy strategy; for (int i = 1; i <= reader.getNumberOfPages(); i++) { strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); out.println(strategy.getResultantText()); } out.flush(); out.close(); reader.close(); } private static String INPUTFILE = "d:\\examplePDF.pdf"; private static String OUTPUTFILE = "d:\\exampleText.txt"; public static void main(String[] args) throws DocumentException, IOException { System.out.println("Program Starts"); new pdfToText().partPdf(INPUTFILE, OUTPUTFILE); System.out.println("Program Ends"); } }
Verify Content in PDF-Page wise (Core JAVA)
If you are using maven then add dependency for itextpdf from below link or add itextpdf jars to your project:
Maven Dependency itextpdf
Download sample pdf from below link and and save it in your d drive as examplePDF.pdf
Download Sample PDF (examplePDF.pdf)
Output is :
Page Number: 1 Fail
Page Number: 2 Pass
Page Number: 3 Fail
Page Number: 4 Fail
package automation.prac; import java.io.IOException; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.parser.PdfReaderContentParser; import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy; import com.itextpdf.text.pdf.parser.TextExtractionStrategy; public class getContentPdf { private static String INPUTFILE = "d:\\examplePDF.pdf"; public void parsePdf(String pdf) throws IOException { PdfReader reader = new PdfReader(pdf); PdfReaderContentParser parser = new PdfReaderContentParser(reader); TextExtractionStrategy strategy; for (int i = 1; i <= reader.getNumberOfPages(); i++) { strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); if(strategy.getResultantText().contains("Gurdial Singh")){ System.out.print("Page Number: "+i); System.out.println(" Pass"); } else{ System.out.print("Page Number: "+i); System.out.println(" Fail"); } } } public static void main(String[] args) throws IOException { new getContentPdf().parsePdf(INPUTFILE); } }
Monday, 13 July 2015
Program to determine Prime Numbers from 1 to 100 (Core JAVA)
Save File as primeNumber.java
package myFirstProject; public class primeNumber { public static void main(String[] args) { int a1 =0; int number =0; //Empty String for printing Prime Numbers String primeNumbers = ""; for (a1 = 1; a1 <= 100; a1++) { int counter=0; for(number =a1; number>=1; number--) { if(a1%number==0) { counter = counter + 1; } } if (counter ==2) { //Appended the Prime number to the String primeNumbers = primeNumbers + a1 + " "; } } System.out.println("Prime Numbers from 1 to 100 are :"); System.out.println(primeNumbers); } }
Friday, 10 July 2015
Swap value of two variable without using third varibale (Core JAVA)
Save File as swapVariables.java
package myFirstProject; public class swapVariables { public static void main(String[] args) { int firstVariable = 10; int secondVariable = 5; // Code to swap 'firstVariable' and 'secondVariable' firstVariable = firstVariable + secondVariable; // firstVariable now becomes 15 secondVariable = firstVariable - secondVariable; // secondVariable becomes 10 firstVariable = firstVariable - secondVariable; // firstVariable becomes 5 System.out.println("Value of firstVariable is: "+firstVariable); System.out.println("Value of secondVariable is: "+secondVariable); } }
Selenium WebDriver and Project Challenges
Selenium WebDriver Challenges
- Dealing with pop-up windows
- Testing dynamic text or content
- How to go about testing Flash
- Capturing screen shots, either to file or in some form of report
- Iteration of the test case, running it repeatedly with some minor change
- Data Driven Testing, using suites of pre-cooked data or generating it on the fly
- Generating useful test status reports
- Configuring Node
- Setting up Grid
- Handling Alerts Popups
- Switching between windows
- Working with Nested frames.
- Field validation
- How to identify dynamic objects.
- Xpath and CSS locators for identifying elements.
- File Upload/Download Using : Java-AutoIT-Selenium
- Handling Multiple Popup Windows.
- Switching with multiple Windows
Projects Challenges
- Time pressure and deadlines
- Late migration of components and DBs
- Requirements getting changed in the middle
- Patch migration without intimating
- Less experienced resources
- Large data in DB which increases the testing time
- Third party intervention - when some orders are made, onsite guys have to approve the orders before Proceeding with next application
- Defect rejection without even analysing the probs
- Some defects which feels hardto recreate
- Finding critical test data -misbehaviour of system for a few types of test data.
- Bugs closing taking its max time
- n/w unavailability
Monday, 29 June 2015
Java Custom Exception (Core JAVA)
package testing.automationTesting; public class customException extends Exception{ customException(){ } customException(String s){ super(s); } static void validate(int age) throws customException{ if(age<18) throw new customException("Invalid.Age.Format.Exception - Age should be 18"); else if(age>18) throw new customException("Invalid.Age.Format.Exception - Age should be 18"); else System.out.print(""); } public static void main(String[] args) { try{ validate(19); } catch(Exception m){ System.out.println("Exception is: "+m); } } }
Wednesday, 24 June 2015
Cucumber Selenium JAVA Integration (Cucumber Project Using Selenium and JAVA)
For cucumber project there are 3 important files.
You can run your test by right clicking on Java Test Runner file and runnig that file as JUNIT test.
3. testRunner.java
1. Feature File: It has
.feature extension. We can have multiple feature files
according to our requirements. We can place the feature file in any
folder and specify the name of the folder in test runner file e.g.
features
= "Feature".
2. Java Step Definition File:
This file describes the feature file. This is the main java file
where do write our scripts. We can implement our functions in this
file.
3. Java Test Runner File: This
file acts as a controller to run different feature files and java files. In
this file we specify the various parameters like features
= "Feature"
,glue={"testfolder"}
,monochrome
= false
,plugin={"pretty",
"html:out"}
If you are using maven then include
following dependencies in pom.xml or you can simply add jars to your
project.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ZS</groupId> <artifactId>automationProject</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>automationProject</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.theoryinpractise</groupId> <artifactId>cucumber-testng-factory</artifactId> <version>1.0.1</version> </dependency> <dependency> <groupId>com.sun</groupId> <artifactId>tools</artifactId> <version>1.6</version> <scope>system</scope> <systemPath>C:\Program Files\Java\jdk1.8.0_40\lib\tools.jar</systemPath> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-core</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-jvm-deps</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.10.8</version> </dependency> <dependency> <groupId>cobertura</groupId> <artifactId>cobertura</artifactId> <version>1.8</version> </dependency> <dependency> <groupId>net.masterthought</groupId> <artifactId>cucumber-reporting</artifactId> <version>0.0.24</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>2.0.1-beta</version> </dependency> <dependency> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> </dependencies> </project>
<dependency> <groupId>com.theoryinpractise</groupId> <artifactId>cucumber-testng-factory</artifactId> <version>1.0.1</version> </dependency> <dependency> <groupId>com.sun</groupId> <artifactId>tools</artifactId> <version>1.6</version> <scope>system</scope> <systemPath>C:\Program Files\Java\jdk1.8.0_40\lib\tools.jar</systemPath> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-core</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-jvm-deps</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.10.8</version> </dependency> <dependency> <groupId>cobertura</groupId> <artifactId>cobertura</artifactId> <version>1.8</version> </dependency> <dependency> <groupId>net.masterthought</groupId> <artifactId>cucumber-reporting</artifactId> <version>0.0.24</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>2.0.1-beta</version> </dependency> <dependency> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency>
You can run your test by right clicking on Java Test Runner file and runnig that file as JUNIT test.
Here is the structure for your project:
Test Result report can be seen under
out folder in index.html
Please find below all 3 files:
1. Feature File:
2. google_test.java
1. Feature File:
Feature: Google Testing
Scenario: Click on Gmail
Given User is on Google Home Page
When Click on Gmail link
Then Gmail opens successfully
2. google_test.java
package stepDefinition; import java.util.concurrent.TimeUnit; import junit.framework.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class google_test { public static WebDriver driver; @Given("^User is on Google Home Page$") public void User_is_on_Google_Home_Page() throws Throwable { driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://www.google.co.in/?gfe_rd=cr&ei=g1OKVcrzFOfI8Aff75zYBw&gws_rd=ssl"); driver.manage().window().maximize(); } @When("^Click on Gmail link$") public void Click_on_Gmail_link() throws Throwable { driver.findElement(By.className("gb_ma")).click(); } @Then("^Gmail opens successfully$") public void Gmail_opens_successfully() throws Throwable { Assert.assertEquals(driver.getTitle(),"Gmail"); System.out.println("Gmail opens successfully"); } }
3. testRunner.java
package cucumberTest; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( features = "Feature" ,glue={"stepDefinition"} ,monochrome = false ,plugin={"pretty", "html:out"} ) public class TestRunner { }
Subscribe to:
Posts (Atom)