org.testcontainers.containers.DockerComposeContainer Java Examples

The following examples show how to use org.testcontainers.containers.DockerComposeContainer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuthenticatedImagePullTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void testThatAuthLocatorIsUsedForDockerComposePull() throws IOException {
    // Prepare a simple temporary Docker Compose manifest which requires our custom private image
    Path tempFile = getLocalTempFile(".docker-compose.yml");
    @Language("yaml") String composeFileContent =
        "version: '2.0'\n" +
            "services:\n" +
            "  privateservice:\n" +
            "      command: /bin/sh -c 'sleep 60'\n" +
            "      image: " + testImageNameWithTag;
    Files.write(tempFile, composeFileContent.getBytes());

    // Start the docker compose project, which will require an authenticated pull
    try (final DockerComposeContainer<?> compose = new DockerComposeContainer<>(tempFile.toFile())) {
        compose.start();

        assertTrue("container started following an authenticated pull",
            compose
                .getContainerByServiceName("privateservice_1")
                .map(ContainerState::isRunning)
                .orElse(false)
        );
    }
}
 
Example #2
Source File: DockerComposeErrorHandlingTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void simpleTest() {
    VisibleAssertions.assertThrows("starting with an invalid docker-compose file throws an exception",
        IllegalArgumentException.class,
            () -> {
                DockerComposeContainer environment = new DockerComposeContainer(new File("src/test/resources/invalid-compose.yml"))
                    .withExposedService("something", 123);
            });
}
 
Example #3
Source File: SkyWalkingAnnotations.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void initDockerContainers(final Object testClass,
                                         final DockerComposeContainer<?> compose) throws Exception {
    final List<Field> containerFields = Stream.of(testClass.getClass().getDeclaredFields())
                                              .filter(SkyWalkingAnnotations::isAnnotatedWithDockerContainer)
                                              .collect(Collectors.toList());
    if (containerFields.isEmpty()) {
        return;
    }

    final Field serviceMap = DockerComposeContainer.class.getDeclaredField("serviceInstanceMap");
    serviceMap.setAccessible(true);
    final Map<String, ContainerState> serviceInstanceMap = (Map<String, ContainerState>) serviceMap.get(compose);

    for (final Field containerField : containerFields) {
        if (containerField.getType() != ContainerState.class) {
            throw new IllegalArgumentException(
                "@DockerContainer can only be annotated on fields of type " + ContainerState.class.getName()
                    + " but was " + containerField.getType() + "; field \"" + containerField.getName() + "\""
            );
        }
        final DockerContainer dockerContainer = containerField.getAnnotation(DockerContainer.class);
        final String serviceName = dockerContainer.value();
        final Optional<ContainerState> container =
            serviceInstanceMap.entrySet()
                              .stream()
                              .filter(e -> e.getKey().startsWith(serviceName + "_"))
                              .findFirst()
                              .map(Map.Entry::getValue);
        containerField.setAccessible(true);
        containerField.set(
            testClass,
            container.orElseThrow(
                () -> new NoSuchElementException("cannot find container with name " + serviceName)
            )
        );
    }
}
 
Example #4
Source File: SkyWalkingAnnotations.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private static void initLoggers(final List<File> files, final DockerComposeContainer<?> compose) {
    files.forEach(file -> {
        try {
            load(file).as(DockerComposeFile.class).getServices().forEach(
                (service, ignored) -> compose.withLogConsumer(
                    service, new Slf4jLogConsumer(new ContainerLogger(LOG_DIR, service + ".log"))
                )
            );
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    });
}
 
Example #5
Source File: SkyWalkingAnnotations.java    From skywalking with Apache License 2.0 5 votes vote down vote up
/**
 * Destroy the containers started by the docker compose in the given test class, this should be typically called in
 * the corresponding {@code @AfterAll} or {@code @AfterEach} method.
 *
 * @param testClass in which the containers should be destroyed
 */
public static void destroy(final Object testClass) {
    Stream.of(testClass.getClass().getDeclaredFields())
          .filter(SkyWalkingAnnotations::isAnnotatedWithDockerCompose)
          .findFirst()
          .ifPresent(field -> {
              try {
                  field.setAccessible(true);
                  ((DockerComposeContainer<?>) field.get(testClass)).stop();
              } catch (IllegalAccessException e) {
                  throw new RuntimeException(e);
              }
          });
}
 
Example #6
Source File: DockerComposeOverridesTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void test() {
    try (DockerComposeContainer compose =
             new DockerComposeContainer(composeFiles)
                 .withLocalCompose(localMode)
                 .withExposedService(SERVICE_NAME, SERVICE_PORT)) {

        compose.start();

        BufferedReader br = Unreliables.retryUntilSuccess(10, TimeUnit.SECONDS, () -> {
            Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);

            Socket socket = new Socket(compose.getServiceHost(SERVICE_NAME, SERVICE_PORT), compose.getServicePort(SERVICE_NAME, SERVICE_PORT));
            return new BufferedReader(new InputStreamReader(socket.getInputStream()));
        });

        Unreliables.retryUntilTrue(10, TimeUnit.SECONDS, () -> {
            while (br.ready()) {
                String line = br.readLine();
                if (line.contains(expectedEnvVar)) {
                    pass("Mapped environment variable was found");
                    return true;
                }
            }
            info("Mapped environment variable was not found yet - process probably not ready");
            Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
            return false;
        });
    }
}
 
Example #7
Source File: DockerComposeContainerWithBuildTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void performTest() {
    final File composeFile = new File("src/test/resources/compose-build-test/docker-compose.yml");

    final AtomicReference<String> builtImageName = new AtomicReference<>("");
    final AtomicReference<String> pulledImageName = new AtomicReference<>("");
    try (DockerComposeContainer environment = new DockerComposeContainer<>(composeFile)
        .withExposedService("customredis", 6379)
        .withBuild(true)
        .withRemoveImages(removeMode)) {

        environment.start();

        builtImageName.set(imageNameForRunningContainer("_customredis_1"));
        final boolean isBuiltImagePresentWhileRunning = isImagePresent(builtImageName.get());
        assertEquals("the built image is present while running", true, isBuiltImagePresentWhileRunning);

        pulledImageName.set(imageNameForRunningContainer("_normalredis_1"));
        final boolean isPulledImagePresentWhileRunning = isImagePresent(pulledImageName.get());
        assertEquals("the pulled image is present while running", true, isPulledImagePresentWhileRunning);
    }

    Unreliables.retryUntilSuccess(10, TimeUnit.SECONDS, () -> {
        final boolean isBuiltImagePresentAfterRunning = isImagePresent(builtImageName.get());
        assertEquals("the built image is not present after running", shouldBuiltImageBePresentAfterRunning, isBuiltImagePresentAfterRunning);
        return null;
    });

    Unreliables.retryUntilSuccess(10, TimeUnit.SECONDS, () -> {
        final boolean isPulledImagePresentAfterRunning = isImagePresent(pulledImageName.get());
        assertEquals("the pulled image is present after running", shouldPulledImageBePresentAfterRunning, isPulledImagePresentAfterRunning);
        return null;
    });
}
 
Example #8
Source File: DockerComposeContainerWithBuildTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
public DockerComposeContainerWithBuildTest(final DockerComposeContainer.RemoveImages removeMode,
                                           final boolean shouldBuiltImageBePresentAfterRunning,
                                           final boolean shouldPulledImageBePresentAfterRunning) {
    this.removeMode = removeMode;
    this.shouldBuiltImageBePresentAfterRunning = shouldBuiltImageBePresentAfterRunning;
    this.shouldPulledImageBePresentAfterRunning = shouldPulledImageBePresentAfterRunning;
}
 
Example #9
Source File: DockerComposeLocalImageTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void usesLocalImageEvenWhenPullFails() throws InterruptedException {
    tagImage("redis:4.0.10", "redis-local", "latest");

    DockerComposeContainer composeContainer = new DockerComposeContainer(new File("src/test/resources/local-compose-test.yml"))
        .withExposedService("redis", 6379);
    composeContainer.start();
}
 
Example #10
Source File: DockerComposeLogConsumerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void testLogConsumer() throws TimeoutException {
    WaitingConsumer logConsumer = new WaitingConsumer();
    DockerComposeContainer environment = new DockerComposeContainer(new File("src/test/resources/v2-compose-test.yml"))
        .withExposedService("redis_1", 6379)
        .withLogConsumer("redis_1", logConsumer);

    try {
        environment.starting(Description.EMPTY);
        logConsumer.waitUntil(frame -> frame.getType() == STDOUT && frame.getUtf8String().contains("Ready to accept connections"), 5, TimeUnit.SECONDS);
    } finally {
        environment.finished(Description.EMPTY);
    }
}
 
Example #11
Source File: DockerComposeContainerTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Override
protected DockerComposeContainer getEnvironment() {
    return environment;
}
 
Example #12
Source File: DockerComposeServiceTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Override
protected DockerComposeContainer getEnvironment() {
    return environment;
}
 
Example #13
Source File: DockerComposeWaitStrategyTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Before
public final void setUp() {
    environment = new DockerComposeContainer<>(
        new File("src/test/resources/compose-test.yml"));
}
 
Example #14
Source File: DockerComposeV2FormatTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Override
protected DockerComposeContainer getEnvironment() {
    return environment;
}
 
Example #15
Source File: DockerComposeV2WithNetworkTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Override
protected DockerComposeContainer getEnvironment() {
    return environment;
}
 
Example #16
Source File: SkyWalkingAnnotations.java    From skywalking with Apache License 2.0 3 votes vote down vote up
public static void init(final Object testClass) throws Exception {
    Objects.requireNonNull(testClass, "testClass");

    final DockerComposeContainer<?> compose = initDockerComposeField(testClass).orElseThrow(RuntimeException::new);

    compose.start();

    initHostAndPort(testClass, compose);

    initDockerContainers(testClass, compose);
}
 
Example #17
Source File: BaseDockerComposeTest.java    From testcontainers-java with MIT License votes vote down vote up
protected abstract DockerComposeContainer getEnvironment();