|
| 1 | +package org.testcontainers.dockerclient; |
| 2 | + |
| 3 | +import com.github.dockerjava.api.DockerClient; |
| 4 | +import com.github.dockerjava.api.model.Event; |
| 5 | +import com.github.dockerjava.core.command.EventsResultCallback; |
| 6 | +import org.jetbrains.annotations.NotNull; |
| 7 | +import org.junit.Test; |
| 8 | +import org.rnorth.visibleassertions.VisibleAssertions; |
| 9 | +import org.testcontainers.DockerClientFactory; |
| 10 | +import org.testcontainers.containers.GenericContainer; |
| 11 | +import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; |
| 12 | + |
| 13 | +import java.io.IOException; |
| 14 | +import java.time.Instant; |
| 15 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 16 | + |
| 17 | +/** |
| 18 | + * Test that event streaming from the {@link DockerClient} works correctly |
| 19 | + */ |
| 20 | +public class EventStreamTest { |
| 21 | + |
| 22 | + /** |
| 23 | + * Test that docker events can be streamed from the client. |
| 24 | + */ |
| 25 | + @Test |
| 26 | + public void test() throws IOException, InterruptedException { |
| 27 | + DockerClient client = DockerClientFactory.instance().client(); |
| 28 | + Instant startTime = Instant.now(); |
| 29 | + final AtomicBoolean received = new AtomicBoolean(false); |
| 30 | + |
| 31 | + // Start a one-shot Container |
| 32 | + try ( |
| 33 | + GenericContainer container = new GenericContainer<>() |
| 34 | + .withCommand("/bin/sh", "-c", "sleep 0") |
| 35 | + .withStartupCheckStrategy(new OneShotStartupCheckStrategy())) { |
| 36 | + |
| 37 | + container.start(); |
| 38 | + Instant endTime = Instant.now(); |
| 39 | + |
| 40 | + // Request all events between startTime and endTime for the container |
| 41 | + try (EventsResultCallback response = client.eventsCmd() |
| 42 | + .withContainerFilter(container.getContainerId()) |
| 43 | + .withEventFilter("create") |
| 44 | + .withSince(Long.toString(startTime.getEpochSecond())) |
| 45 | + .withUntil(Long.toString(endTime.getEpochSecond())) |
| 46 | + .exec(new EventsResultCallback() { |
| 47 | + @Override |
| 48 | + public void onNext(@NotNull Event event) { |
| 49 | + // Check that a create event for the container is received |
| 50 | + if (event.getId().equals(container.getContainerId()) && event.getStatus().equals("create")) { |
| 51 | + received.set(true); |
| 52 | + } |
| 53 | + } |
| 54 | + })) { |
| 55 | + |
| 56 | + response.awaitCompletion(); |
| 57 | + } |
| 58 | + |
| 59 | + } |
| 60 | + |
| 61 | + VisibleAssertions.assertTrue("Events has been captured", received.get()); |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments