Sunday, June 28, 2020

Complete professional different Selenium script for Practice

A Real-Time time scenario


package test;

import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.Sleeper;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import okio.Timeout;


public class SeleniumTest {

WebDriver driver;
 //( webdriver is a interface and firebox,chrome,edge driver is a classes) driver is a reference of webdriver. chromeDriver driver = new ChromeDriver(); this driver calls from the webdriver and in addition of chromedriver too.

// multilaver inheritance: WebDriver(Interface) implements RemoteWebDriver (Super class) extents ChromeDriver


//@Beforeclass //execute only one times at starting,if we need to invoke browser one time only one times
//@AfterClass //execute only one at end of test, if we want to close browser at a end then..
// BeforeMethod and AfterMethod executes in every Test case
@BeforeMethod
public void invokeBrowser() {
System.setProperty("webdriver.chrome.driver", "C:/Dev/libs/chromedriver_win32/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();

/*Wait commands- 4 types. Selenium big challange is synchronization
*  PageLoadTimeout -waiting to page load. threshold value 60-90 sec, default is 1=-1,which means infinite time to get response. page waits for page to load successfully on browser, page takes more time then throw Page not foundException
*  Implicit wait - finds again elemnt till find the element, waits condition only check available in html code. by defaul -1, its zero.if you have interct with webelement , if that webelement is taking time then defining
* Explicit Wait -advanced version implicit. wait element is visibile ,invisible in the screen,element is  intractive, create out any condition, also called conditional wait
* Fluent Wait - maximum time to wait for a condition, wait a polling time, not used. it can use something comes after a minute.
*
* // explicit wait example

public void  waitTillElementVisible(int timeoutInseconds, By by) {
WebDriverWait wait = new WebDriverWait(driver, timeoutInseconds);
wait.until(ExpectedConditions.visibilityOf(by));
}
then use: this explicit wait on any webpage eg
By anylink = By.id("email");
waitTillElementVisible(10,anylink);
.....implicit wait 6 sec. max and min

......fuent wait - if time is taking some minute one particualr somewhere used
public static void fluentWait(WebDriver driver, int timeout, int pollingTime, By by){

        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(timeout))
.pollingEvery(Duration.ofSeconds(pollingTime))
.ignoring(NoSuchElementException.class);
wait.until(ExpectedConditions.visibilityOfElementLocated(by));
}
*/

driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);//default -1 ie infinite time, we keep 60-90 sec
driver.manage().timeouts().implicitlyWait(8, TimeUnit.MILLISECONDS);//we keep low generally 5-10 sec
}

@Test(priority = 100, groups = "Mulitple Wndow Handling", invocationCount = 5, enabled = false) //it repeats invocation
public void WindowHandling() throws InterruptedException {
driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_open");
String parentWindow = driver.getWindowHandle();
System.out.println("Parent Window Handle " + parentWindow);
driver.switchTo().frame("iframeResult");
driver.findElement(By.tagName("button")).click();

String childWindow;
childWindow = driver.getWindowHandles().toArray()[1].toString();
driver.switchTo().window(childWindow);
System.out.println("Child window Title" + driver.getTitle());

driver.close();

driver.switchTo().window(parentWindow);

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

}

@Test (priority =1100, groups = "Mouse Double click and Right Click ",invocationCount = 1)
public void DoubleRightClick() {
driver.get("http://demo.guru99.com/test/simple_context_menu.html");
// Double click the button to launch an alertbox
Actions action = new Actions(driver);
WebElement link = driver.findElement(By.xpath("//button[text()='Double-Click Me To See Alert']"));
action.doubleClick(link).perform();

// Switch to the alert box and click on OK button
Alert alert = driver.switchTo().alert();
System.out.println("I got a alert message: " + alert.getText());
alert.accept();

// Right click
WebElement rightClick = driver.findElement(By.xpath("//*[text()='right click me']"));
action.contextClick(rightClick).perform();

String textRightClick = driver.findElement(By.xpath("//ul[@class='context-menu-list context-menu-root']"))
.getText();
System.out.println("My right Click text is: " + textRightClick);

}
@Test(priority =1200, groups="Upload file from desktop and Download File from browser ")
public void UploadAndDownloadFile() {
// ..................UPload File .......................
driver.get("http://demo.guru99.com/test/upload/");

        WebElement uploadmyText = driver.findElement(By.id("uploadfile_0"));

        // enter the file path onto the file-selection input field
        uploadmyText.sendKeys("C:\\Dev\\a.txt");

        // check the "I accept the terms of service" check box
        driver.findElement(By.id("terms")).click();

        // click the "UploadFile" button
        driver.findElement(By.name("send")).click();
     

        driver.get("http://demo.guru99.com/test/yahoo.html");
        WebElement downloadButton = driver.findElement(By.id("messenger-download"));
        downloadButton.click();
     
        String sourceLocation = downloadButton.getAttribute("href");
        String wget_command = "cmd /c C:\\sf\\wget.exe -P D: --no-check-certificate " + sourceLocation;

        try {
        Process exec = Runtime.getRuntime().exec(wget_command);
        int exitVal = exec.waitFor();
        System.out.println("Exit value: " + exitVal);
        } catch (InterruptedException | IOException ex) {
        System.out.println(ex.toString());
        }
}

@Test(priority = 1000, groups = "Mastering WebElement  Xpath",  invocationCount = 1)
public void FindingWebElement() throws InterruptedException {
driver.get("https://www.facebook.com");
// using 'or' , 'and' => or is finding either of one . And is searching both
driver.findElement(By.xpath("//input[@name='firstname' or @id='u_0_10']"));
// or
// driver.findElement(By.xpath("//input[@type='email' or
// contains(@name,'email')]")).sendKeys("manoj@gmail.com");
driver.findElement(By.xpath("//input[@name='email' and @id='email']")).sendKeys("rabina");
driver.findElement(By.xpath("//input[contains(@id,'pass')]")).sendKeys("reange");
driver.findElement(By.xpath("//input[contains(@value,'Log In')]")).click();
String login;
login = driver.getTitle();
System.out.println("Facebook login title:" + login);

driver.get("http://demo.guru99.com/V4/");
/*
//xpath types conatins,start-with,text
* ..........................................
   //a[contains(text(),'Amazon Pay')] // contains www.amazon.com a- anchor tag
//a [text()='Amazon Pay'] // text means only one value ,exactly amzon pay. contains a method- how many value
//a[starts-with(text(),'Amazon')]  //
//input[starts-with(@class,'input')] //fb.com//we can search all value based on attribute and starting value
//input[contains(@name,'uid')]//demoguru94/v4
  //input[contains(@type,'te')]
   *
7 types Axes in selenium navigate to the direction it navigate to html:
1. ancestor,child, following, preceding, following-sibling,preceding-sibling,parent
.............................................................................

//input[@name='uid']//following-sibling::label //following:: or
// preceding-sibling::

// table[@id='customer']//td[text()='Customer ID']//following-sibling::td
//// table[@id='customer']//td[contains(text(),'Customer
// ID')]//following-sibling::td //table column
// or ////table[@id='customer']//td[text()='Customer ID']//following-sibling::td
// sibling after the node

// http://demo.guru99.com/V4/index.php how to use parent preceeding
//// input[@name='uid']//parent::td//preceding-sibling::td
// input[@name='uid']//ancestor::td //reach any parent.
//// input[@name='uid']//following::td //searching following the all node.it

// input[name='uid'] //css selector // http://demo.guru99.com/V4/index.php
// html input[name='uid'][type='text'] //css selector is fast
// html>body>form>table>tbody>tr>td>input
// .gw-col.gw-fixed-col.celwidget.csm-placement-id-744c1c0f-5dbe-430f-b384-779b5fcfe871
// // . (dot) operator is used in class.amazon .com.if there is multiple class
// inside
// #email //# (hash) operator is useed for id (fb.com)
// input[id^=email] //^(power symbol) used for starts-with
// input[id$=mail] // $ (dollar sign used for end-with)
// input[id*=mail] // * operator is used for contains method
* ...By.tagName("button")

*/


}
/*
@Test (priority = 1, groups ="Multiple Browser")
public void MultipleBrowser() throws InterruptedException {

System.setProperty("webdriver.chrome.driver", "C:/Dev/libs/chromedriver_win32/chromedriver.exe");
      driver = new ChromeDriver();
     
System.setProperty("webdriver.gecko.driver", "C:/Dev/libs/geckodriver.exe");
driver = new FirefoxDriver();

System.setProperty("webdriver.edge.driver", "C:/Dev/libs/MicrosoftWebDriver.exe");
driver = new EdgeDriver();

driver.get("https://qatechhub.com");
System.out.println(driver.getTitle());
Thread.sleep(1000000);
}

*/


// Printing page title and matching expected result and actual result
@Test(priority = 2000, groups = "Facebook",  invocationCount = 1)
public void verifyPageTitle() {
driver.get("https://www.facebook.com");
String Title = driver.getTitle();
System.out.println("My website title page is: " + Title);
// Assert.assertEquals(Title, "Facebook - Log In or Sign Up"); // both are same //

if (Title.equals("Facebook - Log In or Sign Up")) { // if "Title.cotains" => if partial text is match then test
// case pass
System.out.println("Test case 1 [Facebook login Page] - Passed");
} else {
System.out.println("Test case 1 [Facebook login Page] - Failed");
}

}
@Test (priority = 3000, groups = "DragAndDrop")
public void DragAndDrop() throws InterruptedException {
driver.get("https://jqueryui.com/droppable/");
WebElement webFrame = driver.findElement(By.className("demo-frame"));
driver.switchTo().frame(webFrame);
WebElement source = driver.findElement(By.id("draggable"));
WebElement target = driver.findElement(By.id("droppable"));

Actions action = new Actions(driver);   

// String colourBeforeDnD = target.getCssValue("color");
// action.dragAndDrop(source, target).build().perform();
action.moveToElement(source).clickAndHold().moveToElement(target).release().build().perform();

String colorAfterDnD = target.getCssValue("color");
// System.out.println("Color before Drag and Drop:"+ colourBeforeDnD);
// System.out.println("Color after Drag and Drop:"+ colorAfterDnD);

if (colorAfterDnD.contentEquals("rgba(119, 118, 32, 1)")){
System.out.println("Drag And Drop = Successfully drag and drop Element - passed");
} else {
System.out.println("Drag And Drop: Could not drop element - Failed");
}
driver.switchTo().defaultContent(); // it brings on a default browser

}
@Test (priority = 4000, groups = "AlertHandling")
public void AlertAndFrameHandling() throws InterruptedException {
driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert");
driver.switchTo().frame("iframeResult");
//driver.switchTo().defaultContent(); //when you wants to come out of a frame
driver.findElement(By.tagName("button")).click();
Alert alert = driver.switchTo().alert();
System.out.println("Oops, i got a alert:" + alert.getText());
alert.dismiss();
//      alert.accept();
}

@Test(priority = 5000, groups = "MouseHover")
public void mouseHover() throws InterruptedException {
driver.get("https://www.edureka.co");
driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
// catagory
WebElement catagory = driver.findElement(By.xpath("//a[@class='cat_btn hidden-xs giTrackElementHeader']"));
Actions builder = new Actions(driver);
builder.moveToElement(catagory).build().perform();
// Dev blockchain and click
WebElement devOps = driver.findElement(By.xpath("//a[@id=\"blockchain-certification-courses\" and @class='open_submenu_on_hover giTrackElementHeader'] "));
builder.moveToElement(devOps).click().build().perform();

//print blockchain Courses title
String title;
title = driver.getTitle();
System.out.println(title);
if (title.contains("Blockchain")) {
System.out.println("Hover - Test case is passed");
}
else {
System.out.println("Hover - Sorry, test case is failed.");
}

}

// Matching expected result and the actual result
@Test(priority = 6000, groups = "Google")
public void verifySecondPageTitle() {
driver.navigate().to("https://google.com");
boolean b = driver.findElement(By.id("hplogo")).isDisplayed();
Assert.assertTrue(b); // Assert.assertEquals = Assert.assertTrue [ both are same)
}

@Test(priority = 7000, groups = (" Navigation Command"))
public void navigationCommand() throws InterruptedException {
driver.get("https://www.southwest.com/");
String Title2 = driver.getTitle();
System.out.println("My website title page is: " + Title2);

driver.navigate().to("https://ebay.com/");
String Title3 = driver.getTitle();
System.out.println("My website title page is: " + Title3);
driver.navigate().back();

driver.navigate().forward();

driver.navigate().refresh();
}

@Test(priority = 8000, groups = "DropDwon &Creating Unique Email ")
public void DropDown() throws InterruptedException {
driver.get("https://www.facebook.com");
driver.findElement(By.name("firstname")).sendKeys("Manoj");
driver.findElement(By.name("lastname")).sendKeys("Adhikari");

//..............................Creating unique emailId & multiple email id..................................................
String emailId = "manoj" + System.currentTimeMillis() + "@gmail.com";
System.out.println("My Automatic generated email id: " + emailId);

driver.findElement(By.name("reg_email__")).sendKeys(emailId);
driver.findElement(By.name("reg_email_confirmation__")).sendKeys(emailId);
driver.findElement(By.name("reg_passwd__")).sendKeys("Mall1234@@");

//..............................Creating unique emailId & multiple email id..................................................
WebElement selDropdown;

selDropdown = driver.findElement(By.name("birthday_month"));
Select birthday_month = new Select(selDropdown);
birthday_month.selectByVisibleText("Jul");

selDropdown = driver.findElement(By.name("birthday_day"));
Select birthday_day = new Select(selDropdown);
birthday_day.selectByVisibleText("24");

selDropdown = driver.findElement(By.name("birthday_year"));
Select birthday_year = new Select(selDropdown);
birthday_year.selectByVisibleText("1994");

driver.findElement(By.xpath("//input[@value='2']")).click();
driver.findElement(By.name("websubmit")).click();
Thread.sleep(100);
}

@AfterMethod
public void tearDown() {
driver.close();
}

}

No comments:

Post a Comment