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

The following examples show how to use com.tngtech.archunit.core.domain.JavaClasses. 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: ArchitecturesTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void layered_architecture_combines_multiple_ignores() {
    JavaClasses classes = new ClassFileImporter().importClasses(
            FirstAnyPkgClass.class, SomePkgSubClass.class,
            SecondThreeAnyClass.class, SomePkgClass.class);

    LayeredArchitecture layeredArchitecture = layeredArchitecture()
            .layer("One").definedBy(absolute("some.pkg.."))
            .whereLayer("One").mayNotBeAccessedByAnyLayer()
            .ignoreDependency(FirstAnyPkgClass.class, SomePkgSubClass.class);

    assertThat(layeredArchitecture.evaluate(classes).hasViolation()).as("result has violation").isTrue();

    layeredArchitecture = layeredArchitecture
            .ignoreDependency(SecondThreeAnyClass.class, SomePkgClass.class);

    assertThat(layeredArchitecture.evaluate(classes).hasViolation()).as("result has violation").isFalse();
}
 
Example #2
Source File: PlantUmlArchConditionTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void class_must_be_contained_within_the_diagram_if_it_has_relevant_dependencies() {
    File file = TestDiagram.in(temporaryFolder)
            .component("SomeComponent").withStereoTypes("..someStereotype.")
            .write();
    JavaClasses notContained = importClasses(Object.class);
    PlantUmlArchCondition condition = adhereToPlantUmlDiagram(file, consideringAllDependencies());

    classes().should(condition.ignoreDependenciesWithOrigin(equivalentTo(Object.class)))
            .check(notContained);

    thrown.expect(IllegalStateException.class);
    thrown.expectMessage(String.format(
            "Class %s is not contained in any component",
            getOnlyElement(notContained).getName()));

    classes().should(condition).check(notContained);
}
 
Example #3
Source File: ArchitecturesTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
@UseDataProvider("layeredArchitectureDefinitions")
public void layered_architecture_gathers_all_layer_violations(LayeredArchitecture architecture) {
    JavaClasses classes = new ClassFileImporter().importPackages(absolute(""));

    EvaluationResult result = architecture.evaluate(classes);

    assertPatternMatches(result.getFailureReport().getDetails(),
            ImmutableSet.of(
                    expectedAccessViolationPattern(FirstAnyPkgClass.class, "call", SomePkgSubClass.class, "callMe"),
                    expectedAccessViolationPattern(SecondThreeAnyClass.class, "call", SomePkgClass.class, "callMe"),
                    expectedAccessViolationPattern(FirstThreeAnyClass.class, "call", FirstAnyPkgClass.class, "callMe"),
                    fieldTypePattern(FirstAnyPkgClass.class, "illegalTarget", SomePkgSubClass.class),
                    fieldTypePattern(FirstThreeAnyClass.class, "illegalTarget", FirstAnyPkgClass.class),
                    fieldTypePattern(SecondThreeAnyClass.class, "illegalTarget", SomePkgClass.class)));
}
 
Example #4
Source File: ClassFileImporterSlowTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void imports_classes_from_classpath_specified_in_manifest_file() {
    TestClassFile testClassFile = new TestClassFile().create();
    String manifestClasspath = testClassFile.getClasspathRoot().getAbsolutePath();
    String jarPath = new TestJarFile()
            .withManifestAttribute(CLASS_PATH, manifestClasspath)
            .create()
            .getName();

    verifyCantLoadWithCurrentClasspath(testClassFile);
    System.setProperty(JAVA_CLASS_PATH_PROP, jarPath);

    JavaClasses javaClasses = new ClassFileImporter().importPackages(testClassFile.getPackageName());

    assertThat(javaClasses).extracting("name").contains(testClassFile.getClassName());
}
 
Example #5
Source File: ClassFileImporterSlowTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void creates_JavaPackages() {
    JavaClasses javaClasses = importJavaBase();

    JavaPackage defaultPackage = javaClasses.getDefaultPackage();

    assertThat(defaultPackage.containsPackage("java"))
            .as("Created default package contains 'java'").isTrue();

    JavaPackage javaPackage = defaultPackage.getPackage("java.lang");
    assertThatClasses(javaPackage.getClasses()).contain(Object.class, String.class, Integer.class);
    assertThatClasses(javaPackage.getAllClasses()).contain(Object.class, Annotation.class, Field.class);

    assertThat(javaClasses.containPackage("java.util"))
            .as("Classes contain package 'java.util'").isTrue();
    assertThatClasses(javaClasses.getPackage("java.util").getClasses()).contain(List.class);
}
 
Example #6
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void imports_paths() throws Exception {
    File exampleFolder = new File(new File(urlOf(getClass()).toURI()).getParentFile(), "testexamples");
    File folderOne = new File(exampleFolder, "pathone");
    File folderTwo = new File(exampleFolder, "pathtwo");

    JavaClasses classes = new ClassFileImporter()
            .importPaths(ImmutableList.of(folderOne.toPath(), folderTwo.toPath()));
    assertThatClasses(classes).matchInAnyOrder(Class11.class, Class12.class, Class21.class, Class22.class);

    classes = new ClassFileImporter().importPaths(folderOne.toPath(), folderTwo.toPath());
    assertThatClasses(classes).matchInAnyOrder(Class11.class, Class12.class, Class21.class, Class22.class);

    classes = new ClassFileImporter().importPaths(folderOne.getAbsolutePath(), folderTwo.getAbsolutePath());
    assertThatClasses(classes).matchInAnyOrder(Class11.class, Class12.class, Class21.class, Class22.class);

    classes = new ClassFileImporter().importPath(folderOne.toPath());
    assertThatClasses(classes).matchInAnyOrder(Class11.class, Class12.class);

    classes = new ClassFileImporter().importPath(folderOne.getAbsolutePath());
    assertThatClasses(classes).matchInAnyOrder(Class11.class, Class12.class);
}
 
Example #7
Source File: ClassesShouldEvaluator.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
Set<JavaClass> on(Class<?>... toCheck) {
    JavaClasses classes = importClasses(toCheck);
    List<String> relevantFailures = getRelevantFailures(classes);
    Set<JavaClass> result = new HashSet<>();
    for (JavaClass clazz : classes) {
        if (anyLineMatches(relevantFailures, clazz)) {
            result.add(clazz);
        }
    }
    return result;
}
 
Example #8
Source File: ArchUnitTestDescriptor.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void createChildren(ElementResolver resolver) {
    Supplier<JavaClasses> classes =
            memoize(() -> classCache.getClassesToAnalyzeFor(testClass, new JUnit5ClassAnalysisRequest(testClass)))::get;

    getAllFields(testClass, withAnnotation(ArchTest.class))
            .forEach(field -> resolveField(resolver, classes, field));
    getAllMethods(testClass, withAnnotation(ArchTest.class))
            .forEach(method -> resolveMethod(resolver, classes, method));
}
 
Example #9
Source File: CompositeArchRuleTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private static ArchRule createArchRuleWithSatisfied(final boolean satisfied) {
    return ArchRule.Factory.create(new AbstractClassesTransformer<JavaClass>("irrelevant") {
        @Override
        public Iterable<JavaClass> doTransform(JavaClasses collection) {
            return collection;
        }
    }, new ArchCondition<JavaClass>("irrelevant") {
        @Override
        public void check(JavaClass item, ConditionEvents events) {
            events.add(new SimpleConditionEvent(item, satisfied, "irrelevant"));
        }
    }, Priority.MEDIUM).as(String.format("%s rule", satisfied ? "satisfied" : "failing"));
}
 
Example #10
Source File: ClassCacheTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void get_all_classes_by_LocationProvider() {
    JavaClasses classes = cache.getClassesToAnalyzeFor(TestClass.class, new TestAnalysisRequest()
            .withPackagesRoots(ClassCacheTest.class)
            .withLocationProviders(TestLocationProviderOfClass_String.class, TestLocationProviderOfClass_Rule.class));

    assertThatClasses(classes).contain(String.class, Rule.class, getClass());

    classes = cache.getClassesToAnalyzeFor(TestClassWithLocationProviderUsingTestClass.class,
            analyzeLocation(LocationOfClass.Provider.class));

    assertThatClasses(classes).contain(String.class);
    assertThatClasses(classes).doNotContain(getClass());
}
 
Example #11
Source File: ClassCacheTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void non_existing_packages_are_ignored() {
    JavaClasses first = cache.getClassesToAnalyzeFor(TestClass.class, new TestAnalysisRequest()
            .withPackages("something.that.doesnt.exist")
            .withPackagesRoots(Rule.class));
    JavaClasses second = cache.getClassesToAnalyzeFor(TestClass.class,
            analyzePackagesOf(Rule.class));

    assertThat(first).isEqualTo(second);
    verifyNumberOfImports(1);
}
 
Example #12
Source File: AbstractClassesTransformer.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public final ClassesTransformer<T> that(final DescribedPredicate<? super T> predicate) {
    return new AbstractClassesTransformer<T>(description + " that " + predicate.getDescription()) {
        @Override
        public Iterable<T> doTransform(JavaClasses collection) {
            Iterable<T> transformed = AbstractClassesTransformer.this.doTransform(collection);
            return Guava.Iterables.filter(transformed, predicate);
        }
    };
}
 
Example #13
Source File: Transformers.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
static ClassesTransformer<JavaMember> members() {
    return new AbstractClassesTransformer<JavaMember>("members") {
        @Override
        public Iterable<JavaMember> doTransform(JavaClasses collection) {
            ImmutableSet.Builder<JavaMember> result = ImmutableSet.builder();
            for (JavaClass javaClass : collection) {
                result.addAll(javaClass.getMembers());
            }
            return result.build();
        }
    };
}
 
Example #14
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void imports_classes_outside_of_the_classpath() throws IOException {
    Path targetDir = outsideOfClassPath
            .onlyKeep(not(containsPattern("^Missing.*")))
            .setUp(getClass().getResource("testexamples/outsideofclasspath"));

    JavaClasses classes = new ClassFileImporter().importPath(targetDir);

    assertThat(classes).hasSize(5);
    assertThat(classes).extracting("name").containsOnly(
            "com.tngtech.archunit.core.importer.testexamples.outsideofclasspath.ChildClass",
            "com.tngtech.archunit.core.importer.testexamples.outsideofclasspath.MiddleClass",
            "com.tngtech.archunit.core.importer.testexamples.outsideofclasspath.ExistingDependency",
            "com.tngtech.archunit.core.importer.testexamples.outsideofclasspath.ChildClass$MySeed",
            "com.tngtech.archunit.core.importer.testexamples.outsideofclasspath.ExistingDependency$GimmeADescription"
    );

    JavaClass middleClass = findAnyByName(classes,
            "com.tngtech.archunit.core.importer.testexamples.outsideofclasspath.MiddleClass");
    assertThat(middleClass.getSimpleName()).as("simple name").isEqualTo("MiddleClass");
    assertThat(middleClass.isInterface()).as("is interface").isFalse();
    assertThatCall(findAnyByName(middleClass.getMethodCallsFromSelf(), "println"))
            .isFrom(middleClass.getMethod("overrideMe"))
            .isTo(targetWithFullName(String.format("%s.println(%s)", PrintStream.class.getName(), String.class.getName())))
            .inLineNumber(12);
    assertThatCall(findAnyByName(middleClass.getMethodCallsFromSelf(), "getSomeString"))
            .isFrom(middleClass.getMethod("overrideMe"))
            .isTo(targetWithFullName(
                    "com.tngtech.archunit.core.importer.testexamples.outsideofclasspath.MissingDependency.getSomeString()"))
            .inLineNumber(12);

    JavaClass gimmeADescription = findAnyByName(classes,
            "com.tngtech.archunit.core.importer.testexamples.outsideofclasspath.ExistingDependency$GimmeADescription");
    assertThat(gimmeADescription.getSimpleName()).as("simple name").isEqualTo("GimmeADescription");
    assertThat(gimmeADescription.isInterface()).as("is interface").isTrue();
}
 
Example #15
Source File: ClassCacheTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("test_classes_without_any_imported_classes")
public void when_there_are_only_nonexisting_sources_nothing_is_imported(TestAnalysisRequest analysisRequest) {
    JavaClasses classes = cache.getClassesToAnalyzeFor(TestClass.class, analysisRequest);

    assertThat(classes).isEmpty();

    verify(cacheClassFileImporter).importClasses(any(ImportOptions.class), locationCaptor.capture());
    assertThat(locationCaptor.getValue()).isEmpty();
}
 
Example #16
Source File: ArchUnitTestDescriptor.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private static void resolveArchRules(
        TestDescriptor parent, ElementResolver resolver, Field field, Supplier<JavaClasses> classes) {

    DeclaredArchRules rules = getDeclaredRules(field);

    resolver.resolveClass(rules.getDefinitionLocation())
            .ifRequestedAndResolved(CreatesChildren::createChildren)
            .ifRequestedButUnresolved((clazz, childResolver) -> {
                ArchUnitRulesDescriptor rulesDescriptor = new ArchUnitRulesDescriptor(childResolver, rules, classes, field);
                parent.addChild(rulesDescriptor);
                rulesDescriptor.createChildren(childResolver);
            });
}
 
Example #17
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void classes_know_which_fields_have_their_type() {
    JavaClasses classes = new ClassFileImporter().importClasses(SomeClass.class, OtherClass.class, SomeEnum.class);

    assertThat(classes.get(SomeEnum.class).getFieldsWithTypeOfSelf())
            .extracting("name").contains("other", "someEnum");
}
 
Example #18
Source File: ArchUnitTestDescriptor.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private static void resolveChildren(
        TestDescriptor parent, ElementResolver resolver, Field field, Supplier<JavaClasses> classes) {

    if (ArchRules.class.isAssignableFrom(field.getType())) {
        resolveArchRules(parent, resolver, field, classes);
    } else {
        parent.addChild(new ArchUnitRuleDescriptor(resolver.getUniqueId(), getValue(field), classes, field));
    }
}
 
Example #19
Source File: ClassCacheTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void filters_jars_relative_to_class() {
    JavaClasses classes = cache.getClassesToAnalyzeFor(TestClass.class, analyzePackagesOf(Rule.class));

    assertThat(classes).isNotEmpty();
    for (JavaClass clazz : classes) {
        assertThat(clazz.getPackageName()).doesNotContain("tngtech");
    }
}
 
Example #20
Source File: SlicesTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void matching_description() {
    JavaClasses classes = importClassesWithContext(Object.class);

    Slices.Transformer transformer = Slices.matching("java.(*)..");
    assertThat(transformer.getDescription()).isEqualTo("slices matching 'java.(*)..'");

    Slices slices = transformer.transform(classes);
    assertThat(slices.getDescription()).isEqualTo("slices matching 'java.(*)..'");

    slices = transformer.that(DescribedPredicate.<Slice>alwaysTrue().as("changed")).transform(classes);
    assertThat(slices.getDescription()).isEqualTo("slices matching 'java.(*)..' that changed");
}
 
Example #21
Source File: AbstractClassesTransformerTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void description_can_be_overwritten() {
    ClassesTransformer<String> transformer = toNameTransformer().as("names")
            .that(endInTest().as("end in Test"))
            .as("override");

    JavaClasses classes = importClassesWithContext(AbstractClassesTransformer.class, AbstractClassesTransformerTest.class);
    DescribedIterable<String> transformed = transformer.transform(classes);

    assertThat(transformed.getDescription()).isEqualTo("override");
}
 
Example #22
Source File: AggregateArchitectureTest.java    From ddd-with-spring with Apache License 2.0 5 votes vote down vote up
@ArchTest
public static void aggregateAnnotationRules(JavaClasses importedClasses) {
    ArchRule namingToAnnotation = classes().that().haveSimpleNameEndingWith("Aggregate").should().beAnnotatedWith(Aggregate.class);
    namingToAnnotation.check(importedClasses);

    ArchRule annotationToNaming = classes().that().areAnnotatedWith(Aggregate.class).should().haveSimpleNameEndingWith("Aggregate");
    annotationToNaming.check(importedClasses);
}
 
Example #23
Source File: SlicesTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void default_naming_slices() {
    JavaClasses classes = importClassesWithContext(Object.class, String.class, Pattern.class);
    DescribedIterable<Slice> slices = Slices.matching("java.(*)..").transform(classes);

    assertThat(slices).extractingResultOf("getDescription").containsOnly("Slice lang", "Slice util");
}
 
Example #24
Source File: ArchRuleTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private ClassesTransformer<String> strings() {
    return new AbstractClassesTransformer<String>("strings") {
        @Override
        public Iterable<String> doTransform(JavaClasses collection) {
            SortedSet<String> result = new TreeSet<>();
            for (JavaClass javaClass : collection) {
                result.add(javaClass.getName());
            }
            return result;
        }
    };
}
 
Example #25
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void handles_static_modifier_of_nested_classes() throws Exception {
    JavaClasses classes = classesIn("testexamples/nestedimport").classes;

    assertThat(classes.get(ClassWithNestedClass.class).getModifiers()).as("modifiers of ClassWithNestedClass").doesNotContain(STATIC);
    assertThat(classes.get(ClassWithNestedClass.NestedClass.class).getModifiers()).as("modifiers of ClassWithNestedClass.NestedClass").doesNotContain(STATIC);
    assertThat(classes.get(ClassWithNestedClass.StaticNestedClass.class).getModifiers()).as("modifiers of ClassWithNestedClass.StaticNestedClass").contains(STATIC);
    assertThat(classes.get(ClassWithNestedClass.NestedInterface.class).getModifiers()).as("modifiers of ClassWithNestedClass.NestedInterface").contains(STATIC);
    assertThat(classes.get(ClassWithNestedClass.StaticNestedInterface.class).getModifiers()).as("modifiers of ClassWithNestedClass.StaticNestedInterface").contains(STATIC);
}
 
Example #26
Source File: AbstractClassesTransformerTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void description_is_extended_by_predicate() {
    ClassesTransformer<String> transformer = toNameTransformer().as("names").that(endInTest().as("end in Test"));

    JavaClasses classes = importClassesWithContext(AbstractClassesTransformer.class, AbstractClassesTransformerTest.class);
    DescribedIterable<String> transformed = transformer.transform(classes);

    assertThat(transformed.getDescription()).isEqualTo("names that end in Test");
}
 
Example #27
Source File: ClassFileImporterSlowTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void imports_the_classpath() {
    JavaClasses classes = new ClassFileImporter().importClasspath();

    assertThatClasses(classes).contain(ClassFileImporter.class, getClass());
    assertThatClasses(classes).doNotContain(Rule.class); // Default does not import jars
    assertThatClasses(classes).doNotContain(File.class); // Default does not import JDK classes

    classes = new ClassFileImporter().importClasspath(new ImportOptions().with(importJavaBaseOrRtAndJUnitJarAndFilesOnTheClasspath()));

    assertThatClasses(classes).contain(ClassFileImporter.class, getClass(), Rule.class, File.class);
}
 
Example #28
Source File: SlicesTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void renaming_slices() {
    JavaClasses classes = importClassesWithContext(Object.class, String.class, Pattern.class);
    DescribedIterable<Slice> slices = Slices.matching("java.(*)..").namingSlices("Hallo $1").transform(classes);

    assertThat(slices).extractingResultOf("getDescription").containsOnly("Hallo lang", "Hallo util");
}
 
Example #29
Source File: Transformers.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
static ClassesTransformer<JavaCodeUnit> codeUnits() {
    return new AbstractClassesTransformer<JavaCodeUnit>("code units") {
        @Override
        public Iterable<JavaCodeUnit> doTransform(JavaClasses collection) {
            ImmutableSet.Builder<JavaCodeUnit> result = ImmutableSet.builder();
            for (JavaClass javaClass : collection) {
                result.addAll(javaClass.getCodeUnits());
            }
            return result.build();
        }
    };
}
 
Example #30
Source File: ArchitectureTests.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void freeOfCycles() {
	String pkg = "org.springframework.boot.autoconfigure.security.oauth2";
	JavaClasses classes = new ClassFileImporter().importPackages(pkg);
	slices().matching("(**)").should().beFreeOfCycles().ignoreDependency(isATestClass(), alwaysTrue())
			.check(classes);
}