Automation - Selenium

 Installation:

Java

JRE

Maven dependencies

Install Testing and add dependency in POM

----------


Components:

WebDriver, Grid, IDE

Webdriver is Interface: 

Chrome Driver/ Firefox driver/ Edge Driver etc (Classes)

-----

WebDriver driver = new ChromeDriver()

driver.get()

.get title()

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

driver.findElement(By.id).is displayed()

For single element:

------

id

Name

Linktext

PartialLinkText

For group of elements

-----

TagName "a[href]" for links "img" for images

Class

-----

findElement(loc) Ret WebElement

findElement s(loc) Ret List<WebElement>

------

CSS (Cascading style sheet) - 

Traverse top to bottom

tag#id

tag.classname

tag[attribute=”value”]

tag.classname[attribute=”value”]

SelectorsHub- Extension

------

Xpath ( All directions)

//input[@name='search'][@placeholder='search']

//a[text()='MacBook'] - xpath using innerText

//input[contains(@placeholder,'Sear')]

starts-with

Chained xpath: //div[@id='logo]/a/img

Self, parent, ancestor, child, descendent, preceding-sibling, following-sibling

//input[@id='001']/Parent::div

//input[@id='001']/Parent::*

--------

Get Methods through driver instance 

get(URL)

getTitle()

getCurrentUrl()

getPageSource()

getWindowHandle()

getWindowHandles()

-----

Browser Methods

Close() - One window

Quit() - All windows

------

Conditional Methods : access via WebElement ( Boolean value)

isDisplayed()

isEnabled()

isSelected()

-----

ElementNotFoundException: Incorr loc

NoSuchElementException : Sync issue

Thread.sleep(30000)

driver.manage().timeouts().implicit Wait(Duration.ofSeconds(5)):

Explicit wait

Fluent wait:

wait<WebDriver> wait = new Fluent wait WebDriver> (driver)

------

Navigational Commands

Navigate().to()/ back()/ forward() / refresh()

Navigate().to() - accepts URL in string and object format

------

driver.SwitchTo().window(windowID)

------

Checkboxes

-----

Alert ( Not a webElement - Alert)

1) Normal driver.switchTo().alert().accept()/dismiss()

2) Confirmation

3) Prompting

.getText()

.sendKeys(text)

4) Authenticated popup

https://admin:admin@www.google.com

----------

Frames/iframes (Mostly with desktop app)

driver.switchTo().frame(WebElement)

Name.Id, Index also can be passed

driver.switchTo().defaultContent()

--------

Dropdown

1) select dropdowns

selectByVisibleText()

selectByValue() - Attribute in html

selectByIndex()

.getOptions(). - Get and store in List<WebElement>

2) Bootstrap (Need to use only xpath)

3) Hidden : SelectorHub: Turn on Debugger (5sec)

Opt2: EventListeners- Remove Blur option

4) Auto Suggest dropDown ( Xpath)

--------

Tables

Static web tables

rows.size()

columns.size()

"+r+" - Add index value in xpath

Dynamic web tables:

Table with pagination:

subStr()

indexOf()

---------

Calendar:

1) Set Expected date

2) use While Loop

3) Find locator for month and year

4) Compare Expected with current Year and month: If match break else click on next/previous

5) Find common locator for all the dates and store in List. Itearate using for loop and compare with expected date using if else and click


Complex Calendar: Month comparison

Convert Month to Object using Month class

Compare months using CompareTo method

CompartTo gives results : 0 + -

Break if result is 0 and cliss next if result is +

---------------------------

Action

Mousehover - moveToElement().perform()

Doubleclick- doubleClick().perform()

Right Click- contextClick().perform()

draganddrop- dragAndDrop().perform()

.getText : When inner text is available

.getAttribute(Value): When inner text is miss

Action: Interface to store created actions

Actions: Class

-----------------

Slider

min_slider.getLocation().getX()/getY()

act.dragAndDropBy(min_slider, x, y).perform()

100: Move forward

-100: Move backword

----------------------

Keyboard

act.KeyDown(keys.CONTROL).sendKeys(A).keyUp(keys.CONTROL).perform()

Open link in new tab: CTRL + Click

------------SwitchTo()--------------

driver.switchTo().window()

driver.switchTo.frame()

driver.switchTo.alert()

switchTo.newWindow(WindowType.Tab)

(WindowType.Window)

------------- JavascriptExecutor je = driver---------

executeScript()

Element intercepted exception- Error

je.executeScript("arguments[0].setAttribute('value','amit')",ele)

arguments[].click()

SCROLLING

arguments[0].scrollIntoView()

document.body.style.zoom='50%'

------------File upload----------

Single file: File location

Multiple files:(File1 +"\n"+ File2)

---------Capture Screenshots----

TakesScreenshot - Interface

TakesScreenshot ts = driver (Req typecast)

ts.getScreenshotAs(OutputType.FILE)

File sourcefile=

File targetfile = new File("location")

sourcefile.renameTo(targetfile)

1) Full page 

2) partial page

3) WebElement

------HeadlessOption--

ChromeOptions opt= new ChromeOptions()

opt.addArgument("--headless=New")

WebDriver  driver= new ChromeDriver(opt)

-----Handle SSL certificates:

options.setAcceptInsecureCerte(true);

----Hide Automation message

options.setExperimentalOption("exclude switches", new String[] {"enable-automation"}

-----------Run in incognito

hromeOptions opt= new ChromeOptions()

opt.addArgument("--incognito")

--------- Add extention 

1) Add CRX Extractor to chrome

2) Capture crx file for extension- Rightclick

3) Pass crx file path in automation script

options.addExtensions(file)

----------

Broken Links

1) Capture all links from website using a tag

2.1) Read link and capture href attribute

2.2) check if href is available else print error and continue

3.1) convert href to URL

3.2) Create connection openConnection()

5) Check if responsecode>400

----------

Shadow DOM

Shadow Host-->Shadow Root-->Shadow Ele

SearchContext shadow =driver...... By.cssSelector("host").getShadowRoot()

shadow.findElement(By.cssSelector(#ele)

---------SVG tags--------Icons on website

Doesn't work with normal xpath

Need to use name attribute

-----------------------Data driven----------

Read data :

FileInputStream

XSSFWorkbook

XSSFworksheet

NoOfRows:

NoOfCells

XSSFRow

XSSFCell

Read data using For loop

Close the workbook and File


Write data:

Create utility:

FileOutputStream fos

Create workbook wb

Create worksheet

Create Row

Create cell

cell.setCellValue()

wb.write(fos)

wb.close()

fos.close()

----------Data driven Usecase------

1) Create utility

2) Get Number of rows

3) Read data from file using utility and store in variables (For loop)

4) find elements and pass the above variables

5) Compare the results and write result in the same file

-----------Properties file------plain text/No syntax

FileOutputStream fos

Properties prop = new Properties()

prop.load(fos)

prop.getProperty("url");

prop.keySet();

prop.values();

fos.close();

---------------TestNG------

XML: Suite--Test--Classes-Class

Suite-Test-Class-Method-Test

Class- Testcase

@Test(priority=1)

@BeforeMethod : Before every method

@AfterMethod: After every method


@BeforeClass: Once before all Tests

@AfterClass: Once after all Tests


@BeforeTest:XML level (One test multiple classes)

@AfterTest:1st round/2nd round


@BeforeSuite : Smoke/Sanity/Regression

@AfterSuite

---------

Assertions

Hard Assertions: Code breaks after assert

With conditional statements

Assert.assertTrue(true)

Assert.assertTrue(False)

Without conditional statements

Assert.assertEquals(exp, act)

Assert.assertNotEquals()

Assert.fail()

Soft Assertions: Code gets executed post assertion as well, rarely used

SoftAssert sa = new SoftAssert()

sa.assertEquals()

sa.assertAll() -- Mandatory rule

----------Dependency-----

If one fails another will not run

@Test(dependsOnMethods={"open app"})

------Grouping-----

Changes in XML

<groups><run><include><exclude>

<!--       --> : Used for comments

@Test(groups={"sanity"})

----------DataProvider-----

Returns 2D data always

@DataProvider(name="dp", indices={0,1})

@Test(dataProvider="dp")

----------Parameter------Cross browser Testing

<parameter name="browser" value="chrome"/>

@Parameters("browser")

Switch or if else can be used to retrieve and create driver in the method

Parallel Execution: 

<suite name = "Suite" Parallel="tests">

------Listener--------Post execution

.class file is created which has methods from ITestListener interface

onStart(ITestContext context)

onTestSuccess(ITestResult result)

onTestFail()

onTestSkip()

- Tag can be added in XML

<listeners>

<listener class-name = day45.EventReport>

</listeners>

----------Extent -----Report creation

Dependency can be added and used

--------------

Page Object Model: Design pattern

Two Ways: 1) By class 2) PageFactory

By class:

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

PageFactory:

PageFactory.initElements(driver,this)

@findBy(xpath="")

@findBy(how=How.XPATH, using="")

WebElement textUser;

List<WebElement>  links  

------

1) Identify pages

2) Create page with elements+ Action methods

3) Test class: Write test method and add validation

Steps:

1) Create constructor

2) Create Locator

3) Create Action methods

-------

Framework

Built in: testng, junit, cucumber, robot

Customized: (User defined): Data driven, keyword driven, hybrid 

Phases:

1) Analyzing AUT

2) Choose Testcases (Automatable/Not)

3) Design and development of framework

4) Execution - local, remote

5) Maintenance 

Logging: 

Loggers: All<Trace<Debug<Info<Warna<Error<Fatal<Off

Appenders: Where to generate (Console/File)

1) Add dependency in pom.xml

2) Download and add log4j2.xml in Resources folder or any other

4) Check appenders and Loggers

5) Add code in Baseclass setup method

public Logger logger;

logger= LogManager.getLogger(this.getClass())

6) Then add logger in test cases wherever needed (logger.info("")

------

Extent reports:

Create Extentreport class in Utilities

implements ITestListener

Add all listener methods

Create screenshot method in basement class.

Call from onFail() method : Take the location and add in test report

Add listener class entry in testng.xml file.

----------

How to run failed testcases 

test-output folder has testing-failed.xml

--------Selenium Grid -----

DesiredCapabilities class :

capbilities.setPlatform(platform.MAC)

capabilities.setBrowserName("")

driver = new RemoteWebDriver (new URL (""), capabilities);


Docker - Images- Containers- Nodes

Image commands

Install Docerhub

docker images

docker pull ubuntu

docker rmi <image id>

Container commands

docker ps: Running containers

docker run <image name>

docker start ubuntu

docker stop ubuntu

docker network create grid: Create network

No comments:

Post a Comment