Created
October 10, 2017 08:04
-
-
Save VadimKirilchuk/161905b0f974f6b21651b892c8c35868 to your computer and use it in GitHub Desktop.
RestAssured RequestResponseFilter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.ByteArrayOutputStream; | |
import java.io.PrintStream; | |
import java.io.UnsupportedEncodingException; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import com.jayway.restassured.filter.Filter; | |
import com.jayway.restassured.filter.FilterContext; | |
import com.jayway.restassured.filter.log.LogDetail; | |
import com.jayway.restassured.internal.print.RequestPrinter; | |
import com.jayway.restassured.internal.print.ResponsePrinter; | |
import com.jayway.restassured.response.Response; | |
import com.jayway.restassured.specification.FilterableRequestSpecification; | |
import com.jayway.restassured.specification.FilterableResponseSpecification; | |
import ru.yandex.qatools.allure.annotations.Attachment; | |
public class RequestResponseFilter implements Filter { | |
private static final Logger LOG = LoggerFactory.getLogger(RequestResponseFilter.class); | |
@Override | |
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, | |
FilterContext ctx) { | |
Response response = ctx.next(requestSpec, responseSpec); | |
try { | |
processRequest(requestSpec); | |
processResponse(requestSpec.getURI(), response); | |
} catch (UnsupportedEncodingException e) { | |
throw new RuntimeException("Unsupported encoding", e); | |
} | |
return response; | |
} | |
@Attachment(value = "Request to {0}") | |
public byte[] processRequest(FilterableRequestSpecification request) throws UnsupportedEncodingException { | |
ByteArrayOutputStream out = new ByteArrayOutputStream(); | |
PrintStream stream = new PrintStream(out, true, "UTF-8"); | |
RequestPrinter.print(request, request.getMethod().toString(), request.getURI(), LogDetail.ALL, stream, true); | |
LOG.debug(out.toString("UTF-8")); | |
return out.toByteArray(); | |
} | |
@Attachment(value = "Response from {0}") | |
public byte[] processResponse(String requestUri, Response response) throws UnsupportedEncodingException { | |
ByteArrayOutputStream out = new ByteArrayOutputStream(); | |
PrintStream stream = new PrintStream(out, true, "UTF-8"); | |
stream.printf("Response(%s) ", requestUri); | |
ResponsePrinter.print(response, response.getBody(), stream, LogDetail.ALL, true); | |
LOG.debug(out.toString("UTF-8")); | |
return out.toByteArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment