Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, October 1, 2024

Run two browsers simultaneously in Selenium

 package TEST;


import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.firefox.FirefoxDriver;


public class Selenium_Latest {


public static void main(String[] args) {

// Create and start two threads, one for each browser.

Thread chromeThread = new Thread(new BrowserRunnable("chrome"));

Thread firefoxThread = new Thread(new BrowserRunnable("firefox"));


chromeThread.start();

firefoxThread.start();

}


}


// Runnable class for launching a browser

class BrowserRunnable implements Runnable {

private String browserType;


public BrowserRunnable(String browserType) {

this.browserType = browserType;

}


@Override

public void run() {

WebDriver driver = null;


if (browserType.equals("chrome")) {

driver = new ChromeDriver();

} else if (browserType.equals("firefox")) {

driver = new FirefoxDriver();

}


if (driver != null) {

driver.get("https://suriyaparithy.blogspot.com/");


// Optionally, get the title and print it for each browser

String title = driver.getTitle();

System.out.println(browserType + " Browser - Page Title: " + title);


// Closing the browser after operation

driver.quit();

}

}

}

Saturday, July 27, 2024

Java Selenium Script to Extract Two Numbers from a Web Page Automatically

 package system;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;

public class Practice {

   WebDriver driver;

@BeforeMethod
public void setUp() {
  WebDriverManager.chromedriver().setup();
  driver = new ChromeDriver();
}

@Test(description = "extraction of two numbers from a web page")
public void test() throws InterruptedException {

driver.get("https://ultimateqa.com/complicated-page");

// Locate the element containing the CAPTCHA question
WebElement captchaElement = driver.findElement(By.className("et_pb_contact_captcha_question"));

// Extract the CAPTCHA question text
String captchaText = captchaElement.getText().trim(); // Example: "5 + 6"

// Split the text to get the operands
String[] parts = captchaText.split("\\+");
int firstNumber = Integer.parseInt(parts[0].trim());
int secondNumber = Integer.parseInt(parts[1].trim());

// Calculate the sum
int sum = firstNumber + secondNumber;

// Print the sum (for debugging purposes)
System.out.println("Extracted Numbers: " + firstNumber + " + " + secondNumber + " = " + sum);

// Enter the sum into the CAPTCHA input field
WebElement captchaInputField = driver.findElement(By.className("et_pb_contact_captcha"));
captchaInputField.sendKeys(String.valueOf(sum));
}
}

Monday, June 10, 2024

How to Handle Checkboxes in Selenium

 package com.system.patternz;

import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;

public class Practice {
WebDriver driver;

@BeforeMethod
public void setUp() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.get("https://testautomationpractice.blogspot.com/");
driver.manage().window().maximize();
}

@Test(enabled = true, priority = 0, description = "how to select specific checkboxes")
public void test1() throws InterruptedException {
driver.findElement(By.id("sunday")).click();
Thread.sleep(3000);
}

@Test(enabled = true, priority = 1, description = "how to select all checkboxes")
public void test2() throws InterruptedException {
List<WebElement> list = driver.findElements(By.xpath("//*[@class='form-group'][4]//div"));
for (WebElement x : list) {
x.click();
}
}

@Test(enabled = true, priority = 2, description = "how to select multiple checkboxes by choice")
public void test3() throws InterruptedException {
ArrayList<String> list3 = new ArrayList<String>();
list3.add("Sunday");
list3.add("Wednesday");
list3.add("Saturday");
System.out.println(list3);
List<WebElement> list1 = driver.findElements(By.xpath("//*[@class='form-group'][4]//div"));
for (WebElement x : list1) {
String str = x.getText();
for (String x1 : list3) {
if (str.equals(x1)) {
x.click();
Thread.sleep(3000);
}
}
}
}

@Test(enabled = true, priority = 3, description = "how to select multiple checkboxes by choice")
public void test4() throws InterruptedException {
List<WebElement> list1 = driver.findElements(By.xpath("//*[@class='form-group'][4]//div//input"));
for (WebElement x : list1) {
String str = x.getAttribute("id");
if (str.equals("monday") || str.equals("wednesday") || str.equals("saturday")) {
System.out.println("next click");
x.click();
Thread.sleep(3000);
} else {
System.out.println("not found");
}
}
}

@Test(enabled = true, priority = 4, description = "how to select last 2 checkboxes")
public void test5() throws InterruptedException {
List<WebElement> list = driver.findElements(By.xpath("//*[@class='form-group'][4]//div"));
int totalcheckboxes = list.size();
for (int i = totalcheckboxes - 2; i < totalcheckboxes; i++) {
list.get(i).click();
}
}

@Test(enabled = true, priority = 5, description = "how to select first 2 checkboxes")
public void test6() throws InterruptedException {
List<WebElement> list = driver.findElements(By.xpath("//*[@class='form-group'][4]//div"));
int totalcheckboxes = list.size();
for (int i = 0; i < totalcheckboxes; i++) {
if (i < 2) {
list.get(i).click();
Thread.sleep(3000);
}
}
}
}

Selenium test run without using System.setProperty in the code

 package com.system.pattern;


import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

import io.github.bonigarcia.wdm.WebDriverManager;


public class Practice {


WebDriver driver;


@BeforeMethod

public void setUp() {

WebDriverManager.chromedriver().setup();

driver = new ChromeDriver();

}


@Test(description = "Selenium test run without using System.setProperty in the code")

public void test() {

driver.get("https://suriyaparithy.blogspot.com/");


}

}


Chrome version - 125.0.6422.141


Webdrivermanager version - 5.5.3

How to Easily Read Chrome Driver Files from the src/main/resources Folder

 package com.system.pattern;


import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.Test;


public class NewTest {


WebDriver driver;


@Test(description = "chrome webdriver found under src/main/resources")

public void chrome() {


String chromeDriverPath = System.getProperty

("user.dir") + "/src/main/resources/chrome/chromedriver";

System.setProperty("webdriver.chrome.driver", chromeDriverPath);

driver = new ChromeDriver();

driver.get("https://suriyaparithy.blogspot.com/");


}

}

Wednesday, March 29, 2023

How To Use CROSS BROWSER TESTING IN SELENIUM WEBDRIVER

 package Practice;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.firefox.FirefoxOptions;

import org.testng.annotations.Test;

import io.github.bonigarcia.wdm.WebDriverManager;

public class WebDriver {

@Test

public void testChrome() {

ChromeOptions chromeOptions = new ChromeOptions();

WebDriverManager.chromedriver().setup();

ChromeDriver driver = new ChromeDriver(chromeOptions);

driver.get("https://suriyaparithy.blogspot.com/");

driver.quit();

}

@Test

public void testFirefox() {

FirefoxOptions firefoxOptions = new FirefoxOptions();

WebDriverManager.firefoxdriver().setup();

FirefoxDriver driver = new FirefoxDriver(firefoxOptions);

driver.get("https://suriyaparithy.blogspot.com/");

driver.quit();

}

}


testng.xml file:

<suite name="My Test Suite" parallel="tests">

<test name="Chrome Test">

<classes>

<class name="Practice.WebDriver">

<methods>

<include name="testChrome" />

</methods>

</class>

</classes>

</test>

<test name="Firefox Test">

<classes>

<class name="Practice.WebDriver">

<methods>

<include name="testFirefox" />

</methods>

</class>

</classes>

</test>

</suite>

Tuesday, March 28, 2023

Quick & Easy Method to Send TestNG Reports via Email in Selenium WebDriver

package Practice;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

public class SendMailSSLWithAttachment {

public static void main(String[] args) {

// Create object of Property file

Properties props = new Properties();

// this will set host of server- you can change based on your requirement

props.put("mail.smtp.host", "smtp.gmail.com");

// set the port of socket factory

props.put("mail.smtp.socketFactory.port", "465");

// set socket factory

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

// set the authentication to true

props.put("mail.smtp.auth", "true");

// set the port of SMTP server

props.put("mail.smtp.port", "465");

// This will handle the complete authentication

Session session = Session.getDefaultInstance(props,

new javax.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication("youremail@gmail.com", "email-app-password");

}

});

try {

// Create object of MimeMessage class

Message message = new MimeMessage(session);

// Set the from address

message.setFrom(new InternetAddress("from@gmail.com"));

// Set the recipient address

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("s@gmail.com"));

// Add the subject link

message.setSubject("Automation Testing Report");

// Create object to add multimedia type content

BodyPart messageBodyPart1 = new MimeBodyPart();

// Set the body of email

messageBodyPart1.setText("This is testng report");

// Create another object to add another content

MimeBodyPart messageBodyPart2 = new MimeBodyPart();

// Mention the file which you want to send

String filename = "D:\\SURIYA\\test-output\\emailable-report.html";

// Create data source and pass the filename

DataSource source = new FileDataSource(filename);

// set the handler

messageBodyPart2.setDataHandler(new DataHandler(source));

// set the file

messageBodyPart2.setFileName(filename);

// Create object of MimeMultipart class

Multipart multipart = new MimeMultipart();

// add body part 1

multipart.addBodyPart(messageBodyPart2);

// add body part 2

multipart.addBodyPart(messageBodyPart1);

// set the content

message.setContent(multipart);

// finally send the email

Transport.send(message);

System.out.println("=====Email Sent=====");

} catch (MessagingException e) {

throw new RuntimeException(e);

}

}

}

NOTE:

  1. Download this repository
  • https://mvnrepository.com/artifact/javax.mail/javax.mail-api/1.6.2
  • https://mvnrepository.com/artifact/com.sun.mail/javax.mail/1.6.2
  • https://mvnrepository.com/artifact/javax.activation/activation/1.1.1

Friday, March 24, 2023

Automating Image Upload using Selenium WebDriver: A Step-by-Step Guide

 package Practice;

import java.awt.AWTException;

import java.awt.Robot;

import java.awt.Toolkit;

import java.awt.datatransfer.StringSelection;

import java.awt.event.KeyEvent;

import java.time.Duration;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

public class Get_Photo {

@SuppressWarnings("deprecation")

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

System.setProperty ("webdriver.chrome.driver", "D:\\SURIYA\\chromedriver.exe");

WebDriver driver = new ChromeDriver();

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

driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));

driver.get("http://localhost:3000/SignUp");

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

// identify image

WebElement ph = driver.findElement(By.xpath("//button[normalize-space()='photo']"));

ph.click();

Thread.sleep(2000);

Robot rb = new Robot();

StringSelection str = new StringSelection("C:\\Users\\Admin\\Surya.jpg");

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(str, null);

// press Contol+V for pasting

rb.keyPress(KeyEvent.VK_CONTROL);

rb.keyPress(KeyEvent.VK_V);

// release Contol+V for pasting

rb.keyRelease(KeyEvent.VK_CONTROL);

rb.keyRelease(KeyEvent.VK_V);

// for pressing and releasing Enter

rb.keyPress(KeyEvent.VK_ENTER);

rb.keyRelease(KeyEvent.VK_ENTER);

Thread.sleep(3000);

}

}

Thursday, March 23, 2023

QR Access: Simplify Your Entry Process with Java Code Implementation

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;

import com.google.zxing.LuminanceSource;

import com.google.zxing.MultiFormatReader;

import com.google.zxing.NotFoundException;

import com.google.zxing.Result;

import com.google.zxing.client.j2se.BufferedImageLuminanceSource;

import com.google.zxing.common.HybridBinarizer;

public class QR_Code_Scan {

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

File file = new File("D:\\SURIYA\\my_web.png");

BufferedImage bufferedimage = ImageIO.read(file);

LuminanceSource luminanceSource = new BufferedImageLuminanceSource(bufferedimage);

BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));

// To Extract information from QR code;

Result result = new MultiFormatReader().decode(binaryBitmap);

String decodedText = result.getText();

System.out.println(decodedText);

}

}

Tuesday, August 2, 2022

Read excel file in selenium webdriver using jxl

 package coaching;

import java.io.FileInputStream;

import java.io.IOException;

import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

import jxl.Sheet;

import jxl.Workbook;

import jxl.read.biff.BiffException;


public class JxlData {

WebDriver driver;

String [][] data = null;

@DataProvider(name="loginData")

public String [][] loginDataProvider() throws BiffException, IOException{

data=getExcelData();

// string change to object

// jxl jar used only xls format(97-2003 worksheet)

return data;

}

  public String[][] getExcelData() throws BiffException, IOException{

  

  FileInputStream excel = new FileInputStream("F:\\Suriya\\suri.xls");

   Workbook workbook = Workbook.getWorkbook(excel);

  Sheet sheet = workbook.getSheet(0); // sheet name

  int rowCount = sheet.getRows();

  int columnCount = sheet.getColumns();

  String testData[][] = new String[rowCount-1][columnCount];

  

  for (int i=1; i<rowCount;i++) {

  for (int j=0;j<columnCount;j++) {

  testData[i-1][j]=sheet.getCell(j, i).getContents();

  }

  }

   return testData;

  }

  @Test(dataProvider="loginData")

  public void login(String uName, String pword) {

  System.setProperty("webdriver.chrome.driver", "F:\\Suriya\\chromedriver.exe");

driver = new ChromeDriver();

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

driver.manage().deleteAllCookies();

driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));

driver.get("URL");

WebElement username = driver.findElement(By.id("userName"));

username.sendKeys(uName);


WebElement password = driver.findElement(By.id("pwd"));

password.sendKeys(pword);


WebElement login = driver.findElement(By.cssSelector(".btn:nth-child(3)"));

login.click();

    }

}


Saturday, July 30, 2022

Selenium Tests using Data Provider and TestNG

 package coaching;


import java.io.File;

import java.io.FileInputStream;

import java.io.FileReader;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.time.Duration;

import java.util.Date;

import java.util.Properties;


import org.apache.commons.io.FileUtils;

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

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

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

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

import org.openqa.selenium.By;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.ITestResult;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.AfterTest;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;


import com.relevantcodes.extentreports.ExtentReports;

import com.relevantcodes.extentreports.ExtentTest;

import com.relevantcodes.extentreports.LogStatus;


public class Login_Page {

public WebDriver driver;

public ExtentReports extent;

public ExtentTest extentTest; //helps to generate the logs in test report.

@BeforeTest

public void setExtent(){

// initialize the HtmlReporter

extent = new ExtentReports("./src/test/resources/Reports/LoginPageReport.html", true); // true - new data insert into report,false-append the old data

//To add system or environment info by using the addSystemInfo method.

extent.addSystemInfo("User Name", "Suriya");

extent.addSystemInfo("Environment", "Automation Testing");

extent.addSystemInfo("Application","Learning Online Course "); 

extent.addSystemInfo("Test Scenario","Login Functionality");


}

@AfterTest

public void endReport(){


extent.flush(); // Flush method is used to erase any previous data on the report and create a new report.

//extent.close(); 

}

public static String getScreenshot(WebDriver driver, String screenshotName) throws IOException{

String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());

TakesScreenshot ts = (TakesScreenshot) driver;

File source = ts.getScreenshotAs(OutputType.FILE);

// after execution, you could see a folder "FailedTestsScreenshots"

// under src folder

String destination = System.getProperty("user.dir") + "/FailedTestsScreenshots/" + screenshotName + dateName

+ ".png";

File finalDestination = new File(destination);

FileUtils.copyFile(source, finalDestination);

return destination;

}

@BeforeMethod

public void setup() throws InterruptedException, IOException {


System.setProperty("webdriver.chrome.driver", "F:\\Suriya\\chromedriver.exe");

driver = new ChromeDriver();

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

driver.manage().deleteAllCookies();

driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));

driver.get("URL");

}

@Test (dataProvider = "getData") 

public void login(String Username, String Password) {

extentTest = extent.startTest("Enter username and password");

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));

WebElement username = driver.findElement(By.id("userName"));

username.sendKeys(Username);

WebElement password = driver.findElement(By.id("pwd"));

password.sendKeys(Password);

WebElement login = driver.findElement(By.cssSelector(".btn:nth-child(3)"));

login.click();

}

@DataProvider(name = "getData") 

// Declare a method whose return type is an array of object. 

    public Object[ ][ ] dataProviderMethod() 

    {

// Create an object of an array object and declare parameters 3 and 2. 

// 3 represents the number of times your test has to be repeated. 

// 2 represents the number of parameters in test data. Here, we are providing two parameters. 

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


// 1st row. 

      data[0][0] = "John"; 

      data[0][1] = "23RYRTE7E5"; 


// 2nd row. 

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

     data[1][1] = "40EEUE5"; 


// 3rd row. 

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

     data[2][1] = "01E575E"; 

      return data; 

   } 

@AfterMethod

public void Down(ITestResult result) throws IOException{


if(result.getStatus()==ITestResult.FAILURE){

extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS "+result.getName()); //to add name in extent report

extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS "+result.getThrowable()); //to add error/exception in extent report


String screenshotPath = getScreenshot(driver, result.getName());

extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath)); //to add screenshot in extent report

//extentTest.log(LogStatus.FAIL, extentTest.addScreencast(screenshotPath)); //to add screencast/video in extent report

}

else if(result.getStatus()==ITestResult.SKIP){

extentTest.log(LogStatus.SKIP, "Test Case SKIPPED IS " + result.getName());

}

else if(result.getStatus()==ITestResult.SUCCESS){

extentTest.log(LogStatus.PASS, "Test Case PASSED IS " + result.getName());


}



extent.endTest(extentTest); //ending test and ends the current test and prepare to create html report

driver.quit();

}

}