Skip to content

Commit

Permalink
feat(rest-assured): add support for headers blacklist (via #1007)
Browse files Browse the repository at this point in the history
  • Loading branch information
antonfilichkin authored Mar 22, 2024
1 parent ed837de commit 6ff650c
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,11 @@
import io.restassured.specification.FilterableResponseSpecification;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;

import static io.qameta.allure.attachment.http.HttpRequestAttachment.Builder.create;
import static io.qameta.allure.attachment.http.HttpResponseAttachment.Builder.create;
Expand All @@ -40,6 +43,8 @@
*/
public class AllureRestAssured implements OrderedFilter {

private static final String HIDDEN_PLACEHOLDER = "[ BLACKLISTED ]";

private String requestTemplatePath = "http-request.ftl";
private String responseTemplatePath = "http-response.ftl";
private String requestAttachmentName = "Request";
Expand Down Expand Up @@ -89,10 +94,14 @@ public Response filter(final FilterableRequestSpecification requestSpec,
final FilterContext filterContext) {
final Prettifier prettifier = new Prettifier();
final String url = requestSpec.getURI();

final Set<String> hiddenHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
hiddenHeaders.addAll(Objects.requireNonNull(requestSpec.getConfig().getLogConfig().blacklistedHeaders()));

final HttpRequestAttachment.Builder requestAttachmentBuilder = create(requestAttachmentName, url)
.setMethod(requestSpec.getMethod())
.setHeaders(toMapConverter(requestSpec.getHeaders()))
.setCookies(toMapConverter(requestSpec.getCookies()));
.setHeaders(toMapConverter(requestSpec.getHeaders(), hiddenHeaders))
.setCookies(toMapConverter(requestSpec.getCookies(), new HashSet<>()));

if (Objects.nonNull(requestSpec.getBody())) {
requestAttachmentBuilder.setBody(prettifier.getPrettifiedBodyIfPossible(requestSpec));
Expand All @@ -116,7 +125,7 @@ public Response filter(final FilterableRequestSpecification requestSpec,

final HttpResponseAttachment responseAttachment = create(attachmentName)
.setResponseCode(response.getStatusCode())
.setHeaders(toMapConverter(response.getHeaders()))
.setHeaders(toMapConverter(response.getHeaders(), hiddenHeaders))
.setBody(prettifier.getPrettifiedBodyIfPossible(response, response.getBody()))
.build();

Expand All @@ -128,9 +137,10 @@ public Response filter(final FilterableRequestSpecification requestSpec,
return response;
}

private static Map<String, String> toMapConverter(final Iterable<? extends NameAndValue> items) {
private static Map<String, String> toMapConverter(final Iterable<? extends NameAndValue> items,
final Set<String> toHide) {
final Map<String, String> result = new HashMap<>();
items.forEach(h -> result.put(h.getName(), h.getValue()));
items.forEach(h -> result.put(h.getName(), toHide.contains(h.getName()) ? HIDDEN_PLACEHOLDER : h.getValue()));
return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,21 @@
import io.qameta.allure.model.TestResult;
import io.qameta.allure.test.AllureResults;
import io.restassured.RestAssured;
import io.restassured.config.LogConfig;
import io.restassured.config.RestAssuredConfig;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import org.junit.jupiter.params.provider.ArgumentsSource;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

Expand All @@ -55,10 +59,27 @@ public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
}
}

class HiddenHeadersArgumentProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) {

final String hiddenHeader = "Authorization";
final String header = "Accept";
final String headerValue = "value";

final Map<String, String> headers = Map.of(hiddenHeader, headerValue, header, headerValue);
final List<String> expectedHeaders = List.of(hiddenHeader + ": [ BLACKLISTED ]", header + ": " + headerValue);

return Stream.of(
arguments(headers, hiddenHeader, expectedHeaders, new AllureRestAssured()),
arguments(headers, hiddenHeader.toUpperCase(), expectedHeaders, new AllureRestAssured())
);
}
}

/**
* @author charlie (Dmitry Baev).
*/
@SuppressWarnings("unchecked")
class AllureRestAssuredTest {

@ParameterizedTest
Expand All @@ -72,7 +93,7 @@ void shouldCreateAttachment(final List<String> attachmentNames, final AllureRest
.map(TestResult::getAttachments)
.flatMap(Collection::stream)
.map(Attachment::getName))
.isEqualTo(attachmentNames);
.containsExactlyElementsOf(attachmentNames);
}

@Test
Expand Down Expand Up @@ -122,21 +143,46 @@ void shouldCatchAttachmentBody(final List<String> attachmentNames, final AllureR
.collect(Collectors.toList());

assertThat(actualAttachments)
.flatExtracting(Attachment::getName)
.isEqualTo(attachmentNames)
.map(Attachment::getName)
.containsExactlyElementsOf(attachmentNames)
.doesNotContainNull();

assertThat(actualAttachments)
.flatExtracting(Attachment::getSource)
.containsExactlyInAnyOrderElementsOf(new ArrayList<>(results.getAttachments().keySet()))
.map(Attachment::getSource)
.containsExactlyInAnyOrderElementsOf(results.getAttachments().keySet())
.doesNotContainNull();
}

@ParameterizedTest
@ArgumentsSource(HiddenHeadersArgumentProvider.class)
void shouldHideHeadersInAttachments(final Map<String, String> headers,
final String hiddenHeader,
final List<String> expectedValues,
final AllureRestAssured filter) {

final ResponseDefinitionBuilder responseBuilder = WireMock.aResponse().withStatus(200);
headers.forEach(responseBuilder::withHeader);

RestAssured.config = new RestAssuredConfig().logConfig(LogConfig.logConfig().blacklistHeaders(List.of(hiddenHeader)));
RestAssured.replaceFiltersWith(filter);

final AllureResults results = executeWithStub(responseBuilder, RestAssured.with().headers(headers));

assertThat(results.getAttachments().values())
.hasSize(2)
.map(at -> new String(at, StandardCharsets.UTF_8))
.allSatisfy(at -> expectedValues.forEach(ev -> assertThat(at).contains(ev)));
}

protected final AllureResults execute() {
return executeWithStub(WireMock.aResponse().withBody("some body"));
}

protected final AllureResults executeWithStub(ResponseDefinitionBuilder responseBuilder) {
return executeWithStub(responseBuilder, RestAssured.given());
}

protected final AllureResults executeWithStub(ResponseDefinitionBuilder responseBuilder, RequestSpecification spec) {
final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort());
final int statusCode = responseBuilder.build().getStatus();

Expand All @@ -146,13 +192,13 @@ protected final AllureResults executeWithStub(ResponseDefinitionBuilder response

WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/hello?Allure=Form")).willReturn(responseBuilder));
try {
RestAssured.given()
.contentType(ContentType.URLENC)
spec.contentType(ContentType.URLENC)
.formParams("Allure", "Form")
.get(server.url("/hello")).then().statusCode(statusCode);
} finally {
server.stop();
RestAssured.replaceFiltersWith(ImmutableList.of());
RestAssured.config = new RestAssuredConfig();
}
});
}
Expand Down

0 comments on commit 6ff650c

Please sign in to comment.