Java Code Examples for com.github.tomakehurst.wiremock.client.WireMock#verify()

The following examples show how to use com.github.tomakehurst.wiremock.client.WireMock#verify() . 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: AuthenticatedRestTemplateTest.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthRestTemplateForSessionTimeoutWithPostForObject() {
    initialAuthenticationMock();
    mockCsrfTokenEndpoint();

    logger.debug("Mock returns 403 for POST request when session timeout");
    WireMock.stubFor(
            WireMock.post(WireMock.urlEqualTo("/random-403-endpoint"))
                    .willReturn(WireMock.aResponse().withStatus(HttpStatus.FORBIDDEN.value()))
    );

    String response = null;
    try {
        response = authenticatedRestTemplate.postForObject("random-403-endpoint", new HashMap<String, String>(), String.class);
    } catch (RestClientException e) {
        logger.debug("Expecting this to fail because the response for /random-403-endpoint has been stubbed to be always returning a 403");
        Assert.assertEquals("Tried to re-authenticate but the response remains to be unauthenticated", e.getMessage());
    }

    Assert.assertNull(response);

    WireMock.verify(2, WireMock.getRequestedFor(WireMock.urlMatching("/login")).withHeader("Accept", WireMock.matching("text/plain.*")));
    WireMock.verify(2, WireMock.postRequestedFor(WireMock.urlMatching("/login")).withHeader("Accept", WireMock.matching("text/plain.*")));
    WireMock.verify(2, WireMock.postRequestedFor(WireMock.urlMatching("/random-403-endpoint")).withHeader("Accept", WireMock.matching("text/plain.*")).withHeader("X-CSRF-TOKEN", WireMock.matching("madeup-csrf-value")));
}
 
Example 2
Source File: AuthenticatedRestTemplateTest.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthRestTemplateFor401() {
    initialAuthenticationMock();
    mockCsrfTokenEndpoint();

    logger.debug("Mock returns 401 for POST request when session timeout");
    WireMock.stubFor(
            WireMock.post(WireMock.urlEqualTo("/random-401-endpoint"))
                    .willReturn(WireMock.aResponse().withStatus(HttpStatus.UNAUTHORIZED.value()))
    );

    String response = null;
    try {
        response = authenticatedRestTemplate.postForObject("random-401-endpoint", new HashMap<String, String>(), String.class);
    } catch (RestClientException e) {
        logger.debug("Expecting this to fail because the response for /random-401-endpoint has been stubbed to be always returning a 401");
        Assert.assertEquals("Tried to re-authenticate but the response remains to be unauthenticated", e.getMessage());
    }

    Assert.assertNull(response);

    WireMock.verify(2, WireMock.getRequestedFor(WireMock.urlMatching("/login")).withHeader("Accept", WireMock.matching("text/plain.*")));
    WireMock.verify(2, WireMock.postRequestedFor(WireMock.urlMatching("/login")).withHeader("Accept", WireMock.matching("text/plain.*")));
    WireMock.verify(2, WireMock.postRequestedFor(WireMock.urlMatching("/random-401-endpoint")).withHeader("Accept", WireMock.matching("text/plain.*")).withHeader("X-CSRF-TOKEN", WireMock.matching("madeup-csrf-value")));
}
 
Example 3
Source File: AuthenticatedRestTemplateTest.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoubleEncodedUrlForGetForObject() {
    initialAuthenticationMock();
    mockCsrfTokenEndpoint();

    WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/api/assets?path=abc%5Cdef"))
            .willReturn(WireMock.aResponse()
                    .withStatus(HttpStatus.FOUND.value())
                    .withHeader("Location", "/api/assets?path=abc%5Cdefs")
                    .withBody("")));

    Map<String, String> uriVariables = new HashMap<>();
    uriVariables.put("path", "abc\\def");
    authenticatedRestTemplate.getForObjectWithQueryStringParams("/api/assets", String.class, uriVariables);

    WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/api/assets?path=abc%5Cdef")));
}
 
Example 4
Source File: TokenFileAuthenticationTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void testTokenProvided() throws IOException, ApiException {
  stubFor(
      get(urlPathEqualTo("/api/v1/pods")).willReturn(okForContentType("application/json", "{}")));
  CoreV1Api api = new CoreV1Api();

  api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
  WireMock.verify(
      1,
      getRequestedFor(urlPathEqualTo("/api/v1/pods"))
          .withHeader("Authorization", equalTo("Bearer token1")));

  this.auth.setFile(SERVICEACCOUNT_TOKEN2_PATH);
  api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
  WireMock.verify(
      2,
      getRequestedFor(urlPathEqualTo("/api/v1/pods"))
          .withHeader("Authorization", equalTo("Bearer token1")));

  this.auth.setExpiry(Instant.now().minusSeconds(1));
  api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
  WireMock.verify(
      1,
      getRequestedFor(urlPathEqualTo("/api/v1/pods"))
          .withHeader("Authorization", equalTo("Bearer token2")));
}
 
Example 5
Source File: StyxServerTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void canConfigureWithStyxOrigins() {
    styxServer = new StyxServer.Builder()
            .addRoute("/", origin(originServer1.port()))
            .addRoute("/o2/", origin(originServer2.port()))
            .start();

    HttpResponse response1 = await(client.sendRequest(get(format("http://localhost:%d/foo", styxServer.proxyHttpPort())).build()));
    assertThat(response1.status(), is(OK));
    assertThat(response1.header("origin"), isValue("first"));

    HttpResponse response2 = await(client.sendRequest(get(format("http://localhost:%d/o2/foo", styxServer.proxyHttpPort())).build()));
    assertThat(response2.status(), is(OK));
    assertThat(response2.header("origin"), isValue("second"));

    configureFor(originServer1.port());
    WireMock.verify(getRequestedFor(urlPathEqualTo("/foo")));
    configureFor(originServer2.port());
    WireMock.verify(getRequestedFor(urlPathEqualTo("/o2/foo")));
}
 
Example 6
Source File: InstanceProfileCredentialsProviderTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveCredentials_queriesTokenResource_403Error_fallbackToInsecure() {
    stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(403).withBody("oops")));
    stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile")));
    stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS)));

    InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build();

    provider.resolveCredentials();

    WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)));
    WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")));
}
 
Example 7
Source File: WireMockTestUtils.java    From junit-servers with MIT License 5 votes vote down vote up
/**
 * Verify that a given request has been triggered.
 *
 * @param endpoint Request endpoint.
 * @param method Request method.
 */
static void assertUploadRequest(String endpoint, HttpMethod method, File file) {
	UrlPattern urlPattern = urlEqualTo(endpoint);
	RequestMethod rqMethod = new RequestMethod(method.name());
	RequestPatternBuilder rq = new RequestPatternBuilder(rqMethod, urlPattern)
		.withAllRequestBodyParts(new MultipartValuePatternBuilder()
			.withName(file.getName())
			.withBody(new BinaryEqualToPattern(TestUtils.readFile(file)))
		);

	WireMock.verify(1, rq);
}
 
Example 8
Source File: EC2MetadataUtilsTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void getAmiId_queriesAndIncludesToken() {
    stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token")));
    stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}")));

    EC2MetadataUtils.getAmiId();

    WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600")));
    WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withHeader(TOKEN_HEADER, equalTo("some-token")));
}
 
Example 9
Source File: AutoConfigureWireMockRandomPortApplicationTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() throws Exception {
	wireMockServer.verify(0, RequestPatternBuilder.allRequests());
	WireMock.verify(0, RequestPatternBuilder.allRequests());

	stubFor(get(urlEqualTo("/test")).willReturn(aResponse()
			.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
	assertThat(this.service.go()).isEqualTo("Hello World!");

	wireMockServer.verify(1, RequestPatternBuilder.allRequests());
	WireMock.verify(1, RequestPatternBuilder.allRequests());
}
 
Example 10
Source File: InstanceProfileCredentialsProviderTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveCredentials_queriesTokenResource_405Error_fallbackToInsecure() {
    stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(405).withBody("oops")));
    stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile")));
    stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS)));

    InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build();

    provider.resolveCredentials();

    WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)));
    WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")));
}
 
Example 11
Source File: InstanceProfileCredentialsProviderTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveCredentials_queriesTokenResource_404Error_fallbackToInsecure() {
    stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(404).withBody("oops")));
    stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile")));
    stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS)));

    InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build();

    provider.resolveCredentials();

    WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)));
    WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")));
}
 
Example 12
Source File: ResponseTest.java    From verano-http with MIT License 5 votes vote down vote up
@Test
public void successfulResponse() {
    this.mock.stubFor(WireMock.get(WireMock.urlMatching("/.*"))
        .willReturn(WireMock.aResponse().withStatus(200))
    );
    new Response(
        String.format("http://localhost:%d", this.mock.port())
    ).touch();
    WireMock.verify(
        WireMock.getRequestedFor(WireMock.urlPathEqualTo("/"))
    );
}
 
Example 13
Source File: StyxServerTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void proxiesToOrigin() {
    styxServer = new StyxServer.Builder()
            .addRoute("/", originServer1.port())
            .start();

    HttpResponse response = await(client.sendRequest(get(format("https://localhost:%d/", styxServer.proxyHttpPort())).build()));

    assertThat(response.status(), is(OK));
    configureFor(originServer1.port());
    WireMock.verify(getRequestedFor(urlPathEqualTo("/")));
}
 
Example 14
Source File: EC2MetadataUtilsTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void getAmiId_queriesTokenResource_405Error_fallbackToInsecure() {
    stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(405).withBody("oops")));
    stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}")));

    EC2MetadataUtils.getAmiId();

    WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600")));
    WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER));
}
 
Example 15
Source File: ApacheWireTest.java    From verano-http with MIT License 5 votes vote down vote up
@Test
public void sendsGetRequestWithHeaders() throws Exception {
    this.mock.stubFor(WireMock.get(WireMock.urlMatching("/.*"))
        .willReturn(WireMock.aResponse().withStatus(200))
    );
    new ApacheWire(
        String.format("http://localhost:%d", this.mock.port()),
        new VrApacheClient(),
        new Accept("application/json")
    ).send(new Get("/items"));
    WireMock.verify(
        WireMock.getRequestedFor(WireMock.urlMatching("/items"))
            .withHeader("Accept", WireMock.containing("application/json"))
    );
}
 
Example 16
Source File: EC2MetadataUtilsTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void getAmiId_queriesTokenResource_403Error_fallbackToInsecure() {
    stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(403).withBody("oops")));
    stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}")));

    EC2MetadataUtils.getAmiId();

    WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600")));
    WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER));
}
 
Example 17
Source File: FakeHttpServer.java    From styx with Apache License 2.0 4 votes vote down vote up
public void verify(RequestPatternBuilder builder) {
    configureFor("localhost", adminPort());
    WireMock.verify(builder);
}
 
Example 18
Source File: FakeHttpServer.java    From styx with Apache License 2.0 4 votes vote down vote up
public void verify(int count, RequestPatternBuilder builder) {
    configureFor("localhost", adminPort());
    WireMock.verify(count, builder);
}
 
Example 19
Source File: FakeHttpServer.java    From styx with Apache License 2.0 4 votes vote down vote up
public void verify(RequestPatternBuilder builder) {
    configureFor("localhost", adminPort());
    WireMock.verify(builder);
}
 
Example 20
Source File: WireMockTestUtils.java    From junit-servers with MIT License 3 votes vote down vote up
/**
 * Verify that a given request has been triggered.
 *
 * @param endpoint Request endpoint.
 * @param method Request method.
 * @param headerName Header name.
 * @param headerValue Header value.
 */
static void assertRequestWithHeader(String endpoint, HttpMethod method, String headerName, String headerValue) {
	UrlPattern urlPattern = urlEqualTo(endpoint);
	RequestMethod rqMethod = new RequestMethod(method.name());
	RequestPatternBuilder rq = new RequestPatternBuilder(rqMethod, urlPattern);
	rq.withHeader(headerName, equalTo(headerValue));
	WireMock.verify(1, rq);
}