com.github.tomakehurst.wiremock.WireMockServer Java Examples

The following examples show how to use com.github.tomakehurst.wiremock.WireMockServer. 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: 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 #2
Source File: WireMockExtension.java    From wiremock-extension with MIT License 6 votes vote down vote up
private void checkForUnmatchedRequests(final WireMockServer server) {
	
	final boolean mustCheck = Optional.of(server)
		.filter(ManagedWireMockServer.class::isInstance)
		.map(ManagedWireMockServer.class::cast)
		.map(ManagedWireMockServer::failOnUnmatchedRequests)
		.orElse(generalFailOnUnmatchedRequests);

	if (mustCheck) {
		final List<LoggedRequest> unmatchedRequests = server.findAllUnmatchedRequests();
		if (!unmatchedRequests.isEmpty()) {
			final List<NearMiss> nearMisses = server.findNearMissesForAllUnmatchedRequests();
			throw nearMisses.isEmpty()
				  ? VerificationException.forUnmatchedRequests(unmatchedRequests)
				  : VerificationException.forUnmatchedNearMisses(nearMisses);
		}
	}
}
 
Example #3
Source File: RetryWithStateTest.java    From zerocode with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpWireMock() throws Exception {
    mockServer = new WireMockServer(port);
    basePath = "http://localhost:" + port;
    String path = "/retry/ids/1";
    fullPath = basePath + path;

    mockServer.start();

    mockServer.stubFor(get(urlEqualTo(path))
            .inScenario("Retry Scenario")
            .whenScenarioStateIs(STARTED)
            .willReturn(aResponse()
                    .withStatus(500))
            .willSetStateTo("retry")
    );

    mockServer.stubFor(get(urlEqualTo(path))
            .inScenario("Retry Scenario")
            .whenScenarioStateIs("retry")
            .willReturn(aResponse()
                    .withStatus(200))
    );
}
 
Example #4
Source File: ApacheClientTlsAuthTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws IOException {
    ClientTlsAuthTestBase.setUp();

    // Will be used by both client and server to trust the self-signed
    // cert they present to each other
    System.setProperty("javax.net.ssl.trustStore", serverKeyStore.toAbsolutePath().toString());
    System.setProperty("javax.net.ssl.trustStorePassword", STORE_PASSWORD);
    System.setProperty("javax.net.ssl.trustStoreType", "jks");

    wireMockServer = new WireMockServer(wireMockConfig()
            .dynamicHttpsPort()
            .needClientAuth(true)
            .keystorePath(serverKeyStore.toAbsolutePath().toString())
            .keystorePassword(STORE_PASSWORD)
    );

    wireMockServer.start();

    keyManagersProvider = FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, STORE_PASSWORD);
}
 
Example #5
Source File: RestAssured2IntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@BeforeClass
public static void before() throws Exception {
    System.out.println("Setting up!");
    final int port = Util.getAvailablePort();
    wireMockServer = new WireMockServer(port);
    wireMockServer.start();
    configureFor("localhost", port);
    RestAssured.port = port;
    stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
      aResponse().withStatus(200)
        .withHeader("Content-Type", APPLICATION_JSON)
        .withBody(ODDS)));
    stubFor(post(urlEqualTo("/odds/new"))
        .withRequestBody(containing("{\"price\":5.25,\"status\":1,\"ck\":13.1,\"name\":\"X\"}"))
        .willReturn(aResponse().withStatus(201)));
}
 
Example #6
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 #7
Source File: WireMockBaseTest.java    From parsec-libraries with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setupServer() throws IOException {
    String rootDirPath = "parsec_wiremock_test";
    File root = Files.createTempDirectory(rootDirPath).toFile();
    new File(root, WireMockApp.MAPPINGS_ROOT).mkdirs();
    new File(root, WireMockApp.FILES_ROOT).mkdirs();
    wireMockServer = new WireMockServer(
            WireMockConfiguration.options()
                    .dynamicPort()
                    .fileSource(new SingleRootFileSource(rootDirPath))
    );

    wireMockServer.start();
    wireMockBaseUrl = "http://localhost:"+wireMockServer.port();
    WireMock.configureFor(wireMockServer.port());
}
 
Example #8
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 #9
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 #10
Source File: HumioMeterRegistryTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
private HumioMeterRegistry humioMeterRegistry(WireMockServer server, String... tags) {
    return new HumioMeterRegistry(new HumioConfig() {
        @Override
        public String get(String key) {
            return null;
        }

        @Override
        public String uri() {
            return server.baseUrl();
        }

        @Override
        public Map<String, String> tags() {
            Map<String, String> tagMap = new HashMap<>();
            for (int i = 0; i < tags.length; i += 2) {
                tagMap.put(tags[i], tags[i + 1]);
            }
            return tagMap;
        }
    }, clock);
}
 
Example #11
Source File: RemoteFileTest.java    From mastering-junit5 with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setup() throws Exception {
    // Look for free port for SUT instantiation
    int port;
    try (ServerSocket socket = new ServerSocket(0)) {
        port = socket.getLocalPort();
    }
    remoteFileService = new RemoteFileService("http://localhost:" + port);

    // Mock server
    wireMockServer = new WireMockServer(options().port(port));
    wireMockServer.start();
    configureFor("localhost", wireMockServer.port());

    // Stubbing service
    stubFor(post(urlEqualTo("/api/v1/paths/" + filename + "/open-file"))
            .willReturn(aResponse().withStatus(200).withBody(streamId)));
    stubFor(post(urlEqualTo("/api/v1/streams/" + streamId + "/read"))
            .willReturn(aResponse().withStatus(200).withBody(contentFile)));
    stubFor(post(urlEqualTo("/api/v1/streams/" + streamId + "/close"))
            .willReturn(aResponse().withStatus(200)));
}
 
Example #12
Source File: AllureHttpClientTest.java    From allure-java with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() {
    server = new WireMockServer(options().dynamicPort());
    server.start();
    configureFor(server.port());

    stubFor(get(urlEqualTo("/hello"))
            .willReturn(aResponse()
                    .withBody(BODY_STRING)));

    stubFor(get(urlEqualTo("/empty"))
            .willReturn(aResponse()
                    .withStatus(304)));

    stubFor(delete(urlEqualTo("/hello"))
            .willReturn(noContent()));
}
 
Example #13
Source File: HttpSenderCompatibilityKit.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@EnumSource(HttpSender.Method.class)
void customHeader(HttpSender.Method method, @WiremockResolver.Wiremock WireMockServer server) throws Throwable {
    server.stubFor(any(urlEqualTo("/metrics"))
            .willReturn(unauthorized()));

    HttpSender.Response response = httpSender.newRequest(server.baseUrl() + "/metrics")
            .withMethod(method)
            .withHeader("customHeader", "customHeaderValue")
            .send();

    assertThat(response.code()).isEqualTo(401);

    server.verify(WireMock.requestMadeFor(request ->
            MatchResult.aggregate(
                    MatchResult.of(request.getMethod().getName().equals(method.name())),
                    MatchResult.of(request.getUrl().equals("/metrics"))
            ))
            .withHeader("customHeader", equalTo("customHeaderValue")));
}
 
Example #14
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 #15
Source File: OkHttpMetricsEventListenerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void timeNotFound(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    server.stubFor(any(anyUrl()).willReturn(aResponse().withStatus(404)));
    Request request = new Request.Builder()
            .url(server.baseUrl())
            .build();

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

    assertThat(registry.get("okhttp.requests")
            .tags("foo", "bar", "status", "404", "uri", "NOT_FOUND",
                    "target.host", "localhost",
                    "target.port", String.valueOf(server.port()),
                    "target.scheme", "http")
            .timer().count()).isEqualTo(1L);
}
 
Example #16
Source File: OkHttpMetricsEventListenerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void uriTagWorksWithUriMapper(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    server.stubFor(any(anyUrl()));
    OkHttpClient client = new OkHttpClient.Builder()
            .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests")
                    .uriMapper(req -> req.url().encodedPath())
                    .tags(Tags.of("foo", "bar"))
                    .build())
            .build();

    Request request = new Request.Builder()
            .url(server.baseUrl() + "/helloworld.txt")
            .build();

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

    assertThat(registry.get("okhttp.requests")
            .tags("foo", "bar", "uri", "/helloworld.txt", "status", "200",
                    "target.host", "localhost",
                    "target.port", String.valueOf(server.port()),
                    "target.scheme", "http")
            .timer().count()).isEqualTo(1L);
}
 
Example #17
Source File: OkHttpMetricsEventListenerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void contextSpecificTags(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    server.stubFor(any(anyUrl()));
    OkHttpClient client = new OkHttpClient.Builder()
            .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests")
                    .tag((req, res) -> Tag.of("another.uri", req.url().encodedPath()))
                    .build())
            .build();

    Request request = new Request.Builder()
            .url(server.baseUrl() + "/helloworld.txt")
            .build();

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

    assertThat(registry.get("okhttp.requests")
            .tags("another.uri", "/helloworld.txt", "status", "200")
            .timer().count()).isEqualTo(1L);
}
 
Example #18
Source File: OkHttpMetricsEventListenerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void cachedResponsesDoNotLeakMemory(
        @WiremockResolver.Wiremock WireMockServer server, @TempDir Path tempDir) throws IOException {
    OkHttpMetricsEventListener listener = OkHttpMetricsEventListener.builder(registry, "okhttp.requests").build();
    OkHttpClient clientWithCache = new OkHttpClient.Builder()
            .eventListener(listener)
            .cache(new Cache(tempDir.toFile(), 55555))
            .build();
    server.stubFor(any(anyUrl()).willReturn(aResponse().withHeader("Cache-Control", "max-age=9600")));
    Request request = new Request.Builder()
            .url(server.baseUrl())
            .build();

    clientWithCache.newCall(request).execute().close();
    assertThat(listener.callState).isEmpty();
    try (Response response = clientWithCache.newCall(request).execute()) {
        assertThat(response.cacheResponse()).isNotNull();
    }

    assertThat(listener.callState).isEmpty();
}
 
Example #19
Source File: WireMockListener.java    From restdocs-wiremock with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
	if(wireMockAnnotation == null) {
		return;
	}
	WireMockTest methodAnnotation = testContext.getTestMethod().getAnnotation(WireMockTest.class);
	
	String stubPath = "";
	if(this.wireMockAnnotation.stubPath() != null) {
		stubPath = this.wireMockAnnotation.stubPath();
	}
	if (methodAnnotation != null && methodAnnotation.stubPath() != null) {
		stubPath += "/" + methodAnnotation.stubPath();
	}

	ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) testContext
			.getApplicationContext();

	WireMockServer server = applicationContext.getBean(WireMockServer.class);
	server.resetMappings();
	if(! stubPath.isEmpty()) {
		server.loadMappingsUsing(new JsonFileMappingsSource(new ClasspathFileSource(stubPath)));
	}
}
 
Example #20
Source File: SendGridFluentEmailTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setup() {
	when(generator.generate(anyString())).then(AdditionalAnswers.returnsArgAt(0));
	server = new WireMockServer(options().dynamicPort());
	server.start();
	messagingService = MessagingBuilder.standard()
			.email()
				.images()
					.inline()
						.attach()
							.cid()
								.generator(generator)
								.and()
							.and()
						.and()
					.and()
				.sender(SendGridV4Builder.class)
					.url("http://localhost:"+server.port())
					.apiKey("foobar")
					.and()
				.and()
			.build();
}
 
Example #21
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 #22
Source File: HttpSenderCompatibilityKit.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@EnumSource(HttpSender.Method.class)
void basicAuth(HttpSender.Method method, @WiremockResolver.Wiremock WireMockServer server) throws Throwable {
    server.stubFor(any(urlEqualTo("/metrics"))
            .willReturn(unauthorized()));

    HttpSender.Response response = httpSender.newRequest(server.baseUrl() + "/metrics")
            .withMethod(method)
            .withBasicAuthentication("superuser", "superpassword")
            .send();

    assertThat(response.code()).isEqualTo(401);

    server.verify(WireMock.requestMadeFor(request ->
            MatchResult.aggregate(
                    MatchResult.of(request.getMethod().getName().equals(method.name())),
                    MatchResult.of(request.getUrl().equals("/metrics"))
            ))
            .withBasicAuth(new BasicCredentials("superuser", "superpassword")));
}
 
Example #23
Source File: SendGridHttpTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setup() {
	when(generator.generate(anyString())).then(AdditionalAnswers.returnsArgAt(0));
	server = new WireMockServer(options().dynamicPort());
	server.start();
	messagingService = MessagingBuilder.standard()
			.email()
				.images()
					.inline()
						.attach()
							.cid()
								.generator(generator)
								.and()
							.and()
						.and()
					.and()
				.sender(SendGridV4Builder.class)
					.url("http://localhost:"+server.port())
					.apiKey("foobar")
					.and()
				.and()
			.build();
}
 
Example #24
Source File: OkHttpSenderTests.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 OkHttpSender(new OkHttpClient.Builder().readTimeout(1, TimeUnit.MILLISECONDS).build());
    server.stubFor(any(urlEqualTo("/metrics")).willReturn(ok().withFixedDelay(5)));

    assertThatExceptionOfType(SocketTimeoutException.class)
            .isThrownBy(() -> httpSender.post(server.baseUrl() + "/metrics").send());
}
 
Example #25
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 #26
Source File: RemoteActionsClientTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
private void givenServerStubForIsPlayerBanned(
    final String ip, final WireMockServer server, final boolean response) {
  server.stubFor(
      post(RemoteActionsClient.IS_PLAYER_BANNED_PATH)
          .withRequestBody(equalTo(ip))
          .willReturn(WireMock.aResponse().withStatus(200).withBody(String.valueOf(response))));
}
 
Example #27
Source File: ToolboxModeratorManagementClientTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Test
void fetchModeratorList(@WiremockResolver.Wiremock final WireMockServer server) {
  server.stubFor(
      WireMock.get(ToolboxModeratorManagementClient.FETCH_MODERATORS_PATH)
          .withHeader(AuthenticationHeaders.API_KEY_HEADER, equalTo(EXPECTED_API_KEY))
          .willReturn(
              WireMock.aResponse().withStatus(200).withBody(toJson(List.of(MODERATOR_INFO)))));

  final List<ModeratorInfo> results = newClient(server).fetchModeratorList();

  assertThat(results, hasSize(1));
  assertThat(results.get(0), is(MODERATOR_INFO));
}
 
Example #28
Source File: LobbyLoginClientTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Test
void loginSucces(@WiremockResolver.Wiremock final WireMockServer server) {
  givenLoginRequestReturning(server, SUCCESS_LOGIN_RESPONSE);

  final LobbyLoginResponse result = withLoginRequest(server);

  assertThat(result, is(SUCCESS_LOGIN_RESPONSE));
}
 
Example #29
Source File: HttpClientTesting.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/** Verifies http client behavior on error cases, eg: communication error, server 500. */
public static <T> void verifyErrorHandling(
    final WireMockServer wireMockServer,
    final String expectedRequestPath,
    final RequestType requestType,
    final Function<URI, T> serviceCall) {
  server500(wireMockServer, expectedRequestPath, requestType, serviceCall);
  faultCases(wireMockServer, expectedRequestPath, requestType, serviceCall);
}
 
Example #30
Source File: OkHttpMetricsEventListenerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void requestTagsWithoutClass(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    Request request = new Request.Builder()
            .url(server.baseUrl() + "/helloworld.txt")
            .tag(Tags.of("requestTag1", "tagValue1"))
            .build();

    testRequestTags(server, request);
}