├── .editorconfig ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE.md ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── main └── java │ └── com │ └── github │ └── geowarin │ └── junit │ ├── DockerRule.java │ ├── DockerRuleBuilder.java │ └── DockerRuleParams.java └── test └── java └── integration └── RabbitIntegrationTest.java /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /gradle.properties 2 | 3 | .idea 4 | *.iml 5 | 6 | # gradle 7 | .gradle 8 | build 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | 3 | services: 4 | - docker 5 | 6 | script: 7 | - ./gradlew assemble 8 | - ./gradlew check --info 9 | 10 | before_cache: 11 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 12 | cache: 13 | directories: 14 | - $HOME/.gradle/caches/ 15 | - $HOME/.gradle/wrapper/ 16 | 17 | language: java 18 | 19 | jdk: 20 | - oraclejdk8 21 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to this project will be documented in this file. 3 | This project adheres to [Semantic Versioning](http://semver.org/). 4 | 5 | ## 1.2.0 6 | 7 | - Add `isLocalImage` to the builder to specify image which should not be pulled from the registry (#4 by @fagossa) 8 | - Upgrade to com.spotify:docker-client:8.9.1 9 | ⚠️ We no longer use the shaded version because of https://github.com/spotify/docker-client/issues/900 10 | - Fix default environment (it now works with docker for mac) 11 | 12 | ## 1.1.0 13 | 14 | - Add a builder to remove the need for inheritance 15 | - Add a waitForLog directive 16 | 17 | ## 1.0.2 18 | > 2016-01-06 19 | 20 | - Include guava in the dependencies 21 | 22 | ## 1.0.1 23 | > 2016-01-06 24 | 25 | - Use the shaded jar of the docker-client 26 | 27 | ## 1.0.0 28 | > 2016-01-06 29 | 30 | - Initial release 31 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Geoffroy Warin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # docker-junit-rule 2 | 3 | A junit rule to run docker containers 4 | 5 | [![Build Status](https://travis-ci.org/geowarin/docker-junit-rule.svg)](https://travis-ci.org/geowarin/docker-junit-rule) 6 | 7 | ## Usage 8 | 9 | Example for rabbitMQ: 10 | 11 | ```java 12 | import com.github.geowarin.junit.DockerRule; 13 | import com.rabbitmq.client.ConnectionFactory; 14 | import org.junit.ClassRule; 15 | import org.junit.Test; 16 | 17 | public class RabbitIntegrationTest { 18 | 19 | @ClassRule 20 | public static DockerRule rabbitRule = 21 | DockerRule.builder() 22 | .image("rabbitmq:management") 23 | .ports("5672") 24 | // .waitForPort("5672/tcp") 25 | .waitForLog("Server startup complete") 26 | .build(); 27 | 28 | @Test 29 | public void testConnectsToDocker() throws Exception { 30 | ConnectionFactory factory = new ConnectionFactory(); 31 | factory.setHost(rabbitRule.getDockerHost()); 32 | factory.setPort(rabbitRule.getHostPort("5672/tcp")); 33 | factory.newConnection(); 34 | } 35 | } 36 | ``` 37 | 38 | ## Installation 39 | 40 | The library is available on jcenter 41 | 42 | ### Maven 43 | 44 | Add the following to your `pom.xml`: 45 | 46 | ```xml 47 | 48 | 49 | 50 | false 51 | 52 | central 53 | bintray 54 | http://jcenter.bintray.com 55 | 56 | 57 | 58 | ... 59 | 60 | 61 | com.github.geowarin 62 | docker-junit-rule 63 | 1.1.0 64 | test 65 | 66 | ``` 67 | 68 | ### Gradle 69 | 70 | Add the following to your `build.gradle`: 71 | 72 | ```groovy 73 | repositories { 74 | jcenter() 75 | } 76 | 77 | dependencies { 78 | testCompile 'com.github.geowarin:docker-junit-rule:1.1.0' 79 | } 80 | ``` 81 | 82 | ## Principle 83 | 84 | Uses https://github.com/spotify/docker-client to connect to the docker daemon API. 85 | 86 | Tested with docker-for-mac and travis runs it on linux. 87 | If it does not work with docker-for-windows, please open a PR ;) 88 | 89 | ## Licence 90 | 91 | MIT 92 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "com.jfrog.bintray" version "1.3.1" 3 | } 4 | 5 | allprojects { 6 | repositories { 7 | jcenter() 8 | } 9 | apply plugin: 'maven' 10 | apply plugin: 'maven-publish' 11 | apply plugin: 'java' 12 | } 13 | 14 | group = 'com.github.geowarin' 15 | version = '1.2.0' 16 | 17 | description = 'A junit rule to run docker containers' 18 | 19 | sourceCompatibility = 1.7 20 | targetCompatibility = 1.7 21 | 22 | repositories { 23 | mavenCentral() 24 | } 25 | 26 | dependencies { 27 | compile 'org.slf4j:slf4j-api:1.7.12' 28 | compile 'com.spotify:docker-client:8.9.1' 29 | compileOnly('junit:junit:4.12') 30 | testCompile('junit:junit:4.12') 31 | testCompile 'org.slf4j:slf4j-simple:1.7.12' 32 | testCompile 'com.rabbitmq:amqp-client:3.2.1' 33 | } 34 | 35 | task sourcesJar(type: Jar, dependsOn: classes) { 36 | classifier = 'sources' 37 | from sourceSets.main.allSource 38 | } 39 | 40 | task javadocJar(type: Jar, dependsOn: javadoc) { 41 | classifier = 'javadoc' 42 | from javadoc.destinationDir 43 | } 44 | 45 | artifacts { 46 | archives sourcesJar, javadocJar 47 | } 48 | 49 | publishing { 50 | publications { 51 | JarPublication(MavenPublication) { 52 | from components.java 53 | artifact sourcesJar 54 | artifact javadocJar 55 | } 56 | } 57 | } 58 | 59 | def bintrayUser = project.hasProperty('bintrayUser') ? project.bintrayUser : System.getenv('BINTRAY_USER') 60 | def bintrayKey = project.hasProperty('bintrayKey') ? project.bintrayKey : System.getenv('BINTRAY_KEY') 61 | 62 | bintray { 63 | user = bintrayUser 64 | key = bintrayKey 65 | publications = ['JarPublication'] 66 | pkg { 67 | repo = 'maven' 68 | name = project.name 69 | desc = project.description 70 | licenses = ['MIT'] 71 | vcsUrl = 'https://github.com/geowarin/docker-junit-rule.git' 72 | version { 73 | name = project.version 74 | desc = project.description 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geowarin/docker-junit-rule/8439647b12625d86e0ff09fb76e92e7a8a599906/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Nov 13 15:42:13 CET 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.2-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/main/java/com/github/geowarin/junit/DockerRule.java: -------------------------------------------------------------------------------- 1 | package com.github.geowarin.junit; 2 | 3 | import com.spotify.docker.client.DefaultDockerClient; 4 | import com.spotify.docker.client.DockerClient; 5 | import com.spotify.docker.client.LogMessage; 6 | import com.spotify.docker.client.LogStream; 7 | import com.spotify.docker.client.exceptions.DockerCertificateException; 8 | import com.spotify.docker.client.exceptions.DockerException; 9 | import com.spotify.docker.client.messages.*; 10 | import org.apache.commons.logging.Log; 11 | import org.apache.commons.logging.LogFactory; 12 | import org.junit.rules.ExternalResource; 13 | 14 | import java.io.IOException; 15 | import java.io.UnsupportedEncodingException; 16 | import java.net.InetSocketAddress; 17 | import java.net.SocketAddress; 18 | import java.nio.ByteBuffer; 19 | import java.nio.channels.SocketChannel; 20 | import java.util.Collections; 21 | import java.util.HashMap; 22 | import java.util.List; 23 | import java.util.Map; 24 | 25 | import static com.spotify.docker.client.DockerClient.LogsParam.follow; 26 | import static com.spotify.docker.client.DockerClient.LogsParam.stdout; 27 | import static com.spotify.docker.client.DockerClient.RemoveContainerParam.removeVolumes; 28 | 29 | /** 30 | *

31 | * JUnit rule starting a docker container before the test and killing it 32 | * afterwards. 33 | *

34 | *

35 | * Uses spotify/docker-client. 36 | * Adapted from https://gist.github.com/mosheeshel/c427b43c36b256731a0b 37 | *

38 | * author: Geoffroy Warin (geowarin.github.io) 39 | */ 40 | public class DockerRule extends ExternalResource { 41 | protected final Log logger = LogFactory.getLog(getClass()); 42 | public static final String DOCKER_MACHINE_SERVICE_URL = "https://192.168.99.100:2376"; 43 | 44 | private final DockerClient dockerClient; 45 | private ContainerCreation container; 46 | private Map> ports; 47 | private DockerRuleParams params; 48 | 49 | public static DockerRuleBuilder builder() { 50 | return new DockerRuleBuilder(); 51 | } 52 | 53 | DockerRule(DockerRuleParams params) { 54 | this.params = params; 55 | dockerClient = createDockerClient(); 56 | ContainerConfig containerConfig = createContainerConfig(params.imageName, params.ports, params.cmd); 57 | 58 | try { 59 | if (!params.isLocalImage) { 60 | dockerClient.pull(params.imageName); 61 | } 62 | container = dockerClient.createContainer(containerConfig); 63 | } catch (DockerException | InterruptedException e) { 64 | throw new IllegalStateException(e); 65 | } 66 | } 67 | 68 | @Override 69 | protected void before() throws Throwable { 70 | super.before(); 71 | dockerClient.startContainer(container.id()); 72 | ContainerInfo info = dockerClient.inspectContainer(container.id()); 73 | ports = info.networkSettings().ports(); 74 | 75 | if (params.portToWaitOn != null) { 76 | waitForPort(getHostPort(params.portToWaitOn), params.waitTimeout); 77 | } 78 | 79 | if (params.logToWait != null) { 80 | waitForLog(params.logToWait); 81 | } 82 | } 83 | 84 | @Override 85 | protected void after() { 86 | super.after(); 87 | try { 88 | dockerClient.killContainer(container.id()); 89 | dockerClient.removeContainer(container.id(), removeVolumes()); 90 | dockerClient.close(); 91 | } catch (DockerException | InterruptedException e) { 92 | throw new RuntimeException("Unable to stop/remove docker container " + container.id(), e); 93 | } 94 | } 95 | 96 | /** 97 | * Utility method to get the docker host. 98 | * Can be different from localhost if using docker-machine 99 | * 100 | * @return The current docker host 101 | */ 102 | public String getDockerHost() { 103 | return dockerClient.getHost(); 104 | } 105 | 106 | protected void waitForPort(int port, long timeoutInMillis) { 107 | SocketAddress address = new InetSocketAddress(getDockerHost(), port); 108 | long totalWait = 0; 109 | while (true) { 110 | try { 111 | SocketChannel.open(address); 112 | return; 113 | } catch (IOException e) { 114 | try { 115 | Thread.sleep(100); 116 | totalWait += 100; 117 | if (totalWait > timeoutInMillis) { 118 | throw new IllegalStateException("Timeout while waiting for port " + port); 119 | } 120 | } catch (InterruptedException ie) { 121 | throw new IllegalStateException(ie); 122 | } 123 | } 124 | } 125 | } 126 | 127 | protected DockerClient createDockerClient() { 128 | try { 129 | return DefaultDockerClient.fromEnv().build(); 130 | } catch (DockerCertificateException e) { 131 | throw new IllegalStateException("Could not create docker client from environement", e); 132 | } 133 | } 134 | 135 | protected ContainerConfig createContainerConfig(String imageName, String[] ports, String cmd) { 136 | Map> portBindings = new HashMap<>(); 137 | for (String port : ports) { 138 | List hostPorts = Collections.singletonList(PortBinding.randomPort("0.0.0.0")); 139 | portBindings.put(port, hostPorts); 140 | } 141 | 142 | HostConfig hostConfig = HostConfig.builder() 143 | .portBindings(portBindings) 144 | .build(); 145 | 146 | ContainerConfig.Builder configBuilder = ContainerConfig.builder() 147 | .hostConfig(hostConfig) 148 | .image(imageName) 149 | .networkDisabled(false) 150 | .exposedPorts(ports); 151 | 152 | if (cmd != null) { 153 | configBuilder = configBuilder.cmd(cmd); 154 | } 155 | return configBuilder.build(); 156 | } 157 | 158 | public int getHostPort(String containerPort) { 159 | List portBindings = ports.get(containerPort); 160 | if (portBindings.isEmpty()) { 161 | return -1; 162 | } 163 | return Integer.parseInt(portBindings.get(0).hostPort()); 164 | } 165 | 166 | protected void waitForLog(String messageToMatch) throws DockerException, InterruptedException, UnsupportedEncodingException { 167 | LogStream logs = dockerClient.logs(container.id(), follow(), stdout()); 168 | String log; 169 | do { 170 | LogMessage logMessage = logs.next(); 171 | ByteBuffer buffer = logMessage.content(); 172 | byte[] bytes = new byte[buffer.remaining()]; 173 | buffer.get(bytes); 174 | log = new String(bytes); 175 | } while (!log.contains(messageToMatch)); 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /src/main/java/com/github/geowarin/junit/DockerRuleBuilder.java: -------------------------------------------------------------------------------- 1 | package com.github.geowarin.junit; 2 | 3 | public class DockerRuleBuilder { 4 | private final DockerRuleParams params = new DockerRuleParams(); 5 | 6 | /** 7 | * @param imageName The name of the docker image to download 8 | * @return The builder 9 | */ 10 | public DockerRuleBuilder image(String imageName) { 11 | params.imageName = imageName; 12 | return this; 13 | } 14 | 15 | /** 16 | *

17 | * List the container ports that you would like to open in the container. 18 | * They will be bound on your host on random ports. 19 | *

20 | *

21 | * To know which ports are used on your host use DockerRule#getHostPort(String). 22 | * Example: 23 | *

24 | *
25 |    * {@code
26 |    * myRule.getHostPort("80/tcp")
27 |    * }
28 |    * 
29 | * 30 | * @param ports The ports to open on the container 31 | * @return The builder 32 | * @see DockerRule#getHostPort(String) 33 | */ 34 | public DockerRuleBuilder ports(String... ports) { 35 | params.ports = ports; 36 | return this; 37 | } 38 | 39 | public DockerRuleBuilder cmd(String cmd) { 40 | params.cmd = cmd; 41 | return this; 42 | } 43 | 44 | /** 45 | * @param isLocalImage If the image has been built locally 46 | * @return The builder 47 | */ 48 | public DockerRuleBuilder isLocalImage(boolean isLocalImage) { 49 | params.isLocalImage = isLocalImage; 50 | return this; 51 | } 52 | 53 | /** 54 | * Utility method to ensure a container is started 55 | * 56 | * @param portToWaitOn The port to wait on 57 | * @return The builder 58 | */ 59 | public DockerRuleBuilder waitForPort(String portToWaitOn) { 60 | return waitForPort(portToWaitOn, 10000); 61 | } 62 | 63 | /** 64 | * Utility method to ensure a container is started 65 | * 66 | * @param portToWaitOn The port to wait on 67 | * @param timeoutInMillis Maximum waiting time in milliseconds 68 | * @return The builder 69 | */ 70 | public DockerRuleBuilder waitForPort(String portToWaitOn, int timeoutInMillis) { 71 | params.portToWaitOn = portToWaitOn; 72 | params.waitTimeout = timeoutInMillis; 73 | return this; 74 | } 75 | 76 | /** 77 | * @param logToWait The log message to wait. 78 | * This will stop blocking as soon as the docker logs contains that string 79 | * @return The builder 80 | */ 81 | public DockerRuleBuilder waitForLog(String logToWait) { 82 | params.logToWait = logToWait; 83 | return this; 84 | } 85 | 86 | public DockerRule build() { 87 | return new DockerRule(params); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/github/geowarin/junit/DockerRuleParams.java: -------------------------------------------------------------------------------- 1 | package com.github.geowarin.junit; 2 | 3 | public class DockerRuleParams { 4 | 5 | String imageName; 6 | 7 | String[] ports; 8 | String cmd; 9 | 10 | String portToWaitOn; 11 | public int waitTimeout; 12 | String logToWait; 13 | 14 | boolean isLocalImage; 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/integration/RabbitIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package integration; 2 | 3 | import com.github.geowarin.junit.DockerRule; 4 | import com.rabbitmq.client.ConnectionFactory; 5 | import org.junit.ClassRule; 6 | import org.junit.Test; 7 | 8 | public class RabbitIntegrationTest { 9 | 10 | @ClassRule 11 | public static DockerRule rabbitRule = 12 | DockerRule.builder() 13 | .image("rabbitmq:management") 14 | .ports("5672") 15 | // .waitForPort("5672/tcp") 16 | .waitForLog("Server startup complete") 17 | .build(); 18 | 19 | @Test 20 | public void testConnectsToDocker() throws Exception { 21 | ConnectionFactory factory = new ConnectionFactory(); 22 | factory.setHost(rabbitRule.getDockerHost()); 23 | factory.setPort(rabbitRule.getHostPort("5672/tcp")); 24 | factory.newConnection(); 25 | } 26 | } 27 | --------------------------------------------------------------------------------