org.junit.jupiter.api.extension.ExtensionConfigurationException#com.github.tomakehurst.wiremock.WireMockServer源码实例Demo

下面列出了org.junit.jupiter.api.extension.ExtensionConfigurationException#com.github.tomakehurst.wiremock.WireMockServer 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: wiremock-extension   文件: WireMockExtension.java
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);
		}
	}
}
 
源代码2 项目: triplea   文件: LobbyWatcherClientTest.java
@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));
}
 
源代码3 项目: mastering-junit5   文件: RemoteFileTest.java
@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)));
}
 
源代码4 项目: triplea   文件: LobbyWatcherClientTest.java
@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"));
}
 
源代码5 项目: allure-java   文件: AllureHttpClientTest.java
@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()));
}
 
源代码6 项目: ogham   文件: SendGridHttpTest.java
@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();
}
 
@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);
}
 
@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);
}
 
@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);
}
 
@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);
}
 
@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);
}
 
@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();
}
 
源代码13 项目: restdocs-wiremock   文件: WireMockListener.java
@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)));
	}
}
 
源代码14 项目: ogham   文件: SendGridFluentEmailTest.java
@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();
}
 
源代码15 项目: micrometer   文件: HttpSenderCompatibilityKit.java
@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")));
}
 
源代码16 项目: micrometer   文件: HttpSenderCompatibilityKit.java
@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")));
}
 
源代码17 项目: micrometer   文件: HumioMeterRegistryTest.java
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);
}
 
源代码18 项目: zerocode   文件: RetryWithStateTest.java
@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))
    );
}
 
源代码19 项目: triplea   文件: LobbyWatcherClientTest.java
@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);
}
 
源代码20 项目: aws-sdk-java-v2   文件: ApacheClientTlsAuthTest.java
@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);
}
 
源代码21 项目: tutorials   文件: RestAssured2IntegrationTest.java
@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)));
}
 
源代码22 项目: triplea   文件: HttpClientTesting.java
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")));
}
 
源代码23 项目: parsec-libraries   文件: WireMockBaseTest.java
@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());
}
 
源代码24 项目: triplea   文件: LobbyLoginClientTest.java
@Test
void loginSucces(@WiremockResolver.Wiremock final WireMockServer server) {
  givenLoginRequestReturning(server, SUCCESS_LOGIN_RESPONSE);

  final LobbyLoginResponse result = withLoginRequest(server);

  assertThat(result, is(SUCCESS_LOGIN_RESPONSE));
}
 
源代码25 项目: triplea   文件: ForgotPasswordClientTest.java
@Test
void sendForgotPasswordSuccessCase(@WiremockResolver.Wiremock final WireMockServer server) {
  final ForgotPasswordResponse response =
      HttpClientTesting.sendServiceCallToWireMock(
          HttpClientTesting.ServiceCallArgs.<ForgotPasswordResponse>builder()
              .wireMockServer(server)
              .expectedRequestPath(ForgotPasswordClient.FORGOT_PASSWORD_PATH)
              .expectedBodyContents(List.of(REQUEST.getUsername(), REQUEST.getEmail()))
              .serverReturnValue(new Gson().toJson(SUCCESS_RESPONSE))
              .serviceCall(ForgotPasswordClientTest::doServiceCall)
              .build());

  assertThat(response, is(SUCCESS_RESPONSE));
}
 
源代码26 项目: tutorials   文件: RestAssuredXMLIntegrationTest.java
@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(post(urlEqualTo(EVENTS_PATH)).willReturn(
      aResponse().withStatus(200)
        .withHeader("Content-Type", APPLICATION_XML)
        .withBody(EMPLOYEES)));
}
 
源代码27 项目: triplea   文件: ToolboxUsernameBanClientTest.java
@Test
void addUsernameBan(@WiremockResolver.Wiremock final WireMockServer server) {
  serve200ForToolboxPostWithBody(
      server, ToolboxUsernameBanClient.ADD_BANNED_USER_NAME_PATH, USERNAME);

  newClient(server).addUsernameBan(USERNAME);
}
 
源代码28 项目: triplea   文件: ToolboxAccessLogClientTest.java
@Test
void sendErrorReportSuccessCase(@WiremockResolver.Wiremock final WireMockServer server) {
  server.stubFor(
      WireMock.post(ToolboxAccessLogClient.FETCH_ACCESS_LOG_PATH)
          .withHeader(AuthenticationHeaders.API_KEY_HEADER, equalTo(EXPECTED_API_KEY))
          .withRequestBody(
              equalToJson(
                  toJson(
                      AccessLogRequest.builder()
                          .accessLogSearchRequest(
                              AccessLogSearchRequest.builder()
                                  .username("%")
                                  .ip("1.%")
                                  .systemId("123")
                                  .build())
                          .pagingParams(HttpClientTesting.PAGING_PARAMS)
                          .build())))
          .willReturn(
              WireMock.aResponse().withStatus(200).withBody(toJson(List.of(ACCESS_LOG_DATA)))));

  final List<AccessLogData> results =
      newClient(server)
          .getAccessLog(
              AccessLogSearchRequest.builder().username("%").systemId("123").ip("1.%").build(),
              HttpClientTesting.PAGING_PARAMS);

  assertThat(results, IsCollectionWithSize.hasSize(1));
  assertThat(results.get(0), is(ACCESS_LOG_DATA));
}
 
源代码29 项目: wiremock-extension   文件: WireMockExtension.java
@Override
public void afterEach(final ExtensionContext context) {
	final List<WireMockServer> wireMockServers = collectServers(context);
	// Stopping all servers first
	wireMockServers.forEach(WireMockExtension::stopServer);
	wireMockServers.forEach(this::checkForUnmatchedRequests);
}
 
源代码30 项目: triplea   文件: LobbyWatcherClientTest.java
@Test
void sendGameHostingRequest(@WiremockResolver.Wiremock final WireMockServer wireMockServer) {
  wireMockServer.stubFor(
      post(LobbyWatcherClient.UPLOAD_CHAT_PATH).willReturn(WireMock.aResponse().withStatus(200)));

  newClient(wireMockServer)
      .uploadChatMessage(
          ApiKey.newKey(),
          ChatUploadParams.builder()
              .gameId("game-id")
              .chatMessage("chat-message")
              .fromPlayer(UserName.of("player"))
              .build());
}