Friday, 7 August 2015

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


# 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


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"


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 

  1. Time pressure and deadlines
  2. Late migration of components and DBs
  3. Requirements getting changed in the middle
  4. Patch migration without intimating
  5. Less experienced resources
  6. Large data in DB which increases the testing time
  7. Third party intervention - when some orders are made, onsite guys have to approve the orders before Proceeding with next application
  8. Defect rejection without even analysing the probs
  9. Some defects which feels hardto recreate
  10. Finding critical test data -misbehaviour of system for a few types of test data.
  11. Bugs closing taking its max time
  12. 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.

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:



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 {
 
}


Monday, 22 June 2015

IP Address Program (Core JAVA)



import java.net.InetAddress;

class IPAddress
{
   public static void main(String args[]) throws Exception
   {
      System.out.println(InetAddress.getLocalHost());
   }
}