How to use SocatContainer method of org.testcontainers.containers.DockerComposeContainer class

Best Testcontainers-java code snippet using org.testcontainers.containers.DockerComposeContainer.SocatContainer

Source:AirbyteTestContainer.java Github

copy

Full Screen

...24import java.util.function.Consumer;25import org.slf4j.Logger;26import org.slf4j.LoggerFactory;27import org.testcontainers.containers.DockerComposeContainer;28import org.testcontainers.containers.SocatContainer;29import org.testcontainers.containers.output.OutputFrame;30/**31 * The goal of this class is to make it easy to run the Airbyte docker-compose configuration from32 * test containers. This helps make it easy to stop the test container without deleting the volumes33 * { @link AirbyteTestContainer#stopRetainVolumes() }. It waits for Airbyte to be ready. It also34 * handles the nuances of configuring the Airbyte docker-compose configuration in test containers.35 */36public class AirbyteTestContainer {37 private static final Logger LOGGER = LoggerFactory.getLogger(AirbyteTestContainer.class);38 private final File dockerComposeFile;39 private final Map<String, String> env;40 private final Map<String, Consumer<String>> customServiceLogListeners;41 private DockerComposeContainer<?> dockerComposeContainer;42 public AirbyteTestContainer(final File dockerComposeFile,43 final Map<String, String> env,44 final Map<String, Consumer<String>> customServiceLogListeners) {45 this.dockerComposeFile = dockerComposeFile;46 this.env = env;47 this.customServiceLogListeners = customServiceLogListeners;48 }49 /**50 * Starts Airbyte docker-compose configuration. Will block until the server is reachable or it times51 * outs.52 */53 @SuppressWarnings({"unchecked", "rawtypes"})54 public void start() throws IOException, InterruptedException {55 final File cleanedDockerComposeFile = prepareDockerComposeFile(dockerComposeFile);56 dockerComposeContainer = new DockerComposeContainer(cleanedDockerComposeFile).withEnv(env);57 serviceLogConsumer(dockerComposeContainer, "init");58 serviceLogConsumer(dockerComposeContainer, "db");59 serviceLogConsumer(dockerComposeContainer, "seed");60 serviceLogConsumer(dockerComposeContainer, "scheduler");61 serviceLogConsumer(dockerComposeContainer, "server");62 serviceLogConsumer(dockerComposeContainer, "webapp");63 serviceLogConsumer(dockerComposeContainer, "worker");64 serviceLogConsumer(dockerComposeContainer, "airbyte-temporal");65 dockerComposeContainer.start();66 waitForAirbyte();67 }68 private static Map<String, String> prepareDockerComposeEnvVariables(File envFile) throws IOException {69 LOGGER.info("Searching for environment in {}", envFile);70 Preconditions.checkArgument(envFile.exists(), "could not find docker compose environment");71 final Properties prop = new Properties();72 prop.load(new FileInputStream(envFile));73 return Maps.fromProperties(prop);74 }75 /**76 * TestContainers docker compose files cannot have container_names, so we filter them.77 */78 private static File prepareDockerComposeFile(File originalDockerComposeFile) throws IOException {79 final File cleanedDockerComposeFile = Files.createTempFile(Path.of("/tmp"), "docker_compose", "acceptance_test").toFile();80 try (final Scanner scanner = new Scanner(originalDockerComposeFile)) {81 try (final FileWriter fileWriter = new FileWriter(cleanedDockerComposeFile)) {82 while (scanner.hasNextLine()) {83 final String s = scanner.nextLine();84 if (s.contains("container_name")) {85 continue;86 }87 fileWriter.write(s);88 fileWriter.write('\n');89 }90 }91 }92 return cleanedDockerComposeFile;93 }94 @SuppressWarnings("BusyWait")95 private static void waitForAirbyte() throws InterruptedException {96 // todo (cgardens) - assumes port 8001 which is misleading since we can start airbyte on other97 // ports. need to make this configurable.98 final AirbyteApiClient apiClient = new AirbyteApiClient(99 new ApiClient().setScheme("http")100 .setHost("localhost")101 .setPort(8001)102 .setBasePath("/api"));103 final HealthApi healthApi = apiClient.getHealthApi();104 ApiException lastException;105 int i = 0;106 while (true) {107 try {108 healthApi.getHealthCheck();109 break;110 } catch (ApiException e) {111 lastException = e;112 LOGGER.info("airbyte not ready yet. attempt: {}", i);113 }114 if (i == 10) {115 throw new IllegalStateException("Airbyte took too long to start. Including last exception.", lastException);116 }117 Thread.sleep(5000);118 i++;119 }120 }121 private void serviceLogConsumer(DockerComposeContainer<?> composeContainer, String service) {122 composeContainer.withLogConsumer(service, logConsumer(customServiceLogListeners.get(service)));123 }124 /**125 * Exposes logs generated by docker containers in docker compose temporal test container.126 *127 * @param customConsumer - each line output by the service in docker compose will be passed ot the128 * consumer. if null do nothing.129 * @return log consumer130 */131 private Consumer<OutputFrame> logConsumer(Consumer<String> customConsumer) {132 return c -> {133 if (c != null && c.getBytes() != null) {134 final String log = new String(c.getBytes());135 if (customConsumer != null) {136 customConsumer.accept(log);137 }138 LOGGER.info(log.replace("\n", ""));139 }140 };141 }142 /**143 * This stop method will delete any underlying volumes for the docker compose setup.144 */145 public void stop() {146 if (dockerComposeContainer != null) {147 dockerComposeContainer.stop();148 }149 }150 /**151 * This method is hacked from {@link org.testcontainers.containers.DockerComposeContainer#stop()} We152 * needed to do this to avoid removing the volumes when the container is stopped so that the data153 * persists and can be tested against in the second run154 */155 public void stopRetainVolumes() {156 if (dockerComposeContainer == null) {157 return;158 }159 try {160 stopRetainVolumesInternal();161 } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException | NoSuchFieldException e) {162 throw new RuntimeException(e);163 }164 }165 @SuppressWarnings("rawtypes")166 private void stopRetainVolumesInternal() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, NoSuchFieldException {167 final Class<? extends DockerComposeContainer> dockerComposeContainerClass = dockerComposeContainer.getClass();168 try {169 final Field ambassadorContainerField = dockerComposeContainerClass.getDeclaredField("ambassadorContainer");170 ambassadorContainerField.setAccessible(true);171 final SocatContainer ambassadorContainer = (SocatContainer) ambassadorContainerField.get(dockerComposeContainer);172 ambassadorContainer.stop();173 final String cmd = "down ";174 final Method runWithComposeMethod = dockerComposeContainerClass.getDeclaredMethod("runWithCompose", String.class);175 runWithComposeMethod.setAccessible(true);176 runWithComposeMethod.invoke(dockerComposeContainer, cmd);177 } finally {178 final Field projectField = dockerComposeContainerClass.getDeclaredField("project");179 projectField.setAccessible(true);180 final Method randomProjectId = dockerComposeContainerClass.getDeclaredMethod("randomProjectId");181 randomProjectId.setAccessible(true);182 final String newProjectValue = (String) randomProjectId.invoke(dockerComposeContainer);183 projectField.set(dockerComposeContainer, newProjectValue);184 }185 }...

Full Screen

Full Screen

SocatContainer

Using AI Code Generation

copy

Full Screen

1 public class SocatContainer extends GenericContainer<SocatContainer> {2 private static final String IMAGE = "alpine/socat";3 private static final int DEFAULT_PORT = 2375;4 public SocatContainer() {5 super(IMAGE + ":latest");6 withExposedPorts(DEFAULT_PORT);7 }8 public String getTargetIpAddress() {9 return getContainerIpAddress();10 }11 public Integer getTargetPort() {12 return getMappedPort(DEFAULT_PORT);13 }14 }15 public class DockerComposeContainer extends GenericContainer<DockerComposeContainer> {16 private static final String IMAGE = "docker/compose";17 private static final int DEFAULT_PORT = 2375;18 public DockerComposeContainer() {19 super(IMAGE + ":latest");20 withExposedPorts(DEFAULT_PORT);21 }22 public String getTargetIpAddress() {23 return getContainerIpAddress();24 }25 public Integer getTargetPort() {26 return getMappedPort(DEFAULT_PORT);27 }28 }29 public class DockerComposeContainer extends GenericContainer<DockerComposeContainer> {30 private static final String IMAGE = "docker/compose";31 private static final int DEFAULT_PORT = 2375;32 public DockerComposeContainer() {33 super(IMAGE + ":latest");34 withExposedPorts(DEFAULT_PORT);35 }36 public String getTargetIpAddress() {37 return getContainerIpAddress();38 }39 public Integer getTargetPort() {40 return getMappedPort(DEFAULT_PORT);41 }42 }43 public class DockerComposeContainer extends GenericContainer<DockerComposeContainer> {44 private static final String IMAGE = "docker/compose";45 private static final int DEFAULT_PORT = 2375;46 public DockerComposeContainer() {47 super(IMAGE + ":latest");48 withExposedPorts(DEFAULT_PORT);49 }50 public String getTargetIpAddress() {51 return getContainerIpAddress();52 }53 public Integer getTargetPort() {54 return getMappedPort(DEFAULT_PORT);55 }56 }

Full Screen

Full Screen

SocatContainer

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.DockerComposeContainer2import org.testcontainers.containers.wait.strategy.Wait3class DockerComposeTest extends Specification {4 def "test docker compose"() {5 def dockerCompose = new DockerComposeContainer(new File("src/test/resources/docker-compose.yml"))6 .withExposedService("redis_1", 6379, Wait.forListeningPort())7 .withExposedService("redis_2", 6379, Wait.forListeningPort())8 .withExposedService("redis_3", 6379, Wait.forListeningPort())9 .withExposedService("redis_4", 6379, Wait.forListeningPort())10 .withExposedService("redis_5", 6379, Wait.forListeningPort())11 .withExposedService("redis_6", 6379, Wait.forListeningPort())12 .withExposedService("redis_7", 6379, Wait.forListeningPort())13 .withExposedService("redis_8", 6379, Wait.forListeningPort())14 .withExposedService("redis_9", 6379, Wait.forListeningPort())15 .withExposedService("redis_10", 6379, Wait.forListeningPort())16 .withExposedService("redis_11", 6379, Wait.forListeningPort())17 .withExposedService("redis_12", 6379, Wait.forListeningPort())18 .withExposedService("redis_13", 6379, Wait.forListeningPort())19 .withExposedService("redis_14", 6379, Wait.forListeningPort())20 .withExposedService("redis_15", 6379, Wait.forListeningPort())21 .withExposedService("redis_16", 6379, Wait.forListeningPort())22 .withExposedService("redis_17", 6379, Wait.forListeningPort())23 .withExposedService("redis_18", 6379, Wait.forListeningPort())24 .withExposedService("redis_19", 6379, Wait.forListeningPort())25 .withExposedService("redis_20", 6379, Wait.forListeningPort())26 .withExposedService("redis_21", 6379, Wait.forListeningPort())27 .withExposedService("redis_22", 6379, Wait.forListeningPort())28 .withExposedService("redis_23", 6379, Wait.forListeningPort())

Full Screen

Full Screen

SocatContainer

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.DockerComposeContainer2import org.testcontainers.containers.wait.strategy.Wait3import org.testcontainers.containers.wait.strategy.WaitAllStrategy4import org.testcontainers.containers.wait.strategy.WaitAllStrategy.WaitAllStrategyBuilder5import org.testcontainers.containers.wait.strategy.WaitStrategy6import org.testcontainers.containers.wait.strategy.WaitStrategyTarget7import java.io.File8import java.time.Duration9class SocatContainer : DockerComposeContainer<SocatContainer>(File("docker-compose.yml")) {10 init {11 withExposedService("socat", 2375)12 withLocalCompose(true)13 withPull(false)14 waitingFor("socat", Wait.forLogMessage(".*socat.*", 1))15 }16}17import org.testcontainers.containers.DockerComposeContainer18import org.testcontainers.containers.wait.strategy.Wait19import org.testcontainers.containers.wait.strategy.WaitAllStrategy20import org.testcontainers.containers.wait.strategy.WaitAllStrategy.WaitAllStrategyBuilder21import org.testcontainers.containers.wait.strategy.WaitStrategy22import org.testcontainers.containers.wait.strategy.WaitStrategyTarget23import java.io.File24import java.time.Duration25class SocatContainer : DockerComposeContainer<SocatContainer>(File("docker-compose.yml")) {26 init {27 withExposedService("socat", 2375)28 withLocalCompose(true)29 withPull(false)30 waitingFor("socat", Wait.forLogMessage(".*socat.*", 1))31 }32}33import org.testcontainers.containers.DockerComposeContainer34import org.testcontainers.containers.wait.strategy.Wait35import org.testcontainers.containers.wait.strategy.WaitAllStrategy36import org.testcontainers.containers.wait.strategy.WaitAllStrategy.WaitAllStrategyBuilder37import org.testcontainers.containers.wait.strategy.WaitStrategy38import org.testcontainers.containers.wait.strategy.WaitStrategyTarget39import java.io.File40import java.time.Duration

Full Screen

Full Screen

SocatContainer

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.DockerComposeContainer2import org.testcontainers.containers.wait.strategy.Wait3import org.testcontainers.containers.wait.strategy.WaitAllStrategy4import org.testcontainers.containers.wait.strategy.WaitStrategy5import org.testcontainers.containers.wait.strategy.WaitStrategyTarget6import org.testcontainers.containers.wait.strategy.WaitStrategyTargetContainer7import org.testcontainers.containers.wait.strategy.WaitStrategyTargetHostPort8import org.testcontainers.containers.wait.strategy.WaitStrategyTargetPort9import org.testcontainers.containers.wait.strategy.WaitStrategyTargetSocket10import org.testcontainers.containers.wait.strategy.WaitStrategyTargetSocketStream11import org.testcontainers.containers.wait.strategy.WaitStrategyTargetUnixSocket12import org.testcontainers.containers.wait.strategy.WaitStrategyTargetUnixSocketStream13import org.testcontainers.containers.wait.strategy.WaitStrategyTargetWindowsNamedPipe14import org.testcontainers.containers.wait.strategy.WaitStrategyTargetWindowsNamedPipeStream15import org.testcontainers.containers.wait.strategy.WaitStrategyTargetWindowsPipe16import org.testcontainers.containers.wait.strategy.WaitStrategyTargetWindowsPipeStream17import org.testcontainers.utility.MountableFile18import java.io.File19import java.time.Duration20import java.util.concurrent.TimeUnit21DockerComposeContainer(File("docker-compose.yml"))22 .withExposedService("web_1", 80, Wait.forHttp("/").forStatusCode(200))23 .withExposedService("web_2", 80, Wait.forHttp("/").forStatusCode(200))24 .withLocalCompose(true)25 .withPull(false)26 .withEnv("COMPOSE_PROJECT_NAME", "myproject")27 .withEnv("COMPOSE_FILE", "docker-compose.yml")28 .withEnv("COMPOSE_HTTP_TIMEOUT", "300")29 .withEnv("COMPOSE_PROJECT_NAME", "myproject")30 .withEnv("COMPOSE_FILE", "docker-compose.yml")31 .withEnv("COMPOSE_HTTP_TIMEOUT", "300")32 .withCommand("up -d")33 .withLocalCompose(true)34 .withPull(false)35 .withEnv("COMPOSE_PROJECT_NAME", "myproject")36 .withEnv("COMPOSE_FILE", "docker-compose.yml")37 .withEnv("COMPOSE_HTTP_TIMEOUT", "300")38 .withCommand("up -d")39 .withExposedService("web_1

Full Screen

Full Screen

SocatContainer

Using AI Code Generation

copy

Full Screen

1public class DockerComposeTest {2 private static final String COMPOSE_FILE = "src/test/resources/docker-compose.yml";3 private static final String SERVICE_NAME = "my-service";4 private static final String SERVICE_PORT = "8080";5 public static DockerComposeContainer dockerCompose = new DockerComposeContainer(new File(COMPOSE_FILE))6 .withExposedService(SERVICE_NAME, Integer.parseInt(SERVICE_PORT), 7 Wait.forHttp(SERVICE_URL).forStatusCode(200));8 public void test() {9 final String url = String.format("%s:%s", SERVICE_URL, SERVICE_PORT);10 final String response = new RestTemplate().getForObject(url, String.class);11 assertThat(response).isEqualTo("Hello World");12 }13}14[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ testcontainers ---15[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ testcontainers ---16[INFO] --- maven-compiler-plugin:3.5.1:compile (default-compile) @ testcontainers ---17[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ testcontainers ---18[INFO] --- maven-compiler-plugin:3.5.1:testCompile (default-testCompile) @ testcontainers ---

Full Screen

Full Screen

SocatContainer

Using AI Code Generation

copy

Full Screen

1DockerComposeContainer compose = new DockerComposeContainer(new File("docker-compose.yml"))2.withSocatContainer(SocatContainer::new)3.start()4DockerComposeContainer compose = new DockerComposeContainer(new File("docker-compose.yml"))5.withSocatContainer(SocatContainer::new)6.start()7DockerComposeContainer compose = new DockerComposeContainer(new File("docker-compose.yml"))8.withSocatContainer(SocatContainer::new)9.start()10DockerComposeContainer compose = new DockerComposeContainer(new File("docker-compose.yml"))11.withSocatContainer(SocatContainer::new)12.start()13DockerComposeContainer compose = new DockerComposeContainer(new File("docker-compose.yml"))14.withSocatContainer(SocatContainer::new)15.start()

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful