com.github.tomakehurst.wiremock.http.Fault Java Examples

The following examples show how to use com.github.tomakehurst.wiremock.http.Fault. 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: StatusUpdaterTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_change_status_to_offline() {
    wireMock.stubFor(get("/health").willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));

    StepVerifier.create(eventStore)
                .expectSubscription()
                .then(() -> StepVerifier.create(updater.updateStatus(instance.getId())).verifyComplete())
                .assertNext(event -> assertThat(event).isInstanceOf(InstanceStatusChangedEvent.class))
                .thenCancel()
                .verify();

    StepVerifier.create(repository.find(instance.getId())).assertNext(app -> {
        assertThat(app.getStatusInfo().getStatus()).isEqualTo("OFFLINE");
        assertThat(app.getStatusInfo().getDetails()).containsKeys("message", "exception");
    }).verifyComplete();

    StepVerifier.create(updater.updateStatus(instance.getId())).verifyComplete();
}
 
Example #2
Source File: HttpSinkTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Test
public void testABeanProducingJsonObjectsWithFault() {
    stubFor(post(urlEqualTo("/items"))
            .willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER)));

    addConfig(new HttpConnectorConfig("http", "outgoing", "http://localhost:8089/items"));
    addClasses(BeanProducingJsonObjects.class, SourceBean.class);
    initialize();

    awaitForRequest(1);
    verify(1, postRequestedFor(urlEqualTo("/items")));

    bodies("/items").stream()
            .map(JsonObject::new)
            .forEach(json -> assertThat(json.getMap()).containsKey("value"));

    assertThat(bodies("/items").stream()
            .map(JsonObject::new)
            .map(j -> j.getInteger("value"))
            .collect(Collectors.toList())).containsExactlyInAnyOrder(1);
}
 
Example #3
Source File: NettyNioAsyncHttpClientSpiVerificationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void signalsErrorViaOnErrorAndFuture() throws InterruptedException, ExecutionException, TimeoutException {
    stubFor(any(urlEqualTo("/")).willReturn(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE)));

    CompletableFuture<Boolean> errorSignaled = new CompletableFuture<>();

    SdkAsyncHttpResponseHandler handler = new TestResponseHandler() {
        @Override
        public void onError(Throwable error) {
            errorSignaled.complete(true);
        }
    };

    SdkHttpRequest request = createRequest(URI.create("http://localhost:" + mockServer.port()));

    CompletableFuture<Void> executeFuture = client.execute(AsyncExecuteRequest.builder()
            .request(request)
            .responseHandler(handler)
            .requestContentPublisher(new EmptyPublisher())
            .build());

    assertThat(errorSignaled.get(1, TimeUnit.SECONDS)).isTrue();
    assertThatThrownBy(executeFuture::join).hasCauseInstanceOf(IOException.class);
}
 
Example #4
Source File: ProbeEndpointsStrategyTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_return_detect_endpoints() {
	// given
	Instance instance = Instance.create(InstanceId.of("id")).register(Registration
			.create("test", this.wireMock.url("/mgmt/health")).managementUrl(this.wireMock.url("/mgmt")).build());

	this.wireMock.stubFor(options(urlEqualTo("/mgmt/metrics")).willReturn(ok()));
	this.wireMock.stubFor(options(urlEqualTo("/mgmt/stats")).willReturn(ok()));
	this.wireMock.stubFor(options(urlEqualTo("/mgmt/info")).willReturn(ok()));
	this.wireMock.stubFor(options(urlEqualTo("/mgmt/non-exist")).willReturn(notFound()));
	this.wireMock.stubFor(options(urlEqualTo("/mgmt/error")).willReturn(serverError()));
	this.wireMock.stubFor(
			options(urlEqualTo("/mgmt/exception")).willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));

	ProbeEndpointsStrategy strategy = new ProbeEndpointsStrategy(this.instanceWebClient,
			new String[] { "metrics:stats", "metrics", "info", "non-exist", "error", "exception" });

	// when
	StepVerifier.create(strategy.detectEndpoints(instance))
			// then
			.expectNext(Endpoints.single("metrics", this.wireMock.url("/mgmt/stats")).withEndpoint("info",
					this.wireMock.url("/mgmt/info")))//
			.verifyComplete();
}
 
Example #5
Source File: QueryIndexEndpointStrategyTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_retry() {
	// given
	Instance instance = Instance.create(InstanceId.of("id")).register(Registration
			.create("test", this.wireMock.url("/mgmt/health")).managementUrl(this.wireMock.url("/mgmt")).build());

	String body = "{\"_links\":{\"metrics-requiredMetricName\":{\"templated\":true,\"href\":\"/mgmt/metrics/{requiredMetricName}\"},\"self\":{\"templated\":false,\"href\":\"/mgmt\"},\"metrics\":{\"templated\":false,\"href\":\"/mgmt/stats\"},\"info\":{\"templated\":false,\"href\":\"/mgmt/info\"}}}";

	this.wireMock.stubFor(get("/mgmt").inScenario("retry").whenScenarioStateIs(STARTED)
			.willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER)).willSetStateTo("recovered"));

	this.wireMock.stubFor(get("/mgmt").inScenario("retry").whenScenarioStateIs("recovered")
			.willReturn(ok(body).withHeader("Content-Type", ActuatorMediaType.V2_JSON)));

	QueryIndexEndpointStrategy strategy = new QueryIndexEndpointStrategy(this.instanceWebClient);

	// when
	StepVerifier.create(strategy.detectEndpoints(instance))
			// then
			.expectNext(Endpoints.single("metrics", "/mgmt/stats").withEndpoint("info", "/mgmt/info"))//
			.verifyComplete();
}
 
Example #6
Source File: StatusUpdaterTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_change_status_to_offline() {
	this.wireMock.stubFor(get("/health").willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));

	StepVerifier.create(this.eventStore).expectSubscription()
			.then(() -> StepVerifier.create(this.updater.updateStatus(this.instance.getId())).verifyComplete())
			.assertNext((event) -> assertThat(event).isInstanceOf(InstanceStatusChangedEvent.class)).thenCancel()
			.verify();

	StepVerifier.create(this.repository.find(this.instance.getId())).assertNext((app) -> {
		assertThat(app.getStatusInfo().getStatus()).isEqualTo("OFFLINE");
		assertThat(app.getStatusInfo().getDetails()).containsKeys("message", "exception");
	}).verifyComplete();

	StepVerifier.create(this.updater.updateStatus(this.instance.getId())).verifyComplete();
}
 
Example #7
Source File: RideRequestButtonControllerTest.java    From rides-android-sdk with MIT License 6 votes vote down vote up
@Test
public void testLoadInformation_whenPriceFails() throws Exception {
    stubTimeApi(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE));
    stubPriceApiSuccessful();

    controller.loadRideInformation(rideParameters);

    countDownLatch.await(3, TimeUnit.SECONDS);

    verify(callback, never()).onRideInformationLoaded();

    ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class);
    verify(callback).onError(errorCaptor.capture());
    assertThat(errorCaptor.getValue()).isNotNull();

    verify(view, never()).showEstimate(any(TimeEstimate.class));
    verify(view, never()).showEstimate(any(TimeEstimate.class), any(PriceEstimate.class));

    verify(view).showDefaultView();
}
 
Example #8
Source File: HttpClientTesting.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
private static void givenFaultyConnection(
    final WireMockServer wireMockServer,
    final String expectedRequestPath,
    final RequestType requestType,
    final Fault fault) {
  wireMockServer.stubFor(
      requestType
          .verifyPath(expectedRequestPath)
          .withHeader(HttpHeaders.ACCEPT, equalTo(CONTENT_TYPE_JSON))
          .willReturn(
              aResponse()
                  .withFault(fault)
                  .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR)
                  .withHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_JSON)
                  .withBody("a simulated error occurred")));
}
 
Example #9
Source File: HttpClientTesting.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
private static <T> void testFaultHandling(
    final WireMockServer wireMockServer,
    final String expectedRequestPath,
    final RequestType requestType,
    final Function<URI, T> serviceCall,
    final Fault fault) {
  givenFaultyConnection(wireMockServer, expectedRequestPath, requestType, fault);
  final URI hostUri = configureWireMock(wireMockServer);

  assertThrows(FeignException.class, () -> serviceCall.apply(hostUri));
}
 
Example #10
Source File: RetryTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * Test if the download task can retry infinitely
 * @throws Exception if anything else goes wrong
 */
@Test
public void inifinite() throws Exception {
    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(STARTED)
            .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))
            .willSetStateTo(TWO));

    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(TWO)
            .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))
            .willSetStateTo(THREE));

    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(THREE)
            .willReturn(aResponse().withBody(CONTENTS)));

    Download t = makeProjectAndTask();
    t.retries(-1);
    assertEquals(-1, t.getRetries());
    t.src(wireMockRule.url(TEST_FILE_NAME));
    File dst = folder.newFile();
    t.dest(dst);
    t.execute();

    String dstContents = FileUtils.readFileToString(dst);
    assertEquals(CONTENTS, dstContents);

    wireMockRule.verify(3, getRequestedFor(urlEqualTo("/" + TEST_FILE_NAME)));
}
 
Example #11
Source File: RetryTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * Test if the download task can retry up to three times
 * @throws Exception if anything else goes wrong
 */
@Test
public void retryUpToThree() throws Exception {
    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(STARTED)
            .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))
            .willSetStateTo(TWO));

    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(TWO)
            .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))
            .willSetStateTo(THREE));

    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(THREE)
            .willReturn(aResponse().withBody(CONTENTS)));

    Download t = makeProjectAndTask();
    t.retries(3);
    assertEquals(3, t.getRetries());
    t.src(wireMockRule.url(TEST_FILE_NAME));
    File dst = folder.newFile();
    t.dest(dst);
    t.execute();

    String dstContents = FileUtils.readFileToString(dst);
    assertEquals(CONTENTS, dstContents);

    wireMockRule.verify(3, getRequestedFor(urlEqualTo("/" + TEST_FILE_NAME)));
}
 
Example #12
Source File: RetryTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * Test if the download task can retry three times
 * @throws Exception if anything else goes wrong
 */
@Test
public void retryThree() throws Exception {
    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(STARTED)
            .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))
            .willSetStateTo(TWO));

    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(TWO)
            .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))
            .willSetStateTo(THREE));

    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(THREE)
            .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))
            .willSetStateTo(FOUR));

    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(FOUR)
            .willReturn(aResponse().withBody(CONTENTS)));

    Download t = makeProjectAndTask();
    t.retries(3);
    assertEquals(3, t.getRetries());
    t.src(wireMockRule.url(TEST_FILE_NAME));
    File dst = folder.newFile();
    t.dest(dst);
    t.execute();

    String dstContents = FileUtils.readFileToString(dst);
    assertEquals(CONTENTS, dstContents);

    wireMockRule.verify(4, getRequestedFor(urlEqualTo("/" + TEST_FILE_NAME)));
}
 
Example #13
Source File: RetryTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * Test if the download task can retry once
 * @throws Exception if anything else goes wrong
 */
@Test
public void retryOnce() throws Exception {
    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(STARTED)
            .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))
            .willSetStateTo(TWO));

    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(TWO)
            .willReturn(aResponse().withBody(CONTENTS)));

    Download t = makeProjectAndTask();
    t.retries(1);
    assertEquals(1, t.getRetries());
    t.src(wireMockRule.url(TEST_FILE_NAME));
    File dst = folder.newFile();
    t.dest(dst);
    t.execute();

    String dstContents = FileUtils.readFileToString(dst);
    assertEquals(CONTENTS, dstContents);

    wireMockRule.verify(2, getRequestedFor(urlEqualTo("/" + TEST_FILE_NAME)));
}
 
Example #14
Source File: RetryTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * Test if the download task does not retry requests by default
 * @throws Exception if anything else goes wrong
 */
@Test
public void retryDefault() throws Exception {
    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(STARTED)
            .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))
            .willSetStateTo(TWO));

    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(TWO)
            .willReturn(aResponse().withBody(CONTENTS)));

    Download t = makeProjectAndTask();
    assertEquals(0, t.getRetries());
    t.src(wireMockRule.url(TEST_FILE_NAME));
    File dst = folder.newFile();
    t.dest(dst);
    try {
        t.execute();
        fail("Request should have failed");
    } catch (TaskExecutionException e) {
        wireMockRule.verify(1, getRequestedFor(urlEqualTo("/" + TEST_FILE_NAME)));
        assertTrue(e.getCause() instanceof UncheckedIOException);
        assertTrue(e.getCause().getCause() instanceof NoHttpResponseException);
    }
}
 
Example #15
Source File: QueryIndexEndpointStrategyTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_return_empty_on_error() {
	// given
	Instance instance = Instance.create(InstanceId.of("id")).register(Registration
			.create("test", this.wireMock.url("/mgmt/health")).managementUrl(this.wireMock.url("/mgmt")).build());

	this.wireMock.stubFor(get("/mgmt").willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));

	QueryIndexEndpointStrategy strategy = new QueryIndexEndpointStrategy(this.instanceWebClient);

	// when
	StepVerifier.create(strategy.detectEndpoints(instance))
			// then
			.verifyComplete();
}
 
Example #16
Source File: AbstractInstancesProxyControllerIntegrationTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
private void stubForInstance(String managementPath) {
	String managementUrl = this.wireMock.url(managementPath);

	//@formatter:off
	String actuatorIndex = "{ \"_links\": { " +
						"\"env\": { \"href\": \"" + managementUrl + "/env\", \"templated\": false }," +
						"\"test\": { \"href\": \"" + managementUrl + "/test\", \"templated\": false }," +
						"\"post\": { \"href\": \"" + managementUrl + "/post\", \"templated\": false }," +
						"\"delete\": { \"href\": \"" + managementUrl + "/delete\", \"templated\": false }," +
						"\"invalid\": { \"href\": \"" + managementUrl + "/invalid\", \"templated\": false }," +
						"\"timeout\": { \"href\": \"" + managementUrl + "/timeout\", \"templated\": false }" +
						" } }";
	//@formatter:on
	this.wireMock.stubFor(get(urlEqualTo(managementPath + "/health"))
			.willReturn(ok("{ \"status\" : \"UP\" }").withHeader(CONTENT_TYPE, ActuatorMediaType.V2_JSON)));
	this.wireMock.stubFor(get(urlEqualTo(managementPath + "/info"))
			.willReturn(ok("{ }").withHeader(CONTENT_TYPE, ACTUATOR_CONTENT_TYPE)));
	this.wireMock.stubFor(options(urlEqualTo(managementPath + "/env")).willReturn(
			ok().withHeader(ALLOW, HttpMethod.HEAD.name(), HttpMethod.GET.name(), HttpMethod.OPTIONS.name())));
	this.wireMock.stubFor(get(urlEqualTo(managementPath + ""))
			.willReturn(ok(actuatorIndex).withHeader(CONTENT_TYPE, ACTUATOR_CONTENT_TYPE)));
	this.wireMock.stubFor(
			get(urlEqualTo(managementPath + "/invalid")).willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));
	this.wireMock.stubFor(get(urlEqualTo(managementPath + "/timeout")).willReturn(ok().withFixedDelay(10000)));
	this.wireMock.stubFor(get(urlEqualTo(managementPath + "/test"))
			.willReturn(ok("{ \"foo\" : \"bar\" }").withHeader(CONTENT_TYPE, ACTUATOR_CONTENT_TYPE)));
	this.wireMock.stubFor(get(urlEqualTo(managementPath + "/test/has%20spaces"))
			.willReturn(ok("{ \"foo\" : \"bar-with-spaces\" }").withHeader(CONTENT_TYPE, ACTUATOR_CONTENT_TYPE)));
	this.wireMock.stubFor(post(urlEqualTo(managementPath + "/post")).willReturn(ok()));
	this.wireMock.stubFor(delete(urlEqualTo(managementPath + "/delete")).willReturn(serverError()
			.withBody("{\"error\": \"You're doing it wrong!\"}").withHeader(CONTENT_TYPE, ACTUATOR_CONTENT_TYPE)));
}
 
Example #17
Source File: SimpleRoadClientTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Test(expected = OnrampException.class)
public void ioError() throws Exception {
  stubFor(post(urlEqualTo("/onramp/v1/roads/" + TEST_ROAD + "/messages"))
      .willReturn(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE)));
  SimpleModel messageModel = new SimpleModel();
  messageModel.setId(1L);
  messageModel.setStr("test message");
  underTest.sendMessage(messageModel);
}
 
Example #18
Source File: HttpClientTesting.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/** Verifies http client behavior when communication problems happen. */
private static <T> void faultCases(
    final WireMockServer wireMockServer,
    final String expectedRequestPath,
    final RequestType requestType,
    final Function<URI, T> serviceCall) {
  List.of(
          // caution, one of the wiremock faults is known to cause a hang in windows, so to avoid
          // that problem do not use the full available list of of wiremock faults
          Fault.EMPTY_RESPONSE, Fault.RANDOM_DATA_THEN_CLOSE)
      .forEach(
          fault ->
              testFaultHandling(
                  wireMockServer, expectedRequestPath, requestType, serviceCall, fault));
}
 
Example #19
Source File: WiremockServerApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void malformed() throws Exception {
	wiremock.stubFor(get(urlEqualTo("/resource"))
			.willReturn(aResponse().withFault(Fault.MALFORMED_RESPONSE_CHUNK)));
	// It's a different exception type than Jetty, but it's in the right ballpark

	assertThatThrownBy(() -> this.service.go()).hasCauseInstanceOf(IOException.class);
}
 
Example #20
Source File: WiremockServerApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyResponse() throws Exception {
	wiremock.stubFor(get(urlEqualTo("/resource"))
			.willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));

	assertThatThrownBy(() -> this.service.go()).hasCauseInstanceOf(NoHttpResponseException.class);
}
 
Example #21
Source File: WiremockServerApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void randomData() throws Exception {
	wiremock.stubFor(get(urlEqualTo("/resource"))
			.willReturn(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE)));

	assertThatThrownBy(() -> this.service.go()).hasCauseInstanceOf(ClientProtocolException.class);
}
 
Example #22
Source File: WiremockServerApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void malformed() throws Exception {
	wiremock.stubFor(get(urlEqualTo("/resource"))
			.willReturn(aResponse().withFault(Fault.MALFORMED_RESPONSE_CHUNK)));

	assertThatThrownBy(() -> this.service.go()).hasCauseInstanceOf(ClientProtocolException.class);
}
 
Example #23
Source File: WiremockServerApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyResponse() throws Exception {
	wiremock.stubFor(get(urlEqualTo("/resource"))
			.willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));

	assertThatThrownBy(() -> this.service.go()).hasCauseInstanceOf(NoHttpResponseException.class);
}
 
Example #24
Source File: WiremockServerApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void randomData() throws Exception {
	wiremock.stubFor(get(urlEqualTo("/resource"))
			.willReturn(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE)));

	assertThatThrownBy(() -> this.service.go()).hasCauseInstanceOf(ClientProtocolException.class);
}
 
Example #25
Source File: NettyNioAsyncHttpClientWireMockTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void connectionInactive_shouldReleaseChannel() throws Exception {

    ChannelFactory channelFactory = mock(ChannelFactory.class);
    EventLoopGroup customEventLoopGroup = new NioEventLoopGroup(1);
    NioSocketChannel channel = new NioSocketChannel();

    when(channelFactory.newChannel()).thenAnswer((Answer<NioSocketChannel>) invocationOnMock -> channel);
    SdkEventLoopGroup eventLoopGroup = SdkEventLoopGroup.create(customEventLoopGroup, channelFactory);

    NettyNioAsyncHttpClient customClient =
        (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder()
                                                         .eventLoopGroup(eventLoopGroup)
                                                         .maxConcurrency(1)
                                                         .build();


    String body = randomAlphabetic(10);
    URI uri = URI.create("http://localhost:" + mockServer.port());
    SdkHttpRequest request = createRequest(uri);
    RecordingResponseHandler recorder = new RecordingResponseHandler();


    stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withBody(body)
                                                           .withStatus(500)
                                                           .withFault(Fault.RANDOM_DATA_THEN_CLOSE)));

    customClient.execute(AsyncExecuteRequest.builder()
                                            .request(request)
                                            .requestContentPublisher(createProvider(""))
                                            .responseHandler(recorder).build());

    verifyChannelRelease(channel);
    assertThat(channel.isShutdown()).isTrue();

    customClient.close();
    eventLoopGroup.eventLoopGroup().shutdownGracefully().awaitUninterruptibly();
}
 
Example #26
Source File: SimpleRoadClientTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Test(expected = OnrampException.class)
public void anotherIOError() throws Exception {
  stubFor(post(urlEqualTo("/onramp/v1/roads/" + TEST_ROAD + "/messages"))
      .willReturn(aResponse().withFault(Fault.MALFORMED_RESPONSE_CHUNK)));
  SimpleModel messageModel = new SimpleModel();
  messageModel.setId(1L);
  messageModel.setStr("test message");
  underTest.sendMessage(messageModel);
}
 
Example #27
Source File: RideRequestButtonControllerTest.java    From rides-android-sdk with MIT License 4 votes vote down vote up
@Test
public void testLoadInformation_whenTimeFails() throws Exception {
    stubTimeApiSuccessful();
    stubPriceApi(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE));

    controller.loadRideInformation(rideParameters);

    countDownLatch.await(3, TimeUnit.SECONDS);

    verify(callback, never()).onRideInformationLoaded();

    ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class);
    verify(callback).onError(errorCaptor.capture());

    assertThat(errorCaptor.getValue()).isNotNull();

    verify(view, never()).showEstimate(any(TimeEstimate.class));
    verify(view, never()).showEstimate(any(TimeEstimate.class), any(PriceEstimate.class));

    verify(view).showDefaultView();
}
 
Example #28
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 #29
Source File: AbstractInstancesProxyControllerIntegrationTest.java    From Moss with Apache License 2.0 4 votes vote down vote up
public void setUpClient(ConfigurableApplicationContext context) {
    int localPort = context.getEnvironment().getProperty("local.server.port", Integer.class, 0);
    client = WebTestClient.bindToServer()
                          .baseUrl("http://localhost:" + localPort)
                          .responseTimeout(Duration.ofSeconds(10))
                          .build();

    String managementUrl = "http://localhost:" + wireMock.port() + "/mgmt";
    //@formatter:off
    String actuatorIndex = "{ \"_links\": { " +
                           "\"env\": { \"href\": \"" + managementUrl + "/env\", \"templated\": false }," +
                           "\"test\": { \"href\": \"" + managementUrl + "/test\", \"templated\": false }," +
                           "\"invalid\": { \"href\": \"" + managementUrl + "/invalid\", \"templated\": false }," +
                           "\"timeout\": { \"href\": \"" + managementUrl + "/timeout\", \"templated\": false }" +
                           " } }";
    //@formatter:on
    wireMock.stubFor(get(urlEqualTo("/mgmt/health")).willReturn(ok("{ \"status\" : \"UP\" }").withHeader(CONTENT_TYPE,
        ActuatorMediaType.V2_JSON
    )));
    wireMock.stubFor(get(urlEqualTo("/mgmt/info")).willReturn(ok("{ }").withHeader(CONTENT_TYPE,
        ACTUATOR_CONTENT_TYPE
    )));
    wireMock.stubFor(options(urlEqualTo("/mgmt/env")).willReturn(ok().withHeader(ALLOW,
        HttpMethod.HEAD.name(),
        HttpMethod.GET.name(),
        HttpMethod.OPTIONS.name()
    )));
    wireMock.stubFor(get(urlEqualTo("/mgmt")).willReturn(ok(actuatorIndex).withHeader(CONTENT_TYPE,
        ACTUATOR_CONTENT_TYPE
    )));
    wireMock.stubFor(get(urlEqualTo("/mgmt/invalid")).willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));
    wireMock.stubFor(get(urlEqualTo("/mgmt/timeout")).willReturn(ok().withFixedDelay(10000)));
    wireMock.stubFor(get(urlEqualTo("/mgmt/test")).willReturn(ok("{ \"foo\" : \"bar\" }").withHeader(CONTENT_TYPE,
        ACTUATOR_CONTENT_TYPE
    )));
    wireMock.stubFor(get(urlEqualTo("/mgmt/test/has%20spaces")).willReturn(ok("{ \"foo\" : \"bar-with-spaces\" }").withHeader(CONTENT_TYPE,
        ACTUATOR_CONTENT_TYPE
    )));
    wireMock.stubFor(post(urlEqualTo("/mgmt/test")).willReturn(ok()));
    wireMock.stubFor(delete(urlEqualTo("/mgmt/test")).willReturn(serverError().withBody(
        "{\"error\": \"You're doing it wrong!\"}").withHeader(CONTENT_TYPE, ACTUATOR_CONTENT_TYPE)));

    instanceId = registerInstance(managementUrl);
}
 
Example #30
Source File: RetryTest.java    From gradle-download-task with Apache License 2.0 4 votes vote down vote up
/**
 * Test if the download task can retry two times and the fails
 * @throws Exception if anything else goes wrong
 */
@Test
public void retryTwo() throws Exception {
    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(STARTED)
            .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))
            .willSetStateTo(TWO));

    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(TWO)
            .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))
            .willSetStateTo(THREE));

    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(THREE)
            .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))
            .willSetStateTo(FOUR));

    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .inScenario(SCENARIO)
            .whenScenarioStateIs(FOUR)
            .willReturn(aResponse().withBody(CONTENTS)));

    Download t = makeProjectAndTask();
    t.retries(2);
    assertEquals(2, t.getRetries());
    t.src(wireMockRule.url(TEST_FILE_NAME));
    File dst = folder.newFile();
    t.dest(dst);
    try {
        t.execute();
        fail("Request should have failed");
    } catch (TaskExecutionException e) {
        wireMockRule.verify(3, getRequestedFor(urlEqualTo("/" + TEST_FILE_NAME)));
        assertTrue(e.getCause() instanceof UncheckedIOException);
        assertTrue(e.getCause().getCause() instanceof NoHttpResponseException);
    }
}