Thursday, March 30, 2023

Where Can You Find Free SELENIUM REAL TIME PROJECT Resources

 This project includes the following frameworks and libraries:
  1.  ChromeOptions
  2.  TestNG
  3.  Maven
  4.  Extent Report
  5.  Data Provider Method
  6.  Excel File Read (JXL)
  7.  Send Reports Automatically to Email
  8.  Failed Tests Screenshots
Selenium Code:

package Practice;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.lang.reflect.Method;

import java.text.SimpleDateFormat;

import java.time.Duration;

import java.util.Date;

import java.util.Properties;

import java.util.concurrent.TimeUnit;

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;

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import org.testng.ITestResult;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.AfterSuite;

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;

import jxl.Sheet;

import jxl.Workbook;

import jxl.read.biff.BiffException;

public class Selenium_Test {

public WebDriver driver;

public ExtentReports extent;

public ExtentTest extentTest;

@SuppressWarnings("deprecation")

@BeforeMethod

public void setup(Method method) {

ChromeOptions chromeOptions = new ChromeOptions();

chromeOptions.addArguments("--remote-allow-origins=*");

this.driver = new ChromeDriver(chromeOptions);

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

driver.manage().deleteAllCookies();

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

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

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

extentTest = extent.startTest(method.getName(), "This is a test for " + method.getName());

}

@BeforeTest(alwaysRun = true)

public void setExtent() {

extent = new ExtentReports("./test-output/Reports/Report.html", true);

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

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

extent.addSystemInfo("Application", "Blog");

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

}

public 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);

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

+ screenshotName + dateName + ".png";

File finalDestination = new File(destination);

FileUtils.copyFile(source, finalDestination);

return destination;

}

// DATA PROVIDER METHOD in JXL

String[][] data = null;

@DataProvider(name = "loginData")

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

data = getExcelData();

return data;

}

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

FileInputStream excel = new FileInputStream("D:\\SUR\\src\\test\\resources\\login.xls");

Workbook workbook = Workbook.getWorkbook(excel);

Sheet sheet = workbook.getSheet(0);

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(enabled = true, priority = 1)

public void testExcelData() {

System.out.println("suriya");

}

@AfterMethod(alwaysRun = true)

public void Down(ITestResult result) throws IOException {

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

extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS " + result.getName());

extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS " + result.getThrowable());

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

extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath));

} 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);

// driver.quit();

}

@AfterTest(alwaysRun = true)

public void endReport() {

extent.flush();

// extent.close();

}

@AfterSuite

public void sendEmailReport() {

Properties props = new Properties();

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

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

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

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

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

Session session = Session.getDefaultInstance(props,

new javax.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication("yourgmail@gmail.com", "your app password");

}

});

try {

Message message = new MimeMessage(session);

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

message.setRecipients(Message.RecipientType.TO,

InternetAddress.parse("email1@gmail.com, email2@gmail.com"));

message.setSubject("Automation Testing Report");

BodyPart messageBodyPart1 = new MimeBodyPart();

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

String[] filenames = { "D:\\SURIYA\\test-output\\emailable-report.html",

"D:\\SURIYA\\test-output\\index.html" };

Multipart multipart = new MimeMultipart();

for (String filename : filenames) {

MimeBodyPart messageBodyPart = new MimeBodyPart();

DataSource source = new FileDataSource(filename);

messageBodyPart.setDataHandler(new DataHandler(source));

messageBodyPart.setFileName(filename);

multipart.addBodyPart(messageBodyPart);

}

message.setContent(multipart);

Transport.send(message);

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

} catch (MessagingException e) {

throw new RuntimeException(e);

}

}

}

Wednesday, March 29, 2023

Webdriver Manager: A Comprehensive Overview of Its Benefits

WebDriverManager is a library in Java that allows for easy setup and management of web drivers for different browsers such as Chrome, Firefox, and Edge. The main benefits of using WebDriverManager are:

1. Automatic driver management: WebDriverManager automatically downloads the required driver binaries and sets up the system properties, making it easier to use different web drivers without manual intervention.

2. Easy setup: Using WebDriverManager eliminates the need to download and set up the web driver executable file separately. The library handles everything for you.

3. Cross-platform support: WebDriverManager supports multiple operating systems, including Windows, Mac, and Linux.

4. Integration with testing frameworks: WebDriverManager can be easily integrated with popular testing frameworks like JUnit and TestNG, allowing for seamless web driver management during test automation.

5. Improved maintenance: By using WebDriverManager, you can avoid issues related to outdated driver versions or incompatible operating systems. It helps ensure that you have the latest version of the driver, thereby reducing the maintenance effort required to keep your test automation suite up-to-date.



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

The Quickest & Easiest Way To SEND TESTNG REPORT THROUGH 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

Headless Browser Testing in Selenium: Best Tools and Frameworks to Use

 import java.io.IOException;

import org.openqa.selenium.NotFoundException;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

public class Headless_Browser {

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

ChromeOptions options = new ChromeOptions();

options.addArguments("headless");

WebDriver driver = new ChromeDriver(options);

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

System.out.println("Title of the page is -> " + driver.getTitle());

}

}

The Power of API Testing: How it Can Save Your Business Time and Money

 1. Core Functionality Testing: 

  • This kind of testing provides access to the entire system without the need for a user interface. The functionalities of the application would be evaluated end-to-end without the need for GUI (Graphical User Interface) which helps in detecting issues that can prove to be bigger at the time of GUI testing.

2. Time and Cost Effectiveness: 

  • This is usually less time-consuming when compared to GUI testing. It also requires less code for testing the functionalities thereby making it easier to set up and get faster access to test coverage. It also results in effective cost savings for the project.

3. Language-Independent: 

  • The data transfer between the test platform to the applications is done utilizing XML or JSON and is completely independent of the languages used in developing the systems. The test automation suite can be developed in any language.

4. Ease of Integration with GUI:

  •  API testing provides highly flexible test suites that help in easier integration with the GUI tests. For instance, before the GUI test cases are initiated, employing API test cases, we can create sample users that can act as an initial base for the GUI tests.

The Power of Headless Browser Testing: Enhancing Your QA Strategy

What is Headless Testing?
  • Headless testing is a method for evaluating a website’s or online application’s functionality without having to use a web browser. The test script simulates operations like clicking buttons and filling out form fields by sending commands directly to the website’s source code rather than engaging with it through the UI. As a result, testing may be done more quickly and effectively because there is no need to load a full web browser; the test script can instead run in the background.

Advantages of Headless Testing:
  1.  Speed of Execution: Headless tests run substantially quicker than tests executed on a real browser. The primary reason for this is that your tests aren’t having to start up a browser UI each time. This means they can avoid the time it takes a real browser to load JavaScript, CSS, and render HTML on a website. I’ve seen estimated execution time savings in the range of 7-15%.
  2.  CICD: Because it is so much quicker, it makes it ideal for continuous integration and delivery (CI/CD) pipelines.
  3.  Server Testing: It can also be helpful for testing web applications in contexts without a UI, such as servers.
  4.  Multi-Tasking: The test script can run in the background and finish tests more rapidly because it does not need to open a full web browser.
  5.  Shift-Left: Because it runs so much quicker than real browser testing, you can get the results of your testing much faster.

Disadvantages of Headless Testing:
  1.  User Experience: Headless testing may not always correctly imitate the user experience, which is one potential problem. The test script may not always correctly reflect how a user would actually interact with the website or web application because it is engaging directly with the source code rather than through a UI.
  2.  UX or Visual Design: Additionally, headless testing might not be able to completely test specific features of a website or web application, including the user interface or visual design.
  3.  Debugging: Debugging with headless can be challenging. Typically you will need to run the traditional way to get to the bottom of failures.
  4.  Real-time test execution visual: When running headless you don’t get the option to watch your test running on the UI.

Headless Testing Use Cases:
  •  Simulating multiple browsers on a single machine.
  •  Running tests on a headless system without a UI.
  •  Element testing – since headless browsers render and interpret CSS & HTML like a real browser, you can use them to test style elements such as buttons, forms, links, etc…
  •  Extracting values from a page/scraping.
  •  Extracting a PDF.
  •  Generate test data.
  •  Performance issues such as SSL, front- and back-end code, and load considerations, as well as non-graphic elements such as response time, error handling, and access to remote resources, can all be evaluated using headless testing.

Common Headless Browsers:
  •  For headless testing, a number of tools and frameworks are available, including Headless Chrome, PhantomJS, HtmlUnit, Firefox, Puppeteer, and Splinter. These tools allow you to create and execute test scripts in a number of different computer languages, such as Java, Python, and JavaScript.

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);

}

}

Wednesday, March 22, 2023

Essential Points to Include in Your Checklist for Testing a Web Application

PDF - Testing of Web Application

Step-by-Step Guide: Connecting MySQL with Eclipse for Seamless Database Management

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class Mysql {

private static final String DB_URL = "jdbc:mysql://localhost:3306/local";

private static final String DB_USERNAME = "root";

private static final String DB_PASSWORD = "your_password";

@SuppressWarnings("unused")

public static void main(String[] args) {

try {

Connection con = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);

System.out.println("Connected to the database.");

Statement statement = con.createStatement();

ResultSet resultSet = statement.executeQuery("SELECT * FROM trial_user");

while (resultSet.next()) {

int id = resultSet.getInt("demoid");

String email = resultSet.getString("email");

String exam = resultSet.getString("exam");

String password = resultSet.getString("password");

String phoneno = resultSet.getString("primarycontactphoneno");

System.out.println(id + " " + email + " " + phoneno);

}

} catch (SQLException ex) {

System.err.println("Error occurred while connecting to the database: " + ex.getMessage());

}

}

}

Tuesday, March 21, 2023

Building Java Projects Made Easy with Maven

 Maven:

  •  Maven is a project management tool or software build tool or dependency management tool.
  •  It is used for project build or dependencies.

Maven addresses two aspects:

 1. It describes how software is built.

 2. It describes the software dependencies.

  • In Maven execution starts from the pom.xml file, it reads the POM.xml file and starts execution.

Uses of Maven:

  •  It is used to build the software application, manage your dependencies, run your tests, and create reports.

Maven Structure:

 src/main/java

 src/main/resources

 src/test/java

 src/test/resources

 JRE System library

 Maven Dependencies

 src

 target

 pom.xml


pom.xml: (Project Object Model)

  •  A Project Object Model or POM is the fundamental unit of work in Maven.
  •  It is an XML file that contains information about the project and configuration details used by Maven to build the project.
  •  It contains default values for most projects.


How to Write Effective Test Scripts for Postman API Testing

pm.test("success status", () => pm.response.to.be.success );


pm.test("Status code is 200 or 201"function () {
  pm.expect(pm.response.code).to.be.oneOf([200201]);
});


pm.test("Response time is less than 300ms", () => {
  pm.expect(pm.response.responseTime).to.be.below(300);
});


pm.test("Response status code contains 'Created' or 'OK'"function () {
  console.log(pm.response.status);
  pm.expect(pm.response.status).to.be.oneOf(['Created''OK']);
});


pm.test("Response body is not empty"function () {
    pm.expect(pm.response.text()).to.not.be.empty;
});