Best Testcontainers-java code snippet using org.testcontainers.elasticsearch.ElasticsearchContainerTest.getClusterHealth
Source:ElasticsearchContainerTest.java  
...266            )267        ) {268            // Start the container. This step might take some time...269            container.start();270            Response response = getClusterHealth(container);271            assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);272            assertThat(EntityUtils.toString(response.getEntity())).contains("cluster_name");273        }274    }275    @Test276    public void testElasticsearch8SecureByDefaultCustomCaCertFails() throws Exception {277        final MountableFile mountableFile = MountableFile.forClasspathResource("http_ca.crt");278        String caPath = "/tmp/http_ca.crt";279        try (280            ElasticsearchContainer container = new ElasticsearchContainer(281                "docker.elastic.co/elasticsearch/elasticsearch:8.1.2"282            )283                .withCopyToContainer(mountableFile, caPath)284                .withCertPath(caPath)285        ) {286            container.start();287            // this is expected, as a different cert is used for creating the SSL context288            assertThat(catchThrowable(() -> getClusterHealth(container)))289                .as(290                    "PKIX path validation failed: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors"291                )292                .isInstanceOf(SSLHandshakeException.class);293        }294    }295    @Test296    public void testElasticsearch8SecureByDefaultHttpWaitStrategy() throws Exception {297        final HttpWaitStrategy httpsWaitStrategy = Wait298            .forHttps("/")299            .forPort(9200)300            .forStatusCode(200)301            .withBasicCredentials(ELASTICSEARCH_USERNAME, ELASTICSEARCH_PASSWORD)302            // trusting self-signed certificate303            .allowInsecure();304        try (305            ElasticsearchContainer container = new ElasticsearchContainer(306                "docker.elastic.co/elasticsearch/elasticsearch:8.1.2"307            )308                .waitingFor(httpsWaitStrategy)309        ) {310            // Start the container. This step might take some time...311            container.start();312            Response response = getClusterHealth(container);313            assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);314            assertThat(EntityUtils.toString(response.getEntity())).contains("cluster_name");315        }316    }317    @Test318    public void testElasticsearch8SecureByDefaultFailsSilentlyOnLatestImages() throws Exception {319        // this test exists for custom images by users that use the `latest` tag320        // even though the version might be older than version 8321        // this tags an old 7.x version as :latest322        tagImage("docker.elastic.co/elasticsearch/elasticsearch:7.9.2", "elasticsearch-tc-older-release", "latest");323        DockerImageName image = DockerImageName324            .parse("elasticsearch-tc-older-release:latest")325            .asCompatibleSubstituteFor("docker.elastic.co/elasticsearch/elasticsearch");326        try (ElasticsearchContainer container = new ElasticsearchContainer(image)) {327            container.start();328            Response response = getClient(container).performRequest(new Request("GET", "/_cluster/health"));329            assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);330            assertThat(EntityUtils.toString(response.getEntity())).contains("cluster_name");331        }332    }333    @Test334    public void testElasticsearchDefaultMaxHeapSize() throws Exception {335        long defaultHeapSize = 2147483648L;336        try (ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)) {337            container.start();338            assertElasticsearchContainerHasHeapSize(container, defaultHeapSize);339        }340    }341    @Test342    public void testElasticsearchCustomMaxHeapSizeInEnvironmentVariable() throws Exception {343        long customHeapSize = 1574961152;344        try (345            ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)346                .withEnv("ES_JAVA_OPTS", String.format("-Xms%d  -Xmx%d", customHeapSize, customHeapSize))347        ) {348            container.start();349            assertElasticsearchContainerHasHeapSize(container, customHeapSize);350        }351    }352    @Test353    public void testElasticsearchCustomMaxHeapSizeInJvmOptionsFile() throws Exception {354        long customHeapSize = 1574961152;355        try (356            ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)357                .withClasspathResourceMapping(358                    "test-custom-memory-jvm.options",359                    "/usr/share/elasticsearch/config/jvm.options.d/a-user-defined-jvm.options",360                    BindMode.READ_ONLY361                );362        ) {363            container.start();364            assertElasticsearchContainerHasHeapSize(container, customHeapSize);365        }366    }367    private void tagImage(String sourceImage, String targetImage, String targetTag) throws InterruptedException {368        DockerClient dockerClient = DockerClientFactory.instance().client();369        dockerClient370            .tagImageCmd(new RemoteDockerImage(DockerImageName.parse(sourceImage)).get(), targetImage, targetTag)371            .exec();372    }373    private Response getClusterHealth(ElasticsearchContainer container) throws IOException {374        // Create the secured client.375        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();376        credentialsProvider.setCredentials(377            AuthScope.ANY,378            new UsernamePasswordCredentials(379                ELASTICSEARCH_USERNAME,380                ElasticsearchContainer.ELASTICSEARCH_DEFAULT_PASSWORD381            )382        );383        client =384            RestClient385                .builder(HttpHost.create("https://" + container.getHttpHostAddress()))386                .setHttpClientConfigCallback(httpClientBuilder -> {387                    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);...getClusterHealth
Using AI Code Generation
1import org.testcontainers.elasticsearch.ElasticsearchContainer;2import org.testcontainers.elasticsearch.ElasticsearchContainerProvider;3public class ElasticsearchContainerTest {4    public static void main(String[] args) {5        try (ElasticsearchContainer container = new ElasticsearchContainerProvider().newInstance("5.6.16")) {6            container.start();7            System.out.println(container.getClusterHealth());8        }9    }10}11{cluster_name=elasticsearch, status=green, timed_out=false, number_of_nodes=1, number_of_data_nodes=1, active_primary_shards=5, active_shards=5, relocating_shards=0, initializing_shards=0, unassigned_shards=0, delayed_unassigned_shards=0, number_of_pending_tasks=0, number_of_in_flight_fetch=0, task_max_waiting_in_queue_millis=0, active_shards_percent_as_number=100.0}getClusterHealth
Using AI Code Generation
1ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:6.7.0");2container.start();3RestHighLevelClient client = container.getClient();4GetClusterHealthRequest request = new GetClusterHealthRequest();5GetClusterHealthResponse response = client.cluster().health(request, RequestOptions.DEFAULT);6System.out.println("Cluster health status: " + response.getStatus());7container.stop();8}9}getClusterHealth
Using AI Code Generation
1ElasticsearchContainer container = new ElasticsearchContainer();2container.start();3RestClient restClient = container.getClient();4Response response = restClient.performRequest("GET", "_cluster/health");5System.out.println(EntityUtils.toString(response.getEntity()));6container.stop();7public void getClusterHealth() throws IOException {8    try (ElasticsearchContainer container = new ElasticsearchContainer()) {9        container.start();10        RestClient restClient = container.getClient();11        Response response = restClient.performRequest("GET", "_cluster/health");12        System.out.println(EntityUtils.toString(response.getEntity()));13    }14}15public void start() {16    super.start();17    if (getEnvMap().containsKey("ES_JAVA_OPTS")) {18        throw new IllegalStateException("ES_JAVA_OPTS is not supported by ElasticsearchContainer. " +19            "Please use withEnv method to pass custom JVM options");20    }21    String esJavaOpts = "-Xms" + getMemLimit() + "m -Xmx" + getMemLimit() + "m";22    withEnv("ES_JAVA_OPTS", esJavaOpts);23    this.restClient = RestClient.builder(HttpHost.create(getHttpHostAddress()))24        .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))25        .build();26}getClusterHealth
Using AI Code Generation
1org.testcontainers.elasticsearch.ElasticsearchContainer.getClusterHealth()2public String getClusterHealth()3public void stop()4public void close()5public void close(boolean removeVolumes)6public String getContainerIpAddress()7public Integer getMappedPort(int originalPort)8public String getClusterName()9public String getHttpHostAddress()10public String getTransportHostAddress()11public String getClusterHosts()12public String getInternalClusterHosts()13public String getElasticsearchVersion()14public String getElasticsearchVersion(boolean includeSnapshot)Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
