Search in sources :

Example 26 with GenericContainer

use of org.testcontainers.containers.GenericContainer in project spring-boot by spring-projects.

the class PaketoBuilderTests method plainWarApp.

@Test
void plainWarApp() throws Exception {
    writeMainClass();
    writeServletInitializerClass();
    String imageName = "paketo-integration/" + this.gradleBuild.getProjectDir().getName();
    ImageReference imageReference = ImageReference.of(ImageName.of(imageName));
    BuildResult result = buildImage(imageName);
    assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
    try (GenericContainer<?> container = new GenericContainer<>(imageName).withExposedPorts(8080)) {
        container.waitingFor(Wait.forHttp("/test")).start();
        ContainerConfig config = container.getContainerInfo().getConfig();
        ImageAssertions.assertThat(config).buildMetadata((metadata) -> {
            metadata.buildpacks().contains("paketo-buildpacks/ca-certificates", "paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/apache-tomcat", "paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot");
            metadata.processOfType("web").extracting("command", "args").containsExactly("bash", Arrays.asList("catalina.sh", "run"));
            metadata.processOfType("tomcat").extracting("command", "args").containsExactly("bash", Arrays.asList("catalina.sh", "run"));
        });
        assertImageHasSbomLayer(imageReference, config, "apache-tomcat");
        DigestCapturingCondition digest = new DigestCapturingCondition();
        ImageAssertions.assertThat(config).lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest));
        ImageAssertions.assertThat(imageReference).layer(digest.getDigest(), (layer) -> layer.entries().contains("WEB-INF/classes/example/ExampleApplication.class", "WEB-INF/classes/example/HelloController.class", "META-INF/MANIFEST.MF").anyMatch((s) -> s.startsWith("WEB-INF/lib/spring-boot-")).anyMatch((s) -> s.startsWith("WEB-INF/lib/spring-core-")).anyMatch((s) -> s.startsWith("WEB-INF/lib/spring-web-")));
    } finally {
        removeImage(imageReference);
    }
}
Also used : ContainerConfig(com.github.dockerjava.api.model.ContainerConfig) ImageName(org.springframework.boot.buildpack.platform.docker.type.ImageName) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) ContainerConfig(com.github.dockerjava.api.model.ContainerConfig) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TaskOutcome(org.gradle.testkit.runner.TaskOutcome) ImageReference(org.springframework.boot.buildpack.platform.docker.type.ImageReference) JarFile(java.util.jar.JarFile) ArrayList(java.util.ArrayList) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) GradleBuildInjectionExtension(org.springframework.boot.image.junit.GradleBuildInjectionExtension) GradleBuildExtension(org.springframework.boot.testsupport.gradle.testkit.GradleBuildExtension) GenericContainer(org.testcontainers.containers.GenericContainer) PrintWriter(java.io.PrintWriter) Wait(org.testcontainers.containers.wait.strategy.Wait) GradleBuild(org.springframework.boot.testsupport.gradle.testkit.GradleBuild) ImageAssertions(org.springframework.boot.image.assertions.ImageAssertions) Predicate(java.util.function.Predicate) FileWriter(java.io.FileWriter) IOException(java.io.IOException) BuildResult(org.gradle.testkit.runner.BuildResult) Attributes(java.util.jar.Attributes) Assertions.entry(org.assertj.core.api.Assertions.entry) File(java.io.File) DockerApi(org.springframework.boot.buildpack.platform.docker.DockerApi) Consumer(java.util.function.Consumer) Test(org.junit.jupiter.api.Test) List(java.util.List) Condition(org.assertj.core.api.Condition) Collections(java.util.Collections) StringUtils(org.springframework.util.StringUtils) ImageReference(org.springframework.boot.buildpack.platform.docker.type.ImageReference) BuildResult(org.gradle.testkit.runner.BuildResult) Test(org.junit.jupiter.api.Test)

Example 27 with GenericContainer

use of org.testcontainers.containers.GenericContainer in project graylog2-server by Graylog2.

the class NodeContainerFactory method createRunningContainer.

private static GenericContainer<?> createRunningContainer(NodeContainerConfig config, ImageFromDockerfile image) {
    Path fileCopyBaseDir = config.mavenProjectDirProvider.getFileCopyBaseDir();
    List<Path> pluginJars = config.pluginJarsProvider.getJars();
    boolean includeFrontend = config.mavenProjectDirProvider.includeFrontend();
    GenericContainer<?> container = new GenericContainer<>(image).withFileSystemBind(property("server_jar"), GRAYLOG_HOME + "/graylog.jar", BindMode.READ_ONLY).withNetwork(config.network).withEnv("GRAYLOG_MONGODB_URI", config.mongoDbUri).withEnv("GRAYLOG_ELASTICSEARCH_HOSTS", config.elasticsearchUri).withEnv("GRAYLOG_ELASTICSEARCH_VERSION", config.elasticsearchVersion.encode()).withEnv("GRAYLOG_PASSWORD_SECRET", "M4lteserKreuzHerrStrack?").withEnv("GRAYLOG_NODE_ID_FILE", "data/config/node-id").withEnv("GRAYLOG_HTTP_BIND_ADDRESS", "0.0.0.0:" + API_PORT).withEnv("GRAYLOG_ROOT_PASSWORD_SHA2", ADMIN_PW_SHA2).withEnv("GRAYLOG_LB_RECOGNITION_PERIOD_SECONDS", "0").withEnv("GRAYLOG_VERSIONCHECKS", "false").waitingFor(new WaitAllStrategy().withStrategy(Wait.forLogMessage(".*Graylog server up and running.*", 1)).withStrategy(new HttpWaitStrategy().forPort(API_PORT).forPath("/api/system/indices/ranges").withMethod("GET").withBasicCredentials("admin", "admin").forResponsePredicate(body -> {
        try {
            return StreamSupport.stream(OBJECT_MAPPER.readTree(body).path("ranges").spliterator(), false).anyMatch(range -> range.path("index_name").asText().startsWith("graylog_"));
        } catch (IOException e) {
            throw new RuntimeException("Couldn't extract response", e);
        }
    }))).withExposedPorts(config.portsToExpose()).withStartupTimeout(Duration.of(120, SECONDS));
    if (!includeFrontend) {
        container.withEnv("DEVELOPMENT", "true");
    }
    pluginJars.forEach(hostPath -> {
        if (Files.exists(hostPath)) {
            final Path containerPath = Paths.get(GRAYLOG_HOME, "plugin", hostPath.getFileName().toString());
            container.addFileSystemBind(hostPath.toString(), containerPath.toString(), BindMode.READ_ONLY);
        }
    });
    container.start();
    if (config.enableDebugging) {
        LOG.info("Container debug port: " + container.getMappedPort(DEBUG_PORT));
    }
    config.mavenProjectDirProvider.getFilesToAddToBinDir().forEach(filename -> {
        final Path originalPath = fileCopyBaseDir.resolve(filename);
        final String containerPath = GRAYLOG_HOME + "/bin/" + originalPath.getFileName();
        container.copyFileToContainer(MountableFile.forHostPath(originalPath), containerPath);
        if (!containerFileExists(container, containerPath)) {
            LOG.error("Mandatory file {} does not exist in container at {}", filename, containerPath);
        }
    });
    return container;
}
Also used : Path(java.nio.file.Path) WaitAllStrategy(org.testcontainers.containers.wait.strategy.WaitAllStrategy) HttpWaitStrategy(org.testcontainers.containers.wait.strategy.HttpWaitStrategy) IOException(java.io.IOException) GenericContainer(org.testcontainers.containers.GenericContainer)

Example 28 with GenericContainer

use of org.testcontainers.containers.GenericContainer in project flink by apache.

the class FlinkContainersBuilder method buildTaskManagerContainers.

private List<GenericContainer<?>> buildTaskManagerContainers(Path tempDirectory) {
    List<GenericContainer<?>> taskManagers = new ArrayList<>();
    for (int i = 0; i < numTaskManagers; i++) {
        // Configure TaskManager
        final Configuration taskManagerConf = new Configuration();
        taskManagerConf.addAll(this.conf);
        final String taskManagerHostName = TASK_MANAGER_HOSTNAME_PREFIX + i;
        taskManagerConf.set(TaskManagerOptions.HOST, taskManagerHostName);
        // Build TaskManager container
        final ImageFromDockerfile taskManagerImage;
        try {
            taskManagerImage = new FlinkImageBuilder().setTempDirectory(tempDirectory).setConfiguration(taskManagerConf).setLogProperties(logProperties).asTaskManager().build();
        } catch (ImageBuildException e) {
            throw new RuntimeException("Failed to build TaskManager image", e);
        }
        taskManagers.add(configureContainer(new GenericContainer<>(taskManagerImage), taskManagerHostName, "TaskManager-" + i));
    }
    return taskManagers;
}
Also used : ImageFromDockerfile(org.testcontainers.images.builder.ImageFromDockerfile) Configuration(org.apache.flink.configuration.Configuration) ArrayList(java.util.ArrayList) GenericContainer(org.testcontainers.containers.GenericContainer)

Example 29 with GenericContainer

use of org.testcontainers.containers.GenericContainer in project flink by apache.

the class FlinkContainersBuilder method buildJobManagerContainer.

// --------------------------- Helper Functions -------------------------------------
private GenericContainer<?> buildJobManagerContainer(Path tempDirectory) {
    // Configure JobManager
    final Configuration jobManagerConf = new Configuration();
    jobManagerConf.addAll(this.conf);
    // Build JobManager container
    final ImageFromDockerfile jobManagerImage;
    try {
        jobManagerImage = new FlinkImageBuilder().setTempDirectory(tempDirectory).setConfiguration(jobManagerConf).setLogProperties(logProperties).asJobManager().build();
    } catch (ImageBuildException e) {
        throw new RuntimeException("Failed to build JobManager image", e);
    }
    return configureContainer(new GenericContainer<>(jobManagerImage), JOB_MANAGER_HOSTNAME, "JobManager").withExposedPorts(jobManagerConf.get(RestOptions.PORT));
}
Also used : ImageFromDockerfile(org.testcontainers.images.builder.ImageFromDockerfile) Configuration(org.apache.flink.configuration.Configuration) GenericContainer(org.testcontainers.containers.GenericContainer)

Example 30 with GenericContainer

use of org.testcontainers.containers.GenericContainer in project instrumentation-java by census-instrumentation.

the class JaegerExporterHandlerIntegrationTest method startContainer.

/**
 * 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);
    }
}
Also used : AssumptionViolatedException(org.junit.AssumptionViolatedException) HttpWaitStrategy(org.testcontainers.containers.wait.strategy.HttpWaitStrategy) GenericContainer(org.testcontainers.containers.GenericContainer) BeforeClass(org.junit.BeforeClass)

Aggregations

GenericContainer (org.testcontainers.containers.GenericContainer)30 File (java.io.File)6 IOException (java.io.IOException)6 ImageFromDockerfile (org.testcontainers.images.builder.ImageFromDockerfile)6 ArrayList (java.util.ArrayList)5 Test (org.junit.Test)5 Arrays (java.util.Arrays)4 AssumptionViolatedException (org.junit.AssumptionViolatedException)4 Test (org.junit.jupiter.api.Test)4 WaitingConsumer (org.testcontainers.containers.output.WaitingConsumer)4 OneShotStartupCheckStrategy (org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy)4 PrintWriter (java.io.PrintWriter)3 Path (java.nio.file.Path)3 List (java.util.List)3 BuildResult (org.gradle.testkit.runner.BuildResult)3 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)3 BeforeEach (org.junit.jupiter.api.BeforeEach)3 ImageReference (org.springframework.boot.buildpack.platform.docker.type.ImageReference)3 HttpWaitStrategy (org.testcontainers.containers.wait.HttpWaitStrategy)3 MountableFile (org.testcontainers.utility.MountableFile)3