package org.junit.jupiter.engine.execution;
import static java.lang.String.format;
import static org.apiguardian.api.API.Status.INTERNAL;
import org.apiguardian.api.API;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.engine.config.JupiterConfiguration;
import org.junit.jupiter.engine.extension.ExtensionRegistry;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.junit.platform.commons.util.StringUtils;
@API(status = INTERNAL, since = "5.0")
public class ConditionEvaluator {
private static final Logger logger = LoggerFactory.getLogger(ConditionEvaluator.class);
private static final ConditionEvaluationResult ENABLED = ConditionEvaluationResult.enabled(
"No 'disabled' conditions encountered");
public ConditionEvaluationResult evaluate(ExtensionRegistry extensionRegistry, JupiterConfiguration configuration,
ExtensionContext context) {
return extensionRegistry.stream(ExecutionCondition.class)
.filter(configuration.getExecutionConditionFilter())
.map(condition -> evaluate(condition, context))
.filter(ConditionEvaluationResult::isDisabled)
.findFirst()
.orElse(ENABLED);
}
private ConditionEvaluationResult evaluate(ExecutionCondition condition, ExtensionContext context) {
try {
ConditionEvaluationResult result = condition.evaluateExecutionCondition(context);
logResult(condition.getClass(), result);
return result;
}
catch (Exception ex) {
throw evaluationException(condition.getClass(), ex);
}
}
private void logResult(Class<?> conditionType, ConditionEvaluationResult result) {
logger.trace(() -> format("Evaluation of condition [%s] resulted in: %s", conditionType.getName(), result));
}
private ConditionEvaluationException evaluationException(Class<?> conditionType, Exception ex) {
String cause = StringUtils.isNotBlank(ex.getMessage()) ? ": " + ex.getMessage() : "";
return new ConditionEvaluationException(
format("Failed to evaluate condition [%s]%s", conditionType.getName(), cause), ex);
}
}