Sunday, 17 June 2018

Extent Reports

JARS- Dependency

<dependency>
    <groupId>com.relevantcodes</groupId>
    <artifactId>extentreports</artifactId>
    <version>2.41.0</version>
</dependency>



extent-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<extentreports>
  <configuration>
    <!-- report theme -->
    <!-- standard, dark -->
    <theme>standard</theme>
 
    <!-- document encoding -->
    <!-- defaults to UTF-8 -->
    <encoding>UTF-8</encoding>
   
    <!-- protocol for script and stylesheets -->
    <!-- defaults to https -->
    <protocol>https</protocol>
   
    <!-- title of the document -->
    <documentTitle>ExtentReports 2.0</documentTitle>
   
    <!-- report name - displayed at top-nav -->
    <reportName></reportName>
   
    <!-- report headline - displayed at top-nav, after reportHeadline -->
    <reportHeadline>Automation Report</reportHeadline>
   
    <!-- global date format override -->
    <!-- defaults to yyyy-MM-dd -->
    <dateFormat>yyyy-MM-dd</dateFormat>
   
    <!-- global time format override -->
    <!-- defaults to HH:mm:ss -->
    <timeFormat>HH:mm:ss</timeFormat>
   
    <!-- custom javascript -->
    <scripts>
      <![CDATA[
        $(document).ready(function() {
         
        });
      ]]>
    </scripts>
   
    <!-- custom styles -->
    <styles>
      <![CDATA[
       
      ]]>
    </styles>
  </configuration>

</extentreports>


Extent Report Class


import java.io.File;

import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.LogStatus;

public class ExtentReportsClass {


ExtentReports extent;
static com.relevantcodes.extentreports.ExtentTest logger;


@BeforeTest
public void startReport(){
//ExtentReports(String filePath,Boolean replaceExisting)
//filepath - path of the file, in .htm or .html format - path where your report needs to generate.
//replaceExisting - Setting to overwrite (TRUE) the existing file or append to it
//True (default): the file will be replaced with brand new markup, and all existing data will be lost. Use this option to create a brand new report
//False: existing data will remain, new tests will be appended to the existing report. If the the supplied path does not exist, a new file will be created.
extent = new ExtentReports (System.getProperty("user.dir") +"/test-output/STMExtentReport.html", true);
//extent.addSystemInfo("Environment","Environment Name")
extent
                .addSystemInfo("Host Name", "SoftwareTestingMaterial")
                .addSystemInfo("Environment", "Automation Testing")
                .addSystemInfo("User Name", "Rajkumar SM");
                //loading the external xml file (i.e., extent-config.xml) which was placed under the base directory
                //You could find the xml file below. Create xml file in your project and copy past the code mentioned below
                extent.loadConfig(new File(System.getProperty("user.dir")+"\\extent-config.xml"));
}

@Test
public void passTest(){
//extent.startTest("TestCaseName", "Description")
//TestCaseName – Name of the test
//Description – Description of the test
//Starting test
logger = extent.startTest("passTest");
Assert.assertTrue(true);
//To generate the log when the test case is passed
logger.log(LogStatus.PASS, "Test Case Passed is passTest");

}

@Test
public void failTest(){
logger = extent.startTest("failTest");
Assert.assertTrue(false);
logger.log(LogStatus.FAIL, "Test Case  Status is passed");
}

// @Test
public void skipTest(){
logger = extent.startTest("skipTest");
throw new SkipException("Skipping - This is not ready for testing ");
}

// @AfterMethod
public void getResult(ITestResult result){
if(result.getStatus() == ITestResult.FAILURE){
logger.log(LogStatus.FAIL, "Test Case Failed is "+result.getName());
logger.log(LogStatus.FAIL, "Test Case Failed is "+result.getThrowable());
}else if(result.getStatus() == ITestResult.SKIP){
logger.log(LogStatus.SKIP, "Test Case Skipped is "+result.getName());
}
// ending test
//endTest(logger) : It ends the current test and prepares to create HTML report
extent.endTest(logger);
}
@AfterTest
public void endReport(){
// writing everything to document
//flush() - to write or update test information to your report.
                extent.flush();
                //Call close() at the very end of your session to clear all resources.
                //If any of your test ended abruptly causing any side-affects (not all logs sent to ExtentReports, information missing), this method will ensure that the test is still appended to the report with a warning message.
                //You should call close() only once, at the very end (in @AfterSuite for example) as it closes the underlying stream.
                //Once this method is called, calling any Extent method will throw an error.
                //close() - To close all the operation
               // extent.close();
    }
}



API Testing-Rest Assured

package framework.RestAPI;

import org.testng.Assert;
import org.testng.annotations.Test;

import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;
import com.relevantcodes.extentreports.LogStatus;

import framework.TestBase.TestBase;
import framework.configReader.ObjectRepo;

import  static com.jayway.restassured.RestAssured.*;

public class weatherGetRequest extends TestBase {

@Test(priority=1)

public void weatherGetStatusCode(){
Response resp=
       given().
       param("q","London").
       param("appid","b6907d289e10d714a6e88b30761fae22").
       when().
       get("http://samples.openweathermap.org/data/2.5/weather");
     

int statuscode=resp.getStatusCode();
Assert.assertEquals(statuscode, 200);
TestBase.logger.info("Get the Status code");
TestBase.extentlogger = TestBase.extent.startTest("Verify the status code -->passTest");
TestBase.extentlogger.log(LogStatus.PASS, "Test Case Passed is passTest");

//System.out.println(resp.getStatusCode());


}
@Test(priority=2)
public void getResponse(){

Response resp=
       given().
       parameter("q","London").
       parameter("appid","b6907d289e10d714a6e88b30761fae22").
       when().
       get("http://samples.openweathermap.org/data/2.5/weather");
String Expected="light intensity drizzle";
String Actual=resp.then().contentType(ContentType.JSON).extract().path("weather[0].description");
Assert.assertEquals(Actual,Expected);
TestBase.logger.info("check response data");
TestBase.extentlogger = TestBase.extent.startTest("Check the response data -->passTest");
TestBase.extentlogger.log(LogStatus.PASS, "Test Case Passed is passTest");

// System.out.println(resp.asString());
}

@Test(priority=3)
public void transferLonLat(){

Response resp=given().
       parameter("q","London").
       parameter("appid","b6907d289e10d714a6e88b30761fae22").
       when().
       get("http://samples.openweathermap.org/data/2.5/weather");

   String respbyid =   resp.then().
       contentType(ContentType.JSON).
       extract().
       path("weather[0].description");

System.out.println(respbyid);





String lon=String.valueOf(resp.then().
contentType(ContentType.JSON).
extract().
path("coord.lon"));
System.out.println(lon);

String lat=String.valueOf(resp.then().
contentType(ContentType.JSON).
extract().
path("coord.lat"));
System.out.println(lat);



String respbycoord=given().
parameter("lat",lat ).
parameter("lon", lon).
parameter("appid","b6907d289e10d714a6e88b30761fae22").
get("http://samples.openweathermap.org/data/2.5/weather").
then().
contentType(ContentType.JSON).extract().
path("weather[0].description");

System.out.println(respbycoord);

try{
Assert.assertEquals(respbyid, respbycoord);
TestBase.logger.info("Verify longitude and latitude");
TestBase.extentlogger = TestBase.extent.startTest("Check the longitude and latitude -->passTest");
TestBase.extentlogger.log(LogStatus.PASS, "Test Case Passed is passTest");
}
catch(Exception e){
TestBase.logger.info("Verify longitude and latitude");
TestBase.extentlogger = TestBase.extent.startTest("Check the longitude and latitude -->passTest");
TestBase.extentlogger.log(LogStatus.FAIL, "Test Case failed");
}

}

}



JARS needed


<dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>2.9.0</version>
    <scope>test</scope>
</dependency>


<!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.jayway.restassured/json-schema-validator -->
<dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>2.2.0</version>
</dependency>
    
  </dependencies>

Tuesday, 22 May 2018

CUCUMBER FRAMEWORK


CUCUMBER FRAMEWORK

Create Maven project
Group id:com
Aritifact Id:Cucumber





















For Cucumber plug in




Dependencies for the framework [POM.XML]
<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>com</groupId>
  <artifactId>Cucumber1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Cucumber1</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-jvm</artifactId>
<version>1.2.5</version>
<type>pom</type>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-jvm-deps</artifactId>
<version>1.0.5</version>
</dependency>

<dependency>
<groupId>net.masterthought</groupId>
<artifactId>cucumber-reporting</artifactId>
<version>1.0.0</version>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>gherkin</artifactId>
<version>2.12.2</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>



<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.5.3</version>
</dependency>

<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-picocontainer -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-testng</artifactId>
<version>1.2.5</version>
</dependency>

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.relevantcodes/extentreports -->
<dependency>
    <groupId>com.relevantcodes</groupId>
    <artifactId>extentreports</artifactId>
    <version>2.41.0</version>
</dependency>

<dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>2.9.0</version>
    <scope>test</scope>
</dependency>


<!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.jayway.restassured/json-schema-validator -->
<dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>2.2.0</version>
</dependency>
    
  </dependencies>
</project>



To display Navigator
Window->Show View-> Navigator


Create the below folder structure




For the above folders just right click on desired folder and add the respective folder


For Resources folder

Right click on the project->properties->Sources->Cucumber/src/test/java->Add folder->test->Create New folder->folder name- resources





















Add folder





















New Folder


















Create feature folder and feature file (Facebooklogin.feature)















FacebookLogin.feature





Create runner package and FacebookloginFeatureRunner.java




















FacebookloginFeature Runner [class file]










Create TestNg folder and TestNg.xml

























TestNg.xml





Right click on TestNg.xml and run



Below output is displayed in Console







Create stepDefinitons folder under framework and create LoginToFacebook class




























Copy the console output[ methods-Given,When, Then] to LoginToFacebook class























LoginToFacebook-Step Definition

package framework.stepDefinition;


import com.relevantcodes.extentreports.LogStatus;

import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import framework.TestBase.TestBase;
import framework.configReader.ObjectRepo;
import framework.pageObject.Login;

public class LoginToApplication {

Login l= new Login(TestBase.driver);
@Given("^Enter the url and launch the application$")
public void enter_the_url_and_launch_the_application() throws Throwable {
TestBase.driver.get(ObjectRepo.reader.getWebsite());
TestBase.logger.info("Enter the URL and launch application --> "+ ObjectRepo.reader.getWebsite());
TestBase.extentlogger = TestBase.extent.startTest("Enter the URL and launch application -->passTest");
TestBase.extentlogger.log(LogStatus.PASS, "Test Case Passed is passTest");
}

@And("^I enter username$")
public void i_enter_username() throws Throwable {
try{
TestBase.logger.info("Enter username --> ");

l.enterUsername("sagarseleniumstl@gmail.com");
  // System.out.println("enter username");
  // TestBase.type("Login_username", "Username");
   TestBase.extentlogger = TestBase.extent.startTest("Enter username ");
   TestBase.extentlogger.log(LogStatus.PASS, "Test Case Passed is passTest");
}
catch(Exception e){
TestBase.extentlogger.log(LogStatus.FAIL, "Test Case failed ");

}
}

@And("^I enter password$")
public void i_enter_password() throws Throwable {
try{
TestBase.logger.info("Enter password");
l.enterPassword("sagarsomaiah");
  //System.out.println("enter password");
// TestBase.type("Login_password", "Password");
  TestBase.extentlogger = TestBase.extent.startTest("Enter password");
  TestBase.extentlogger.log(LogStatus.PASS, "Test Case Passed is passTest");
}
catch(Exception e){
TestBase.extentlogger.log(LogStatus.FAIL, "Test Case failed ");

}
}

@And("^I click on login button$")
public void i_click_on_login_button() throws Throwable {
try{

TestBase.extentlogger = TestBase.extent.startTest("click login button-->");

l.clickSubmit();
TestBase.logger.info("Click submit");
//System.out.println("click login");
//TestBase.click("Login_submit");
TestBase.extentlogger.log(LogStatus.PASS, "Test Case Passed is passTest");
}
catch(Exception e){
TestBase.extentlogger.log(LogStatus.FAIL, "Test Case failed ");
}
}

@Then("^User is succesfully logged$")
public void user_is_succesfully_logged() throws Throwable {
try{
TestBase.extentlogger = TestBase.extent.startTest("logged successfully-->");
TestBase.logger.info("Logged successfully");
TestBase.extentlogger.log(LogStatus.PASS, "Test Case Passed is passTest");
   //System.out.println("logged");
}
catch(Exception e){
TestBase.extentlogger.log(LogStatus.FAIL, "Test Case failed ");
}
}
}




Create below folders in src/main




























Note: Create Resource folder is the same way mentioned earlier( Right click project->Buildpath->source-src/main-new folder)


Package Explorer view






















Log4j.properties

# Define the root logger with appender file
log4j.rootLogger = INFO, FILE,stdout,HTML

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=selenium.out
log4j.appender.FILE.Append=false
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
log4j.appender.file.MaxFileSize=4MB
log4j.appender.file.MaxBackupIndex=9


log4j.appender.HTML=org.apache.log4j.FileAppender
log4j.appender.HTML.File=application.html
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
log4j.appender.HTML.layout.Title=Application log
log4j.appender.HTML.layout.LocationInfo=true
log4j.appender.HTML.Append=false


# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n






Config.properties





Create configreader under framework and PropertyFileReader.java

















Create two classes-> DateTimeHelper.java & ResourceHelper.java under utility folder




















ResourceHelper.java

package com.cucumber.framework.utility;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class ResourceHelper {
public static String getResourcePath(String resource) {
String path = getBaseResourcePath() + resource;
return path;
}
public static String getBaseResourcePath() {
String path = System.getProperty("user.dir");
System.out.println(path);
return path;
            }
public static InputStream getResourcePathInputStream(String path) throws FileNotFoundException{
return new FileInputStream(ResourceHelper.getResourcePath(path));
            }
public static void main(String[] args) throws FileNotFoundException {
//System.out.println(ResourceHelper.getResourcePath("configfile/"+ "config.properties"));   
getBaseResourcePath() ;
            }}



PropertyFileReader.java

package com.cucumber.framework.configreader;
public class PropertyFileReader implements ConfigReader{
            private Properties prop = null;
            public PropertyFileReader() {
            prop = new Properties();
            try {
            prop.load(ResourceHelper.getResourcePathInputStream("/src/main/resources/configfile/config.properties"));
                        } catch (Exception e) {
                                    e.printStackTrace();
                        }}
            public String getUserName() {
                        return prop.getProperty("Username");
            }
            public String getPassword() {
                        return prop.getProperty("Password");
            }
            public String getWebsite() {
                        return prop.getProperty("Website");
            }
            public int getPageLoadTimeOut() {
                        return Integer.parseInt(prop.getProperty("PageLoadTimeOut"));
            }
            public int getImplicitWait() {
                        return Integer.parseInt(prop.getProperty("ImplcitWait"));
            }
            public int getExplicitWait() {
                        return Integer.parseInt(prop.getProperty("ExplicitWait"));
            }
            public String getDbType() {
                        return prop.getProperty("DataBase.Type");
            }
            public String getDbConnStr() {
                        return prop.getProperty("DtaBase.ConnectionStr");
            }
            public BrowserType getBrowser() {
                        return BrowserType.valueOf(prop.getProperty("Browser"));
            }




TestBase.java

package framework.TestBase;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;

import com.relevantcodes.extentreports.ExtentReports;

import cucumber.api.java.After;
import cucumber.api.java.Before;
import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
import framework.Configuration.Browser.BrowserType;
import framework.Configuration.Browser.ChromeBrowser;
import framework.Configuration.Browser.FirefoxBrowser;
import framework.Utility.Screenshots;
import framework.configReader.ObjectRepo;
import framework.configReader.PropertyFileReader;

public class TestBase {

public static WebDriver driver;
public static final Logger logger=Logger.getLogger(TestBase.class.getName());
public static ExtentReports extent;
public static com.relevantcodes.extentreports.ExtentTest extentlogger;

public WebDriver getBrowserObject(BrowserType bType) throws Exception {

try {

switch (bType) {

case Chrome:
ChromeBrowser chrome = ChromeBrowser.class.newInstance();
return chrome.getChromeDriver();

case Firefox:
FirefoxBrowser firefox = FirefoxBrowser.class.newInstance();
return firefox.getFirefoxDriver();

default:
throw new Exception(" Driver Not Found : " + new PropertyFileReader().getBrowser());
}
} catch (Exception e) {

throw e;
}
}

public void setUpDriver(BrowserType bType) throws Exception {

driver = getBrowserObject(bType);

driver.manage().window().maximize();

}

@Before()
public void before() throws Exception {
ObjectRepo.reader = new PropertyFileReader();
setUpDriver(ObjectRepo.reader.getBrowser());
String log4jpath=System.getProperty("user.dir")+"\\log4j.properties";
//System.out.println(log4jpath);

PropertyConfigurator.configure(log4jpath);

//*********************************************

}

 @After()
public void after(){

extent.flush();
       driver.quit();
}


public  TestBase(){

extent = new ExtentReports (System.getProperty("user.dir") +"/test-output/ExtentReport.html", true);

extent
                .addSystemInfo("Host Name", "SAGAR PC")
                .addSystemInfo("Environment", "Cucumber BDD Framework")
                .addSystemInfo("User Name", "Sagar Somaiah");
                extent.loadConfig(new File(System.getProperty("user.dir")+"\\src\\main\\resources\\ConfigFile\\extent-config.xml"));
}
 }



Loginpage

package framework.pageObject;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class Login {

WebDriver driver;

@FindBy(xpath="//input[@id='email']")
WebElement username;

@FindBy(xpath="//input[@id='pass']")
WebElement password;

@FindBy(xpath="//input[@value='Log In']")
WebElement submit;

public Login(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);

}

public void enterUsername(String username){
//log.info("clicked on sign in link...");
this.username.sendKeys(username);
}



public void enterPassword(String password){
//log.info("entering password...."+password);
this.password.sendKeys(password);
}
public void clickSubmit(){
this.submit.click();
}
}