Wednesday, June 28, 2023

How to Quickly Refresh Your Browser in Selenium Java

1. Navigate the refresh method
driver. navigate().refresh();

2. Get the current URL
driver.get(driver.getCurrentUrl());

3. Javascript Executor
JavascriptExecutor executor=(JavascriptExecutor) driver;
executor.executeScript("location.reload()");

4. Robot class
Robot robot=new Robot();
robot.keyPress(KeyEvent.VK_F5);
robot.keyRelease(KeyEvent.VK_F5);

Thursday, May 11, 2023

Exploring the Common API Terminology You Need to Know

  1. REST (Representational State Transfer): An architectural style for designing networked applications, typically using HTTP as the underlying protocol.
  2. SOAP (Simple Object Access Protocol): A protocol for exchanging structured information in web services using XML-based messages.
  3. JSON (JavaScript Object Notation): A lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
  4. OAuth (Open Authorization): An open standard for authorization that allows users to grant access to their protected resources without sharing their credentials.
  5. SDK (Software Development Kit): A set of tools, libraries, and documentation that developers use to build applications for a specific platform or programming language.
  6. SDK Client: A software component or library that provides an interface for interacting with an API from within an application.
  7. API client: A program or tool that interacts with an API on behalf of a user or system.
  8. API key: A secret token or credential to authenticate a user or system when accessing an API.
  9. Authentication: The process of verifying the identity of a user or system attempting to access an API.
  10. Authorization: The process of determining whether a user or system has permission to access a specific resource or perform a particular action.
  11. Endpoint: A URL that represents a specific resource or action within an API.
  12. HTTP verb/method: The type of request being made (e.g., GET, POST, PUT, DELETE) that determines the action to be taken on a resource.
  13. Rate Limiting: The process of restricting the number of requests a client can make to an API within a given time period to prevent abuse or ensure fair usage.
  14. Webhooks: A mechanism for receiving real-time notifications from an API by sending HTTP requests to a specified URL when a specific event occurs.
  15. CORS (Cross-Origin Resource Sharing): A mechanism that allows resources (e.g., fonts, JavaScript) on a web page to be requested from another domain outside the domain from which the resource originated.
  16. API Gateway: A server that acts as an entry point for client requests and provides various features such as routing, authentication, and rate limiting for backend APIs.
  17. Bearer Token: A type of access token used in authentication, where the token is presented by the client to access protected resources.
  18. GraphQL (Graph Query Language): A query language and runtime for APIs that provide a flexible and efficient approach to request and manipulate data.
  19. Versioning: The practice of assigning a version number to an API to manage changes, additions, or removals of functionality over time.
  20. Payload: The data transmitted in a request or response body, typically in formats like JSON or XML.
  21. Pagination: The process of dividing a large data set into smaller pages or chunks to improve performance and limit the amount of data transferred in a single response.
  22. Content-Type: An HTTP header that specifies the media type of the data being sent or received in a request or response.
  23. API Documentation: Comprehensive and structured information about an API, including endpoints, request/response formats, parameters, and example usage.
  24. API Key: A unique identifier or token provided to a client application for authentication and authorization purposes when making API requests.
  25. Query parameter: A way to pass additional information to an API endpoint through the URL query string.
  26. Asynchronous API: An API design pattern where the client can send a request to the server and receive a response at a later time, without blocking the client's execution until the response is received.

Thursday, May 4, 2023

What is the difference between Mistake, Error, Bug, Defect, Fault and Failure?

Testing is the process of identifying defects, where a defect is any variance between actual and expected results. “A mistake in coding is called an Error, an error found by a tester is called a Defect, a defect accepted by the development team then is called Bug, build does not meet the requirements then it Is Failure.”

Although the terms "mistake," "error," "bug," "defect," "fault," and "failure" are often used interchangeably in everyday language, in the world of software development and quality assurance, they have distinct meanings. Here are some definitions to help differentiate between them:

1. Mistake: 

  • A mistake is a human action that produces an incorrect result. In software development, this could be a coding mistake, such as a typo or a logic error, made by a developer.

2. Error: 

  • An error is a deviation from the expected behaviour of a program, which can occur due to a mistake made by a developer or because of some other external factor, such as hardware malfunction or network failure.

3. Bug: 

  • A bug is a specific type of error that is caused by a fault in the code, which can be as simple as a missing semicolon or as complex as a race condition. Bugs are typically discovered during testing or after the software has been released.

4. Defect: 

  • A defect is a flaw in the software that causes it to deviate from its intended behaviour. This could be due to a design flaw, a coding mistake, or an error in the requirements specification.

5. Fault: 

  • A fault is a defect that exists in the software but has not yet been activated or triggered. For example, a race condition in the code may not cause a problem until the software is run on a specific hardware configuration.

6. Failure: 

  • A failure is an event in which the software does not behave as expected, resulting in a loss of service or data. Failures can be caused by errors, bugs, defects, or faults, and can occur at any stage of the software development process.

What Is The Difference Between Regression Testing And Smoke Testing?

Regression testing and smoke testing are both types of software testing, but they serve different purposes and have different characteristics.

Regression Testing:

  • Regression testing is the process of testing a software application to ensure that any new changes or modifications to the code have not introduced new defects or broken existing functionality. 
  • It involves running a set of previously executed test cases to check if any new errors have been introduced or if the changes made to the code have affected the existing functionality. Regression testing is usually done after code changes or bug fixes.

Smoke Testing:
  • Smoke testing, on the other hand, is a preliminary level of testing that checks the basic functionality of an application. 
  • It is usually performed to ensure that the build or the application is stable and ready for further testing. 
  • Smoke testing is done to ensure that the most critical functionalities of the application are working fine, and the application is not completely broken.

Sanity Testing:
  • Sanity testing is similar to smoke testing, but it is performed after smoke testing to verify that the defects found in smoke testing have been fixed and that the critical functionalities are still working fine. 
  • Sanity testing is also used to ensure that the new features added to the application are working as expected, and the application is ready for further testing.
In summary, regression testing checks for any new errors or defects that might have been introduced after code changes, while smoke testing and sanity testing ensure that the basic and critical functionalities of the application are working fine. Smoke testing is done before further testing, while sanity testing is done after smoke testing to ensure that the application is ready for further testing.


Thursday, April 27, 2023

How To Test Software - Get Functional Defects

1. User Interface Issues
  • Poorly designed user interfaces can cause several defects, such as non-responsive buttons, broken links, or incorrect field validations.
2. Data Integrity Issues
  • Defects in data integrity may occur when the system doesn't validate the data or doesn't store it correctly. An example of this is if a user enters an email address with an incorrect format, and the system accepts it.
3. Functionality Issues
  • Functionality defects occur when the system doesn't meet the business requirements. For example, if a banking application doesn't allow users to transfer funds between accounts or a social media platform doesn't enable users to create a new post.
4. Integration Issues
  • Integration defects arise when different modules or systems don't work well together. An example of this is if a CRM system doesn't synchronize data with a marketing automation system.
5. Boundary and Limits Issues
  • Boundary and limits issues may arise when the system doesn't handle inputs or outputs correctly that are at the boundaries or limits of the system. For instance, if a system doesn't allow negative values for certain inputs.
6. Business Logic Issues 
  • Business logic defects occur when the system doesn't correctly implement the business rules or logic. For example, if a discount code isn't applied correctly or if a system calculates taxes incorrectly.
7. Compatibility Issues
  • Compatibility defects may occur when the system doesn't work correctly with different browsers or operating systems. For example, if a website works fine on Google Chrome but doesn't display correctly on Mozilla Firefox.
8. Localization Issues
  • Localization defects occur when the system doesn't support various languages or regions. For instance, if a website's interface is not translated into Spanish, which is a required language for the user.
9. Accessibility Issues
  • Accessibility defects may arise when the system doesn't provide easy access to all users, such as people with disabilities. For example, if a website doesn't offer a screen reader or keyboard shortcuts.
10. Usability Issues
  • Usability defects occur when the system doesn't provide a user-friendly experience. For instance, if a user has difficulty finding the right button or menu item or if the user manual is hard to understand.
 Functional defects can impact the quality and performance of a system, leading to a negative user experience. As testers, it is crucial to identify these defects early in the software development lifecycle to prevent them from affecting the system's overall quality.

Saturday, April 22, 2023

The Most Famous Software Failures of All Time

 1. Memory Failure - Tesla Recalls 135,000 Vehicles
  •  Tesla will recall a maximum of 135,000 cars to fix computer memory issues in the touchscreen that could cause a loss of some features notified the electric car manufacturer to the U.S NHTSA (National Highway Traffic Safety Administration).
  •  The manufacturer said that the touchscreen’s flash memory reached the end of its lifespan. It can trigger failures of the software components of the centre monitor and can unintentionally lead to the loss of external turn signal lighting, rearview camera display, and defog/defrost control settings.
2. HSBC’s Significant IT Outages
  • One of the famous software failure examples. HSBC experienced a big IT outage in January 2016 and millions of bank customers were unable to access online accounts. The bank took almost two days to recover and get back to normal service. The Chief Operating Officer of HSBC (COO) claimed that this was the result of a ‘unique technological problem’ within internal systems.
3. Prison Break
  •  An error that happened in December 2015 resulted in more than 3,200 US prisoners being released before their announced date of release. The software was developed to track the actions of prisoners and was released in 2002. The problem has been around for about 13 years and an average inmate has been released almost 49 days in advance.
4. The Explosion of the Ariane 5
  •  On June 4, 1996, an Ariane 5 rocket launched by the ESA (European Space Agency) exploded just forty seconds after its launch from Kourou in French Guiana. The rocket was on its inaugural voyage, after a decade of development costing $8 billion and the result of this bug was the loss of $370 million.
  •  The reason behind its failure was an integer Overflow, which is a widespread bug in computer programming. In this case, an attempt was made to set a 64-bit number in 16-bit space.
5. PayPal accidentally credits man $92 quadrillion
  •  When Chris Reynolds opened his PayPal e-mail statement, the Pennsylvania PR executive’s account balance was $92,233,720,368,547,800.
  •  The amount is significant in the world of 64-bit numbers suggesting a programming error. The error was quickly recognized, and his account had returned to zero by the time he logged in.
  •  PayPal offered to give an unspecified amount of money to a cause of Reynolds’ choice.
6. Windows Calculator Bug
  •  This bug exists in most Windows versions(except in Windows 10), including Windows XP, Windows 7, Windows Vista, and Windows 8. You can check it in your OS if you have one of these versions.
  •  Steps: Open Windows Calculator, type 4 and take the square root, you will get two then subtract two from it. Instead of the result from zero, you will see different outputs on different versions of Windows.
  •  The cause for the bug is the way calculator manages sqrt operations. The results are saved as floating-point numbers instead of integers, and the precision errors when it comes to floating-point calculations are the result that you can see.
  •  Microsoft acknowledged this bug in the calculator app, and they fixed it in Windows 10 Build 17639.
7. Gangnam Style music video ‘broke’ YouTube
  •  YouTube’s counter before used a 32-bit integer, which is a unit used to represent data in computer architecture. This 32-bit integer determines the maximum number of possible views it can count was 2,147,483,647.
  •  The Gangnam Style video exceeded the maximum value, and we got the below famous Gangnam Style YouTube bug.
  •  Nowadays, YouTube uses a 64-bit integer for its video counter, which means videos have a maximum viewer count of 9.22 quintillion.

Thursday, April 20, 2023

How to Write a Good Bug Report: A Comprehensive Guide

1. Clear Summary:
  •  Summarize the bug clearly.
  •  The summary should give the bug's full picture in a single sentence.
2. One Issue = One Bug:
  •  Do not combine multiple issues in one bug.
  •  Because different bugs can be assigned to different developers to fix.
3. Clear & Detailed Description:
  •  Expand the summary in description-simple and precise.
  •  Provide as much information as possible.
4. Steps To Reproduce:
  •  How can you reproduce the bug - mention it in bullet points.
  •  Clear enough developers would reproduce and fix quickly.
5. Expected & Actual Results:
  •  What is the requirement & what is happening?
  •  The developer knows what is the issue by looking at it.
6. Additional Details As Notes:
  •  Write about your additional observations.
  •  Helps developers to analyze & hence fix bugs quickly.
7. Environment Details:
  •  Where have you tested - QA/PRD/CHROME ETC.
  •  Developer compares this with other environments.
8. Build Number:
  •  In which version of the application you found the bug.
9. PRIORITY:
  •  How soon the bug should be fixed.
  •  Can be HIGH/LOIW/MEDIUM.
10. SEVERITY:
  •  Impact on the product.
  •  Can be CRITICAL/MAJOR/MINOR/TRIVIAL.
11. Screenshot/Screen Recording:
  •  Evidence of the bug.
  •  Can be screenshots or screen recordings.
12. Link the related test case and or story:
  •  Link bug to story/test case you are testing.
  •  Can be 'Associated With' OR 'Blocked By'.
13. LOGS:
  •  Attach log file or snippet of log.
  •  This is a mine of data for developers.
14. Avoid Duplicates:
  •  Check if already bug is reported by someone. 

What Type of Test Cases Should Not Be Automated?



1. User Interface (UI) testing

2. Exploratory testing

3. Usability testing

4. Ad hoc testing

5. Performance testing

  • Test cases that require human judgment, exploration, or unpredictability may not be suitable for automation. Additionally, test cases highly dependent on an application's user interface, performance, or usability may be better suited for manual testing.


Wednesday, April 19, 2023

User Interface Test Cases: What You Need to Know

1. Navigation Test: 
  • Test the navigation bar or menu by clicking on each link or button to ensure that they take you to the correct page or section of the website or application.
2. Input Validation Test: 
  • Test the input fields, such as forms or search boxes, by entering valid and invalid data to ensure that the system handles the inputs correctly.
3. Button Test: 
  • Test all buttons on the UI to ensure they perform the intended actions and provide appropriate feedback, such as success or error messages.
4. Compatibility Test: 
  • Test the UI on different devices and browsers to ensure it is compatible with various screen sizes, resolutions, and operating systems.
5. Responsiveness Test: 
  • Test the UI for responsiveness by resizing the browser window or using device emulators to see how the UI adapts to different screen sizes.
6. Content Test: 
  • Test the UI for consistency and accuracy of content, including text, images, and multimedia.
7. Accessibility Test: 
  • Test the UI for accessibility compliance, ensuring that users with disabilities can access and use the UI without any issues.
8. Performance Test: 
  • Test the UI for performance by checking loading times, response times, and any delays or lags in the system.

How to Send MySQL Data to an Email with Python

import smtplib
import csv
import pymysql
import json
import base64
import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

# Connect to the MySQL database
db = pymysql.connect(host="localhost", user="root", password="pass1234", database="local")

# Execute an SQL query to retrieve data
cursor = db.cursor()
cursor.execute("SELECT * FROM local.questions")
data = cursor.fetchall()

# Write the data to a json file
data = [[str(col) if isinstance(col, datetime.datetime) else col for col in row] for row in data]
with open('data.json', 'w', encoding='utf-8', newline='') as file:
    json.dump(data, file, ensure_ascii=False)

# Open the JSON file
with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)

# Create the email message
from_addr = 'your@gmail.com'
to_addr = 'friend@gmail.com'
subject = 'JSON data'
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = subject

# Add the JSON file as an attachment
attachment = MIMEApplication(json.dumps(data, indent=2))
attachment['Content-Disposition'] = f'attachment; filename=data.json'
msg.attach(attachment)

# Connect to the SMTP server and send the message
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_addr, 'Your_Gmail_APP_PASSWORD')
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()

Saturday, April 8, 2023

How to Implement Continuous Integration in Test Automation



Continuous integration (CI) is a software development practice that involves frequently integrating code changes from multiple developers( in your team) into a central repository. Example-Git etc.

How CI Helps:
  • This process helps to detect and fix bugs early in the development cycle, leading to faster and more efficient software delivery.
Automated test process:
  • In the context of software testing, continuous integration refers to the automated testing process that is triggered whenever new code changes are integrated into the main codebase.
What is the Goal?
  • The goal of this process is to ensure that the newly added code does not break the existing functionality of the application.
Easy example:
  • Here's an example of how continuous integration works in software testing:
  • You can consider the Amazon website or any other e-commerce website.
  • Suppose a software development team is working on an e-commerce application that allows users to purchase products online.
CI Tools:
  • The team uses a continuous integration tool such as Jenkins to automatically build and test the application every time a developer makes a code change and pushes it to the central code repository.
  • Whenever a developer makes a code change, Jenkins automatically pulls the latest code from the repository, builds the application, and runs a suite of automated tests to check if the application is still functioning correctly.
  • If any of the tests fail, the developer is notified immediately so they can fix the issue before it causes further problems.

Conclusion:
  • Continuous integration ensures that any new code changes are thoroughly tested before they are integrated into the main codebase, reducing the likelihood of introducing bugs or breaking existing functionality.
  • This helps to improve the quality of the software and accelerates the development process.

The Ultimate Guide to Smoke and Sanity Testing



Smoke Testing:
  • Smoke testing is done when we received the new build from the developer the build is stable or not, that build is testable or not.
  • Smoke testing is done by the developer and tester.
  • Smoke testing is done for every new build.
  • It is done on the initial build.

Sanity Testing:
  • Sanity testing is done at the release time of the software, it checks the main functionality of the software without going deeper.
  • Sanity testing is done by the tester only.
  • Sanity testing is done when the build is stable.
  • It is planned when we don't have sufficient time to test the software.

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 and 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