Best Testcontainers-java code snippet using org.testcontainers.DockerRegistryContainer
Source:DockerClientTest.java
1package org.keycloak.testsuite.docker;2import org.junit.Assert;3import org.junit.BeforeClass;4import org.junit.Test;5import org.keycloak.common.Profile;6import org.keycloak.representations.idm.KeysMetadataRepresentation;7import org.keycloak.representations.idm.RealmRepresentation;8import org.keycloak.testsuite.AbstractKeycloakTest;9import org.keycloak.testsuite.ProfileAssume;10import org.slf4j.LoggerFactory;11import org.testcontainers.containers.BindMode;12import org.testcontainers.containers.Container;13import org.testcontainers.containers.GenericContainer;14import org.testcontainers.containers.output.Slf4jLogConsumer;15import sun.security.provider.X509Factory;16import java.io.File;17import java.io.PrintWriter;18import java.util.HashMap;19import java.util.List;20import java.util.Map;21import java.util.Optional;22import static org.hamcrest.MatcherAssert.assertThat;23import static org.hamcrest.Matchers.containsString;24import static org.junit.Assume.assumeTrue;25import static org.keycloak.testsuite.util.WaitUtils.pause;26public class DockerClientTest extends AbstractKeycloakTest {27 public static final String REALM_ID = "docker-test-realm";28 public static final String CLIENT_ID = "docker-test-client";29 public static final String DOCKER_USER = "docker-user";30 public static final String DOCKER_USER_PASSWORD = "password";31 public static final String REGISTRY_HOSTNAME = "localhost";32 public static final Integer REGISTRY_PORT = 5000;33 public static final String MINIMUM_DOCKER_VERSION = "1.8.0";34 private GenericContainer dockerRegistryContainer = null;35 private GenericContainer dockerClientContainer = null;36 private static String hostIp;37 private static String authServerPort;38 @BeforeClass39 public static void verifyEnvironment() {40 ProfileAssume.assumeFeatureEnabled(Profile.Feature.DOCKER);41 final Optional<DockerVersion> dockerVersion = new DockerHostVersionSupplier().get();42 assumeTrue("Could not determine docker version for host machine. It either is not present or accessible to the JVM running the test harness.", dockerVersion.isPresent());43 assumeTrue("Docker client on host machine is not a supported version. Please upgrade and try again.", DockerVersion.COMPARATOR.compare(dockerVersion.get(), DockerVersion.parseVersionString(MINIMUM_DOCKER_VERSION)) >= 0);44 hostIp = System.getProperty("host.ip");45 if (hostIp == null) {46 final Optional<String> foundHostIp = new DockerHostIpSupplier().get();47 if (foundHostIp.isPresent()) {48 hostIp = foundHostIp.get();49 }50 }51 Assert.assertNotNull("Could not resolve host machine's IP address for docker adapter, and 'host.ip' system poperty not set. Client will not be able to authenticate against the keycloak server!", hostIp);52 authServerPort = AUTH_SERVER_SSL_REQUIRED ? System.getProperty("auth.server.https.port") : System.getProperty("auth.server.http.port");53 }54 @Override55 public void addTestRealms(final List<RealmRepresentation> testRealms) {56 final RealmRepresentation dockerRealm = DockerTestRealmSetup.createRealm(REALM_ID);57 DockerTestRealmSetup.configureDockerRegistryClient(dockerRealm, CLIENT_ID);58 DockerTestRealmSetup.configureUser(dockerRealm, DOCKER_USER, DOCKER_USER_PASSWORD);59 testRealms.add(dockerRealm);60 }61 @Override62 public void beforeAbstractKeycloakTest() throws Exception {63 super.beforeAbstractKeycloakTest();64 // find the realm cert65 String realmCert = null;66 List<KeysMetadataRepresentation.KeyMetadataRepresentation> realmKeys = adminClient.realm(REALM_ID).keys().getKeyMetadata().getKeys();67 for (KeysMetadataRepresentation.KeyMetadataRepresentation key : realmKeys) {68 if (key.getType().equals("RSA")) {69 realmCert = key.getCertificate();70 }71 }72 if (realmCert == null) {73 throw new IllegalStateException("Cannot find public realm cert");74 }75 // save the cert to a file76 File tmpCertFile = File.createTempFile("keycloak-docker-realm-cert-", ".pem");77 tmpCertFile.deleteOnExit();78 PrintWriter tmpCertWriter = new PrintWriter(tmpCertFile);79 tmpCertWriter.println(X509Factory.BEGIN_CERT);80 tmpCertWriter.println(realmCert);81 tmpCertWriter.println(X509Factory.END_CERT);82 tmpCertWriter.close();83 final Map<String, String> environment = new HashMap<>();84 environment.put("REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY", "/tmp");85 environment.put("REGISTRY_AUTH_TOKEN_REALM", "http://" + hostIp + ":" + authServerPort + "/auth/realms/" + REALM_ID + "/protocol/docker-v2/auth");86 environment.put("REGISTRY_AUTH_TOKEN_SERVICE", CLIENT_ID);87 environment.put("REGISTRY_AUTH_TOKEN_ISSUER", "http://" + hostIp + ":" + authServerPort + "/auth/realms/" + REALM_ID);88 environment.put("REGISTRY_AUTH_TOKEN_ROOTCERTBUNDLE", "/opt/kc-certs/" + tmpCertFile.getCanonicalFile().getName());89 environment.put("INSECURE_REGISTRY", "--insecure-registry " + REGISTRY_HOSTNAME + ":" + REGISTRY_PORT);90 String dockerioPrefix = Boolean.parseBoolean(System.getProperty("docker.io-prefix-explicit")) ? "docker.io/" : "";91 dockerRegistryContainer = new GenericContainer(dockerioPrefix + "registry:2")92 .withFileSystemBind(tmpCertFile.getCanonicalPath(), "/opt/kc-certs/" + tmpCertFile.getCanonicalFile().getName(), BindMode.READ_ONLY)93 .withEnv(environment)94 .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("dockerRegistryContainer")))95 .withNetworkMode("host")96 .withPrivilegedMode(true);97 dockerRegistryContainer.start();98 dockerClientContainer = new GenericContainer(dockerioPrefix + "docker:dind")99 .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("dockerClientContainer")))100 .withNetworkMode("host")101 .withPrivilegedMode(true);102 dockerClientContainer.start();103 }104 @Override105 public void afterAbstractKeycloakTest() {106 super.afterAbstractKeycloakTest();107 pause(5000); // wait for the container logs108 dockerClientContainer.close();109 dockerRegistryContainer.close();110 }111 @Test112 public void shouldPerformDockerAuthAgainstRegistry() throws Exception {113 log.info("Starting the attempt for login...");114 Container.ExecResult dockerLoginResult = dockerClientContainer.execInContainer("docker", "login", "-u", DOCKER_USER, "-p", DOCKER_USER_PASSWORD, REGISTRY_HOSTNAME + ":" + REGISTRY_PORT);115 printCommandResult(dockerLoginResult);116 assertThat(dockerLoginResult.getStdout(), containsString("Login Succeeded"));117 }118 private void printCommandResult(Container.ExecResult result) {119 log.infof("Command executed. Output follows:\nSTDOUT: %s\n---\nSTDERR: %s", result.getStdout(), result.getStderr());120 }121}...
DockerRegistryContainer
Using AI Code Generation
1 public void testDockerRegistryContainer() throws Exception {2 DockerRegistryContainer registry = new DockerRegistryContainer();3 registry.start();4 DockerClientFactory.instance().client()5 .pushImageCmd("alpine:3.3")6 .withTag("alpine:3.3")7 .withAuthConfig(registry.getAuthConfig())8 .exec(new PushImageResultCallback())9 .awaitSuccess();10 registry.stop();11 }12}13The DockerRegistryContainer class also provides the getRegistryUrl() method to get the URL of the Docker registry container. You can use this method to get the URL of the Docker registry container. For example, you can use the following code to get the URL of the Docker registry container:14String registryUrl = registry.getRegistryUrl();15The DockerRegistryContainer class also provides the getRegistryPort() method to get the port of the Docker registry container. You can use this method to get the port of the Docker registry container. For example, you can use the following code to get the port of the Docker registry container:16int registryPort = registry.getRegistryPort();17The DockerRegistryContainer class also provides the withRegistryUrl(String) method to set the URL of the Docker registry container. You can use this method to set the URL of the Docker registry container. For example, you can use the following code to set the URL of the Docker registry container:18registry.withRegistryUrl("
DockerRegistryContainer
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer2import org.testcontainers.containers.DockerRegistryContainer3import org.testcontainers.containers.GenericContainer4import org.testcontainers.containers.wait.strategy.Wait5import org.testcontainers.images.builder.ImageFromDockerfile6import org.testcontainers.utility.DockerImageName7import java.io.File8import java.nio.file.Files9def registry = new DockerRegistryContainer()10registry.start()11def imageName = DockerImageName.parse("alpine")12def image = new ImageFromDockerfile()13 .withDockerfileFromBuilder { builder ->14 builder.from(imageName)15 .cmd("sleep", "9999")16 .build()17 }18 .withFileFromFile(".", new File("build.gradle"))19 .withFileFromFile("src", new File("src"))20def imageId = image.get()21registry.start()22registry.addImage(imageId)23def container = new GenericContainer(DockerImageName.parse(imageId))24 .withExposedPorts(80)25 .waitingFor(Wait.forHttp("/"))26 .withCommand("sleep", "9999")27 .start()28def compose = new DockerComposeContainer(new File("src/test/resources/compose/docker-compose.yml"))29 .withExposedService("service_1", 80)30 .withLocalCompose(true)31 .withPull(false)32 .withEnv("TEST_VAR", "test")33 .withCommand("up -d")34 .withTailChildContainers(true)35 .withLogConsumer("service_1", new Slf4jLogConsumer(log))36 .start()37def compose = new DockerComposeContainer(new File("src/test/resources/compose/docker-compose.yml"))38 .withExposedService("service_1", 80)39 .withLocalCompose(true)40 .withPull(false)41 .withEnv("TEST_VAR", "test")42 .withCommand("up -d")43 .withTailChildContainers(true)44 .withLogConsumer("service_1", new Slf4jLogConsumer(log))45 .start()46def compose = new DockerComposeContainer(new File("src/test/resources/compose/docker-compose.yml"))47 .withExposedService("service_1", 80)48 .withLocalCompose(true)49 .withPull(false)50 .withEnv("TEST_VAR", "
DockerRegistryContainer
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer2import org.testcontainers.containers.DockerRegistryContainer3import org.testcontainers.containers.GenericContainer4import org.testcontainers.containers.wait.strategy.Wait5import org.testcontainers.images.builder.ImageFromDockerfile6import org.testcontainers.utility.DockerImageName7import java.io.File8import java.nio.file.Files9def registry = new DockerRegistryContainer()10registry.start()11def imageName = DockerImageName.parse("alpine")12def image = new ImageFromDockerfile()13 .withDockerfileFromBuilder { builder ->14 builder.from(imageName)15 .cmd("sleep", "9999")16 .build()17 }18 .withFileFromFile(".", new File("build.gradle"))19 .withFileFromFile("src", new File("src"))20def imageId = image.get()21registry.start()22registry.addImage(imageId)23def container = new GenericContainer(DockerImageName.parse(imageId))24 .withExposedPorts(80)25 .waitingFor(Wait.forHttp("/"))26 .withCommand("sleep", "9999")27 .start()28def compose = new DockerComposeContainer(new File("src/test/resources/compose/docker-compose.yml"))29 .withExposedService("service_1", 80)30 .withLocalCompose(true)31 .withPull(false)32 .withEnv("TEST_VAR", "test")33 .withCommand("up -d")34 .withTailChildContainers(true)35 .withLogConsumer("service_1", new Slf4jLogConsumer(log))36 .start()37def compose = new DockerComposeContainer(new File("src/test/resources/compose/docker-compose.yml"))38 .withExposedService("service_1", 80)39 .withLocalCompose(true)40 .withPull(false)41 .withEnv("TEST_VAR", "test")42 .withCommand("up -d")43 .withTailChildContainers(true)44 .withLogConsumer("service_1", new Slf4jLogConsumer(log))45 .start()46def compose = new DockerComposeContainer(new File("src/test/resources/compose/docker-compose.yml"))47 .withExposedService("service_1", 80)48 .withLocalCompose(true)49 .withPull(false)50 .withEnv("TEST_VAR", "
DockerRegistryContainer
Using AI Code Generation
1 public void testDockerRegistryContainer() throws Exception {2 DockerRegistryContainer registry = new DockerRegistryContainer();3 registry.start();4 DockerClientFactory.instance().client()5 .pushImageCmd("alpine:3.3")6 .withTag("alpine:3.3")7 .withAuthConfig(registry.getAuthConfig())8 .exec(new PushImageResultCallback())9 .awaitSuccess();10 registry.stop();11 }12}13The DockerRegistryContainer class also provides the getRegistryUrl() method to get the URL of the Docker registry container. You can use this method to get the URL of the Docker registry container. For example, you can use the following code to get the URL of the Docker registry container:14String registryUrl = registry.getRegistryUrl();15The DockerRegistryContainer class also provides the getRegistryPort() method to get the port of the Docker registry container. You can use this method to get the port of the Docker registry container. For example, you can use the following code to get the port of the Docker registry container:16int registryPort = registry.getRegistryPort();17The DockerRegistryContainer class also provides the withRegistryUrl(String) method to set the URL of the Docker registry container. You can use this method to set the URL of the Docker registry container. For example, you can use the following code to set the URL of the Docker registry container:18registry.withRegistryUrl("
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!