下面列出了org.junit.jupiter.api.extension.ExtensionConfigurationException#com.github.tomakehurst.wiremock.WireMockServer 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
}
@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));
}
@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)));
}
@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"));
}
@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()));
}
@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();
}
@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)));
}
}
@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();
}
@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")));
}
@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")));
}
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);
}
@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))
);
}
@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);
}
@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);
}
@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)));
}
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")));
}
@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());
}
@Test
void loginSucces(@WiremockResolver.Wiremock final WireMockServer server) {
givenLoginRequestReturning(server, SUCCESS_LOGIN_RESPONSE);
final LobbyLoginResponse result = withLoginRequest(server);
assertThat(result, is(SUCCESS_LOGIN_RESPONSE));
}
@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));
}
@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)));
}
@Test
void addUsernameBan(@WiremockResolver.Wiremock final WireMockServer server) {
serve200ForToolboxPostWithBody(
server, ToolboxUsernameBanClient.ADD_BANNED_USER_NAME_PATH, USERNAME);
newClient(server).addUsernameBan(USERNAME);
}
@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));
}
@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);
}
@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());
}