org.junit.jupiter.api.extension.ConditionEvaluationResult Java Examples

The following examples show how to use org.junit.jupiter.api.extension.ConditionEvaluationResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DisabledOnEnvironmentCondition.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluate(TestExtensionContext context) {
    Properties props = new Properties();
    String env = "";
    try {
        props.load(ConnectionUtil.class.getResourceAsStream("/application.properties"));
        env = props.getProperty("env");
    } catch (IOException e) {
        e.printStackTrace();
    }
    Optional<DisabledOnEnvironment> disabled = AnnotationSupport.findAnnotation(context.getElement().get(), DisabledOnEnvironment.class);
    if (disabled.isPresent()) {
        String[] envs = disabled.get().value();
        if (Arrays.asList(envs).contains(env)) {
            return ConditionEvaluationResult.disabled("Disabled on environment " + env);
        }
    }

    return ConditionEvaluationResult.enabled("Enabled on environment "+env);
}
 
Example #2
Source File: EnabledIfPropertyCondition.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
private ConditionEvaluationResult map(EnabledIfProperty annotation) {
    final String name = annotation.named().trim();
    final String regex = annotation.matches();

    Preconditions.notBlank(name, () -> "The 'named' attribute must not be blank in " + annotation);
    Preconditions.notBlank(regex, () -> "The 'matches' attribute must not be blank in " + annotation);

    return ConfigProviderResolver.instance().getConfig().getOptionalValue(name, String.class)
            .map(actual -> {
                return actual.matches(regex)
                        ? enabled(
                                format("Config property [%s] with value [%s] matches regular expression [%s]",
                                        name, actual, regex))
                        : disabled(
                                format("Config property [%s] with value [%s] does not match regular expression [%s]",
                                        name, actual, regex));
            })
            .orElseGet(() -> {
                return disabled(
                        format("Config property [%s] does not exist", name));
            });
}
 
Example #3
Source File: DisabledOnWeekday.java    From JUnit-5-Quick-Start-Guide-and-Framework-Support with MIT License 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {

    // Search for the @DisabledWeekdays annotation from the TestExtensionContext
    Optional<AnnotatedElement> contextElement = context.getElement();
    AnnotatedElement annotatedElement = contextElement.orElse(null);

    if (annotatedElement == null) return null;

    DisabledWeekdays weekdayAnnotation = annotatedElement.getAnnotation(DisabledWeekdays.class);

    // Determine whether the test should be disabled
    boolean weekdayToday = IntStream.of(weekdayAnnotation.value())
            .anyMatch(day -> day == Calendar.getInstance().get(Calendar.DAY_OF_WEEK));

    // Return a ConditionEvaluationResult based on the outcome of the boolean weekdayToday
    return weekdayToday ?
            ConditionEvaluationResult.disabled("I spare you today.") :
            ConditionEvaluationResult.enabled("Don't spare you on other days though >:(");
}
 
Example #4
Source File: DisabledOnNativeImageCondition.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Containers/tests are disabled if {@code @DisabledOnNativeImage} is present on the test
 * class or method and we're running on a native image.
 */
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    Optional<AnnotatedElement> element = context.getElement();
    Optional<DisabledOnNativeImage> disabled = findAnnotation(element, DisabledOnNativeImage.class);
    if (disabled.isPresent()) {
        // Cannot use ExtensionState here because this condition needs to be evaluated before QuarkusTestExtension
        boolean nativeImage = findAnnotation(context.getTestClass(), NativeImageTest.class).isPresent();
        if (nativeImage) {
            String reason = disabled.map(DisabledOnNativeImage::value)
                    .filter(StringUtils::isNotBlank)
                    .orElseGet(() -> element.get() + " is @DisabledOnNativeImage");
            return ConditionEvaluationResult.disabled(reason);
        }
    }
    return ENABLED;
}
 
Example #5
Source File: ServicePresentCondition.java    From dekorate with Apache License 2.0 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
 Optional<OnServicePresentCondition> annotation = context.getElement().map(e -> e.getAnnotation(OnServicePresentCondition.class));
 if (!annotation.isPresent()) {
  return ConditionEvaluationResult.enabled("Condition not found!");
 }
 OnServicePresentCondition condition = annotation.get();
  try {
    KubernetesClient client = getKubernetesClient(context);
    String namespace = Strings.isNotNullOrEmpty(condition.namespace()) ? condition.namespace() :  client.getNamespace();
    Service service = getKubernetesClient(context).services().inNamespace(namespace).withName(condition.value()).get();
    if (service != null) {
      return ConditionEvaluationResult.enabled("Found service:" + condition.value() + " in namespace:" + namespace + " .");
    } else {
      return ConditionEvaluationResult.disabled("Could not find service:" + condition.value() + " in namespace:" + namespace + " .");
    }
  } catch (Throwable t) {
    return ConditionEvaluationResult.disabled("Could not lookup for service.");
  }
}
 
Example #6
Source File: OsCondition.java    From mastering-junit5 with Apache License 2.0 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(
        ExtensionContext context) {

    Optional<AnnotatedElement> element = context.getElement();
    ConditionEvaluationResult out = ConditionEvaluationResult
            .enabled("@DisabledOnOs is not present");

    Optional<DisabledOnOs> disabledOnOs = AnnotationUtils
            .findAnnotation(element, DisabledOnOs.class);

    if (disabledOnOs.isPresent()) {
        Os myOs = Os.determine();
        if (Arrays.asList(disabledOnOs.get().value()).contains(myOs)) {
            out = ConditionEvaluationResult
                    .disabled("Test is disabled on " + myOs);
        } else {
            out = ConditionEvaluationResult
                    .enabled("Test is not disabled on " + myOs);
        }
    }

    System.out.println("--> " + out.getReason().get());
    return out;
}
 
Example #7
Source File: RequireIPv6Condition.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    if (ipv6Result == null) {
        boolean result = false;
        try {
            result = hasIPv6Loopback();
        } catch (SocketException e) {
            log.warn("Could not determine presence of IPv6 loopback address", e);
        }

        if (result) {
            ipv6Result = ConditionEvaluationResult.enabled("Found IPv6 loopback");
        } else {
            ipv6Result = ConditionEvaluationResult.disabled("Could not find IPv6 loopback");
        }
    }
    return ipv6Result;
}
 
Example #8
Source File: TestDisabler.java    From junit5-extensions with MIT License 6 votes vote down vote up
private ConditionEvaluationResult evaluate(
    LinkedList<String> displayName,
    ExtensionContext context) {
  Optional<ConditionEvaluationResult> result =
      context
          .getElement()
          .flatMap(element -> evaluateElement(displayName, element));

  if (result.isPresent()) {
    return result.get();
  }

  displayName.addFirst(context.getDisplayName());
  return context.getParent()
      .map(parent -> evaluate(displayName, parent))
      .orElse(ConditionEvaluationResult.enabled(null));
}
 
Example #9
Source File: OsCondition.java    From Mastering-Software-Testing-with-JUnit-5 with MIT License 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(
        ExtensionContext context) {

    Optional<AnnotatedElement> element = context.getElement();
    ConditionEvaluationResult out = ConditionEvaluationResult
            .enabled("@DisabledOnOs is not present");

    Optional<DisabledOnOs> disabledOnOs = AnnotationUtils
            .findAnnotation(element, DisabledOnOs.class);

    if (disabledOnOs.isPresent()) {
        Os myOs = Os.determine();
        if (Arrays.asList(disabledOnOs.get().value()).contains(myOs)) {
            out = ConditionEvaluationResult
                    .disabled("Test is disabled on " + myOs);
        } else {
            out = ConditionEvaluationResult
                    .enabled("Test is not disabled on " + myOs);
        }
    }

    System.out.println("--> " + out.getReason().get());
    return out;
}
 
Example #10
Source File: CapabilityCondition.java    From status-keycard with Apache License 2.0 6 votes vote down vote up
/**
 * Containers/tests are disabled if {@code @Disabled} is present on the test
 * class or method.
 */
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
  Optional<AnnotatedElement> element = context.getElement();
  Optional<Capabilities> capsAnnotation = findAnnotation(element, Capabilities.class);

  if (capsAnnotation.isPresent()) {
    for (String c : capsAnnotation.get().value()) {
      if (!availableCapabilities.contains(c)) {
        return disabled("The " + c + " capability is not available on the tested target");
      }
    }

    return ENABLED;
  }

  return ENABLED_BY_DEFAULT;
}
 
Example #11
Source File: RequireIPv6Condition.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    if (ipv6Result == null) {
        boolean result = false;
        try {
            result = hasIPv6Loopback();
        } catch (SocketException e) {
            log.warn("Could not determine presence of IPv6 loopback address", e);
        }

        if (result) {
            ipv6Result = ConditionEvaluationResult.enabled("Found IPv6 loopback");
        } else {
            ipv6Result = ConditionEvaluationResult.disabled("Could not find IPv6 loopback");
        }
    }
    return ipv6Result;
}
 
Example #12
Source File: AssumeOpenshiftCondition.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    Optional<OpenShift> annotation = findAnnotation(context.getElement(), OpenShift.class);
    if (annotation.isPresent()) {
        var version = annotation.get().version();
        var type = annotation.get().type();
        var multinode = type.equals(ClusterType.CRC) ? MultinodeCluster.NO : annotation.get().multinode();
        if ((Kubernetes.getInstance().getCluster().toString().equals(ClusterType.OPENSHIFT.toString().toLowerCase()) ||
                Kubernetes.getInstance().getCluster().toString().equals(ClusterType.CRC.toString().toLowerCase())) &&
                (version == OpenShiftVersion.WHATEVER || version == Kubernetes.getInstance().getOcpVersion()) &&
                (multinode == MultinodeCluster.WHATEVER || multinode == Kubernetes.getInstance().isClusterMultinode())) {
            return ConditionEvaluationResult.enabled("Test is supported on current cluster");
        } else {
            return ConditionEvaluationResult.disabled("Test is not supported on current cluster");
        }
    }
    return ConditionEvaluationResult.enabled("No rule set, test is enabled");
}
 
Example #13
Source File: SupportedInstallTypeCondition.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    Optional<SupportedInstallType> annotation = findAnnotation(context.getRequiredTestClass(), SupportedInstallType.class);
    if (annotation.isPresent()) {
        SupportedInstallType supports = annotation.get();
        io.enmasse.systemtest.platform.Kubernetes kube = io.enmasse.systemtest.platform.Kubernetes.getInstance();
        Environment env = Environment.getInstance();
        String reason = String.format("Env is supported types %s type used %s olmAvailability %s",
                supports.value().toString(), env.installType(), kube.isOLMAvailable());
        if (isTestEnabled(supports, kube.isOLMAvailable(), env.installType())) {
           return ConditionEvaluationResult.enabled(reason);
        } else {
            return ConditionEvaluationResult.disabled(reason);
        }
    }
    return ConditionEvaluationResult.enabled("No rule set, test is enabled");
}
 
Example #14
Source File: JavaVersionCheckExtension.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
	// Check if the minimal version of Java is used for running the tests.
	final JavaVersion cVersion = JavaVersion.fromQualifier(System.getProperty("java.specification.version"));
	if (cVersion == null) {
		return ConditionEvaluationResult.disabled("You must use JDK " + SARLVersion.MINIMAL_JDK_VERSION_FOR_SARL_COMPILATION_ENVIRONMENT + " or higher for running the tests.");
	}
	final JavaVersion mVersion = JavaVersion.fromQualifier(SARLVersion.MINIMAL_JDK_VERSION_FOR_SARL_COMPILATION_ENVIRONMENT);
	if (mVersion == null || !cVersion.isAtLeast(mVersion)) {
		return ConditionEvaluationResult.disabled("You must use JDK " + SARLVersion.MINIMAL_JDK_VERSION_FOR_SARL_COMPILATION_ENVIRONMENT + " or higher for running the tests.");
	}
	final JavaVersion xVersion = JavaVersion.fromQualifier(SARLVersion.INCOMPATIBLE_JDK_VERSION_FOR_SARL_COMPILATION_ENVIRONMENT);
	// If null the max version that is specified into the SARL configuration is not yey supported by Xtext enumeration
	if (xVersion != null && cVersion.isAtLeast(xVersion)) {
		return ConditionEvaluationResult.disabled("You must use JDK strictly below " + SARLVersion.INCOMPATIBLE_JDK_VERSION_FOR_SARL_COMPILATION_ENVIRONMENT + " for running the tests.");
	}
	return ConditionEvaluationResult.enabled("supported version of JDK");
}
 
Example #15
Source File: EnabledOnGitVersionCondition.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    Optional<EnabledOnGitVersions> maybe = findAnnotation(context.getElement(), EnabledOnGitVersions.class);
    if (maybe.isPresent()) {
        final EnabledOnGitVersions annotation = maybe.get();
        final Version gitVersion = fetchGitVersion();

        if (noneSpecified(annotation)) {
            return ConditionEvaluationResult.enabled("Version requirements not provided. Running by default.");
        }

        if (atLeast(annotation.from(), gitVersion) && atMost(annotation.through(), gitVersion)) {
            return ConditionEvaluationResult.enabled(
                    format("Git version %s satisfies %s", gitVersion, criteria(annotation))
            );
        } else {
            return ConditionEvaluationResult.disabled(
                    format("Git version %s does not satisfy %s", gitVersion, criteria(annotation))
            );
        }
    }

    return ConditionEvaluationResult.enabled("Version requirements not provided. Running by default.");
}
 
Example #16
Source File: DisabledOnQAEnvironmentExtension.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    Properties properties = new Properties();
    try {
        properties.load(DisabledOnQAEnvironmentExtension.class.getClassLoader()
            .getResourceAsStream("application.properties"));
        if ("qa".equalsIgnoreCase(properties.getProperty("env"))) {
            String reason = String.format("The test '%s' is disabled on QA environment", context.getDisplayName());
            System.out.println(reason);
            return ConditionEvaluationResult.disabled(reason);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return ConditionEvaluationResult.enabled("Test enabled");
}
 
Example #17
Source File: DisableOnMacCondition.java    From cssfx with Apache License 2.0 5 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    final String osName = System.getProperty("os.name");
    final String cleanOsName = osName
            .replaceAll("\\s", "")
            .toLowerCase(Locale.ENGLISH);
    if(cleanOsName.contains(MAC_OS)) {
        return ConditionEvaluationResult.disabled("Test disabled on JVM running on " + osName);
    } else {
        return ConditionEvaluationResult.enabled("Test enabled, running on " + osName);
    }
}
 
Example #18
Source File: RequiresNetworkExtension.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
  return context.getElement()
      .flatMap(element -> AnnotationSupport.findAnnotation(element, RequiresNetwork.class))
      .map(net -> {
        try (Socket ignored = new Socket(net.host(), net.port())) {
          return enabled(net.host() + ":" + net.port() + " is reachable");
        } catch (Exception e) {
          return disabled(net.host() + ":" + net.port() + " is unreachable: " + e.getMessage());
        }
      })
      .orElseGet(() -> enabled("@RequiresNetwork is not found"));
}
 
Example #19
Source File: IamAuthCondition.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    if (IS_IAM_ENABLED) {
        return ConditionEvaluationResult.disabled("Test is not supported when using IAM.");
    } else {
        return ConditionEvaluationResult.enabled("Test enabled.");
    }
}
 
Example #20
Source File: EnvironmentExtension.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    Properties props = new Properties();

    try {
        props.load(EnvironmentExtension.class.getResourceAsStream("application.properties"));
        String env = props.getProperty("env");
        if ("qa".equalsIgnoreCase(env)) {
            return ConditionEvaluationResult.disabled("Test disabled on QA environment");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return ConditionEvaluationResult.enabled("Test enabled on QA environment");
}
 
Example #21
Source File: AssumeKubernetesCondition.java    From enmasse with Apache License 2.0 5 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    Optional<Kubernetes> annotation = findAnnotation(context.getElement(), Kubernetes.class);
    if (annotation.isPresent()) {
        ClusterType cluster = annotation.get().type();
        MultinodeCluster multinode = annotation.get().multinode();
        if (!io.enmasse.systemtest.platform.Kubernetes.getInstance().getCluster().toString().equals(cluster.toString().toLowerCase()) &&
                (multinode == MultinodeCluster.WHATEVER || multinode == io.enmasse.systemtest.platform.Kubernetes.getInstance().isClusterMultinode())) {
            return ConditionEvaluationResult.disabled("Test is not supported on current cluster");
        } else {
            return ConditionEvaluationResult.enabled("Test is supported on current cluster");
        }
    }
    return ConditionEvaluationResult.enabled("No rule set, test is enabled");
}
 
Example #22
Source File: OpenShiftOnlyCondition.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) {
    KubeClusterResource clusterResource = KubeClusterResource.getInstance();

    if (clusterResource.cluster() instanceof OpenShift || clusterResource.cluster() instanceof Minishift) {
        return ConditionEvaluationResult.enabled("Test is enabled");
    } else {
        LOGGER.info("{} is @OpenShiftOnly, but the running cluster is not OpenShift: Ignoring {}",
                extensionContext.getDisplayName(),
                extensionContext.getDisplayName()
        );
        return ConditionEvaluationResult.disabled("Test is disabled");
    }
}
 
Example #23
Source File: DisabledByFormula.java    From demo-junit-5 with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(
		ExtensionContext context) {
	return formula.evaluate()
			// disable when formula is true
			? ConditionEvaluationResult.disabled(message)
			: ConditionEvaluationResult.enabled("Not '" + message + "'");
}
 
Example #24
Source File: StepMethodOrderer.java    From demo-junit-5 with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
	if (failedTests.isEmpty())
		return ConditionEvaluationResult.enabled("");

	boolean testIsDescendantOfFailedTest = failedTests.stream()
			.flatMap(DirectedNode::descendants)
			.anyMatch(node -> Objects.equals(
					node.testMethod().getMethod().getName(),
					context.getRequiredTestMethod().getName()));

	return testIsDescendantOfFailedTest
			? ConditionEvaluationResult.disabled("An earlier scenario test failed")
			: ConditionEvaluationResult.enabled("");
}
 
Example #25
Source File: EnabledIfTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private ConditionEvaluationResult map(EnabledIf annotation) {
    for (Class<? extends BooleanSupplier> type : annotation.value()) {
        try {
            if (!type.newInstance().getAsBoolean()) {
                return disabled(format("Condition %s is false", type.getName()));
            }
        } catch (InstantiationException | IllegalAccessException e) {
            return disabled(format("Unable to evaluate condition: %s", type.getName()));
        }
    }
    return enabled("All conditions match");
}
 
Example #26
Source File: DisabledIfTestFailedWithCondition.java    From demo-junit-5 with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
	Class<? extends Exception>[] exceptionTypes = context.getTestClass()
			.flatMap(testClass -> findAnnotation(testClass, DisabledIfTestFailedWith.class))
			.orElseThrow(() -> new IllegalStateException("The extension should not be executed "
					+ "unless the test class is annotated with @DisabledIfTestFailedWith."))
			.value();

	return disableIfExceptionWasThrown(context, exceptionTypes);
}
 
Example #27
Source File: OsCondition.java    From demo-junit-5 with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
private ConditionEvaluationResult disabledIfOn(OS[] disabledOnOs) {
	OS os = OS.determine();
	if (Arrays.asList(disabledOnOs).contains(os))
		return ConditionEvaluationResult.disabled("Test is disabled on " + os + ".");
	else
		return ConditionEvaluationResult.enabled("Test is not disabled in " + os + ".");
}
 
Example #28
Source File: OsCondition.java    From demo-junit-5 with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
private ConditionEvaluationResult evaluateIfAnnotated(Optional<AnnotatedElement> element) {
	Optional<DisabledOnOs> disabled = element.flatMap(el -> findAnnotation(el, DisabledOnOs.class));
	if (disabled.isPresent())
		return disabledIfOn(disabled.get().value());

	Optional<TestExceptOnOs> testExcept = element.flatMap(el -> findAnnotation(el, TestExceptOnOs.class));
	if (testExcept.isPresent())
		return disabledIfOn(testExcept.get().value());

	return ConditionEvaluationResult.enabled("");
}
 
Example #29
Source File: DisabledOnMonday.java    From JUnit-5-Quick-Start-Guide-and-Framework-Support with MIT License 5 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    boolean monday = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY;

    return monday ?
            ConditionEvaluationResult.disabled("I spare you on Mondays.") :
            ConditionEvaluationResult.enabled("Don't spare you on other days though >:(");
}
 
Example #30
Source File: DisabledInHeadlessGraphicsEnvironmentTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Test
void shouldReturnDisabledWhenGraphicsEnvironmentIsHeadless() {
  final ConditionEvaluationResult result = evaluateExecutionCondition(true);

  assertThat(result.isDisabled(), is(true));
  assertThat(
      result.getReason(), isPresentAndIs("Test disabled in headless graphics environment"));
}