How to use graphql query in restassured api automation directly using java ?

How to use the graphql query in rest API directly using java?



GraphQL String : 




//Sample program 

System.out.println(classname.graphqlToJson(value));

//this call will return the graphql query into formatted JSON payload and that can be directly used in REST ASSURED API for automation. 

How to get the value entered in the command line to Testng using maven ?

How to get the value entered in the command line to Testng using maven ?


 


Add the following code to your pom.xml:


Add maven-surefire plugin in the dependency :

<dependency>  
  <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>  
  <version>2.21.0</version>  
  <type>maven-plugin</type>
</dependency>


Add the build just like below and set the Systempropertyvariable just like you want.

For example: if you want to add an environment variable and set value to this environment variable at the run time.add the following tag inside the  <systemPropertyVariables> tag.
       
                <environement> ${environment} </envionment>

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.21.0</version>
      <configuration>
        <suiteXmlFiles>
          <!--    <suiteXmlFile>Testsuites/test.xml</suiteXmlFile>    
            <suiteXmlFile>Testsuites/Scantool.xml</suiteXmlFile>         
            
            
            <suiteXmlFile>Testsuites/v2api.xml</suiteXmlFile>
            
            
                Note:-                    =====              
            
            
            
            mvn clean test -Dsurefire.suiteXmlFiles=testng.xml                    -->      
          <suiteXmlFile>${suiteXmlFile}</suiteXmlFile>
        </suiteXmlFiles>
        <!-- Add the property value here and get it inside the program -->
        <systemPropertyVariables>
          <browser>${browsername}</browser>
        </systemPropertyVariables>
      </configuration>
    </plugin>
  </plugins>
</build>


Testng file:
File name: commandline.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Commandline">
  <test verbose="0" name="Commandline" group-by-instances="true" >
    <parameter name="value" value="${browser}" />
    <classes>
      <class name="testcase.runtimecommandline" />
    </classes>
  </test>
</suite>

Java class file
File name:runtimecommandline.java


You can access the value in two ways:
1. One is get the value directly by using System.getProperty("<tag name>")
2. Another one is set the value in testng xml file <parameter name="value" value="${browser}" />
   like this and you can access the value inside the parmeter.


package testcase;
import core.framework;import org.testng.annotations.Parameters;import org.testng.annotations.Test;
public class runtimecommandline  {


    @Test    public void browser(){


        //To use the command line feature use the following command to set the value :
 mvn clean test -Dsurefire.suiteXmlFiles=Testsuites/commandline.xml -Dbrowser=firefox
        String commandlinevalue = System.getProperty("browser");
        if(commandlinevalue.equals(""))
            commandlinevalue="Manually assign value to this variable since value is not passed in commandline";       
     System.out.println("Entered command line value : "+commandlinevalue);    }


    @Parameters({"value"})
    @Test    public void paramter(String value){
        System.out.println("parameter value: "+value);
    }

}


In command line :Run the following command

mvn clean test -Dsurefire.suiteXmlFiles=commandline.xml -Dbrowser=firefox 

Output:

[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running TestSuite
************************      Commandline       *************************
------------------------------             testcase.runtimecommandline:browser      
      --------------------------------------------

->Entered command line value : firefox
------------------------------------------------------------------------------------------------
------------------------------             testcase.runtimecommandline:paramter        
    --------------------------------------------

->parameter value: firefox
------------------------------------------------------------------------------------------------
**********************            -E---N---D-          *********************************
X
X





How to integrate OSWAP ZAP with Selenium ?

What is OSWAP ZAP?
OWASP ZAP (short for Zed Attack Proxy) is an open-source web application security scanner. It is intended to be used by both those new to application security as well as professional penetration testers.


Where to Download OSWAP ZAP?

Go to the below-mentioned link and download the Cross-Platform Package

https://github.com/zaproxy/zaproxy/wiki/Downloads


How to Integrate it With Selenium? 


POM.XML
 <!-- https://mvnrepository.com/artifact/org.zaproxy/zap --> 
   <dependency>  
      <groupId>org.zaproxy</groupId> 
       <artifactId>zap</artifactId> 
       <version>2.7.0</version>
    </dependency>

    <dependency> 
       <groupId>org.zaproxy</groupId>
        <artifactId>zap-clientapi</artifactId>
        <version>1.6.0</version> 
   </dependency>
</dependencies>



// This  Method is to launch the zap

Security.java


public security(){
    String os=System.getProperty("os.name").toLowerCase();
    try {
        if(os.contains("mac")||os.contains("linux")) {

             r = Runtime.getRuntime();           
         p = r.exec(System.getProperty("user.dir")+"/Config/ZAP_2.7.0/zap.sh");      
      Thread.sleep(30000);
        }
        else if( os.contains("win")){

             r = Runtime.getRuntime();         
    p = r.exec(System.getProperty("user.dir")+"/Config/ZAP_2.7.0/zap.bat");       
     Thread.sleep(30000);        }
    
    } catch(Exception e) {
       System.out.println("Exception"+e);
    }
}


Config.Properties

#Secuirty vulnerability : OSWSP ZED
====================================
ZED_HOSTIP=localhost
ZED_HOSTPORT=8089
ZED_APIKEY=Put your zap key


Test.java


Proxy proxy = new Proxy();
proxy.setHttpProxy(lib.getProperty("ZED_HOSTIP")+":"+lib.getProperty("ZED_HOSTPORT"));
proxy.setFtpProxy(lib.getProperty("ZED_HOSTIP")+":"+lib.getProperty("ZED_HOSTPORT"));
proxy.setSslProxy(lib.getProperty("ZED_HOSTIP")+":"+lib.getProperty("ZED_HOSTPORT"));
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("proxy", proxy);

        System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + lib.getProperty("MAC_CHROME"));    
  WebDriver driver=new ChromeDriver(capabilities));    
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
        driver.manage().window().maximize();   
//Write your selenium code 

        driver.close

// Once the code is ran, Pull the report from zap and save it as html report. The below method will do that
//Also place your directory path according, i used inbuild class to get the path using config.


//The return type consist of html tag,to include it in report. Change the return type as per your needs
public  String returnSecurityHtmlReport(){
    try {
        ClientApi api = new ClientApi(lib.getProperty("ZED_HOSTIP").toString(), Integer.parseInt(lib.getProperty("ZED_HOSTPORT")));     
   String result=new String(api.core.htmlreport(lib.getProperty("ZED_APIKEY")));    
    FileOutputStream fop = null;      
  File file;      
  String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());     
   securityReportFilePath=DirectoryCreator.returnReportDirectoryPath()+"/SecurityTesting-"+timeStamp+".html";     
   file = new File(securityReportFilePath);     
   fop = new FileOutputStream(file);
        // if file doesnt exists, then create it     
   if (!file.exists()) {
            file.createNewFile();        }

        // get the content in bytes        byte[] contentInBytes = result.getBytes();   
     fop.write(contentInBytes);       
     fop.flush();      
      fop.close();
        Document doc = Jsoup.parse(result);
       
            return returnTable("<a href=\"file:///"+securityReportFilePath+"\" target=“_blank” >Click to View Security Report</a>");           
    }

    catch (Exception e)
    {
        return "Not able to retrive html report from zap security tool";    }
}



How to filter value in JSON response using expression?



Response JSON Example:
{
    "search": {
        "street": "31, Trevor Street",
        "state": "AL",
        "postal_code": "67901",
        "phone": "6574727441",
        "name": "John Corp",
        "country": "US",
        "city": "Alabama"
    },
    "results": {
        "speedylocal.com": {
            "status": "no-result"
        },
        "chamberofcommerce.com": {
            "status": "complete",
            "data": {
                "site_logo": "http://cdn.verifymybiz.com/",
                "phones": [
                    "271893712"
                ],
                "name": "Sample",
                "live_link": "https://www.chamberofcommerce.com/",
                "full_address": "Testing street",
                "country": "US",
                "accurate": false
            }
        },
        "facebook.com": {
            "status": "in-progress"
        },
     
    }
}


Dependency :

POM.XML
<dependency> 
   <groupId>com.jayway.jsonpath</groupId>  
  <artifactId>json-path</artifactId> 
   <version>2.3.0</version>  
  <exclusions>     
   <exclusion>      
      <artifactId>jcl-over-slf4j</artifactId>     
       <groupId>org.slf4j</groupId>       
 </exclusion>       
 <exclusion>      
      <artifactId>slf4j-api</artifactId>     
       <groupId>org.slf4j</groupId>    
    </exclusion> 
   </exclusions></dependency>



Sample.java

I saved the rest API response in Response object from RestAssured. 



//Reference : https://github.com/json-path/JsonPath

public  String getResponseValueUsingJayway(String objectXpath){
      return com.jayway.jsonpath.JsonPath.read
(response.jsonPath().prettify(),objectXpath).toString();}


Test.java

Example 1:

String Result=object.getResponseValueUsingJayway("$.results");


Example 2:

String Result=object.getResponseValueUsingJayway("$.results..status");




How to use graphql query in postmark and how to automate graphql using restassured api ?


How to use graphql query in postmark ?


1. Open the graphql in web browser and type Query or mutation. which you want to execute in postman.



2. Open developer console and choose the network tab. and then hit the play button in web browser to execute the graphql query


3. In network tab, Right click on the request send to the server and then  select copy->copy as cURL




4. Open postmat and click the import button at the top




5. click on Paste Raw text tab




6. Paste the copied request and then click import button


7. Once the request is import to postmar, click the send button and verify the graphql request return the response.




8. Result of my graphql request in Postmark






how to automate graphql using restassured api ?


Sample snippet of how to use graphql query in restassured api.

Once the request is imported in postmark, copy the data and send the request using restassured api as like a normal api.


response=given()
.body("{"query":"{\n  viewer {\n    login\n  }\n}\n","variables":{},"operationName":null}")
.when()
.contentType(ContentType.JSON)
.post("https://graphql-explorer.githubapp.com/graphql/proxy");

response.print();


How to install chrome in Circle CI


To install chrome browser in CircelCi, Paste the below-mentioned commands in circle ci "pre-dependency commands"





Pre-dependency commands

sudo apt-get install libxss1 libappindicator1 libindicator7
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i ./google-chrome*.deb
sudo apt-get install -f

Remove an web-element from the page during runtime


To Remove the web element in the webpage during selenium execution:


Lets consider this :

Here I want to remove the footer from the webpage while executing and then take a screenshot without the footer.





Method to execute the javascript in the webpage

Method.java

public static void javaScriptExecutor(String javaScript){
    JavascriptExecutor js=null;    if (driver instanceof JavascriptExecutor) {
        js = (JavascriptExecutor)driver;    }
    js.executeScript(javaScript);}



Sample.java

//code whatever you want

Method.javaScriptExecutor("document.getElementsByClassName('footer')[0].style.display
 = \"none\";");

Change the class name as per your requirement.

After this code is executed, the footer is removed.





Integrating rollbar into java application

Rollbar is an error tracking and monitoring application.


Whenever an exception is happing in the java code, it can be logged in the rollbar to view the error log.

POM.XML:
<dependency> 
   <groupId>com.rollbar</groupId>   
   <artifactId>rollbar-java</artifactId>
    <version>1.1.0</version> 
   <exclusions> 
       <exclusion>
            <artifactId>jcl-over-slf4j</artifactId>
            <groupId>org.slf4j</groupId> 
       </exclusion>
        <exclusion>
            <artifactId>slf4j-api</artifactId>
            <groupId>org.slf4j</groupId> 
       </exclusion>
    </exclusions>
</dependency>

Rollbar.java :

package utils;
import com.rollbar.notifier.Rollbar;import com.rollbar.notifier.config.Config;
import java.net.InetAddress;
import static com.rollbar.notifier.config.ConfigBuilder.withAccessToken;
public class rollbar {
    private static Rollbar rollbar;    private static void init() {
        try {
            Config config = withAccessToken(API KEY)
                    .environment("Testing Framework")
                    .platform(InetAddress.getLocalHost().getHostName())
                    .codeVersion("1.0")
                    .build();            rollbar = Rollbar.init(config);        }
        catch (Exception e)
        {
            e.printStackTrace();            log.exception("Rollbar:init() "+"\n"+e.getStackTrace());
        }
    }

    public static void exceptionLog(Exception exception, String exceptionDetils){
        init();        rollbar.error(exception,exceptionDetils);    }

}



Now in your program, you can include the static method in try and catch block to log the details:

Rollbar.exceptionLog(e,"Exception details");


Quality Assurance Engineer - Amazon Interview question

I attend QAE-I interview in Amazon.

Totally i had 8 round of interview. 

1st round : written test
==============
5 question :  1. written programming 
                    2. pseudocode for a program 
                   3. testcase writing 
                        * Functional and non-functional testcase for booking taxi through ola app.
                  4. problem solving
                        * Skype video call is not working, find out the all possible issues.
                 5. test data enumeration  

2nd round : Problem solving 
==================

Totally 2 programming question was asked. 

1. Find the most repetitive character in a string
2. Find the first maximum repeated character in a string

3rd round : Test case enumeration
=====================

1. Testcase for birthday remainder in outlook
2. Testcase for mobile game application
3.Testcase for amazon wallet

4th round: Problem solving
=================
Program + problem solving question
1. Webpage is not loading, what could be the issue ? tell about all possible case to troubleshoot it.
2. Amazon search is not working. how to troubleshoot this issue.

5th round : Managerial Interview 
=====================
Behavioral question  + cultural fit + work done in the past 
1. testcases for banking application. which uses 3rd party app for transcation.

6th round : Bar raiser
=============
Combination of all round with cultural fit 
Few basic question like what is cross browser testing, few program and testcase for whispersync on kindle.

7th round : problem solving
==================
1. two unsorted array 
[-1,-2,4,5,6,8]
[4,3,1,2]

where k=8, find the possible combination which equal to K?

2. abcdeffghijabcd - find the maximum substring in the given string which have a non-repeated characters.

8th round: test data enumeration
====================

1. Testcase for ola app
2. test data enumeration - Given x and y, the program should return number between x and y.
i. Write the program for the above question.
ii. create testdata to break the program which i written.


At last i got the offer in amazon as QAE 😂

Appium Setup in Mac


1. Install android studio :https://developer.android.com/studio/

2. In Avd manager, install the required android os version and create the emulator.

3. Download appium :http://appium.io/

4. Setup the environment variable in .bash_profile.

 To set up :
   i. Open the terminal
   ii. Enter the command : open ~/.bash_profile

Set the environement variable like below:

export PATH=$PATH:/Users/premkumar/Library/Android/sdk
export ANDROID_HOME=/Users/premkumar/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/tools
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home
export PATH=$PATH:$JAVA_HOME/bin:$JAVA_HOME/bin

  iii. save the file and close it.

5. Install node js : brew install node

6.  Then install appium doctor : npm install -g appium-doctor

7. Once it is installed, Run this command : appium-doctor --android

info AppiumDoctor Appium Doctor v.1.4.3
info AppiumDoctor ### Diagnostic starting ###
info AppiumDoctor  ✔ The Node.js binary was found at: /usr/local/bin/node
info AppiumDoctor  ✔ Node version is 10.1.0
info AppiumDoctor  ✔ ANDROID_HOME is set to: /Users/premkumar/Library/Android/sdk
info AppiumDoctor  ✔ JAVA_HOME is set to: /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home
info AppiumDoctor  ✔ adb exists at: /Users/premkumar/Library/Android/sdk/platform-tools/adb
info AppiumDoctor  ✔ android exists at: /Users/premkumar/Library/Android/sdk/tools/android
info AppiumDoctor  ✔ emulator exists at: /Users/premkumar/Library/Android/sdk/tools/emulator
info AppiumDoctor  ✔ Bin directory of $JAVA_HOME is set
info AppiumDoctor ### Diagnostic completed, no fix needed. ###
info AppiumDoctor
info AppiumDoctor Everything looks good, bye!
info AppiumDoctor

If all the things are set correct, then appium is configured properly in Mac.

8. run the program.



TO Launch Emulator in Command prompt in MAC:

${ANDROID_HOME}/emulator/emulator -avd Android



How to start appium server using Program:

Install Node Js:
https://nodejs.org/en/

Install appium:
npm install -g appium


Once the appium is installed use this method in your program to launch appium server:


private static AppiumDriverLocalService service=null;
public void startServer() {

    service = AppiumDriverLocalService.buildDefaultService();   
    service.start();

}


To Stop Appium Server Use this method in your program:

public static void stopAppiumServer() throws Exception{
    service.stop();}


To Launch Android Emulator use this method in your program :


public static void startAndroidEmulator() throws Exception{
    Process p;    if(System.getenv("ANDROID_HOME")==null)
        p=Runtime.getRuntime().exec("/Users/premkumar/Library/Android/sdk/emulator/"
+"emulator -avd "+lib.getProperty("ANDROID_DEVICE_NAME"));     
else     
   p=Runtime.getRuntime().exec(System.getenv("ANDROID_HOME")+"/emulator/"
+"emulator -avd "+lib.getProperty("ANDROID_DEVICE_NAME"));
    Thread.sleep(10000);
}

To Close Android Emulator use this method in your program:


public static void stopAndroidEmulator() throws Exception{
    Process p;  
  if(System.getenv("ANDROID_HOME")==null)
        p=Runtime.getRuntime().exec("/Users/premkumar/Library/Android/sdk/platform-tools/
adb -e emu kill");  
  else 
       p=Runtime.getRuntime().exec(System.getenv("ANDROID_HOME")+"/platform-tools/
adb -e emu kill");  
  Thread.sleep(10000);}


To launch App use this method:
(Please make sure, I used lib.getProperty method to get value from the file , in that place use the value instead of method)


public static void AndroidappLauch() throws Exception {
    DesiredCapabilities capabilities=new DesiredCapabilities();   
 capabilities.setCapability(MobileCapabilityType.DEVICE_NAME,
lib.getProperty("ANDROID_DEVICE_NAME"));   
 capabilities.setCapability(MobileCapabilityType.APP,
System.getProperty("user.dir")+"/MobileApps/"+ 
lib.getProperty("ANDROID_APP"));   
 capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME,"Android");   
 AndroidDriver driver=new AndroidDriver(new 
URL(lib.getProperty("APPIUM_SERVER_URL")), capabilities);
    framework.setAndroidDriver(driver);}

Convert resultset object to list of map

Convert the resultset object to list of map In some cases, while we doing API automation, we need to fetch the value from the DB and hav...