5

I need Get the "CURL" operation from each Rest Assured test and print in the console when not pass the test. It's possible?

For axample, convert:

 given().relaxedHTTPSValidation().
   auth().basic("name", "password").
   param("grant_type","client_credentials").
 when().
   post("https://test_url/oauth/token").
 then().
   statusCode(200);

to

curl --user name:passwoed -k -X POST \
https://test_url/oauth/token \
-H 'cache-control: no-cache' \
-H 'content-type: application/x-www-form-urlencoded' \
-d grant_type=client_credentials
Renzo Parente
  • 315
  • 1
  • 4
  • 10
  • 2
    Not something that I have tried, but the details in the link are quite similar to your ask - https://github.com/dzieciou/curl-logger – Wilfred Clement Feb 15 '19 at 09:43

3 Answers3

8

Include the following dependencies.

Maven:

<dependency>
  <groupId>com.github.dzieciou.testing</groupId>
  <artifactId>curl-logger</artifactId>
  <version>1.0.4</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.6</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.0.9</version>
</dependency>

Once configured use the following piece of code to log the curl request in the console output.

package com.api.test;

import static org.hamcrest.CoreMatchers.is;

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

import com.sample.model.EnrollEmail;
import com.github.dzieciou.testing.curl.CurlLoggingRestAssuredConfigFactory;

import io.restassured.RestAssured;
import io.restassured.config.RestAssuredConfig;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;

/**
 * @author vamsiravi
 *
 */
public class Sample {

    @Test(enabled=true)
    public void sampleAPITest() {

        RestAssuredConfig config = CurlLoggingRestAssuredConfigFactory.createConfig();  

        EnrollEmail email = new EnrollEmail();
        email.setEmailAddress("sample@domain.com");
        RestAssured.given().config(config).contentType(ContentType.JSON).body(email).when().post("https://jsonplaceholder.typicode.com/posts").then()
        .assertThat()
        .statusCode(201);   

    }
}

Output :

[main] DEBUG curl - **
curl 'https://jsonplaceholder.typicode.com/posts' 
-H 'Accept: */*' 
-H 'Content-Type: application/json; charset=UTF-8' 
-H 'Host: jsonplaceholder.typicode.com' 
-H 'Connection: Keep-Alive' 
-H 'User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_181)' 
--data-binary '{"emailAddress":"sample@domain.com"}' 
--compressed 
-k 
-v**

PASSED: sampleAPITest
Nic3500
  • 8,144
  • 10
  • 29
  • 40
Vamsi Ravi
  • 1,196
  • 8
  • 26
4

An alternative is to parse the output of the log().all() as seen in my article.

Note: I've not shared the code here, as it's Apache 2.0 licensed, which is different to Stack Overflow's default licensing.

jamietanna
  • 263
  • 1
  • 8
  • 21
4

Based of @vamsi's answer this is the full implementation of what worked for us.

POM

<http.client.version>4.5.3</http.client.version>
<curl.logger.version>1.0.5</curl.logger.version>

<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>${http.client.version}</version>
</dependency>
<dependency>
   <groupId>com.github.dzieciou.testing</groupId>
   <artifactId>curl-logger</artifactId>
   <version>${curl.logger.version}</version>
</dependency>

And

public class Requests {
    public String baseUrl;
    public RequestSpecification getRequestSpecification(String authorizationToken) {
        /** Enables printing request as curl under the terminal as per https://github.com/dzieciou/curl-logger */
        Options options = Options.builder()
                .printMultiliner()
                .updateCurl(curl -> curl
                        .removeHeader("Host")
                        .removeHeader("User-Agent")
                        .removeHeader("Connection"))
                .build();
        RestAssuredConfig config = CurlLoggingRestAssuredConfigFactory.createConfig(options);
        baseUrl = Constants.getEndpoint();
        RestAssured.baseURI = baseUrl;
        RequestSpecification rq = given()
                .config(config)
                .contentType(ContentType.JSON)
                .contentType("application/json\r\n")
                .header("Accept", "application/json").and()
                .header("Content-Type", "application/json")
                .header("Authorization", authorizationToken)
                .when()
                .log()
                .everything();
        return rq;
    }
}

Generates this bit on the run terminal:

enter image description here

If you can't see it straight away on your run terminal after triggering your tests, or if needing to log it to the standard system output or to a .log file, creating a logback.xml file under the test/resources folder as per the below may help you.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
    </encoder>
</appender>

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>mylog.log</file>
    <append>true</append>
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{15} - %msg%n%rEx</pattern>
    </encoder>
</appender>

<logger name="curl" level="DEBUG">
    <appender-ref ref="FILE"/>
</logger>

PS: Changing between the system output or .log file is done based on which one you pass as a reference for the "curl" logger appender.

enter image description here

Francislainy Campos
  • 3,462
  • 4
  • 33
  • 81