Loggin RestAssure Request and Response data


Loggin RestAssure Request and Response data

Hi, all welcome to another of my lockdown blog series posts. When performing a test on API endpoints it is important to obtain detailed logs of the request and response data to verify if the output is as expected. In this blog post, I will discuss how we can use RequestLogFilter and ResponseLogFilter to achieve this.

In the below code we are using FileOutputStream and specifying to which file we need to log the output. Next, within the request specification, we call the addFilter method and pass an instance of the RequestLogFilter and ResponseLogFilter. When our test method is invoked, this will call the RequestSpecification type method and write the output to a file. In this example, we are writing to a method file named new-log.txt.

package SpecBuilder;

import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.filter.log.LogDetail;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.filter.log.ResponseLoggingFilter;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.ResponseSpecification;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.FileOutputStream;
import java.io.PrintStream;
import static io.restassured.RestAssured.given;

public class SpecBuilderTest {

    public static  PrintStream log;

    @BeforeTest
    public RequestSpecification requestSpec() throws java.io.IOException {


        log=new PrintStream(new FileOutputStream("new-log.txt"),true);
        log.append("*********************TestResults**********************\r");

        RequestSpecification requestSpecification =new RequestSpecBuilder()
                .setBaseUri("http://api.zippopotam.us")
                .setContentType(ContentType.JSON)
                .addFilter(new RequestLoggingFilter(log))
                .addFilter(new ResponseLoggingFilter(log))
                .build();
        return requestSpecification;
    }

    public ResponseSpecification responseSpec()  {

        ResponseSpecification responseSpecification=new ResponseSpecBuilder()
                .expectStatusCode(200)
                .expectContentType(ContentType.JSON)
                .build();

        return  responseSpecification;
    } 
 
     @Test
     public void testLKCode() throws java.io.IOException {
        given().
                spec(requestSpec()).
                when().
                get("/lk/10350").
                then()
                .spec(responseSpec());
    } 
 
    @Test
     public void testUSCode() throws java.io.IOException {
        given().
                spec(requestSpec()).
                when().
                get("/us/90201").
                then()
                .spec(responseSpec());
    }

    @AfterTest
    public void cleanup(){

        log.append("*********************AfterTestResults**********************");
        log.flush();
        log.close();
    }
}
 
On running this test, within the target folder we should see a file named new-log.txt 
created with the contents as below:
 
*********************TestResults**********************
Request method:    GET
Request URI:   http://api.zippopotam.us/us/90201
Proxy:       <none>
Request params:    <none>
Query params:  <none>
Form params:   <none>
Path params:   <none>
Headers:      Accept=*/*
            Content-Type=application/json; charset=UTF-8
Cookies:      <none>
Multiparts:       <none>
Body:        <none>
HTTP/1.1 200 OK
Date: Wed, 08 Apr 2020 08:41:02 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: __cfduid=dde9b8f5f8715e0f497f22d8fe5c82f6f1586335262; expires=Fri, 08-May-20 08:41:02 GMT; path=/; domain=.zippopotam.us; HttpOnly; SameSite=Lax
X-Cache: hit
Charset: UTF-8
Vary: Accept-Encoding
Access-Control-Allow-Origin: *
CF-Cache-Status: DYNAMIC
Server: cloudflare
CF-RAY: 580aafdd5a4b9760-FRA
Content-Encoding: gzip

{
    "post code": "90201",
    "country": "United States",
    "country abbreviation": "US",
    "places": [
        {
            "place name": "Bell",
            "longitude": "-118.1689",
            "state": "California",
            "state abbreviation": "CA",
            "latitude": "33.9767"
        }
    ]
}
*********************AfterTestResults********************** 
 
When running the above test you would have noticed that the logs only print the second
test and the results for test method testLKCode was not available. To overcome this the
best approach is to check if the request spec object is null and then peform the logic as
shown below.
 
 RequestSpecification requestSpecification;@BeforeTestpublic RequestSpecification requestSpec() throws java.io.IOException {

    if (requestSpecification == null) {
        log = new PrintStream(new FileOutputStream("new-log3.txt"), true);  
        log.append("*********************TestResults**********************\r");
        requestSpecification = new RequestSpecBuilder()
                .setBaseUri(GlobalVariables.getGlobalVariables("baseURL"))
                .setContentType(ContentType.JSON)
                .addFilter(new RequestLoggingFilter(log))
                .addFilter(new ResponseLoggingFilter(log))
                .build();        return requestSpecification;    }
    return requestSpecification;}

The new test would update the logs as below

*********************TestResults**********************
Request method:    GET
Request URI:   http://api.zippopotam.us/lk/10350
Proxy:       <none>
Request params:    <none>
Query params:  <none>
Form params:   <none>
Path params:   <none>
Headers:      Accept=*/*
            Content-Type=application/json; charset=UTF-8
Cookies:      <none>
Multiparts:       <none>
Body:        <none>
HTTP/1.1 200 OK
Date: Fri, 10 Apr 2020 00:52:31 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: __cfduid=d6a3784778e29156d27e376018d50f73b1586479951; expires=Sun, 10-May-20 00:52:31 GMT; path=/; domain=.zippopotam.us; HttpOnly; SameSite=Lax
X-Cache: hit
Charset: UTF-8
Vary: Accept-Encoding
Access-Control-Allow-Origin: *
CF-Cache-Status: DYNAMIC
Server: cloudflare
CF-RAY: 58187c4ffa55324c-FRA
Content-Encoding: gzip

{
    "post code": "10350",
    "country": "Sri Lanka",
    "country abbreviation": "LK",
    "places": [
        {
            "place name": "Dehiwala",
            "longitude": "79.8653",
            "state": "",
            "state abbreviation": "CO",
            "latitude": "6.8514"
        }
    ]
}
Request method:    GET
Request URI:   http://api.zippopotam.us/us/90201
Proxy:       <none>
Request params:    <none>
Query params:  <none>
Form params:   <none>
Path params:   <none>
Headers:      Accept=*/*
            Content-Type=application/json; charset=UTF-8
Cookies:      <none>
Multiparts:       <none>
Body:        <none>
HTTP/1.1 200 OK
Date: Fri, 10 Apr 2020 00:52:32 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: __cfduid=df80bce01b6d70a2f484cc194db32a84e1586479952; expires=Sun, 10-May-20 00:52:32 GMT; path=/; domain=.zippopotam.us; HttpOnly; SameSite=Lax
X-Cache: hit
Charset: UTF-8
Vary: Accept-Encoding
Access-Control-Allow-Origin: *
CF-Cache-Status: DYNAMIC
Server: cloudflare
CF-RAY: 58187c549dd5175a-FRA
Content-Encoding: gzip

{
    "post code": "90201",
    "country": "United States",
    "country abbreviation": "US",
    "places": [
        {
            "place name": "Bell",
            "longitude": "-118.1689",
            "state": "California",
            "state abbreviation": "CA",
            "latitude": "33.9767"
        }
    ]
}
*********************AfterTestResults**********************
 
 
 

Comments