com.tngtech.archunit.lang.ArchCondition Java Examples

The following examples show how to use com.tngtech.archunit.lang.ArchCondition. 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: CoreSubscriberArchTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotUseDefaultCurrentContext() {
	classes()
			.that().implement(CoreSubscriber.class)
			.and().doNotHaveModifier(JavaModifier.ABSTRACT)
			.should(new ArchCondition<JavaClass>("not use the default currentContext()") {
				@Override
				public void check(JavaClass item, ConditionEvents events) {
					boolean overridesMethod = item
							.getAllMethods()
							.stream()
							.filter(it -> "currentContext".equals(it.getName()))
							.filter(it -> it.getRawParameterTypes().isEmpty())
							.anyMatch(it -> !it.getOwner().isEquivalentTo(CoreSubscriber.class));

					if (!overridesMethod) {
						events.add(SimpleConditionEvent.violated(
								item,
								item.getFullName() + item.getSourceCodeLocation() + ": currentContext() is not overridden"
						));
					}
				}
			})
			.check(classes);
}
 
Example #2
Source File: GivenMembersTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
@UseDataProvider("member_syntax_testcases")
public void test_members(GivenMembers<JavaMember> members, String ruleStart, ArchCondition<JavaMember> condition,
        List<String> expectedViolationDetails) {
    ArchRule rule = members
            .that(have(modifier(PRIVATE)))
            .or(have(modifier(PROTECTED)))
            .and(are(annotatedWith(B.class)))
            .should(condition);

    assertThat(rule.getDescription()).as("rule description")
            .isEqualTo(ruleStart + " that have modifier PRIVATE or have modifier PROTECTED and are annotated with @B "
                    + "should " + condition.getDescription());

    EvaluationResult result = rule.evaluate(importClasses(ClassWithVariousMembers.class));

    assertViolation(result);
    assertThat(result.getFailureReport().getDetails()).containsOnlyElementsOf(expectedViolationDetails);
}
 
Example #3
Source File: ClassesShouldTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
@UseDataProvider("resideOutsideOfPackage_rules")
public void resideOutsideOfPackage(ArchRule rule, String packageIdentifier) {
    checkTestStillValid(packageIdentifier,
            ImmutableSet.of(ArchRule.class, ArchCondition.class),
            ImmutableSet.<Class<?>>of(ArchConfiguration.class),
            ImmutableSet.<Class<?>>of(GivenObjects.class));

    EvaluationResult result = rule.evaluate(importClasses(
            ArchRule.class, ArchCondition.class, ArchConfiguration.class, GivenObjects.class));

    assertThat(singleLineFailureReportOf(result))
            .contains(String.format("classes should reside outside of package '%s'", packageIdentifier))
            .containsPattern(doesntResideOutsideOfPackagePatternFor(ArchRule.class, packageIdentifier))
            .containsPattern(doesntResideOutsideOfPackagePatternFor(ArchCondition.class, packageIdentifier))
            .doesNotContain(String.format("%s", ArchConfiguration.class.getSimpleName()))
            .doesNotContain(String.format("%s", GivenObjects.class.getSimpleName()));
}
 
Example #4
Source File: ArchConditionsTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private ArchCondition<Object> conditionWithDescription(String description) {
    return new ArchCondition<Object>(description) {
        @Override
        public void check(Object item, ConditionEvents events) {
        }
    };
}
 
Example #5
Source File: GivenMembersTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    return conjunction.should(new ArchCondition<Object>("removeMe") {
        @Override
        public void check(Object item, ConditionEvents events) {
        }
    }).getDescription().replace("should removeMe", "");
}
 
Example #6
Source File: AbstractGivenMembersInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
GivenMembersInternal(
        Priority priority,
        ClassesTransformer<JavaMember> classesTransformer,
        Function<ArchCondition<JavaMember>, ArchCondition<JavaMember>> prepareCondition) {

    this(new GivenMembersFactory(),
            priority,
            classesTransformer,
            prepareCondition,
            new PredicateAggregator<JavaMember>(),
            Optional.<String>absent());
}
 
Example #7
Source File: GivenSlicesInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
@PublicAPI(usage = ACCESS)
public SliceRule beFreeOfCycles() {
    return new SliceRule(classesTransformer, priority, new SliceRule.ConditionFactory() {
        @Override
        public ArchCondition<Slice> create(Slices.Transformer transformer, DescribedPredicate<Dependency> predicate) {
            return new SliceCycleArchCondition(predicate);
        }
    });
}
 
Example #8
Source File: GivenSlicesInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
@PublicAPI(usage = ACCESS)
public SliceRule notDependOnEachOther() {
    return new SliceRule(classesTransformer, priority, new SliceRule.ConditionFactory() {
        @Override
        public ArchCondition<Slice> create(Slices.Transformer transformer, DescribedPredicate<Dependency> predicate) {
            return new NotDependOnEachOtherCondition(predicate, transformer);
        }
    });
}
 
Example #9
Source File: ArchUnitRunnerTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private static ArchCondition<JavaClass> beOkay() {
    return new ArchCondition<JavaClass>("be okay") {
        @Override
        public void check(JavaClass item, ConditionEvents events) {
        }
    };
}
 
Example #10
Source File: GivenMethodsInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
GivenMethodsInternal(
        Priority priority,
        ClassesTransformer<JavaMethod> classesTransformer,
        Function<ArchCondition<JavaMethod>, ArchCondition<JavaMethod>> prepareCondition) {

    this(new GivenMethodsFactory(),
            priority,
            classesTransformer,
            prepareCondition,
            new PredicateAggregator<JavaMethod>(),
            Optional.<String>absent());
}
 
Example #11
Source File: GivenConstructorsInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public GivenConstructorsInternal create(
        Priority priority,
        ClassesTransformer<JavaConstructor> classesTransformer,
        Function<ArchCondition<JavaConstructor>, ArchCondition<JavaConstructor>> prepareCondition,
        PredicateAggregator<JavaConstructor> relevantObjectsPredicates,
        Optional<String> overriddenDescription) {

    return new GivenConstructorsInternal(this,
            priority, classesTransformer, prepareCondition, relevantObjectsPredicates, overriddenDescription);
}
 
Example #12
Source File: ArchUnitRunnerRunsRuleSetsTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private static ArchCondition<JavaClass> satisfySomething() {
    return new ArchCondition<JavaClass>("satisfy something") {
        @Override
        public void check(JavaClass item, ConditionEvents events) {
        }
    };
}
 
Example #13
Source File: ObjectsShouldInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
static <T> AddMode<T> and(final Function<ArchCondition<T>, ArchCondition<T>> prepareCondition) {
    return new AddMode<T>() {
        @Override
        ArchCondition<T> apply(Optional<ArchCondition<T>> first, ArchCondition<? super T> other) {
            ArchCondition<T> second = prepareCondition.apply(other.<T>forSubType());
            return first.isPresent() ? first.get().and(second) : second;
        }
    };
}
 
Example #14
Source File: GivenObjectsInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public GivenObjectsInternal<T> create(Priority priority,
        ClassesTransformer<T> classesTransformer,
        Function<ArchCondition<T>, ArchCondition<T>> prepareCondition,
        PredicateAggregator<T> relevantObjectsPredicates,
        Optional<String> overriddenDescription) {

    return new GivenObjectsInternal<>(
            priority, classesTransformer, prepareCondition, relevantObjectsPredicates, overriddenDescription);
}
 
Example #15
Source File: GivenFieldsInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public GivenFieldsInternal create(
        Priority priority,
        ClassesTransformer<JavaField> classesTransformer,
        Function<ArchCondition<JavaField>, ArchCondition<JavaField>> prepareCondition,
        PredicateAggregator<JavaField> relevantObjectsPredicates,
        Optional<String> overriddenDescription) {

    return new GivenFieldsInternal(this,
            priority, classesTransformer, prepareCondition, relevantObjectsPredicates, overriddenDescription);
}
 
Example #16
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@PublicAPI(usage = ACCESS)
public static ArchCondition<JavaClass> callMethod(String ownerName, String methodName, String... parameterTypeNames) {
    return callMethodWhere(JavaCall.Predicates.target(With.<JavaClass>owner(name(ownerName)))
            .and(JavaCall.Predicates.target(name(methodName)))
            .and(JavaCall.Predicates.target(rawParameterTypes(parameterTypeNames))))
            .as("call method %s", Formatters.formatMethodSimple(
                    ensureSimpleName(ownerName), methodName, asList(parameterTypeNames)));
}
 
Example #17
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@PublicAPI(usage = ACCESS)
public static ArchCondition<JavaClass> onlyCallMethodsThat(final DescribedPredicate<? super JavaMethod> predicate) {
    ChainableFunction<JavaMethodCall, MethodCallTarget> getTarget = JavaAccess.Functions.Get.target();
    DescribedPredicate<JavaMethodCall> callPredicate = getTarget.then(MethodCallTarget.Functions.RESOLVE)
            .is(anyElementThat(predicate.<JavaMethod>forSubType()).or(empty()));
    return new ClassOnlyAccessesCondition<>(callPredicate, GET_METHOD_CALLS_FROM_SELF)
            .as("only call methods that " + predicate.getDescription());
}
 
Example #18
Source File: ArchitectureTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void everySubpackageShouldBeTestsForCyclicDependencies() {
  List<Pattern> excludePackages =
      Stream.of(
              "pro.taskana", // from TaskanaEngineConfiguration
              "acceptance.*" // all our acceptance tests
              )
          .map(Pattern::compile)
          .collect(Collectors.toList());
  ArchCondition<JavaClass> condition =
      new ArchCondition<JavaClass>("all be defined in TASKANA_SUB_PACKAGES") {
        @Override
        public void check(JavaClass item, ConditionEvents events) {
          if (TASKANA_SUB_PACKAGES.stream().noneMatch(p -> item.getPackageName().startsWith(p))
              && excludePackages.stream()
                  .noneMatch(p -> p.matcher(item.getPackageName()).matches())) {
            String message =
                String.format(
                    "Package '%s' was not declared in TASKANA_SUB_PACKAGES",
                    item.getPackageName());
            events.add(SimpleConditionEvent.violated(item, message));
          }
        }
      };
  ArchRule myRule = classes().should(condition);
  myRule.check(importedClasses);
}
 
Example #19
Source File: MethodsShouldInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
MethodsShouldInternal(
        ClassesTransformer<? extends JavaMethod> classesTransformer,
        Priority priority,
        Function<ArchCondition<JavaMethod>, ArchCondition<JavaMethod>> prepareCondition) {

    super(classesTransformer, priority, prepareCondition);
}
 
Example #20
Source File: GivenFieldsInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
GivenFieldsInternal(
        Priority priority,
        ClassesTransformer<JavaField> classesTransformer,
        Function<ArchCondition<JavaField>, ArchCondition<JavaField>> prepareCondition) {

    super(new GivenFieldsFactory(),
            priority,
            classesTransformer,
            prepareCondition,
            new PredicateAggregator<JavaField>(),
            Optional.<String>absent());
}
 
Example #21
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@PublicAPI(usage = ACCESS)
public static ArchCondition<JavaClass> dependOnClassesThat(final DescribedPredicate<? super JavaClass> predicate) {
    return new AnyDependencyCondition(
            "depend on classes that " + predicate.getDescription(),
            GET_TARGET_CLASS.is(predicate),
            GET_DIRECT_DEPENDENCIES_FROM_SELF);
}
 
Example #22
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@PublicAPI(usage = ACCESS)
public static ArchCondition<JavaClass> onlyDependOnClassesThat(final DescribedPredicate<? super JavaClass> predicate) {
    return new AllDependenciesCondition(
            "only depend on classes that " + predicate.getDescription(),
            GET_TARGET_CLASS.is(predicate),
            GET_DIRECT_DEPENDENCIES_FROM_SELF);
}
 
Example #23
Source File: GivenMethodsInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private GivenMethodsInternal(
        Factory<JavaMethod, GivenMethodsInternal> factory,
        Priority priority,
        ClassesTransformer<JavaMethod> classesTransformer,
        Function<ArchCondition<JavaMethod>, ArchCondition<JavaMethod>> prepareCondition,
        PredicateAggregator<JavaMethod> relevantObjectsPredicates,
        Optional<String> overriddenDescription) {

    super(factory, priority, classesTransformer, prepareCondition, relevantObjectsPredicates, overriddenDescription);
}
 
Example #24
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
/**
 * @param packageIdentifiers Strings identifying a package according to {@link PackageMatcher}
 * @return A condition matching accesses to packages matching any of the identifiers
 */
@PublicAPI(usage = ACCESS)
public static ArchCondition<JavaClass> accessClassesThatResideInAnyPackage(String... packageIdentifiers) {
    JavaAccessPackagePredicate predicate = JavaAccessPackagePredicate.forAccessTarget().matching(packageIdentifiers);
    return new ClassAccessesCondition<>(predicate, GET_ACCESSES_FROM_SELF)
            .as("access classes that reside in " + predicate);
}
 
Example #25
Source File: GivenConstructorsInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private GivenConstructorsInternal(
        Factory<JavaConstructor, GivenConstructorsInternal> factory,
        Priority priority,
        ClassesTransformer<JavaConstructor> classesTransformer,
        Function<ArchCondition<JavaConstructor>, ArchCondition<JavaConstructor>> prepareCondition,
        PredicateAggregator<JavaConstructor> relevantObjectsPredicates,
        Optional<String> overriddenDescription) {

    super(factory, priority, classesTransformer, prepareCondition, relevantObjectsPredicates, overriddenDescription);
}
 
Example #26
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
/**
 * @param packageIdentifiers Strings identifying packages according to {@link PackageMatcher}
 * @return A condition matching {@link JavaClass classes} that have other classes
 * depending on them (e.g. calling methods of this class)
 * with a package matching any of the identifiers
 */
@PublicAPI(usage = ACCESS)
public static ArchCondition<JavaClass> onlyHaveDependentsInAnyPackage(String... packageIdentifiers) {
    String description = String.format("only have dependents in any package ['%s']",
            Joiner.on("', '").join(packageIdentifiers));
    return onlyHaveDependentsWhere(dependencyOrigin(GET_PACKAGE_NAME.is(PackageMatchers.of(packageIdentifiers))))
            .as(description);
}
 
Example #27
Source File: GivenClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
public List<T> on(Class<?>... toCheck) {
    final List<T> result = new ArrayList<>();
    JavaClasses classes = importClassesWithContext(toCheck);
    ArchCondition<T> condition = new ArchCondition<T>("ignored") {
        @Override
        public void check(T item, ConditionEvents events) {
            result.add(item);
        }
    };
    givenObjects.should(condition).check(classes);
    return result;
}
 
Example #28
Source File: AbstractGivenCodeUnitsInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
AbstractGivenCodeUnitsInternal(
        Factory<MEMBER, SELF> factory,
        Priority priority,
        ClassesTransformer<MEMBER> classesTransformer,
        Function<ArchCondition<MEMBER>, ArchCondition<MEMBER>> prepareCondition,
        PredicateAggregator<MEMBER> relevantObjectsPredicates,
        Optional<String> overriddenDescription) {

    super(factory, priority, classesTransformer, prepareCondition, relevantObjectsPredicates, overriddenDescription);
}
 
Example #29
Source File: AbstractGivenCodeUnitsInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public GivenCodeUnitsInternal create(
        Priority priority,
        ClassesTransformer<JavaCodeUnit> classesTransformer,
        Function<ArchCondition<JavaCodeUnit>, ArchCondition<JavaCodeUnit>> prepareCondition,
        PredicateAggregator<JavaCodeUnit> relevantObjectsPredicates,
        Optional<String> overriddenDescription) {

    return new GivenCodeUnitsInternal(this,
            priority, classesTransformer, prepareCondition, relevantObjectsPredicates, overriddenDescription);
}
 
Example #30
Source File: GivenSlicesTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private Set<Slice> getSlicesMatchedByFilter(GivenConjunction<Slice> givenSlices) {
    final Set<Slice> matched = new HashSet<>();
    givenSlices.should(new ArchCondition<Slice>("") {
        @Override
        public void check(Slice item, ConditionEvents events) {
            matched.add(item);
        }
    }).evaluate(new ClassFileImporter().importPackages(TEST_CLASSES_PACKAGE));
    return matched;
}