io.restassured.specification.FilterableRequestSpecification Java Examples

The following examples show how to use io.restassured.specification.FilterableRequestSpecification. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RestAssuredEdgeGridFilterIntegrationTest.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 6 votes vote down vote up
@Test
public void replacesProvidedHostHeader() throws URISyntaxException, IOException,
        RequestSigningException {


    RestAssured.given()
            .relaxedHTTPSValidation()
            .header("Host", "ignored-hostname.com")
            .filter(new RestAssuredEdgeGridFilter(credential))
            .filter(new Filter() {
                @Override
                public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
                    MatcherAssert.assertThat(requestSpec.getHeaders().getList("Host").size(),
                            CoreMatchers.equalTo(1));
                    MatcherAssert.assertThat(requestSpec.getHeaders().get("Host").getValue(),
                            CoreMatchers.equalTo(credential.getHost()));

                    return ctx.next(requestSpec, responseSpec);
                }
            })
            .get();


}
 
Example #2
Source File: RestAssuredEdgeGridFilterTest.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 6 votes vote down vote up
@Test
public void replacesProvidedHostHeader() throws URISyntaxException, IOException,
        RequestSigningException {


    RestAssured.given()
            .relaxedHTTPSValidation()
            .header("Host", "ignored-hostname.com")
            .filter(new RestAssuredEdgeGridFilter(credential))
            .filter(new Filter() {
                @Override
                public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
                    MatcherAssert.assertThat(requestSpec.getHeaders().getList("Host").size(),
                            CoreMatchers.equalTo(1));
                    MatcherAssert.assertThat(requestSpec.getHeaders().get("Host").getValue(),
                            CoreMatchers.equalTo(credential.getHost()));

                    return ctx.next(requestSpec, responseSpec);
                }
            })
            .get();


}
 
Example #3
Source File: RestAssuredEdgeGridRequestSigner.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 6 votes vote down vote up
@Override
protected Request map(FilterableRequestSpecification requestSpec) {
    if (!requestSpec.getMultiPartParams().isEmpty()) {
        throw new IllegalArgumentException("multipart request is not supported");
    }

    Request.RequestBuilder builder = Request.builder()
            .method(requestSpec.getMethod())
            .uri(URI.create(requestSpec.getURI()))
            .body(serialize(requestSpec.getBody()));

    for (Header header : requestSpec.getHeaders()) {
        builder.header(header.getName(), header.getValue());
    }
    return builder.build();
}
 
Example #4
Source File: RequestVerifierFilter.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
@Override
public Response filter(FilterableRequestSpecification requestSpec,
		FilterableResponseSpecification responseSpec, FilterContext context) {
	Map<String, Object> configuration = getConfiguration(requestSpec, context);
	configuration.put("contract.jsonPaths", this.jsonPaths.keySet());
	Response response = context.next(requestSpec, responseSpec);
	if (requestSpec.getBody() != null && !this.jsonPaths.isEmpty()) {
		String actual = new String((byte[]) requestSpec.getBody());
		for (JsonPath jsonPath : this.jsonPaths.values()) {
			new JsonPathValue(jsonPath, actual).assertHasValue(Object.class,
					"an object");
		}
	}
	if (this.builder != null) {
		this.builder.willReturn(getResponseDefinition(response));
		StubMapping stubMapping = this.builder.build();
		MatchResult match = stubMapping.getRequest()
				.match(new WireMockRestAssuredRequestAdapter(requestSpec));
		assertThat(match.isExactMatch()).as("wiremock did not match request")
				.isTrue();
		configuration.put("contract.stubMapping", stubMapping);
	}
	return response;
}
 
Example #5
Source File: YamlToJsonFilter.java    From microprofile-open-api with Apache License 2.0 6 votes vote down vote up
@Override
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
    try {
        Response response = ctx.next(requestSpec, responseSpec);

        ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
        Object obj = yamlReader.readValue(response.getBody().asString(), Object.class);

        ObjectMapper jsonWriter = new ObjectMapper();
        String json = jsonWriter.writeValueAsString(obj);

        ResponseBuilder builder = new ResponseBuilder();
        builder.clone(response);
        builder.setBody(json);
        builder.setContentType(ContentType.JSON);

        return builder.build();
    }
    catch (Exception e) {
        throw new IllegalStateException("Failed to convert the request: " + ExceptionUtils.getMessage(e), e);
    }
}
 
Example #6
Source File: RamlValidationFilter.java    From raml-tester with Apache License 2.0 5 votes vote down vote up
@Override
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec,
                       FilterContext filterContext) {
    final Response response = filterContext.next(requestSpec, responseSpec);
    final RamlReport report = ramlChecker.check(new RestAssuredRamlRequest(requestSpec), new RestAssuredRamlResponse(response));
    reportStore.storeReport(report);
    return response;

}
 
Example #7
Source File: RestAssuredEdgeGridRequestSigner.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 5 votes vote down vote up
@Override
protected void setHost(FilterableRequestSpecification requestSpec, String host, URI uri) {
    // Avoid redundant Host headers
    requestSpec.removeHeader("Host")
            .baseUri("https://" + host)
            .header("Host", host);
}
 
Example #8
Source File: RestAssuredEdgeGridRequestSigner.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 5 votes vote down vote up
@Override
protected URI requestUri(FilterableRequestSpecification requestSpec) {
    // Due to limitations of REST-assured design only requests with relative paths can be updated
    String requestPath = getRequestPath(requestSpec);
    if (!isRelativeUrl(requestPath)) {
        throw new IllegalArgumentException("path in request cannot be absolute");
    }

    return URI.create(requestSpec.getBaseUri() + requestPath);
}
 
Example #9
Source File: RestAssuredEdgeGridRequestSigner.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 5 votes vote down vote up
private static String getRequestPath(FilterableRequestSpecification requestSpec) {
    try {
        Field f = requestSpec.getClass().getDeclaredField("path");
        f.setAccessible(true);
        String requestPath = (String) f.get(requestSpec);
        // remove path placeholder parameter brackets
        requestPath = requestPath.replaceAll("[{}]*", "");
        return requestPath;
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw new RuntimeException(e); // should never occur
    }
}
 
Example #10
Source File: RestAssuredEdgeGridFilter.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 5 votes vote down vote up
@Override
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
    try {
        binding.sign(requestSpec, requestSpec);
    } catch (RequestSigningException e) {
        throw new RuntimeException(e);
    }
    return ctx.next(requestSpec, responseSpec);
}
 
Example #11
Source File: RestAssuredIntegrationTest.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 5 votes vote down vote up
@Test
public void replaceProvidedHostHeaderOnlyInApacheClient() throws URISyntaxException, IOException,
        RequestSigningException {

    wireMockServer.stubFor(get(urlPathEqualTo("/billing-usage/v1/reportSources"))
            .withHeader("Authorization", matching(".*"))
            .willReturn(aResponse()
                    .withStatus(200)));

    getBaseRequestSpecification()
            .header("Host", "ignored-hostname.com")
            .filter(new Filter() {
                @Override
                public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
                    MatcherAssert.assertThat(requestSpec.getHeaders().getList("Host").size(),
                            CoreMatchers.equalTo(1));
                    MatcherAssert.assertThat(requestSpec.getHeaders().get("Host").getValue(),
                            CoreMatchers.equalTo("ignored-hostname.com"));
                    return ctx.next(requestSpec, responseSpec);
                }
            })
            .get("/billing-usage/v1/reportSources");


    List<LoggedRequest> loggedRequests = wireMockServer.findRequestsMatching(RequestPattern
            .everything()).getRequests();
    MatcherAssert.assertThat(loggedRequests.get(0).getHeader("Host"),
            CoreMatchers.equalTo(SERVICE_MOCK));

}
 
Example #12
Source File: WebCustomRequestMapperTest.java    From cukes with Apache License 2.0 5 votes vote down vote up
@Test
public void snapshotNumberShouldBeLessThan10Digits() {
    FilterableRequestSpecification requestSpec = mock(FilterableRequestSpecification.class);
    when(requestSpec.getURI()).thenReturn("http://www.google.com");
    when(requestSpec.getHeaders()).thenReturn(new Headers());

    WebCustomRequest request = mapper.map(requestSpec);
    assertThat(request, hasProperty("snapshot", CustomMatchers.stringWithLength(lessThanOrEqualTo(15)))); //10 digits + t + .inf
}
 
Example #13
Source File: WebCustomRequestMapper.java    From cukes with Apache License 2.0 5 votes vote down vote up
public WebCustomRequest map(FilterableRequestSpecification requestSpec) {
    try {
        URL url = new URL(requestSpec.getURI());
        String method = String.valueOf(requestSpec.getMethod());

        WebCustomRequest request = new WebCustomRequest();
        request.setName(method + " to " + url.toString());
        //Don't URL encode LR parameter boundaries (curly braces)
        request.setUrl(url.toString().replace("%7B", "{").replace("%7D", "}"));
        request.setMethod(method);
        request.setResource("0");
        request.setSnapshot(String.format("t%d.inf", (long) (System.currentTimeMillis() % Math.pow(10, 10))));
        request.setMode(url.getProtocol());
        request.setBody(requestSpec.getBody());

        request.getBeforeFunctions().add(new WebRequestSaveParam());
        request.getBeforeFunctions().add(new WebRequestSaveResponseBody());
        request.getBeforeFunctions().add(new WebRequestSaveResponseHeaders());

        for (Header header : requestSpec.getHeaders()) {
            request.getBeforeFunctions().add(headerMapper.map(header));
        }

        return request;
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}
 
Example #14
Source File: LoadRunnerFilter.java    From cukes with Apache License 2.0 5 votes vote down vote up
@Override
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec,
                       FilterContext ctx) {
    WebCustomRequest request = mapper.map(requestSpec);
    trx.addFunction(request);
    boolean blockRequests = globalWorldFacade.getBoolean(CukesOptions.LOADRUNNER_FILTER_BLOCKS_REQUESTS);
    if (blockRequests) {
        Response response = Mockito.mock(Response.class);
        Mockito.when(response.then()).thenReturn(Mockito.mock(ValidatableResponse.class));
        return response;
    }
    return ctx.next(requestSpec, responseSpec);
}
 
Example #15
Source File: HttpLoggingPlugin.java    From cukes with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeRequest(RequestSpecification requestSpecification) {
    if (!(requestSpecification instanceof FilterableRequestSpecification)) {
        throw new IllegalArgumentException("Cannot retrieve configuration from: " + requestSpecification);
    }

    final FilterableRequestSpecification filterableRequestSpecification = (FilterableRequestSpecification) requestSpecification;

    final RequestLogSpecification logSpec = filterableRequestSpecification.log();
    final List<LogDetail> logDetails = parseLogDetails(world.get(LOGGING_REQUEST_INCLUDES, DEFAULT_REQUEST_INCLUDES));

    details:
    for (LogDetail detail : logDetails) {
        switch (detail) {
            case ALL:
                logSpec.all();
                break details;
            case BODY:
                logSpec.body();
                break;
            case COOKIES:
                logSpec.cookies();
                break;
            case HEADERS:
                logSpec.headers();
                break;
            case METHOD:
                logSpec.method();
                break;
            case PARAMS:
                logSpec.parameters();
                break;
            case URI:
                logSpec.uri();
                break;
        }
    }
}
 
Example #16
Source File: AuthFilter.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Response filter( FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec,
    FilterContext ctx )
{
    if ( requestSpec.getAuthenticationScheme() instanceof NoAuthScheme )
    {
        if ( hasSessionCookie( requestSpec ) )
        {
            requestSpec.removeCookies();
        }

        lastLoggedInUser = "";
        lastLoggedInUserPsw = "";
    }

    if ( requestSpec.getAuthenticationScheme() instanceof PreemptiveBasicAuthScheme && (
        ((PreemptiveBasicAuthScheme) requestSpec.getAuthenticationScheme()).getUserName() != lastLoggedInUser ||
        ((PreemptiveBasicAuthScheme) requestSpec.getAuthenticationScheme()).getPassword() != lastLoggedInUserPsw ) )
    {
        if ( hasSessionCookie( requestSpec ) )
        {
            requestSpec.removeCookies();
        }

        lastLoggedInUser = ((PreemptiveBasicAuthScheme) requestSpec.getAuthenticationScheme()).getUserName();
        lastLoggedInUserPsw = ((PreemptiveBasicAuthScheme) requestSpec.getAuthenticationScheme()).getPassword();
    }

    final Response response = ctx.next( requestSpec, responseSpec );
    return response;
}
 
Example #17
Source File: RestAssuredRequestMaker.java    From heat with Apache License 2.0 5 votes vote down vote up
private String getRequestDetails(Method httpMethod, String url) {
    Optional<String> requestDetails = Optional.absent();
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        requestDetails = Optional.fromNullable(RequestPrinter.print((FilterableRequestSpecification) requestSpecification, httpMethod.name(), url, LogDetail.ALL,
                new PrintStream(os), true));
    } catch (IOException e) {
        logUtils.error("Unable to log 'Request Details', error occured during retrieving the information");
    }
    return requestDetails.or("");
}
 
Example #18
Source File: AllureRestAssured.java    From allure-java with Apache License 2.0 5 votes vote down vote up
@Override
public Response filter(final FilterableRequestSpecification requestSpec,
                       final FilterableResponseSpecification responseSpec,
                       final FilterContext filterContext) {
    final Prettifier prettifier = new Prettifier();


    final HttpRequestAttachment.Builder requestAttachmentBuilder = create("Request", requestSpec.getURI())
            .setMethod(requestSpec.getMethod())
            .setHeaders(toMapConverter(requestSpec.getHeaders()))
            .setCookies(toMapConverter(requestSpec.getCookies()));

    if (Objects.nonNull(requestSpec.getBody())) {
        requestAttachmentBuilder.setBody(prettifier.getPrettifiedBodyIfPossible(requestSpec));
    }

    final HttpRequestAttachment requestAttachment = requestAttachmentBuilder.build();

    new DefaultAttachmentProcessor().addAttachment(
            requestAttachment,
            new FreemarkerAttachmentRenderer(requestTemplatePath)
    );

    final Response response = filterContext.next(requestSpec, responseSpec);
    final HttpResponseAttachment responseAttachment = create(response.getStatusLine())
            .setResponseCode(response.getStatusCode())
            .setHeaders(toMapConverter(response.getHeaders()))
            .setBody(prettifier.getPrettifiedBodyIfPossible(response, response.getBody()))
            .build();

    new DefaultAttachmentProcessor().addAttachment(
            responseAttachment,
            new FreemarkerAttachmentRenderer(responseTemplatePath)
    );

    return response;
}
 
Example #19
Source File: RequestVerifierFilter.java    From spring-cloud-netflix with Apache License 2.0 4 votes vote down vote up
WireMockRestAssuredRequestAdapter(FilterableRequestSpecification request) {
	this.request = request;
}
 
Example #20
Source File: RequestVerifierFilter.java    From spring-cloud-netflix with Apache License 2.0 4 votes vote down vote up
protected Map<String, Object> getConfiguration(
		FilterableRequestSpecification requestSpec, FilterContext context) {
	Map<String, Object> configuration = context
			.<Map<String, Object>>getValue(CONTEXT_KEY_CONFIGURATION);
	return configuration;
}
 
Example #21
Source File: RestAssuredRamlRequest.java    From raml-tester with Apache License 2.0 4 votes vote down vote up
RestAssuredRamlRequest(FilterableRequestSpecification requestSpec) {
    this.requestSpec = requestSpec;
}
 
Example #22
Source File: RestAssuredEdgeGridRequestSigner.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 4 votes vote down vote up
public void sign(FilterableRequestSpecification requestSpecification) throws RequestSigningException {
    sign(requestSpecification, requestSpecification);
}
 
Example #23
Source File: AuthFilter.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private boolean hasSessionCookie( FilterableRequestSpecification requestSpec )
{
    return requestSpec.getCookies().hasCookieWithName( "JSESSIONID" ) ||
        requestSpec.getCookies().hasCookieWithName( "SESSION" );
}
 
Example #24
Source File: RestAssuredEdgeGridRequestSigner.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 4 votes vote down vote up
@Override
protected void setAuthorization(FilterableRequestSpecification requestSpec, String signature) {
    requestSpec.header("Authorization", signature);
}