/** * {@inheritDoc} */ @Override public Integer getMappedPort(int originalPort) { return this.proxyContainer.getMappedPort(this.mappedPorts.get(originalPort)); }
/** * @return the port on which to check if the container is ready * @deprecated see {@link GenericContainer#getLivenessCheckPorts()} for replacement */ @Deprecated protected Integer getLivenessCheckPort() { // legacy implementation for backwards compatibility if (exposedPorts.size() > 0) { return getMappedPort(exposedPorts.get(0)); } else if (portBindings.size() > 0) { return Integer.valueOf(PortBinding.parse(portBindings.get(0)).getBinding().getHostPortSpec()); } else { return null; } }
@Test public void fetchPortsByNumber() { Integer firstMappedPort = container.getMappedPort(2424); Integer secondMappedPort = container.getMappedPort(2480); }
@SneakyThrows private Connection createSSHSession() { String password = UUID.randomUUID().toString(); container = new GenericContainer<>(TestcontainersConfiguration.getInstance().getSSHdImage()) .withExposedPorts(22) .withEnv("PASSWORD", password) .withCommand( "sh", "-c", // Disable ipv6 & Make it listen on all interfaces, not just localhost "echo \"root:$PASSWORD\" | chpasswd && /usr/sbin/sshd -D -o PermitRootLogin=yes -o AddressFamily=inet -o GatewayPorts=yes" ); container.start(); Connection connection = new Connection(container.getContainerIpAddress(), container.getMappedPort(22)); connection.setTCPNoDelay(true); connection.connect( (hostname, port, serverHostKeyAlgorithm, serverHostKey) -> true, (int) Duration.ofSeconds(30).toMillis(), (int) Duration.ofSeconds(30).toMillis() ); if (!connection.authenticateWithPassword("root", password)) { throw new IllegalStateException("Authentication failed."); } return connection; }
@Test public void simpleDslTest() throws IOException { String address = String.format("http://%s:%s", dslContainer.getContainerIpAddress(), dslContainer.getMappedPort(80)); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(address); try (CloseableHttpResponse response = httpClient.execute(get)) { assertEquals("A container built from a dockerfile can run nginx as expected, and returns a good status code", 200, response.getStatusLine().getStatusCode()); assertTrue("A container built from a dockerfile can run nginx as expected, and returns an expected Server header", response.getHeaders("Server")[0].getValue().contains("nginx")); } } }
@Test public void getContainerIpAddressAndMappedPort() { String address = container.getContainerIpAddress() + ":" + container.getMappedPort(2424); } }
@Test public void exceptionThrownWhenMappedPortNotFound() throws IOException { assertThrows("When the requested port is not mapped, getMappedPort() throws an exception", IllegalArgumentException.class, () -> { return redis.getMappedPort(666); }); }
@Test public void simpleMongoDbTest() { MongoClient mongoClient = new MongoClient(mongo.getContainerIpAddress(), mongo.getMappedPort(MONGO_PORT)); MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("testCollection"); Document doc = new Document("name", "foo") .append("value", 1); collection.insertOne(doc); Document doc2 = collection.find(new Document("name", "foo")).first(); assertEquals("A record can be inserted into and retrieved from MongoDB", 1, doc2.get("value")); }
@Test public void testFixedHostPortMapping() throws IOException { // first find a free port on the docker host that will work for testing GenericContainer portDiscoveryRedis = new GenericContainer("redis:3.0.2").withExposedPorts(REDIS_PORT); portDiscoveryRedis.start(); Integer freePort = portDiscoveryRedis.getMappedPort(REDIS_PORT); portDiscoveryRedis.stop(); // Set up a FixedHostPortGenericContainer as if this were a @Rule FixedHostPortGenericContainer redis = new FixedHostPortGenericContainer("redis:3.0.2").withFixedExposedPort(freePort, REDIS_PORT); redis.start(); // Config redisConfig = new Config(); // redisConfig.useSingleServer().setAddress(redis.getContainerIpAddress() + ":" + freePort); // Redisson redisson = Redisson.create(redisConfig); // // redisson.getBucket("test").set("foo"); // // assertEquals("The bucket content was successfully set", "foo", redisson.getBucket("test").get()); // assertEquals("The container returns the fixed port from getMappedPort(...)", freePort, redis.getMappedPort(REDIS_PORT)); } }
@Test public void simpleRabbitMqTest() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rabbitMq.getContainerIpAddress()); factory.setPort(rabbitMq.getMappedPort(RABBITMQ_PORT)); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(RABBIQMQ_TEST_EXCHANGE, "direct", true); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, RABBIQMQ_TEST_EXCHANGE, RABBITMQ_TEST_ROUTING_KEY); // Set up a consumer on the queue final boolean[] messageWasReceived = new boolean[1]; channel.basicConsume(queueName, false, new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { messageWasReceived[0] = Arrays.equals(body, RABBITMQ_TEST_MESSAGE.getBytes()); } }); // post a message channel.basicPublish(RABBIQMQ_TEST_EXCHANGE, RABBITMQ_TEST_ROUTING_KEY, null, RABBITMQ_TEST_MESSAGE.getBytes()); // check the message was received assertTrue("The message was received", Unreliables.retryUntilSuccess(5, TimeUnit.SECONDS, () -> { if (!messageWasReceived[0]) { throw new IllegalStateException("Message not received yet"); } return true; })); }
@Test public void testCompatibleValues() { boolean hasException = false; String url = new UrlResolver("mongodb", mongo.getContainerIpAddress(), mongo.getMappedPort(MONGO_DEFAULT_PORT)) .getUrl("mongodb", mongo.getContainerIpAddress()); try (MongoDB.Coll coll = MongoDB.Coll.Factory.create(url, "test", "test", true)) { Map<String, Object> document = coll.first(MapUtil.map("name", "testDocument")); assertNotNull(((Map<String, Object>) document.get("_id")).get("timestamp")); assertEquals(currentTime.getTime(), document.get("date")); assertEquals(longValue, document.get("longValue")); } catch (Exception e) { hasException = true; } assertFalse("should not have an exception", hasException); }
/** * {@inheritDoc} */ @Override public Integer getMappedPort(int originalPort) { return this.proxyContainer.getMappedPort(this.mappedPorts.get(originalPort)); }
@Test public void testObjectIdToStringMapping() { boolean hasException = false; String url = new UrlResolver("mongodb", mongo.getContainerIpAddress(), mongo.getMappedPort(MONGO_DEFAULT_PORT)) .getUrl("mongodb", mongo.getContainerIpAddress()); try (MongoDB.Coll coll = MongoDB.Coll.Factory.create(url, "test", "test", false)) { Map<String, Object> document = coll.first(MapUtil.map("name", "testDocument")); assertTrue(document.get("_id") instanceof String); } catch (Exception e) { hasException = true; } assertFalse("should not have an exception", hasException); }
@BeforeClass public static void setUp() throws Exception { TestUtil.ignoreException(() -> { mongo = new GenericContainer("mongo:3") .withNetworkAliases("mongo-" + Base58.randomString(6)) .withExposedPorts(MONGO_DEFAULT_PORT) .waitingFor(new HttpWaitStrategy() .forPort(MONGO_DEFAULT_PORT) .forStatusCodeMatching(response -> response == HTTP_OK || response == HTTP_UNAUTHORIZED) .withStartupTimeout(Duration.ofMinutes(2))); mongo.start(); }, Exception.class); assumeNotNull(mongo); assumeTrue("Mongo DB must be running", mongo.isRunning()); MongoClient mongoClient = new MongoClient(mongo.getContainerIpAddress(), mongo.getMappedPort(MONGO_DEFAULT_PORT)); HOST = String.format("mongodb://%s:%s", mongo.getContainerIpAddress(), mongo.getMappedPort(MONGO_DEFAULT_PORT)); params = map("host", HOST, "db", "test", "collection", "test"); MongoDatabase database = mongoClient.getDatabase("test"); collection = database.getCollection("test"); collection.deleteMany(new Document()); collection.insertOne(new Document(map("name", "testDocument", "date", currentTime, "longValue", longValue))); db = new TestGraphDatabaseFactory() .newImpermanentDatabaseBuilder() .newGraphDatabase(); TestUtil.registerProcedure(db, MongoDB.class); mongoClient.close(); }
@Override public int getPort() { return zookeeper.getMappedPort(ContainersProvider.ZOOKEEPER_PORT); } };
private static String tracesForServiceEndpoint(String service) { return format( "http://%s:%s/api/traces?service=%s", container.getContainerIpAddress(), container.getMappedPort(JAEGER_HTTP_PORT), service); } }
private static String thriftTracesEndpoint() { return format( "http://%s:%s/api/traces", container.getContainerIpAddress(), container.getMappedPort(JAEGER_HTTP_PORT_THRIFT)); }
private SpamAssassin(GenericContainer<?> spamAssassinContainer) { this.spamAssassinContainer = spamAssassinContainer; this.ip = spamAssassinContainer.getContainerIpAddress(); this.bindingPort = spamAssassinContainer.getMappedPort(SPAMASSASSIN_PORT); }
@Override protected SQLClient createClient(Vertx vertx, JsonObject config) { return MySQLClient.createNonShared(vertx, config.mergeIn(new JsonObject() .put("host", mysql.getContainerIpAddress()) .put("port", mysql.getMappedPort(3306)) .put("database", MYSQL_DATABASE) .put("username", MYSQL_USERNAME) .put("password", MYSQL_PASSWORD))); }
public RabbitMQOptions config() throws Exception { RabbitMQOptions config = new RabbitMQOptions(); config.setUri("amqp://" + rabbitmq.getContainerIpAddress() + ":" + rabbitmq.getMappedPort(5672)); return config; }