|
| 1 | +/* |
| 2 | + * Copyright 2012-2019 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.boot.testsupport.testcontainers; |
| 18 | + |
| 19 | +import java.util.function.Supplier; |
| 20 | + |
| 21 | +import org.junit.AssumptionViolatedException; |
| 22 | +import org.junit.rules.TestRule; |
| 23 | +import org.junit.runner.Description; |
| 24 | +import org.junit.runners.model.Statement; |
| 25 | +import org.testcontainers.DockerClientFactory; |
| 26 | +import org.testcontainers.containers.FailureDetectingExternalResource; |
| 27 | +import org.testcontainers.containers.GenericContainer; |
| 28 | + |
| 29 | +/** |
| 30 | + * A {@link GenericContainer} decorator that skips test execution when Docker is not |
| 31 | + * available. |
| 32 | + * |
| 33 | + * @param <T> type of the underlying container |
| 34 | + * @author Andy Wilkinson |
| 35 | + */ |
| 36 | +public class SkippableContainer<T> implements TestRule { |
| 37 | + |
| 38 | + private final Supplier<T> containerFactory; |
| 39 | + |
| 40 | + private T container; |
| 41 | + |
| 42 | + public SkippableContainer(Supplier<T> containerFactory) { |
| 43 | + this.containerFactory = containerFactory; |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + public Statement apply(Statement base, Description description) { |
| 48 | + try { |
| 49 | + DockerClientFactory.instance().client(); |
| 50 | + } |
| 51 | + catch (Throwable ex) { |
| 52 | + return new SkipStatement(); |
| 53 | + } |
| 54 | + this.container = this.containerFactory.get(); |
| 55 | + return ((FailureDetectingExternalResource) this.container).apply(base, |
| 56 | + description); |
| 57 | + } |
| 58 | + |
| 59 | + public T getContainer() { |
| 60 | + if (this.container == null) { |
| 61 | + throw new IllegalStateException( |
| 62 | + "Container cannot be accessed prior to test invocation"); |
| 63 | + } |
| 64 | + return this.container; |
| 65 | + } |
| 66 | + |
| 67 | + private static class SkipStatement extends Statement { |
| 68 | + |
| 69 | + @Override |
| 70 | + public void evaluate() { |
| 71 | + throw new AssumptionViolatedException( |
| 72 | + "Could not find a valid Docker environment."); |
| 73 | + } |
| 74 | + |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments