How to use checkNotRunning method of org.testcontainers.couchbase.CouchbaseContainer class

Best Testcontainers-java code snippet using org.testcontainers.couchbase.CouchbaseContainer.checkNotRunning

Source:CouchbaseContainer.java Github

copy

Full Screen

...81 * @param password the password for the admin user.82 * @return this {@link CouchbaseContainer} for chaining purposes.83 */84 public CouchbaseContainer withCredentials(final String username, final String password) {85 checkNotRunning();86 this.username = username;87 this.password = password;88 return this;89 }90 public CouchbaseContainer withBucket(final BucketDefinition bucketDefinition) {91 checkNotRunning();92 this.buckets.add(bucketDefinition);93 return this;94 }95 public CouchbaseContainer withEnabledServices(final CouchbaseService... enabled) {96 checkNotRunning();97 this.enabledServices = EnumSet.copyOf(Arrays.asList(enabled));98 return this;99 }100 public final String getUsername() {101 return username;102 }103 public final String getPassword() {104 return password;105 }106 public int getBootstrapCarrierDirectPort() {107 return getMappedPort(KV_PORT);108 }109 public int getBootstrapHttpDirectPort() {110 return getMappedPort(MGMT_PORT);111 }112 public String getConnectionString() {113 return String.format("couchbase://%s:%d", getContainerIpAddress(), getBootstrapCarrierDirectPort());114 }115 @Override116 protected void configure() {117 super.configure();118 WaitAllStrategy waitStrategy = new WaitAllStrategy();119 // Makes sure that all nodes in the cluster are healthy.120 waitStrategy = waitStrategy.withStrategy(121 new HttpWaitStrategy()122 .forPath("/pools/default")123 .forPort(MGMT_PORT)124 .withBasicCredentials(username, password)125 .forStatusCode(200)126 .forResponsePredicate(response -> {127 try {128 return Optional.of(MAPPER.readTree(response))129 .map(n -> n.at("/nodes/0/status"))130 .map(JsonNode::asText)131 .map("healthy"::equals)132 .orElse(false);133 } catch (IOException e) {134 logger().error("Unable to parse response {}", response);135 return false;136 }137 })138 );139 if (enabledServices.contains(CouchbaseService.QUERY)) {140 waitStrategy = waitStrategy.withStrategy(141 new HttpWaitStrategy()142 .forPath("/admin/ping")143 .forPort(QUERY_PORT)144 .withBasicCredentials(username, password)145 .forStatusCode(200)146 );147 }148 waitingFor(waitStrategy);149 }150 @Override151 protected void containerIsStarting(final InspectContainerResponse containerInfo) {152 logger().debug("Couchbase container is starting, performing configuration.");153 waitUntilNodeIsOnline();154 renameNode();155 initializeServices();156 configureAdminUser();157 configureExternalPorts();158 if (enabledServices.contains(CouchbaseService.INDEX)) {159 configureIndexer();160 }161 }162 @Override163 protected void containerIsStarted(InspectContainerResponse containerInfo) {164 createBuckets();165 logger().info("Couchbase container is ready! UI available at http://{}:{}", getContainerIpAddress(), getMappedPort(MGMT_PORT));166 }167 /**168 * Before we can start configuring the host, we need to wait until the cluster manager is listening.169 */170 private void waitUntilNodeIsOnline() {171 new HttpWaitStrategy()172 .forPort(MGMT_PORT)173 .forPath("/pools")174 .forStatusCode(200)175 .waitUntilReady(this);176 }177 /**178 * Rebinds/renames the internal hostname.179 * <p>180 * To make sure the internal hostname is different from the external (alternate) address and the SDK can pick it181 * up automatically, we bind the internal hostname to the internal IP address.182 */183 private void renameNode() {184 logger().debug("Renaming Couchbase Node from localhost to {}", getContainerIpAddress());185 Response response = doHttpRequest(MGMT_PORT, "/node/controller/rename", "POST", new FormBody.Builder()186 .add("hostname", getInternalIpAddress())187 .build(), false188 );189 checkSuccessfulResponse(response, "Could not rename couchbase node");190 }191 /**192 * Initializes services based on the configured enabled services.193 */194 private void initializeServices() {195 logger().debug("Initializing couchbase services on host: {}", enabledServices);196 final String services = enabledServices.stream().map(s -> {197 switch (s) {198 case KV: return "kv";199 case QUERY: return "n1ql";200 case INDEX: return "index";201 case SEARCH: return "fts";202 default: throw new IllegalStateException("Unknown service!");203 }204 }).collect(Collectors.joining(","));205 Response response = doHttpRequest(MGMT_PORT, "/node/controller/setupServices", "POST", new FormBody.Builder()206 .add("services", services)207 .build(), false208 );209 checkSuccessfulResponse(response, "Could not enable couchbase services");210 }211 /**212 * Configures the admin user on the couchbase node.213 * <p>214 * After this stage, all subsequent API calls need to have the basic auth header set.215 */216 private void configureAdminUser() {217 logger().debug("Configuring couchbase admin user with username: \"{}\"", username);218 Response response = doHttpRequest(MGMT_PORT, "/settings/web", "POST", new FormBody.Builder()219 .add("username", username)220 .add("password", password)221 .add("port", Integer.toString(MGMT_PORT))222 .build(), false);223 checkSuccessfulResponse(response, "Could not configure couchbase admin user");224 }225 /**226 * Configures the external ports for SDK access.227 * <p>228 * Since the internal ports are not accessible from outside the container, this code configures the "external"229 * hostname and services to align with the mapped ports. The SDK will pick it up and then automatically connect230 * to those ports. Note that for all services non-ssl and ssl ports are configured.231 */232 private void configureExternalPorts() {233 logger().debug("Mapping external ports to the alternate address configuration");234 final FormBody.Builder builder = new FormBody.Builder();235 builder.add("hostname", getContainerIpAddress());236 builder.add("mgmt", Integer.toString(getMappedPort(MGMT_PORT)));237 builder.add("mgmtSSL", Integer.toString(getMappedPort(MGMT_SSL_PORT)));238 if (enabledServices.contains(CouchbaseService.KV)) {239 builder.add("kv", Integer.toString(getMappedPort(KV_PORT)));240 builder.add("kvSSL", Integer.toString(getMappedPort(KV_SSL_PORT)));241 builder.add("capi", Integer.toString(getMappedPort(VIEW_PORT)));242 builder.add("capiSSL", Integer.toString(getMappedPort(VIEW_SSL_PORT)));243 }244 if (enabledServices.contains(CouchbaseService.QUERY)) {245 builder.add("n1ql", Integer.toString(getMappedPort(QUERY_PORT)));246 builder.add("n1qlSSL", Integer.toString(getMappedPort(QUERY_SSL_PORT)));247 }248 if (enabledServices.contains(CouchbaseService.SEARCH)) {249 builder.add("fts", Integer.toString(getMappedPort(SEARCH_PORT)));250 builder.add("ftsSSL", Integer.toString(getMappedPort(SEARCH_SSL_PORT)));251 }252 final Response response = doHttpRequest(253 MGMT_PORT,254 "/node/controller/setupAlternateAddresses/external",255 "PUT",256 builder.build(),257 true258 );259 checkSuccessfulResponse(response, "Could not configure external ports");260 }261 /**262 * Configures the indexer service so that indexes can be created later on the bucket.263 */264 private void configureIndexer() {265 logger().debug("Configuring the indexer service");266 Response response = doHttpRequest(MGMT_PORT, "/settings/indexes", "POST", new FormBody.Builder()267 .add("storageMode", "memory_optimized")268 .build(), true269 );270 checkSuccessfulResponse(response, "Could not configure the indexing service");271 }272 /**273 * Based on the user-configured bucket definitions, creating buckets and corresponding indexes if needed.274 */275 private void createBuckets() {276 logger().debug("Creating " + buckets.size() + " buckets (and corresponding indexes).");277 for (BucketDefinition bucket : buckets) {278 logger().debug("Creating bucket \"" + bucket.getName() + "\"");279 Response response = doHttpRequest(MGMT_PORT, "/pools/default/buckets", "POST", new FormBody.Builder()280 .add("name", bucket.getName())281 .add("ramQuotaMB", Integer.toString(bucket.getQuota()))282 .build(), true);283 checkSuccessfulResponse(response, "Could not create bucket " + bucket.getName());284 new HttpWaitStrategy()285 .forPath("/pools/default/buckets/" + bucket.getName())286 .forPort(MGMT_PORT)287 .withBasicCredentials(username, password)288 .forStatusCode(200)289 .waitUntilReady(this);290 if (bucket.hasPrimaryIndex()) {291 if (enabledServices.contains(CouchbaseService.QUERY)) {292 Response queryResponse = doHttpRequest(QUERY_PORT, "/query/service", "POST", new FormBody.Builder()293 .add("statement", "CREATE PRIMARY INDEX on `" + bucket.getName() + "`")294 .build(), true);295 checkSuccessfulResponse(queryResponse, "Could not create primary index for bucket " + bucket.getName());296 } else {297 logger().info("Primary index creation for bucket " + bucket.getName() + " ignored, since QUERY service is not present.");298 }299 }300 }301 }302 /**303 * Helper method to extract the internal IP address based on the network configuration.304 */305 private String getInternalIpAddress() {306 return getContainerInfo().getNetworkSettings().getNetworks().values().stream()307 .findFirst()308 .map(ContainerNetwork::getIpAddress)309 .orElseThrow(() -> new IllegalStateException("No network available to extract the internal IP from!"));310 }311 /**312 * Helper method to check if the response is successful and release the body if needed.313 *314 * @param response the response to check.315 * @param message the message that should be part of the exception of not successful.316 */317 private void checkSuccessfulResponse(final Response response, final String message) {318 try {319 if (!response.isSuccessful()) {320 throw new IllegalStateException(message + ": " + response.toString());321 }322 } finally {323 if (response.body() != null) {324 response.body().close();325 }326 }327 }328 /**329 * Checks if already running and if so raises an exception to prevent too-late setters.330 */331 private void checkNotRunning() {332 if (isRunning()) {333 throw new IllegalStateException("Setter can only be called before the container is running");334 }335 }336 /**337 * Helper method to perform a request against a couchbase server HTTP endpoint.338 *339 * @param port the (unmapped) original port that should be used.340 * @param path the relative http path.341 * @param method the http method to use.342 * @param body if present, will be part of the payload.343 * @param auth if authentication with the admin user and password should be used.344 * @return the response of the request.345 */...

Full Screen

Full Screen

checkNotRunning

Using AI Code Generation

copy

Full Screen

1 try (CouchbaseContainer couchbase = new CouchbaseContainer()) {2 couchbase.start();3 couchbase.checkNotRunning();4 }5 }6}7public void checkNotRunning() {8 if (isRunning()) {9 throw new IllegalStateException("This container is already running");10 }11}12public void stop() {13 if (isRunning()) {14 super.stop();15 }16}17public void start() {18 if (!isRunning()) {19 super.start();20 }21}22public boolean isRunning() {23 return super.isRunning();24}25public int getBootstrapCarrierDirectPort() {26 return getMappedPort(BOOTSTRAP_DIRECT_PORT);27}28public int getBootstrapHttpDirectPort() {29 return getMappedPort(BOOTSTRAP_HTTP_DIRECT_PORT);30}31public int getBootstrapCarrierSslPort() {32 return getMappedPort(BOOTSTRAP_SSL_PORT);33}34public int getBootstrapHttpSslPort() {35 return getMappedPort(BOOTSTRAP_HTTP_SSL_PORT);36}37public int getBootstrapCarrierDirectPort() {38 return getMappedPort(BOOTSTRAP_DIRECT_PORT);39}40public int getBootstrapHttpDirectPort() {41 return getMappedPort(BOOTSTRAP_HTTP_DIRECT_PORT);42}43public int getBootstrapCarrierSslPort() {44 return getMappedPort(BOOTSTRAP_SSL_PORT);45}46public int getBootstrapHttpSslPort() {47 return getMappedPort(BOOTSTRAP

Full Screen

Full Screen

checkNotRunning

Using AI Code Generation

copy

Full Screen

1public class CouchbaseContainer extends GenericContainer<CouchbaseContainer> {2 public boolean checkNotRunning() {3 return super.isRunning();4 }5}6public class CouchbaseContainerTest {7 public void testCheckNotRunning() {8 CouchbaseContainer couchbase = new CouchbaseContainer();9 couchbase.start();10 Assert.assertTrue(couchbase.checkNotRunning());11 couchbase.stop();12 Assert.assertFalse(couchbase.checkNotRunning());13 }14}15 at org.testcontainers.containers.GenericContainer.tryStart(GenericContainer.java:345)16 at org.testcontainers.containers.GenericContainer.lambda$doStart$0(GenericContainer.java:317)17 at org.rnorth.ducttape.unreliables.Unreliables.retryUntilSuccess(Unreliables.java:81)18 at org.testcontainers.containers.GenericContainer.doStart(GenericContainer.java:315)19 at org.testcontainers.containers.GenericContainer.start(GenericContainer.java:303)20 at org.testcontainers.containers.CouchbaseContainer.start(CouchbaseContainer.java:68)21 at org.testcontainers.containers.CouchbaseContainerTest.testCheckNotRunning(CouchbaseContainerTest.java:15)22 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)23 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)24 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)25 at java.lang.reflect.Method.invoke(Method.java:498)26 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)27 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)28 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)29 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)30 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)31 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)32 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)33 at org.junit.runners.ParentRunner$3.run(Parent

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful