com.tngtech.archunit.core.importer.ClassFileImporter Java Examples

The following examples show how to use com.tngtech.archunit.core.importer.ClassFileImporter. 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
@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 #2
Source File: Modules.java    From moduliths with Apache License 2.0 6 votes vote down vote up
private Modules(ModulithMetadata metadata, Collection<String> packages, DescribedPredicate<JavaClass> ignored,
		boolean useFullyQualifiedModuleNames) {

	this.metadata = metadata;

	List<String> toImport = new ArrayList<>(packages);
	toImport.addAll(FRAMEWORK_PACKAGES);

	this.allClasses = new ClassFileImporter() //
			.withImportOption(new ImportOption.DoNotIncludeTests()) //
			.importPackages(toImport) //
			.that(not(ignored));

	Classes classes = Classes.of(allClasses);

	this.modules = packages.stream() //
			.flatMap(it -> getSubpackages(classes, it)) //
			.map(it -> new Module(it, useFullyQualifiedModuleNames)) //
			.collect(toMap(Module::getName, Function.identity()));

	this.rootPackages = packages.stream() //
			.map(it -> JavaPackage.of(classes, it).toSingle()) //
			.collect(Collectors.toList());

	this.sharedModules = Collections.emptySet();
}
 
Example #3
Source File: ArchTest.java    From jhipster-online with Apache License 2.0 6 votes vote down vote up
@Test
void servicesAndRepositoriesShouldNotDependOnWebLayer() {

    JavaClasses importedClasses = new ClassFileImporter()
        .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
        .importPackages("io.github.jhipster.online");

    noClasses()
        .that()
            .resideInAnyPackage("io.github.jhipster.online.service..")
        .or()
            .resideInAnyPackage("io.github.jhipster.online.repository..")
        .should().dependOnClassesThat()
            .resideInAnyPackage("..io.github.jhipster.online.web..")
    .because("Services and repositories should not depend on web layer")
    .check(importedClasses);
}
 
Example #4
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 #5
Source File: ArchTest.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
@Test
void servicesAndRepositoriesShouldNotDependOnWebLayer() {

    JavaClasses importedClasses = new ClassFileImporter()
        .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
        .importPackages("io.github.jhipster.registry");

    noClasses()
        .that()
            .resideInAnyPackage("io.github.jhipster.registry.service..")
        .or()
            .resideInAnyPackage("io.github.jhipster.registry.repository..")
        .should().dependOnClassesThat()
            .resideInAnyPackage("..io.github.jhipster.registry.web..")
    .because("Services and repositories should not depend on web layer")
    .check(importedClasses);
}
 
Example #6
Source File: JavaClassTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void predicate_belong_to() {
    JavaClasses classes = new ClassFileImporter().importPackagesOf(getClass());
    JavaClass outerAnonymous =
            getOnlyClassSettingField(classes, ClassWithNamedAndAnonymousInnerClasses.name_of_fieldIndicatingOuterAnonymousInnerClass);
    JavaClass nestedAnonymous =
            getOnlyClassSettingField(classes, ClassWithNamedAndAnonymousInnerClasses.name_of_fieldIndicatingNestedAnonymousInnerClass);

    assertThat(belongToAnyOf(Object.class, ClassWithNamedAndAnonymousInnerClasses.class))
            .hasDescription(String.format("belong to any of [%s, %s]",
                    Object.class.getName(), ClassWithNamedAndAnonymousInnerClasses.class.getName()))
            .accepts(classes.get(ClassWithNamedAndAnonymousInnerClasses.class))
            .accepts(classes.get(ClassWithNamedAndAnonymousInnerClasses.NamedInnerClass.class))
            .accepts(classes.get(ClassWithNamedAndAnonymousInnerClasses.NamedInnerClass.NestedNamedInnerClass.class))
            .accepts(outerAnonymous)
            .accepts(nestedAnonymous)
            .rejects(classes.get(getClass()));
}
 
Example #7
Source File: GivenSlicesTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void restricting_slices_that_should_not_depend_on_each_other() {
    GivenSlices givenSlices = slices().matching("..testclasses.(*)..");
    JavaClasses classes = new ClassFileImporter().importPackages("com.tngtech.archunit.library.testclasses");

    EvaluationResult result = givenSlices.that(DescribedPredicate.<Slice>alwaysFalse())
            .and(DescribedPredicate.<Slice>alwaysTrue())
            .should().notDependOnEachOther().evaluate(classes);

    assertThat(result.hasViolation()).as("Result has violation").isFalse();

    result = givenSlices.that(DescribedPredicate.<Slice>alwaysTrue())
            .or(DescribedPredicate.<Slice>alwaysFalse())
            .should().notDependOnEachOther().evaluate(classes);

    assertThat(result.hasViolation()).as("Result has violation").isTrue();
}
 
Example #8
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;
}
 
Example #9
Source File: ArchitecturesTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("toIgnore")
public void layered_architecture_ignores_specified_violations(RuleWithIgnore layeredArchitectureWithIgnore) {
    JavaClasses classes = new ClassFileImporter().importClasses(
            FirstAnyPkgClass.class, SomePkgSubClass.class,
            SecondThreeAnyClass.class, SomePkgClass.class);

    EvaluationResult result = layeredArchitectureWithIgnore.rule.evaluate(classes);

    assertThat(singleLine(result))
            .doesNotMatch(String.format(".*%s[^%s]*%s.*",
                    quote(FirstAnyPkgClass.class.getName()), NEW_LINE_REPLACE, quote(SomePkgSubClass.class.getName())))
            .matches(String.format(".*%s[^%s]*%s.*",
                    quote(SecondThreeAnyClass.class.getName()), NEW_LINE_REPLACE, quote(SomePkgClass.class.getName())));
}
 
Example #10
Source File: ArchitecturesTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void onion_architecture_gathers_all_violations() {
    OnionArchitecture architecture = getTestOnionArchitecture();
    JavaClasses classes = new ClassFileImporter().importPackages(absolute("onionarchitecture"));

    EvaluationResult result = architecture.evaluate(classes);

    assertPatternMatches(result.getFailureReport().getDetails(), getExpectedOnionViolations().toPatterns());
}
 
Example #11
Source File: ArchitecturesTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void onion_architecture_is_not_violated_by_ignored_dependencies() {
    OnionArchitecture onionIgnoringOriginApplicationLayerClass = getTestOnionArchitecture()
            .ignoreDependency(ApplicationLayerClass.class, CliAdapterLayerClass.class)
            .ignoreDependency(ApplicationLayerClass.class.getName(), PersistenceAdapterLayerClass.class.getName())
            .ignoreDependency(simpleNameStartingWith("ApplicationLayerCl"), simpleNameContaining("estAdapterLayerCl"));
    JavaClasses classes = new ClassFileImporter().importPackages(absolute("onionarchitecture"));

    EvaluationResult result = onionIgnoringOriginApplicationLayerClass.evaluate(classes);

    ExpectedOnionViolations expectedViolations = getExpectedOnionViolations().withoutViolationsWithOrigin(ApplicationLayerClass.class);
    assertPatternMatches(result.getFailureReport().getDetails(), expectedViolations.toPatterns());
}
 
Example #12
Source File: ArchitecturesTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void onion_architecture_rejects_empty_layers_by_default() {
    OnionArchitecture architecture = anOnionArchitectureWithEmptyLayers();

    JavaClasses classes = new ClassFileImporter().importPackages(absolute("onionarchitecture"));

    EvaluationResult result = architecture.evaluate(classes);
    assertFailureOnionArchitectureWithEmptyLayers(result);
}
 
Example #13
Source File: ArchitecturesTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void onion_architecture_allows_empty_layers_if_all_layers_are_optional() {
    OnionArchitecture architecture = anOnionArchitectureWithEmptyLayers().withOptionalLayers(true);
    assertThat(architecture.getDescription()).startsWith("Onion architecture consisting of (optional)");

    JavaClasses classes = new ClassFileImporter().importPackages(absolute("onionarchitecture"));

    EvaluationResult result = architecture.evaluate(classes);
    assertThat(result.hasViolation()).as("result of evaluating empty layers has violation").isFalse();
    assertThat(result.getFailureReport().isEmpty()).as("failure report").isTrue();
}
 
Example #14
Source File: ArchitecturesTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void onion_architecture_rejects_empty_layers_if_layers_are_explicitly_not_optional_by_default() {
    OnionArchitecture architecture = anOnionArchitectureWithEmptyLayers().withOptionalLayers(false);

    JavaClasses classes = new ClassFileImporter().importPackages(absolute("onionarchitecture"));

    EvaluationResult result = architecture.evaluate(classes);
    assertFailureOnionArchitectureWithEmptyLayers(result);
}
 
Example #15
Source File: SliceRuleTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private String getFailureReportForCyclesInRootPackageOf(Class<?> packageRoot) {
    JavaClasses classes = new ClassFileImporter().importPackagesOf(packageRoot);
    return slices()
            .matching(packageRoot.getPackage().getName() + ".(*)")
            .should().beFreeOfCycles().evaluate(classes)
            .getFailureReport().toString();
}
 
Example #16
Source File: SlicesShouldTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("rules")
public void slice_rules_should_ignore_configured_dependencies(SliceRule rule) {
    JavaClasses classes = new ClassFileImporter().importPackages(TEST_CLASSES_PACKAGE);

    assertViolations(classes, rule)
            .contain(FirstThreeAnyClass.class, SecondThreeAnyClass.class)
            .contain(FirstAnyPkgClass.class, SomePkgSubClass.class)
            .contain(SecondAnyClass.class, FirstAnyPkgClass.class)
            .contain(SecondThreeAnyClass.class, SomePkgClass.class);

    rule = rule.ignoreDependency(classIn(".*\\.first\\.three\\..*"), DescribedPredicate.<JavaClass>alwaysTrue());
    assertViolations(classes, rule)
            .doNotContain(FirstThreeAnyClass.class, SecondThreeAnyClass.class)
            .contain(FirstAnyPkgClass.class, SomePkgSubClass.class)
            .contain(SecondAnyClass.class, FirstAnyPkgClass.class)
            .contain(SecondThreeAnyClass.class, SomePkgClass.class);

    rule = rule.ignoreDependency(FirstAnyPkgClass.class.getName(), SomePkgSubClass.class.getName());
    assertViolations(classes, rule)
            .doNotContain(FirstThreeAnyClass.class, SecondThreeAnyClass.class)
            .doNotContain(FirstAnyPkgClass.class, SomePkgSubClass.class)
            .contain(SecondAnyClass.class, FirstAnyPkgClass.class)
            .contain(SecondThreeAnyClass.class, SomePkgClass.class);

    rule = rule.ignoreDependency(SecondAnyClass.class, FirstAnyPkgClass.class);
    assertViolations(classes, rule)
            .doNotContain(FirstThreeAnyClass.class, SecondThreeAnyClass.class)
            .doNotContain(FirstAnyPkgClass.class, SomePkgSubClass.class)
            .doNotContain(SecondAnyClass.class, FirstAnyPkgClass.class)
            .contain(SecondThreeAnyClass.class, SomePkgClass.class);

    rule = rule.ignoreDependency(DescribedPredicate.<JavaClass>alwaysTrue(), classIn(".*\\.some\\.pkg\\..*"));
    assertViolations(classes, rule)
            .doNotContain(FirstThreeAnyClass.class, SecondThreeAnyClass.class)
            .doNotContain(FirstAnyPkgClass.class, SomePkgSubClass.class)
            .doNotContain(SecondAnyClass.class, FirstAnyPkgClass.class)
            .doNotContain(SecondThreeAnyClass.class, SomePkgClass.class);
}
 
Example #17
Source File: ArchUnitTests.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
public void testJGraphT() {
	// JGraphT library
	// TODO reduce package dependencies
	JavaClasses importedClasses = new ClassFileImporter().importPackages("org");

	ArchRule myRule = classes().that().resideInAPackage("org.jgrapht..").//
			should().onlyBeAccessed().byAnyPackage(//
					"org.jgrapht..", //
					"..core.builtin..", //
					"..core.expression", //
					"..core.expression.data", //
					"..core.reflection.system..");

	myRule.check(importedClasses);
}
 
Example #18
Source File: ArchUnitTests.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
public void testConsoleMethods() {
	JavaClasses importedClasses = new ClassFileImporter().importPackages("org.matheclipse.core.eval");

	ArchRule rule = methods().that().areDeclaredIn("org.matheclipse.core.eval.Console").//
			and().doNotHaveName("main").//
			should().notBePublic().andShould().notBeProtected();
	rule.check(importedClasses);
}
 
Example #19
Source File: ArchUnitTests.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
public void testMMAConsoleMethods() {
	JavaClasses importedClasses = new ClassFileImporter().importPackages("org.matheclipse.core.eval");

	ArchRule rule = methods().that().areDeclaredIn("org.matheclipse.core.eval.MMAConsole").//
			and().doNotHaveName("main").//
			should().notBePublic().andShould().notBeProtected();
	rule.check(importedClasses);
}
 
Example #20
Source File: ArchUnitTests.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
public void testAST() {
	JavaClasses importedClasses = new ClassFileImporter().importPackages("org.matheclipse");

	ArchRule myRule = classes().that().resideInAPackage("org.matheclipse.core.expression..").//
			and().haveSimpleName("AST"). //
			// TODO change dependency from "org.matheclipse.core.convert"
			should().onlyBeAccessed().byAnyPackage("org.matheclipse.core.expression..");

	myRule.check(importedClasses);
}
 
Example #21
Source File: ArchUnitTests.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
public void testAST0() {
	JavaClasses importedClasses = new ClassFileImporter().importPackages("org.matheclipse");

	ArchRule myRule = classes().that().resideInAPackage("org.matheclipse.core.expression..").//
			and().haveSimpleName("AST0"). //
			should().onlyBeAccessed().byAnyPackage("org.matheclipse.core.expression..");

	myRule.check(importedClasses);
}
 
Example #22
Source File: ArchUnitTests.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
public void testAST1() {
	JavaClasses importedClasses = new ClassFileImporter().importPackages("org.matheclipse");

	ArchRule myRule = classes().that().resideInAPackage("org.matheclipse.core.expression..").//
			and().haveSimpleName("AST1"). //
			should().onlyBeAccessed().byAnyPackage("org.matheclipse.core.expression..");

	myRule.check(importedClasses);
}
 
Example #23
Source File: ArchUnitTests.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
public void testAST2() {
	JavaClasses importedClasses = new ClassFileImporter().importPackages("org.matheclipse");

	ArchRule myRule = classes().that().resideInAPackage("org.matheclipse.core.expression..").//
			and().haveSimpleName("AST2"). //
			should().onlyBeAccessed().byAnyPackage("org.matheclipse.core.expression..");

	myRule.check(importedClasses);
}
 
Example #24
Source File: ArchUnitTests.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
public void testAST3() {
	JavaClasses importedClasses = new ClassFileImporter().importPackages("org.matheclipse");

	ArchRule myRule = classes().that().resideInAPackage("org.matheclipse.core.expression..").//
			and().haveSimpleName("AST3"). //
			should().onlyBeAccessed().byAnyPackage("org.matheclipse.core.expression..");

	myRule.check(importedClasses);
}
 
Example #25
Source File: ArchUnitTests.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
/**
 * <p>
 * Split in packages <code>org.matheclipse.core..</code> and <code>org.matheclipse.parser..</code>.
 * <code>org.matheclipse.parser..</code> should not call Symja <code>IExpr</code> object hierarchy.
 * </p>
 * <b>Note:</b>The <code>ExprParser</code> in package <code>org.matheclipse.core.parser..</code> is allowed to call
 * Symja <code>IExpr</<code> object hierarchy.
 */
public void testNoIExprInParser() {
	JavaClasses importedClasses = new ClassFileImporter().importPackages("org.matheclipse");

	ArchRule rule = classes().that().haveSimpleName("IExpr").or().haveSimpleName("IAST").//
			should().onlyBeAccessed().byAnyPackage(//
					"org.matheclipse.core..");
	rule.check(importedClasses);
}
 
Example #26
Source File: ArchUnitTests.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
public void testLogicNG() {
	// LogicNG library
	JavaClasses importedClasses = new ClassFileImporter().importPackages("org");

	ArchRule myRule = classes().that().resideInAPackage("org.logicng..").//
			should().onlyBeAccessed().byAnyPackage("org.logicng..", "..core.builtin..");

	myRule.check(importedClasses);
}
 
Example #27
Source File: ArchitecturesTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void layered_architecture_rejects_empty_layers_if_layers_are_explicity_not_optional_by_default() {
    LayeredArchitecture architecture = aLayeredArchitectureWithEmptyLayers().withOptionalLayers(false);

    JavaClasses classes = new ClassFileImporter().importPackages(absolute(""));

    EvaluationResult result = architecture.evaluate(classes);
    assertFailureLayeredArchitectureWithEmptyLayers(result);
}
 
Example #28
Source File: ArchitectureTest.java    From archunit-examples with MIT License 5 votes vote down vote up
@BeforeClass
public static void setUp() {
  classes = new ClassFileImporter()
    .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
    .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_ARCHIVES)
    .importPackages("com.company.app");
}
 
Example #29
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);
}
 
Example #30
Source File: PojoTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
private Stream<Class<?>> getPojoClasses() {
  // TODO how to identify pojos? Is overwritten equals method enough?
  return new ClassFileImporter()
      .importPackages("pro.taskana").stream()
          .filter(javaClass -> javaClass.tryGetMethod("equals", Object.class).isPresent())
          .map(JavaClass::reflect);
}