@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; }
protected GenericContainer startContainerWithCommand(String shellCommand, WaitStrategy waitStrategy, Integer... ports) { // apply WaitStrategy to container return new GenericContainer(IMAGE_NAME) .withExposedPorts(ports) .withCommand("sh", "-c", shellCommand) .waitingFor(waitStrategy.withStartupTimeout(Duration.ofMillis(WAIT_TIMEOUT_MILLIS))); }
@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)); } }
@Override @Deprecated protected void starting(Description description) { if (this instanceof TestLifecycleAware) { ((TestLifecycleAware) this).beforeTest(toDescription(description)); } this.start(); }
@Test(expected = NotFoundException.class) public void copyFromContainerShouldFailBecauseNoFileTest() throws NotFoundException { try ( GenericContainer alpineCopyToContainer = new GenericContainer("alpine:3.2") .withCommand("top") ) { alpineCopyToContainer.start(); alpineCopyToContainer.copyFileFromContainer("/home/test.txt", "src/test/resources/copy-from/test.txt"); } }
@Bean(name = BEAN_NAME_EMBEDDED_VOLTDB, destroyMethod = "stop") public GenericContainer voltDB(ConfigurableEnvironment environment, VoltDBProperties properties, VoltDBStatusCheck voltDbStatusCheck) { log.info("Starting VoltDB server. Docker image: {}", properties.dockerImage); GenericContainer voltDB = new GenericContainer(properties.dockerImage) .withEnv("HOST_COUNT", "1") .withLogConsumer(containerLogsConsumer(log)) .withExposedPorts(properties.port) .waitingFor(voltDbStatusCheck) .withStartupTimeout(properties.getTimeoutDuration()); voltDB.start(); registerVoltDBEnvironment(voltDB, environment, properties); return voltDB; }
@SuppressWarnings("resource") public DockerCassandra() { client = DockerClientFactory.instance().client(); cassandraContainer = new GenericContainer<>("cassandra:3.11.3") .withCreateContainerCmdModifier(cmd -> cmd.getHostConfig().withTmpFs(ImmutableMap.of("/var/lib/cassandra", "rw,noexec,nosuid,size=200m"))) .withExposedPorts(CASSANDRA_PORT) .withLogConsumer(DockerCassandra::displayDockerLog); cassandraContainer .waitingFor(new CassandraWaitStrategy(cassandraContainer)); }
@BeforeClass void before() throws Exception { SvnTestHelper.skipTestIfDockerUnavailable(); String gitlabVersion = System.getenv("GITLAB_VERSION"); if (gitlabVersion == null) { if (System.getenv("TRAVIS") != null) throw new SkipException("Only run gitlab tests on Travis when explicitly asked"); gitlabVersion = "latest"; } final int gitlabPort = 80; gitlab = new GenericContainer<>("gitlab/gitlab-ce:" + gitlabVersion) .withEnv("GITLAB_ROOT_PASSWORD", rootPassword) .withExposedPorts(gitlabPort) .waitingFor(Wait.forHttp("/users/sign_in") .withStartupTimeout(Duration.of(10, ChronoUnit.MINUTES))); gitlab.start(); gitlabUrl = "http://" + gitlab.getContainerIpAddress() + ":" + gitlab.getMappedPort(gitlabPort); rootToken = createToken(root, rootPassword, true); final GitlabAPI rootAPI = GitLabContext.connect(gitlabUrl, rootToken); final GitlabUser gitlabUser = rootAPI.createUser(new CreateUserRequest(user, user, "git-as-svn@localhost").setPassword(userPassword)); Assert.assertNotNull(gitlabUser); final GitlabGroup group = rootAPI.createGroup(new CreateGroupRequest("testGroup").setVisibility(GitlabVisibility.PUBLIC), null); Assert.assertNotNull(group); Assert.assertNotNull(rootAPI.addGroupMember(group.getId(), gitlabUser.getId(), GitlabAccessLevel.Developer)); gitlabProject = createGitlabProject(rootAPI, group, "test", GitlabVisibility.INTERNAL, Collections.singleton("git-as-svn")); gitlabPublicProject = createGitlabProject(rootAPI, group, "publik", GitlabVisibility.PUBLIC, Collections.emptySet()); }
); GenericContainer container = new GenericContainer(image) .withStartupCheckStrategy(new OneShotStartupCheckStrategy()) .withLogConsumer(consumer); container.start(); container.stop();
@Test public void getContainerIpAddressAndMappedPort() { String address = container.getContainerIpAddress() + ":" + container.getMappedPort(2424); } }
@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(); }
public static void main(String[] args) { Thread mainThread = Thread.currentThread(); GenericContainer genericContainer = null; try { genericContainer = new GenericContainer().withCommand("top"); genericContainer.start(); Set<Thread> threads = new HashSet<>(Thread.getAllStackTraces().keySet()); threads.remove(mainThread); Set<Thread> nonDaemonThreads = threads.stream().filter(it -> !it.isDaemon()).collect(Collectors.toSet()); if (nonDaemonThreads.isEmpty()) { VisibleAssertions.pass("All threads marked as daemon"); } else { String nonDaemonThreadNames = nonDaemonThreads.stream() .map(Thread::getName) .collect(Collectors.joining("\n", "\n", "")); VisibleAssertions.fail("Expected all threads to be daemons but the following are not:\n" + nonDaemonThreadNames); } } finally { if (genericContainer != null) { genericContainer.stop(); } } }
@Test public void testNetworkSupport() throws Exception { try ( Network network = newNetwork(); GenericContainer foo = new GenericContainer() .withNetwork(network) .withNetworkAliases("foo") .withCommand("/bin/sh", "-c", "while true ; do printf 'HTTP/1.1 200 OK\\n\\nyay' | nc -l -p 8080; done"); GenericContainer bar = new GenericContainer() .withNetwork(network) .withCommand("top") ) { foo.start(); bar.start(); String response = bar.execInContainer("wget", "-O", "-", "http://foo:8080").getStdout(); assertEquals("received response", "yay", response); } }
/** Starts a docker container optionally. For example, skips if Docker is unavailable. */ @SuppressWarnings("rawtypes") @BeforeClass public static void startContainer() { try { container = new GenericContainer(JAEGER_IMAGE) .withExposedPorts(JAEGER_HTTP_PORT, JAEGER_HTTP_PORT_THRIFT) .waitingFor(new HttpWaitStrategy()); container.start(); } catch (RuntimeException e) { throw new AssumptionViolatedException("could not start docker container", e); } }
@Test public void checkFileCopied() throws IOException, InterruptedException { try( GenericContainer container = new GenericContainer("alpine:latest") .withCommand("sleep","3000") .withCopyFileToContainer(MountableFile.forClasspathResource("/mappable-resource/"), containerPath) ) { container.start(); String filesList = container.execInContainer("ls","/tmp/mappable-resource").getStdout(); Assert.assertTrue(filesList.contains(fileName)); } } }
protected void verifyImage(ImageFromDockerfile image) { GenericContainer container = new GenericContainer(image); try { container.start(); pass("Should start from Dockerfile"); } finally { container.stop(); } } }
@Test public void withTmpFsTest() throws Exception { try ( GenericContainer container = new GenericContainer() .withCommand("top") .withTmpFs(singletonMap("/testtmpfs", "rw")) ) { container.start(); // check file doesn't exist String path = "/testtmpfs/test.file"; Container.ExecResult execResult = container.execInContainer("ls", path); assertEquals("tmpfs inside container works fine", execResult.getStderr(), "ls: /testtmpfs/test.file: No such file or directory\n"); // touch && check file does exist container.execInContainer("touch", path); execResult = container.execInContainer("ls", path); assertEquals("tmpfs inside container works fine", execResult.getStdout(), path + "\n"); } }
@Test public void testIsRunning() { try (GenericContainer container = new GenericContainer().withCommand("top")) { assertFalse("Container is not started and not running", container.isRunning()); container.start(); assertTrue("Container is started and running", container.isRunning()); } }
@Test public void test() { try (final GenericContainer container = new GenericContainer<>(image) .withCommand("/bin/sh", "-c", "sleep 0") .withStartupCheckStrategy(new OneShotStartupCheckStrategy())) { container.start(); // do nothing other than start and stop } } }
@Test public void sharedMemorySetTest() { try (GenericContainer containerWithSharedMemory = new GenericContainer("busybox:1.29") .withSharedMemorySize(1024L * FileUtils.ONE_MB)) { containerWithSharedMemory.start(); HostConfig hostConfig = containerWithSharedMemory.getDockerClient().inspectContainerCmd(containerWithSharedMemory.getContainerId()) .exec().getHostConfig(); assertEquals("Shared memory not set on container", hostConfig.getShmSize(), 1024 * FileUtils.ONE_MB); } } }