org.mockserver.client.MockServerClient Java Examples

The following examples show how to use org.mockserver.client.MockServerClient. 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: PGPKeysServerClientIT.java    From pgpverify-maven-plugin with Apache License 2.0 7 votes vote down vote up
@BeforeClass
public void setupMockServer() {
    mockServer = ClientAndServer.startClientAndServer(0);

    ConfigurationProperties.disableSystemOut(true);
    ConfigurationProperties.logLevel("WARNING");

    MockServerClient mockServerClient = new MockServerClient("localhost", mockServer.getLocalPort());

    mockServerClient
            .when(request().withPath("/sleep"))
            .respond(response()
                    .withStatusCode(200)
                    .withDelay(TimeUnit.SECONDS, 10));

    mockServerClient
            .when(request().withPath("/404"))
            .respond(response().withStatusCode(404));

    mockServerClient
            .when(request().withPath("/502"))
            .respond(response().withStatusCode(502));

}
 
Example #2
Source File: MsTeamsPublisherTest.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@Test
public void testPublish() {
    new MockServerClient("localhost", 1080)
            .when(
                    request()
                            .withMethod("POST")
                            .withPath("/mychannel")
            )
            .respond(
                    response()
                            .withStatusCode(200)
                            .withHeader(HttpHeaders.CONTENT_TYPE, "application/json")
            );
    JsonObject config = Json.createObjectBuilder().add("destination", "http://localhost:1080/mychannel").build();
    Notification notification = new Notification();
    notification.setScope(NotificationScope.PORTFOLIO.name());
    notification.setGroup(NotificationGroup.NEW_VULNERABILITY.name());
    notification.setLevel(NotificationLevel.INFORMATIONAL);
    notification.setTitle("Test Notification");
    notification.setContent("This is only a test");
    MsTeamsPublisher publisher = new MsTeamsPublisher();
    publisher.inform(notification, config);
}
 
Example #3
Source File: SlackPublisherTest.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@Test
public void testPublish() {
    new MockServerClient("localhost", 1080)
            .when(
                    request()
                            .withMethod("POST")
                            .withPath("/mychannel")
            )
            .respond(
                    response()
                            .withStatusCode(200)
                            .withHeader(HttpHeaders.CONTENT_TYPE, "application/json")
            );
    JsonObject config = Json.createObjectBuilder().add("destination", "http://localhost:1080/mychannel").build();
    Notification notification = new Notification();
    notification.setScope(NotificationScope.PORTFOLIO.name());
    notification.setGroup(NotificationGroup.NEW_VULNERABILITY.name());
    notification.setLevel(NotificationLevel.INFORMATIONAL);
    notification.setTitle("Test Notification");
    notification.setContent("This is only a test");
    SlackPublisher publisher = new SlackPublisher();
    publisher.inform(notification, config);
}
 
Example #4
Source File: MockServerTestHelper.java    From mutual-tls-ssl with Apache License 2.0 6 votes vote down vote up
public MockServerTestHelper(ClientType clientType) {
    clientAndServer = ClientAndServer.startClientAndServer(8080);
    mockServerClient = new MockServerClient("127.0.0.1", 8080);
    mockServerClient
            .when(
                    HttpRequest.request()
                            .withMethod("GET")
                            .withPath("/api/hello")
                            .withHeader("client-type", clientType.getValue()),
                    Times.unlimited(),
                    TimeToLive.unlimited())
            .respond(
                    HttpResponse.response()
                            .withBody("Hello")
                            .withStatusCode(200)
            );
}
 
Example #5
Source File: SampleResourceIT.java    From blog-tutorials with MIT License 6 votes vote down vote up
@Test
public void shouldReturnQuoteOfTheDay() {

    var resultQuote = Json.createObjectBuilder()
            .add("contents",
                    Json.createObjectBuilder().add("quotes",
                            Json.createArrayBuilder().add(Json.createObjectBuilder()
                                    .add("quote", "Do not worry if you have built your castles in the air. " +
                                            "They are where they should be. Now put the foundations under them."))))
            .build();

    new MockServerClient(mockServer.getContainerIpAddress(), mockServer.getServerPort())
            .when(request("/qod"))
            .respond(response().withBody(resultQuote.toString(), com.google.common.net.MediaType.JSON_UTF_8));

    var result = sampleEndpoint.getQuotes();

    System.out.println("Quote of the day: " + result);

    assertNotNull(result);
    assertFalse(result.isEmpty());
}
 
Example #6
Source File: WebhookPublisherTest.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@Test
public void testPublish() {
    new MockServerClient("localhost", 1080)
            .when(
                    request()
                            .withMethod("POST")
                            .withPath("/mychannel")
            )
            .respond(
                    response()
                            .withStatusCode(200)
                            .withHeader(HttpHeaders.CONTENT_TYPE, "application/json")
            );
    JsonObject config = Json.createObjectBuilder().add("destination", "http://localhost:1080/mychannel").build();
    Notification notification = new Notification();
    notification.setScope(NotificationScope.PORTFOLIO.name());
    notification.setGroup(NotificationGroup.NEW_VULNERABILITY.name());
    notification.setLevel(NotificationLevel.INFORMATIONAL);
    notification.setTitle("Test Notification");
    notification.setContent("This is only a test");
    WebhookPublisher publisher = new WebhookPublisher();
    publisher.inform(notification, config);
}
 
Example #7
Source File: FortifySscClientTest.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@Test
public void testUploadFindingsNegativeCase() throws Exception {
    String token = "db975c97-98b1-4988-8d6a-9c3e044dfff3";
    String applicationVersion = "";
    new MockServerClient("localhost", 1080)
            .when(
                    request()
                            .withMethod("POST")
                            .withHeader(HttpHeaders.ACCEPT, "application/xml")
                            .withPath("/ssc/upload/resultFileUpload.html?mat=" + token + "&engineType=DEPENDENCY_TRACK&entityId=" + applicationVersion)
                            .withQueryStringParameter("engineType", "DEPENDENCY_TRACK")
                            .withQueryStringParameter("mat", token)
                            .withQueryStringParameter("entityId", applicationVersion)
            )
            .respond(
                    response()
                            .withStatusCode(400)
                            .withHeader(HttpHeaders.CONTENT_TYPE, "application/xml")
            );
    FortifySscUploader uploader = new FortifySscUploader();
    FortifySscClient client = new FortifySscClient(uploader, new URL("https://localhost/ssc"));
    client.uploadDependencyTrackFindings(token, applicationVersion, new NullInputStream(16));
}
 
Example #8
Source File: FortifySscClientTest.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@Test
public void testUploadFindingsPositiveCase() throws Exception {
    String token = "db975c97-98b1-4988-8d6a-9c3e044dfff3";
    String applicationVersion = "12345";
    new MockServerClient("localhost", 1080)
            .when(
                    request()
                            .withMethod("POST")
                            .withHeader(HttpHeaders.ACCEPT, "application/xml")
                            .withPath("/ssc/upload/resultFileUpload.html?mat=" + token + "&engineType=DEPENDENCY_TRACK&entityId=" + applicationVersion)
                            .withQueryStringParameter("engineType", "DEPENDENCY_TRACK")
                            .withQueryStringParameter("mat", token)
                            .withQueryStringParameter("entityId", applicationVersion)
            )
            .respond(
                    response()
                            .withStatusCode(200)
                            .withHeader(HttpHeaders.CONTENT_TYPE, "application/xml")
            );
    FortifySscUploader uploader = new FortifySscUploader();
    FortifySscClient client = new FortifySscClient(uploader, new URL("https://localhost/ssc"));
    client.uploadDependencyTrackFindings(token, applicationVersion, new NullInputStream(0));
}
 
Example #9
Source File: MockServerContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void shouldReturnExpectation() throws Exception {
    // testSimpleExpectation {
    new MockServerClient(mockServer.getHost(), mockServer.getServerPort())
        .when(request()
            .withPath("/person")
            .withQueryStringParameter("name", "peter"))
        .respond(response()
            .withBody("Peter the person!"));

    // ...a GET request to '/person?name=peter' returns "Peter the person!"
    // }

    assertThat("Expectation returns expected response body",
        responseFromMockserver(mockServer, "/person?name=peter"),
        containsString("Peter the person")
    );
}
 
Example #10
Source File: MockServerContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void shouldCallActualMockserverVersion() throws Exception {
    String actualVersion = MockServerClient.class.getPackage().getImplementationVersion();
    try (MockServerContainer mockServer = new MockServerContainer(actualVersion)) {
        mockServer.start();

        String expectedBody = "Hello World!";

        new MockServerClient(mockServer.getHost(), mockServer.getServerPort())
            .when(request().withPath("/hello"))
            .respond(response().withBody(expectedBody));

        assertThat("MockServer returns correct result",
            responseFromMockserver(mockServer, "/hello"),
            equalTo(expectedBody)
        );
    }
}
 
Example #11
Source File: FortifySscClientTest.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@Test
public void testOneTimeTokenInvalidCredentials() throws Exception {
    new MockServerClient("localhost", 1080)
            .when(
                    request()
                            .withMethod("POST")
                            .withHeader(HttpHeaders.AUTHORIZATION, HttpUtil.basicAuthHeaderValue("admin", "wrong"))
                            .withPath("/ssc/api/v1/fileTokens")
                            .withBody("{\"fileTokenType\":\"UPLOAD\"}")
            )
            .respond(
                    response()
                            .withStatusCode(401)
            );
    FortifySscUploader uploader = new FortifySscUploader();
    FortifySscClient client = new FortifySscClient(uploader, new URL("https://localhost/ssc"));
    String token = client.generateOneTimeUploadToken("admin", "wrong");
    Assert.assertNull(token);
}
 
Example #12
Source File: FortifySscClientTest.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@Test
public void testOneTimeTokenPositiveCase() throws Exception {
    new MockServerClient("localhost", 1080)
            .when(
                    request()
                            .withMethod("POST")
                            .withHeader(HttpHeaders.AUTHORIZATION, HttpUtil.basicAuthHeaderValue("admin", "admin"))
                            .withPath("/ssc/api/v1/fileTokens")
                            .withBody("{\"fileTokenType\":\"UPLOAD\"}")
            )
            .respond(
                    response()
                            .withStatusCode(201)
                            .withHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                            .withBody("{ \"data\": { \"token\": \"db975c97-98b1-4988-8d6a-9c3e044dfff3\" }}")
            );
    FortifySscUploader uploader = new FortifySscUploader();
    FortifySscClient client = new FortifySscClient(uploader, new URL("https://localhost/ssc"));
    String token = client.generateOneTimeUploadToken("admin", "admin");
    Assert.assertEquals("db975c97-98b1-4988-8d6a-9c3e044dfff3", token);
}
 
Example #13
Source File: DeployApiTest.java    From bdt with Apache License 2.0 6 votes vote down vote up
@Test
public void example() throws Exception {
    setEnvs();
    String endpoint = "/service/";
    endpoint = endpoint.concat(ThreadProperty.get("deploy_api_id")).concat("/deployments");

    String responsePath = baseResponsePath.concat("getAppsResponseOK.json");
    String response = new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource(responsePath).getFile())));

    new MockServerClient("localhost", port)
        .when(
            request()
                .withMethod("GET")
                .withPath(endpoint)
        )
        .respond(
            response()
                .withStatusCode(200)
                .withBody(response)
        );

    BaseResponseList<DeployedApp> responseList = deployApiClient.getDeployedApps();
    assertThat(responseList.getList()).as("List should not be empty").isNotEmpty();
    assertThat(responseList.getList().size()).as("Response elements do not match").isEqualTo(16);
}
 
Example #14
Source File: MockClientServerFacade.java    From cukes with Apache License 2.0 5 votes vote down vote up
@Inject
public MockClientServerFacade(GlobalWorldFacade worldFacade) {
    this.worldFacade = worldFacade;

    services = new ConcurrentHashMap<>();
    servers = new ConcurrentHashMap<>();

    String servicesProperty = worldFacade.get("http.mock.services")
        .or(
            () -> {
                throw new CukesRuntimeException("No mocks defined in cukes.properties file. please add cukes.http.mock.services value");
            }
        );
    for (String serviceName : servicesProperty.split(",")) {
        MockServerClient client = new MockServerClient(
            worldFacade.get("http.mock.services." + serviceName + ".host", "localhost"),
            Integer.parseInt(worldFacade.get("http.mock.services." + serviceName + ".port")
                .or(
                    () -> {
                        throw new CukesRuntimeException("No port provided for mock service " + serviceName + ". Please provide property cukes.http.mock.services." + serviceName + ".port");
                    })
            )
        );
        services.put(serviceName, client);
    }

}
 
Example #15
Source File: MockClientServerFacade.java    From cukes with Apache License 2.0 5 votes vote down vote up
public MockServerClient getMockServerClient(String serviceName) {
    return services.computeIfAbsent(serviceName, key -> {
        String availableMockServices = services.keySet().stream().collect(Collectors.joining(", "));
        throw new CukesRuntimeException("Unable to find http mock service by name:" + key + ". " +
            "Available mock services are: {" + availableMockServices + "}");
    });
}
 
Example #16
Source File: DependentServiceIT.java    From microshed-testing with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatePerson() {
    Person expectedPerson = new Person("Hank", 42, 5L);
    new MockServerClient(mockServer.getContainerIpAddress(), mockServer.getServerPort())
                    .when(request("/mock-passthrough/person/5"))
                    .respond(response().withBody(jsonb.toJson(expectedPerson), MediaType.JSON_UTF_8));

    Person actualPerson = personSvc.getPersonFromExternalService(5);
    assertEquals("Hank", actualPerson.name);
    assertEquals(42, actualPerson.age);
    assertEquals(5, actualPerson.id);
}
 
Example #17
Source File: DependentServiceTest.java    From microprofile-sandbox with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatePerson() {
    Person expectedPerson = new Person("Hank", 42, 5L);
    new MockServerClient(mockServer.getContainerIpAddress(), mockServer.getServerPort())
                    .when(request("/mock-passthrough/person/5"))
                    .respond(response().withBody(jsonb.toJson(expectedPerson), MediaType.JSON_UTF_8));

    Person actualPerson = personSvc.getPersonFromExternalService(5);
    assertEquals("Hank", actualPerson.name);
    assertEquals(42, actualPerson.age);
    assertEquals(5, actualPerson.id);
}
 
Example #18
Source File: ClientTest.java    From geoportal-server-harvester with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws IOException {
  client = new MockServerClient("localhost", 5000);
  client.when(
                  request()
                  .withMethod("GET")
                  .withPath("/robots.txt")
          )
          .respond(
                  response()
                  .withStatusCode(200)
                  .withBody(readAndClose(getClass().getResourceAsStream("/robots.txt")))
          );
  client.when(
                  request()
                  .withMethod("GET")
                  .withQueryStringParameter("request", "GetCapabilities")
                  .withQueryStringParameter("service", "CSW")
                  .withPath("/csw")
          )
          .respond(
                  response()
                  .withStatusCode(200)
                  .withHeaders(
                    new Header("Content-Type", "application/xml; charset=utf-8")
                  )
                  .withBody(readAndClose(getClass().getResourceAsStream("/GetCapabilitiesResponse.xml")))
          );
  client.when(
                  request()
                  .withMethod("POST")
                  .withPath("/csw")
          )
          .respond(
                  response()
                  .withStatusCode(200)
                  .withHeaders(
                    new Header("Content-Type", "application/xml; charset=utf-8")
                  )
                  .withBody(readAndClose(getClass().getResourceAsStream("/GetRecordsResponse.xml")))
          );
  client.when(
                  request()
                  .withMethod("GET")
                  .withQueryStringParameter("request", "GetRecordById")
                  .withQueryStringParameter("service", "CSW")
                  .withPath("/csw")
          )
          .respond(
                  response()
                  .withStatusCode(200)
                  .withHeaders(
                    new Header("Content-Type", "application/xml; charset=utf-8")
                  )
                  .withBody(readAndClose(getClass().getResourceAsStream("/GetRecordByIdResponse.xml")))
          );
}
 
Example #19
Source File: MockServerImpl.java    From Insights with Apache License 2.0 4 votes vote down vote up
/**
 * This function will read all json files from getAllMockRequestsFromJson method
 * and create expectations from the given Paths and Response in the individual
 * tool's json.
 */
public void startMockServerWithExpectations() {
	// Starting mock server on port 1080.
	MockServerClient mockServer = startClientAndServer(1080);
	// Reading mock requests from multiple JSON files.
	List<MockRequest> mockRequests = getAllMockRequestsFromJson();
	String response = null;
	
	Iterator<MockRequest> mockIterator = mockRequests.iterator();
	while (mockIterator.hasNext()) {
		
		MockRequest request = mockIterator.next();
		List<Parameter> parameterList = new ArrayList<>();
		
		if(request.isResponseJson()) {
			response = request.getResponse().get(0).toString();
		} else {
			response = request.getResponse().toString();	
		}
		
		// checking if the request has any parameters.
		if(request.getParameters() != null) {
			for (Map.Entry<String,String> paramEntry : request.getParameters().entrySet()) {
				
				Parameter param = new Parameter(paramEntry.getKey(), paramEntry.getValue());
				parameterList.add(param);
			}
		}
		
		// Creating mock Expectation 
		mockServer
		.when(
				request()
				.withPath(request.getPath())
				.withQueryStringParameters(parameterList)
			)
		.respond(
				response()
				.withStatusCode(200)
				.withBody(response)
				);
		
		log.debug("Expectation created for the path {} with query string parmeters {}",request.getPath(),parameterList);
	}
	log.info("Mock Server Started");
 }
 
Example #20
Source File: MockServerContainer.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
public MockServerClient getClient() {
    return client;
}
 
Example #21
Source File: MockServerContainer.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
@Override
protected void containerIsStarted(InspectContainerResponse containerInfo) {
    super.containerIsStarted(containerInfo);
    client = new MockServerClient(getContainerIpAddress(), getFirstMappedPort());
}