Java Code Examples for com.github.tomakehurst.wiremock.client.WireMock#stubFor()

The following examples show how to use com.github.tomakehurst.wiremock.client.WireMock#stubFor() . 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: AuthenticatedRestTemplateTest.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthRestTemplateFor401() {
    initialAuthenticationMock();
    mockCsrfTokenEndpoint();

    logger.debug("Mock returns 401 for POST request when session timeout");
    WireMock.stubFor(
            WireMock.post(WireMock.urlEqualTo("/random-401-endpoint"))
                    .willReturn(WireMock.aResponse().withStatus(HttpStatus.UNAUTHORIZED.value()))
    );

    String response = null;
    try {
        response = authenticatedRestTemplate.postForObject("random-401-endpoint", new HashMap<String, String>(), String.class);
    } catch (RestClientException e) {
        logger.debug("Expecting this to fail because the response for /random-401-endpoint has been stubbed to be always returning a 401");
        Assert.assertEquals("Tried to re-authenticate but the response remains to be unauthenticated", e.getMessage());
    }

    Assert.assertNull(response);

    WireMock.verify(2, WireMock.getRequestedFor(WireMock.urlMatching("/login")).withHeader("Accept", WireMock.matching("text/plain.*")));
    WireMock.verify(2, WireMock.postRequestedFor(WireMock.urlMatching("/login")).withHeader("Accept", WireMock.matching("text/plain.*")));
    WireMock.verify(2, WireMock.postRequestedFor(WireMock.urlMatching("/random-401-endpoint")).withHeader("Accept", WireMock.matching("text/plain.*")).withHeader("X-CSRF-TOKEN", WireMock.matching("madeup-csrf-value")));
}
 
Example 2
Source File: RequestResponeLoggingFilterTest.java    From parsec-libraries with Apache License 2.0 6 votes vote down vote up
@Test
public void getRequestShouldNotBeLogged() throws ExecutionException, InterruptedException {

    String url = "/getWithFilter200?param1=value1";
    WireMock.stubFor(get(urlEqualTo(url))
            .willReturn(okJson(stubRespBodyJson)));

    String requestMethod = HttpMethod.GET;

    Map<String, Collection<String>> headers = stubHeaders;

    ParsecAsyncHttpRequest request =
            new ParsecAsyncHttpRequest.Builder()
                    .setUrl(wireMockBaseUrl+url)
                    .setHeaders(headers)
                    .setRequestTimeout(30)
                    .setMethod(requestMethod)
                    .setBody("").setBodyEncoding("UTF-8").build();

    Response response = parsecHttpClient.criticalExecute(request).get();
    assertThat(response.getStatus(), equalTo(200));

    then(mockAppender).should(never()).doAppend(any());

}
 
Example 3
Source File: CustomerClientWiremockTest.java    From bootiful-testing-online-training with Apache License 2.0 6 votes vote down vote up
@Test
public void customerByIdShouldReturnACustomer() {

	WireMock.stubFor(WireMock.get(WireMock.urlMatching("/customers/1"))
		.willReturn(
			WireMock.aResponse()
				.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)
				.withStatus(HttpStatus.OK.value())
				.withBody(asJson(customerById))
		));

	Customer customer = client.getCustomerById(1L);
	BDDAssertions.then(customer.getFirstName()).isEqualToIgnoringCase("first");
	BDDAssertions.then(customer.getLastName()).isEqualToIgnoringCase("last");
	BDDAssertions.then(customer.getEmail()).isEqualToIgnoringCase("email");
	BDDAssertions.then(customer.getId()).isEqualTo(1L);
}
 
Example 4
Source File: AuthenticatedRestTemplateTest.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthRestTemplateForSessionTimeoutWithPostForObject() {
    initialAuthenticationMock();
    mockCsrfTokenEndpoint();

    logger.debug("Mock returns 403 for POST request when session timeout");
    WireMock.stubFor(
            WireMock.post(WireMock.urlEqualTo("/random-403-endpoint"))
                    .willReturn(WireMock.aResponse().withStatus(HttpStatus.FORBIDDEN.value()))
    );

    String response = null;
    try {
        response = authenticatedRestTemplate.postForObject("random-403-endpoint", new HashMap<String, String>(), String.class);
    } catch (RestClientException e) {
        logger.debug("Expecting this to fail because the response for /random-403-endpoint has been stubbed to be always returning a 403");
        Assert.assertEquals("Tried to re-authenticate but the response remains to be unauthenticated", e.getMessage());
    }

    Assert.assertNull(response);

    WireMock.verify(2, WireMock.getRequestedFor(WireMock.urlMatching("/login")).withHeader("Accept", WireMock.matching("text/plain.*")));
    WireMock.verify(2, WireMock.postRequestedFor(WireMock.urlMatching("/login")).withHeader("Accept", WireMock.matching("text/plain.*")));
    WireMock.verify(2, WireMock.postRequestedFor(WireMock.urlMatching("/random-403-endpoint")).withHeader("Accept", WireMock.matching("text/plain.*")).withHeader("X-CSRF-TOKEN", WireMock.matching("madeup-csrf-value")));
}
 
Example 5
Source File: AuthenticatedRestTemplateTest.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoubleEncodedUrlForGetForObject() {
    initialAuthenticationMock();
    mockCsrfTokenEndpoint();

    WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/api/assets?path=abc%5Cdef"))
            .willReturn(WireMock.aResponse()
                    .withStatus(HttpStatus.FOUND.value())
                    .withHeader("Location", "/api/assets?path=abc%5Cdefs")
                    .withBody("")));

    Map<String, String> uriVariables = new HashMap<>();
    uriVariables.put("path", "abc\\def");
    authenticatedRestTemplate.getForObjectWithQueryStringParams("/api/assets", String.class, uriVariables);

    WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/api/assets?path=abc%5Cdef")));
}
 
Example 6
Source File: HttpCredentialsUtilsTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private void generateStub(int statusCode, String message) {
    WireMock.stubFor(
        WireMock.get(WireMock.urlPathEqualTo(CREDENTIALS_PATH))
                .willReturn(WireMock.aResponse()
                                    .withStatus(statusCode)
                                    .withHeader("Content-Type", "application/json")
                                    .withHeader("charset", "utf-8")
                                    .withBody(message)));
}
 
Example 7
Source File: ParsecAsyncHttpClientProfilingTest.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
@Test
public void criticalPostRequestShouldBeLogged() throws URISyntaxException, ExecutionException, InterruptedException {

    String url = "/post200Profiling";
    String headerStr = "criticalPostHost";

    WireMock.stubFor(post(urlEqualTo(url))
            .withRequestBody(equalToJson(stubReqBodyJson))
            .willReturn(okJson(stubRespBodyJson)
                    .withHeader(ParsecClientDefine.HEADER_CONTENT_LENGTH, String.valueOf(stubRespBodyJson.length()))
            ));

    String requestMethod = HttpMethod.POST;
    Map<String, Collection<String>> headers = new HashMap<>();
    headers.put(ParsecClientDefine.HEADER_HOST, Arrays.asList(headerStr));


    ParsecAsyncHttpRequest request =
            new ParsecAsyncHttpRequest.Builder()
                    .setUrl(wireMockBaseUrl + url)
                    .setHeaders(headers)
                    .setRequestTimeout(COMMON_REQUEST_TIME_OUT)
                    .setMethod(requestMethod)
                    .setBody(stubReqBodyJson).setBodyEncoding("UTF-8").build();


    parsecHttpClient.criticalExecute(request).get();

    String patternAsStr = createPatternString(requestMethod, request.getUrl(), headerStr,
            String.valueOf(stubRespBodyJson.length()), 200, "single");


    then(mockAppender).should().doAppend(argThat(hasToString(matchesPattern(patternAsStr))));

}
 
Example 8
Source File: ParsecAsyncHttpClientProfilingTest.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
@Test
public void faultyPostRequestShouldBeLogged() throws URISyntaxException {

    String url = "/postAtFault";
    String headerStr = "postAtFaultHost";
    WireMock.stubFor(post(urlEqualTo(url))
            .withRequestBody(equalToJson(stubReqBodyJson))
            .willReturn(aResponse().withFixedDelay(1000)));

    String requestMethod = HttpMethod.POST;


    Map<String, Collection<String>> headers = new HashMap<>();
    headers.put(ParsecClientDefine.HEADER_HOST, Arrays.asList(headerStr));

    ParsecAsyncHttpRequest request =
            new ParsecAsyncHttpRequest.Builder()
                    .setUrl(wireMockBaseUrl + url)
                    .setHeaders(headers)
                    .setRequestTimeout(300)
                    .setMethod(requestMethod)
                    .setBody(stubReqBodyJson).setBodyEncoding("UTF-8").build();

    Throwable exception = null;
    try {
        parsecHttpClient.criticalExecute(request).get();
    } catch (Exception e) {
        exception = e;
    }

    assertThat(exception, is(notNullValue()));

    String patternAsStr = createPatternString(requestMethod, request.getUrl(), headerStr,
            "",-1, "single");

    then(mockAppender).should().doAppend(argThat(hasToString(matchesPattern(patternAsStr))));

}
 
Example 9
Source File: BoxCollectionTest.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
@Test
@Category(UnitTest.class)
public void addItemToCollectionSucceeds() throws IOException {
    String result = "";
    String collectionsResults = "";
    final String folderId = "12345";
    final String addItemURL = "/folders/" + folderId + "?([a-z]*)";
    final String collectionURL = "/collections/?limit=100&offset=0";
    BoxCollection favorites = null;

    collectionsResults = TestConfig.getFixture("BoxCollection/GetCollections200");

    WireMock.stubFor(WireMock.get(WireMock.urlEqualTo(collectionURL))
            .willReturn(WireMock.aResponse()
                    .withHeader("Content-Type", "application/json")
                    .withBody(collectionsResults)));

    result = TestConfig.getFixture("BoxCollection/AddItemToCollection200");

    WIRE_MOCK_CLASS_RULE.stubFor(WireMock.put(WireMock.urlPathMatching(addItemURL))
            .willReturn(WireMock.aResponse()
                    .withHeader("Content-Type", "application/json")
                    .withBody(result)));

    Iterable<BoxCollection.Info> collections = BoxCollection.getAllCollections(this.api);

    for (BoxCollection.Info info : collections) {
        favorites = info.getResource();
    }

    BoxFolder folder = new BoxFolder(this.api, "12345");
    BoxFolder.Info folderInfo = folder.setCollections(favorites);

    assertThat(favorites, is(notNullValue()));
    Assert.assertEquals("Ball Valve Diagram", folderInfo.getName());
    Assert.assertEquals(75256, folderInfo.getSize());
    Assert.assertEquals("12345", folderInfo.getID());
}
 
Example 10
Source File: AuthenticatedRestTemplateTest.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnPreparedAuthRestTemplateAndSessionTimeoutForGetForObject() {
    initialAuthenticationMock();
    mockCsrfTokenEndpoint();

    WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/session-timeout-endpoint"))
            .willReturn(WireMock.aResponse()
                    .withStatus(HttpStatus.FOUND.value())
                    .withHeader("Location", "/login")
                    .withBody("")));

    String response = null;
    try {
        response = authenticatedRestTemplate.getForObject("session-timeout-endpoint", String.class);
    } catch (RestClientException e) {
        logger.debug("Expecting this to fail because the response for /session-timeout-endpoint has been stubbed to be always returning a 302");
        Assert.assertEquals("Tried to re-authenticate but the response remains to be unauthenticated", e.getMessage());
    }

    Assert.assertNull("There should have been no response", response);

    // Expecting 2 requests for each because initially, the AuthenticatedRestTemplate has not been prepared,
    // there hasn't been any session set or csrf token, so it'll authenticate first.
    // Then it'll resume the original request (ie. session-timeout-endpoint) but the response session timeout, so it
    // retries the auth flow again, and lastly, tries the session-timeout-endpoint again.
    // So in summary, this is the following expected flow:
    // 1. GET /login - because it has not been prepped, it starts auth flow
    // 2. POST /login
    // 3. GET /session-timeout-endpoint - response 302/login
    // 4. GET /login
    // 5. POST /login
    // 6. GET /session-timeout-endpoint
    WireMock.verify(2, WireMock.getRequestedFor(WireMock.urlMatching("/login")).withHeader("Accept", WireMock.matching("text/plain.*")));
    WireMock.verify(2, WireMock.postRequestedFor(WireMock.urlMatching("/login")).withHeader("Accept", WireMock.matching("text/plain.*")));
    WireMock.verify(2, WireMock.getRequestedFor(WireMock.urlMatching("/session-timeout-endpoint")).withHeader("Accept", WireMock.matching("text/plain.*")).withHeader("X-CSRF-TOKEN", WireMock.matching("madeup-csrf-value")));
}
 
Example 11
Source File: RequestResponeLoggingFilterTest.java    From parsec-libraries with Apache License 2.0 4 votes vote down vote up
@Test
public void successPostRequestsShouldBeLogged() throws URISyntaxException, ExecutionException, InterruptedException, IOException {

    String url = "/postWithFilter200?param1=value1";
    WireMock.stubFor(post(urlEqualTo(url))
            .withRequestBody(equalToJson(stubReqBodyJson))
            .willReturn(okJson(stubRespBodyJson)
                    .withHeader("respHeader1", "respHV1","respHV2")));

    Map<String, Collection<String>> responseHeaders = new HashMap<>();
    responseHeaders.put("respHeader1", Arrays.asList("respHV1", "respHV2"));

    String requestMethod = HttpMethod.POST;

    Map<String, Collection<String>> headers = stubHeaders;

    ParsecAsyncHttpRequest request =
            new ParsecAsyncHttpRequest.Builder()
                    .setUrl(wireMockBaseUrl+url)
                    .setHeaders(headers)
                    .setRequestTimeout(30)
                    .setMethod(requestMethod)
                    .setBody(stubReqBodyJson).setBodyEncoding("UTF-8").build();

    Response response = parsecHttpClient.criticalExecute(request).get();

    String pattern = createLogStringPattern(requestMethod, request.getUrl(), "param1=value1",
            headers, stubReqBodyJson,
            200, responseHeaders, stubRespBodyJson);

    ArgumentCaptor<ILoggingEvent> loggingEventArgumentCaptor = ArgumentCaptor.forClass(ILoggingEvent.class);
    then(mockAppender).should().doAppend(loggingEventArgumentCaptor.capture());

    String message = loggingEventArgumentCaptor.getValue().getMessage();

    assertThat(message,
            JsonMatchers.jsonEquals(pattern)
                        .whenIgnoringPaths("request.headers.Accept-Encoding",
                                "response.headers.Content-Type","response.headers.Server","response.headers.Transfer-Encoding")

    );


    assertThat(response.getStatus(), equalTo(200));
    assertThat(response.getEntity(), is(notNullValue()));
}
 
Example 12
Source File: OAuthClientTest.java    From rundeck-http-plugin with ISC License 4 votes vote down vote up
@Before
public void setUp() {
    // Validate endpoints with a variety of access tokens.
    WireMock.stubFor(WireMock.get(WireMock.urlEqualTo(ENDPOINT_VALIDATE))
            .withHeader(HttpHeaders.ACCEPT, WireMock.equalTo(OAuthClient.JSON_CONTENT_TYPE))
            .withHeader(HttpHeaders.AUTHORIZATION, WireMock.equalTo("Bearer " + ACCESS_TOKEN_VALID))
            .willReturn(WireMock.aResponse()
                    .withStatus(200)
                    .withHeader(HttpHeaders.CONTENT_TYPE, OAuthClient.JSON_CONTENT_TYPE)
                    .withBody("{\"client\": \"" + CLIENT_VALID + "\"}")));
    WireMock.stubFor(WireMock.get(WireMock.urlEqualTo(ENDPOINT_VALIDATE))
            .withHeader(HttpHeaders.ACCEPT, WireMock.equalTo(OAuthClient.JSON_CONTENT_TYPE))
            .withHeader(HttpHeaders.AUTHORIZATION, WireMock.equalTo("Bearer " + ACCESS_TOKEN_CONFUSED_DEPUTY))
            .willReturn(WireMock.aResponse()
                    .withStatus(200)
                    .withHeader(HttpHeaders.CONTENT_TYPE, OAuthClient.JSON_CONTENT_TYPE)
                    .withBody("{\"client\": \"confused\"}")));
    WireMock.stubFor(WireMock.get(WireMock.urlEqualTo(ENDPOINT_VALIDATE))
            .withHeader(HttpHeaders.AUTHORIZATION, WireMock.equalTo("Bearer " + ACCESS_TOKEN_EXPIRED))
            .willReturn(WireMock.aResponse()
                    .withStatus(401)));
    WireMock.stubFor(WireMock.get(WireMock.urlEqualTo(ENDPOINT_VALIDATE))
            .withHeader(HttpHeaders.AUTHORIZATION, WireMock.equalTo("Bearer " + ACCESS_TOKEN_FOREVER_EXPIRED))
            .willReturn(WireMock.aResponse()
                    .withStatus(401)));
    WireMock.stubFor(WireMock.get(WireMock.urlEqualTo(ENDPOINT_VALIDATE))
            .withHeader(HttpHeaders.AUTHORIZATION, WireMock.equalTo("Bearer " + ACCESS_TOKEN_INVALID))
            .willReturn(WireMock.aResponse()
                    .withStatus(400)));

    // Token endpoints with a variety of access tokens.
    WireMock.stubFor(WireMock.post(WireMock.urlEqualTo(ENDPOINT_TOKEN))
            .withHeader(HttpHeaders.ACCEPT, WireMock.equalTo(OAuthClient.JSON_CONTENT_TYPE))
            .withHeader(HttpHeaders.CONTENT_TYPE, WireMock.equalTo(OAuthClient.FORM_CONTENT_TYPE))
            .withHeader(HttpHeaders.AUTHORIZATION, WireMock.equalTo("Basic " + Base64.encode(CLIENT_VALID + ":" + CLIENT_SECRET)))
            .withRequestBody(WireMock.matching(".*grant_type=client_credentials.*"))
            .willReturn(WireMock.aResponse()
                    .withStatus(200)
                    .withHeader(HttpHeaders.CONTENT_TYPE, OAuthClient.JSON_CONTENT_TYPE)
                    .withBody("{\"access_token\":\"" + ACCESS_TOKEN_VALID + "\",\"token_type\":\"bearer\"}")));
    WireMock.stubFor(WireMock.post(WireMock.urlEqualTo(ENDPOINT_TOKEN))
            .withHeader(HttpHeaders.ACCEPT, WireMock.equalTo(OAuthClient.JSON_CONTENT_TYPE))
            .withHeader(HttpHeaders.CONTENT_TYPE, WireMock.equalTo(OAuthClient.FORM_CONTENT_TYPE))
            .withHeader(HttpHeaders.AUTHORIZATION, WireMock.equalTo("Basic " + Base64.encode(CLIENT_FOREVER_EXPIRED+ ":" + CLIENT_SECRET)))
            .withRequestBody(WireMock.matching(".*grant_type=client_credentials.*"))
            .willReturn(WireMock.aResponse()
                    .withStatus(200)
                    .withHeader(HttpHeaders.CONTENT_TYPE, OAuthClient.JSON_CONTENT_TYPE)
                    .withBody("{\"access_token\":\"" + ACCESS_TOKEN_VALID + "\",\"token_type\":\"bearer\"}")));
    WireMock.stubFor(WireMock.post(WireMock.urlEqualTo(ENDPOINT_TOKEN))
            .withHeader(HttpHeaders.ACCEPT, WireMock.equalTo(OAuthClient.JSON_CONTENT_TYPE))
            .withHeader(HttpHeaders.CONTENT_TYPE, WireMock.equalTo(OAuthClient.FORM_CONTENT_TYPE))
            .withHeader(HttpHeaders.AUTHORIZATION, WireMock.equalTo("Basic " + Base64.encode(CLIENT_INVALID + ":" + CLIENT_SECRET)))
            .withRequestBody(WireMock.matching(".*grant_type=client_credentials.*"))
            .willReturn(WireMock.aResponse()
                    .withStatus(401)));
    WireMock.stubFor(WireMock.post(WireMock.urlEqualTo(ENDPOINT_TOKEN))
            .withHeader(HttpHeaders.ACCEPT, WireMock.equalTo(OAuthClient.JSON_CONTENT_TYPE))
            .withHeader(HttpHeaders.CONTENT_TYPE, WireMock.equalTo(OAuthClient.FORM_CONTENT_TYPE))
            .withHeader(HttpHeaders.AUTHORIZATION, WireMock.equalTo("Basic " + Base64.encode(CLIENT_INVALID_GRANT + ":" + CLIENT_SECRET)))
            .withRequestBody(WireMock.matching(".*grant_type=client_credentials.*"))
            .willReturn(WireMock.aResponse()
                    .withStatus(400)
                    .withHeader(HttpHeaders.CONTENT_TYPE, OAuthClient.JSON_CONTENT_TYPE)
                    .withBody("{\"error_description\":\"" + ERROR_UNAUTHORIZED_GRANT_TYPE_DESCRIPTION +
                            "\",\"error\":\"" + ERROR_UNAUTHORIZED_GRANT_TYPE + "\"}")));
    WireMock.stubFor(WireMock.post(WireMock.urlEqualTo(ENDPOINT_TOKEN))
            .withHeader(HttpHeaders.ACCEPT, WireMock.equalTo(OAuthClient.JSON_CONTENT_TYPE))
            .withHeader(HttpHeaders.CONTENT_TYPE, WireMock.equalTo(OAuthClient.FORM_CONTENT_TYPE))
            .withHeader(HttpHeaders.AUTHORIZATION, WireMock.equalTo("Basic " + Base64.encode(CLIENT_INVALID_GRANT_NO_DESCRIPTION + ":" + CLIENT_SECRET)))
            .withRequestBody(WireMock.matching(".*grant_type=client_credentials.*"))
            .willReturn(WireMock.aResponse()
                    .withStatus(400)
                    .withHeader(HttpHeaders.CONTENT_TYPE, OAuthClient.JSON_CONTENT_TYPE)
                    .withBody("{\"error\":\"" + ERROR_UNAUTHORIZED_GRANT_TYPE + "\"}")));
}
 
Example 13
Source File: HttpWorkflowStepPluginTest.java    From rundeck-http-plugin with ISC License 4 votes vote down vote up
@Before
public void setUp() {
    plugin = new HttpWorkflowStepPlugin();
    oAuthClientTest.setUp(); // We need to setup the OAuth endpoints too.

    synchronized(HttpWorkflowStepPlugin.oauthClients) {
        HttpWorkflowStepPlugin.oauthClients.clear();
    }

    // Test all endpoints by simply iterating.
    for(String method : HttpWorkflowStepPlugin.HTTP_METHODS) {
        // Simple endpoint
        WireMock.stubFor(WireMock.request(method, WireMock.urlEqualTo(REMOTE_URL)).atPriority(100)
                .willReturn(WireMock.aResponse()
                        .withStatus(200)));

        // HTTP Basic
        WireMock.stubFor(WireMock.request(method, WireMock.urlEqualTo(REMOTE_BASIC_URL))
                .withBasicAuth(OAuthClientTest.CLIENT_VALID, OAuthClientTest.CLIENT_SECRET)
                .willReturn(WireMock.aResponse()
                        .withStatus(200)));

        // OAuth with a fresh token
        WireMock.stubFor(WireMock.request(method, WireMock.urlEqualTo(REMOTE_OAUTH_URL))
                .withHeader("Authorization", WireMock.equalTo("Bearer " + OAuthClientTest.ACCESS_TOKEN_VALID))
                .willReturn(WireMock.aResponse()
                        .withStatus(200)));

        // BASIC that returns a 401
        WireMock.stubFor(WireMock.request(method, WireMock.urlEqualTo(ERROR_URL_401))
                .willReturn(WireMock.aResponse()
                        .withStatus(401)));

        // OAuth with an expired token
        WireMock.stubFor(WireMock.request(method, WireMock.urlEqualTo(REMOTE_OAUTH_EXPIRED_URL))
                .withHeader("Authorization", WireMock.equalTo("Bearer " + OAuthClientTest.ACCESS_TOKEN_EXPIRED))
                .willReturn(WireMock.aResponse()
                        .withStatus(401)));
        WireMock.stubFor(WireMock.request(method, WireMock.urlEqualTo(REMOTE_OAUTH_EXPIRED_URL))
                .withHeader("Authorization", WireMock.equalTo("Bearer " + OAuthClientTest.ACCESS_TOKEN_VALID))
                .willReturn(WireMock.aResponse()
                        .withStatus(200)));

        // 500 Error
        WireMock.stubFor(WireMock.request(method, WireMock.urlEqualTo(ERROR_URL_500))
                .willReturn(WireMock.aResponse()
                        .withStatus(500)));
    }

    // Simple bogus URL that yields a 404
    WireMock.stubFor(WireMock.request("GET", WireMock.urlEqualTo(BOGUS_URL))
                    .willReturn(WireMock.aResponse().withStatus(404)));

    // Timeout test
    WireMock.stubFor(WireMock.request("GET", WireMock.urlEqualTo(REMOTE_SLOW_URL))
            .willReturn(WireMock.aResponse().withFixedDelay(SLOW_TIMEOUT).withStatus(200)));
}
 
Example 14
Source File: RetryAutoConfigurationTest.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
/**
 * This test verifies that the combination of @FeignClient and @Retry annotation works as same
 * as @Retry alone works with any normal service class
 */
@Test
public void testFeignClient() {

    WireMock.stubFor(WireMock
        .get(WireMock.urlEqualTo("/retry/"))
        .willReturn(WireMock.aResponse().withStatus(200).withBody("This is successful call"))
    );
    WireMock.stubFor(WireMock.get(WireMock.urlMatching("^.*\\/retry\\/error.*$"))
        .willReturn(WireMock.aResponse().withStatus(400).withBody("This is error")));

    assertThat(retryRegistry).isNotNull();
    assertThat(retryProperties).isNotNull();

    RetryEventsEndpointResponse retryEventListBefore = retryEvents("/actuator/retryevents");
    RetryEventsEndpointResponse retryEventsEndpointFeignListBefore = retryEvents(
        "/actuator/retryevents/" + RETRY_DUMMY_FEIGN_CLIENT_NAME);

    try {
        retryDummyFeignClient.doSomething("error");
    } catch (Exception ex) {
        // Do nothing. The IOException is recorded by the retry as it is one of failure exceptions
    }
    // The invocation is recorded by the CircuitBreaker as a success.
    retryDummyFeignClient.doSomething(StringUtils.EMPTY);

    Retry retry = retryRegistry.retry(RETRY_DUMMY_FEIGN_CLIENT_NAME);
    assertThat(retry).isNotNull();

    // expect retry is configured as defined in application.yml
    assertThat(retry.getRetryConfig().getMaxAttempts()).isEqualTo(3);
    assertThat(retry.getName()).isEqualTo(RETRY_DUMMY_FEIGN_CLIENT_NAME);
    assertThat(retry.getRetryConfig().getExceptionPredicate().test(new IOException())).isTrue();

    assertThat(retry.getMetrics().getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
    assertThat(retry.getMetrics().getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(1);
    assertThat(retry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt()).isEqualTo(1);
    assertThat(retry.getMetrics().getNumberOfSuccessfulCallsWithRetryAttempt()).isEqualTo(0);

    // expect retry actuator endpoint contains both retries
    ResponseEntity<RetryEndpointResponse> retriesList = restTemplate
        .getForEntity("/actuator/retries", RetryEndpointResponse.class);
    assertThat(new HashSet<>(retriesList.getBody().getRetries()))
        .contains(RETRY_BACKEND_A, RETRY_BACKEND_B,
            BACKEND_C, RETRY_DUMMY_FEIGN_CLIENT_NAME);

    // expect retry-event actuator endpoint recorded both events
    RetryEventsEndpointResponse retryEventList = retryEvents("/actuator/retryevents");
    assertThat(retryEventList.getRetryEvents())
        .hasSize(retryEventListBefore.getRetryEvents().size() + 3);

    retryEventList = retryEvents("/actuator/retryevents/" + RETRY_DUMMY_FEIGN_CLIENT_NAME);
    assertThat(retryEventList.getRetryEvents())
        .hasSize(retryEventsEndpointFeignListBefore.getRetryEvents().size() + 3);

    assertThat(retry.getRetryConfig().getExceptionPredicate().test(new IOException())).isTrue();
    assertThat(retry.getRetryConfig().getExceptionPredicate().test(new IgnoredException()))
        .isFalse();
    assertThat(retryAspect.getOrder()).isEqualTo(399);
}
 
Example 15
Source File: RequestResponeLoggingFilterTest.java    From parsec-libraries with Apache License 2.0 4 votes vote down vote up
@Test
public void faultyPostRequestShouldBeLogged() throws URISyntaxException, JsonProcessingException {

    String url = "/postWithFilterAtFault";
    WireMock.stubFor(post(urlEqualTo(url))
            .withRequestBody(equalToJson(stubReqBodyJson))
            .willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER)));

    String requestMethod = HttpMethod.POST;



    ParsecAsyncHttpRequest request =
            new ParsecAsyncHttpRequest.Builder()
                    .setUrl(wireMockBaseUrl+url)
                    .setHeaders(stubHeaders)
                    .setRequestTimeout(30)
                    .setMethod(requestMethod)
                    .setBody(stubReqBodyJson).setBodyEncoding("UTF-8").build();

    Throwable exception = null;
    try {
        parsecHttpClient.criticalExecute(request).get();
    } catch (Exception e) {
        exception = e;
    }

    assertThat(exception, is(notNullValue()));

    ArgumentCaptor<ILoggingEvent> loggingEventArgumentCaptor = ArgumentCaptor.forClass(ILoggingEvent.class);
    then(mockAppender).should().doAppend(loggingEventArgumentCaptor.capture());

    String message = loggingEventArgumentCaptor.getValue().getMessage();
    String pattern = createLogStringPatternForError(requestMethod, request.getUrl(), "",
            stubHeaders, stubReqBodyJson, null);

    assertThat(message,
            JsonMatchers.jsonEquals(pattern)
                    .whenIgnoringPaths("request.headers.Accept-Encoding")
    );
}
 
Example 16
Source File: ParsecAsyncHttpClientProfilingTest.java    From parsec-libraries with Apache License 2.0 4 votes vote down vote up
@Test
public void faultyPostRetryRequestsShouldBeLogged() throws URISyntaxException, ExecutionException, InterruptedException {

    String scenarioName = "retryPostAfterError";
    String secondState = "success after retry";
    String url = "/retryPostAtFault";
    String headerStr = "retryPostAtFaultHost";

    int clientTimeout = COMMON_REQUEST_TIME_OUT;
    WireMock.stubFor(post(urlEqualTo(url)).inScenario(scenarioName)
            .withRequestBody(equalToJson(stubReqBodyJson))
            .willSetStateTo(secondState)
            .willReturn(okJson(stubRespBodyJson)
                    .withChunkedDribbleDelay(20, clientTimeout+100)));


    WireMock.stubFor(post(urlEqualTo(url)).inScenario(scenarioName)
            .whenScenarioStateIs(secondState)
            .withRequestBody(equalToJson(stubReqBodyJson))
            .willReturn(okJson(stubRespBodyJson)
                    .withHeader(ParsecClientDefine.HEADER_CONTENT_LENGTH, String.valueOf(stubRespBodyJson.length()))
            ));


    String requestMethod = HttpMethod.POST;


    Map<String, Collection<String>> headers = new HashMap<>();
    headers.put(ParsecClientDefine.HEADER_HOST, Arrays.asList(headerStr));

    ParsecAsyncHttpRequest request =
            new ParsecAsyncHttpRequest.Builder()
                    .setUrl(wireMockBaseUrl + url)
                    .setHeaders(headers)
                    .addRetryException(IOException.class)
                    .addRetryException(TimeoutException.class)
                    .setMaxRetries(2)
                    .setRequestTimeout(clientTimeout)
                    .setMethod(requestMethod)
                    .setBody(stubReqBodyJson).setBodyEncoding("UTF-8").build();

    Response response = parsecHttpClient.criticalExecute(request).get();

    assertThat(response.getStatus(), equalTo(200));



    ArgumentCaptor<ILoggingEvent> loggingEventArgumentCaptor = ArgumentCaptor.forClass(ILoggingEvent.class);
    then(mockAppender).should(times(2)).doAppend(loggingEventArgumentCaptor.capture());


    String loggedFailureMsg = loggingEventArgumentCaptor.getAllValues().get(0).toString();


    String failurePatternAsStr = createPatternString(requestMethod, request.getUrl(), headerStr,
            "", -1, "single");
    assertThat(loggedFailureMsg, matchesPattern(failurePatternAsStr));


    String successPatternAsStr = createPatternString(requestMethod, request.getUrl(), headerStr,
            "49", 200, "single\\|retry:-1");
    String loggedSuccessMsg = loggingEventArgumentCaptor.getAllValues().get(1).toString();
    assertThat(loggedSuccessMsg, matchesPattern(successPatternAsStr));
}
 
Example 17
Source File: ParsecAsyncHttpClientProfilingTest.java    From parsec-libraries with Apache License 2.0 4 votes vote down vote up
@Test
public void postRequestRetriesShouldBeLogged() throws ExecutionException, InterruptedException {


    String url = "/postRequestRetriesProfiling";
    String headerStr = "postRetriesHost";

    String scenarioName = "postRetries";
    WireMock.stubFor(post(urlEqualTo(url)).inScenario(scenarioName)
            .whenScenarioStateIs(Scenario.STARTED)
            .willSetStateTo("requested count 1")
            .withRequestBody(equalToJson(stubReqBodyJson))
            .willReturn(aResponse()
                    .withHeader(ParsecClientDefine.HEADER_CONTENT_LENGTH,"0")
                    .withStatus(500)));

    WireMock.stubFor(post(urlEqualTo(url)).inScenario(scenarioName)
            .whenScenarioStateIs("requested count 1")
            .withRequestBody(equalToJson(stubReqBodyJson))
            .willReturn(okJson(stubRespBodyJson)
                    .withHeader(ParsecClientDefine.HEADER_CONTENT_LENGTH, String.valueOf(stubRespBodyJson.length()))
            ));

    String requestMethod = HttpMethod.POST;
    Map<String, Collection<String>> headers = new HashMap<>();
    headers.put(ParsecClientDefine.HEADER_HOST, Arrays.asList(headerStr));

    ParsecAsyncHttpRequest request =
            new ParsecAsyncHttpRequest.Builder()
                    .setUrl(wireMockBaseUrl + url)
                    .setHeaders(headers)
                    .setRequestTimeout(COMMON_REQUEST_TIME_OUT)
                    .setMethod(requestMethod)
                    .setMaxRetries(2)
                    .addRetryStatusCode(500)
                    .setBody(stubReqBodyJson).setBodyEncoding("UTF-8").build();


    Response response = parsecHttpClient.criticalExecute(request).get();


    assertThat(response.getStatus(), equalTo(200));


    ArgumentCaptor<ILoggingEvent> loggingEventArgumentCaptor = ArgumentCaptor.forClass(ILoggingEvent.class);
    then(mockAppender).should(times(2)).doAppend(loggingEventArgumentCaptor.capture());

    String loggedFailureMsg = loggingEventArgumentCaptor.getAllValues().get(0).toString();

    String failurePatternAsStr = createPatternString(requestMethod, request.getUrl(), headerStr,
            "0",500, "single");
    assertThat(loggedFailureMsg, matchesPattern(failurePatternAsStr));


    String successPatternAsStr = createPatternString(requestMethod, request.getUrl(), headerStr,
            "49", 200, "single\\|retry:500");

    String loggedSuccessMsg = loggingEventArgumentCaptor.getAllValues().get(1).toString();
    assertThat(loggedSuccessMsg, matchesPattern(successPatternAsStr));
}
 
Example 18
Source File: ValidatorTest.java    From validator-badge with Apache License 2.0 4 votes vote down vote up
@BeforeClass
private void setUpWireMockServer() throws IOException {
    this.wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().dynamicPort());
    this.wireMockServer.start();
    this.serverPort = wireMockServer.port();
    WireMock.configureFor(this.serverPort);

    String pathFile = FileUtils.readFileToString(new File("src/test/resources/valid_oas3.yaml"));

    WireMock.stubFor(get(urlPathMatching("/valid/yaml"))
            .willReturn(aResponse()
                    .withStatus(HttpURLConnection.HTTP_OK)
                    .withHeader("Content-type", "application/yaml")
                    .withBody(pathFile
                            .getBytes(StandardCharsets.UTF_8))));

    pathFile = FileUtils.readFileToString(new File("src/test/resources/invalid_oas3.yaml"));

    WireMock.stubFor(get(urlPathMatching("/invalid/yaml"))
            .willReturn(aResponse()
                    .withStatus(HttpURLConnection.HTTP_OK)
                    .withHeader("Content-type", "application/yaml")
                    .withBody(pathFile
                            .getBytes(StandardCharsets.UTF_8))));

    pathFile = FileUtils.readFileToString(new File("src/test/resources/valid_swagger2.yaml"));

    WireMock.stubFor(get(urlPathMatching("/validswagger/yaml"))
            .willReturn(aResponse()
                    .withStatus(HttpURLConnection.HTTP_OK)
                    .withHeader("Content-type", "application/yaml")
                    .withBody(pathFile
                            .getBytes(StandardCharsets.UTF_8))));

    pathFile = FileUtils.readFileToString(new File("src/test/resources/invalid_swagger2.yaml"));

    WireMock.stubFor(get(urlPathMatching("/invalidswagger/yaml"))
            .willReturn(aResponse()
                    .withStatus(HttpURLConnection.HTTP_OK)
                    .withHeader("Content-type", "application/yaml")
                    .withBody(pathFile
                            .getBytes(StandardCharsets.UTF_8))));

}
 
Example 19
Source File: BulkheadAutoConfigurationTest.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
/**
 * This test verifies that the combination of @FeignClient and @Bulkhead annotation works as
 * same as @Bulkhead alone works with any normal service class
 */
@Test
public void testFeignClient() throws InterruptedException {
    BulkheadEventsEndpointResponse eventsBefore = getBulkheadEvents("/actuator/bulkheadevents")
        .getBody();
    int expectedConcurrentCalls = 3;
    int expectedRejectedCalls = 2;
    int responseDelay = 1000;
    WireMock.stubFor(WireMock
        .get(WireMock.urlEqualTo("/sample/"))
        .willReturn(WireMock.aResponse().withStatus(200).withBody("This is successful call")
            .withFixedDelay(responseDelay))
    );

    ExecutorService es = Executors.newFixedThreadPool(5);
    List<CompletableFuture<Void>> futures = new ArrayList<>(5);
    for (int i = 0; i < 5; i++) {
        futures.add(runAsync(this::callService, es));
    }

    Thread.sleep(responseDelay + 100);
    int actualSuccessfulCalls =
        (int) futures.stream().filter(f -> f.isDone() && !f.isCompletedExceptionally()).count();
    int actualRejectedCalls = 0;

    List<BulkheadEventDTO> bulkheadEvents = getBulkheadEvents("/actuator/bulkheadevents")
        .getBody().getBulkheadEvents();
    bulkheadEvents = bulkheadEvents
        .subList(eventsBefore.getBulkheadEvents().size(), bulkheadEvents.size());
    for (BulkheadEventDTO eventDTO : bulkheadEvents) {
        if (eventDTO.getType().equals(BulkheadEvent.Type.CALL_REJECTED)) {
            actualRejectedCalls++;
        }
    }
    Bulkhead bulkhead = bulkheadRegistry.bulkhead("dummyFeignClient");

    assertThat(bulkhead).isNotNull();
    assertThat(bulkhead.getMetrics().getMaxAllowedConcurrentCalls()).isEqualTo(3);
    assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(3);
    assertThat(actualSuccessfulCalls).isEqualTo(expectedConcurrentCalls);
    assertThat(actualRejectedCalls).isEqualTo(expectedRejectedCalls);
}
 
Example 20
Source File: ParsecAsyncHttpClientProfilingTest.java    From parsec-libraries with Apache License 2.0 3 votes vote down vote up
@Test
public void nonCriticalGetShouldBeLogged() throws URISyntaxException, ExecutionException, InterruptedException {

    String url = "/get200Profiling";
    String headerStr = "nonCriticalGetHost";
    WireMock.stubFor(get(urlEqualTo(url))
            .willReturn(okJson(stubRespBodyJson)
                    .withHeader(ParsecClientDefine.HEADER_CONTENT_LENGTH,
                            String.valueOf(stubRespBodyJson.length()))
            ));


    Map<String, Collection<String>> headers = new HashMap<>();
    headers.put(ParsecClientDefine.HEADER_HOST, Arrays.asList(headerStr));


    String requestMethod = HttpMethod.GET;

    ParsecAsyncHttpRequest request =
            new ParsecAsyncHttpRequest.Builder()
                    .setUrl(wireMockBaseUrl + url)
                    .setHeaders(headers)
                    .setRequestTimeout(COMMON_REQUEST_TIME_OUT)
                    .setMethod(requestMethod)
                    .setBody(stubReqBodyJson).setBodyEncoding("UTF-8").build();

    Response response = parsecHttpClient.execute(request).get();

    assertThat(response.getStatus(), equalTo(200));


    //the log would look like below:
    //time=1541132036.456, req_url=http://localhost:59041/get200Profiling, req_host_header=criticalGetHost, req_method=GET, exec_info={"namelookup_time":8289,"connect_time":79202,"pretransfer_time":97919,"starttransfer_time":155815,"total_time":533641}, resp_code=200, src_url=, req_status=single, content_length=49, origin=,

    String patternAsStr = createPatternString(requestMethod, request.getUrl(), headerStr,
            String.valueOf(stubRespBodyJson.length()), 200, "single");

    then(mockAppender).should().doAppend(argThat(hasToString(matchesPattern(patternAsStr))));

}