Best Testcontainers-java code snippet using org.testcontainers.elasticsearch.ElasticsearchContainerTest.getAnonymousClient
Source:ElasticsearchContainerTest.java  
...99            container.start();100            // The cluster should be secured so it must fail when we try to access / without credentials101            assertThrows("We should not be able to access / URI with an anonymous client.",102                ResponseException.class,103                () -> getAnonymousClient(container).performRequest(new Request("GET", "/")));104            // But it should work when we try to access / with the proper login and password105            Response response = getClient(container).performRequest(new Request("GET", "/"));106            assertThat(response.getStatusLine().getStatusCode(), is(200));107            assertThat(EntityUtils.toString(response.getEntity()), containsString(ELASTICSEARCH_VERSION));108        }109    }110    @Test111    public void elasticsearchVersion() throws IOException {112        try (ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)) {113            container.start();114            Response response = getClient(container).performRequest(new Request("GET", "/"));115            assertThat(response.getStatusLine().getStatusCode(), is(200));116            String responseAsString = EntityUtils.toString(response.getEntity());117            assertThat(responseAsString, containsString(ELASTICSEARCH_VERSION));118        }119    }120    @Test121    public void elasticsearchOssImage() throws IOException {122        try (ElasticsearchContainer container =123                 // ossContainer {124                 new ElasticsearchContainer(125                     DockerImageName126                         .parse("docker.elastic.co/elasticsearch/elasticsearch-oss")127                         .withTag(ELASTICSEARCH_VERSION)128                 )129             // }130        ) {131            container.start();132            Response response = getClient(container).performRequest(new Request("GET", "/"));133            assertThat(response.getStatusLine().getStatusCode(), is(200));134            // The OSS image does not have any feature under Elastic License135            assertThrows("We should not have /_xpack endpoint with an OSS License",136                ResponseException.class,137                () -> getClient(container).performRequest(new Request("GET", "/_xpack/")));138        }139    }140    @Test141    public void restClientClusterHealth() throws IOException {142        // httpClientContainer {143        // Create the elasticsearch container.144        try (ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)) {145            // Start the container. This step might take some time...146            container.start();147            // Do whatever you want with the rest client ...148            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();149            credentialsProvider.setCredentials(AuthScope.ANY,150                new UsernamePasswordCredentials(ELASTICSEARCH_USERNAME, ELASTICSEARCH_PASSWORD));151            client = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))152                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))153                .build();154            Response response = client.performRequest(new Request("GET", "/_cluster/health"));155            // }}156            assertThat(response.getStatusLine().getStatusCode(), is(200));157            assertThat(EntityUtils.toString(response.getEntity()), containsString("cluster_name"));158            // httpClientContainer {{159        }160        // }161    }162    @Test163    public void restClientSecuredClusterHealth() throws IOException {164        // httpClientSecuredContainer {165        // Create the elasticsearch container.166        try (ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)167            // With a password168            .withPassword(ELASTICSEARCH_PASSWORD)) {169            // Start the container. This step might take some time...170            container.start();171            // Create the secured client.172            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();173            credentialsProvider.setCredentials(AuthScope.ANY,174                new UsernamePasswordCredentials(ELASTICSEARCH_USERNAME, ELASTICSEARCH_PASSWORD));175            client = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))176                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))177                .build();178            Response response = client.performRequest(new Request("GET", "/_cluster/health"));179            // }}180            assertThat(response.getStatusLine().getStatusCode(), is(200));181            assertThat(EntityUtils.toString(response.getEntity()), containsString("cluster_name"));182            // httpClientSecuredContainer {{183        }184        // }185    }186    @SuppressWarnings("deprecation") // The TransportClient will be removed in Elasticsearch 8.187    @Test188    public void transportClientClusterHealth() {189        // transportClientContainer {190        // Create the elasticsearch container.191        try (ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)){192            // Start the container. This step might take some time...193            container.start();194            // Do whatever you want with the transport client195            TransportAddress transportAddress = new TransportAddress(container.getTcpHost());196            String expectedClusterName = "docker-cluster";197            Settings settings = Settings.builder().put("cluster.name", expectedClusterName).build();198            try (TransportClient transportClient = new PreBuiltTransportClient(settings)199                .addTransportAddress(transportAddress)) {200                ClusterHealthResponse healths = transportClient.admin().cluster().prepareHealth().get();201                String clusterName = healths.getClusterName();202                // }}}203                assertThat(clusterName, is(expectedClusterName));204                // transportClientContainer {{{205            }206        }207        // }208    }209    @Test210    public void incompatibleSettingsTest() {211        // The OSS image can not use security feature212        assertThrows("We should not be able to activate security with an OSS License",213            IllegalArgumentException.class,214            () -> new ElasticsearchContainer(215                DockerImageName216                    .parse("docker.elastic.co/elasticsearch/elasticsearch-oss")217                    .withTag(ELASTICSEARCH_VERSION))218            .withPassword("foo")219        );220    }221    private RestClient getClient(ElasticsearchContainer container) {222        if (client == null) {223            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();224            credentialsProvider.setCredentials(AuthScope.ANY,225                new UsernamePasswordCredentials(ELASTICSEARCH_USERNAME, ELASTICSEARCH_PASSWORD));226            client = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))227                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))228                .build();229        }230        return client;231    }232    private RestClient getAnonymousClient(ElasticsearchContainer container) {233        if (anonymousClient == null) {234            anonymousClient = RestClient.builder(HttpHost.create(container.getHttpHostAddress())).build();235        }236        return anonymousClient;237    }238}...getAnonymousClient
Using AI Code Generation
1ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.4");2container.start();3ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:6.5.4");4container.start();5ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.4");6container.start();7ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:6.5.4");8container.start();9ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.4");10container.start();11ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:6.5.4");12container.start();13ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.4");14container.start();15ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:6.5.4");16container.start();17ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.4");18container.start();19ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:6.5.4");20container.start();getAnonymousClient
Using AI Code Generation
1    private static final String ELASTICSEARCH_VERSION = "7.4.0";2    private static final String ELASTICSEARCH_IMAGE = "docker.elastic.co/elasticsearch/elasticsearch:" + ELASTICSEARCH_VERSION;3    public static ElasticsearchContainer container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)4            .withStartupAttempts(5)5            .withStartupTimeout(Duration.ofMinutes(10));6    public void test() {7        RestHighLevelClient client = container.getAnonymousClient();8        String username = container.getUsername();9        String password = container.getPassword();10        String httpHostAddress = container.getHttpHostAddress();11        String clusterName = container.getClusterName();12    }13}getAnonymousClient
Using AI Code Generation
1RestHighLevelClient anonymousClient = getAnonymousClient();2anonymousClient.indices().create(new CreateIndexRequest("test-container-index"),3        RequestOptions.DEFAULT);4anonymousClient.index(new IndexRequest("test-container-index").id("1").source(5        XContentType.JSON, "field", "value"), RequestOptions.DEFAULT);6GetResponse getResponse = anonymousClient.get(new GetRequest("test-container-index", "1"),7        RequestOptions.DEFAULT);8assertEquals("value", getResponse.getSource().get("field"));9anonymousClient.indices().delete(new DeleteIndexRequest("test-container-index"),10        RequestOptions.DEFAULT);11anonymousClient.close();12RestHighLevelClient client = new RestHighLevelClient(13        RestClient.builder(new HttpHost(elasticsearchContainer.getContainerIpAddress(),14                elasticsearchContainer.getMappedPort(9200), "http")));15client.indices().create(new CreateIndexRequest("test-container-index"), RequestOptions.DEFAULT);16client.index(new IndexRequest("test-container-index").id("1").source(XContentType.JSON, "field",17        "value"), RequestOptions.DEFAULT);18getResponse = client.get(new GetRequest("test-container-index", "1"), RequestOptions.DEFAULT);19assertEquals("value", getResponse.getSource().get("field"));20client.indices().delete(new DeleteIndexRequest("test-container-index"), RequestOptions.DEFAULT);21client.close();22elasticsearchContainer.stop();23elasticsearchContainer.close();24}25}getAnonymousClient
Using AI Code Generation
1public class ElasticsearchContainerTest {2    public void testGetAnonymousClient() throws Exception {3        final ElasticsearchContainer elasticsearchContainer = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:5.6.3");4        elasticsearchContainer.start();5        final Client client = elasticsearchContainer.getAnonymousClient();6        assertThat(client).isNotNull();7        final GetResponse response = client.prepareGet("twitter", "tweet", "1").get();8        assertThat(response.isExists()).isFalse();9        elasticsearchContainer.stop();10    }11}12[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ testcontainers-elasticsearch ---13[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ testcontainers-elasticsearch ---14[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ testcontainers-elasticsearch ---15[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ testcontainers-elasticsearch ---getAnonymousClient
Using AI Code Generation
1import org.testcontainers.elasticsearch.ElasticsearchContainer;2import org.testcontainers.elasticsearch.ElasticsearchContainerTest;3public class TestElasticsearchContainer {4    private static final String ELASTICSEARCH_VERSION = "6.4.2";5    public static void main(String[] args) {6        try (ElasticsearchContainer container = ElasticsearchContainerTest.getAnonymousClient(ELASTICSEARCH_VERSION)) {7            container.start();8            System.out.println("ElasticsearchContainer started");9        }10    }11}getAnonymousClient
Using AI Code Generation
1ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.4");2container.start();3ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:6.5.4");4container.start();5ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.4");6container.start();7ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:6.5.4");8container.start();9ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.4");10container.start();11ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:6.5.4");12container.start();13ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.4");14container.start();15ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:6.5.4");16container.start();17ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.4");18container.start();19ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:6.5.4");20container.start();getAnonymousClient
Using AI Code Generation
1import org.testcontainers.elasticsearch.ElasticsearchContainer;2import org.testcontainers.elasticsearch.ElasticsearchContainerTest;3public class TestElasticsearchContainer {4    private static final String ELASTICSEARCH_VERSION = "6.4.2";5    public static void main(String[] args) {6        try (ElasticsearchContainer container = ElasticsearchContainerTest.getAnonymousClient(ELASTICSEARCH_VERSION)) {7            container.start();8            System.out.println("ElasticsearchContainer started");9        }10    }11}12public class ElasticsearchContainerTest {13    public void testGetAnonymousClient() throws Exception {14        final ElasticsearchContainer elasticsearchContainer = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:5.6.3");15        elasticsearchContainer.start();16        final Client client = elasticsearchContainer.getAnonymousClient();17        assertThat(client).isNotNull();18        final GetResponse response = client.prepareGet("twitter", "tweet", "1").get();19        assertThat(response.isExists()).isFalse();20        elasticsearchContainer.stop();21    }22}23[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ testcontainers-elasticsearch ---24[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ testcontainers-elasticsearch ---25[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ testcontainers-elasticsearch ---26[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ testcontainers-elasticsearch ---getAnonymousClient
Using AI Code Generation
1import org.testcontainers.elasticsearch.ElasticsearchContainer;2import org.testcontainers.elasticsearch.ElasticsearchContainerTest;3public class TestElasticsearchContainer {4    private static final String ELASTICSEARCH_VERSION = "6.4.2";5    public static void main(String[] args) {6        try (ElasticsearchContainer container = ElasticsearchContainerTest.getAnonymousClient(ELASTICSEARCH_VERSION)) {7            container.start();8            System.out.println("ElasticsearchContainer started");9        }10    }11}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!!
