Friday, July 20, 2018

AbstractScreen

@Slf4j  
 public abstract class AbstractScreen {  
   private static final Integer DEFAULT_TIMEOUT = 20;  
   static final String ANDROID_PKG_INSTLR_ID = "com.android.packageinstaller:id/";  
   static final String ANDROID_ID = "android:id/";  
   private final AppiumDriver driver;  
   private final EventFiringWebDriver eventFiringWebDriver;  
   private final FluentWait<WebDriver> wait;  
   private int scrollStart;  
   private int scrollEnd;  
   AbstractScreen(ScreenContext context) {  
     this.driver = getAppiumDriver(context);  
     this.eventFiringWebDriver = new EventFiringWebDriver(driver);  
     this.wait = initializeScreenAndGetWaitDriver();  
     registerListener(context);  
     computeAndSetScrollValuesForScreen();  
   }  
   private FluentWait<WebDriver> initializeScreenAndGetWaitDriver() {  
     this.driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);  
     PageFactory.initElements(new AppiumFieldDecorator(driver), this);  
     ////TODO-READ THIS COMMENT!  
     /*at this point the eventFiringWebDriver cannot use the decorator above for listening  
     * this is because the the iOSFindBy annotation with accessiblity tag sequentially checks for name even if  
     * you do not use it in your elements, causing the test to fail. When this issue is fixed change the above  
     * line to :  
     * PageFactory.initElements(new AppiumFieldDecorator(eventFiringWebDriver), this);  
     */  
     return new WebDriverWait(eventFiringWebDriver, DEFAULT_TIMEOUT)  
         .pollingEvery(1, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);  
   }  
   private AppiumDriver getAppiumDriver(ScreenContext context) {  
     Driver driver = context.getDriver();  
     log.info(driver.toString());  
     return driver.getAppiumDriver();  
   }  
   private void registerListener(ScreenContext context) {  
     eventFiringWebDriver.register(context.getErrorModalListener());  
   }  
   private void computeAndSetScrollValuesForScreen() {  
     Dimension dimensions = driver.manage().window().getSize();  
     Double screenHeightStart = dimensions.getHeight() * 0.5;  
     int scrollStart = screenHeightStart.intValue();  
     log.info("scrollStart : {}", scrollStart);  
     Double screenHeightEnd = dimensions.getHeight() * 0.2;  
     int scrollEnd = screenHeightEnd.intValue();  
     log.info("scrollEnd : {}", scrollEnd);  
     this.scrollStart = scrollStart;  
     this.scrollEnd = scrollEnd;  
   }  
   abstract public String getName();  
   abstract public boolean isDisplayed();  
   private WebElement getIfVisible(WebElement element) {  
     element = checkNotNull(element);  
     return wait.until(visibilityOf(element));  
   }  
   final boolean isElementDisplayed(WebElement element) {  
     try {  
       element = checkNotNull(getIfVisible(element));  
       return element.isDisplayed();  
     } catch (final Exception e) {  
       log.info("Element {} is not displayed due to {}", element, e);  
       return false;  
     }  
   }  
   final boolean areElementsDisplayed(List<WebElement> elements) {  
     elements = checkNotNull(elements);  
     return elements.parallelStream().allMatch(this::isElementDisplayed);  
   }  
   final void clickOnLink(WebElement element) {  
     clickOnElement(element);  
   }  
   final void clickOnText(WebElement element) {  
     clickOnElement(element);  
   }  
   final void clickOnLabel(WebElement element) {  
     clickOnElement(element);  
   }  
   final void clickOnCheckBox(WebElement element) {  
     clickOnElement(element);  
   }  
   final void clickOnButton(WebElement element) {  
     element = scrollTo(element);  
     element.click();  
     //checkForErrorModalAfterClick();  
   }  
   final void clickOnElement(WebElement element) {  
     element = scrollTo(element);  
     element.click();  
   }  
   ////TODO-READ THIS COMMENT!  
   /**  
    * This method is created as the listener does not work with iOSFindBy annotations  
    * This and it's usages should be deprecated in the future in preference of the listener  
    */  
   final void checkForErrorModalAfterClick() {  
     log.info("checking if error modal is present!");  
     WebElement elmErrorModal = null;  
     try {  
       elmErrorModal = driver.findElement(By.id("errorMessage"));  
       elmErrorModal = wait.until(visibilityOf(elmErrorModal));  
     } catch (final Exception e) {  
       log.info("Ignoring exception for error Modal check!");  
     }  
     //Adding "success" condition to prevent success GSMs from getting flagged  
     if (elmErrorModal != null && elmErrorModal.isDisplayed() && !elmErrorModal.getText().contains("Success")) {  
       throw new RuntimeException("Error modal with id errorMessage is displayed!");  
     }  
   }  
   final String getText(WebElement element) {  
     element = scrollTo(element);  
     return element.getText().trim();  
   }  
   final void populate(WebElement element, String text) {  
     element = scrollTo(element);  
     element.clear();  
     element.sendKeys(text);  
   }  
   final void hideKeyboard() {  
     try {  
       driver.hideKeyboard();  
     } catch (final Exception e) {  
       log.info("Keyboard is absent, hence ignoring exception." +  
           " Hack as appium has no method to check for keyboard");  
     }  
   }  
   private WebElement scrollTo(WebElement element) {  
     for (int counter = 0; !isElementDisplayed(element) && counter < 5; counter++) {  
       log.info("element not present loop count {}", counter);  
       driver.swipe(0, scrollStart, 0, scrollEnd, 2000);  
     }  
     return element;  
   }  
   final WebElement getElementContainingText(List<WebElement> elements, String text) {  
     List<WebElement> candidates = elements.parallelStream().  
         filter(i -> i.getText().contains(text)).collect(Collectors.toList());  
     if (candidates.size() == 1) {  
       return candidates.get(0);  
     }else if(candidates.size() > 1) {  
       throw new RuntimeException("More than one element with text " + text + " found!");  
     } else {  
       throw new RuntimeException("Element with text " + text + " not found!");  
     }  
   }  
 }  

cucumber step definition enhancements

@Slf4j  
 @ContextConfiguration(classes = Application.class)  
 @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)  
 public class SpringContextConfigurationSteps {  
   @Before  
   public void dummy() {  
     log.info("Used to load spring context for cucumber due to constraints! Not a real step definition!");  
   }  
 }  

Saturday, August 13, 2016

sample pom

<?xml version="1.0" encoding="UTF-8"?>  
 <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.mridul.auotmation.webservices</groupId>  
   <artifactId>WeatherAPI</artifactId>  
   <version>1.0-SNAPSHOT</version>  
   <properties>  
     <java>1.8</java>  
     <maven.compiler>3.5.1</maven.compiler>  
     <maven.failsafe>2.19.1</maven.failsafe>  
     <maven.failsafe.parallel>methods</maven.failsafe.parallel>  
     <maven.failsafe.threadcount>10</maven.failsafe.threadcount>  
     <apache.cxf>3.1.7</apache.cxf>  
     <serenity.core>1.1.36</serenity.core>  
     <serenity.maven.plugin>1.1.36</serenity.maven.plugin>  
     <serenity.junit>1.1.36</serenity.junit>  
     <serenity.spring>1.1.36</serenity.spring>  
     <google.guava>19.0</google.guava>  
     <spring.boot.web>1.4.0.RELEASE</spring.boot.web>  
   </properties>  
   <dependencies>  
     <!--core java specific libraries-->  
     <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->  
     <dependency>  
       <groupId>com.google.guava</groupId>  
       <artifactId>guava</artifactId>  
       <version>${google.guava}</version>  
     </dependency>  
     <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot -->  
     <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->  
     <dependency>  
       <groupId>org.springframework.boot</groupId>  
       <artifactId>spring-boot-starter-web</artifactId>  
       <version>${spring.boot.web}</version>  
     </dependency>  
     <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-frontend-jaxrs -->  
     <dependency>  
       <groupId>org.apache.cxf</groupId>  
       <artifactId>cxf-rt-frontend-jaxrs</artifactId>  
       <version>${apache.cxf}</version>  
     </dependency>  
     <!--Serenity plugins-->  
     <!-- https://mvnrepository.com/artifact/net.serenity-bdd/serenity-core -->  
     <dependency>  
       <groupId>net.serenity-bdd</groupId>  
       <artifactId>serenity-core</artifactId>  
       <version>${serenity.core}</version>  
     </dependency>  
     <!-- https://mvnrepository.com/artifact/net.serenity-bdd/serenity-junit -->  
     <dependency>  
       <groupId>net.serenity-bdd</groupId>  
       <artifactId>serenity-junit</artifactId>  
       <version>${serenity.junit}</version>  
     </dependency>  
     <!-- https://mvnrepository.com/artifact/net.serenity-bdd/serenity-spring -->  
     <dependency>  
       <groupId>net.serenity-bdd</groupId>  
       <artifactId>serenity-spring</artifactId>  
       <version>${serenity.spring}</version>  
     </dependency>  
     <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-failsafe-plugin -->  
     <dependency>  
       <groupId>org.apache.maven.plugins</groupId>  
       <artifactId>maven-failsafe-plugin</artifactId>  
       <version>${maven.failsafe}</version>  
     </dependency>  
   </dependencies>  
   <build>  
     <plugins>  
       <plugin>  
         <groupId>org.apache.maven.plugins</groupId>  
         <artifactId>maven-compiler-plugin</artifactId>  
         <version>${maven.compiler}</version>  
         <configuration>  
           <source>${java}</source>  
           <target>${java}</target>  
         </configuration>  
       </plugin>  
       <plugin>  
         <groupId>org.apache.maven.plugins</groupId>  
         <artifactId>maven-failsafe-plugin</artifactId>  
         <version>${maven.failsafe}</version>  
         <configuration>  
           <parallel>${maven.failsafe.parallel}</parallel>  
           <threadCount>${maven.failsafe.threadcount}</threadCount>  
           <includes>  
             <include>**/features/**/When*.java</include>  
           </includes>  
         </configuration>  
       </plugin>  
       <plugin>  
         <groupId>net.serenity-bdd.maven.plugins</groupId>  
         <artifactId>serenity-maven-plugin</artifactId>  
         <version>${serenity.maven.plugin}</version>  
         <executions>  
           <execution>  
             <id>serenity-reports</id>  
             <phase>post-integration-test</phase>  
             <goals>  
               <goal>aggregate</goal>  
             </goals>  
           </execution>  
         </executions>  
       </plugin>  
     </plugins>  
   </build>  
 </project>  

Friday, August 5, 2016

TestWebAuthorHelp

package com.mridul.framework.selenium.tests;  
 import com.mridul.framework.selenium.pages.LoginPage;  
 import org.testng.annotations.Test;  
 import static org.testng.Assert.assertNotNull;  
 /**  
  * Created by Mridul on 3/16/2016.  
  */  
 public class TestWebAuthorHelp extends AbstractTest{  
   @Test(enabled = true, groups = "prerequisite") //, dependsOnMethods = {"testURLToDash"} )  
   public void testLoginToDashFluently(){  
     try {  
       loginPage = new LoginPage(driver);  
       assertNotNull(loginPage);  
       homePage=loginPage.navigateToURL(expectedURL).and().typeInUserId("UserId")  
           .and().typeInPassword("Password").and().then().clickOnSubmitButton();  
       assertNotNull(homePage);  
     }catch (Exception e){  
       System.out.printf("Exception thrown : %s%n", e);  
     }  
   }  
   @Test(enabled = true, dependsOnMethods = {"testLoginToDashFluently"}, groups = "prerequisite" )  
   public void testWebAuthorHelpModal(){  
     try {  
       webAuthorHelpModal=homePage.clickOnWebAuthorHelp();  
       assertNotNull(webAuthorHelpModal);  
     }catch (Exception e){  
       System.out.printf("Exception thrown : %s%n",e);  
     }  
   }  
   @Test(enabled = true, dependsOnMethods = {"testWebAuthorHelpModal"}, dependsOnGroups = "prerequisite")  
   public void testOpenWebAuthorHelp(){  
     try {  
       webAuthorHelpModal.selectPleaseChooseACategory("Company Directory")  
           .and().selectNatureOfRequest("Terminated User showing in directory")  
           .and().fillInRequestDetails("Testing WebAuthor Help")  
           .and().fillInNotesOrComments("Testing POC for WebAuthor Help")  
           .and().clickOnOrderNowButton()  
           .and().clickOnSubmitOrder();  
     }catch (Exception e){  
       System.out.printf("Exception thrown : %s%n%n", e);  
       e.printStackTrace();  
     }  
   }  
 }  

TestReportAnIssue

package com.mridul.framework.selenium.tests;  
 import com.mridul.framework.selenium.pages.LoginPage;  
 import static org.testng.Assert.*;  
 import org.testng.annotations.Test;  
 /**  
  * Created by Mridul on 3/10/2016.  
  */  
 //@ContextConfiguration(classes = ApplicationConfig.class)  
 public class TestReportAnIssue extends AbstractTest{  
   //Fluent tests  
   @Test(enabled = true, groups = "prerequisite") //, dependsOnMethods = {"testURLToDash"} )  
   public void testLoginToDashFluently(){  
     try {  
       loginPage = new LoginPage(driver);  
       assertNotNull(loginPage);  
       homePage=loginPage.navigateToURL(expectedURL).and().typeInUserId("UserId")  
           .and().typeInPassword("Password").and().then().clickOnSubmitButton();  
       assertNotNull(homePage);  
     }catch (Exception e){  
       System.out.printf("Exception thrown : %s%n", e);  
     }  
   }  
   @Test(enabled = true, dependsOnMethods = {"testLoginToDashFluently"}, groups = "prerequisite" )  
   public void testReportAnIssueModal(){  
     try {  
       reportAnIssueModal=homePage.clickOnReportAnIssue();  
       assertNotNull(reportAnIssueModal);  
     }catch (Exception e){  
       System.out.printf("Exception thrown : %s%n",e);  
     }  
   }  
   @Test(enabled = false, dependsOnMethods = {"testReportAnIssueModal"} , dependsOnGroups = "prerequisite")  
   public void testReportAnIncidentWithoutUnlistedUser(){  
     try {  
       reportAnIssueModal.and().fillInRequestedBy("MRIDUL JAYAN")  
           .and().fillInCallbackNumber("1111111111")  
           .and().selectAnyBusinessUrgency()  
           .and().selectAnyBusinessImpact()  
           .and().selectAnyTypeOfIssue()  
           .and().selectAnyCategory()  
           .and().fillInPleaseDescribeYourIssue("Testing Portal")  
           .and().clickOnSubmitButton();  
       assertNotNull(reportAnIssueModal);  
     }catch (Exception e){  
       System.out.printf("Exception thrown : %s%n%n", e);  
       e.printStackTrace();  
     }  
   }  
   @Test(enabled = false, dependsOnMethods = {"testReportAnIssueModal"}, dependsOnGroups = "prerequisite" )  
   public void testReportAnIncidentWithUnlistedUser(){  
     try {  
       reportAnIssueModal.  
           and().fillInRequestedBy("MRIDUL JAYAN").  
           and().fillInCallbackNumber("1111111111").  
           and().checkUnlistedUser().  
           and().fillInUnlistedContactName("MRIDUL JAYAN").  
           and().fillInUnlistedContactEmail("test@testmail.com").  
           and().selectAnyBusinessUrgency().  
           and().selectAnyBusinessImpact().  
           and().selectAnyTypeOfIssue().  
           and().selectAnyCategory().  
           and().fillInPleaseDescribeYourIssue("Testing Portal").  
           and().clickOnSubmitButton();  
       assertNotNull(reportAnIssueModal);  
     }catch (Exception e){  
       System.out.printf("Exception thrown : %s%n%n", e);  
       e.printStackTrace();  
     }  
   }  
   @Test(enabled = true, dependsOnMethods = {"testReportAnIssueModal"}, dependsOnGroups = "prerequisite")  
   public void testReportAnIncidentWithUnlistedUserUsingSpecificText(){  
     try {  
       reportAnIssueModal.  
           and().fillInRequestedBy("MRIDUL JAYAN").  
           and().fillInCallbackNumber("1111111111").  
           and().checkUnlistedUser().  
           and().fillInUnlistedContactName("MRIDUL JAYAN").  
           and().fillInUnlistedContactEmail("test@testmail.com").  
           and().selectBusinessUrgency("Short amount of time").  
           and().selectBusinessImpact("Small business impact").  
           and().selectTypeOfIssue("Hardware").  
           and().selectCategory("Printer").  
           and().fillInPleaseDescribeYourIssue("Testing Portal").  
           and().clickOnSubmitButton();  
       assertNotNull(reportAnIssueModal);  
     }catch (Exception e){  
       System.out.printf("Exception thrown : %s%n%n", e);  
       e.printStackTrace();  
     }  
   }  
 }  

AbstractTest

package com.mridul.framework.selenium.tests;  
 import com.mridul.framework.selenium.modals.WebAuthorHelpModal;  
 import com.mridul.framework.selenium.pages.HomePage;  
 import com.mridul.framework.selenium.pages.LoginPage;  
 import com.mridul.framework.selenium.modals.ReportAnIssueModal;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.testng.annotations.*;  
 import static org.testng.Assert.assertNotNull;  
 /**  
  * Created by Mridul on 3/11/2016.  
  */  
 public abstract class AbstractTest {  
   protected WebDriver driver;  
   protected LoginPage loginPage;  
   protected HomePage homePage;  
   protected ReportAnIssueModal reportAnIssueModal;  
   protected WebAuthorHelpModal webAuthorHelpModal;  
   public String expectedURL="https://www.google.com";  
   //@BeforeSuite(enabled = true)  
   @BeforeTest(enabled = true)  
   public void setUp() {  
     ////TODO-Fix spring injection  
     System.setProperty("webdriver.chrome.driver", "src/main/resources/drivers/chromedriver.exe");  
     driver = new ChromeDriver();  
 /*  
     System.setProperty("webdriver.ie.driver", "src/main/resources/drivers/IEDriverServer.exe");  
     driver = new InternetExplorerDriver();*/  
   }  
   @AfterTest(enabled = false)  
   public void closePage(){  
     loginPage.closePage();  
   }  
   @AfterSuite(enabled = false)  
   public void tearDown() {  
     if (driver != null) {  
       driver.quit();  
     }  
   }  
 }  

ExtentReporterNG

package com.mridul.framework.selenium.reports;  
 import com.relevantcodes.extentreports.ExtentReports;  
 import com.relevantcodes.extentreports.ExtentTest;  
 import com.relevantcodes.extentreports.LogStatus;  
 import org.testng.*;  
 import org.testng.xml.XmlSuite;  
 import java.io.File;  
 import java.util.Calendar;  
 import java.util.Date;  
 import java.util.List;  
 import java.util.Map;  
 /**  
  * Created by Mridul on 3/16/2016.  
  */  
   public class ExtentReporterNG implements IReporter {  
     private ExtentReports extent;  
     @Override  
     public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {  
       extent = new ExtentReports(outputDirectory + File.separator + "ExtentReportTestNG.html", false);  
       for (ISuite suite : suites) {  
         Map<String, ISuiteResult> result = suite.getResults();  
         for (ISuiteResult r : result.values()) {  
           ITestContext context = r.getTestContext();  
           buildTestNodes(context.getPassedTests(), LogStatus.PASS);  
           buildTestNodes(context.getFailedTests(), LogStatus.FAIL);  
           buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);  
         }  
       }  
       extent.flush();  
       extent.close();  
     }  
     private void buildTestNodes(IResultMap tests, LogStatus status) {  
       ExtentTest test;  
       if (tests.size() > 0) {  
         for (ITestResult result : tests.getAllResults()) {  
           test = extent.startTest(result.getMethod().getMethodName());  
           test.getTest().setStartedTime(getTime(result.getStartMillis()));  
           test.getTest().setEndedTime(getTime(result.getEndMillis()));  
           for (String group : result.getMethod().getGroups())  
             test.assignCategory(group);  
           String message = "Test " + status.toString().toLowerCase() + "ed";  
           if (result.getThrowable() != null)  
             message = result.getThrowable().getMessage();  
           test.log(status, message);  
           extent.endTest(test);  
         }  
       }  
     }  
     private Date getTime(long millis) {  
       Calendar calendar = Calendar.getInstance();  
       calendar.setTimeInMillis(millis);  
       return calendar.getTime();  
     }  
 }