Wednesday 6 May 2020

io.restassured

<dependency>

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

<artifactId>rest-assured</artifactId>

<version>4.3.0</version>

<scope>test</scope>

</dependency>


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

<dependency>

<groupId>org.testng</groupId>

<artifactId>testng</artifactId>

<version>7.1.0</version>

<scope>test</scope>

</dependency>




package eu.restcountries.restautomation;

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

import io.restassured.RestAssured;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.http.Method;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.specification.RequestSpecification;

public class NewTest {
String baseUrl = "https://restcountries.eu/rest/v2/name/";

public Response getResponse(String restApi) {
// Specify the base URL to the RESTful web service
RestAssured.baseURI = baseUrl;

// Get the RequestSpecification of the request that you want to sent
// to the server. The server is specified by the BaseURI that we have
// specified in the above step.
RequestSpecification httpRequest = RestAssured.given();

// Make a request to the server by specifying the method Type and the method
// URL.
// This will return the Response from the server. Store the response in a
// variable.
Response response = httpRequest.request(Method.GET, restApi);
return response;
}

@Test
public void TestsPositive() {
Response response = getResponse("/eesti");
// Now let us print the body of the message to see what response
// we have recieved from the server
String responseBody = response.getBody().asString();
System.out.println("Response Body is =>  " + responseBody);

// Get the status code from the Response. In case of
// a successfull interaction with the web service, we
// should get a status code of 200.
int statusCode = response.getStatusCode();

// Assert that correct status code is returned.
Assert.assertEquals(statusCode, 200, "Correct status code returned");

// Get all the headers. Return value is of type Headers.
// Headers class implements Iterable interface, hence we
// can apply an advance for loop to go through all Headers
// as shown in the code below
Headers allHeaders = response.headers();

// Iterate over all the Headers
for (Header header : allHeaders) {
System.out.println("Key: " + header.getName() + " Value: " + header.getValue());
}

// Reader header of a give name. In this line we will get
// Header named Content-Type
String contentType = response.header("Content-Type");
Assert.assertEquals(contentType, "application/json;charset=utf-8");

// Reader header of a give name. In this line we will get
// Header named Content-Encoding
String contentEncoding = response.header("Content-Encoding");
Assert.assertEquals(contentEncoding, "gzip");

// Retrieve the body of the Response
ResponseBody body = response.getBody();

// To check for sub string presence get the Response body as a String.
// Do a String.contains
String bodyAsString = body.asString();

// By using the ResponseBody.asString() method, we can convert the body
// into the string representation.
System.out.println("Response Body is: " + body.asString());

// convert the body into lower case and then do a comparison to ignore casing.
Assert.assertEquals(bodyAsString.contains("Estonian"), true, "Response body contains Estonian");

// First get the JsonPath object instance from the Response interface
JsonPath jsonPathEvaluator = response.jsonPath();

// Then simply query the JsonPath object to get a String value of the node
// specified by JsonPath: City (Note: You should not put $. in the Java code)
String city = jsonPathEvaluator.get("[0].demonym");

// Let us print the city variable to see what we got
System.out.println("City name received from Response " + city);

// Validate the response
Assert.assertEquals(city, "Estonian", "Correct city name received in the Response");
}

@Test
public void TestsNegative() {
Response response = getResponse("/wrongInput");
// Now let us print the body of the message to see what response
// we have recieved from the server
String responseBody = response.getBody().asString();
System.out.println("Response Body is =>  " + responseBody);

// Get the status code from the Response. In case of
// a successfull interaction with the web service, we
// should get a status code of 200.
int statusCode = response.getStatusCode();
// Assert that correct status code is returned.
Assert.assertEquals(statusCode, 404, "Correct status code returned");
}
}

Tuesday 7 April 2020

Running jmeter scripts in FF & IE browser

FF:

windows:
Jmeter - bin folder - find out system.properties file and add below line

webdriver.gecko.driver=C:\\Users\\Kranthi\\Desktop\\AA-Perf\\new\\geckodriver.exe

yes you need to add Firefox config file in the Test plan of jmter - no modifications required!

for mac:
>> jmeter -Dwebdriver.gecko.driver=/path/to/geckodriver
----------------------------------
IE:
only one version driver works in IE:
IEDriver  2.53.1 version of 32 bit IE driver. No other versions will work.


Saturday 21 March 2020

Appium - webAutomation





<dependency>
<groupId>io.appium</groupId>
<artifactId>java-client</artifactId>
<version>5.0.3</version>
</dependency>




package com.gitlab.appium;

import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;

public class NewTest2 {

public static void main(String[] ards) throws MalformedURLException {

// Created object of DesiredCapabilities class.
DesiredCapabilities capabilities = new DesiredCapabilities();

// Set android deviceName desired capability. Set your device name.
capabilities.setCapability("deviceName", "J7AXPW");

capabilities.setCapability("udid", "J7AXPW");

// Set BROWSER_NAME desired capability. It's Android in our case here.
capabilities.setCapability("browserName", "Chrome");

// Set android VERSION desired capability. Set your mobile device's OS
// version.
capabilities.setCapability("platformVersion", "9.0");

// Set android platformName desired capability. It's Android in our case
// here.
capabilities.setCapability("platformName", "Android");

capabilities.setCapability("noReset", true);

// Set ChromeDriver location
System.setProperty("webdriver.chrome.driver", "C:\\Users\\KKasthuri\\Downloads\\chromedriver_win32\\chromedriver.exe");
AppiumDriver<MobileElement> driver = null;
try {
driver = new AndroidDriver<MobileElement>(new URL("http://0.0.0.0:4723/wd/hub"), capabilities);

} catch (MalformedURLException e) {
System.out.println(e.getMessage());
}

// Open URL in Chrome Browser
driver.get("http://www.google.com");
driver.quit();
}
}

Friday 6 March 2020

Program - Given an array A[] and a number x, check for pair in A[] with sum as x

hasArrayTwoCandidates (A[], ar_size, sum)
1) Sort the array in non-decreasing order.
2) Initialize two index variables to find the candidate 
   elements in the sorted array.
       (a) Initialize first to the leftmost index: l = 0
       (b) Initialize second  the rightmost index:  r = ar_size-1
3) Loop while l < r.
       (a) If (A[l] + A[r] == sum)  then return 1
       (b) Else if( A[l] + A[r] <  sum )  then l++
       (c) Else r--    
4) No candidates in whole array - return 0
// Java program to check if given array 
// has 2 elements whose sum is equal 
// to the given value 
import java.util.*; 

class GFG { 
 // Function to check if array has 2 elements 
 // whose sum is equal to the given value 
 static boolean hasArrayTwoCandidates(int A[], 
          int arr_size, int sum) 
 { 
  int l, r; 

  /* Sort the elements */
  Arrays.sort(A); 

  /* Now look for the two candidates 
  in the sorted array*/
  l = 0; 
  r = arr_size - 1; 
  while (l < r) { 
   if (A[l] + A[r] == sum) 
    return true; 
   else if (A[l] + A[r] < sum) 
    l++; 
   else // A[i] + A[j] > sum 
    r--; 
  } 
  return false; 
 } 

 // Driver code 
 public static void main(String args[]) 
 { 
  int A[] = { 1, 4, 45, 6, 10, -8 }; 
  int n = 16; 
  int arr_size = A.length; 

  // Function calling 
  if (hasArrayTwoCandidates(A, arr_size, n)) 
   System.out.println("Array has two "
       + "elements with given sum"); 
  else
   System.out.println("Array doesn't have "
       + "two elements with given sum"); 
 } 
} 

Tuesday 3 March 2020

Why WebDriver driver = new ChromeDriver() ?


Below is WebDriver Interface & Respective class implementation architecture.





ChromeDriver driver = new ChromeDriver(); // Lot of methods from parent calss RemoteWebDriver

vs

WebDriver driver = new ChromeDriver(); // we can access only few methods from WebDriver Interface & SerchContext Interface







Ex: Advantage of interface

Public List getList(){
       return new ArrayList<String>()
}

We can return any implemented class for any method which has return type as interface




Wednesday 12 February 2020

macOS - selenium with chrome browser




download chromedriver.exe and run below code - rest all same as windows


@org.testng.annotations.Test
public void m2() {
System.setProperty("webdriver.chrome.driver",
"/Users/kk/Documents/workspace/test/driver/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://www.facebook.com");

}

macOS - Safari browser : selenium setup

Install Java
Install Eclipse
Install TestNg
Create Maven project - add selenium-java & TestNG dependencies

1. Open Safari Browser and look out for Develop Menu
     if you do not found Develop menu , you had to enable it by following below step
     Safari->Preferences -> Advanced Tab -> Select 'Show Develop menu in menu bar'
2. Develop menu -> Allow Remote Automation

Thats all - Here is the Program for safari'

        @Test
public void m1(){
System.out.println("test");
WebDriver driver = new SafariDriver();
driver.get("http://www.facebook.com");

}

Run it

To summarise, we do not need any driver.exe file needs to be downloaded
and configured!

Thursday 23 January 2020

core java interview questions

Can we Override static methods in java? - NO
If a derived class defines a static method with same signature as a static method in base class, the method in the derived class hides the method in the base class

Can we overload static methods? - Yes
We can have two ore more static methods with same name, but differences in input parameters.

what is factory design pattern?
Pattern provides one of the best ways to create an object - We create object without exposing the creation logic to the client and refer to newly created object using a common interface.

https://www.tutorialspoint.com/design_pattern/factory_pattern.htm

how you initialize Page factory object
https://www.seleniumeasy.com/selenium-tutorials/page-factory-pattern-in-selenium-webdriver

what is POM design pattern?
https://www.guru99.com/page-object-model-pom-page-factory-in-selenium-ultimate-guide.html


is java pure object oriented?  - NO
- because it supports primitive data type [Non Object types] like byte,short,int,long,float,double,char,boolean,which are not objects.
- evrything in java is class, except primitive datatypes.still wrapper classess are there..for this reason we can say java is not fully object oriented language
-The main difference between primitive and reference type is that primitive type always has a value, it can never be null but reference type can be null, which denotes the absence of value
-the main difference between two types is that primitive types store actual values but reference type stores handle to object in the heap
-modification on one primitive variable doesn't affect the copy but it does in the case of the reference variable

int i = 20; int j = i; j++; // will not affect i, j will be 21 but i will still be 20
List<String> list = new ArrayList(2);
List<String> copy = list;
copy.add("EUR");
// adding a new element into list, it would be visible to both list and copy
System.out.printf("value of list and copy after modification list: %s, copy: %s %n", list, copy);




staic class :
Static classes are basically a way of grouping classes together in Java. Java doesn't allow you to create top-level static classes; only nested (inner) static classes.
 public class CarParts {
 
    public static class Wheel {
        public Wheel() {
            System.out.println("Wheel created!");
        }
    }

    public CarParts() {
        System.out.println("Car Parts object created!");
    }
}

wrapper class:
Each Java primitive has a corresponding wrapper:
boolean, byte, short, char, int, long, float, double
Boolean, Byte, Short, Character, Integer, Long, Float, Double
These are all defined in the java.lang package, hence we don't need to import them manually.

Basically, generic classes (Collection Framework)only work with objects and don't support primitives. As a result, if we want to work with them, we have to convert primitive values into wrapper objects.

heap memory vs stack memory:
stack memory is used to store local variables and function call
heap memory is used to store objects in Java
Each Thread in Java has their own stack which can be specified using
If there is no memory left in the stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating an object, JVM will throw java.lang.OutOfMemoryError:
If you are using Recursion, on which method calls itself, You can quickly fill up stack memory. Another difference between stack and heap is that size of stack memory is a lot lesser than the size of  heap memory in Java.
ariables stored in stacks are only visible to the owner Thread while objects created in the heap are visible to all thread. In other words, stack memory is kind of private memory of Java Threads while heap memory is shared among all threads.

== vs equals
We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2); //false
System.out.println(s1.equals(s2)); //True