com.tngtech.archunit.core.domain.JavaClass Java Examples

The following examples show how to use com.tngtech.archunit.core.domain.JavaClass. 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: ViolationHandlingTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void field_accesses_are_handled() {
    EvaluationResult result = noClasses().should()
            .accessTargetWhere(target(
                    Get.<JavaClass>owner().is(equivalentTo(Target.class))))
            .evaluate(importClasses(Origin.class, Target.class));

    FieldAccessRecorder fieldAccessRecorder = new FieldAccessRecorder();
    result.handleViolations(fieldAccessRecorder);

    assertThat(fieldAccessRecorder.getRecords()).as("number of violations").hasSize(3);
    assertThatAccesses(fieldAccessRecorder.getAccesses()).containOnly(
            accessToTargetField("fieldOne"),
            accessToTargetField("fieldTwo"),
            accessToTargetField("fieldThree"));

}
 
Example #2
Source File: GivenClassesThatTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
/**
 * We do not support operator precedence, like && and || does, we just aggregate as the predicates come.
 * If someone really needs such precedence, he has to use custom predicates, like a.and(b.or(c)).
 */
@Test
public void conjunctions_aggregate_in_sequence_without_special_precedence() {
    List<JavaClass> classes = filterResultOf(
            // (List OR String) AND Collection => empty
            classes().that().haveSimpleName(List.class.getSimpleName())
                    .or(have(simpleName(String.class.getSimpleName())))
                    .and().haveSimpleName(Collection.class.getSimpleName()))
            .on(List.class, String.class, Collection.class, Iterable.class);

    assertThat(classes).isEmpty();

    classes = filterResultOf(
            // (List AND String) OR Collection OR Iterable => [Collection, Iterable]
            classes().that().haveSimpleName(List.class.getSimpleName())
                    .and(have(simpleName(String.class.getSimpleName())))
                    .or().haveSimpleName(Collection.class.getSimpleName())
                    .or().haveSimpleName(Iterable.class.getSimpleName()))
            .on(List.class, String.class, Collection.class, Iterable.class);

    assertThatClasses(classes).matchInAnyOrder(Collection.class, Iterable.class);
}
 
Example #3
Source File: Classes.java    From moduliths with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a Classes with the current elements and the given other ones combined.
 *
 * @param others must not be {@literal null}.
 * @return
 */
Classes and(Collection<JavaClass> others) {

	Assert.notNull(others, "JavaClasses must not be null!");

	if (others.isEmpty()) {
		return this;
	}

	List<JavaClass> result = new ArrayList<>(classes);

	others.forEach(it -> {
		if (!result.contains(it)) {
			result.add(it);
		}
	});

	return new Classes(result);
}
 
Example #4
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void imports_shadowed_and_superclass_field_access() throws Exception {
    ImportedClasses classes = classesIn("testexamples/hierarchicalfieldaccess");
    JavaClass classThatAccessesFieldOfSuperClass = classes.get(AccessToSuperAndSubClassField.class);
    JavaClass superClassWithAccessedField = classes.get(SuperClassWithAccessedField.class);
    JavaClass subClassWithAccessedField = classes.get(SubClassWithAccessedField.class);

    Set<JavaFieldAccess> accesses = classThatAccessesFieldOfSuperClass.getFieldAccessesFromSelf();

    assertThat(accesses).hasSize(2);
    JavaField field = superClassWithAccessedField.getField("field");
    FieldAccessTarget expectedSuperClassFieldAccess = new FieldAccessTargetBuilder()
            .withOwner(subClassWithAccessedField)
            .withName(field.getName())
            .withType(field.getRawType())
            .withField(Suppliers.ofInstance(Optional.of(field)))
            .build();
    assertThatAccess(getOnly(accesses, "field", GET))
            .isFrom("accessSuperClassField")
            .isTo(expectedSuperClassFieldAccess)
            .inLineNumber(5);
    assertThatAccess(getOnly(accesses, "maskedField", GET))
            .isFrom("accessSubClassField")
            .isTo(subClassWithAccessedField.getField("maskedField"))
            .inLineNumber(9);
}
 
Example #5
Source File: SessionBeanRulesTest.java    From ArchUnit-Examples with Apache License 2.0 6 votes vote down vote up
private static DescribedPredicate<JavaClass> haveLocalBeanSubclass() {
    return new DescribedPredicate<JavaClass>("have subclass that is a local bean") {
        @Override
        public boolean apply(JavaClass input) {
            for (JavaClass subClass : input.getAllSubClasses()) {
                if (isLocalBeanImplementation(subClass, input)) {
                    return true;
                }
            }
            return false;
        }

        // NOTE: We assume that in this project by convention @Local is always used as @Local(type) with exactly
        //       one type, otherwise this would need to be more sophisticated
        private boolean isLocalBeanImplementation(JavaClass bean, JavaClass businessInterfaceType) {
            return bean.isAnnotatedWith(Local.class) &&
                    bean.getAnnotationOfType(Local.class).value()[0].getName()
                            .equals(businessInterfaceType.getName());
        }
    };
}
 
Example #6
Source File: ClassGraphCreator.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
void registerMethods(Set<JavaMethod> methods) {
    for (JavaMethod method : methods) {
        for (JavaClass parameter : method.getRawParameterTypes()) {
            methodParameterTypeDependencies.put(parameter, method);
        }
        methodReturnTypeDependencies.put(method.getRawReturnType(), method);
        for (ThrowsDeclaration<JavaMethod> throwsDeclaration : method.getThrowsClause()) {
            methodsThrowsDeclarationDependencies.put(throwsDeclaration.getRawType(), throwsDeclaration);
        }
    }
}
 
Example #7
Source File: ShouldOnlyByClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("should_only_be_by_rule_starts")
public void areNestedClasses_predicate(ClassesThat<ClassesShouldConjunction> classesShouldOnlyBeBy) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(
            classesShouldOnlyBeBy.areNestedClasses())
            .on(ClassAccessingStaticNestedClass.class, StaticNestedClassBeingAccessed.class,
                    ClassAccessingOtherClass.class, ClassBeingAccessedByOtherClass.class);

    assertThatClasses(classes).matchInAnyOrder(ClassAccessingOtherClass.class, ClassBeingAccessedByOtherClass.class);
}
 
Example #8
Source File: ShouldClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("no_classes_should_that_rule_starts")
public void areAssignableFrom_predicate(ClassesThat<ClassesShouldConjunction> noClassesShouldThatRuleStart) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(
            noClassesShouldThatRuleStart.areAssignableFrom(classWithNameOf(Collection.class)))
            .on(ClassAccessingList.class, ClassAccessingString.class,
                    ClassAccessingCollection.class, ClassAccessingIterable.class);

    assertThatClasses(classes).matchInAnyOrder(ClassAccessingCollection.class, ClassAccessingIterable.class);
}
 
Example #9
Source File: ClassGraphCreator.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private void completeAnnotations() {
    for (JavaClass javaClass : classes.getAll().values()) {
        DomainObjectCreationContext.completeAnnotations(javaClass, this);
        for (JavaMember member : concat(javaClass.getFields(), javaClass.getMethods(), javaClass.getConstructors())) {
            memberDependenciesByTarget.registerAnnotations(member.getAnnotations());
        }
    }
}
 
Example #10
Source File: ShouldClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("no_classes_should_that_rule_starts")
public void doNotImplement_typeName(ClassesThat<ClassesShouldConjunction> noClassesShouldThatRuleStart) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(
            noClassesShouldThatRuleStart.doNotImplement(Collection.class.getName()))
            .on(ClassAccessingArrayList.class, ClassAccessingList.class, ClassAccessingIterable.class);

    assertThatClasses(classes).matchInAnyOrder(ClassAccessingList.class, ClassAccessingIterable.class);
}
 
Example #11
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void class_handles_optional_annotation_correctly() throws Exception {
    JavaClass clazz = classesIn("testexamples/annotatedclassimport").get(ClassWithOneAnnotation.class);

    assertThat(clazz.tryGetAnnotationOfType(SimpleAnnotation.class)).isPresent();
    assertThat(clazz.tryGetAnnotationOfType(Deprecated.class)).isAbsent();
}
 
Example #12
Source File: ShouldOnlyByClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("should_only_be_by_rule_starts")
public void areNotAssignableTo_predicate(ClassesThat<ClassesShouldConjunction> classesShouldOnlyBeBy) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(
            classesShouldOnlyBeBy.areNotAssignableTo(classWithNameOf(SomeInterface.class)))
            .on(ClassImplementingSomeInterface.class, ClassBeingAccessedByClassImplementingSomeInterface.class,
                    SimpleClass.class, ClassAccessingSimpleClass.class);

    assertThatClasses(classes).matchInAnyOrder(ClassImplementingSomeInterface.class, ClassBeingAccessedByClassImplementingSomeInterface.class);
}
 
Example #13
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("array_types")
public void adds_package_of_component_type_to_arrays(Class<?> classAccessingArray) {
    JavaClass javaClass = new ClassFileImporter().importPackagesOf(classAccessingArray)
            .get(classAccessingArray);

    JavaClass arrayType = getOnlyElement(javaClass.getFieldAccessesFromSelf()).getTarget().getRawType();

    assertThat(arrayType.getPackageName()).isEqualTo(ClassUsedInArray.class.getPackage().getName());
    assertThat(arrayType.getPackage().getName()).isEqualTo(ClassUsedInArray.class.getPackage().getName());
}
 
Example #14
Source File: GivenClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void areMemberClasses_predicate() {
    List<JavaClass> classes = filterResultOf(classes().that().areMemberClasses())
            .on(List.class, Map.class, Map.Entry.class, NestedClassWithSomeMoreClasses.class,
                    NestedClassWithSomeMoreClasses.StaticNestedClass.class, NestedClassWithSomeMoreClasses.InnerMemberClass.class,
                    NestedClassWithSomeMoreClasses.getAnonymousClass(), NestedClassWithSomeMoreClasses.getLocalClass());

    assertThatClasses(classes)
            .matchInAnyOrder(Map.Entry.class, NestedClassWithSomeMoreClasses.class, NestedClassWithSomeMoreClasses.StaticNestedClass.class,
                    NestedClassWithSomeMoreClasses.InnerMemberClass.class);
}
 
Example #15
Source File: ShouldOnlyByClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("should_only_be_by_rule_starts")
public void areNotAnnotatedWith_type(ClassesThat<ClassesShouldConjunction> classesShouldOnlyBeBy) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(
            classesShouldOnlyBeBy.areNotAnnotatedWith(SomeAnnotation.class))
            .on(ClassBeingAccessedByAnnotatedClass.class, AnnotatedClass.class,
                    SimpleClass.class, ClassAccessingSimpleClass.class);

    assertThatClasses(classes).matchInAnyOrder(ClassBeingAccessedByAnnotatedClass.class, AnnotatedClass.class);
}
 
Example #16
Source File: SessionBeanRulesTest.java    From ArchUnit-Examples with Apache License 2.0 5 votes vote down vote up
@Override
public boolean apply(JavaClass input) {
    for (JavaClass subClass : input.getAllSubClasses()) {
        if (isLocalBeanImplementation(subClass, input)) {
            return true;
        }
    }
    return false;
}
 
Example #17
Source File: ShouldClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("no_classes_should_that_rule_starts")
public void areAnonymousClasses_predicate(ClassesThat<ClassesShouldConjunction> noClassesShouldThatRuleStart) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(
            noClassesShouldThatRuleStart.areAnonymousClasses())
            .on(ClassAccessingAnonymousClass.class, ClassAccessingTopLevelClass.class);

    assertThatClasses(classes).matchInAnyOrder(ClassAccessingAnonymousClass.class);
}
 
Example #18
Source File: ShouldClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("no_classes_should_that_rule_starts")
public void areInterfaces_predicate(ClassesThat<ClassesShouldConjunction> noClassesShouldThatRuleStart) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(
            noClassesShouldThatRuleStart.areInterfaces())
            .on(ClassAccessingList.class, ClassAccessingString.class,
                    ClassAccessingCollection.class, ClassAccessingSimpleClass.class);

    assertThatClasses(classes).matchInAnyOrder(ClassAccessingList.class, ClassAccessingCollection.class);
}
 
Example #19
Source File: GivenClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void areNotNestedClasses_predicate() {
    List<JavaClass> classes = filterResultOf(classes().that().areNotNestedClasses())
            .on(List.class, Map.class, Map.Entry.class, NestedClassWithSomeMoreClasses.class,
                    NestedClassWithSomeMoreClasses.StaticNestedClass.class, NestedClassWithSomeMoreClasses.InnerMemberClass.class,
                    NestedClassWithSomeMoreClasses.getAnonymousClass(), NestedClassWithSomeMoreClasses.getLocalClass());

    assertThatClasses(classes).matchInAnyOrder(List.class, Map.class);
}
 
Example #20
Source File: ShouldOnlyByClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("should_only_be_by_rule_starts")
public void areNotInnerClasses_predicate(ClassesThat<ClassesShouldConjunction> classesShouldOnlyBeBy) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(
            classesShouldOnlyBeBy.areNotInnerClasses())
            .on(ClassAccessingInnerMemberClass.class, InnerMemberClassBeingAccessed.class,
                    ClassAccessingOtherClass.class, ClassBeingAccessedByOtherClass.class);

    assertThatClasses(classes).matchInAnyOrder(ClassAccessingInnerMemberClass.class, InnerMemberClassBeingAccessed.class);
}
 
Example #21
Source File: ShouldOnlyByClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("should_only_be_by_rule_starts")
public void haveSimpleNameNotContaining(ClassesThat<ClassesShouldConjunction> classesShouldOnlyBeBy) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(
            classesShouldOnlyBeBy.haveSimpleNameNotContaining("o"))
            .on(ClassAccessedByFoo.class, Foo.class,
                    ClassAccessedByBar.class, Bar.class,
                    ClassAccessedByBaz.class, Baz.class);

    assertThatClasses(classes).matchInAnyOrder(
            ClassAccessedByFoo.class, Foo.class);
}
 
Example #22
Source File: ShouldOnlyByClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void areNotMetaAnnotatedWith_typeName_access() {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(
            classes().should().onlyBeAccessed().byClassesThat().areNotMetaAnnotatedWith(SomeAnnotation.class.getName()))
            .on(ClassBeingAccessedByMetaAnnotatedClass.class, MetaAnnotatedClass.class,
                    ClassBeingAccessedByAnnotatedClass.class, AnnotatedClass.class,
                    SimpleClass.class, ClassAccessingSimpleClass.class,
                    MetaAnnotatedAnnotation.class);

    assertThatClasses(classes).matchInAnyOrder(ClassBeingAccessedByMetaAnnotatedClass.class, MetaAnnotatedClass.class);
}
 
Example #23
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void imports_method_calls_on_overridden_external_class() throws Exception {
    JavaClass classThatCallsExternalMethod = classesIn("testexamples/callimport").get(ExternalOverriddenMethodCall.class);

    JavaMethodCall call = getOnlyElement(classThatCallsExternalMethod.getMethodCallsFromSelf());

    assertThatCall(call)
            .isFrom(classThatCallsExternalMethod.getCodeUnitWithParameterTypes("call"))
            .inLineNumber(9);

    MethodCallTarget target = call.getTarget();
    assertThat(target.getFullName()).isEqualTo(ChildClass.class.getName() + ".overrideMe()");
    assertThat(getOnlyElement(target.resolve()).getFullName()).isEqualTo(ChildClass.class.getName() + ".overrideMe()");
    assertThat(reflect(target)).isEqualTo(method(ChildClass.class, "overrideMe"));
}
 
Example #24
Source File: ShouldClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("classes_should_only_that_rule_starts")
public void only_doNotHaveModifier(ClassesThat<ClassesShouldConjunction> classesShouldOnlyThatRuleStart) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(classesShouldOnlyThatRuleStart.doNotHaveModifier(PRIVATE))
            .on(ClassAccessingPublicClass.class, ClassAccessingPrivateClass.class,
                    ClassAccessingPackagePrivateClass.class, ClassAccessingProtectedClass.class);

    assertThatClasses(classes).matchInAnyOrder(ClassAccessingPrivateClass.class);
}
 
Example #25
Source File: GivenClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void haveSimpleNameNotStartingWith() {
    List<JavaClass> classes = filterResultOf(classes().that().haveSimpleNameNotStartingWith("String"))
            .on(AttributedString.class, String.class, StringBuilder.class, Iterable.class);

    assertThatClasses(classes).matchInAnyOrder(AttributedString.class, Iterable.class);
}
 
Example #26
Source File: ShouldOnlyByClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("should_only_be_by_rule_starts")
public void areNotMemberClasses_predicate(ClassesThat<ClassesShouldConjunction> classesShouldOnlyBeBy) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(
            classesShouldOnlyBeBy.areNotMemberClasses())
            .on(ClassAccessingStaticNestedClass.class, StaticNestedClassBeingAccessed.class,
                    ClassAccessingOtherClass.class, ClassBeingAccessedByOtherClass.class);

    assertThatClasses(classes).matchInAnyOrder(ClassAccessingStaticNestedClass.class, StaticNestedClassBeingAccessed.class);
}
 
Example #27
Source File: ShouldOnlyByClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("should_only_be_by_rule_starts")
public void areTopLevelClasses_predicate(ClassesThat<ClassesShouldConjunction> classesShouldOnlyBeBy) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(
            classesShouldOnlyBeBy.areTopLevelClasses())
            .on(ClassAccessingOtherClass.class, ClassBeingAccessedByOtherClass.class,
                    ClassAccessingStaticNestedClass.class, StaticNestedClassBeingAccessed.class);

    assertThatClasses(classes).matchInAnyOrder(ClassAccessingStaticNestedClass.class, StaticNestedClassBeingAccessed.class);
}
 
Example #28
Source File: ShouldClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("no_classes_should_that_rule_starts")
public void areNotProtected(ClassesThat<ClassesShouldConjunction> noClassesShouldThatRuleStart) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(noClassesShouldThatRuleStart.areNotProtected())
            .on(ClassAccessingPublicClass.class, ClassAccessingPrivateClass.class,
                    ClassAccessingPackagePrivateClass.class, ClassAccessingProtectedClass.class);

    assertThatClasses(classes).matchInAnyOrder(ClassAccessingPublicClass.class, ClassAccessingPrivateClass.class,
            ClassAccessingPackagePrivateClass.class);
}
 
Example #29
Source File: ClassesShouldInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public ClassesThat<ClassesShouldConjunction> accessClassesThat() {
    return new ClassesThatInternal<>(new Function<DescribedPredicate<? super JavaClass>, ClassesShouldConjunction>() {
        @Override
        public ClassesShouldConjunction apply(DescribedPredicate<? super JavaClass> predicate) {
            return addCondition(ArchConditions.accessClassesThat(predicate));
        }
    });
}
 
Example #30
Source File: ShouldClassesThatTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("classes_should_only_that_rule_starts")
public void only_haveSimpleNameNotEndingWith(ClassesThat<ClassesShouldConjunction> classesShouldOnlyThatRuleStart) {
    Set<JavaClass> classes = filterClassesAppearingInFailureReport(
            classesShouldOnlyThatRuleStart.haveSimpleNameNotEndingWith("ist"))
            .on(ClassAccessingList.class, ClassAccessingString.class, ClassAccessingIterable.class);

    assertThat(getOnlyElement(classes)).matches(ClassAccessingList.class);
}