Created
April 27, 2022 16:23
-
-
Save kiview/7002824b7a1d4d528f28c7b385b94e11 to your computer and use it in GitHub Desktop.
Syncing a file between host and container with Testcontainers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.testcontainers; | |
import com.github.dockerjava.api.command.InspectContainerResponse; | |
import lombok.NonNull; | |
import lombok.SneakyThrows; | |
import org.apache.commons.io.FileUtils; | |
import org.junit.Test; | |
import org.testcontainers.containers.GenericContainer; | |
import org.testcontainers.utility.MountableFile; | |
import java.io.File; | |
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.util.stream.Collectors; | |
import static org.rnorth.visibleassertions.VisibleAssertions.assertEquals; | |
public class CopySyncExperiment { | |
@Test | |
public void testForSync() throws IOException, InterruptedException { | |
try (GenericContainer syncContainer = new SyncingContainer("redis:5.0.3-alpine") | |
.withExposedPorts(6379) | |
.withCopyFileToContainer(MountableFile.forHostPath("foobar"), "/sync/foobar")) { | |
syncContainer.start(); | |
syncContainer.execInContainer("sh", "-c", "echo foo >> /sync/foobar"); | |
} | |
String fileContentAfterSync = Files.lines(new File("foobar").toPath()).collect(Collectors.joining()); | |
assertEquals("File was not synced", "somecontentfoo", fileContentAfterSync); | |
} | |
public static class SyncingContainer extends GenericContainer { | |
String syncPath; | |
MountableFile syncFile; | |
public SyncingContainer(@NonNull String dockerImageName) { | |
super(dockerImageName); | |
} | |
@Override | |
public GenericContainer withCopyFileToContainer(MountableFile mountableFile, String containerPath) { | |
syncPath = containerPath; | |
syncFile = mountableFile; | |
return super.withCopyFileToContainer(mountableFile, containerPath); | |
} | |
@Override | |
@SneakyThrows | |
protected void containerIsStopping(InspectContainerResponse containerInfo) { | |
FileUtils.deleteQuietly(new File(syncFile.getResolvedPath())); | |
copyFileFromContainer(syncPath, syncFile.getResolvedPath()); | |
super.containerIsStopping(containerInfo); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment