|
| 1 | +/* |
| 2 | + * Copyright 2002-2016 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.test.context.junit.jupiter; |
| 18 | + |
| 19 | +import java.lang.annotation.Annotation; |
| 20 | +import java.lang.reflect.AnnotatedElement; |
| 21 | +import java.util.Optional; |
| 22 | +import java.util.function.Function; |
| 23 | + |
| 24 | +import org.apache.commons.logging.Log; |
| 25 | +import org.apache.commons.logging.LogFactory; |
| 26 | + |
| 27 | +import org.junit.jupiter.api.extension.ConditionEvaluationResult; |
| 28 | +import org.junit.jupiter.api.extension.ContainerExecutionCondition; |
| 29 | +import org.junit.jupiter.api.extension.ExtensionContext; |
| 30 | +import org.junit.jupiter.api.extension.TestExecutionCondition; |
| 31 | + |
| 32 | +import org.springframework.beans.factory.config.BeanExpressionContext; |
| 33 | +import org.springframework.beans.factory.config.BeanExpressionResolver; |
| 34 | +import org.springframework.beans.factory.config.ConfigurableBeanFactory; |
| 35 | +import org.springframework.context.ApplicationContext; |
| 36 | +import org.springframework.context.ConfigurableApplicationContext; |
| 37 | +import org.springframework.core.annotation.AnnotatedElementUtils; |
| 38 | +import org.springframework.util.Assert; |
| 39 | +import org.springframework.util.StringUtils; |
| 40 | + |
| 41 | +/** |
| 42 | + * Abstract base class for implementations of {@link ContainerExecutionCondition} |
| 43 | + * and {@link TestExecutionCondition} that evaluate expressions configured via |
| 44 | + * annotations to determine if a container or test is enabled. |
| 45 | + * |
| 46 | + * <p>Expressions can be any of the following. |
| 47 | + * |
| 48 | + * <ul> |
| 49 | + * <li>Spring Expression Language (SpEL) expression — for example: |
| 50 | + * <pre style="code">#{systemProperties['os.name'].toLowerCase().contains('mac')}</pre> |
| 51 | + * <li>Placeholder for a property available in the Spring |
| 52 | + * {@link org.springframework.core.env.Environment Environment} — for example: |
| 53 | + * <pre style="code">${smoke.tests.enabled}</pre> |
| 54 | + * <li>Text literal — for example: |
| 55 | + * <pre style="code">true</pre> |
| 56 | + * </ul> |
| 57 | + * |
| 58 | + * @author Sam Brannen |
| 59 | + * @author Tadaya Tsuyukubo |
| 60 | + * @since 5.0 |
| 61 | + * @see EnabledIf |
| 62 | + * @see DisabledIf |
| 63 | + */ |
| 64 | +abstract class AbstractExpressionEvaluatingCondition implements ContainerExecutionCondition, TestExecutionCondition { |
| 65 | + |
| 66 | + private static final Log logger = LogFactory.getLog(AbstractExpressionEvaluatingCondition.class); |
| 67 | + |
| 68 | + |
| 69 | + /** |
| 70 | + * Evaluate the expression configured via the supplied annotation type on |
| 71 | + * the {@link AnnotatedElement} for the supplied {@link ExtensionContext}. |
| 72 | + * |
| 73 | + * @param annotationType the type of annotation to process |
| 74 | + * @param expressionExtractor a function that extracts the expression from |
| 75 | + * the annotation |
| 76 | + * @param reasonExtractor a function that extracts the reason from the |
| 77 | + * annotation |
| 78 | + * @param enabledOnTrue indicates whether the returned {@code ConditionEvaluationResult} |
| 79 | + * should be {@link ConditionEvaluationResult#enabled enabled} if the expression |
| 80 | + * evaluates to {@code true} |
| 81 | + * @param context the {@code ExtensionContext} |
| 82 | + * @return {@link ConditionEvaluationResult#enabled enabled} if the container |
| 83 | + * or test should be enabled; otherwise {@link ConditionEvaluationResult#disabled disabled} |
| 84 | + */ |
| 85 | + protected <A extends Annotation> ConditionEvaluationResult evaluateAnnotation(Class<A> annotationType, |
| 86 | + Function<A, String> expressionExtractor, Function<A, String> reasonExtractor, boolean enabledOnTrue, |
| 87 | + ExtensionContext context) { |
| 88 | + |
| 89 | + AnnotatedElement element = context.getElement().get(); |
| 90 | + Optional<A> annotation = findMergedAnnotation(element, annotationType); |
| 91 | + |
| 92 | + if (!annotation.isPresent()) { |
| 93 | + String reason = String.format("%s is enabled since @%s is not present", element, |
| 94 | + annotationType.getSimpleName()); |
| 95 | + if (logger.isDebugEnabled()) { |
| 96 | + logger.debug(reason); |
| 97 | + } |
| 98 | + return ConditionEvaluationResult.enabled(reason); |
| 99 | + } |
| 100 | + |
| 101 | + // @formatter:off |
| 102 | + String expression = annotation.map(expressionExtractor).map(String::trim).filter(StringUtils::hasLength) |
| 103 | + .orElseThrow(() -> new IllegalStateException(String.format( |
| 104 | + "The expression in @%s on [%s] must not be blank", annotationType.getSimpleName(), element))); |
| 105 | + // @formatter:on |
| 106 | + |
| 107 | + boolean result = evaluateExpression(expression, annotationType, context); |
| 108 | + |
| 109 | + if (result) { |
| 110 | + String adjective = (enabledOnTrue ? "enabled" : "disabled"); |
| 111 | + String reason = annotation.map(reasonExtractor).filter(StringUtils::hasText).orElseGet( |
| 112 | + () -> String.format("%s is %s because @%s(\"%s\") evaluated to true", element, adjective, |
| 113 | + annotationType.getSimpleName(), expression)); |
| 114 | + if (logger.isInfoEnabled()) { |
| 115 | + logger.info(reason); |
| 116 | + } |
| 117 | + return (enabledOnTrue ? ConditionEvaluationResult.enabled(reason) |
| 118 | + : ConditionEvaluationResult.disabled(reason)); |
| 119 | + } |
| 120 | + else { |
| 121 | + String adjective = (enabledOnTrue ? "disabled" : "enabled"); |
| 122 | + String reason = String.format("%s is %s because @%s(\"%s\") did not evaluate to true", |
| 123 | + element, adjective, annotationType.getSimpleName(), expression); |
| 124 | + if (logger.isDebugEnabled()) { |
| 125 | + logger.debug(reason); |
| 126 | + } |
| 127 | + return (enabledOnTrue ? ConditionEvaluationResult.disabled(reason) |
| 128 | + : ConditionEvaluationResult.enabled(reason)); |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + private <A extends Annotation> boolean evaluateExpression(String expression, Class<A> annotationType, |
| 133 | + ExtensionContext extensionContext) { |
| 134 | + |
| 135 | + ApplicationContext applicationContext = SpringExtension.getApplicationContext(extensionContext); |
| 136 | + |
| 137 | + if (!(applicationContext instanceof ConfigurableApplicationContext)) { |
| 138 | + if (logger.isWarnEnabled()) { |
| 139 | + String contextType = (applicationContext != null ? applicationContext.getClass().getName() : "null"); |
| 140 | + logger.warn(String.format("@%s(\"%s\") could not be evaluated on [%s] since the test " + |
| 141 | + "ApplicationContext [%s] is not a ConfigurableApplicationContext", |
| 142 | + annotationType.getSimpleName(), expression, extensionContext.getElement(), contextType)); |
| 143 | + } |
| 144 | + return false; |
| 145 | + } |
| 146 | + |
| 147 | + ConfigurableBeanFactory configurableBeanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory(); |
| 148 | + BeanExpressionResolver expressionResolver = configurableBeanFactory.getBeanExpressionResolver(); |
| 149 | + BeanExpressionContext beanExpressionContext = new BeanExpressionContext(configurableBeanFactory, null); |
| 150 | + |
| 151 | + Object result = expressionResolver.evaluate(configurableBeanFactory.resolveEmbeddedValue(expression), |
| 152 | + beanExpressionContext); |
| 153 | + |
| 154 | + Assert.state((result instanceof Boolean || result instanceof String), |
| 155 | + () -> String.format("@%s(\"%s\") must evaluate to a String or a Boolean, not %s", |
| 156 | + annotationType.getSimpleName(), expression, (result != null ? result.getClass().getName() : "null"))); |
| 157 | + |
| 158 | + return (result instanceof Boolean && ((Boolean) result).booleanValue()) |
| 159 | + || (result instanceof String && Boolean.parseBoolean((String) result)); |
| 160 | + } |
| 161 | + |
| 162 | + private static <A extends Annotation> Optional<A> findMergedAnnotation(AnnotatedElement element, |
| 163 | + Class<A> annotationType) { |
| 164 | + return Optional.ofNullable(AnnotatedElementUtils.findMergedAnnotation(element, annotationType)); |
| 165 | + } |
| 166 | + |
| 167 | +} |
0 commit comments