Skip to content

Commit

Permalink
Fix after review
Browse files Browse the repository at this point in the history
Closes #19
  • Loading branch information
nickkkccc committed Jan 15, 2024
1 parent 9cf3721 commit ae580cb
Show file tree
Hide file tree
Showing 3 changed files with 107 additions and 67 deletions.
69 changes: 3 additions & 66 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,72 +234,9 @@ An example of how to set the `TARANTOOL_CLUSTER_COOKIE` parameter: https://githu

##### Mapping ports

Often there is a need to connect to a container via a certain port. To achieve this goal, you need to know the mapped
port of the port that was specified from the Java code. To get the mapped port use the `getMappedPort(...)` method
of testcontainers API.

As an example, consider the following Java code:

```java
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.TarantoolCartridgeContainer;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class AppTest {

private final Logger logger = LoggerFactory.getLogger(AppTest.class);

private static final GenericContainer<?> container =
new TarantoolCartridgeContainer("cartridge/instances.yml", "cartridge/topology.lua")
.withDirectoryBinding("cartridge")
.withRouterHost("localhost")
.withRouterPort(3301)
// Open http port in container
.withAPIPort(8081)
.withRouterUsername("admin")
.withRouterPassword("tarantool-cartridge-starter-cluster-cookie")
.withReuse(true);

@ClassRule
public static ExternalResource resource = new ExternalResource() {
@Override
public void before() {
container.start();
}
@Override
public void after() {
container.stop();
}
};


@Test
public void shouldAnswerWithTrue() throws IOException {
// Get mapped port
final int mappedHttpPort = container.getMappedPort(8081);
// Get metrics response
final String metricsResponse = sendRequestAndGetResponse("http://localhost:" + mappedHttpPort + "/metrics");
logger.info("Metric response: {}", metricsResponse);
final String helloResponse = sendRequestAndGetResponse("http://localhost:" + mappedHttpPort + "/hello");
logger.info("Hello response: {}", helloResponse);
}

private String sendRequestAndGetResponse(final String urlSource) throws IOException {
final URL url = new URL(urlSource);
// Connect to the URL with mapped port
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
return connection.getResponseMessage();
}
}
```
Often there is a need to connect to a container through a specific port. To achieve this goal it is necessary
know the mapped port specified in the Java code. To get the mapped port, use the getMappedPort(...)` method of
testcontainers API. See examples:


## License
Expand Down
7 changes: 6 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,12 @@
</dependency>

<!-- Test dependencies -->
<dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.3.4</version>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package org.testcontainers.containers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.output.Slf4jLogConsumer;
import org.testcontainers.junit.jupiter.Container;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class TarantoolCartridgePortMappingTest {

@Container
private final static TarantoolCartridgeContainer container = new TarantoolCartridgeContainer(
"Dockerfile",
"mapping-ports-container",
"cartridge/instances.yml",
"cartridge/replicasets.yml")
.withEnv(TarantoolCartridgeContainer.ENV_TARANTOOL_CLUSTER_COOKIE, "secret")
.withRouterUsername("admin")
.withRouterPassword("secret")
.withStartupTimeout(Duration.ofMinutes(5))
.withLogConsumer(new Slf4jLogConsumer(
LoggerFactory.getLogger(TarantoolCartridgeBootstrapFromYamlTest.class)));

@Test
void portMappingTest() throws IOException {

final int httpPortToFirstRouter = 8081;
final int httpPortToSecondRouter = 8082;
final int portToFirstRouter = 3301;
final int portToSecondRouter = 3302;
final String url = "localhost";

container.addExposedPorts(httpPortToFirstRouter, httpPortToSecondRouter);
container.start();

final StringBuilder curlCommandToConnectToRouters = new StringBuilder("http://localhost:")
.append(container.getMappedPort(httpPortToFirstRouter));

// send get request to first router via http
HttpResponse response = sendCurlToRouterHttpAPI(curlCommandToConnectToRouters.toString());
assertEquals(200, response.getStatusLine().getStatusCode());

curlCommandToConnectToRouters.delete(0, curlCommandToConnectToRouters.length())
.append("http://localhost:")
.append(container.getMappedPort(httpPortToSecondRouter));

// send get request to second router via http
response = sendCurlToRouterHttpAPI(curlCommandToConnectToRouters.toString());
assertEquals(200, response.getStatusLine().getStatusCode());

// connect to first router via socket
String result = connectToRouterViaSocket(url, container.getMappedPort(portToFirstRouter));
assertFalse(result.isEmpty());
assertTrue(result.contains("Tarantool"));

// connect to second router via socket
result = connectToRouterViaSocket(url, container.getMappedPort(portToSecondRouter));
assertFalse(result.isEmpty());
assertTrue(result.contains("Tarantool"));

// Connect to random port
result = connectToRouterViaSocket(url, ThreadLocalRandom.current().nextInt(49152, 65535));
assertTrue(result.isEmpty());
}

private HttpResponse sendCurlToRouterHttpAPI(String url) throws IOException {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpGet httpGetRequest = new HttpGet(url);
return httpClient.execute(httpGetRequest);
}
}

private String connectToRouterViaSocket(String url, int port) {
final String returnedString;

try (Socket socket = new Socket(url, port);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

returnedString = in.readLine();
} catch (IOException e) {
return "";
}
return returnedString;
}
}

0 comments on commit ae580cb

Please sign in to comment.