Saturday, December 31, 2022

The Essential Performance Testing Metrics Every Developer Should Know

  1.  Processor Usage: Time spent by the processor to execute non-idle threads.
  2. Memory use: The available physical memory to process on a system.
  3. Disk time: It is the time taken by the disk to read or write a request.
  4. Bandwidth: Bits per second used by a network interface.
  5. Private bytes: A specific number of bytes allocated to a particular process.
  6. Response time: The time between the user’s request and the first response character.
  7. Throughput: Rate of requests received per second by a network. (The formula is Throughput = (number of requests) / (total time). )
  8. Maximum active sessions: Maximum number of sessions that may stay active at once.
  9. Thread (user) counts: Determining the well-being of the application by checking the number of running and active threads.
  10. Latency - JMeter measures the latency from just before sending the request to just after the first response has been received.
  11. Think Time - the time between two transactions of user actions. 
    (Login -> Think Time -> Search -> Think Time -> Logout). 
    The average thinking time could be in the range of 3 to 10 seconds for a normal user.
  12. Error rate - Measures the number of errors that occur in each request.
  13. Network latency - Measures the time it takes for a request to travel from the client to the server.
  14. Transaction time: Measures the time it takes for a transaction to complete.
  15. Resource utilization: Measures the number of resources used by the server to handle requests.
  16. Memory usage: Measures the amount of memory used by the server to process requests.
  17. Load test scalability: Measures how well the server can handle an increasing amount of requests.
  18. Page load time: Measures the time it takes for a web page to load.

Basic concepts of Performance Testing

 Performance Testing

  • Performance testing is a type of software testing that is used to evaluate the speed, scalability, and stability of a system. It is used to ensure that the system can handle the expected load and volume of traffic.

Types:
  1. Load Testing
  2. Stress Testing
  3. Data/Volume Testing
  4. Scalability testing
  5. Endurance testing
  6. Spike testing
Load Testing:
  • Load testing is a generic term covering Performance Testing and Stress Testing.
  • Testing the app with the maximum number of users.
  • To measure the performance under the expected load.
Stress Testing:
  • The system is under extreme load conditions, such as peak user activity or maximum transaction throughput.
  • Testing the application with MORE than the maximum number of users.
  • To measure performance under a load much higher than expected.
Endurance Testing:
  • Endurance Testing is done to ensure the software can handle the EXPECTED load over a long period.
Spike Testing:
  • System by SUDDENLY increasing the load (e.g. the number of users or transactions) to check how it responds.
Data/Volume Testing:
  • System by increasing the number of users or transactions over a PERIOD OF TIME.
Scalability testing:
  • The system performs when the workload increases or decreases.

Common Performance Problem:
  • Most performance problems revolve around speed, response time, load time, and poor scalability.
  • A slow-running application will lose potential users.
  • Long Load time - While some applications are impossible to make load in under a minute, Load time should be kept under a few seconds if possible.
  • Poor response time - Response time is the time it takes from when a user inputs data into the application until the application outputs a response to that input. Generally, this should be very quick. Again if a user has to wait too long, they lose interest.
  • Poor scalability - A software product suffers from poor scalability when it cannot handle the expected number of users or when it does not accommodate a wide enough range of users.
  • Bottlenecking  - Bottlenecking is when either coding errors or hardware issues cause a decrease in throughput under certain loads.

Common performance bottlenecks are:
  • CPU utilization
  • Memory utilization
  • Network utilization
  • Operating System limitations
  • Disk usage

Qualities of a Good Tester

  1.  Problem-solving skills: A good tester should be able to think strategically and come up with creative solutions to problems they encounter while testing.
  2. Communication skills: A good tester should be able to effectively communicate the results of their tests to the development team.
  3. Technical knowledge: A good tester should have a solid understanding of the technology they are using to test.
  4. Writing skills: A good tester should be able to document their testing process in order to help the development team track and debug problems.
  5. Patience: A good tester should be patient and willing to take the time needed to thoroughly test the software.
  6. Flexibility: A good tester should be able to adjust their testing strategies and processes in order to accommodate changes in the software they are testing.
  7. No compromise on the quality.
  8. Negative thinking.

Introduction to JMETER and Performance Testing

 JMeter

  • JMeter is an open-source load-testing tool used by developers and performance engineers to measure the performance of web applications.
  • It can be used to simulate a heavy load on a server, network or object to test its strength or to analyze overall performance under different load types.
  • Measure the application performance and response times.


Test Plan: (Top level directory)
  • A complete test plan will consist of one or more Thread Groups, logic controllers, sample-generating controllers, Listeners, Timers, Assertions, and configuration elements.
  1. Adding elements.
  2. Removing elements.
  3. Saving test plans.
  4. Running test plans.
  5. Stopping a test plan(immediate shutdown), Shutdown(graceful shutdown).
  6. Logging the info and errors.
Important components of a Test Plan:
  1. Thread Group
  2. Listeners
  3. Timers
  4. Assertions
Thread Group:
  • The beginning point of any test plan.
  • The thread group element controls the number of threads Jmeter will use to execute your test.
  • All controllers and samplers must be under a thread group.
Main properties of thread group:
  • Set the number of threads (simulation of a number of concurrent users).
  • Set the ramp-up period (time taken to threads up and running = ramp-up period/Thread 
Samplers:
  • Samplers send requests to the server and collect the response.
  • JMeter supports several types of samplers, including HTTP, FTP, JDBC, LDAP and SOAP.
Listeners:
  • Listeners can be added to test plans or thread group level.
  • Listeners provide a way to view the results of a test in JMeter.
  • Listener options - Graph result, view results tree, view result table, aggregate report, aggregate graph, response time graph.

Saturday, December 24, 2022

Interview Questions on Security Testing

 1. What is Authorization?

  •  Authorization means checking permission.
  •  Authorization is the process of verifying that a user has the necessary permissions to access a particular resource. 
  •  It is typically done by comparing the user's credentials against an access control list to determine if the user is allowed to perform a particular action. 
  •  Authorization is an important part of the security of any system, as it ensures that only authorized users can access sensitive data.

2. What is Authentication?

  •  Authentication means checking credentials.
  •  Authentication is the process of verifying that a person, device, or other entity is who it claims to be.
  •  It is usually accomplished through the use of credentials such as a username/password combination, security tokens, biometric data, or a combination of factors. 
  •  Authentication is an important component of data security, as it helps to ensure that only authorized users can access sensitive information.

3. Why do we do security testing?

  •  To remove vulnerabilities.
  •  Security testing is important because it helps ensure that applications, networks, and systems are protected against potential threats and vulnerabilities.
  •  Security testing helps ensure that data is secure and protected from unauthorized access, manipulation, and theft.
  •  Security testing also helps protect applications, networks, and systems against malicious attacks, and can help detect and identify weaknesses in applications and systems before they can be exploited.

4. Which methods/techniques are used for security testing?

  •  XSS and SQL injection.

5. What is “Vulnerability”?

  •  Weakness in the web application.

6. Security Tests are created on the basis of:

  •  Roles

7. Security Testing is a type of:

  •  Review Testing.
  •  It involves testing the system to identify any security vulnerabilities that could be exploited and gain unauthorized access to the system. 
  •  Security testing is typically done at the end of the software development life cycle.

8. Which symbol is used to test SQL injection?

  •  The most commonly used symbol to test SQL injection is the single quotation mark (').

9. What is the full form of XSS?

  •  Cross-Site Scripting.
  •  Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. 
  •  XSS enables attackers to inject client-side scripts into web pages viewed by other users. 
  •  A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same origin policy.

Tuesday, August 30, 2022

How to Extract Text from PDFs with Python Pypdf2?

import encodings
from PyPDF2 import PdfFileReader
from pathlib import Path
import glob
import json
import re
import pymysql

for pdfFile in Path("pdfs").glob("*.pdf"):

# Create pdf file reader object
  pdf = PdfFileReader(pdfFile)

# Grab the page(s)
  page_1_object = pdf.getPage(0)

# Extract text
  page_1_text = page_1_object.extractText()

# Combine the text from all the pages and save as txt file
with open("txts/{}.txt".format(pdfFile.stem), mode='w', encoding="utf-8") as file:
        for page in pdf.pages:
            text = ''
            text += page.extractText()
            file.write(text)
            file.close

Monday, August 22, 2022

Retrieve Image as a BLOB from MySQL Table using Python

 # Import the required modules
import mysql.connector
import base64
from PIL import Image
import io

# For security reasons, never expose your password
#password = open('password','r').readline()

# Create a connection
mydb = mysql.connector.connect(
host="host",
user="suriyaparithy",
password="suriyaparithy",
database="database" # Name of the database
)

# Create a cursor object
cursor = mydb.cursor()

# Prepare the query
query = 'SELECT PICTURE FROM PROFILE WHERE ID=100'

# Execute the query to get the file
cursor.execute(query)
data = cursor.fetchall()

# The returned data will be a list of list
image = data[0][0]

# Decode the string
binary_data = base64.b64decode(image)

# Convert the bytes into a PIL image
image = Image.open(io.BytesIO(binary_data))

# Display the image
image.show()

Image File stored as a BLOB in MySQL Table using Python

 # Import the required modules
import mysql.connector
import base64
from PIL import Image
import io

# Create a connection
mydb = mysql.connector.connect(
host="localhost",
user="suriyaparithy",
password="suriyaparithy",
database="database" # Name of the database
)

# Create a cursor object
cursor = mydb.cursor()

# Open a file in binary mode
file = open('chemical.PNG','rb').read()

# We must encode the file to get base64 string
file = base64.b64encode(file)

# Sample data to be inserted
args = ('100', 'Sample Name', file)

# Prepare a query
query = 'INSERT INTO PROFILE VALUES(%s, %s, %s)'

# Execute the query and commit the database.
cursor.execute(query,args)
mydb.commit()

Extract text from a single image using Python

#Extract text from a single image using Python
from PIL import Image
from pytesseract import pytesseract

#Define path to tessaract.exe
path_to_tesseract = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

#Define path to image
path_to_image = 'chemical.PNG'

#Point tessaract_cmd to tessaract.exe
pytesseract.tesseract_cmd = path_to_tesseract

#Open image with PIL
img = Image.open(path_to_image)

#Extract text from image
text = pytesseract.image_to_string(img)
print(text)

Extract only images from PDF using Python

 # How to Extract Images from PDF in Python
import fitz # PyMuPDF
import io
from PIL import Image

# file path you want to extract images from
file = "byju.pdf"

# open the file
pdf_file = fitz.open(file)

# iterate over PDF pages
for page_index in range(len(pdf_file)):

    # get the page itself
    page = pdf_file[page_index]
    image_list = page.get_images()

    # printing number of images found in this page
    if image_list:
        print(f"[+] Found a total of {len(image_list)} images in page {page_index}")
    else:
        print("[!] No images found on page", page_index)
    for image_index, img in enumerate(page.get_images(), start=1):

        # get the XREF of the image
        xref = img[0]

        # extract the image bytes
        base_image = pdf_file.extract_image(xref)
        image_bytes = base_image["image"]

        # get the image extension
        image_ext = base_image["ext"]

        # load it to PIL
        image = Image.open(io.BytesIO(image_bytes))

        # save it to local disk
        image.save(open(f"image{page_index+1}_{image_index}.{image_ext}", "wb"))

Extract text and image from PDF files in python

# Module Imports
import os
from PIL import Image
import pytesseract
from pdf2image import convert_from_path

# Define Paths
poppler_path = r'C:\Program Files\poppler-0.68.0\poppler-0.68.0\bin'
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract'
pdf_path = "chemistry.pdf"

# Save PDF pages to images
images = convert_from_path(pdf_path=pdf_path, poppler_path=poppler_path)
for count, img in enumerate(images):
    img_name = f"page_{count}.png"  
    img.save(img_name, "png")

# Extract Text
png_files = [f for f in os.listdir(".") if f.endswith(".png")]
for png_file in png_files:
    extracted_text = pytesseract.image_to_string(Image.open(png_file))
    print(extracted_text)

Reference - https://www.gcptutorials.com/post/python-extract-text-from-pdf-files 

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

    }

}


Selenium using Data Provider Method

 package coaching;


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;


public class DataProviderTest {

WebDriver driver;

@DataProvider(name = "Authentication")

 public static Object[][] credentials() {

           // The number of times data is repeated, test will be executed the same no. of times

          // Here it will execute two times

           return new Object[][] { { "suriya", "Test@123" }, { "parithy", "Test@123" }};

     }

@Test(dataProvider = "Authentication")


  public void test(String username, String password) {

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 username1 = driver.findElement(By.id("userName"));

username1.sendKeys(username);

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

password1.sendKeys(password);

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

login.click();

   }

}


Nodejs get data from Mysql database

 var mysql = require('mysql');

var con = mysql.createConnection({

  host: "localhost",

  user: "root",

  password: "12345",

  port: "3000",

  database: "project",

});

con.connect(function(err) {

  if (err) throw err;

  console.log("Connected!");

});

con.query('SELECT * FROM users', function (err, rows, fields) {

    if (err) throw err;

  console.log('The solution is: ', rows[2].standard);

  });

  con.end();

Convert PDF to Word using Python

 # Importing the Converter() class
from pdf2docx import Converter

# Specifying the pdf & docx files
pdf_file = 'ieep.pdf'
docx_file = 'sample.docx'
try:
cv = Converter(pdf_file)
cv.convert(docx_file)
cv.close()
except:
    print('Conversion Failed')
else:
    print('File Converted Successfully')

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

}

}



Tuesday, June 28, 2022

Selenium Interview Questions and Answers - PART 1

1. What is Selenium?

  •  Selenium is an automation testing tool that is used for automating web-based applications.
  •  It supports multiple browsers, programming languages, and platforms.

2. What are the different forms of selenium?

  •  Selenium WebDriver - It is used to automate web applications using browser methods.
  •  Selenium IDE - It is a plugin that works on record and playback principles.
  •  Selenium RC - Selenium Remote Control(RC) is officially deprecated by Selenium and it used to work on javascript to automate web applications.
  •  Selenium Grid - Allows selenium tests to run in parallel across multiple machines.

3. Advantages of selenium?

  •  Selenium is open source and free to use without any licensing cost.
  •  It supports multiple languages like java, ruby, python, etc.
  •  It supports multi-browser testing.
  •  Using the selenium ide component, non-programmers can also write automation scripts.

4. Limitations of selenium?

  •  We cannot test the desktop applications using selenium.
  •  We cannot test web services using selenium.

5. Which browsers/drivers are supported by the selenium web driver?

 Google chrome - ChromeDriver

 Firefox - FireFoxDriver

 Internet Explorer - InternetExplorerDriver

 Safari - SafariDriver

6. What are the testing types supported by the selenium web driver?

  •  Selenium web driver can be used for performing automated functional and regression testing.

7.Different locators in selenium?

 id,xpath,cssSelector,className,tagName,name,linkText,partialLinkText

8.What is an XPath?

  •  Xpath or XML path is a query language for selecting nodes from XML documents.
  •  XPath is one of the locators supported by the selenium web driver.

 Types of XPath:

 absolute XPath

 relative XPath

9. How can we launch different browsers in the selenium web driver?

  •  By creating an instance of the driver of a particular browser

 WebDriver driver = new ChromeDriver();

10.What is the use of driver.get("url") and driver.navigate().to("url")command?

  •  Both driver. get("url") and driver.navigate().to("URL") commands are used to navigate to a URL passed as a parameter.

11. How can we type text in a textbox element using selenium?

  •  using the sendKeys() method we can type text in a textbox.

 WebElement text = driver.findElement(By.id("search"));

 text.sendKeys("suriya");

12. How we can clear a text written in a textbox?

  •  Using the clear() method we can delete the text written in a textbox.

 driver.findElement(By.id("elementLocator")).clear();

13. How to check a checkbox in selenium?

  •  the click() method used for clicking buttons or radio buttons can be used for checking checkboxes.

14. Difference between close and quit commands?

 driver.close() - used to close the current browser having focus.

 driver.quit() - used to close all the browser instances

15. Maximize browser window - driver.manage().window().maximiza();

16. Find the value - driver.findElement(By.id("locator")).getAttribute("value");

17. How to delete cookies in selenium?

 driver.manage().deleteAllCookies();

18. Double-click an element in selenium?

 Actions action = new Actions(driver);

 WebElement element = driver.findElement(By.id("elementid"));

 action.doubleClick(element).perform();

19. Right-click an element in selenium?

 Actions action = new Actions(driver);

 WebElement element = driver.findElement(By.id("elementid"));

 action.contextClick(element).perform();

20. How to fetch the current page URL in selenium?

 driver.getCurrentUrl();

21. How can we fetch the title of the page in selenium?

 driver.getTitle();

22. fetch the page source in selenium?

 driver.getPageSource();

Monday, June 20, 2022

JavaScriptExecutor in Selenium WebDriver

 JavaScript:

  •  JavaScript is a programming language that interacts with HTML DOM within the browser.

JavaScriptExecutor:

  •  JavaScript executor is an interface provided by Selenium that gives a mechanism to execute JavaScript through Selenium WebDriver.
  •  It provides two methods such as “executeScript” & “executeAsyncScript” to run JavaScript on the currently selected frame, window, or page.

Uses of JavaScriptExecutor:

  •  There are locators in Selenium WebDriver like ID, Class, XPath, etc., to work with elements on a web page.
  •  Sometimes these default Selenium locators may not work.
  •  JavaScriptExecutor is used to perform operations on a web page.
  •  JavascriptExecutor in Selenium enables the WebDriver to interact with HTML DOM within the browser.


1. Type Text in a Text Box

 JavascriptExecutor js = (JavascriptExecutor) driver;

 js.executeScript("document.getElementById('Email').value='suriya@gmail.com';");


2. To Click on a Button

 js.executeScript("document.getElementById('enter your element id').click();");


3. To refresh browser window using Javascript

 js.executeScript("history.go(0)");


4. To get the inner text of the entire webpage in Selenium

 String Text =  js.executeScript("return document.documentElement.innerText;").toString();

 System.out.println(Text);


5. To get the Title of our webpage

 String Text =  js.executeScript("return document.title;").toString();

 System.out.println(Text);


6. To get the URL of a webpage

 String Text =  js.executeScript("return document.URL;").toString();

 System.out.println(Text);


7. To perform Scroll on an application

 js.executeScript("window.scrollBy(0,500)");

Wednesday, May 25, 2022

Types of Software Testing

 Software Testing:

  •  The process of finding errors in the developed product.
  •  Testing the software whether it is working according to the requirement.


Two ways of Testing:

 1. Manual Testing

 2. Automation Testing


Manual Testing:

  •  Manual testing is verifying the software manually and finding errors without the intervention of any tools.
  •  The tester has to execute each test case one by one.
  •  They give input and manually verify the output.


Automation Testing:

  •  Automation Testing is testing the software with the help of some automation tools like Selenium.
  •  The code is run for automating tests and the input data is given to the tool.
  •  The output data is compared with the expected results.
  •  Automation testing is generally performed for repeated tasks so that time can be saved.


Levels of Testing:

 1. Unit Testing

 2. System Testing

 3. Integration Testing

 4. Acceptance Testing


1. Unit Testing:

  •  Unit testing is the first level of testing usually performed by the developers.

Advantage: Error can be detected at an early stage saving time and money to fix it.


2. System Testing:

  •  Complete application testing.
  •  Done by Testers.
  •  Black Box Testing Techniques.
  •  FRS and test case document.

System Testing Categories:

  •  Usability Testing
  •  Functional Testing
  •  Performance Testing
  •  Security Testing


3. Integration Testing:

  •  Combining/merging modules.
  •  Done by Developers.
  •  White box testing technique.

4. Acceptance Testing:

  •  Getting approval from the client.
  •  Done by the client.
  •  Satisfying client requirements.


Types of Testing:

 1. Functional Testing

 2. Non-Functional Testing


1. Functional Testing:

  •  Testing the behaviour of the application.
  •  Based on how well the system is working.

Alpha Testing:

  •  The application is tested for the first time.
  •  Done under the supervision of developers.

Beta Testing:

  •  The application is tested a second time.
  •  Before the final release of the software is released to users for testing.

Smoke Testing:

  •  Testing the primary functionality of the application.

Sanity Testing:

  •  Testing the minor functionality of the application.

Regression Testing:

  •  Testing the whole application to check whether new requirement changes affect previous functionality.

Retesting:

  •  Testing only the bugs fixed by the developers.


2. Non-Functional Testing:

  •  Based on how well the system is performed.
  •  Testing the performed to verify the non-functional requirements of the application.

Usability Testing:

  •  User Friendly
  •  Look and Feel
  •  Ease of use
  •  Speed in Interface
  •  Context Sensitiveness

Performance Testing:

  •  Load Testing
  •  Stress Testing
  •  Data/Volume Testing

Security Testing:

  •  Protecting from unauthorized access.

Compatibility Testing:

  •  OS Compatability - Testing in multiple OS.
  •  Browser Compatability - Testing in multiple Browsers.


Software Testing Interview Questions and Answers:

1. STLC - stands for Software Testing Life Cycle.

  Requirements and analysis, test planning, test design, test execution, error report, solving the error, re-test, test close.

2. Software Quality:

  •   Quality is ensured by two sets of activities. verification and validation.

  Verification - It involves activities like document review, test case review, walk-throughs, and inspections.

  Validation - It involves activities like functional testing and automation testing.

3. Workflow of Functional Testing:

  •   Create input values.
  •   Execute test cases.
  •   Compare actual and expected output.

4. Client Expectation:

  Completeness, correctness, quality.

5. Tester Responsibility: (Zero bugs and 100% quality)

  •   Execute test cases
  •   Positive and Negative Conditions.
  •   Manual or Automation tools.

 6. Error - Done by the developer in code

   Bug - Tester identifies the errors.

7. Quality - Meeting client requirements.

   Customer needs or expectations.

8. How to measure Quality:

  Functionality, Usability, Reliability, Performance, and Scalability.

9. Bug - unexpected or incorrect result.

10. Main Goal of Testing:

  Expected Result = Actual Result (Test Pass)

  Expected Result != Actual Result (Test Fail)

11. Severity - the impact of a bug on the software.

   Priority - is how soon a bug needs to be fixed.