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

The following examples show how to use com.github.tomakehurst.wiremock.http.Response. 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: WireMockBase.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
    // if gzipped, ungzip they body and discard the Content-Encoding header
    if (response.getHeaders().getHeader("Content-Encoding").containsValue("gzip")) {
        Iterable<HttpHeader> headers = Iterables.filter(
            response.getHeaders().all(),
            (HttpHeader header) -> header != null && !header.keyEquals("Content-Encoding") && !header.containsValue("gzip")
        );
        return Response.Builder.like(response)
            .but()
            .body(Gzip.unGzip(response.getBody()))
            .headers(new HttpHeaders(headers))
            .build();
    }
    return response;
}
 
Example #2
Source File: WebhooksAcceptanceTest.java    From wiremock-webhooks-extension with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    targetServer.addMockServiceRequestListener(new RequestListener() {
        @Override
        public void requestReceived(Request request, Response response) {
            if (request.getUrl().startsWith("/callback")) {
                latch.countDown();
            }
        }
    });
    reset();
    notifier.reset();
    targetServer.stubFor(any(anyUrl())
        .willReturn(aResponse().withStatus(200)));
    latch = new CountDownLatch(1);
    client = new WireMockTestClient(rule.port());
    WireMock.configureFor(targetServer.port());

    System.out.println("Target server port: " + targetServer.port());
    System.out.println("Under test server port: " + rule.port());
}
 
Example #3
Source File: FailingWebhookTest.java    From wiremock-webhooks-extension with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
  targetServer.addMockServiceRequestListener(new RequestListener() {
    @Override
    public void requestReceived(Request request, Response response) {
      if (request.getUrl().startsWith("/callback")) {
        latch.countDown();
      }
    }
  });
  reset();
  notifier.reset();
  targetServer.stubFor(any(anyUrl())
      .willReturn(aResponse().withStatus(200)));
  latch = new CountDownLatch(1);
  client = new WireMockTestClient(rule.port());
  WireMock.configureFor(targetServer.port());
}
 
Example #4
Source File: AbstractGitHubWireMockTest.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@Override
public Response transform(Request request, Response response, FileSource files,
                          Parameters parameters) {
    if ("application/json"
        .equals(response.getHeaders().getContentTypeHeader().mimeTypePart())) {
        return Response.Builder.like(response)
            .but()
            .body(response.getBodyAsString()
                .replace("https://api.github.com/",
                    "http://localhost:" + githubApi.port() + "/")
                .replace("https://raw.githubusercontent.com/",
                    "http://localhost:" + githubRaw.port() + "/")
            )
            .build();
    }
    return response;
}
 
Example #5
Source File: BoxDeveloperEditionAPIConnectionTest.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
private void mockListener() {
    this.wireMockRule.addMockServiceRequestListener(new RequestListener() {
        @Override
        public void requestReceived(Request request, Response response) {
            try {
                JwtClaims claims = BoxDeveloperEditionAPIConnectionTest.this
                    .getClaimsFromRequest(request);

                if (BoxDeveloperEditionAPIConnectionTest.this.jtiClaim == null) {
                    BoxDeveloperEditionAPIConnectionTest.this.jtiClaim = claims.getJwtId();
                }
            } catch (Exception ex) {
                Assert.fail("Could not save JTI claim from request");
            }
        }
    });
}
 
Example #6
Source File: RedirectTest.java    From gradle-download-task with Apache License 2.0 6 votes vote down vote up
@Override
public Response transform(Request request, Response response,
        FileSource files, Parameters parameters) {
    if (redirects == null) {
        redirects = parameters.getInt("redirects");
    }
    String nl;
    if (redirects > 1) {
        redirects--;
        nl = "/" + REDIRECT + "?r=" + redirects;
    } else {
        nl = "/" + TEST_FILE_NAME;
    }
    return Response.Builder.like(response)
            .but().headers(response.getHeaders()
                    .plus(new HttpHeader("Location", nl)))
            .build();
}
 
Example #7
Source File: AbstractInstancesProxyControllerIntegrationTest.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Override
public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
    return Response.Builder.like(response)
                           .headers(HttpHeaders.copyOf(response.getHeaders())
                                               .plus(new HttpHeader("Connection", "Close")))
                           .build();
}
 
Example #8
Source File: WiremockResponseConverter.java    From styx with Apache License 2.0 5 votes vote down vote up
static HttpResponse toStyxResponse(Response response) {
    HttpHeaders headers = toStyxHeaders(response.getHeaders());
    byte[] body = response.getBody();

    return HttpResponse.response(statusWithCode(response.getStatus()))
            .headers(headers)
            .body(body, false)
            .build();
}
 
Example #9
Source File: WiremockResponseConverterTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void convertsCreatedResponse() {
    ResponseDefinition created = ResponseDefinition.created();
    Response render = new BasicResponseRenderer().render(created);

    HttpResponse styxResponse = toStyxResponse(render);

    assertThat(styxResponse.status(), is(CREATED));
    assertThat(styxResponse.bodyAs(UTF_8), is(""));
    assertThat(headerCount(styxResponse.headers()), is(0));
}
 
Example #10
Source File: GithubMockBase.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public Response transform(Request request, Response response, FileSource files,
                          Parameters parameters) {
    if ("application/json"
            .equals(response.getHeaders().getContentTypeHeader().mimeTypePart())) {
        return Response.Builder.like(response)
                .but()
                .body(response.getBodyAsString()
                        .replace("https://api.github.com/",
                                "http://localhost:" + githubApi.port() + "/")
                )
                .build();
    }
    return response;
}
 
Example #11
Source File: WireMockBase.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
    if ("application/json"
        .equals(response.getHeaders().getContentTypeHeader().mimeTypePart())) {
        return Response.Builder.like(response)
            .but()
            .body(response.getBodyAsString().replace(sourceUrl, getServerUrl(rule)))
            .build();
    }
    return response;
}
 
Example #12
Source File: EventStreamTest.java    From box-java-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@Category(UnitTest.class)
public void canStopStreamWhileWaitingForAPIResponse() throws InterruptedException {
    final long streamPosition = 123456;
    final String realtimeServerURL = "/realtimeServer?channel=0";

    stubFor(options(urlEqualTo("/events"))
        .willReturn(aResponse()
            .withHeader("Content-Type", "application/json")
            .withBody("{ \"entries\": [ { \"url\": \"http://localhost:53620" + realtimeServerURL + "\", "
                + "\"max_retries\": \"3\", \"retry_timeout\": 60000 } ] }")));

    stubFor(get(urlPathMatching("/events"))
        .withQueryParam("stream_position", WireMock.equalTo("now"))
        .willReturn(aResponse()
            .withHeader("Content-Type", "application/json")
            .withBody("{ \"next_stream_position\": " + streamPosition + ",\"entries\":[] }")));

    stubFor(get(urlMatching("/realtimeServer.*"))
            .willReturn(aResponse()
                    .withHeader("Content-Type", "application/json")
                    .withBody("{ \"message\": \"new_change\" }")));

    BoxAPIConnection api = new BoxAPIConnection("");
    api.setBaseURL("http://localhost:53620/");

    final EventStream stream = new EventStream(api);
    final Object requestLock = new Object();
    this.wireMockRule.addMockServiceRequestListener(new RequestListener() {
        @Override
        public void requestReceived(Request request, Response response) {
            String streamPositionURL = realtimeServerURL + "&stream_position=" + streamPosition;
            boolean requestUrlMatch = request.getUrl().contains(streamPositionURL);
            if (requestUrlMatch) {
                stream.stop();

                synchronized (requestLock) {
                    requestLock.notify();
                }
            }
        }
    });

    stream.start();
    synchronized (requestLock) {
        requestLock.wait();
    }

    assertThat(stream.isStarted(), is(false));
}
 
Example #13
Source File: EventStreamTest.java    From box-java-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@Category(UnitTest.class)
public void duplicateEventsAreNotReported() throws InterruptedException {
    final String realtimeServerURL = "/realtimeServer?channel=0";

    stubFor(options(urlEqualTo("/events"))
        .willReturn(aResponse()
            .withHeader("Content-Type", "application/json")
            .withBody("{ \"entries\": [ { \"url\": \"http://localhost:53620" + realtimeServerURL + "\", "
                + "\"max_retries\": \"3\", \"retry_timeout\": 60000 } ] }")));

    stubFor(get(urlMatching("/events\\?.*stream_position=now.*"))
        .willReturn(aResponse()
            .withHeader("Content-Type", "application/json")
            .withBody("{ \"next_stream_position\": 0 }")));

    stubFor(get(urlMatching("/realtimeServer.*"))
        .willReturn(aResponse()
            .withHeader("Content-Type", "application/json")
            .withBody("{ \"message\": \"new_change\" }")));

    stubFor(get(urlMatching("/events\\?.*stream_position=0"))
        .willReturn(aResponse()
            .withHeader("Content-Type", "application/json")
            .withBody("{ \"next_stream_position\": 1, \"entries\": [ { \"type\": \"event\", "
                + "\"event_id\": \"1\" } ] }")));

    stubFor(get(urlMatching("/events\\?.*stream_position=1"))
        .willReturn(aResponse()
            .withHeader("Content-Type", "application/json")
            .withBody("{ \"next_stream_position\": -1, \"entries\": [ { \"type\": \"event\", "
                + "\"event_id\": \"1\" } ] }")));

    BoxAPIConnection api = new BoxAPIConnection("");
    api.setBaseURL("http://localhost:53620/");

    final EventStream stream = new EventStream(api);
    final EventListener eventListener = mock(EventListener.class);
    stream.addListener(eventListener);

    final Object requestLock = new Object();
    this.wireMockRule.addMockServiceRequestListener(new RequestListener() {
        @Override
        public void requestReceived(Request request, Response response) {
            boolean requestUrlMatch = request.getUrl().contains("-1");
            if (requestUrlMatch) {
                synchronized (requestLock) {
                    requestLock.notify();
                }
            }
        }
    });

    stream.start();
    synchronized (requestLock) {
        requestLock.wait();
    }

    verify(eventListener).onEvent(any(BoxEvent.class));
}
 
Example #14
Source File: EventStreamTest.java    From box-java-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@Category(UnitTest.class)
public void delayBetweenCalls() throws InterruptedException {

    final String realtimeServerURL = "/realtimeServer?channel=0";
    final int delay = 2000;
    final long[] times = new long[2];

    stubFor(options(urlEqualTo("/events"))
            .willReturn(aResponse()
                    .withHeader("Content-Type", "application/json")
                    .withBody("{ \"entries\": [ { \"url\": \"http://localhost:53620" + realtimeServerURL + "\", "
                            + "\"max_retries\": \"3\", \"retry_timeout\": 60000 } ] }")));

    stubFor(get(urlMatching("/events\\?.*stream_position=now.*"))
            .willReturn(aResponse()
                    .withHeader("Content-Type", "application/json")
                    .withBody("{ \"next_stream_position\": 123 }")));

    stubFor(get(urlMatching("/realtimeServer.*"))
            .willReturn(aResponse()
                    .withHeader("Content-Type", "application/json")
                    .withBody("{ \"message\": \"new_change\" }")));

    stubFor(get(urlMatching("/events\\?.*stream_position=123"))
            .willReturn(aResponse()
                    .withHeader("Content-Type", "application/json")
                    .withBody("{ \"next_stream_position\": 456, \"entries\": [ { \"type\": \"event\", "
                            + "\"event_id\": \"1\" } ] }")));

    stubFor(get(urlMatching("/events\\?.*stream_position=456"))
            .willReturn(aResponse()
                    .withHeader("Content-Type", "application/json")
                    .withBody("{ \"next_stream_position\": 789, \"entries\": [ { \"type\": \"event\", "
                            + "\"event_id\": \"1\" } ] }")));

    BoxAPIConnection api = new BoxAPIConnection("");
    api.setBaseURL("http://localhost:53620/");

    final EventStream stream = new EventStream(api, -1, delay);
    final EventListener eventListener = mock(EventListener.class);
    stream.addListener(eventListener);

    final Object requestLock = new Object();
    this.wireMockRule.addMockServiceRequestListener(new RequestListener() {
        @Override
        public void requestReceived(Request request, Response response) {
            boolean firstCall = request.getUrl().contains("stream_position=123");
            boolean secondCall = request.getUrl().contains("stream_position=456");
            boolean lastCall = request.getUrl().contains("stream_position=789");
            if (firstCall) {
                times[0] = System.currentTimeMillis();
            }
            if (secondCall) {
                times[1] = System.currentTimeMillis();
            }
            if (lastCall) {
                synchronized (requestLock) {
                    requestLock.notify();
                }
            }
        }
    });

    stream.start();
    synchronized (requestLock) {
        requestLock.wait();
    }

    Assert.assertTrue("Calls should be be 2s apart", times[1] - times[0] >= delay);
}
 
Example #15
Source File: ConnectionCloseExtension.java    From spring-boot-admin with Apache License 2.0 4 votes vote down vote up
@Override
public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
	return Response.Builder.like(response)
			.headers(HttpHeaders.copyOf(response.getHeaders()).plus(new HttpHeader("Connection", "Close"))).build();
}