Uncategorized

Put and Patch method in Rest Assured

Difference Between Put and Patch Method

What is Put?

When creating an object or resource on an HTTP server, clients utilize the PUT method. This setup procedure itself may take one of two shapes:

When an object is requested that doesn’t already exist, the server creates it and returns a response code 201 to the client.

The server changes the entity, which already exists, and returns a success code of 200 and 204 to a client. Moreover, the server should provide the client with the appropriate error number, often a 4xx or 5xx, if a PUT request encounters a problem.

What is Patch?

The PATCH technique modifies resource elements only partially. The requested modifications are executed atomically via the PATCH technique. It implies that the server won’t alter the target object if it can’t accommodate all of the requested modifications. In this approach, if the request is carried out correctly, the server sends the client the success code 204. Otherwise, an error code is sent by the server.

Here is simple example in Rest Assured for Put and Patch

package session02;

import org.json.simple.JSONObject;
import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;

public class TestPutMethod {
  @Test
  public void test04() {
	  JSONObject jsonData = new JSONObject();
	  jsonData.put("Name", "Rahul kundu");
	  jsonData.put("job", "manager");
	  
	  RestAssured.baseURI = "https://reqres.in/api/users/52";
	  RestAssured.given().header("Content-Type","application/json").contentType(ContentType.JSON)
	             .body(jsonData.toJSONString())
	             .when().put()
	             .then().statusCode(200).log().all();
  }
  @Test
  public void test05() {
	  JSONObject jsonData = new JSONObject();
	  jsonData.put("Name", "Rahul kundu");
	  jsonData.put("job", "QA manager");
	  
	  RestAssured.baseURI = "https://reqres.in/api/users/52";
	  RestAssured.given().header("Content-Type","application/json").contentType(ContentType.JSON)
	             .body(jsonData.toJSONString())
	             .when().patch()
	             .then().statusCode(200).log().all();
  }
}
Uncategorized

Post Method in Rest Assured

Simple Example for Post method.

You have to add Json simple and rest assured dependency in your maven project.

JSON Simple

<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

Rest Assured

<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>

Example of Post Method:

package session02;

import org.json.simple.JSONObject;
import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;

public class TestPostMentod {
  @Test
  public void test04() {
	  
	  JSONObject jsonData = new JSONObject();
	  jsonData.put("Name", "Rahul");
	  jsonData.put("job", "QA Lead");
	  
	  RestAssured.baseURI = "https://reqres.in/api/users";
	  RestAssured.given().header("Content-Type","application/json").contentType(ContentType.JSON)
	             .body(jsonData.toJSONString())
	             .when().post()
	             .then().statusCode(201);
  }
}
Uncategorized

Get Request in Rest Assured

Below is the simple Get Request in Rest Assured.


package session01;

import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.response.Response;

public class GetRequest {
	
  @Test
  public void test01() {
	  
	  //RestAssured.baseURI = "https://reqres.in/api/users/2";
	  Response response = RestAssured.get("https://reqres.in/api/users/2");
	  System.out.println(response.asString());
	  System.out.println(response.getStatusCode());
	  
  }
}
Uncategorized

Get Request in Rest Assured

Create new Maven Project, add the following dependencies in your pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.test.RestAssuredAPITesting</groupId>

<artifactId>RestAssuredAPITesting</artifactId>

<version>0.0.1-SNAPSHOT</version>

<dependencies>

<!-- https://mvnrepository.com/artifact/org.testng/testng -->

<dependency>

<groupId>org.testng</groupId>

<artifactId>testng</artifactId>

<version>7.7.1</version>

<scope>test</scope>

</dependency>

<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->

<dependency>

<groupId>io.rest-assured</groupId>

<artifactId>rest-assured</artifactId>

<version>5.3.0</version>

<scope>test</scope>

</dependency>

<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->

<dependency>

<groupId>com.googlecode.json-simple</groupId>

<artifactId>json-simple</artifactId>

<version>1.1.1</version>

</dependency>

</dependencies>

</project>

Create a new TestNG class and following code:

package session1;

import org.testng.annotations.Test;

import io.restassured.RestAssured;

import io.restassured.response.Response;

public class GetRequest {

@Test

public void test01() {

//RestAssured.baseURI = "https://reqres.in/api/users/2";

Response response = RestAssured.get("https://reqres.in/api/users/2");

System.out.println(response.asString());

System.out.println(response.getStatusCode());

}

}
Uncategorized

TestNG | How to set Test Priority in Selenium

TestNG is a Testing framework, that covers different types of test designs like a unit test, functional test, end to end test, UI test and integration test.

You can run a single or multiple test cases in your Testng code.

If test priority is not defined while, running multiple test cases, TestNG assigns all @Test a priority as zero(0).

Now, while running; lower priorities will be scheduled first.

How to set Priority in TestNG

We will be modifying the @Test annotation with Priority Parameter so that each test should run against to the priority assigned to them.

Now as you can see we have assigned the Priority to each test case means test case will the lower priority value will be executed first.

Priority in testNG in action

import org.openqa.selenium.By;			
import org.openqa.selenium.WebDriver;			
import org.openqa.selenium.firefox.FirefoxDriver;			
import org.testng.Assert;			
import org.testng.annotations.Test;			

public class Priority_In_testNG {		
    WebDriver driver;			

    // Method 1: Open Browser say Firefox			
    @Test (priority=1)		
    public void openBrowser() {				
        driver = new FirefoxDriver();				
    }		

    // Method 2: Launch Google.com			
    @Test (priority=2)		
    public void launchGoogle() {				
        driver.get("http://www.google.co.in");						
    }		

    // Method 3: Perform a search using "Facebook"			
    @Test (priority=3)		
    public void peformSeachAndClick1stLink() {				
        driver.findElement(By.xpath(".//*[@title='Search']")).sendKeys("Facebook");								
    }		

    // Method 4: Verify Google search page title.			
    @Test (priority=4)		
    public void FaceBookPageTitleVerification() throws Exception {				
        driver.findElement(By.xpath(".//*[@value='Search']")).click();						
        Thread.sleep(3000);		
        Assert.assertEquals(driver.getTitle().contains("Facebook - Google Search"), true);				
    }		
}		

Explanation of Code

After assigning priority to each testcases, run the above code using testNG as shown in Video-2 mentioned below.

Here, you can see that test cases are prioritized. Test case having lower priority are executed first i.e. now there is a sequential execution according to priority in the test cases. Hence, all test cases are passing now.

Note the console of eclipse:

Output :

PASSED: openBrowser
PASSED: launchGoogle
PASSED: peformSearchAndClick1stLink
PASSED: FaceBookPageTitleVerification
Uncategorized

How to fetch Key and value from My SQL…

A database is a software subsystem that offers an efficient way to store data and request said data via a structured query language known as SQL. Databases store critical business information, thus functioning as the backbone of an entire application. Database testing is a vital part of software testing that involves verifying the accuracy and completeness of data stored in a database.

Automated database testing can cover a wide range of tests, such as data integrity, performance, security, and integration. It can also detect defects or issues in the database, such as data corruption, missing data, incorrect data, and duplicate data.

Naturally, database testing is essential to ensure the system is working correctly. As automation testing with Selenium is most frequently used by QAs, this article will detail how to perform database testing using Selenium.

Java Database Connectivity

JDBC is the standard Java API required for database-independent connectivity between the Java programming language and many databases. This application program interface (API) lets users encode access request statements in a Structured Query Language (SQL). They are then passed to the program that manages the database. It involves opening a connection, creating a SQL Database, executing SQL queries, and arriving at the output.

Steps to create a JDBC Application

To create a JDBC application, follow the steps below:

  1. Import the packages: Include the packages that contain the JDBC classes required for database programming.
  2. Register the JDBC driver: Initialize a driver to open a communication channel with the database. Register to the database with the command:
    Class.forName(“com.mysql.jdbc.Driver”); // class.forName load the Driver class
  3. Open a connection: After the driver registration, use the getConnection() method to create a Connection object, representing a physical connection with the database.
  4. Execute a query: Use an object of type ‘Statement’ to build and submit a SQL statement to the database.
  5. Extract data from the result set: Use the appropriate getXXX() method.
  6. Clean up the environment: Close all database resources that rely on JVM garbage collection.

2. Selenium Database Connection

Selenium is one of the prominent automation testing tools. As mentioned before, Selenium performs only UI validations. Thus, this article will depict a JDBC connection as Selenium doesn’t support database testing directly, but it can be done with connectors like JDBC and ODBC. This article uses JDBC to connect to a database, and test cases are verified using TestNG framework.

3. Database testing using Selenium

Step 1: Create a database in command prompt and insert the tables.
Step 2: Establish a connection to the database using JDBC.
Step 3: Execute the MySQL queries and process records present in the database.
Step 4: Integrate TestNG with JDBC to perform Database Testing.

Have a look at the script below:

package com.test.traveltest;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class SeleniumDatabaseTesting {
// Connection object
static Connection con = null;
// Statement object
private static Statement stmt;
// Constant for Database URL
public static String DB_URL = "jdbc:mysql://127.0.0.1:3306/hrmdb";
//Database Username
public static String DB_USER = "root";
// Database Password
public static String DB_PASSWORD = "rahul";

public static WebDriver driver;
public static String uname;
public static String uval;
public static String pwd;
public static String pval;
public static String loginbtn;

@BeforeTest
public void setUp() throws Exception {
	
	System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"\\src\\main\\java\\drivers\\chromedriver1.exe");
  	driver = new ChromeDriver();
	driver.manage().window().maximize();
	driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
try{
// Database connection
String dbClass = "com.mysql.cj.jdbc.Driver";
Class.forName(dbClass).newInstance();
// Get connection to DB
Connection con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
// Statement object to send the SQL statement to the Database
stmt = con.createStatement();
}
catch (Exception e)
{
e.printStackTrace();
}
}

@Test (priority = 0)
public void testuname() {
try{
String query = "select * from login where id = '" +1+"'";
// Get the contents of userinfo table from DB
ResultSet res = stmt.executeQuery(query);
// Print the result untill all the records are printed
// res.next() returns true if there is any next record else returns false
while (res.next())
{
System.out.print(res.getString(1));
System.out.print(" | " + res.getString(2));
System.out.print(" | " + res.getString(3));
System.out.println();
uname = res.getString(2);
uval = res.getString(3);
}
}
catch(Exception e)
{
e.printStackTrace();
}

driver.findElement(By.name(uname)).sendKeys(uval);

}

@Test (priority = 1)
public void testpwd() {
try{
String query = "select * from login where id = '" +2+"'";
// Get the contents of userinfo table from DB
ResultSet res = stmt.executeQuery(query);
// Print the result untill all the records are printed
// res.next() returns true if there is any next record else returns false
while (res.next())
{
System.out.print(res.getString(1));
System.out.print(" | " + res.getString(2));
System.out.print(" | " + res.getString(3));
System.out.println();
pwd = res.getString(2);
pval = res.getString(3);
}
}
catch(Exception e)
{
e.printStackTrace();
}

driver.findElement(By.name(pwd)).sendKeys(pval);

}

@Test (priority = 2)
public void testlogin() {
try{
String query = "select * from login where id = '" +3+"'";
// Get the contents of userinfo table from DB
ResultSet res = stmt.executeQuery(query);
// Print the result untill all the records are printed
// res.next() returns true if there is any next record else returns false
while (res.next())
{
System.out.print(res.getString(1));
System.out.print(" | " + res.getString(2));
System.out.print(" | " + res.getString(3));
System.out.println();
loginbtn = res.getString(2);

}
}
catch(Exception e)
{
e.printStackTrace();
}

driver.findElement(By.xpath(loginbtn)).click();

}

@AfterTest
public void tearDown() throws Exception {
// Close DB connection
if (con != null) {
con.close();
}
}
}
Uncategorized

Difference Between List and Set

S.NoListSet
1.The list implementation allows us to add the same or duplicate elements.The set implementation doesn’t allow us to add the same or duplicate elements.
2.The insertion order is maintained by the List.It doesn’t maintain the insertion order of elements.
3.List allows us to add any number of null values.Set allows us to add at least one null value in it.
4.The List implementation classes are LinkedList and ArrayList.The Set implementation classes are TreeSet, HashSet and LinkedHashSet.
5.We can get the element of a specified index from the list using the get() method.We cannot find the element from the Set based on the index because it doesn’t provide any get method().
6.It is used when we want to frequently access the elements by using the index.It is used when we want to design a collection of distinct elements.
7.The method of List interface listiterator() is used to iterate the List elements.The iterator is used when we need to iterate the Set elements.
Uncategorized

Test Case for Header

Here are some manual test cases for the header:

Test Case 1: Verify that the header is displayed correctly

Steps:

  1. Open the website.
  2. Navigate to the homepage.
  3. Verify that the header is displayed.
  4. Check that the header contains the following elements:
    • Website logo
    • Navigation menu
    • Search bar
    • User account information (if applicable)
    • Contact information (if applicable)

Expected Result:

  • The header is displayed correctly with all the required elements.

Test Case 2: Verify that the website logo links to the homepage

Steps:

  1. Open the website.
  2. Navigate to the homepage.
  3. Click on the website logo in the header.

Expected Result:

  • The user is redirected to the homepage.

Test Case 3: Verify that the navigation menu items are clickable and lead to the correct pages

Steps:

  1. Open the website.
  2. Navigate to the homepage.
  3. Click on each navigation menu item in the header.
  4. Verify that the user is redirected to the correct page for each menu item.

Expected Result:

  • Each navigation menu item is clickable and leads to the correct page.

Test Case 4: Verify that the search bar is functional

Steps:

  1. Open the website.
  2. Navigate to the homepage.
  3. Enter a search term in the search bar in the header.
  4. Click the search button.
  5. Verify that the search results are displayed.

Expected Result:

  • The search bar is functional and displays the relevant search results.

Test Case 5: Verify that the user account information is displayed correctly

Steps:

  1. Open the website.
  2. Navigate to the homepage.
  3. If the user account information is displayed, verify that it is correct and up-to-date.
  4. If the user account information is not displayed, log in to the user account.
  5. Verify that the user account information is displayed correctly in the header.

Expected Result:

  • The user account information is displayed correctly and is accurate and up-to-date.

Test Case 6: Verify that the contact information is displayed correctly

Steps:

  1. Open the website.
  2. Navigate to the homepage.
  3. Check that the contact information is displayed in the header.
  4. Click on the contact information in the header.
  5. Verify that the user is redirected to the correct page.

Expected Result:

  • The contact information is displayed correctly in the header, and the user is redirected to the correct page when clicking on it.

Test Case 7: Verify that the header is responsive

Steps:

  1. Open the website.
  2. Resize the browser window to different screen sizes.
  3. Verify that the header elements adjust to fit the screen size.
  4. Check that the header remains functional on smaller screen sizes.

Expected Result:

  • The header elements adjust to fit the screen size, and the header remains functional on smaller screen sizes.

Test Case 8: Verify that the header stays fixed when scrolling

Steps:

  1. Open the website.
  2. Navigate to a page with long content.
  3. Scroll down the page.
  4. Verify that the header remains fixed at the top of the page.

Expected Result:

  • The header remains fixed at the top of the page when scrolling.

Test Case 9: Verify that the header is accessible

Steps:

  1. Open the website using a screen reader.
  2. Navigate to the homepage.
  3. Verify that the screen reader can read out all the header elements.
  4. Check that the header is accessible using only the keyboard.

Expected Result:

  • The header is accessible using a screen reader and keyboard-only navigation.

Test Case 10: Verify that the header loads quickly

Steps:

  1. Open the website.
  2. Navigate to the homepage.
  3. Check the load time of the header using a network monitor tool.
  4. Repeat the test on different internet speeds.

Expected Result:

  • The header loads quickly on all internet speeds.
Uncategorized

How Chat GPT can help in Occupation /Business.

ChatGPT can help businesses and organizations in several ways:

  1. Automation of repetitive tasks: ChatGPT can automate repetitive tasks, such as data entry, customer service, and scheduling appointments, which can save time and increase efficiency.
  2. Customer service: ChatGPT can be used to create a virtual customer service agent that can answer frequently asked questions and provide assistance to customers.
  3. Marketing and advertising: ChatGPT can assist with the creation of persuasive and high-quality marketing and advertising content.
  4. Content creation: ChatGPT can assist in creating high-quality content, such as blog posts, articles, and social media posts, which can help to improve a business’s online presence and engage customers.
  5. Business intelligence: ChatGPT can be used to analyze large amounts of data and provide insights into customer behavior, market trends, and other business-related information that can help organizations make data-driven decisions.
  6. Language Translation: ChatGPT can assist in providing translations for business documents and communicate with clients or partners from different countries, which can help to expand the business globally.
  7. Virtual assistance: ChatGPT can assist in scheduling meeting, sending reminders, and managing emails, which can free up time and increase productivity for business owners and employees.
  8. Research: ChatGPT can assist in researching competitors, market trends, and other relevant information that can help businesses make informed decisions and stay ahead of the competition.

Here are some of the examples we queried to ChatGPT regarding their occupations/business:

1: Nurses:

2: Accountants:

3: Event Management Company:

Uncategorized

Querying ChatGPT: Use of constructor in Automation Testing

RK: write an example of constructor in automation testing

AI: Here is an example of a constructor in automation testing using the Selenium WebDriver:

public class TestClass {
    private WebDriver driver;

    public TestClass() {
        // Set the system property for the driver executable path
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");

        // Create a new instance of the Chrome driver
        driver = new ChromeDriver();

        // Maximize the browser window
        driver.manage().window().maximize();
    }
    
    // Other test methods would go here, such as test cases
    public void testMethod1() {
        // Test steps using the driver
    }

    public void testMethod2() {
        // Test steps using the driver
    }
}

The constructor is the method that is called when an object of the class is created. In this example, the constructor sets the system property for the chrome driver executable, creates a new instance of the Chrome driver, and maximizes the browser window. This is done so that whenever an object of the TestClass is created, the Chrome browser will be launched and maximized, so that the tests can be executed.

This example is using ChromeDriver but you can use other drivers like Firefox, Edge, etc.

It’s important to note that this is just a basic example, you would need to adjust the code according to your test needs, and to consult the Selenium documentation for more information on how to use the WebDriver and constructors.