PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label rest-assured. Show all posts
Showing posts with label rest-assured. Show all posts

Tuesday, November 22, 2022

[FIXED] How to validate specific node from SOAP XML response with several namespaces using Rest-assured?

 November 22, 2022     java, rest-assured, soap, xml, xpath     No comments   

Issue

I'm using SOAP and testing it by Rest-Assured. I want to validate response body XML by Rest-Assured that it has expected node value. But I can't get node I need.

Here is my response XML. It has several namespaces. I want to get the value of this node ns3:site

<soap-env:envelope xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soap-env:body>
      <ns4:findsiteconfigurationbysmth xmlns:ns3="http://www.testsite.com/common" xmlns:ns2="http://www.testsite.com/plant" xmlns:ns4="someapi:com:plant" xmlns:ns5="someapi:com:reasoncode">
         <ns4:response>
            <ns2:ref>SiteWD:QWERTY</ns2:ref>
            <ns3:site>QWERTY</ns3:site>
            <ns3:description>test description</ns3:description>
            <ns3:timezone>Africa/Abidjan</ns3:timezone>
         </ns4:response>
      </ns4:findsiteconfigurationbysmth>
   </soap-env:body>
</soap-env:envelope>

Previously I saved my response to a String variable and produce my validation with this code.

   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   factory.setNamespaceAware(true);
   DocumentBuilder builder = factory.newDocumentBuilder();
   Document myXml = builder.parse(new InputSource(new StringReader(myStringXml)));

   NodeList node = myXml.getDocumentElement()
  .getElementsByTagNameNS("http://www.testsite.com/common", "site");
   node.item(0).getTextContent();

This code works! Response is QWERTY

Now I'm trying to validate it by Rest-Assured.

.spec(defaultRequestSpecification(mySpec))
.config(RestAssuredConfig.config()
.xmlConfig(XmlConfig.xmlConfig()
.with().namespaceAware(true)
.declareNamespace("site", "http://www.testsite.com/common")))
.post()
.then()
.statusCode(200)
.body("site", equalTo("QWERTY"));

And my response is

1 expectation failed. 
XML path site doesn't match. 
Expected: QWERTY 
Actual: SiteWD:QWERTYQWERTYtest descriptionAfrica/Abidjan

I tried to change declared namespace to "ns3", "ns3:site". And the same story with xPath in a body method - "ns3", "ns3:site", "site" and so on. The result is the same... A single string of text from ns3 nodes.

What I'm doing wrong? Please help me to figure out where is the problem. How to get only one node? What should I change?


Solution

According to the REST Assured docs, the following should work for you:

.config(RestAssuredConfig.config()
.xmlConfig(XmlConfig.xmlConfig()
.with()
.namespaceAware(true)
.declareNamespace("soap-env", "http://schemas.xmlsoap.org/soap/envelope/")
.declareNamespace("ns4", "someapi:com:plant")
.declareNamespace("ns3", "http://www.testsite.com/common")))
.post()
.then()
.statusCode(200)
.body("soap-env:envelope.soap-env:body.ns4:findsiteconfigurationbysmth.ns4:response.ns3:site.text()", equalTo("QWERTY"));


Answered By - Not a JD
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do i extract the SOAP XML Response Tag and Validate it in Rest Assured using TestNG

 November 22, 2022     java, rest-assured, soap, testng, xml     No comments   

Issue

This is my Code :

package testcases;

import io.restassured.RestAssured;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.Response;
import org.apache.commons.io.IOUtils;
import org.testng.annotations.Test;

import java.io.FileInputStream;

import static io.restassured.RestAssured.given;
public class api_automation {


        @Test
        public  void postMethod() throws Exception{

            FileInputStream fileinputstream= new FileInputStream("/home/intellij-projects/rest-assured/src/main/java/testcases/request.xml");
            RestAssured.baseURI="*******";
            Response responses= given()
                    .header("Content-Type", "text/xml")
                    .and()
                    .body(IOUtils.toString(fileinputstream,"UTF-8"))
                    .when()
                    .post("******")
                    .then()
                    .statusCode(200)
                    .and()
                    .log().all().extract().response();


            XmlPath xmlPath=new XmlPath(responses.asString());
            String StatusCode= xmlPath.getString("<StatusCode>");

            System.out.println("Status Code is " +StatusCode);

        }

    }

Output of My Code

HTTP/1.1 200 OK
Date: Thu, 10 Nov 2022 12:20:21 IST
Content-Type: text/xml;charset=iso-8859-1
Expires: Thu, 10 Nov 2022 12:20:21 IST
Content-Length: 951
Server: Jetty(9.4.14.v20181114)

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <ns4:SendMessageElement xmlns:ns6="http://******/uwl/ws/message/wsdl/error" 
xmlns:ns5="http://*****/uwl/ws/message/wsdl/common" 
xmlns:ns4="http://*****/uwl/ws/message/wsdl/send" 
xmlns:ns3="http://*****/uwl/ws/message/wsdl/application" 
xmlns:ns2="http://*****/uwl/ws/message/wsdl/header" 
xmlns="http://*****/uwl/ws/message/wsdl/acm">
      <ns4:MessageId>1101220210165</ns4:MessageId>
      <ns4:StatusCode>Success-2000</ns4:StatusCode> ---This Tag needs to be validated
      <ns4:StatusDetail>Success</ns4:StatusDetail>
      <ns4:DestinationResponses>
        <ns4:destinationResponse>
          <ns4:Destination>1000030</ns4:Destination>
          <ns4:TimeStamp>20221110122021</ns4:TimeStamp>
          <ns4:MessageId>43</ns4:MessageId>
          <ns4:StatusCode>Success-2000</ns4:StatusCode>
          <ns4:StatusDetail>Success</ns4:StatusDetail>
        </ns4:destinationResponse>
      </ns4:DestinationResponses>
    </ns4:SendMessageElement>
  </soap:Body>
</soap:Envelope>


Status Code is1101220210165Success-2000Success10000302022111012202143SBL-SMS-MT-2000Success

===============================================
Default Suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================


I want the Test to Pass provided that the given Status Code Matches the Response Tag Status Code

Like in the Code declare a variable and the response should be equal to that

I want to match the following tag with the expected outcome:

  <ns4:StatusCode>Success-2000</ns4:StatusCode>

With the following lines , i am getting other tag responses as well

        String StatusCode= xmlPath.getString("<StatusCode>");

        System.out.println("Status Code is " +StatusCode);

Output :

Status Code is1101220210165Success-2000Success10000302022111012202143SBL-SMS-MT-2000Success

Solution

Use this path: Envelope.Body.SendMessageElement.DestinationResponses.destinationResponse.StatusCode

Test is:

public static void main(String[] args) {
    String result = RestAssured
            .get("https://run.mocky.io/v3/08f352c8-641d-4adc-b2e6-49add556c883")
            .then()
            .extract()
            .xmlPath()
            .getString("Envelope.Body.SendMessageElement.DestinationResponses.destinationResponse.StatusCode");
    System.out.println(result);
}

Output: Success-2000



Answered By - Alexey R.
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 20, 2022

[FIXED] How to match a parameter value which contains ("${") using Cucumber DataTable in Java

 September 20, 2022     cucumber, datatable, hashmap, java, rest-assured     No comments   

Issue

I have the below Cucumber scenario with data table. I want to set query parameters in REST Assured framework. Here we have key= at and value=${atToken} which I am trying to get runtime value instead of passing hardcoded value through data table. In the below setParams method, I am trying to match the ${atToken} using param.contains("${"), but I am not able to get the desired result. Please let me know what I need to change in this for loop.

for (String param : params.keySet()) {
    if (param.contains("${")) {
        params.replace(param, RUN_TIME_DATA.get(param));
    }
}

Feature file:

  And I set query parameters
  | location     | NY         |
  | at           | ${atToken} |

Stepdefintion:

@And("set {} parameters")
public void set_query_parameters(String query, DataTable params) throws IOException {
    POC.setParams(query, params.asMap());
}

Utils file:

public void setParams (String type, Map < String, String > params) throws IOException {
    for (String param : params.keySet()) {
        if (param.contains("${")) {
            params.replace(param, RUN_TIME_DATA.get(param));
        }
    }
    switch (type.toLowerCase()) {
        case "form":
            request.formParams(params);
            break;
        case "query":
            request.queryParams(params);
            break;
        case "path":
            request.pathParams(params);
            break;

    }
}

Hooks file:

@Before
public void beforeScenario() throws Exception {
    RUN_TIME_DATA.put("atToken", POC.createAuth());
}

Solution

If I understood correctly your quetion, there are a few issues with your implementation.

First of all, you have a gherkin instruction as And I set query parameters but the step definition is @And("set {} parameters")

As you defined "query" in your step definition, I assume that you have a scenario like this.

Scenario Outline: Params scenario
Given ...
When ...
Then ...
    And I set "<queryType>" parameters
      | location | NY         |
      | at       | ${atToken} |
    Examples:
      | queryType |
      | form      |
      | path      |

Second problem is that params.asMap() does not create a mutable map but your setParams method will need a mutable one.

@And("I set {string} parameters")
public void set_query_parameters(String queryType, DataTable params) throws IOException {
    // POC.setParams(queryType, params.asMap()); // not mutable map
    POC.setParams(queryType, new HashMap(params.asMap()));
}

The main issue in your loop was that you were searching $ symbol in key instead of value.

public void setParams (String type, Map<String, String> params) throws IOException {
      for (Map.Entry<String, String> entry : params.entrySet()) {
         final String key = entry.getKey();
         final String value = entry.getValue();

         // if value is parameterized
         if (value.contains("${")) {
            // you are using stripped value as key in your RUN_TIME_DATA
            final String keyInRuntimeMap = getParamKeyFrom(value);                      
            params.replace(key, RUN_TIME_DATA.get(keyInRuntimeMap));
         }
      }

      switch (type.toLowerCase()) {
         case "form":
            request.formParams(params);
            break;
         case "query":
            request.queryParams(params);
            break;
         case "path":
            request.pathParams(params);
            break;
        // what should happen if unknown type given
         default:
            throw new IllegalArgumentException("unknown type=" + type);
      }
   }

     /**
    * Will strip someKey from ${someKey}
    *
    * @param text
    * @return stripped text or the original text
    */
   private String getParamKeyFrom(final String text) {
      // pattern to match -> ${someKey}
      final Pattern pattern = Pattern.compile("\\$\\{(.*)\\}");
      final Matcher matcher = pattern.matcher(text);

      if (matcher.find()) {
         return matcher.group(1);
      }

      // if pattern does not match return the same string
      return text;
   }

Hope it helps.



Answered By - ocos
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing