Skip to content

Commit ae580cb

Browse files
committed
Fix after review
Closes #19
1 parent 9cf3721 commit ae580cb

File tree

3 files changed

+107
-67
lines changed

3 files changed

+107
-67
lines changed

README.md

Lines changed: 3 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -234,72 +234,9 @@ An example of how to set the `TARANTOOL_CLUSTER_COOKIE` parameter: https://githu
234234

235235
##### Mapping ports
236236

237-
Often there is a need to connect to a container via a certain port. To achieve this goal, you need to know the mapped
238-
port of the port that was specified from the Java code. To get the mapped port use the `getMappedPort(...)` method
239-
of testcontainers API.
240-
241-
As an example, consider the following Java code:
242-
243-
```java
244-
import org.junit.ClassRule;
245-
import org.junit.Test;
246-
import org.junit.rules.ExternalResource;
247-
import org.slf4j.Logger;
248-
import org.slf4j.LoggerFactory;
249-
import org.testcontainers.containers.GenericContainer;
250-
import org.testcontainers.containers.TarantoolCartridgeContainer;
251-
252-
import java.io.IOException;
253-
import java.net.HttpURLConnection;
254-
import java.net.URL;
255-
256-
public class AppTest {
257-
258-
private final Logger logger = LoggerFactory.getLogger(AppTest.class);
259-
260-
private static final GenericContainer<?> container =
261-
new TarantoolCartridgeContainer("cartridge/instances.yml", "cartridge/topology.lua")
262-
.withDirectoryBinding("cartridge")
263-
.withRouterHost("localhost")
264-
.withRouterPort(3301)
265-
// Open http port in container
266-
.withAPIPort(8081)
267-
.withRouterUsername("admin")
268-
.withRouterPassword("tarantool-cartridge-starter-cluster-cookie")
269-
.withReuse(true);
270-
271-
@ClassRule
272-
public static ExternalResource resource = new ExternalResource() {
273-
@Override
274-
public void before() {
275-
container.start();
276-
}
277-
@Override
278-
public void after() {
279-
container.stop();
280-
}
281-
};
282-
283-
284-
@Test
285-
public void shouldAnswerWithTrue() throws IOException {
286-
// Get mapped port
287-
final int mappedHttpPort = container.getMappedPort(8081);
288-
// Get metrics response
289-
final String metricsResponse = sendRequestAndGetResponse("http://localhost:" + mappedHttpPort + "/metrics");
290-
logger.info("Metric response: {}", metricsResponse);
291-
final String helloResponse = sendRequestAndGetResponse("http://localhost:" + mappedHttpPort + "/hello");
292-
logger.info("Hello response: {}", helloResponse);
293-
}
294-
295-
private String sendRequestAndGetResponse(final String urlSource) throws IOException {
296-
final URL url = new URL(urlSource);
297-
// Connect to the URL with mapped port
298-
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
299-
return connection.getResponseMessage();
300-
}
301-
}
302-
```
237+
Often there is a need to connect to a container through a specific port. To achieve this goal it is necessary
238+
know the mapped port specified in the Java code. To get the mapped port, use the getMappedPort(...)` method of
239+
testcontainers API. See examples:
303240

304241

305242
## License

pom.xml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,12 @@
9292
</dependency>
9393

9494
<!-- Test dependencies -->
95-
<dependency>
95+
<dependency>
96+
<groupId>org.apache.httpcomponents</groupId>
97+
<artifactId>httpclient</artifactId>
98+
<version>4.5.1</version>
99+
</dependency>
100+
<dependency>
96101
<groupId>ch.qos.logback</groupId>
97102
<artifactId>logback-classic</artifactId>
98103
<version>1.3.4</version>
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
package org.testcontainers.containers;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.net.Socket;
7+
import java.time.Duration;
8+
import java.util.concurrent.ThreadLocalRandom;
9+
10+
import org.apache.http.HttpResponse;
11+
import org.apache.http.client.methods.HttpGet;
12+
import org.apache.http.impl.client.CloseableHttpClient;
13+
import org.apache.http.impl.client.HttpClientBuilder;
14+
import org.junit.jupiter.api.Test;
15+
import org.slf4j.LoggerFactory;
16+
import org.testcontainers.containers.output.Slf4jLogConsumer;
17+
import org.testcontainers.junit.jupiter.Container;
18+
import static org.junit.jupiter.api.Assertions.assertEquals;
19+
import static org.junit.jupiter.api.Assertions.assertFalse;
20+
import static org.junit.jupiter.api.Assertions.assertTrue;
21+
22+
public class TarantoolCartridgePortMappingTest {
23+
24+
@Container
25+
private final static TarantoolCartridgeContainer container = new TarantoolCartridgeContainer(
26+
"Dockerfile",
27+
"mapping-ports-container",
28+
"cartridge/instances.yml",
29+
"cartridge/replicasets.yml")
30+
.withEnv(TarantoolCartridgeContainer.ENV_TARANTOOL_CLUSTER_COOKIE, "secret")
31+
.withRouterUsername("admin")
32+
.withRouterPassword("secret")
33+
.withStartupTimeout(Duration.ofMinutes(5))
34+
.withLogConsumer(new Slf4jLogConsumer(
35+
LoggerFactory.getLogger(TarantoolCartridgeBootstrapFromYamlTest.class)));
36+
37+
@Test
38+
void portMappingTest() throws IOException {
39+
40+
final int httpPortToFirstRouter = 8081;
41+
final int httpPortToSecondRouter = 8082;
42+
final int portToFirstRouter = 3301;
43+
final int portToSecondRouter = 3302;
44+
final String url = "localhost";
45+
46+
container.addExposedPorts(httpPortToFirstRouter, httpPortToSecondRouter);
47+
container.start();
48+
49+
final StringBuilder curlCommandToConnectToRouters = new StringBuilder("http://localhost:")
50+
.append(container.getMappedPort(httpPortToFirstRouter));
51+
52+
// send get request to first router via http
53+
HttpResponse response = sendCurlToRouterHttpAPI(curlCommandToConnectToRouters.toString());
54+
assertEquals(200, response.getStatusLine().getStatusCode());
55+
56+
curlCommandToConnectToRouters.delete(0, curlCommandToConnectToRouters.length())
57+
.append("http://localhost:")
58+
.append(container.getMappedPort(httpPortToSecondRouter));
59+
60+
// send get request to second router via http
61+
response = sendCurlToRouterHttpAPI(curlCommandToConnectToRouters.toString());
62+
assertEquals(200, response.getStatusLine().getStatusCode());
63+
64+
// connect to first router via socket
65+
String result = connectToRouterViaSocket(url, container.getMappedPort(portToFirstRouter));
66+
assertFalse(result.isEmpty());
67+
assertTrue(result.contains("Tarantool"));
68+
69+
// connect to second router via socket
70+
result = connectToRouterViaSocket(url, container.getMappedPort(portToSecondRouter));
71+
assertFalse(result.isEmpty());
72+
assertTrue(result.contains("Tarantool"));
73+
74+
// Connect to random port
75+
result = connectToRouterViaSocket(url, ThreadLocalRandom.current().nextInt(49152, 65535));
76+
assertTrue(result.isEmpty());
77+
}
78+
79+
private HttpResponse sendCurlToRouterHttpAPI(String url) throws IOException {
80+
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
81+
HttpGet httpGetRequest = new HttpGet(url);
82+
return httpClient.execute(httpGetRequest);
83+
}
84+
}
85+
86+
private String connectToRouterViaSocket(String url, int port) {
87+
final String returnedString;
88+
89+
try (Socket socket = new Socket(url, port);
90+
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
91+
92+
returnedString = in.readLine();
93+
} catch (IOException e) {
94+
return "";
95+
}
96+
return returnedString;
97+
}
98+
}

0 commit comments

Comments
 (0)