How to use CommandLine class of org.testcontainers.utility package

Best Testcontainers-java code snippet using org.testcontainers.utility.CommandLine

Source:IntegrationTest.java Github

copy

Full Screen

...38import org.testcontainers.lifecycle.Startables;39import org.testcontainers.utility.DockerImageName;40import io.debezium.testing.testcontainers.ConnectorConfiguration;41import io.debezium.testing.testcontainers.DebeziumContainer;42import picocli.CommandLine;43public abstract class IntegrationTest {44 public static final String HEARTBEAT_TOPIC = "heartbeat-test";45 protected static final Network network = Network.newNetwork();46 protected static final KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:5.4.3"))47 .withNetwork(network);48 protected static DebeziumContainer kafkaConnect = DebeziumContainer.latestStable()49 .withNetwork(network)50 .withKafka(kafka)51 .dependsOn(kafka);52 @BeforeAll53 public static void prepare() {54 Startables.deepStart(Stream.of(kafka, kafkaConnect)).join();55 }56 public String getConnectVersion() throws Exception {57 Container.ExecResult result = kafkaConnect.execInContainer("/bin/bash", "-c", "/usr/bin/printenv KAFKA_VERSION");58 return result.getStdout().replace("\n", "");59 }60 @BeforeEach61 void injectCommandContext() {62 ReflectionUtils.findFields(getClass(), it -> it.isAnnotationPresent(InjectCommandContext.class), HierarchyTraversalMode.TOP_DOWN)63 .forEach(field -> {64 try {65 KcctlCommandContext<?> commandContext = prepareContext(field);66 ReflectionUtils.makeAccessible(field);67 field.set(this, commandContext);68 }69 catch (IllegalAccessException e) {70 throw new IntegrationTestException("Couldn't inject KcctlCommandContext", e);71 }72 });73 }74 @AfterEach75 public void cleanup() {76 kafkaConnect.deleteAllConnectors();77 }78 protected void registerTestConnector(String name) {79 ConnectorConfiguration config = ConnectorConfiguration.create()80 .with("connector.class", "org.apache.kafka.connect.mirror.MirrorHeartbeatConnector")81 .with("tasks.max", 1)82 .with("source.cluster.alias", "source")83 .with("topic", HEARTBEAT_TOPIC);84 kafkaConnect.registerConnector(name, config);85 }86 private KcctlCommandContext<?> prepareContext(Field field) {87 Type type = field.getGenericType();88 Type genericType = ((ParameterizedType) type).getActualTypeArguments()[0];89 Class<?> targetCommand = (Class<?>) genericType;90 ensureCaseyCommand(targetCommand);91 var context = initializeConfigurationContext();92 var command = instantiateCommand(targetCommand, context);93 var commandLine = new CommandLine(command);94 var output = new StringWriter();95 commandLine.setOut(new PrintWriter(output));96 return new KcctlCommandContext<>(command, commandLine, output);97 }98 private void ensureCaseyCommand(Class<?> targetCommand) {99 if (!targetCommand.isAnnotationPresent(CommandLine.Command.class)) {100 throw new IntegrationTestException("KcctlCommandContext should target a type annotated with @CommandLine.Command");101 }102 }103 private ConfigurationContext initializeConfigurationContext() {104 try {105 var tempDir = Files.createTempDirectory("kcctl-test");106 var configFile = tempDir.resolve(".kcctl");107 Files.writeString(configFile, String.format("""108 {109 "currentContext": "local",110 "local": {111 "cluster": "%s",112 "username": "testuser",113 "password": "testpassword"114 }115 }116 """, kafkaConnect.getTarget()));117 return new ConfigurationContext(tempDir.toFile());118 }119 catch (IOException e) {120 throw new IntegrationTestException("Couldn't initialize configuration context", e);121 }122 }123 private Object instantiateCommand(Class<?> targetCommand, ConfigurationContext configurationContext) {124 try {125 Constructor<?> constructor = targetCommand.getDeclaredConstructor(ConfigurationContext.class);126 return constructor.newInstance(configurationContext);127 }128 catch (NoSuchMethodException e) {129 throw new IntegrationTestException("Unsupported @CommandLine.Command type. Required a single argument constructor accepting a ConfigurationContext");130 }131 catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {132 throw new IntegrationTestException("Couldn't instantiate command of type " + targetCommand, e);133 }134 }135 public static class IntegrationTestException extends RuntimeException {136 public IntegrationTestException(String msg) {137 super(msg);138 }139 public IntegrationTestException(String msg, Throwable cause) {140 super(msg, cause);141 }142 }143}...

Full Screen

Full Screen

Source:DockerMachineClientProviderStrategy.java Github

copy

Full Screen

1package org.testcontainers.dockerclient;2import com.github.dockerjava.core.LocalDirectorySSLConfig;3import lombok.Getter;4import lombok.extern.slf4j.Slf4j;5import org.testcontainers.utility.CommandLine;6import org.testcontainers.utility.DockerMachineClient;7import java.net.URI;8import java.nio.file.Paths;9import java.util.Arrays;10import java.util.Optional;11import static com.google.common.base.Preconditions.checkArgument;12/**13 * Use Docker machine (if available on the PATH) to locate a Docker environment.14 *15 * @deprecated this class is used by the SPI and should not be used directly16 */17@Slf4j18@Deprecated19public final class DockerMachineClientProviderStrategy extends DockerClientProviderStrategy {20 @Getter(lazy = true)21 private final TransportConfig transportConfig = resolveTransportConfig();22 private TransportConfig resolveTransportConfig() throws InvalidConfigurationException {23 boolean installed = DockerMachineClient.instance().isInstalled();24 checkArgument(installed, "docker-machine executable was not found on PATH (" + Arrays.toString(CommandLine.getSystemPath()) + ")");25 Optional<String> machineNameOptional = DockerMachineClient.instance().getDefaultMachine();26 checkArgument(machineNameOptional.isPresent(), "docker-machine is installed but no default machine could be found");27 String machineName = machineNameOptional.get();28 log.info("Found docker-machine, and will use machine named {}", machineName);29 DockerMachineClient.instance().ensureMachineRunning(machineName);30 String dockerDaemonUrl = DockerMachineClient.instance().getDockerDaemonUrl(machineName);31 log.info("Docker daemon URL for docker machine {} is {}", machineName, dockerDaemonUrl);32 return TransportConfig.builder()33 .dockerHost(URI.create(dockerDaemonUrl))34 .sslConfig(35 new LocalDirectorySSLConfig(36 Paths.get(System.getProperty("user.home") + "/.docker/machine/certs/").toString()37 )38 )39 .build();40 }41 @Override42 protected boolean isApplicable() {43 boolean installed = DockerMachineClient.instance().isInstalled();44 if (!installed) {45 log.info("docker-machine executable was not found on PATH ({})", Arrays.toString(CommandLine.getSystemPath()));46 return false;47 }48 Optional<String> machineNameOptional = DockerMachineClient.instance().getDefaultMachine();49 if (!machineNameOptional.isPresent()) {50 log.info("docker-machine is installed but no default machine could be found");51 }52 return true;53 }54 @Override55 protected boolean isPersistable() {56 return false;57 }58 @Override59 protected int getPriority() {...

Full Screen

Full Screen

Source:CustomWindowsClientProviderStrategy.java Github

copy

Full Screen

...5import lombok.extern.slf4j.Slf4j;6import org.jetbrains.annotations.NotNull;7import org.testcontainers.dockerclient.InvalidConfigurationException;8import org.testcontainers.dockerclient.WindowsClientProviderStrategy;9import org.testcontainers.utility.CommandLine;10import org.testcontainers.utility.DockerMachineClient;11import java.nio.file.Paths;12import java.util.Arrays;13import java.util.Optional;14import static org.testcontainers.shaded.com.google.common.base.Preconditions.checkArgument;15@Slf4j16public class CustomWindowsClientProviderStrategy extends WindowsClientProviderStrategy {17 @Override18 public void test() throws InvalidConfigurationException {19 try {20// boolean installed = DockerMachineClient.instance().isInstalled();21// checkArgument(installed, "docker-machine executable was not found on PATH (" + Arrays.toString(CommandLine.getSystemPath()) + ")");22//23// Optional<String> machineNameOptional = DockerMachineClient.instance().getDefaultMachine();24// checkArgument(machineNameOptional.isPresent(), "docker-machine is installed but no default machine could be found");25// String machineName = machineNameOptional.get();26//27// log.info("Found docker-machine, and will use machine named {}", machineName);28//29// DockerMachineClient.instance().ensureMachineRunning(machineName);30//31// String dockerDaemonIpAddress = DockerMachineClient.instance().getDockerDaemonIpAddress(machineName);32// log.info("Docker daemon IP address for docker machine {} is {}", machineName, dockerDaemonIpAddress);33 config = DefaultDockerClientConfig.createDefaultConfigBuilder()34 .withDockerHost("tcp://" + "192.168.0.130" + ":2376")35 .withDockerTlsVerify(true)...

Full Screen

Full Screen

CommandLine

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.utility;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.containers.output.Slf4jLogConsumer;4import org.slf4j.Logger;5import org.slf4j.LoggerFactory;6public class TestContainer {7 private static final Logger logger = LoggerFactory.getLogger(TestContainer.class);8 public static void main(String[] args) {9 try (GenericContainer container = new GenericContainer("alpine:latest")10 .withCommand("tail", "-f", "/dev/null")11 .withLogConsumer(new Slf4jLogConsumer(logger))) {12 container.start();13 logger.info("Container started");14 Thread.sleep(10000);15 } catch (Exception e) {16 logger.error("Exception occurred while running the container", e);17 }18 }19}

Full Screen

Full Screen

CommandLine

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.utility.CommandLine;2public class 1 {3 public static void main(String[] args) {4 CommandLine cmd = new CommandLine(args);5 System.out.println(cmd.getArgument(0));6 System.out.println(cmd.getArgument(1));7 }8}9import org.testcontainers.utility.DockerImageName;10public class 2 {11 public static void main(String[] args) {12 DockerImageName name = DockerImageName.parse("postgres:13.2");13 System.out.println(name.getUnversionedPart());14 System.out.println(name.getVersionPart());15 }16}17import org.testcontainers.utility.DockerImageName;18public class 3 {19 public static void main(String[] args) {20 DockerImageName name = DockerImageName.parse("postgres:13.2");21 System.out.println(name.getUnversionedPart());22 System.out.println(name.getVersionPart());23 }24}25import org.testcontainers.utility.DockerImageName;26public class 4 {27 public static void main(String[] args) {28 DockerImageName name = DockerImageName.parse("postgres:13.2");29 System.out.println(name.getUnversionedPart());30 System.out.println(name.getVersionPart());31 }32}33import org.testcontainers.utility.DockerImageName;34public class 5 {35 public static void main(String[] args) {36 DockerImageName name = DockerImageName.parse("postgres:13.2");37 System.out.println(name.getUnversionedPart());38 System.out.println(name.getVersionPart());39 }40}41import org.testcontainers.utility.DockerImageName;42public class 6 {43 public static void main(String[] args) {44 DockerImageName name = DockerImageName.parse("postgres:13.2");45 System.out.println(name.getUnversionedPart());46 System.out.println(name.getVersionPart());47 }48}

Full Screen

Full Screen

CommandLine

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.containers.output.Slf4jLogConsumer;3import org.testcontainers.utility.CommandLine;4import org.slf4j.Logger;5import org.slf4j.LoggerFactory;6public class Test {7 private static final Logger logger = LoggerFactory.getLogger(Test.class);8 public static void main(String[] args) {9 GenericContainer container = new GenericContainer("alpine:latest")10 .withCommand("sleep", "9999")11 .withExposedPorts(80);12 container.start();13 Slf4jLogConsumer logConsumer = new Slf4jLogConsumer(logger);14 container.followOutput(logConsumer);15 CommandLine cmd = new CommandLine("sh", "-c", "echo hello");16 cmd.execute(container);17 }18}19[main] INFO org.testcontainers.DockerClientFactory - ✔︎ The Docker daemon should be configured to use a proxy if required by your corporate network (optional)20[main] INFO org.testcontainers.DockerClientFactory - ✔︎ The Docker daemon should be configured to use a proxy if required by your corporate network (optional

Full Screen

Full Screen

CommandLine

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.utility.CommandLine;3import java.io.IOException;4import java.util.List;5public class 1 {6 public static void main(String[] args) throws IOException, InterruptedException {7 try (GenericContainer container = new GenericContainer("alpine:3.12")) {8 container.start();9 CommandLine commandLine = new CommandLine("sh", "-c", "echo hello");10 List<String> result = commandLine.execute(container);11 System.out.println(result);12 }13 }14}

Full Screen

Full Screen

CommandLine

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.utility.CommandLine;2public class Main {3 public static void main(String[] args) {4 CommandLine commandLine = new CommandLine(args);5 String user = commandLine.getEnvVarOrProperty("USER", "default");6 System.out.println("User is " + user);7 int count = commandLine.getIntEnvVarOrProperty("COUNT", 1);8 System.out.println("Count is " + count);9 }10}11import org.testcontainers.utility.CommandLine;12public class Main {13 public static void main(String[] args) {14 CommandLine commandLine = new CommandLine(args);15 String user = commandLine.getEnvVarOrProperty("USER", "default");16 System.out.println("User is " + user);17 int count = commandLine.getIntEnvVarOrProperty("COUNT", 1);18 System.out.println("Count is " + count);19 }20}21import org.testcontainers.utility.CommandLine;22public class Main {23 public static void main(String[] args) {24 CommandLine commandLine = new CommandLine(args);25 String user = commandLine.getEnvVarOrProperty("USER", "default");26 System.out.println("User is " + user);27 int count = commandLine.getIntEnvVarOrProperty("COUNT", 1);28 System.out.println("Count is " + count);29 }30}31import org.testcontainers.utility.CommandLine;32public class Main {33 public static void main(String[] args) {34 CommandLine commandLine = new CommandLine(args);35 String user = commandLine.getEnvVarOrProperty("USER", "default");36 System.out.println("User is " + user);37 int count = commandLine.getIntEnvVarOrProperty("COUNT", 1);38 System.out.println("Count is " + count);39 }40}

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.

Run Testcontainers-java automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful