com.github.tomakehurst.wiremock.client.WireMock.equalTo()方法的使用及代码示例

x33g5p2x  于2022-02-03 转载在 其他  
字(12.3k)|赞(0)|评价(0)|浏览(141)

本文整理了Java中com.github.tomakehurst.wiremock.client.WireMock.equalTo()方法的一些代码示例,展示了WireMock.equalTo()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。WireMock.equalTo()方法的具体详情如下:
包路径:com.github.tomakehurst.wiremock.client.WireMock
类名称:WireMock
方法名:equalTo

WireMock.equalTo介绍

暂无

代码示例

代码示例来源:origin: org.apache.logging.log4j/log4j-core

@Test
public void testAppendCustomHeader() throws Exception {
  wireMockRule.stubFor(post(urlEqualTo("/test/log4j/"))
    .willReturn(SUCCESS_RESPONSE));
  final Appender appender = HttpAppender.newBuilder()
    .withName("Http")
    .withLayout(JsonLayout.createDefaultLayout())
    .setConfiguration(ctx.getConfiguration())
    .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/"))
    .setHeaders(new Property[] {
      Property.createProperty("X-Test", "header value"),
      Property.createProperty("X-Runtime", "${java:runtime}")
    })
    .build();
  appender.append(createLogEvent());
  wireMockRule.verify(postRequestedFor(urlEqualTo("/test/log4j/"))
    .withHeader("Host", containing("localhost"))
    .withHeader("X-Test", equalTo("header value"))
    .withHeader("X-Runtime", equalTo(JAVA_LOOKUP.getRuntime()))
    .withHeader("Content-Type", containing("application/json"))
    .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
}

代码示例来源:origin: com.github.tomakehurst/wiremock-jre8

private StringValuePattern valuePatternForContentType(Request request) {
  String contentType = request.getHeader("Content-Type");
  if (contentType != null) {
    if (contentType.contains("json")) {
      return equalToJson(request.getBodyAsString(), true, true);
    } else if (contentType.contains("xml")) {
      return equalToXml(request.getBodyAsString());
    }
  }
  return equalTo(request.getBodyAsString());
}

代码示例来源:origin: palantir/atlasdb

private void verifyUserAgentOnTimelockTimestampAndLockRequests() {
  verifyUserAgentOnTimestampAndLockRequests(TIMELOCK_TIMESTAMP_PATH, TIMELOCK_LOCK_PATH);
  verify(invalidator, times(1)).backupAndInvalidate();
  availableServer.verify(getRequestedFor(urlEqualTo(TIMELOCK_PING_PATH))
      .withHeader(USER_AGENT_HEADER, WireMock.equalTo(USER_AGENT)));
  availableServer.verify(postRequestedFor(urlEqualTo(TIMELOCK_FF_PATH))
      .withHeader(USER_AGENT_HEADER, WireMock.equalTo(USER_AGENT)));
}

代码示例来源:origin: palantir/atlasdb

@Test
public void directProxyIsConfigurableOnClientRequests() {
  Optional<ProxySelector> directProxySelector = Optional.of(
      ServiceCreator.createProxySelector(ProxyConfiguration.DIRECT));
  TestResource clientWithDirectCall = AtlasDbHttpClients.createProxyWithFailover(
      new MetricRegistry(), NO_SSL,
      directProxySelector, ImmutableSet.of(getUriForPort(availablePort)), TestResource.class);
  clientWithDirectCall.getTestNumber();
  String defaultUserAgent = UserAgents.fromStrings(UserAgents.DEFAULT_VALUE, UserAgents.DEFAULT_VALUE);
  availableServer.verify(getRequestedFor(urlMatching(TEST_ENDPOINT))
      .withHeader(FeignOkHttpClients.USER_AGENT_HEADER, WireMock.equalTo(defaultUserAgent)));
}

代码示例来源:origin: palantir/atlasdb

@Test
public void userAgentIsPresentOnClientRequests() {
  TestResource client =
      AtlasDbHttpClients.createProxy(
          new MetricRegistry(), NO_SSL, getUriForPort(availablePort), TestResource.class);
  client.getTestNumber();
  String defaultUserAgent = UserAgents.fromStrings(UserAgents.DEFAULT_VALUE, UserAgents.DEFAULT_VALUE);
  availableServer.verify(getRequestedFor(urlMatching(TEST_ENDPOINT))
      .withHeader(FeignOkHttpClients.USER_AGENT_HEADER, WireMock.equalTo(defaultUserAgent)));
}

代码示例来源:origin: palantir/atlasdb

@Test
public void httpProxyIsConfigurableOnClientRequests() {
  Optional<ProxySelector> httpProxySelector = Optional.of(
      ServiceCreator.createProxySelector(ProxyConfiguration.of(getHostAndPort(proxyPort))));
  TestResource clientWithHttpProxy = AtlasDbHttpClients.createProxyWithFailover(
      new MetricRegistry(),
      NO_SSL,
      httpProxySelector, ImmutableSet.of(getUriForPort(availablePort)), TestResource.class);
  clientWithHttpProxy.getTestNumber();
  String defaultUserAgent = UserAgents.fromStrings(UserAgents.DEFAULT_VALUE, UserAgents.DEFAULT_VALUE);
  proxyServer.verify(getRequestedFor(urlMatching(TEST_ENDPOINT))
      .withHeader(FeignOkHttpClients.USER_AGENT_HEADER, WireMock.equalTo(defaultUserAgent)));
  availableServer.verify(0, getRequestedFor(urlMatching(TEST_ENDPOINT)));
}

代码示例来源:origin: palantir/atlasdb

private void verifyUserAgentOnTimestampAndLockRequests(String timestampPath, String lockPath) {
  InMemoryTimestampService ts = new InMemoryTimestampService();
  TransactionManagers.LockAndTimestampServices lockAndTimestamp =
      TransactionManagers.createLockAndTimestampServices(
          metricsManager,
          config,
          () -> runtimeConfig,
          environment,
          LockServiceImpl::create,
          () -> ts,
          () -> ts,
          invalidator,
          USER_AGENT);
  lockAndTimestamp.timelock().getFreshTimestamp();
  lockAndTimestamp.timelock().currentTimeMillis();
  availableServer.verify(postRequestedFor(urlMatching(timestampPath))
      .withHeader(USER_AGENT_HEADER, WireMock.equalTo(USER_AGENT)));
  availableServer.verify(postRequestedFor(urlMatching(lockPath))
      .withHeader(USER_AGENT_HEADER, WireMock.equalTo(USER_AGENT)));
}

代码示例来源:origin: palantir/atlasdb

@Test
public void remoteCallsElidedIfTalkingToLocalServer() throws IOException, InterruptedException {
  setUpForLocalServices();
  setUpLeaderBlockInConfig();
  TransactionManagers.LockAndTimestampServices lockAndTimestamp = getLockAndTimestampServices();
  availableServer.verify(getRequestedFor(urlMatching(LEADER_UUID_PATH)));
  lockAndTimestamp.timelock().getFreshTimestamp();
  lockAndTimestamp.lock().currentTimeMillis();
  availableServer.verify(0, postRequestedFor(urlMatching(TIMESTAMP_PATH))
      .withHeader(USER_AGENT_HEADER, WireMock.equalTo(USER_AGENT)));
  availableServer.verify(0, postRequestedFor(urlMatching(LOCK_PATH))
      .withHeader(USER_AGENT_HEADER, WireMock.equalTo(USER_AGENT)));
}

代码示例来源:origin: palantir/atlasdb

@Test
public void remoteCallsStillMadeIfPingableLeader404s() throws IOException, InterruptedException {
  setUpForRemoteServices();
  setUpLeaderBlockInConfig();
  TransactionManagers.LockAndTimestampServices lockAndTimestamp = getLockAndTimestampServices();
  availableServer.verify(getRequestedFor(urlMatching(LEADER_UUID_PATH)));
  lockAndTimestamp.timelock().getFreshTimestamp();
  lockAndTimestamp.lock().currentTimeMillis();
  availableServer.verify(postRequestedFor(urlMatching(TIMESTAMP_PATH))
      .withHeader(USER_AGENT_HEADER, WireMock.equalTo(USER_AGENT)));
  availableServer.verify(postRequestedFor(urlMatching(LOCK_PATH))
      .withHeader(USER_AGENT_HEADER, WireMock.equalTo(USER_AGENT)));
}

代码示例来源:origin: geotools/geotools

@Test
  public void testBasicHeader() throws IOException {
    stubFor(
        get(urlEqualTo("/test"))
            .willReturn(
                aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "text/xml")
                    .withBody("<response>Some content</response>")));

    String longPassword = String.join("", Collections.nCopies(10, "0123456789"));
    String userName = "user";
    SimpleHttpClient client = new SimpleHttpClient();
    client.setUser(userName);
    client.setPassword(longPassword);
    client.get(new URL("http://localhost:" + wireMockRule.port() + "/test"));

    String encodedCredentials =
        "dXNlcjowMTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5";
    verify(
        getRequestedFor(urlEqualTo("/test"))
            .withHeader("Authorization", equalTo("Basic " + encodedCredentials)));
  }
}

代码示例来源:origin: sargue/mailgun

private MappingBuilder expectedBasicPost() {
  return post(urlEqualTo("/api/" + DOMAIN + "/messages"))
    .withHeader("Authorization", equalTo("Basic " + expectedAuthHeader))
    .withHeader("Content-Type",
          equalTo("application/x-www-form-urlencoded"));
}

代码示例来源:origin: sargue/mailgun

private void verifyMessageSent(List<NameValuePair> parametersList) {
  List<NameValuePair> parameters = new ArrayList<>(parametersList);
  boolean fromFound = false;
  for (int i = 0; i < parameters.size() && !fromFound; i++)
    fromFound = parameters.get(i).getName().equals("from");
  if (!fromFound)
    parameters.add(param("from", mail(FROM_NAME, FROM_EMAIL)));
  String form = URLEncodedUtils.format(parameters, "UTF-8");
  verify(postRequestedFor(urlEqualTo("/api/somedomain.com/messages"))
        .withRequestBody(equalTo(form)));
}

代码示例来源:origin: io.micrometer/micrometer-test

@Test
void successfulPostNoBody(HttpSender httpClient, @WiremockResolver.Wiremock WireMockServer server) throws Throwable {
  server.stubFor(any(anyUrl()));
  assertThat(httpClient.post(server.baseUrl() + "/api")
      .withPlainText("this is a line")
      .send().body()).isEqualTo(HttpSender.Response.NO_RESPONSE_BODY);
  server.verify(postRequestedFor(urlEqualTo("/api")).withRequestBody(equalTo("this is a line")));
}

代码示例来源:origin: uber/rides-java-sdk

@Test
  public void testRefresh_whenSuccessful() throws Exception {
    stubFor(post(urlEqualTo("/token"))
        .withRequestBody(equalTo(REQUEST_BODY))
        .willReturn(aResponse()
            .withBodyFile("token_token.json")));

    AccessToken accessToken = oAuth2Service.refresh(REFRESH_TOKEN, CLIENT_ID).execute().body();

    assertThat(accessToken.getExpiresIn()).isEqualTo(2592000);
    assertThat(accessToken.getToken()).isEqualTo("Access999Token");
    assertThat(accessToken.getRefreshToken()).isEqualTo("888RefreshToken");
  }
}

代码示例来源:origin: io.micrometer/micrometer-test

@Test
void successfulPostWithBody(HttpSender httpClient, @WiremockResolver.Wiremock WireMockServer server) throws Throwable {
  server.stubFor(any(anyUrl()).willReturn(aResponse()
      .withBody("a body")));
  assertThat(httpClient.post(server.baseUrl() + "/api")
      .withPlainText("this is a line")
      .send().body()).isEqualTo("a body");
  server.verify(postRequestedFor(urlEqualTo("/api")).withRequestBody(equalTo("this is a line")));
}

代码示例来源:origin: ocadotechnology/newrelic-alerts-configurator

private void newRelicReturnsApplications() throws UnsupportedEncodingException {
  String queryParam = URLEncoder.encode("filter[name]", UTF_8.name());
  WIRE_MOCK.addStubMapping(
      get(urlPathEqualTo("/v2/applications.json"))
          .withQueryParam(queryParam, equalTo("application_name"))
          .withHeader("X-Api-Key", equalTo("secret"))
          .willReturn(aResponse()
              .withStatus(SC_OK)
              .withHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON)
              .withBody(applications)
          ).build());
}

代码示例来源:origin: georocket/georocket

/**
 * Verify that a certain POST request has been made
 * @param url the request URL
 * @param body the request body
 * @param context the current test context
 */
protected void verifyPosted(String url, String body, TestContext context) {
 try {
  verify(postRequestedFor(urlEqualTo(url))
    .withRequestBody(equalTo(body)));
 } catch (VerificationException e) {
  context.fail(e);
 }
}

代码示例来源:origin: kptfh/feign-reactive

@Test
 public void testPayBill_success() throws JsonProcessingException {

  Bill bill = Bill.makeBill(new OrderGenerator().generate(30));

  wireMockRule.stubFor(post(urlEqualTo("/icecream/bills/pay"))
      .withRequestBody(equalTo(TestUtils.MAPPER.writeValueAsString(bill)))
      .willReturn(aResponse().withStatus(200)
          .withHeader("Content-Type", "application/json")));

  Mono<Void> result = client.payBill(bill);
  StepVerifier.create(result)
    .expectNextCount(0)
    .verifyComplete();
 }
}

代码示例来源:origin: org.kie/kie-server-client

@Test
public void testError500Handling() {
  expectedEx.expect( KieServicesException.class );
  expectedEx.expectMessage( "Error code: 500");
  stubFor(get(urlEqualTo("/containers"))
      .withHeader("Accept", equalTo("application/xml"))
      .willReturn(aResponse()
              .withStatus(500)
              .withBody("Internal server error!")
      ));
  KieServicesClient client = new KieServicesClientImpl(config);
  client.listContainers();
}

代码示例来源:origin: kptfh/feign-reactive

@Test
public void shouldThrowRetryException() {
 wireMockRule.stubFor(get(urlEqualTo("/icecream/orders/1"))
   .withHeader("Accept", equalTo("application/json"))
   .willReturn(aResponse().withStatus(HttpStatus.SC_SERVICE_UNAVAILABLE)));
 IcecreamServiceApi client = builder()
   .statusHandler(throwOnStatus(
     status -> status == HttpStatus.SC_SERVICE_UNAVAILABLE,
     (methodTag, response) -> new RetryableException("Should retry on next node", null)))
   .target(IcecreamServiceApi.class, "http://localhost:" + wireMockRule.port());
 StepVerifier.create(client.findFirstOrder())
   .expectError(RetryableException.class);
}

相关文章