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

The following examples show how to use com.github.tomakehurst.wiremock.WireMockServer#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: MicrometerHttpRequestExecutorTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void httpStatusCodeIsTagged(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    server.stubFor(any(urlEqualTo("/ok")).willReturn(aResponse().withStatus(200)));
    server.stubFor(any(urlEqualTo("/notfound")).willReturn(aResponse().withStatus(404)));
    server.stubFor(any(urlEqualTo("/error")).willReturn(aResponse().withStatus(500)));
    HttpClient client = client(executor(false));
    EntityUtils.consume(client.execute(new HttpGet(server.baseUrl() + "/ok")).getEntity());
    EntityUtils.consume(client.execute(new HttpGet(server.baseUrl() + "/ok")).getEntity());
    EntityUtils.consume(client.execute(new HttpGet(server.baseUrl() + "/notfound")).getEntity());
    EntityUtils.consume(client.execute(new HttpGet(server.baseUrl() + "/error")).getEntity());
    assertThat(registry.get(EXPECTED_METER_NAME)
            .tags("method", "GET", "status", "200")
            .timer().count()).isEqualTo(2L);
    assertThat(registry.get(EXPECTED_METER_NAME)
            .tags("method", "GET", "status", "404")
            .timer().count()).isEqualTo(1L);
    assertThat(registry.get(EXPECTED_METER_NAME)
            .tags("method", "GET", "status", "500")
            .timer().count()).isEqualTo(1L);
}
 
Example 2
Source File: OkHttpMetricsEventListenerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void hostTagCanBeDisabled(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    server.stubFor(any(anyUrl()));
    OkHttpClient client = new OkHttpClient.Builder()
            .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests")
                    .includeHostTag(false)
                    .build())
            .build();
    Request request = new Request.Builder()
            .url(server.baseUrl())
            .build();

    client.newCall(request).execute().close();

    assertThat(registry.get("okhttp.requests")
            .tags("status", "200",
                    "target.host", "localhost",
                    "target.port", String.valueOf(server.port()),
                    "target.scheme", "http")
            .timer().getId().getTags()).doesNotContain(Tag.of("host", "localhost"));
}
 
Example 3
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 4
Source File: MicrometerHttpRequestExecutorTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void routeNotTaggedByDefault(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    server.stubFor(any(anyUrl()));
    HttpClient client = client(executor(false));
    EntityUtils.consume(client.execute(new HttpGet(server.baseUrl())).getEntity());
    List<String> tagKeys = registry.get(EXPECTED_METER_NAME)
            .timer().getId().getTags().stream()
            .map(Tag::getKey)
            .collect(Collectors.toList());
    assertThat(tagKeys).doesNotContain("target.scheme", "target.host", "target.port");
    assertThat(tagKeys).contains("status", "method");
}
 
Example 5
Source File: HttpSenderCompatibilityKit.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@DisplayName("successfully send a request with a body and receive a response with a body")
@EnumSource(value = HttpSender.Method.class, names = {"POST", "PUT"})
void successfulRequestSentWithBody(HttpSender.Method method, @WiremockResolver.Wiremock WireMockServer server) throws Throwable {
    server.stubFor(any(urlEqualTo("/metrics"))
            .willReturn(ok("a body")));

    HttpSender.Response response = httpSender.newRequest(server.baseUrl() + "/metrics")
            .withMethod(method)
            .accept("customAccept")
            .withContent("custom/type", "this is a line")
            .send();

    assertThat(response.code()).isEqualTo(200);
    assertThat(response.body()).isEqualTo("a body");

    server.verify(WireMock.requestMadeFor(request ->
            MatchResult.aggregate(
                    MatchResult.of(request.getMethod().getName().equals(method.name())),
                    MatchResult.of(request.getUrl().equals("/metrics"))
            ))
            .withHeader("Accept", equalTo("customAccept"))
            .withHeader("Content-Type", containing("custom/type")) // charset may be added to the type
            .withRequestBody(equalTo("this is a line")));
}
 
Example 6
Source File: LobbyWatcherClientTest.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
@Test
void sendPlayerJoinedNotification(
    @WiremockResolver.Wiremock final WireMockServer wireMockServer) {
  wireMockServer.stubFor(
      post(LobbyWatcherClient.PLAYER_JOINED_PATH)
          .withRequestBody(
              equalToJson(
                  toJson(
                      PlayerJoinedNotification.builder()
                          .gameId("game-id")
                          .playerName("player-joined")
                          .build())))
          .willReturn(WireMock.aResponse().withStatus(200)));

  newClient(wireMockServer).playerJoined("game-id", UserName.of("player-joined"));
}
 
Example 7
Source File: LobbyWatcherClientTest.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
@Test
void postGame(@WiremockResolver.Wiremock final WireMockServer server) {
  server.stubFor(
      post(LobbyWatcherClient.POST_GAME_PATH)
          .withHeader(AuthenticationHeaders.API_KEY_HEADER, equalTo(EXPECTED_API_KEY))
          .withRequestBody(equalToJson(toJson(GAME_POSTING_REQUEST)))
          .willReturn(
              WireMock.aResponse()
                  .withStatus(200)
                  .withBody(
                      toJson(
                          GamePostingResponse.builder()
                              .gameId(GAME_ID)
                              .connectivityCheckSucceeded(true)
                              .build()))));

  final GamePostingResponse response = newClient(server).postGame(GAME_POSTING_REQUEST);

  assertThat(response.getGameId(), is(GAME_ID));
  assertThat(response.isConnectivityCheckSucceeded(), is(true));
}
 
Example 8
Source File: OkHttpMetricsEventListenerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void uriTagWorksWithUriPatternHeader(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    server.stubFor(any(anyUrl()));
    Request request = new Request.Builder()
            .url(server.baseUrl() + "/helloworld.txt")
            .header(OkHttpMetricsEventListener.URI_PATTERN, "/")
            .build();

    client = new OkHttpClient.Builder()
            .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests")
                    .tags(Tags.of("foo", "bar"))
                    .build())
            .build();

    client.newCall(request).execute().close();

    assertThat(registry.get("okhttp.requests")
            .tags("foo", "bar", "uri", "/", "status", "200",
                    "target.host", "localhost",
                    "target.port", String.valueOf(server.port()),
                    "target.scheme", "http")
            .timer().count()).isEqualTo(1L);
}
 
Example 9
Source File: LobbyWatcherClientTest.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
@Test
void updateGame(@WiremockResolver.Wiremock final WireMockServer server) {
  server.stubFor(
      post(LobbyWatcherClient.UPDATE_GAME_PATH)
          .withHeader(AuthenticationHeaders.API_KEY_HEADER, equalTo(EXPECTED_API_KEY))
          .withRequestBody(
              equalToJson(
                  toJson(
                      UpdateGameRequest.builder()
                          .gameId(GAME_ID)
                          .gameData(TestData.LOBBY_GAME)
                          .build())))
          .willReturn(WireMock.aResponse().withStatus(200)));

  newClient(server).updateGame(GAME_ID, TestData.LOBBY_GAME);
}
 
Example 10
Source File: ModeratorChatClientTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Test
void banPlayer(@WiremockResolver.Wiremock final WireMockServer server) {
  server.stubFor(
      WireMock.post(ModeratorChatClient.BAN_PLAYER_PATH)
          .withHeader(AuthenticationHeaders.API_KEY_HEADER, equalTo(EXPECTED_API_KEY))
          .withRequestBody(equalToJson(toJson(BAN_PLAYER_REQUEST)))
          .willReturn(WireMock.aResponse().withStatus(200)));

  newClient(server).banPlayer(BAN_PLAYER_REQUEST);
}
 
Example 11
Source File: GameListingClientTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Test
void fetchGameListing(@WiremockResolver.Wiremock final WireMockServer server) {
  server.stubFor(
      get(GameListingClient.FETCH_GAMES_PATH)
          .withHeader(AuthenticationHeaders.API_KEY_HEADER, equalTo(EXPECTED_API_KEY))
          .willReturn(
              WireMock.aResponse()
                  .withStatus(200)
                  .withBody(toJson(List.of(LOBBY_GAME_LISTING)))));

  final List<LobbyGameListing> results = newClient(server).fetchGameListing();

  assertThat(results, hasSize(1));
  assertThat(results.get(0), is(LOBBY_GAME_LISTING));
}
 
Example 12
Source File: PlayerLobbyActionsClientTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Test
void fetchPlayerInfoAsModerator(@WiremockResolver.Wiremock final WireMockServer server) {
  server.stubFor(
      WireMock.post(PlayerLobbyActionsClient.FETCH_PLAYER_INFORMATION)
          .withHeader(AuthenticationHeaders.API_KEY_HEADER, equalTo(EXPECTED_API_KEY))
          .withRequestBody(equalTo("player-chat-id"))
          .willReturn(
              WireMock.aResponse()
                  .withStatus(200)
                  .withBody(toJson(PLAYER_SUMMARY_FOR_MODERATOR))));

  final var result = newClient(server).fetchPlayerInformation(PlayerChatId.of("player-chat-id"));
  assertThat(result, is(PLAYER_SUMMARY_FOR_MODERATOR));
}
 
Example 13
Source File: LobbyLoginClientTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
private void givenCreateAccountRequestReturning(
    final WireMockServer server, final CreateAccountResponse createAccountResponse) {
  server.stubFor(
      post(LobbyLoginClient.CREATE_ACCOUNT)
          .withRequestBody(equalToJson(toJson(CREATE_ACCOUNT_REQUEST)))
          .willReturn(
              WireMock.aResponse().withStatus(200).withBody(toJson(createAccountResponse))));
}
 
Example 14
Source File: ReactorNettySenderTests.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void customReadTimeoutHonored(@WiremockResolver.Wiremock WireMockServer server) throws Throwable {
    this.httpSender = new ReactorNettySender(HttpClient.create()
            .tcpConfiguration(tcpClient -> tcpClient.doOnConnected(connection ->
                    connection.addHandlerLast(new ReadTimeoutHandler(1, TimeUnit.MILLISECONDS))
                            .addHandlerLast(new WriteTimeoutHandler(1, TimeUnit.MILLISECONDS)))));
    server.stubFor(any(urlEqualTo("/metrics")).willReturn(ok().withFixedDelay(5)));

    assertThatExceptionOfType(ReadTimeoutException.class)
            .isThrownBy(() -> httpSender.post(server.baseUrl() + "/metrics").send());
}
 
Example 15
Source File: UserAccountClientTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Test
void updatePassword(@WiremockResolver.Wiremock final WireMockServer server) {
  server.stubFor(
      WireMock.post(UserAccountClient.CHANGE_PASSWORD_PATH)
          .withHeader(AuthenticationHeaders.API_KEY_HEADER, equalTo(EXPECTED_API_KEY))
          .withRequestBody(equalTo(NEW_PASSWORD))
          .willReturn(WireMock.aResponse().withStatus(200)));
  newClient(server).changePassword(NEW_PASSWORD);
}
 
Example 16
Source File: ToolboxUserBanClientTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Test
void getUserBans(@WiremockResolver.Wiremock final WireMockServer server) {
  server.stubFor(
      WireMock.get(ToolboxUserBanClient.GET_USER_BANS_PATH)
          .withHeader(AuthenticationHeaders.API_KEY_HEADER, equalTo(EXPECTED_API_KEY))
          .willReturn(
              WireMock.aResponse().withStatus(200).withBody(toJson(List.of(BANNED_USER_DATA)))));

  final List<UserBanData> result = newClient(server).getUserBans();

  assertThat(result, hasSize(1));
  assertThat(result.get(0), is(BANNED_USER_DATA));
}
 
Example 17
Source File: MicrometerHttpRequestExecutorTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void additionalTagsAreExposed(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    server.stubFor(any(anyUrl()));
    MicrometerHttpRequestExecutor executor = MicrometerHttpRequestExecutor.builder(registry)
            .tags(Tags.of("foo", "bar", "some.key", "value"))
            .exportTagsForRoute(true)
            .build();
    HttpClient client = client(executor);
    EntityUtils.consume(client.execute(new HttpGet(server.baseUrl())).getEntity());
    assertThat(registry.get(EXPECTED_METER_NAME)
            .tags("foo", "bar", "some.key", "value", "target.host", "localhost")
            .timer().count()).isEqualTo(1L);
}
 
Example 18
Source File: StyxHttpClientTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() {
    server = new WireMockServer(wireMockConfig().dynamicPort().dynamicHttpsPort());
    server.start();
    server.stubFor(WireMock.get(urlStartingWith("/")).willReturn(aResponse().withStatus(200)));

    httpRequest = get("/")
            .header(HOST, hostString(server.port()))
            .build();

    secureRequest = get("/")
            .header(HOST, hostString(server.httpsPort()))
            .build();
}
 
Example 19
Source File: MicrometerHttpRequestExecutorTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void uriIsUnknownByDefault(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    server.stubFor(any(anyUrl()));
    HttpClient client = client(executor(false));
    EntityUtils.consume(client.execute(new HttpGet(server.baseUrl())).getEntity());
    EntityUtils.consume(client.execute(new HttpGet(server.baseUrl() + "/someuri")).getEntity());
    EntityUtils.consume(client.execute(new HttpGet(server.baseUrl() + "/otheruri")).getEntity());
    assertThat(registry.get(EXPECTED_METER_NAME)
            .tags("uri", "UNKNOWN")
            .timer().count()).isEqualTo(3L);
}
 
Example 20
Source File: MicrometerHttpRequestExecutorTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void httpMethodIsTagged(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    server.stubFor(any(anyUrl()));
    HttpClient client = client(executor(false));
    EntityUtils.consume(client.execute(new HttpGet(server.baseUrl())).getEntity());
    EntityUtils.consume(client.execute(new HttpGet(server.baseUrl())).getEntity());
    EntityUtils.consume(client.execute(new HttpPost(server.baseUrl())).getEntity());
    assertThat(registry.get(EXPECTED_METER_NAME)
            .tags("method", "GET")
            .timer().count()).isEqualTo(2L);
    assertThat(registry.get(EXPECTED_METER_NAME)
            .tags("method", "POST")
            .timer().count()).isEqualTo(1L);
}