Docker Commands


Basic Commands

1)docker version

2)docker -v
3)docker info
4)docker --help

docker --help

Example: Get information about images.....
docker images --help     --> Gives you details about how to use images command
docker run --help --> Gives you details about how to use run commands
5)docker login

Images Commands

6)docker images    --> lists the images present in the machine

7)docker pull   ---> pull the image from docker hub
docker pull ubuntu
docker images  --> list the image

8)docker rmi
docker images -q   --> Gives you image ID
docker rmi <>   ----> Deletes image
docker images   ---> No Images


Containers Commands


9)docker ps  & : docker run


docker ps ---> List the containers, Bo containers as of now.

docker run ubuntu ---> Locally not available ,Pulling image from Dockerhub.
docker ps --> Still not listed contaner, becoz we didi not created container so far....
docker run -it ubuntu   ---> inside ubuntu
docker ps ---> lists the container


10) docker start
docker start <>

11)docker stop
docker stop <>

System Commands


12) docker stats   --> gives details abount running containers, memory usage etc..

13)docker system df
14)docker system prune 
docker system prune -f --> Rermoves all stopped contaniers



How to Convert Database Results into JSON Files




Pre-Requisite:

Create Mock Table "constomersInfo" in "ClassicModels" Database and insert some data.

CREATE DATABASE ClassicModels;
use ClassicModels;

CREATE TABLE CustomerInfo

(BookName varchar(50),
PurchasedDate date,
Amount int(50),
Location varchar(50));

INSERT INTO CustomerInfo values("selenium",CURRENT_DATE(),350,'Africa');
INSERT INTO CustomerInfo values("Java",CURRENT_DATE(),200,'Africa');
INSERT INTO CustomerInfo values("Python",CURRENT_DATE(),250,'Asia');
INSERT INTO CustomerInfo values("Jmeter",CURRENT_DATE(),150,'Asia');
INSERT INTO CustomerInfo values("C#",CURRENT_DATE(),300,'Asia');


select * from CustomerInfo where purchasedDate=CURDATE() and Location ='Asia';

Step 1: Retrieve Results from Database using JDBC

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConvertDBResult_JavaObject_JsonFile{

     public static void main(String[] args) throws SQLException {
          // 1) Create a connection
          Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels", "root", "root");

          // 2) Create statement/Query
          Statement stmt = con.createStatement();

          String s = "select * from customerinfo  limit 1";

          // 3,4) Execute statement/Query & Store data in resultset
          ResultSet rs = stmt.executeQuery(s);

          CustomerDetails cd=new CustomerDetails();
         
          while (rs.next()) {
              String bookname = rs.getString("BookName");
              String purchasedate = rs.getString("PurchasedDate");
              int amount = rs.getInt("Amount");
              String location = rs.getString("Location");
              System.out.println(bookname + "   " + purchasedate + "      " + amount+"    "+location);
          }

          // 5) close connection
          con.close();

          System.out.println("Query executed.....");
     }

}


Step 2: Converts Data base Results into Java Object (Plain Old Java Object)  public class CustomerDetails {
     String bookname;
     String purchasedate;
     int amount;
     String location;
    
     public String getBookname() {
          return bookname;
     }
     public void setBookname(String bookname) {
          this.bookname = bookname;
     }
     public String getPurchasedate() {
          return purchasedate;
     }
     public void setPurchasedate(String purchasedate) {
          this.purchasedate = purchasedate;
     }
     public int getAmount() {
          return amount;
     }
     public void setAmount(int amount) {
          this.amount = amount;
     }
     public String getLocation() {
          return location;
     }
     public void setLocation(String location) {
          this.location = location;
     }
}

Modify JDBC Program which will use POJO (Plain Old Java Object) Class to retrieve data from Java Object.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConvertDBResult_JavaObject_JsonFile{

     public static void main(String[] args) throws SQLException {
          // 1) Create a connection
          Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels", "root", "root");

          // 2) Create statement/Query
          Statement stmt = con.createStatement();

          String s = "select * from customerinfo  limit 1";

          // 3,4) Execute statement/Query & Store data in resultset
          ResultSet rs = stmt.executeQuery(s);

          CustomerDetails cd=new CustomerDetails();
         
          while (rs.next()) {
              String bookname = rs.getString("BookName");
              String purchasedate = rs.getString("PurchasedDate");
              int amount = rs.getInt("Amount");
              String location = rs.getString("Location");
             
              cd.setBookname(bookname);
              cd.setPurchasedate(purchasedate);
              cd.setAmount(amount);
              cd.setLocation(location);
          }

          // 5) close connection
          con.close();
    
          System.out.println(cd.getLocation());
     }
}

Step 3: Convert Java Objects into JSON Files
            Maven Dependencies: Jackson Core, Jackson Databind, Jackson annotations

Single Java Object à Single JSON File:

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ConvertDBResult_JavaObject_JsonFile{

     public static void main(String[] args) throws SQLException, JsonGenerationException, JsonMappingException, IOException {
          // 1) Create a connection
          Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels", "root", "root");

          // 2) Create statement/Query
          Statement stmt = con.createStatement();

          String s = "select * from customerinfo  limit 1";

          // 3,4) Execute statement/Query & Store data in resultset
          ResultSet rs = stmt.executeQuery(s);

          CustomerDetails cd=new CustomerDetails();
         
          while (rs.next()) {
              String bookname = rs.getString("BookName");
              String purchasedate = rs.getString("PurchasedDate");
              int amount = rs.getInt("Amount");
              String location = rs.getString("Location");
             
              cd.setBookname(bookname);
              cd.setPurchasedate(purchasedate);
              cd.setAmount(amount);
              cd.setLocation(location);
          }

          // 5) close connection
          con.close();
                  
          // Using Jakson API, Converting Java object into JSON File
          File jsonfile=new File("C:\\Users\\admin\\eclipse-workspace\\sdet\\custinfo.json");
         
          ObjectMapper om=new ObjectMapper();
          om.writeValue(jsonfile, cd);
         
          System.out.println("Done!");
         
     }

}



Multiple Java Objects à Multiple JSON Files:

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ConvertDBResults_JavaObjects_JsonFiles {

     public static void main(String[] args) throws SQLException, JsonGenerationException, JsonMappingException, IOException {
          // 1) Create a connection
          Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels", "root", "root");

          // 2) Create statement/Query
          Statement stmt = con.createStatement();

          String s = "select * from customerinfo";

          // 3,4) Execute statement/Query & Store data in resultset
          ResultSet rs = stmt.executeQuery(s);

          ArrayList ar=new ArrayList();
         
          while (rs.next()) {
              String bookname = rs.getString("BookName");
              String purchasedate = rs.getString("PurchasedDate");
              int amount = rs.getInt("Amount");
              String location = rs.getString("Location");
             
              CustomerDetails cd=new CustomerDetails();
             
              cd.setBookname(bookname);
              cd.setPurchasedate(purchasedate);
              cd.setAmount(amount);
              cd.setLocation(location);
             
              ar.add(cd); // Adding all the objects to arraylist
          }

          //Using Jakson API, Converting all Java objects into JSON Files
         
          for(int i=0;i
          {
              File jsonfile=new File("C:\\Users\\admin\\eclipse-workspace\\sdet\\custinfo"+i+".json");
             
              ObjectMapper om=new ObjectMapper();
              om.writeValue(jsonfile,ar.get(i));
          }
                  
          System.out.println("Done!");
    
          con.close();
         
     }

}


Multiple Java Objects à Single JSON (Along with JSON Formatting):

package sdet;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

public class ConvertDBResults_JavaObjects_SingleJsonFile {

     public static void main(String[] args) throws SQLException, JsonGenerationException, JsonMappingException, IOException {
          // 1) Create a connection
          Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels", "root", "root");

          // 2) Create statement/Query
          Statement stmt = con.createStatement();

          String s = "select * from customerinfo";

          // 3,4) Execute statement/Query & Store data in resultset
          ResultSet rs = stmt.executeQuery(s);

          ArrayList ar=new ArrayList();
         
          while (rs.next()) {
              String bookname = rs.getString("BookName");
              String purchasedate = rs.getString("PurchasedDate");
              int amount = rs.getInt("Amount");
              String location = rs.getString("Location");
             
              CustomerDetails cd=new CustomerDetails();
             
              cd.setBookname(bookname);
              cd.setPurchasedate(purchasedate);
              cd.setAmount(amount);
              cd.setLocation(location);
             
              ar.add(cd); // Adding all the objects to arraylist
          }

          //Using Jakson API, Converting all Java objects into JSON Files
         
          JSONArray jsonr=new JSONArray(); //Required to add JSon string to Json array
         
          for(int i=0;i
          {
              //File jsonfile=new File("C:\\Users\\admin\\eclipse-workspace\\sdet\\custinfo"+i+".json");
              //ObjectMapper om=new ObjectMapper();
              //om.writeValue(jsonfile,ar.get(i));
             
              Gson g=new Gson();
              String JsonString=g.toJson(ar.get(i)); //Converts Java object into JSON String
             
              jsonr.add(JsonString); //Add JSon String to Json Array
          }
         
          JSONObject jo=new JSONObject();
          jo.put("data",jsonr);
         
          System.out.println(jo.toJSONString()); // added escape chars That's not right format
    
          String jsonFormattedString = jo.toJSONString().replace("\\\"", "\""); //removed escape chars
          System.out.println(jsonFormattedString); //still doubles quotes there. It's not exactly in Json format
         
          String finalJSONString=jsonFormattedString.replace("\"{","{").replace("}\"","}"); //Removes double quotes both the sides
          System.out.println(finalJSONString);
         
          System.out.println("Done!");
                  
          con.close();
         
     }

}


Step 4: Convert JSON to Java Object
import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONtoJavaObject {

     public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
         
          ObjectMapper om=new ObjectMapper();
         
          File jsonfile=new File("C:\\Users\\admin\\eclipse-workspace\\sdet\\custinfo.json");
          CustomerDetails cd=om.readValue(jsonfile, CustomerDetails.class);
         
          System.out.println(cd.getBookname());
          System.out.println(cd.getAmount());
         

     }

}


API/Webservices Testing using RestAssured (Part 1)


Rest Assured : Is an API designed for automating REST services/Rest API's

Pre-Requisites

Java
Free videos: https://www.youtube.com/watch?v=ms3NggvNW40&list=PLUDwpEzHYYLv9v8aRuNi67vZ81cW2ksze
Eclipse

TestNG : Framework implemented on top of Java used for organizing test cases, test suites.
Free videos: https://www.youtube.com/playlist?list=PLUDwpEzHYYLsWENabqeETzgPLbmwqhM45
Maven

Setup

1) Creating Maven project in Eclipse
2) We need to update pom.xml with required dependencies

- RestAssured  https://mvnrepository.com/artifact/io.rest-assured/rest-assured
- TestNG       https://mvnrepository.com/artifact/org.testng/testng
- Json-simple  https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
- apache poi   https://mvnrepository.com/artifact/org.apache.poi/poi
       https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml



Test Case 1) Weather API - Validate status code & Status line

http://restapi.demoqa.com/utilities/weather/city/

Request Type: GET

http://restapi.demoqa.com/utilities/weather/city/Hyderabad

SUCCESS RESPONSE
{
“City”: “Hyderabad”,
“Temperature”: “31.49 Degree celsius”,
“Humidity”: “62 Percent”,
“Weather Description”: “scattered clouds”,
“Wind Speed”: “3.6 Km per hour”,
“Wind Direction degree”: “270 Degree”
}

STATUS CODE : 200
Status Line: HTTP/1.1 200 OK"


Code Snippet

import org.testng.Assert;
import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

public class TC001_GET_Request {

@Test
void getweatherDetails()
{
//Specify base URI
RestAssured.baseURI="http://restapi.demoqa.com/utilities/weather/city";
//Request object
RequestSpecification httpRequest=RestAssured.given();
//Response object
Response response=httpRequest.request(Method.GET,"/Hyderabad");
//print response in console window
String responseBody=response.getBody().asString();
System.out.println("Response Body is:" +responseBody);
//status code validation
int statusCode=response.getStatusCode();
System.out.println("Status code is: "+statusCode);
Assert.assertEquals(statusCode, 200);
//status line verification
String statusLine=response.getStatusLine();
System.out.println("Status line is:"+statusLine);
Assert.assertEquals(statusLine, "HTTP/1.1 200 OK");
}
}


Test Case 2) Register Customer API

Request Type: POST
http://restapi.demoqa.com/customer/register

BODY

{
   “FirstName” : “value”
   “LastName” : “value”,
   “UserName” : “value”,
   “Password” : “value”,
   “Email”        : “Value”
 }

SUCCESS RESPONSE

{
“SuccessCode”: “OPERATION_SUCCESS”,
“Message”: “Operation completed successfully”
}

STATUS CODE : 201

Code Snippet

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

import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

public class TC002_POST_Request {

@Test
void RegistrationSuccessful()
{

//Specify base URI
RestAssured.baseURI="http://restapi.demoqa.com/customer";

//Request object
RequestSpecification httpRequest=RestAssured.given();


//Request paylaod sending along with post request
JSONObject requestParams=new JSONObject();

requestParams.put("FirstName","JohnXYZ");
requestParams.put("LastName","XYZJohn");
requestParams.put("UserName","JohnXYZ");
requestParams.put("Password","JohnXYZxyx");
requestParams.put("Email","JohnXYZ@gmail.com");

httpRequest.header("Content-Type","application/json");

httpRequest.body(requestParams.toJSONString()); // attach above data to the request

//Response object
Response response=httpRequest.request(Method.POST,"/register");


//print response in console window

String responseBody=response.getBody().asString();
System.out.println("Response Body is:" +responseBody);

//status code validation
int statusCode=response.getStatusCode();
System.out.println("Status code is: "+statusCode);
Assert.assertEquals(statusCode, 201);

//success code validation
String successCode=response.jsonPath().get("SuccessCode");
Assert.assertEquals(successCode, "OPERATION_SUCCESS");

}


}

Test Case 3) Google Map API - Validating Headers

https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=-33.8670522,151.1957362&radius=1500&type=supermarket&key=AIzaSyBjGCE3VpLU4lgTqSTDmHmJ2HoELb4Jy1s

SUCCESS RESPONSE : Returns list of super markets

"Headers:
Content-Encoding →gzip
Content-Type →application/xml; charset=UTF-8
Server →scaffolding on HTTPServer2
"

Code Snippet

import org.testng.Assert;
import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

public class TC003_GET_Request {

@Test
void googleMapTest()
{

//Specify base URI
RestAssured.baseURI="https://maps.googleapis.com";

//Request object
RequestSpecification httpRequest=RestAssured.given();

//Response object
Response response=httpRequest.request(Method.GET,"/maps/api/place/nearbysearch/xml?location=-33.8670522,151.1957362&radius=1500&type=supermarket&key=AIzaSyBjGCE3VpLU4lgTqSTDmHmJ2HoELb4Jy1s");

//print response in console window
String responseBody=response.getBody().asString();
System.out.println("Response Body is:" +responseBody);

//validating headers
String contentType=response.header("Content-Type");// capture details of Content-Type header
System.out.println("Content Type is:"+contentType);
Assert.assertEquals(contentType, "application/xml; charset=UTF-8");

String contentEncoding=response.header("Content-Encoding");// capture details of Content-Encoding  header
System.out.println("Content Encoding is:"+contentEncoding);
Assert.assertEquals(contentEncoding, "gzip");

}

}




Followers