Thursday, 29 April 2021

TestNG Library

 package MavenTestNG;


import java.io.BufferedInputStream;

import static org.openqa.selenium.support.locators.RelativeLocator.withTagName;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.util.ArrayList;

import java.util.Base64;

import java.util.Collections;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Properties;

import java.util.Set;

import java.util.concurrent.TimeUnit;

import java.util.stream.Collectors;


import org.apache.commons.io.FileUtils;

import org.apache.commons.mail.DefaultAuthenticator;

import org.apache.commons.mail.Email;

import org.apache.commons.mail.EmailException;

import org.apache.commons.mail.SimpleEmail;

import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

import org.apache.pdfbox.pdmodel.PDDocument;

import org.apache.pdfbox.text.PDFTextStripper;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.CellType;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.util.NumberToTextConverter;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.Keys;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.Platform;

import org.openqa.selenium.StaleElementReferenceException;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.WindowType;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import org.openqa.selenium.interactions.Actions;

import org.openqa.selenium.remote.CapabilityType;

import org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.Select;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.testng.Assert;

import org.testng.annotations.AfterClass;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.AfterSuite;

import org.testng.annotations.AfterTest;

import org.testng.annotations.BeforeClass;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.BeforeSuite;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.Test;

import org.testng.asserts.SoftAssert;


import POMFrameworkPages.LoginPage2;

import de.redsix.pdfcompare.PdfComparator;

import io.github.bonigarcia.wdm.WebDriverManager;


/* FEW JAVA CODE TIPS

 1.class name should start with CAPS letter and first word letter should be uppercase/

 2.variable name should start with LOWER case letter and camel case format as example totalSumValue

 3.Alignment of source code using Ctrl+Shift+F or select all content and Ctrl+I for indent

 4. Debugging code- execute code step by step - Debug as-TestNG or Java application-script will stop at debug point

Step over F6- executes and moves to next step

Resume F8- directly goes to next breakpoint, else it will execute entire code

Step Into F7- debugging goes to inside method block, if you want to check method codes step by step 

5.Crete Outer for loop to get matching condion and then create inner for loop to perform action 

6. Covert array to array list for easy search using contains method 

7. Split method will used to to break text from given text/attribute into 2 values as indexes. getText().split("-")

8. trim() method will trim the given text string formatedName= name[0].trim();

9. We will use length() method to get size of an Array & size() method to get size of an ArrayList

10. Synchronizartion methods in selenium

  a)ImplicitWait(3000)--its a global wait time for max wait of 3 sec, if element loads before then continue 

b) ExplicitWait(5000)--its indiviudal element specific wait to forcefully till given 5 sec time.

c) Thread.sleep(2000)--java method-to pause execution till max given time

d) fluent.wait() --


 PRACTICE WEBSITE URLs: TEST WEBSITES

 http://the-internet.herokuapp.com/

 https://rahulshettyacademy.com/AutomationPractice/

 https://the-internet.herokuapp.com/ [ examples for windows Auth, popup etc]

 http://autoitscript.com  [official website]

 http://www.itgeared.com/demo/1506-ajax-loading.html [Ajax loader to implement webdriverwait method]

 https://rahulshettyacademy.com/dropdownsPractise/

 https://freeformatter.com/json-escape.html  [This website will be used for String to escape string]

 

======== JMETER Reference websites: =====================================================================

Sample web applications to practice Jmeter:

https://the-internet-herokuapp.com/login

https://blazedemo.com/purchase

https://newtours.demoaut.com/index.php

rexegg.com/regex-quickstart.html

https://a.blazemeter.com  //to analyse .jtl execution results in proper view

https://blazemeter.com/bog/3-easy-ways-to-monitor-jmeter-non-gui-test-results

 */



/*

 ****************TESTNG ANNOTATIONS -HELPER ATTRIBUTES

 TESTNG XML FORMAT:

testNG.xml - right click and run as testNG Suite to execute multiple cases together.

<SUITE

<test 

<classes>

<class name="packagename.class"/>

<method>

<method name="methodname"/>

</method>

</classes>

</test>

</SUITE>


Define multiple tests under single class 

You can modularise the test cases based on category/functionality 


TEST SUITE - TEST FOLDER (MODULE) - TEST CASES(CLASS)

 ***INLCUDE-EXCLUDE test cases to execute

****EXCLUDE TAG in TestNGXML to skip methods:SKIP 1 Test case/Method from test cases suite - 

<classes>

<class name="class.smoketests"/>

<methods>

<exclude name="registerTestCase"/>

</methods>

</classes>

 ****INCLUDE TAG in TestNGXML to skip methods:SKIP 1 Test case/Method from test cases suite - 

<classes>

<class name="class.smoketests"/>

<methods>

<include name="registerTestCase"/>

</methods>

</classes>


 ****SKIP CASES to execute BASED ON TEST CASE NAME

Naming convension of test cases are based on modulename

<classes>

<class name="class.smoketests"/>

<methods>

<exclude name= "Mobile.*"/>

<include name= "API.*"/> //If you want to include all test cases starts with API%...

<method/>

<class/>

<classes/>



 ***EXECUTE ALL CASES from package by mentioning package name 

<packages>

<package name ="packagename"/>

<packages/>


 *** GROUPING TEST CASES AND EXECUTE USING TESTNG XML 

first tag the cases with groups and second mention grouping in TestNG.xml file

@Test(groups={"smoke"})  //method level categorisation 

Add below syntax in TestNG.xml file to execute all smoke taged cases :

<groups>

<run>

<include name="smoke"/> //to include grouped cases to execute 

</run>

</groups>



<groups>

<run>

<exclude name="smoke"/> //To exclude grouped cases to execute 

</run>

</groups>


 *** PRIORITY - will defines the execution order of test cases 


 *** Groups will define to group the similar cases & execute using in TestNG.xml


 *** dependsOnMethods will make sure those mentioned cases executed before execute current case.

@Test(priority = 5, groups = "Demo", dependsOnMethods = "loginTest" , "RegisterTest") //we can mention multiple dependant tests

@Test(priority = 4, groups = "Demo", dependsOnMethods = "loginTest")


 *** ENABLED=TRUE; ENABLED=FALSE (TestNG helper attribute)to control case level execution 

@Test(enabled=true) - include/on to execute case 

@Test(enabled=false) - exclude/off to execute case 


 **** TIMEOUT attribute 

@Test(timeOut=4000) //milli seconds will wait to get timed out of case execution 


 *****PARAMETERIZING USING TESTNG.XML /GLOBAL ENVIRONMENT LEVEL 

A] Parameters annotation will bring testNG.xml given parameters into the tests 

We can define parameters at suite level or class level

--XML declaration syntax

<parameter name="URL" value="qaclickacademy.com">

<parameter name="username" value="hellouser">


---Test case level syntax to call above parameters 

@Parameters({"URL"})//single parameters retrieval

@Test

public void webLogin(String urlValue){

System.out.println(urlValue);}


@Parameters({"URL", "username"}) //multiple parameters retrieval

@Test

public void webLogin(String urlValue){

System.out.println(urlValue);

System.out.println(username);}


***********SELENIUM POSSIBLE EXCEPTIONS:

1.Path to the driver executable must be set by the webdriver

When browser path was not given


2.Driver executable is does not exist

When browser path is incorrect path 

Use with official latest browser driver based on supported OS 


3. REFER  25-26 JAVA lessons

Go to chrome browser-inspecct element-go to console tab and enter $x("mention xpath here)

$x("XPATH")

$("CSSVALUE")

in chrome show as Lenth=1 means 1 object exist. If not it shows error as "Element is not present in the page as eror"


Attribute = Value

class=inputtext

id=email

**Xpath can be defined in number of ways


*********Customised XPath..CSSSelctor 

//tagName[@attribute='value']

//input[@id='email']

//input[@type='email']-Xpath syntax


$x("//input[@type='email']")- validate Xpath

$("//input[@type='email']")-validate CSS selector


//input[@type='email']

//*[@type='email']-regualr expression 

**Customised CSS from html attributes

tagName['attribute=value'] -CSS syntax

['attribute=value'] -CSS syntax

input[@id='email'] -CSSselector attribute value 

$("input[@id='email']")-validate CSS selector path


https://rahulshettyacademy.com/dropdownsPractise/


****************************************************************************

RAHUL DEMO**



*************************************************************************


 **********PARAMETERIZING MULTIPLE DATA SETS (METHOD LEVEL) USING DATA PROVIDER ANNOTATION

First creae data provider block which can be called to any test from the class, then use this in tests

@DataProvider

public object[][] getData(){ //use multiple data from data provider-data set)

//define multidimentional array based on combinations 3 rows 2 columns

Object [] [] data = new Object[3][2];

//set-1

data[0][0]="firstusername";

data[0][1]="password1"; //columns for the row is value

//set-2

data[1][0]="secondusername";

data[1][1]="password2";

//set-3

data[2][0]="thirdusername";

data[2][1]="password3";  

return data;  //return to pass the value to object 

}


Now use data provider at test level as below SYNTAX

@Test(dataprovider="getData")

public void webLogin(String username, String password){

System.out.println("username");

System.out.println("password");}


 *********** TESTNG LISTENERS ***********

listens and invoke expected methods to perform expected actions to run activate after/before tests

LISTENERS:

ITestListerners interface which implements TestNG listeners 

These methods will be invoked based defined condition test is fail or pass


We need to tell TesNG.xml where lister class is located -syntax to be updated in TestNG.xml file

<listeners>

<listener class-name="test.listeners"/>

<listeners/>


We can pull the passed/failed test name in result using ItestResult class:

System.out.println("I failed and executed listener code" + result.getName());

//this will get back the failed test case name also 


PARRELEL EXECUTION USING TESTNG XML FILE:

add suite level information with below syntax which test/how many tests need parellel execution

<suite name="Loan Module" parellel="tests" thread-count=2>

TEST-OUTPUT folder -refresh index.html file will show the TESTNG REPORT


GLOABAL ENVIRONMENT VARIABLES using PROPERTIES FILE (.properties file)

Creat file - Data.properties as extension will allow the Java to use utiltiies

get properties file values into the code 

Properties class will scan properties mentioned in the .properties files

We need to mention the file path and pass to object 


Properties prop=new Properties();

FileInputStrem fis=new FileInputStrem("c://data.properties");

//file input stream class-fis will be used to load the file in read mode

prop.load(fis); //load method will used to read the data 

System.out.println(prop.getProperty("browser"));//output is chrome coming from property file

We can change property in runtime using SetProperty method

prop.setProperty("browser", "firefox");

System.out.println(browser"); //output is firefox which is runtime value 


To update value in property file after runtime we will use to load File in write mode

FileOutputStream fos=new FileOutputStream("path of file");

prop.store(fos,null); //store method will used to update the data in file.



==============**********MAVEN*********==================

1 Maven can be use to maintain, manage the projects , build management tool. 

a) Cantral repository to get dependencies from mvn repo (jar files, libraries) [mavenrepository.com]

b) Flexible to integrate with CI tools(Jenkins etc)

c) maintaining common structure/templates across organization

d) plugins for test framework execution


2. install maven

Go to download maven- download binary file and install, once done, then map environment variable


3. Set system variables

MAVEN_HOME with path (C:\Apache-maven-3.5.4-bin\apache-maven-3.5.4)

Then add above maven location till bin path to the PATH variable also

(C:\Apache-maven-3.5.4-bin\apache-maven-3.5.4\bin)

Go to CMD - mvn --version , It should display the installed maven version


4. Understand maven terminologies:

a) ArtficatID (sub project)- It is a file, usually a JAR, that gets deployed to maven repo.

b) GroupId (main head)-It will identify your project uniquely acrosss all projects

c) Archetype:generate a new proj from an archetype 

Refer maven in 5 minutes URL [https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html]

We can clone project using groupID and Artifct ID.


5. Creating maven project in Eclipse 

Right click- new- project -selct maven folder - select Maven Project-

selct teamplate (quickStart)1.1 and click next- 

Enter groupID- proj unmrella (QAAcademy)

Artifact ID- sub project name (MavenProj), package - QAAcademy


Src/Main/Java folder- To add utilities, reusable components

Src/Test/java folder-To add Automation test cases

POM.xml- add dependancies 


6. Add dependancies in maven POM file

Selenium java 3.6.0

TestNG 6.11

restAssured 3.0.5

appium 5.0.4

maven sure fire plugin


7. Add -apache MAVEN SURE FIRE plugin  2.20.1 ABOVE THE DEPENDACIES

this will be used to execute all test cases under src/test/java folder


8. RUN test cases using maven commands

go to CMD at project level(where POM is resided) folder and execute below mvn commands

a) mvn clean - delete all temp files and cleans project 

BUID SUCCESS 


b) mvn compile - to check all test cases/code syntax are correct?

BUILD SUCCESS - no syntax errors


c) mvn test - triggers test execution by maven (from project level CMD screen)

even if you run this mvn test; it also runs clean, compile in background before execution starts

It will read local sytem -for dependencies, jars are exist or not, go to .m2 folder for available jars availability

and brings the required jars, if they not available.

TESTS

BUILD SUCCESS


***NOTE: maven expectes test cases and file name should be Test at end of the file name- MAVEN algorithm will see the Test word to consider and execute cases from those files.

APITest.java


*** TESTNG Integration with MAVEN ************

a) create testNG xml file for all the test cases

Project folder- right click -TestNG-ConvertTo TestNG- Next -Finish - testNG.xml will be created.


b) execute testng.xml from Maven using suiteXmlFiles tag of firesure plugin

add config tag and update with TestNG xml path in FIRE SURE PLUGIN dependancy 

//NOTE, if we remove below tags from fire sure plugin-then maven will concider all test cases and execute

<configuration>

<suiteXmlFiles>

<suiteXmlFile>testmg.xml</suiteXmlFile>

</suiteXmlFiles>

</configuration>


c) Running a single Test

maven allows to run single test case using test property to specific test case  

mvn -Dtest=TestCircle test

mvn -Dtest=Testcase/filename test [SYNTAX]


d) MAVEN PROFILING to SWITCH TESTS

Profiles can be created in POM.xml with run mvn commands in below SYNTAX

mvn test -PRegression  -this will run only regression test cases alone

mvn test -PSmoke   -this will run only smoke test cases alone


<profiles>

<profile>

<id>Regression</id>

<build>

-----

------surefire plugin, suiteXML etc..

<builb/>

\<profile>

</profiles>



******** MAVEN INTEGRATION WITH JENKINS*********

1. Importance of JENKINS

a continuous integration development tool for automating repeated items, builds, push code, 

If you have 500 test cases to execute without manual intervension, we will use Jenkins to schedule jobs and trigger jobs for execution.

Schedule a maven command to trigger at specific scheduled time.


Jenkins runs on its own server, we need to configure TestNG, Maven versions to Jenkins

to maintain consistency, Jenkins will support for all versions.

We can share the results to the team once execution is completed.


2. JENKINS INstallation 

DevOps guys will setup servers and install Jenkins.

Jenkins download-->  download jenkins software file "Generic Java package(.war)"

goto CMD at jenkins war file path location and run command below

C:\work>java -jar jenkins.war

C:\work>java -jar jenkins.war -httpPort-9090   

Or 

C:\work>java -jar jenkins.war -httpPort-8080

It will start initialization - JENKINS IS FULLY UP AND RUNNING

localHost:9090/login?from=%2F   [open this url to access Jenkins UI]

admin credentials -enter - navigate to home page .



3. Configure global settings

MAVEN, JAVA need to setup with JENKINS

Mange jenkins- Global Tool Configuration --

JDK section click on- JDK installations 

enter JAVA_HOME path here (system variable path)

Select checkbox if you want to intall java by Jenkins in your system.

Maven section - click on Add Maven

enter Maven_HOME path whcih is from your system 

GIT- check if git details required

Click SAVE= 




4. Understanding Jenkins Workspace

Place maven project in Jenkins directory 

New Item- select FreeStyle Project- click OK- open job config window

enter Maven project details

Bring project code from SVN/GITHUB -then jenkins will get the code from the source .


GENERAL tab  

Advanced- use custom workspace -copy projec path and place that project into jenkins home directory

${JENKINS_HOME}/Mavenjava


BUILD TRIGGERS Tab:


BUILD ENVIRONMENT TAB:

Go to BUILD- Add bulild setup --> Invoke top-level Maven targets 

Enter Maven version/select , enter GOAL as test-PRegression

-click save profile. job will be created.

Now go to dashboard and click on BUILD NOW menu -then build will be created and started.

Consol Output- give all build details will show 


use below statement for GOALS textbox- for API JOB Trigger:

mvn is optional as maven already configured

test verify -Dcucumber.options="--tags @AddPlace" 


When job has parameters then BUILD NOW link will become as BUILD WITH PARAMETERS

Select build with parameters - then at build section mention GOALS as below:

test verify -Dcucumber.options="--tags @"$tag""

Jenkin will look for the parameters when it observed $ symbol.. then respective values to be listed under dropdown.

given parameters will be listed in dropdown to selection then build will happen.



5. Configuring Jenkins job parameters


6. Post Build action plugins


7. TestNG Jenkins plugin to generate Reports

Mange Jenkins- mange plugins - tab 

search testNG Results plugin - click install without restart & then restart Jenkins server

SUCESS instalation 

Open JOB - 

CONFIGURE- 

POSTBUILD ACTIONS- select Publish TestNG Resi;ts.


8. Scheduling Jenkins builds

JENKINS Expect below parameters to schedule a job/cron expression 

a) MINUTES- minutes in one hour (0-59)

b) HOURS -Hours in a day (1-31)

c) DAYMONTH- Day in month (1-31)

d) MONTH - month of the year (1-12)

e) DAYWEEK -day of the week (0-7) 

M H D M DAYWkkk

10 6 * * *  [* MEANS EVERYDAY]


**PARAMETRIZING JENKINS TO RUN WITH MULTIPLE BROWSERS:

maven command: [without using prop file -browser value]

mvn -Dbrowser=chrome   //D-parameter name=value

This can able to control browser in maven command while executing code without updating in prop file.

mvn test -Dbrowser=chrome // this mv ncmd will trigger execution in chrome

mvn test -Dbrowser=firefox 


String browserName=System.getProperty("browser") //code will check if any property defined from maven

CHECKBOX-This project is parameterized

name= browser ; choices = chrome, firefox, safari etc- save project in jenking job.

When you open project -then it will show browser dropdown with above configured browser names.

GOAL input update as test-DbrowserName="$browser"  [//$ refers Jenkins variables defined in project]



Build Now- 


<profiles>

<profile>

<id>RegressionTesting</id>

<build>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-surefire-plugin</artifactId>

<version>2.18.1</version>

<configuration>

<suiteXmlFiles>

<suiteXmlFile>Regression.xml</suiteXmlFile>

</suiteXmlFiles>

</configuration>

</plugin>

</plugins>

</build>

</profile>

</profiles>

======================================


********CONDING/CODE OPTIMIZATION STANDARDS********

1.private variables are restricted to local class &  cannot be accessed in other classes via inheritance..

2.So, variable should be declared as private to donot access in other classes

3.Public methods & private variables will be a good practice/prog technique.

4.Remove hardcoded path from the framework [use as "user.dir" while giving file path]

//System.getProperty(user.dir)+"//reprots//data.properties";  //will gives current project path

5.copy chromedriver in resources and give the project folder path and use in scripts

6. consolidation of test cases and classes

group/club all relavant test cases into single class and use existing browser session will be used to validate for all tests.



********HEADLESS BROWSER EXECUTION********

Executing test case without opening browser is headless browser execution

This will improves performance as we not using browsers

We can run in Jenkins as well with headless browser


ChromeOptions is class - we can inject driver and tell headless

System.SetProperty("webDriver.chromeDriver", "C://chromeDriver.exe");

ChromeOptions options=new ChromeOptions();

options.addArguments("headless");  //This will behaves as headless chrome browser


*************INHERITANCE /INTERFACES in FRAMEWORK

Can driver can be static OR non-static? -static variable/method/class can be accessed anywhere in projects

sometimes if execution is parallel-then will create few problems and variables will be overwriiten.

static declaration will consumes memory for each allocation and override variables and will get nullpointer exception



extends-keyword for inheritence

Implements -keyword for interface 

======================================

*********CUCUMBER FRAMEWORK -BDD- Behavioural Driven Development--

BDD SYNTAX: FEATURE FILE: with scenarios

GIVEN an account with zero balance - prerequisite

WHEN I paid with creditcard for payment - action

THEN -I should get error message - validation


BDD Advantages:

All team will follow the same template with clear business language

Each scenario will reflects a busines value

We can estimate test and business outcome by the template value

We can Tag annotations to selenium and execute business cases 

Common template for manual and automation testing


***CUCUMBER INSTALLATION:

1.Download Java, Eclipse and update system environment variables

2.Download Cucumber/Natural plugin to support GERKIN language

Natural 0.7.6 from eclipse marketplace and install -restrat eclipse.

3.Cucumeber expects standard skeleton to process/udpate cases obtained by maven.

4.Create a Maven project with quickStart template 

5.src/test package -to create test cases 

6.Add cucumber jars to the pom.xml [cucumber-java, cucumber-junit 3.8.11]

7.create a FEATURES package and create FEATURE file with business scenarios (.feature files).

8.create a STEP DEFINITIONS package (src/test) and create a stepDefinition class

build step def implementation code with proper standard @Given("^TEST$")

integrate java code for the actions to be performed.

Use chrome plugin (Tidy Gherkin) to generate   gherkin code

9. Create CUCUMBEROPTIONS package and create a TESTRUNNER class file

here we need to pass Feature file, step definition parameters -to serach and trigger for feature file execution.

Both Featurefiles and stepdefinitions must be under same parent


@RunWith(Cucumber.class)

@CucmberOptions(  

features="path of features package"

glue="path of stepdefinitions package"

)

//takes 2 inputs of feature and step definition)


10.Regular expressions for different data but same implementation

11. Arguments should match with regular expression values

12.



FEATURE -update with business scenario

if scenario has value as "xyz" then cucumber assumes it is dynamic value ( regular expression can be used for implementation)

as parameter 

STEPDEFINITION- with respect to feature -we will include code

TESTRUNNER- this will trigger the execution using featurefile and step definition steps


*** JUnit to TestNG -Cucumber integration-

add cucumber-testing 1.2.5 jar to the maven POM (inof.cukes)

public class TestRunner extends AbstractTestNGCucumberTests{

}


============*******EXTENT REPORTS***================

********1] Extent Reports

Get Extent reports related dependencies and add to the POM.XML file

extentreports 4.1.3

testNG dependancy 

selenium java 


What are extent reports?

Creating extent reports for standalone single test 

Generate extent reports for parellel test execution

Attaching screenshot to reports for failed tests using TestNG Listeners


@BeforeTest method to add extent reports class

//ExtentReports , ExtentSparkReporter

 ExtentSparkReporter- this helper class is responsible to create html report file and place in specified directory path

reporter object can used lot methods to change report name etc

setReportName()-

setDocumentTitle()-


ExtentSparkReporter- main class to attach report 

attachReporter()- 

setSystemInfo()- tester name 


Add below method to all the selenium test cases to get extentreports with test results.

extent.createTest(testname)

extent.flush(); to end monitoring of this test by extent class.


public class ExtentReportDemo {

ExtentReports extent;

@BeforeTest

public void config()

{

// ExtentReports , ExtentSparkReporter

String path =System.getProperty("user.dir")+"\\reports\\index.html";

ExtentSparkReporter reporter = new ExtentSparkReporter(path);

reporter.config().setReportName("Web Automation Results");

reporter.config().setDocumentTitle("Test Results");

extent =new ExtentReports();

extent.attachReporter(reporter);

extent.setSystemInfo("Tester", "Rahul Shetty");

}


@Test

public void initialDemo()

{

ExtentTest test= extent.createTest("Initial Demo");

System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");

WebDriver driver =new ChromeDriver();

driver.get("https://rahulshettyacademy.com");

System.out.println(driver.getTitle());

driver.close();

//test.fail("Result do not match");

extent.flush();

}


**********2] Extent Reports + testNG Listerners




===============DATA DRIVEN TESING USING EXCEL APACHE POI API===============

Apache POI API library- we use for excel data driven test

Maven dependancies setup with a) poi-ooxml and 2) poi 

STRATEGY TO GET DATA FROM EXCEL FILES:

a)Create object for XSSFWorkbook

b)Get access to sheet

c)Get access to all rows of sheet

d)Access to specific row from all rows

e)Get access to all rows of sheet

f)access the data from Excel into Arrays


Array List with Strings ArrayList<String> data=d.getData("Add profile");

Array List generic -- ArrayList data=d.getData("Add profile");


=======================LOG4J===============

Log4J is a reliable,fast and flecxible logging framework (APIs) written in Java-distributed under Apache software Licence

a)Send entire logs to a file?

b)Log only where there is error for Package A

c)Log the entire message for Package B

d)I want logs with the Timestamp

e)I want log file for last week

f)How will i know if there is error by just looking at he logs 


Use log. Error() to log when elements are not displayed in the page or if any validations fail

Use Log. Debug()

When each Selenium action is performed like click, SendKeys, getText()

Use log.info()

When operation is successfully completed ex: After loading page, or after any successful validations


Apache log4J jars download 2.0 URL (Apache Log4j 2 binary(zip) file

http://logging-apache.org/log4j/2.0/download.html

http://logging-apache.org/log4j/2.x/manual/configuration.html  (user manual)


log4j-api-2.8.2 & log4j-core-2.8.2 - add these 2 jars to buildpath 

import org.apache.logging.log4j.*; (import this for log4j support)


logs will read configuration file-then based on that log4J will decide what to print and what to not

Appenders Tag & Logger tags


Where to log: Appenders Tag 

1) simply log in console

2) or log information in seperate log file 

specify what patter yoi


What to Log? Root is entire packages level - 

Root level = error -prints only error messages on console

Root level =trace - prints all messages on console


How to Log? - based on specified pattern in Appenders Tag


Create new xml file as Log4j.xml template for logger: 

Add this xml path (project/src/resources/Log4j.xml to the project build path 

NOTE: SOURCE tab- add xml (log config file) to build path to get logger to print messages


private statuc Logger log=LogManager.getLogger(Demo.class.getName());


Log.debud("Debug message:);

Log.info("This is info message");

Log.error("This is error message");

Log.fatal("This is fatal message");


***LOG4J MESSAGES WRITE INTO FILE instead of on CONSOLE:

Create a text file and name as prints.log then pass this file path to the config file -Appenders 

Change AppenderRef value to refer File (instead of console)


*****************SAMPLE LOG4J XML CONFIGURATION FILE**************

<?xml version="1.0" encoding="UTF-8"?>

<Configuration status="WARN">

       <Properties>

<Property name="basePath">./logs</Property>

</Properties> 

  <Appenders>

      <RollingFile name="File" fileName="${basePath}/prints.log" filePattern="${basePath}/prints-%d{yyyy-MM-dd}.log">

     <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>

      <SizeBasedTriggeringPolicy size="500" />

          </RollingFile>

    <Console name="Console" target="SYSTEM_OUT">

      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>

    </Console>

  </Appenders>

  <Loggers>

    <Root level="trace">

      <AppenderRef ref="File"/>

    </Root>

  </Loggers>

</Configuration>


**************PAGE OBJECT MODEL (POM) **************

1] PROJECT OBJECT MODEL(POM) / PAGE OBJECT PATTERN:

POM (Easy to maintain, realiability, reduce duplicity, re--usability, reliability)


HomePage.java ->to store home page related objects

LoginPage.java ->to store login page related objects

****BY ANNOTATION to define objects in a web page:

By username= By.xpath("username");

By password= By.na,e("password")

public WebElment username()

{

return driver.findElement(username)

}



2] PAGE OBJECT FACTORY: using FindBy annotation 

@FindBy(xpath=".//*[@id='ABCD']")

WebELemnt username;


@FindBy(name="password1")

WebELemnt password;


public WebElment username()

{

return username;

}

PageFactory.initElments(driver,this); //THIS step should be added to the constructor


*****************DATABSE CONNECTION- *****************************

Downloading MySQL

Create Databases and tables

JDBC COnnection with Java

Selenium integration on JDBC code

Retrievig data from DB and using selenium 



https://dev.mysql.com/downloads/windows/installer 

MySQL server and editor  installer community 

username root and input desired password -this can be used in future for MySQL editor 

After installation -open MySQL from Cdrive 

Open -- Myworkbench.exe click 

Connect to the server - click on Local Instance MySQL -enter password and submit

MySQL editor will be launched - test, sakila, world are default databases with default tables

write query and connect to database tables


Create database demo; execute and refresh to see new DB created 

#new DB has been created

#to point database use below command to connect -then create tables

use demo

create table EmployeeInfo(name varchar(20), id int, location varchar(10),age int); #creating table in above database

view table data using below query

describe EmployeeInfo; #this query will explain table details 

insert into EmployeeInfo values(sam, 1, NewYork, 21); #inserting values to database table


mysql-connector-java-5.1.21.jar

driverManager.getConnection(url, root, password);

select * from credentials; # will give credentials for all values

connection URL= 

"jdbc:mysql://" + host + ":' + "/databasename";

String host="localhost";

String port="3306";

Connection con="jdbc:mysql://" + host + ":" + port+ "/databasename";

3306 port, localhost, demo; 

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("QUERY");

rs.getString(columnName/columnLable); # this will return all specified column values


********************AUTOMATING WINDOW CONTROLS ******************

*HANDLING WINDOWS AUTHENTICATION POPUP USING SELENIUM

JavaScript Popup -handle using driver.switchTo.accept() method 


Widnows Auth popup like below which are tied up with browser to enter system credentials 

https://the-internet.herokuapp.com/basic_auth

We need enter site url as "http://username:Password@SiteURL" format to handle this windows auth popups

driver.get("http://Username:Password@SiteURL");

selenium will send these details to browser and resolves the windows auth popup 

Example URL: driver.get("https://admin:admin@the-internet.herokuapp.com/basic_auth");




***FILE UPLOAD POPUP USING SELENIUM/AUTOIT

Shift focus to the file upload window

set text/path into the file name edit box

click open to upload file

record/spy window component using Au3info

build script using scite.exe  and save as .au3 extension

convert file into .exe by compiling .au3

call .exe file with runtime class in java into your selenium tests


ControlFocus("Open","","Edit1")

ControlSetText("Open","","Edit1","C:\Users\rahul\Documents\check\visit.pdf")

ControlClick("Open","","Button1")


HOW TO DOWNLOAD FILE FROM WEB TO LOCAL SYSTEM:



HOW TO VERIFY DOWNLOADED FILE IN LOCAL SYSTEM

File filename=new File("C;\\users\\");

file.exists()- this method will verify the given file name exist in system path



=========================================

++++++++++++++++++++++++WEBDRIVER METHODS:++++++++++++++++++++++++++++++++++++

// Opens a new tab and switches to new tab

driver.switchTo().newWindow(WindowType.TAB);


// Opens a new window and switches to new window

driver.switchTo().newWindow(WindowType.WINDOW);


//Store the ID of the original window

String originalWindow = driver.getWindowHandle();


//Check we don't have other windows open already

assert driver.getWindowHandles().size() == 1;


//Click the link which opens in a new window

driver.findElement(By.linkText("new window")).click();


//Wait for the new window or tab

wait.until(numberOfWindowsToBe(2));


//Loop through until we find a new window handle

for (String windowHandle : driver.getWindowHandles()) {

    if(!originalWindow.contentEquals(windowHandle)) {

        driver.switchTo().window(windowHandle);

        break;

    }

}


//Wait for the new tab to finish loading content

wait.until(titleIs("Selenium documentation"));  

 //Close the tab or window

driver.close();

//Switch back to the old tab or window

driver.switchTo().window(originalWindow);


// Switches to the second frame  

driver.switchTo().frame(1);

// Return to the top level

driver.switchTo().defaultContent();


****GET WINDOW SIZE:

//Access each dimension individually

int width = driver.manage().window().getSize().getWidth();

int height = driver.manage().window().getSize().getHeight();


//Or store the dimensions and query them later

Dimension size = driver.manage().window().getSize();

int width1 = size.getWidth();

int height1 = size.getHeight();

****SET WINDOW SIZE:

driver.manage().window().setSize(new Dimension(1024, 768));

****FULL SCREEN WINDOW:

driver.manage().window().fullscreen();


****TAKE SCREENSHOT:

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.chrome.ChromeDriver;

import java.io.*;

import org.openqa.selenium.*;

  

public class SeleniumTakeScreenshot {

    public static void main(String args[]) throws IOException {

        WebDriver driver = new ChromeDriver();

        driver.get("http://www.example.com");

        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

        FileUtils.copyFile(scrFile, new File("./image.png"));

        driver.quit();

    }

}

****TAKE ELEMENT SCREENSHOT:

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.*;

import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;

import java.io.IOException;


public class SeleniumelementTakeScreenshot {

  public static void main(String args[]) throws IOException {

    WebDriver driver = new ChromeDriver();

    driver.get("https://www.example.com");

    WebElement element = driver.findElement(By.cssSelector("h1"));

    File scrFile = element.getScreenshotAs(OutputType.FILE);

    FileUtils.copyFile(scrFile, new File("./image.png"));

    driver.quit();

  }

}


****EXPLICIT WAIT METHOD:


WebDriver driver = new ChromeDriver();

driver.get("https://google.com/ncr");

driver.findElement(By.name("q")).sendKeys("cheese" + Keys.ENTER);

// Initialize and wait till element(link) became clickable - timeout in 10 seconds

WebElement firstResult = new WebDriverWait(driver, Duration.ofSeconds(10))

        .until(ExpectedConditions.elementToBeClickable(By.xpath("//a/h3")));

// Print the first result

System.out.println(firstResult.getText());


****FLUENT WAIT:

// Waiting 30 seconds for an element to be present on the page, checking

// for its presence once every 5 seconds.

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)

  .withTimeout(Duration.ofSeconds(30))

  .pollingEvery(Duration.ofSeconds(5))

  .ignoring(NoSuchElementException.class);


WebElement foo = wait.until(new Function<WebDriver, WebElement>() {

  public WebElement apply(WebDriver driver) {

    return driver.findElement(By.id("foo"));

  }

});

****JAVA SCRIPT ALERTS, CONFIRM, CANCEL:

//Click the link to activate the alert

driver.findElement(By.linkText("See a sample confirm")).click();


//Wait for the alert to be displayed

wait.until(ExpectedConditions.alertIsPresent());


//Store the alert in a variable

Alert alert = driver.switchTo().alert();


//Store the alert in a variable for reuse

String text = alert.getText();


//Press the Cancel button

alert.dismiss();

//Press the OK button

alert.accept();


****HTTP PROXY SETUP:


import org.openqa.selenium.Proxy;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;


public class proxyTest {

  public static void main(String[] args) {

    Proxy proxy = new Proxy();

    proxy.setHttpProxy("<HOST:PORT>");

    ChromeOptions options = new ChromeOptions();

    options.setCapability("proxy", proxy);

    WebDriver driver = new ChromeDriver(options);

    driver.get("https://www.google.com/");

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

    driver.quit();

  }

}

PAGE LOAD STRATEGY - NORMAL, EAGER, NONE

import org.openqa.selenium.PageLoadStrategy;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import org.openqa.selenium.chrome.ChromeDriver;


public class pageLoadStrategy {

    public static void main(String[] args) {

        ChromeOptions chromeOptions = new ChromeOptions();

        chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);//waits until load event fire is loaded 

chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);//waits until page DOM completely loaded 

     chromeOptions.setPageLoadStrategy(PageLoadStrategy.NONE); //waits until initial page load time

        WebDriver driver = new ChromeDriver(chromeOptions);

        try {

            // Navigate to Url

            driver.get("https://google.com");

        } finally {

            driver.quit();

        }

    }

}

****GET ELEMENT DIMENTIONS:

// Returns height, width, x and y coordinates referenced element

Rectangle res =  driver.findElement(By.cssSelector("h1")).getRect();


// Rectangle class provides getX,getY, getWidth, getHeight methods

System.out.println(res.getX());


****GET ELEMENT CSS VALUE:

// Retrieves the computed style property 'color' of linktext

String cssValue = driver.findElement(By.linkText("More information...")).getCssValue("color");

****GET ELEMENT TAG NAME:

 //returns TagName of the element

 String value = driver.findElement(By.cssSelector("h1")).getTagName();

**** IS ELEMENT SELECTED METHOD:

  //navigates to url 

 driver.get("https://the-internet.herokuapp.com/checkboxes");

  

 //returns true if element is checked else returns false

 boolean value = driver.findElement(By.cssSelector("input[type='checkbox']:first-of-type")).isSelected();

**** IS ELEMENT ENABLED METHOD:

 //navigates to url 

  driver.get("https://www.google.com/");

  

  //returns true if element is enabled else returns false

  boolean value = driver.findElement(By.name("btnK")).isEnabled();

  

// Enter "webdriver" text and perform "ENTER" keyboard action

  driver.findElement(By.name("q")).sendKeys("webdriver" + Keys.ENTER);

****KEYBOARD DOWN EVENT 

  Actions actionProvider = new Actions(driver);

  Action keydown = actionProvider.keyDown(Keys.CONTROL).sendKeys("a").build();

  keydown.perform();

  

****KEYBOARD UP EVENT :

Actions action = new Actions(driver);

      // Store google search box WebElement

      WebElement search = driver.findElement(By.name("q"));

      // Enters text "qwerty" with keyDown SHIFT key and after keyUp SHIFT key (QWERTYqwerty)

      action.keyDown(Keys.SHIFT).sendKeys(search,"qwerty").keyUp(Keys.SHIFT).sendKeys("qwerty").perform();

    }





++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


 */

public class A2TestNGLibrary {

WebDriver driver;


public static class FrameWorkTestNG {

// ****TestNG FRAMEWORK -splitting test and running before after methods-

// priority TAG, dependency TAG, User message in TAG

WebDriver driver;

ChromeOptions options = new ChromeOptions();


@BeforeSuite //executes this method before of all other cases/all modules

public void beforeSuite() {

System.out.println("I am the first from suite");

}


@AfterSuite//executes this method end of all other cases/all modules

public void afterSuite() {

System.out.println("I am the last from suite");

}

@BeforeMethod // this will be executed before for the each of the test method/test case

public void setUp() {

System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");


driver = new ChromeDriver();

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

driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS); // Implicitly wait method

driver.get("http://google.com");

System.out.println("I will execute before of the each and every test method in a class");

}


@Test(priority = 1, groups = "GoogleTest")

public void titletest() {

String title = driver.getTitle();

System.out.println(title);

}


@Test(priority = 2, groups = "GoogleTest")

public void googleLogoTest() {

boolean b = driver.findElement(By.id("gsr")).isDisplayed();

System.out.println("result is " + b);


}


@Test(priority = 3, groups = "Sample")

public void mailLinkTest() {

boolean c = driver.findElement(By.linkText("mail")).isDisplayed();

System.out.println("Result is " + c);

}


@Test(priority = 4, groups = "Demo")

public void loginTest() {

System.out.println("Temp comment");

}

//DependsOnMethods tag in TestNG 

// @Test(priority = 5, groups = "Demo", dependsOnMethods = "loginTest" , "RegisterTest") //we can mention multiple dependant tests

@Test(priority = 5, groups = "Demo", dependsOnMethods = "loginTest")

public void homeTest() {

System.out.println("Temp comment");

}


@BeforeTest

public void beforeTest() {

System.out.println("I will execute first in class");

}

@AfterTest

public void afterTest() {

System.out.println("I will execute last in class");

}

@AfterMethod

public void tearDown() {

System.out.println("I will execute after the each and every test method in a class");

driver.quit();

}

@BeforeClass

public void beforeClassTest() {

System.out.println("I will execute before executing any other method in class level");

}

@AfterClass

public void afterClassTest() {

System.out.println("I will execute before executing any other method in class level");

}


public class DependancyTag {

//// ****TestNG dependency TAG-create dependency between test cases to execute

//// or skip based on outcome

WebDriver driver;


@Test

public void openBrowser() {

System.out.println("this is open browser");

System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

driver = new ChromeDriver();

String url = "http://google.com";

driver.get(url);

Assert.assertEquals(12, 12);

System.out.println("Title is " + driver.getTitle());

driver.quit();

}


@Test(dependsOnMethods = "openBrowser")

public void enterURl() {

System.out.println("this is test enter url");

Assert.assertEquals(12, 13);

}


@Test(dependsOnMethods = "enterURl")

public void closeBrowser() {

System.out.println("this is test close browser");

}

}


// ****TestNG FRAME Handles, SWITCH WINDOW, SWITCH ALERT, Parent and Child windows switch -Handle multiple windows

//switch to window based on ID -which is get by GetWindow handler

//From set - 1st row is parent id and second is child window id 

//To traverse from parent to child - we use Iterator method 

// @Test

public void switchDemo() throws Exception {

System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

driver = new ChromeDriver();

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

driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS); // Implicitly wait method


WebElement button = driver.findElement(By.xpath(""));

WebDriverWait Expwait = new WebDriverWait(driver, 40); // Explicitly wait method

Expwait.until(ExpectedConditions.elementToBeClickable(button));


driver.get("https://www.online.citibank.co.in");

Thread.sleep(3000);

driver.findElement(By.linkText("CITIGROUP.COM")).click();

driver.findElement(By.linkText("TERMS AND CONDITIONS")).click();

driver.findElement(By.linkText("MCLR")).click();


Set<String> windowHandles = driver.getWindowHandles();

System.out.println(windowHandles);


Iterator<String> iter = windowHandles.iterator();

// iter.next();

String id = iter.next();

System.out.println(driver.switchTo().window(id).getTitle());


String id1 = iter.next();

System.out.println(driver.switchTo().window(id1).getTitle());


String id2 = iter.next();

System.out.println(driver.switchTo().window(id2).getTitle());

driver.close();

}

/* ITERATOR METHOD to Find all and click each one from Array List

Iterator<String> it=hs.iterator();

//System.out.println(it.next()); //This stmt will execute the next record from the HashSet records.

while(it.hasNext())

{

System.out.println(it.next());

}

*/


// ****TestNG SWITCH TO ALERT GET ALERT TEXT

// @Test

public void switchToAlert() {

System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

driver = new ChromeDriver();

driver.get("https://ksrtc.in/oprs-web/");

driver.findElement(By.xpath("//*[@id=\"bookingsForm\"]/div/div/div[2]/div[3]/button/i")).click();

System.out.println(driver.switchTo().alert().getText());

driver.switchTo().alert().accept();

System.out.println("Alert popup to be closed");

}

@Test

public void windowAuthPopup () throws Exception {

System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

options.setBinary("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");

driver=new ChromeDriver(options);

//driver.get("https://the-internet.herokuapp.com/basic_auth");

Thread.sleep(3000);

driver.get("https://admin:admin@the-internet.herokuapp.com/basic_auth");

Thread.sleep(2000);

System.out.println("Browser title is " + driver.getTitle());

System.out.println("window popup opened and submitted credentials");

driver.quit();


}


@Test //AUTOIT FILE UPLOAD

public class fileUploadAutoIT {

public void main(String[] args) throws InterruptedException, IOException {

// TODO Auto-generated method stub

String downloadPath=System.getProperty("user.dir"); //This will get the current project directory

System.setProperty("webdriver.chrome.driver","C:\\work\\chromedriver.exe");

HashMap<String, Object> chromePrefs = new HashMap<String, Object>();

chromePrefs.put("profile.default_content_settings.popups", 0);

chromePrefs.put("download.default_directory", downloadPath); //setting default file download path

ChromeOptions options=new ChromeOptions();

options.setExperimentalOption("prefs", chromePrefs);

WebDriver driver=new ChromeDriver(options);

driver.get("https://altoconvertpdftojpg.com/");

driver.findElement(By.cssSelector("[class*='btn--choose']")).click();

Thread.sleep(3000);

Runtime.getRuntime().exec("C:\\Users\\rahul\\Documents\\check\\fileupload.exe");

WebDriverWait wait=new WebDriverWait(driver,10);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("button[class*='medium']")));

driver.findElement(By.cssSelector("button[class*='medium']")).click();

wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Download Now")));

driver.findElement(By.linkText("Download Now")).click();

Thread.sleep(5000);

File f=new File(downloadPath+"/converted.zip");

if(f.exists())

{

Assert.assertTrue(f.exists());

if(f.delete())  //file.delete method will delete the file from the given path

System.out.println("file deleted");

}

}

}


// ***TESTNG Handle alert popup and capture error message

@Test

public void handleAlertPopUp() throws Exception {

String text = "Venkatesh";

System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

driver = new ChromeDriver();

driver.get("https://mail.rediff.com/cgi-bin/login.cgi");

driver.findElement(By.name("proceed")).click();

System.out.println("alert popup 1 text is" + driver.switchTo().alert());

driver.switchTo().alert().accept();

driver.findElement(By.id("login1")).sendKeys("helloUsername");

driver.findElement(By.name("proceed")).click();

System.out.println("alert popup 1 text is" + driver.switchTo().alert());

driver.switchTo().alert().accept();

driver.findElement(By.id("password")).sendKeys("testpassword");

driver.findElement(By.name("proceed")).click();

Thread.sleep(2000);

String error = driver.findElement(By.id("div_login_error")).getText();

System.out.println(error);

driver.get("https://rahulshettyacademy.com/AutomationPractice/");

driver.findElement(By.id("name")).sendKeys(text);

driver.findElement(By.cssSelector("[id='alertbtn']")).click();

System.out.println(driver.switchTo().alert().getText());

driver.switchTo().alert().accept(); // Accepting alert for positivity Yes or OK buttons

driver.findElement(By.id("confirmbtn")).click();

System.out.println(driver.switchTo().alert().getText());

driver.switchTo().alert().dismiss();// Dismissing alert for negativity Cancel OR No buttons

driver.quit();

}


/* HANDLING IFRAMES in Selenium- Frames are component/container seperated prepared and hosted

* Switching Driver web objects to frame using SwitchToFrame method using Frame Index/ID/Web Element 

*/

@Test

public void iFrameTest() throws Exception {

System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

driver = new ChromeDriver();

driver.get("https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_dom_html_get");

driver.switchTo().frame(driver.findElement(By.xpath("//*[@id=\"iframeResult\"]")));

// Switch to frame using Iframe index or name or id or Xpath of the Iframe

// driver.switchTo().frame("iframeResult");

System.out.println("focued to the Iframe");

driver.findElement(By.id("btn1")).click();

System.out.println("Alert popup1 text is===" + driver.switchTo().alert().getText());

driver.switchTo().alert().accept();

System.out.println("frame button1 clicked and accepted alert");

Thread.sleep(2000);

driver.findElement(By.id("btn2")).click();

System.out.println("Alert popup2 text is===" + driver.switchTo().alert().getText());

driver.switchTo().alert().accept();

System.out.println("frame button2 clicked and accepted alert");

driver.switchTo().defaultContent();

driver.quit();

System.out.println("test completed");

}


// ****TestNG INVOCATION COUNT to REPEAT TESTS

// TestNG invocationCount annotation which will be used to repeat tests based on given InvocationCount number

@Test(invocationCount = 10)

public void sum() {

int a = 10;

int b = 20;

int c = a + b;

System.out.println("The result is " + c);

}


// invocationTimeOut annotation used to terminate program

// @Test(invocationTimeOut=2)

public void infiniteTest() {

int i = 1;

while (i == 1) {

System.out.println(i);

}

}


// expectedExceptions can be used to continue test even it is failed also

@Test(expectedExceptions = NumberFormatException.class)

public void expectedException() {

String x = "100A";

Integer.parseInt(x);

}


// ****TestNG JAVA SCRIPT EXECUTOR

// Java Script Executor to use forceful operation when elements not identified

//Java Script extract all hidden elements from HTML/DOM webpage which selenium can't identify hidden elements [ajax, etc]


@Test

public void selectNationality() {

JavascriptExecutor js = (JavascriptExecutor) driver; //JavaScript Executor API nitialise-

js.executeScript("window.scrollTo(0, 0)");

driver.findElement(By.id("sad")).click();

//How to extract value from a field with help of Javascript Executor?

//String val = "return document.getElementById(\"hiddentext\").value;";

//String text=(String) js.executeScript(val);

}


//@Test

public void JavaScriptExecutorMethod() {

driver.get("https://www.ksrtc.in");

driver.findElement(By.xpath("//input[@id='fromPlaceName']")).sendKeys("BENG");

//Thread.sleep(2000);

driver.findElement(By.xpath("//input[@id='fromPlaceName']")).sendKeys(Keys.DOWN);

System.out.println(driver.findElement(By.xpath("//input[@id='fromPlaceName']")).getText());

//Javascript DOM can extract hidden elements

//because selenium cannot identify hidden elements - (Ajax implementation),investigate the properties of object if it have any hidden text

//JavascriptExecutor initialization 

JavascriptExecutor js= (JavascriptExecutor)driver;

String script = "return document.getElementById(\"fromPlaceName\").value;";

String text=(String) js.executeScript(script);

System.out.println(text);

int i =0;

//BENGALURU INTERNATION AIPORT

while(!text.equalsIgnoreCase("BENGALURU INTATION AIPORT"))

{

i++;

driver.findElement(By.xpath("//input[@id='fromPlaceName']")).sendKeys(Keys.DOWN);

text=(String) js.executeScript(script);

System.out.println(text);

if(i>10)

{

break; //Break while loop from infinite execution

}

}

if(i>10)

{

System.out.println("Element not found");

}

else

{

System.out.println("Element  found");

}

//WHILE Loop to find required text in dropdown record  , Break eyword to terminate While Loop execution

}

// *** PARTIAL SCREENSHOT CAPTURE for SPECIFIC WEBELEMENT USING SELENIUM VERSION 4

//SWITCHING WINDOW  WEBELEMENT.

//GET DIMENTIONS()WIDTH-HEIGHT OF THE WEB ELMENET  [GETRECTANGLE METHOD; GETDIMETION METHOD]

public  class SELENIUM4NewWindow {

public void main(String[] args) throws IOException {

System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");

WebDriver driver=new ChromeDriver();

driver.get("https://rahulshettyacademy.com/angularpractice/");

//Switching Window

driver.switchTo().newWindow(WindowType.WINDOW);

Set<String> handles=driver.getWindowHandles();

Iterator<String> it=handles.iterator();

String parentWindowId = it.next();

String childWindow =it.next();

driver.switchTo().window(childWindow);

driver.get("https://rahulshettyacademy.com/");

String courseName = driver.findElements(By.cssSelector("a[href*='https://courses.rahulshettyacademy.com/p']"))

.get(1).getText();

driver.switchTo().window(parentWindowId);

WebElement name=driver.findElement(By.cssSelector("[name='name']"));

name.sendKeys(courseName);

//GET PARTIAL Screenshot

File file=name.getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(file, new File("logo.png"));

//driver.quit();

//GEt Height & Width

System.out.println(name.getRect().getDimension().getHeight());

System.out.println(name.getRect().getDimension().getWidth());

}

}



// ****TestNG TAKE FULL SCREENSHOT USING SELENIUM

@Test

public void captureScreenshot(String fileName) {


File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

try {

// now copy the screenshot to desired location using copyFile //method

FileUtils.copyFile(scrFile, new File("C:\\Users\\vmuriki\\Documents\\SW\\" + fileName));

}

catch (IOException e) {

System.out.println(e.getMessage());

}

}


// ****TestNG WEBDRIVER MANAGER option to INVOKE SYSTEM BROWSER without System

// Set property

@Test

public void webDriverManager() {

WebDriverManager.chromedriver().setup();

driver = new ChromeDriver();

driver.get("http//google.com");

System.out.println(driver.getTitle());

driver.quit();

}


// ****TestNG WRITE FROM EXCEL PROGRAM

// @Test

public void readExcel() throws Exception {


File src = new File("C:\\Users\\vmuriki\\workspace\\Selenium\\src\\test\\java\\TestData\\ExcelRead.xlsx");


FileInputStream fis = new FileInputStream(src);

XSSFWorkbook wb = new XSSFWorkbook(fis);

XSSFSheet sheet = wb.getSheetAt(1);

String data0 = sheet.getRow(0).getCell(0).getStringCellValue();

System.out.println(data0);


String data1 = sheet.getRow(0).getCell(1).getStringCellValue();

System.out.println(data1);


String data2 = sheet.getRow(0).getCell(2).getStringCellValue();

System.out.println(data2);

// wb.close();


}


//Test

//WEB TABLE PAGINATION TEST

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

System.setProperty("webdriver.chrome.driver", "C://Users//vmuriki//Documents//VM//SW//chromedriver.exe");

WebDriver driver = new ChromeDriver();

driver.get("https://rahulshettyacademy.com/greenkart/#/offers");

// click on column

driver.findElement(By.xpath("//tr/th[1]")).click();

// capture all webelements into list

List<WebElement> elementsList = driver.findElements(By.xpath("//tr/td[1]"));

// capture text of all webelements into new(original) list

List<String> originalList = elementsList.stream().map(s -> s.getText()).collect(Collectors.toList());

// sort on the original list of step 3 -> sorted list

List<String> sortedList = originalList.stream().sorted().collect(Collectors.toList());

// compare original list vs sorted list

Assert.assertTrue(originalList.equals(sortedList));

List<String> price;

// scan the name column with getText ->Beans->print the price of the Rice

do

{

List<WebElement> rows = driver.findElements(By.xpath("//tr/td[1]"));

price = rows.stream().filter(s -> s.getText().contains("Rice"))

.map(s -> getPriceVeggie1(s)).collect(Collectors.toList());

price.forEach(a -> System.out.println(a));

if(price.size()<1)

{

driver.findElement(By.cssSelector("[aria-label='Next']")).click();


}


}while(price.size()<1);

}

private static String getPriceVeggie1(WebElement s) {

String pricevalue = s.findElement(By.xpath("following-sibling::td[1]")).getText();

return pricevalue;

}

// ****TestNG WRITE TO EXCEL PROGRAM

@Test

public void writeExcel() throws Exception {


File src = new File("C:\\Users\\vmuriki\\workspace\\Selenium\\src\\test\\java\\TestData\\ExcelRead.xlsx");


FileInputStream fis = new FileInputStream(src);

XSSFWorkbook wb = new XSSFWorkbook(fis);

XSSFSheet sheet = wb.getSheetAt(1);

sheet.getRow(0).createCell(2).setCellValue("RESULTS");

sheet.getRow(1).createCell(2).setCellValue("Pass");

sheet.getRow(2).createCell(2).setCellValue("Fail");

sheet.getRow(3).createCell(2).setCellValue("Fail");

sheet.getRow(4).createCell(2).setCellValue("12.15");

sheet.getRow(5).createCell(2).setCellValue(false);

sheet.getRow(6).createCell(2).setCellValue("12-Jun-2020");


System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

driver = new ChromeDriver();

driver.get("https://google.com");

String title = driver.getTitle();

sheet.getRow(7).createCell(2).setCellValue(title);


String title2 = driver.findElement(By.id("gsr")).getText();

sheet.getRow(8).createCell(2).setCellValue(title2);


FileOutputStream fos = new FileOutputStream(src);

wb.write(fos);


String data8 = sheet.getRow(8).getCell(2).getStringCellValue();

System.out.println("Excel updated data 8 value is " + data8);


String data7 = sheet.getRow(7).getCell(2).getStringCellValue();

System.out.println("Excel updated data 1 value is " + data7);


wb.close();

driver.close();

}


@Test

//EXCEL READ PROGRAM USING ARRAY LIST METHOD

public class ExcelDataDriven {

//Identify Testcases coloum by scanning the entire 1st row

//once coloumn is identified then scan entire testcase coloum to identify purcjhase testcase row

//after you grab purchase testcase row = pull all the data of that row and feed into test

//NumberToTextConverter METHOD to convert number value to String -then add to the Array List which supports String values.

//import org.apache.poi.ss.util.NumberToTextConverter   use this import for NumberToTextConverter

public ArrayList<String> getData(String testcaseName) throws IOException

{

//fileInputStream argument to load excel file

ArrayList<String> a=new ArrayList<String>();

FileInputStream fis=new FileInputStream("C://Users//rahul//Documents//demodata.xlsx");

XSSFWorkbook workbook=new XSSFWorkbook(fis);


int sheets=workbook.getNumberOfSheets();

for(int i=0;i<sheets;i++)

{

if(workbook.getSheetName(i).equalsIgnoreCase("testdata"))

{

XSSFSheet sheet=workbook.getSheetAt(i);

//Identify Testcases coloum by scanning the entire 1st row

Iterator<Row>  rows= sheet.iterator();// sheet is collection of rows

Row firstrow= rows.next();

Iterator<Cell> ce=firstrow.cellIterator();//row is collection of cells

int k=0;

int coloumn = 0;

while(ce.hasNext())

{

Cell value=ce.next();

if(value.getStringCellValue().equalsIgnoreCase("TestCases"))

{

coloumn=k;

}

k++;

}

System.out.println(coloumn);

////once coloumn is identified then scan entire testcase coloum to identify purcjhase testcase row

while(rows.hasNext())

{

Row r=rows.next();

if(r.getCell(coloumn).getStringCellValue().equalsIgnoreCase(testcaseName))

{

////after you grab purchase testcase row = pull all the data of that row and feed into test

Iterator<Cell>  cv=r.cellIterator();

while(cv.hasNext())

{

Cell c= cv.next();

if(c.getCellTypeEnum()==CellType.STRING)

{

a.add(c.getStringCellValue());

}

else{

a.add(NumberToTextConverter.toText(c.getNumericCellValue()));

}

}

}

}

}

}

return a;

}

public void main(String[] args) throws IOException {

// TODO Auto-generated method stub

ExcelDataDriven d=new ExcelDataDriven();

ArrayList data=d.getData("testcaseName");

System.out.println(data.get(0));

System.out.println(data.get(1));

System.out.println(data.get(2));

System.out.println(data.get(3));

}


}

@Test

public void validateAllHyperlinks() {

// ****TestNG VALIDATE ALL HYPERLINKS on a WEBPAGE

// TODO Auto-generated method stub

System.setProperty("webdriver.chrome.driver", "C:\\Users\\vmuriki\\Documents\\VM\\SW\\chromedriver.exe");

driver = new ChromeDriver();

driver.get("https://eenadu.net");

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

driver.manage().deleteCookieNamed("XYZ");// to delete specific cookie.

//driver.manage().addCookie(ABC);//to Add cookie

driver.manage().deleteAllCookies(); //to Delete all cookies in browser

driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

System.out.println("Browser launched");

String browserTitle = driver.getTitle();

System.out.println("Title of browser is " + browserTitle);


List<WebElement> alllinks = driver.findElements(By.xpath("//*[contains(@href,'eenadu.net/')]"));

System.out.println("Number of links " + alllinks.size());


String links[] = new String[alllinks.size()];

int i = 0;

for (WebElement e : alllinks) {

// System.out.println(e.getText());

links[i] = e.getText();

i++;

}

for (String s : links) {

driver.findElement(By.linkText(s)).click();

if (driver.getTitle().contains("404") || driver.getTitle().contains("500")) {

System.out.println("Link:" + s + "---> is not working");

} else {

System.out.println("Link:" + s + "---> is working fine");

}

}

System.out.println("End of script");

driver.quit();

}


@Test //BROKEN LINKS TEST -PERFECT TEST METHODS USING CONNECTION METHOD.

/*

 Chrome-Dev tools- network tab =XHR sub tab- then click on hyperlink 

It will show all the status codes of available hyperlinks 

Java methods(OpenConnection method) will call URL's and get the status codes 

1. get all URL tied of that page using href/ /a tag

2. If status code is > 400 then those links are broken

3. Get all links into list using WebElemnets

4. then use Enhanced for loop to iterate all links to open and verify status

*/

public  class BrokenLinksTest {

public void main(String[] args) throws MalformedURLException, IOException {

System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

WebDriver driver=new ChromeDriver();

//broken URL

//Step 1 - IS to get all urls tied up to the links using Selenium

//  Java methods will call URL's and gets you the status code

//if status code >400 then that url is not working-> link which tied to url is broken

//a[href*="soapui"]'

driver.get("https://rahulshettyacademy.com/AutomationPractice/");

List<WebElement> links=   driver.findElements(By.cssSelector("li[class='gf-li'] a"));

//HARD ASSERT/assertion to stop the test when it is failed 

/*Assert.assertTrue(false); 

for(WebElement link : links)

{

String url=link.getAttribute("href")

if(respCode>400)

{

System.out.println("The failed link is "+link.getText()+"with code"+respCode);

Assert.assertTrue(false); //HARD ASSERTIONS 

}*/

//SOFT ASSERTION  

SoftAssert a =new SoftAssert();

for(WebElement link : links) //Enhanced For Loop 

{

String url= link.getAttribute("href");

HttpURLConnection   conn= (HttpURLConnection)new URL(url).openConnection();

conn.setRequestMethod("HEAD");

conn.connect();

int respCode = conn.getResponseCode();

System.out.println(respCode);

a.assertTrue(respCode<400, "The link with Text"+link.getText()+" is broken with code" +respCode); //Soft Assertion

}

a.assertAll();//Soft Assertion end stmt which will check and print all the failures

}

private Object getReturnCode(WebElement link) {

// TODO Auto-generated method stub

return null;

}

}

//**********PASSWORD ENCRYPT DECRYPT AND PASS TO THE TEST*********************

@Test

public static void encryption1() {

String str1="Selenium";

byte[] byteEncodedtext=Base64.getEncoder().encode(str1.getBytes());

String str1Encode=new String(byteEncodedtext);

System.out.println("String after encoded is "+ str1Encode);

byte[] byteDecodedtext=Base64.getDecoder().decode(str1Encode.getBytes());

String str1Decode=new String(byteDecodedtext);

System.out.println("String after encoded is "+ str1Decode);

}

//USE DECODESTRING METHOD WHILE PASSING THE STRING TO THE SELENIUM TEST AS BELOW

static String decodeString (String password) {

byte[] decodeText=Base64.getDecoder().decode(password.getBytes());

return(new String(decodeText));

//USE DECODESTRING METHOD WHILE PASSING THE STRING TO THE SELENIUM TEST AS BELOW

//driver.findElement(By.id("password")).sendKeys(decodeString(prop.getProperty("PWD")));

}

// ****TESNG Reusable function webdriver wait method -explicitly wait method

@Test

public void webDriverWait() {

System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

driver = new ChromeDriver();

driver.get("https://facebook.com");

clickOn(driver, driver.findElement(By.id("sd")), 20);

clickOn(driver, driver.findElement(By.name("sd")), 40);

}


public void clickOn(WebDriver driver, WebElement locator, int timeout) {

new WebDriverWait(driver, timeout).ignoring(StaleElementReferenceException.class)

.until(ExpectedConditions.elementToBeClickable(locator));

locator.click();

}

//WEBDRIVER WAIT WITH TEXT() FUNCTION as Xpath

@Test

public void explicitWaitMethod() {

System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

options.setBinary("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");

driver=new ChromeDriver(options);

driver.get("http://www.itgeared.com/demo/1506-ajax-loading.html");

driver.findElement(By.xpath("//a[contains(text(),'Click to load get data via Ajax!')]")).click();

//WebElement error=driver.findElement(By.xpath("//div[contains(text(),'Process completed')]"));

WebDriverWait wait=new WebDriverWait(driver,10);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'Process completed')]")));

String error=driver.findElement(By.xpath("//div[contains(text(),'Process completed')]")).getText();

System.out.println(error);

/* ALTERNATE CODE 

driver.get("http://www.itgeared.com/demo/1506-ajax-loading.html");

        driver.findElement(By.cssSelector("a[href*='loadAjax']")).click();

        WebDriverWait d=new WebDriverWait(driver,20);

        d.until(ExpectedConditions.elementToBeClickable(By.id("results")));

        System.out.println(driver.findElement(By.id("results")).getText());

      //  System.out.println( driver.findElement(By.xpath("//*[@id='checkbox-example']/fieldset/label[2]")).getText());   

*/

}


//*******WEBTABLE PAGINATION HANDINLG USING JAVA STREAMS

@Test

public void webTableTest01() {

//public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

System.setProperty("webdriver.chrome.driver", "C://Users//vmuriki//Documents//VM//SW//chromedriver.exe");

WebDriver driver = new ChromeDriver();

driver.get("https://rahulshettyacademy.com/greenkart/#/offers");

// click on column

driver.findElement(By.xpath("//tr/th[1]")).click();

// capture all webelements into list

List<WebElement> elementsList = driver.findElements(By.xpath("//tr/td[1]"));

// capture text of all webelements into new(original) list

List<String> originalList = elementsList.stream().map(s -> s.getText()).collect(Collectors.toList());

// sort on the original list of step 3 -> sorted list

List<String> sortedList = originalList.stream().sorted().collect(Collectors.toList());

// compare original list vs sorted list

Assert.assertTrue(originalList.equals(sortedList));

List<String> price;

// scan the name column with getText ->Beans->print the price of the Rice

do

{

List<WebElement> rows = driver.findElements(By.xpath("//tr/td[1]"));

price = rows.stream().filter(s -> s.getText().contains("Rice"))

.map(s -> getPriceVeggie1(s)).collect(Collectors.toList());

price.forEach(a -> System.out.println(a));

if(price.size()<1)

{

driver.findElement(By.cssSelector("[aria-label='Next']")).click();


}


}while(price.size()<1);

}

private String getPriceVeggie(WebElement s) {

String pricevalue = s.findElement(By.xpath("following-sibling::td[1]")).getText();

return pricevalue;

}

//***** TESTNG Validate dropdown values in ascending and descending order list

@Test

public void dropDownAscDescTest() {


System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

driver = new ChromeDriver();

driver.get("https://www.ifsccodebank.com/");

Select tools = new Select(driver.findElement(By.id("BC_ddlBank")));

List actualList = new ArrayList();

List<WebElement> myTools = tools.getOptions();

for (WebElement ele : myTools) {

String data = ele.getText();

actualList.add(data);

}

List temp = new ArrayList();

// ascending order

Collections.sort(temp);

// Descending order

// Collections.sort(temp, Collections.reverseOrder());

Assert.assertTrue(actualList.equals(temp));

}


// ****TESTNG Tooktip test validation & Keyboard mouse movements

// Pause debugger by pressing F8 in inspect element window -then capture the

// text of tool tip ouse hover for webelement capture the text and store in

// variable and validate the same

//Kyboard mouse movements, interactions -right click, double click, write text in caps, can be automated using ACTIONS CLASS

//composite actions then later build action and perform to complete steps

//enter text in caps letters ,right click on screen,drag and drop, select string using keybord interaction menthods


@Test

public void toolTipTest() {


System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

driver = new ChromeDriver();

driver.get("http://seleniumpractice.blogspot.com");

Actions action = new Actions(driver);

WebElement move = (driver.findElement(By.xpath("test2")));

action.moveToElement(move).build().perform();

action.moveToElement(move).click().keyDown(Keys.SHIFT).sendKeys("hello"); //this action will enter CAPS letter in locator

action.moveToElement(move).contextClick().build().perform(); //this action will rightclick on given locator

//action.moveToElement(driver.findElement(By.xpath("test2"))).perform();

//action.dragAndDrop('source', 'target'); //This method use to drag an drop from source to target location.

String helpText = driver.findElement(By.xpath("test")).getText();

System.out.println(helpText);

Assert.assertTrue(helpText.contains("test"));


}


// *****TEST ASSERTIONS

/*

* Assert.assertTrue(expects always true); Assert.assertFalse(expects always

* false); Assert.assertEquals(actuals, expected);//compares both and if equals

* pass,else fail

*/

@Test

public void testAssesrtions() {


driver.findElement(By.id("autosuggest")).sendKeys("ind");

List<WebElement> options = driver.findElements(By.cssSelector("li[class='ui-menu-item'] a"));

for (WebElement option : options) {

if (option.getText().equalsIgnoreCase("India")) {

option.click();

break;

}

// ASSERSIONS

Assert.assertFalse(driver.findElement(By.cssSelector("input[id*='SeniorCitizenDiscount']")).isSelected());

// Assert.assertFalse(true);System.out.println(driver.findElement(By.cssSelector("input[id*='SeniorCitizenDiscount']")).isSelected());

driver.findElement(By.cssSelector("input[id*='SeniorCitizenDiscount']")).click();

System.out.println(driver.findElement(By.cssSelector("input[id*='SeniorCitizenDiscount']")).isSelected());

Assert.assertTrue(driver.findElement(By.cssSelector("input[id*='SeniorCitizenDiscount']")).isSelected());

Assert.assertEquals((driver.findElement(By.cssSelector("input[id*='SeniorCitizenDiscount']")).getText()),

"expected TEXT");

// Use this assertEquals for expected results from the test to be true

}

}


// *TESTNG SEND EMAIL FROM MAIL SERVER

public void sendEmails() {

// https://commons.apache.org/proper/commons-email/userguide.html

try {

Email email = new SimpleEmail();

// email.setHostName("smtp.gmail.com");

email.setHostName("smtp.googlemail.com");

email.setSmtpPort(465);

email.setAuthenticator(new DefaultAuthenticator("test@gmail.com", "pwd"));

email.setSSLOnConnect(true);

email.setFrom("test@gmail.com");

email.setSubject("TestMail");

email.setMsg("This is a test mail from Selenium... :-)");

email.addTo("test@gmail.com");

email.send();

} catch (EmailException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


// *** GET AND SET PROPERTY FILE VALUES ..getProperty/setProperty methods..

//static String projectPath = System.getProperty("user.dir");

//static Properties prop = new Properties();



//HNADLING SSL Certificates/SECURE CERTIFICATE ISSUE WEB SITES- TO ACCEPT AND PROCEED ANYWAY

//We need to use DESIREDCAPABILITIES and CHROME OPTIONS to handle SSL ccertificate erros on web applications(Script will execute by click on continue anyway button from the insecure webpage)

@Test

public void propertiesFile() throws IOException {

Properties prop=new Properties(); //Properties class will scan properties mentioned in the .properties files

FileInputStream fis =new FileInputStream("C:\\Users\\Owner\\CoreJava\\CoreJava\\src\\data.properties");

prop.load(fis); //to load file in readonly mode

System.out.println(prop.getProperty("browser"));

System.out.println(prop.getProperty("url"));

prop.setProperty("browser", "firefox"); //to update the property file orignal value to update with new value in runtime

System.out.println(prop.getProperty("browser"));

FileOutputStream fos =new FileOutputStream("C:\\Users\\Owner\\CoreJava\\CoreJava\\src\\data.properties");

prop.store(fos, null);//to load file in update mode and store latest value to property file.

}


/*

// TODO Auto-generated method stub

DesiredCapabilities ch = DesiredCapabilities.chrome();

ch.acceptInsecureCerts();

ch.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);

ch.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);

//Below is to your local browser

ChromeOptions co= new ChromeOptions();

co.merge(ch);

WebDriver driver=new ChromeDriver(co);

driver.get("http://google.com");

}

*/


//**** CHROME OPTIONS with Chrome browser exe-BINARY PATH SETTING instead of WebDriver path:

@Test

public void todayTest() {

System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

ChromeOptions options = new ChromeOptions();

options.setBinary("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");

driver=new ChromeDriver(options);

driver.get("http://seleniumpractice.blogspot.com");

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

driver.manage().window().fullscreen();

System.out.println("======HELLO=========");

System.out.println("TEST COMPLETED====");

driver.quit();


// USE THIS CHROME OPTIONS WITH SET BINARY METHOD WITH ACTUAL CROME EXE PATH IN LOCAL SYSTEM

// options.setBinary("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");

// driver=new ChromeDriver(options);

// driver.get(prop.getProperty("WebURL"));


}


//*****AUTOMATED TESTS IN CLOUD ENVIRONMENT [SAUCELABS.COM]


public class CloudSauceLabsTest {

// public static final String USERNAME = "venkatesh113";

// public static final String ACCESS_KEY = "XXXXX"; //https://app.saucelabs.com/dashboard/tests/vdc 

public static final String URL = "https://venkatesh113:d25005b9-c369-4fb4-8207-676ec2ee2bc8@ondemand.us-west-1.saucelabs.com:443/wd/hub";

//private static final String Date = null;


//driver = new WebDriver(

//new URL("https://venkatesh113:d25005b9-c369-4fb4-8207-676ec2ee2bc8@ondemand.us-west-1.saucelabs.com:443/wd/hub"));

/*

public static void main(String[] args) throws MalformedURLException {

DesiredCapabilities caps = DesiredCapabilities.chrome();

caps.setCapability("platform", "Windows 7");

caps.setCapability("version", "51.0");

WebDriver driver=new RemoteWebDriver(new URL(URL), caps);

driver.get("http://google.com");

System.out.println(driver.getTitle());

System.out.println("Cloud Test Completed" + Date);

}

*/

/*

@Test

public void cloudtest() throws MalformedURLException {

DesiredCapabilities caps = DesiredCapabilities.chrome();

caps.setCapability("platform", "Windows 7");

caps.setCapability("version", "51.0");

WebDriver driver=new RemoteWebDriver(new URL(URL), caps);


driver.get("http://google.com");

System.out.println("Page 1 Titile is "+ driver.getTitle());

driver.get("https://eenadu.net");

System.out.println("Page 2 Titile is "+ driver.getTitle());

driver.get("https://citibank.co.in");

System.out.println("Page 3 Titile is "+ driver.getTitle());

System.out.println("Cloud Test Completed" + Date);

}


@Test

public void getProperty() {

try {

InputStream input = new FileInputStream(projectPath + "./src/test/java/config/config.properties");

prop.load(input);

String browser = prop.getProperty("Browser");

System.out.println(browser);

System.out.println(prop.getProperty("URL"));

} catch (Exception exp) {

exp.getCause();

exp.getMessage();

exp.printStackTrace();

}


}


@Test

private static void setProperty() {

try {

OutputStream output = new FileOutputStream(projectPath + "./src/test/java/config/config.properties");

prop.setProperty("Browser", "firefox");

prop.setProperty("URL", "http://amazon.co.in");

prop.setProperty("RESULT", "PASS");

prop.setProperty("Title", "Title of the Browser");

prop.store(output, null); // this will save values to property file

System.out.println("browser title captured as " + prop.getProperty("Title"));

System.out.println("Test output results are " + prop.getProperty("RESULT"));

// System.out.println(browser);


} catch (Exception exp) {

exp.getCause();

exp.getMessage();

exp.printStackTrace();

}

}


/*

* include, exclude pages for comparison.. ignored shows in Yellow highlighted

* https://youtu.be/koMegSvZEVE Add script to write results in to result P Step

* 1 : create a maven project in java Step 2 : Goto pdfcompare github page and

* add the dependency in pom.xml https://github.com/red6/pdfcompare Step 3 :

* Create java script for pdf comparison Step 4: Add script to write results in

* a result pdf file Step 5 : Add script to ignore areas in pdf file Step 6 :

* Run and Validate

*/

//RELATIVE LOCATORS FROM SELENIUM 4 version onwards 

//Import static one for this locators realted -import static org.openqa.selenium.support.locators.RelativeLocator.withTagName;

/* ****RELATIVE LOCATORS:

Parent to child/sibling traverse -- 

These relative locators supports with TagName property/label alone 

above() METHOD:Element located above with respect to the specified element

Below() METHOD:Element located to the left of specified element

toLeftOf() METHOD:Element the right of with respect to the specified element

toRightIf() METHOD:

SYNTAX- driver.findElement(withTagName('label").above(nameEditBox)

*/

@Test //LOG4J DEMO 

public class Log4jDemo {

// private static Logger log =LogManager.getLogger(Log4jDemo.class.getName());

// public static void main(String[] args) {

private  Logger log =LogManager.getLogger(Log4jDemo.class.getName());

public  void main(String[] args) {

// TODO Auto-generated method stub

   log.debug("Setting chrome driver property");

System.setProperty("webdriver.chrome.driver","C:\\work\\chromedriver.exe");

WebDriver driver =new ChromeDriver();

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

   log.info("Window Maximized");

   log.debug("Now hitting Amazon server");

driver.get("https://www.amazon.com/");

   log.info("Landed on amazon home page");

Actions a =new Actions(driver);

/* a.moveToElement(driver.findElement(By.xpath("//*[@id='twotabsearchtextbox']"))) .click().keyDown(Keys.SHIFT).sendKeys("capitalletters").doubleClick().build().perform();

a.moveToElement(driver.findElement(By.cssSelector("a[id='nav-link-accountList']"))).build().perform();

a.moveToElement(driver.findElement(By.cssSelector("a[id='nav-link-accountList']"))).contextClick().build().perform();*/


driver.get("http://jqueryui.com/demos/droppable/");

   log.debug("Getting the frames count");

System.out.println(driver.findElements(By.tagName("iframe")).size());

log.info("Frames count retreived");

try

{

driver.switchTo().frame(0);

log.info("Successfully switched to frame");

}

catch(Exception e)

{

log.error("Cannot identify the frame"); 

}

//driver.switchTo().frame(driver.findElement(By.cssSelector("iframe.demo-frame")));

   log.debug("Identifying Draggable objects");

       WebElement draggable = driver.findElement(By.id("draggable"));

       WebElement droppable = driver.findElement(By.id("droppable"));

       new Actions(driver).dragAndDrop(draggable, droppable).build().perform();

log.info("Drag and drop success");

}


}

@Test 

public class RelativeLocators {

public void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");

WebDriver driver=new ChromeDriver();

driver.get("https://rahulshettyacademy.com/angularpractice/");

WebElement nameEditBox =driver.findElement(By.cssSelector("[name='name']"));

System.out.println(driver.findElement(withTagName("label").above(nameEditBox)).getText());

WebElement dateofBirth= driver.findElement(By.cssSelector("[for='dateofBirth']"));

driver.findElement(withTagName("input").below(dateofBirth)).sendKeys("02/02/1992");

WebElement iceCreamLabel=driver.findElement(By.xpath("//label[text()='Check me out if you Love IceCreams!']"));

driver.findElement(withTagName("input").toLeftOf(iceCreamLabel)).click();

//Get me the label of first Radio button

WebElement rb=driver.findElement(By.id("inlineRadio1"));

System.out.println(driver.findElement(withTagName("label").toRightOf(rb)).getText());

}



//SELENIUM GRID- NODE CONFIGURATION AND EXECUTION ON NODES

@Test //put static for method and main class

public class GridSelenium {

/*

Download Selenium server jar.

Started the hub 

java -jar selenium-server-standalone-3.8.1jar -role hub

Login to another machine and register it as node for hub.

Download the selenium server jar in node machine as well/check java 

java -jar selenium-server-standalone-3.8.1jar-role webdriver -hub 

>ipaddress>/grid/register -port 5566 

Chrome driver.exe file geckodriver 

*/

public void main(String[] args) throws MalformedURLException {

// TODO Auto-generated method stub

//Automated- chrome,firefox,ie,safari

DesiredCapabilities dc= new DesiredCapabilities();

dc.setBrowserName("chrome");

dc.setPlatform(Platform.WINDOWS);

//dc.se

//Webdriver driver=new ChromeDriver();

WebDriver driver= new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),dc);

driver.get("http://rediff.com");

}

}


@Test(priority = 1) //PDF COMPARISON

public void comparePDF01() {


try {

String file1 = "C:/driver/Doc1.pdf";

String file2 = "C:/driver/Doc2.pdf";

String resultFile = "C:/driver/results/result";


// new PdfComparator("expected.pdf",

// "actual.pdf").compare().writeTo("diffOutput.pdf");

new PdfComparator(file1, file2).compare().writeTo(resultFile);

System.out.println("Test Finished");


} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


}

@Test(priority = 2)

public void comparePDF02() {


try {

String file1 = "C:/driver/Doc1.pdf";

String file2 = "C:/driver/Doc2.pdf";

String resultFile = "C:/driver/results/result";


new PdfComparator(file1, file2).compare().writeTo(resultFile);

boolean isequals = new PdfComparator(file1, file2).compare().writeTo(resultFile);

System.out.println("Are PDF files similar : " + isequals);

System.out.println("Test Finished");


} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


@Test(priority = 3)

// include, exclude pages for comparison..

public void comparePDF03() {


try {

String file1 = "C:/driver/Doc1.pdf";

String file2 = "C:/driver/Doc2.pdf";

String resultFile = "C:/driver/results/result";

String ignoreFile = "C:/driver/results/result";


new PdfComparator(file1, file2).withIgnore(ignoreFile).compare().writeTo(resultFile);

boolean isequals = new PdfComparator(file1, file2).withIgnore(ignoreFile).compare().writeTo(resultFile);

System.out.println("Are PDF files similar : " + isequals);

System.out.println("Test Finished");


} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


}


@Test(priority = 1)

public void readPDFTest() throws MalformedURLException {

/*

* Use below dependency for PDF reading and parsing as content

* https://www.youtube.com/watch?v=jeN9WeTowGg <dependency>

* <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId>

* <version>2.0.20</version> </dependency>

*/


WebDriver driver = new ChromeDriver();

driver.get("URL");

String currentUrl = driver.getCurrentUrl();

System.out.println(currentUrl);


// URL url = new URL("path of pdf url"); If you don't want to use chrome

URL url = new URL(currentUrl);

InputStream is;

try {

is = url.openStream();

BufferedInputStream fileParse = new BufferedInputStream(is);

PDDocument document = null;


document = PDDocument.load(fileParse);

String pdfContent = new PDFTextStripper().getText(document);

System.out.println(pdfContent);


Assert.assertTrue(pdfContent.contains("Emp"));

Assert.assertTrue(pdfContent.contains("Company"));


} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


}


// **************POM Model testNG Create LoginPage2 factory and import that page

// to the VerifyWordPressLogin2 test class

// PAGE OBJECT MODEL http://code.google.com

/*

*/


public class LoginPage2 {

WebDriver driver;

By username = By.id("user_login");

By password = By.xpath(".//*[@id='user_pass']");

By loginButton = By.name("wp-submit");


// constructor

public LoginPage2(WebDriver driver) {

this.driver = driver;

}


public void LoginToWordPress(String userid, String userpwd) {

driver.findElement(username).sendKeys(userid);

driver.findElement(password).sendKeys(userpwd);

driver.findElement(loginButton).click();

}

}

public class VerifyWordPressLogin2 {

WebDriver driver;

@Test

public void verifyValidLogin() {

System.setProperty("webdriver.chrome.driver", "C:/Users/vmuriki/Documents/VM/SW/chromedriver.exe");

driver = new ChromeDriver();

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

driver.get("http://demosite.center/wordpress/wp-login.php");


LoginPage2 login = new LoginPage2(driver);

login.LoginToWordPress("admin", "demo123");

driver.quit();

}

}

}}}}

No comments:

Post a Comment