Java Code Examples for org.mockserver.integration.ClientAndServer#startClientAndServer()

The following examples show how to use org.mockserver.integration.ClientAndServer#startClientAndServer() . 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: 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 3
Source File: HealthCheckServiceUnitTest.java    From galeb with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setupClass() {
    environmentVariables.set("ENVIRONMENT_NAME", "env1");
    environmentVariables.set("ZONE_ID", "zone1");
    
    mockServer = ClientAndServer.startClientAndServer(BACKEND_PORT);

    mockServer.when(HttpRequest.request()
                    .withMethod("GET")
                    .withPath("/")
                    .withHeaders(
                            Header.header("user-agent", "Galeb_HealthChecker/1.0"),
                            Header.header(NottableString.not("cookie")))
                    .withKeepAlive(true))
              .respond(HttpResponse.response()
                    .withCookie(new Cookie("session", "test-cookie"))
                    .withStatusCode(HttpStatus.OK.value()));
    
    mockTCPOnlyServer();
}
 
Example 4
Source File: CollaboratorServiceExTests.java    From HubTurbo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void getCollaborators_validRepoId_successful() throws IOException {
    MockServerClient mockServer = ClientAndServer.startClientAndServer(8888);
    String sampleCollaborators = TestUtils.readFileFromResource(this, "tests/CollaboratorsSample.json");

    mockServer.when(
            request()
                .withPath(TestUtils.API_PREFIX + "/repos/hubturbo/tests/collaborators")
    ).respond(response().withBody(sampleCollaborators));

    Type listOfUsers = new TypeToken<List<User>>() {}.getType();
    List<User> expectedCollaborators = new Gson().fromJson(sampleCollaborators, listOfUsers);
    List<User> actualCollaborators = service.getCollaborators(RepositoryId.createFromId("hubturbo/tests"));

    assertEquals(expectedCollaborators.size(), actualCollaborators.size());

    for (int i = 0; i < expectedCollaborators.size(); i++) {
        assertEquals(expectedCollaborators.get(i).getLogin(), actualCollaborators.get(i).getLogin());
        assertEquals(expectedCollaborators.get(i).getName(), actualCollaborators.get(i).getName());
        assertEquals(true, actualCollaborators.get(i).getName() != null);
    }

    mockServer.stop();
}
 
Example 5
Source File: OdooXmlRpcProxyTest.java    From openerp-java-api with Apache License 2.0 6 votes vote down vote up
@Test
public void should_return_server_version() throws Exception {
	// Make sure SSL works by adding MockServer CA certificate to context
	SSLSocketFactory previousFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
	HttpsURLConnection.setDefaultSSLSocketFactory(SSLFactory.getInstance().sslContext().getSocketFactory());
	ClientAndServer mockServer = ClientAndServer.startClientAndServer(port);
	try {
		// Given: the server expects a request of its version
		mockServer
				.when(request().withMethod("POST").withPath("/xmlrpc/2/db")
						.withBody(new StringBody(
								"<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>server_version</methodName><params/></methodCall>")))
				.respond(response().withStatusCode(200).withBody(
						"<?xml version='1.0'?>\n<methodResponse>\n<params>\n<param>\n<value><string>9.0e</string></value>\n</param>\n</params>\n</methodResponse>\n"));

		// When: Server version is requested
		Version version = OdooXmlRpcProxy.getServerVersion(RPCProtocol.RPC_HTTPS, host, port);

		// Then: the server version is returned
		assertThat(version).as("Server version").isNotNull().hasToString("9.0e");
	} finally {
		mockServer.stop();
		HttpsURLConnection.setDefaultSSLSocketFactory(previousFactory);
	}

}
 
Example 6
Source File: MetadataTestServer.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
/**
 * Start the server.
 *
 * @return This instance, for chaining.
 */
@SuppressWarnings("BusyWait")
public MetadataTestServer start() {
    mockServer = ClientAndServer.startClientAndServer(port);

    // Set the response for "/latest"

    latest(latest);

    // Set the responses for the "${version}/cli-data.zip" requests, with and without etags

    for (TestVersion version : TestVersion.values()) {
        zipData(version, TestMetadata.zipData(version));
    }

    // Ensure started

    int retries = 5;
    while (!mockServer.isRunning()) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (--retries > 0) {
            Log.info("Waiting for metadata test server to start, remaining retries = %s", retries);
        } else {
            stop();
            throw new IllegalStateException("Metadata test server did not start.");
        }
    }
    Log.info("Started metadata test server with latest=%s at %s", latest, url);
    return this;
}
 
Example 7
Source File: PullRequestServiceExTests.java    From HubTurbo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Tests that getReviewComments method correctly receives 1 page of review comments
 * returned from a MockServer that emulates GitHub API service.
 */
@Test
public void testGetReviewComments() throws IOException {
    MockServerClient mockServer = ClientAndServer.startClientAndServer(8888);
    String sampleComments = TestUtils.readFileFromResource(this, "tests/ReviewCommentsSample.json");

    mockServer.when(
            request()
                    .withPath(TestUtils.API_PREFIX + "/repos/hubturbo/hubturbo/pulls/1125/comments")
                    .withQueryStringParameters(
                            new Parameter("per_page", "100"),
                            new Parameter("page", "1")
                    )
    ).respond(response().withBody(sampleComments));

    GitHubClient client = new GitHubClient("localhost", 8888, "http");
    PullRequestServiceEx service = new PullRequestServiceEx(client);

    Type listOfComments = new TypeToken<List<ReviewComment>>() {
    }.getType();
    List<ReviewComment> expectedComments = new Gson().fromJson(sampleComments, listOfComments);
    List<ReviewComment> actualComments = service.getReviewComments(
            RepositoryId.createFromId("hubturbo/hubturbo"), 1125);

    assertEquals(expectedComments.size(), actualComments.size());

    Comparator<ReviewComment> comparator = (a, b) -> (int) (a.getId() - b.getId());
    Collections.sort(expectedComments, comparator);
    Collections.sort(actualComments, comparator);

    for (int i = 0; i < expectedComments.size(); i++) {
        assertEquals(expectedComments.get(i).getId(), actualComments.get(i).getId());
    }

    mockServer.stop();

}
 
Example 8
Source File: BaseClientTest.java    From bdt with Apache License 2.0 5 votes vote down vote up
protected void startMockServer() throws Exception {
    ConfigurationProperties.logLevel("ERROR");
    port  = PortFactory.findFreePort();
    logger.info("Starting mock server...");
    mockServer = ClientAndServer.startClientAndServer(port);
    logger.info("Mock sever started.");
}
 
Example 9
Source File: FileDownloadManagerIntegrationTest.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@BeforeClass
public static void startServer() {
    mockServer = ClientAndServer.startClientAndServer(4242);

    mockServer
        .when(HttpRequest.request().withMethod("GET").withPath("/test.txt"))
        .respond(HttpResponse.response()
            .withStatusCode(200)
            .withHeader("Content-Type", "text/plain; charset=utf-8")
            .withBody("Hello World!"));

    mockServer
        .when(HttpRequest.request().withMethod("GET").withPath("/404"))
        .respond(HttpResponse.response().withStatusCode(404));
}
 
Example 10
Source File: SessionTest.java    From openerp-java-api with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startProxy() throws Exception {
	if (isUsingMockServer()) {
		previousFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
		HttpsURLConnection.setDefaultSSLSocketFactory(SSLFactory.getInstance().sslContext().getSocketFactory());
		proxy = ClientAndProxy.startClientAndProxy(PortFactory.findFreePort());
		mockServer = ClientAndServer.startClientAndServer(MOCKSERVER_PORT);
	}
}
 
Example 11
Source File: PageHeaderIteratorTests.java    From HubTurbo with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Tests that a PageHeaderIterator correctly retrieves ETag headers for 3 pages from
 * a mocked server that conform to GitHub API's pagination specifications and terminates afterwards.
 *
 * @throws NoSuchElementException
 */
@Test
public void testHeaderIterator() throws NoSuchElementException, IOException {
    MockServerClient mockServer = ClientAndServer.startClientAndServer(8888);

    HttpRequest page1Request = createMockServerPagedHeaderRequest(1);
    List<Header> page1Headers = TestUtils.parseHeaderRecord(
            TestUtils.readFileFromResource(this, "tests/PagedHeadersSample/page1-header.txt"));
    String page1Etag = "aaf65fc6b10d5afbdc9cd0aa6e6ada4c";

    HttpRequest page2Request = createMockServerPagedHeaderRequest(2);
    List<Header> page2Headers = TestUtils.parseHeaderRecord(
            TestUtils.readFileFromResource(this, "tests/PagedHeadersSample/page2-header.txt"));
    String page2Etag = "731501e0f7d9816305782bc4c3f70d9f";

    HttpRequest page3Request = createMockServerPagedHeaderRequest(3);
    List<Header> page3Headers = TestUtils.parseHeaderRecord(
            TestUtils.readFileFromResource(this, "tests/PagedHeadersSample/page3-header.txt")
    );
    String page3Etag = "a6f367d674155d6fbbacbc2fca04917b";

    setUpHeadRequestOnMockServer(mockServer, page1Request, page1Headers);
    setUpHeadRequestOnMockServer(mockServer, page2Request, page2Headers);
    setUpHeadRequestOnMockServer(mockServer, page3Request, page3Headers);

    PagedRequest<Milestone> request = new PagedRequest<>();
    Map<String, String> params = new HashMap<>();
    params.put("state", "all");

    GitHubClientEx client = new GitHubClientEx("localhost", 8888, "http");

    String path = SEGMENT_REPOS + "/hubturbo/hubturbo" + SEGMENT_PULLS;
    request.setUri(path);
    request.setResponseContentType(CONTENT_TYPE_JSON);
    request.setParams(params);

    PageHeaderIterator iter = new PageHeaderIterator(request, client, "ETag");
    assertEquals(page1Etag, Utility.stripQuotes(iter.next()));
    assertEquals(page2Etag, Utility.stripQuotes(iter.next()));
    assertEquals(page3Etag, Utility.stripQuotes(iter.next()));
    assertFalse(iter.hasNext());

    mockServer.stop();
}
 
Example 12
Source File: TunnelTest.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public void startProxy()
    throws IOException {
  mockServer = ClientAndServer.startClientAndServer(0);
  PORT = mockServer.getPort();
}
 
Example 13
Source File: LowLatencyMontageClientTest.java    From render with GNU General Public License v2.0 4 votes vote down vote up
@BeforeClass
public static void before() throws Exception {
    mockServerPort = PortFactory.findFreePort();
    mockServer = ClientAndServer.startClientAndServer(mockServerPort);
}
 
Example 14
Source File: SimpleHttpClientIntegrationTest.java    From alf.io with GNU General Public License v3.0 4 votes vote down vote up
@BeforeClass
public static void startServer() {
    mockServer = ClientAndServer.startClientAndServer(4243);
}
 
Example 15
Source File: IntegrationTest.java    From zulip-plugin with MIT License 4 votes vote down vote up
@BeforeClass
public static void startMockServer() {
    mockServer = ClientAndServer.startClientAndServer(1080);
}
 
Example 16
Source File: ZulipTest.java    From zulip-plugin with MIT License 4 votes vote down vote up
@BeforeClass
public static void startMockServer() {
    mockServer = ClientAndServer.startClientAndServer(1080);
}