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

The following examples show how to use com.tngtech.archunit.core.domain.JavaModifier. 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: JavaClassProcessor.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Override
public void visitInnerClass(String name, String outerName, String innerName, int access) {
    if (importAborted()) {
        return;
    }

    String innerTypeName = createTypeName(name);
    if (!visitingCurrentClass(innerTypeName)) {
        return;
    }

    javaClassBuilder.withSimpleName(nullToEmpty(innerName));

    // Javadoc for innerName: "May be null for anonymous inner classes."
    boolean isAnonymousClass = innerName == null;
    javaClassBuilder.withAnonymousClass(isAnonymousClass);

    // Javadoc for outerName: "May be null for not member classes."
    boolean isMemberClass = outerName != null;
    javaClassBuilder.withMemberClass(isMemberClass);

    if (isMemberClass) {
        javaClassBuilder.withModifiers(JavaModifier.getModifiersForClass(access));
        declarationHandler.registerEnclosingClass(innerTypeName, createTypeName(outerName));
    }
}
 
Example #3
Source File: JavaClassProcessor.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
    LOG.debug("Analyzing class '{}'", name);
    JavaType javaType = JavaTypeImporter.createFromAsmObjectTypeName(name);
    if (alreadyImported(javaType)) {
        return;
    }

    ImmutableSet<String> interfaceNames = createInterfaceNames(interfaces);
    LOG.trace("Found interfaces {} on class '{}'", interfaceNames, name);
    boolean opCodeForInterfaceIsPresent = (access & Opcodes.ACC_INTERFACE) != 0;
    boolean opCodeForEnumIsPresent = (access & Opcodes.ACC_ENUM) != 0;
    Optional<String> superClassName = getSuperClassName(superName, opCodeForInterfaceIsPresent);
    LOG.trace("Found superclass {} on class '{}'", superClassName.orNull(), name);

    javaClassBuilder = new DomainBuilders.JavaClassBuilder()
            .withSourceDescriptor(sourceDescriptor)
            .withType(javaType)
            .withInterface(opCodeForInterfaceIsPresent)
            .withEnum(opCodeForEnumIsPresent)
            .withModifiers(JavaModifier.getModifiersForClass(access));

    className = javaType.getName();
    declarationHandler.onNewClass(className, superClassName, interfaceNames);
}
 
Example #4
Source File: BaseArchitectureComplianceCheck.java    From waltz with Apache License 2.0 6 votes vote down vote up
@Override
public void check(JavaClass item, ConditionEvents events) {
    item.getMethods()
            .stream()
            .filter(m -> m.getName().startsWith("find"))
            .filter(m -> m.getModifiers().contains(JavaModifier.PUBLIC))
            .forEach(m -> {
                JavaClass returnType = m.getReturnType();
                if (! any(validReturnTypes, vrt -> returnType.isAssignableTo(vrt))) {
                    String message = String.format(
                            "Method %s.%s does not return a collection, map or optional. It returns: %s",
                            item.getName(),
                            m.getName(),
                            returnType.getName());
                    events.add(SimpleConditionEvent.violated(item, message));
                }
            });
}
 
Example #5
Source File: Asciidoctor.java    From moduliths with Apache License 2.0 6 votes vote down vote up
private String toOptionalLink(JavaClass source) {

		String type = toCode(FormatableJavaClass.of(source).getAbbreviatedFullName(module));

		if (!source.getModifiers().contains(JavaModifier.PUBLIC)) {
			return type;
		}

		String classPath = convertClassNameToResourcePath(source.getFullName()) //
				.replace('$', '.');

		return Optional.ofNullable(javaDocBase == "¯\\_(ツ)_/¯" ? null : javaDocBase) //
				.map(it -> it.concat("/").concat(classPath).concat(".html")) //
				.map(it -> toLink(type, it)) //
				.orElse(type);
	}
 
Example #6
Source File: JavaClassProcessor.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    if (importAborted()) {
        return super.visitMethod(access, name, desc, signature, exceptions);
    }

    LOG.trace("Analyzing method {}.{}:{}", className, name, desc);
    List<JavaType> parameters = JavaTypeImporter.importAsmMethodArgumentTypes(desc);
    accessHandler.setContext(new CodeUnit(name, namesOf(parameters), className));

    DomainBuilders.JavaCodeUnitBuilder<?, ?> codeUnitBuilder = addCodeUnitBuilder(name);
    codeUnitBuilder
            .withName(name)
            .withModifiers(JavaModifier.getModifiersForMethod(access))
            .withParameters(parameters)
            .withReturnType(JavaTypeImporter.importAsmMethodReturnType(desc))
            .withDescriptor(desc)
            .withThrowsClause(typesFrom(exceptions));

    return new MethodProcessor(className, accessHandler, codeUnitBuilder);
}
 
Example #7
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void imports_simple_enum() throws Exception {
    JavaClass javaClass = classesIn("testexamples/simpleimport").get(EnumToImport.class);

    assertThat(javaClass.getName()).as("full name").isEqualTo(EnumToImport.class.getName());
    assertThat(javaClass.getSimpleName()).as("simple name").isEqualTo(EnumToImport.class.getSimpleName());
    assertThat(javaClass.getPackageName()).as("package name").isEqualTo(EnumToImport.class.getPackage().getName());
    assertThat(javaClass.getModifiers()).as("modifiers").containsOnly(JavaModifier.PUBLIC, JavaModifier.FINAL);
    assertThat(javaClass.getSuperClass().get()).as("super class").matches(Enum.class);
    assertThat(javaClass.getInterfaces()).as("interfaces").isEmpty();
    assertThatClasses(javaClass.getAllInterfaces()).matchInAnyOrder(Enum.class.getInterfaces());
    assertThat(javaClass.isInterface()).as("is interface").isFalse();
    assertThat(javaClass.isEnum()).as("is enum").isTrue();

    JavaEnumConstant constant = javaClass.getEnumConstant(EnumToImport.FIRST.name());
    assertThat(constant.getDeclaringClass()).as("declaring class").isEqualTo(javaClass);
    assertThat(constant.name()).isEqualTo(EnumToImport.FIRST.name());
    assertThat(javaClass.getEnumConstants()).extractingResultOf("name").as("enum constant names")
            .containsOnly(EnumToImport.FIRST.name(), EnumToImport.SECOND.name());
}
 
Example #8
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void imports_simple_class_details() throws Exception {
    ImportedClasses classes = classesIn("testexamples/simpleimport");
    JavaClass javaClass = classes.get(ClassToImportOne.class);

    assertThat(javaClass.getName()).as("full name").isEqualTo(ClassToImportOne.class.getName());
    assertThat(javaClass.getSimpleName()).as("simple name").isEqualTo(ClassToImportOne.class.getSimpleName());
    assertThat(javaClass.getPackageName()).as("package name").isEqualTo(ClassToImportOne.class.getPackage().getName());
    assertThat(javaClass.getModifiers()).as("modifiers").containsOnly(JavaModifier.PUBLIC);
    assertThat(javaClass.getSuperClass().get()).as("super class").matches(Object.class);
    assertThat(javaClass.getInterfaces()).as("interfaces").isEmpty();
    assertThat(javaClass.isInterface()).as("is interface").isFalse();
    assertThat(javaClass.isEnum()).as("is enum").isFalse();
    assertThat(javaClass.getEnclosingClass()).as("enclosing class").isAbsent();
    assertThat(javaClass.isTopLevelClass()).as("is top level class").isTrue();
    assertThat(javaClass.isNestedClass()).as("is nested class").isFalse();
    assertThat(javaClass.isMemberClass()).as("is member class").isFalse();
    assertThat(javaClass.isInnerClass()).as("is inner class").isFalse();
    assertThat(javaClass.isLocalClass()).as("is local class").isFalse();
    assertThat(javaClass.isAnonymousClass()).as("is anonymous class").isFalse();

    assertThat(classes.get(ClassToImportTwo.class).getModifiers()).containsOnly(JavaModifier.PUBLIC, JavaModifier.FINAL);
}
 
Example #9
Source File: GivenClassShouldTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
@UseDataProvider("theClass_should_bePackagePrivate_rules")
public void theClass_should_bePackagePrivate(ArchRule satisfiedRule, ArchRule unsatisfiedRule) {
    assertThatRules(satisfiedRule, unsatisfiedRule, PackagePrivateClass.class, Object.class)
            .haveSuccessfulRuleText("the class %s should be package private",
                    PackagePrivateClass.class.getName())
            .haveFailingRuleText("the class %s should not be package private",
                    PackagePrivateClass.class.getName())
            .containFailureDetail(String.format("Class <%s> does not have modifier %s in %s "
                            + "and Class <%s> does not have modifier %s in %s "
                            + "and Class <%s> does not have modifier %s in %s",
                    quote(PackagePrivateClass.class.getName()),
                    quote(JavaModifier.PRIVATE.name()),
                    locationPattern(GivenClassShouldTest.class),
                    quote(PackagePrivateClass.class.getName()),
                    quote(JavaModifier.PROTECTED.name()),
                    locationPattern(GivenClassShouldTest.class),
                    quote(PackagePrivateClass.class.getName()),
                    quote(JavaModifier.PUBLIC.name()),
                    locationPattern(GivenClassShouldTest.class)))
            .doNotContainFailureDetail(quote(Object.class.getName()));
}
 
Example #10
Source File: GivenClassShouldTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
@UseDataProvider("noClass_should_bePackagePrivate_rules")
public void noClass_should_bePackagePrivate(ArchRule satisfiedRule, ArchRule unsatisfiedRule) {
    assertThatRules(satisfiedRule, unsatisfiedRule, PackagePrivateClass.class, Object.class)
            .haveSuccessfulRuleText("no class %s should not be package private",
                    PackagePrivateClass.class.getName())
            .haveFailingRuleText("no class %s should be package private",
                    PackagePrivateClass.class.getName())
            .containFailureDetail(String.format("Class <%s> does not have modifier %s in %s "
                            + "and Class <%s> does not have modifier %s in %s "
                            + "and Class <%s> does not have modifier %s in %s",
                    quote(PackagePrivateClass.class.getName()),
                    quote(JavaModifier.PRIVATE.name()),
                    locationPattern(GivenClassShouldTest.class),
                    quote(PackagePrivateClass.class.getName()),
                    quote(JavaModifier.PROTECTED.name()),
                    locationPattern(GivenClassShouldTest.class),
                    quote(PackagePrivateClass.class.getName()),
                    quote(JavaModifier.PUBLIC.name()),
                    locationPattern(GivenClassShouldTest.class)))
            .doNotContainFailureDetail(quote(Object.class.getName()));
}
 
Example #11
Source File: Assertions.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
public void matches(Class<?> clazz) {
    assertThat(actual.getName()).as("Name of " + actual)
            .isEqualTo(clazz.getName());
    assertThat(actual.getSimpleName()).as("Simple name of " + actual)
            .isEqualTo(ensureArrayName(clazz.getSimpleName()));
    assertThat(actual.getPackage().getName()).as("Package of " + actual)
            .isEqualTo(getExpectedPackageName(clazz));
    assertThat(actual.getPackageName()).as("Package name of " + actual)
            .isEqualTo(getExpectedPackageName(clazz));
    assertThat(actual.getModifiers()).as("Modifiers of " + actual)
            .isEqualTo(JavaModifier.getModifiersForClass(clazz.getModifiers()));
    assertThat(actual.isArray()).as(actual + " is array").isEqualTo(clazz.isArray());
    assertThat(runtimePropertiesOf(actual.getAnnotations())).as("Annotations of " + actual)
            .isEqualTo(propertiesOf(clazz.getAnnotations()));

    if (clazz.isArray()) {
        new JavaClassAssertion(actual.getComponentType()).matches(clazz.getComponentType());
    }
}
 
Example #12
Source File: Classes.java    From moduliths with Apache License 2.0 5 votes vote down vote up
static String format(JavaClass type, String basePackage) {

		Assert.notNull(type, "Type must not be null!");
		Assert.notNull(basePackage, "Base package must not be null!");

		String prefix = type.getModifiers().contains(JavaModifier.PUBLIC) ? "+" : "o";
		String name = StringUtils.hasText(basePackage) //
				? type.getName().replace(basePackage, "…") //
				: type.getName();

		return String.format("    %s %s", prefix, name);
	}
 
Example #13
Source File: GivenClassShouldTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("theClass_should_haveModifier_public_rules")
public void theClass_should_haveModifier_public(ArchRule satisfiedRule, ArchRule unsatisfiedRule) {
    assertThatRules(satisfiedRule, unsatisfiedRule, PublicClass.class, Object.class)
            .haveSuccessfulRuleText("the class %s should have modifier %s",
                    PublicClass.class.getName(), PUBLIC)
            .haveFailingRuleText("the class %s should not have modifier %s",
                    PublicClass.class.getName(), PUBLIC)
            .containFailureDetail(String.format("Class <%s> has modifier %s in %s",
                    quote(PublicClass.class.getName()),
                    quote(JavaModifier.PUBLIC.name()),
                    locationPattern(GivenClassShouldTest.class)))
            .doNotContainFailureDetail(quote(Object.class.getName()));
}
 
Example #14
Source File: UtilsTest.java    From netdata-java-orchestrator with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testUtils() {
	JavaClasses importedClasses = new ClassFileImporter().importPackages("org.firehol");

	final ArchRule rule = classes().that()
			.haveSimpleNameEndingWith("Utils")
			.should()
			.haveModifier(JavaModifier.FINAL)
			.andShould()
			.haveOnlyPrivateConstructors();

	rule.check(importedClasses);
}
 
Example #15
Source File: HasModifiersTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private static HasModifiers hasModifiers(final JavaModifier... modifiers) {
    return new HasModifiers() {
        @Override
        public Set<JavaModifier> getModifiers() {
            return ImmutableSet.copyOf(modifiers);
        }
    };
}
 
Example #16
Source File: HasModifiersTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void modifier_predicate() {
    assertThat(modifier(JavaModifier.PRIVATE))
            .accepts(hasModifiers(JavaModifier.PRIVATE, JavaModifier.STATIC))
            .rejects(hasModifiers(JavaModifier.PUBLIC, JavaModifier.STATIC))
            .hasDescription("modifier PRIVATE");
}
 
Example #17
Source File: ImportTestUtils.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private static JavaClass javaClassFor(Class<?> owner) {
    return new DomainBuilders.JavaClassBuilder()
            .withType(JavaType.From.name(owner.getName()))
            .withInterface(owner.isInterface())
            .withModifiers(JavaModifier.getModifiersForClass(owner.getModifiers()))
            .build();
}
 
Example #18
Source File: ImportTestUtils.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private static Set<DomainBuilders.BuilderWithBuildParameter<JavaClass, JavaConstructor>> constructorBuildersFor(Class<?> inputClass,
        ClassesByTypeName importedClasses) {
    final Set<DomainBuilders.BuilderWithBuildParameter<JavaClass, JavaConstructor>> constructorBuilders = new HashSet<>();
    for (Constructor<?> constructor : inputClass.getDeclaredConstructors()) {
        constructorBuilders.add(new DomainBuilders.JavaConstructorBuilder()
                .withReturnType(JavaType.From.name(void.class.getName()))
                .withParameters(typesFrom(constructor.getParameterTypes()))
                .withName(CONSTRUCTOR_NAME)
                .withDescriptor(Type.getConstructorDescriptor(constructor))
                .withAnnotations(javaAnnotationBuildersFrom(constructor.getAnnotations(), inputClass, importedClasses))
                .withModifiers(JavaModifier.getModifiersForMethod(constructor.getModifiers()))
                .withThrowsClause(typesFrom(constructor.getExceptionTypes())));
    }
    return constructorBuilders;
}
 
Example #19
Source File: ImportTestUtils.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private static Set<DomainBuilders.BuilderWithBuildParameter<JavaClass, JavaMethod>> methodBuildersFor(Class<?> inputClass,
        ClassesByTypeName importedClasses) {
    final Set<DomainBuilders.BuilderWithBuildParameter<JavaClass, JavaMethod>> methodBuilders = new HashSet<>();
    for (Method method : inputClass.getDeclaredMethods()) {
        methodBuilders.add(new DomainBuilders.JavaMethodBuilder()
                .withReturnType(JavaType.From.name(method.getReturnType().getName()))
                .withParameters(typesFrom(method.getParameterTypes()))
                .withName(method.getName())
                .withDescriptor(Type.getMethodDescriptor(method))
                .withAnnotations(javaAnnotationBuildersFrom(method.getAnnotations(), inputClass, importedClasses))
                .withModifiers(JavaModifier.getModifiersForMethod(method.getModifiers()))
                .withThrowsClause(typesFrom(method.getExceptionTypes())));
    }
    return methodBuilders;
}
 
Example #20
Source File: GivenClassShouldTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("noClass_should_haveModifier_public_rules")
public void noClass_should_haveModifier_public(ArchRule satisfiedRule, ArchRule unsatisfiedRule) {
    assertThatRules(satisfiedRule, unsatisfiedRule, PublicClass.class, Object.class)
            .haveSuccessfulRuleText("no class %s should not have modifier %s",
                    PublicClass.class.getName(), PUBLIC)
            .haveFailingRuleText("no class %s should have modifier %s",
                    PublicClass.class.getName(), PUBLIC)
            .containFailureDetail(String.format("Class <%s> has modifier %s in %s",
                    quote(PublicClass.class.getName()),
                    quote(JavaModifier.PUBLIC.name()),
                    locationPattern(GivenClassShouldTest.class)))
            .doNotContainFailureDetail(quote(Object.class.getName()));
}
 
Example #21
Source File: JavaClassProcessor.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
    if (importAborted()) {
        return super.visitField(access, name, desc, signature, value);
    }

    DomainBuilders.JavaFieldBuilder fieldBuilder = new DomainBuilders.JavaFieldBuilder()
            .withName(name)
            .withType(JavaTypeImporter.importAsmType(desc))
            .withModifiers(JavaModifier.getModifiersForField(access))
            .withDescriptor(desc);
    declarationHandler.onDeclaredField(fieldBuilder);
    return new FieldProcessor(fieldBuilder);
}
 
Example #22
Source File: GivenClassShouldTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("noClass_should_beProtected_rules")
public void noClass_should_beProtected(ArchRule satisfiedRule, ArchRule unsatisfiedRule) {
    assertThatRules(satisfiedRule, unsatisfiedRule, ProtectedClass.class, Object.class)
            .haveSuccessfulRuleText("no class %s should not be protected",
                    ProtectedClass.class.getName())
            .haveFailingRuleText("no class %s should be protected",
                    ProtectedClass.class.getName())
            .containFailureDetail(String.format("Class <%s> has modifier %s in %s",
                    quote(ProtectedClass.class.getName()),
                    quote(JavaModifier.PROTECTED.name()),
                    locationPattern(GivenClassShouldTest.class)))
            .doNotContainFailureDetail(quote(Object.class.getName()));
}
 
Example #23
Source File: GivenClassShouldTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("noClass_should_bePrivate_rules")
public void noClass_should_bePrivate(ArchRule satisfiedRule, ArchRule unsatisfiedRule) {
    assertThatRules(satisfiedRule, unsatisfiedRule, PrivateClass.class, Object.class)
            .haveSuccessfulRuleText("no class %s should not be private",
                    PrivateClass.class.getName())
            .haveFailingRuleText("no class %s should be private",
                    PrivateClass.class.getName())
            .containFailureDetail(String.format("Class <%s> has modifier %s in %s",
                    quote(PrivateClass.class.getName()),
                    quote(JavaModifier.PRIVATE.name()),
                    locationPattern(GivenClassShouldTest.class)))
            .doNotContainFailureDetail(quote(Object.class.getName()));
}
 
Example #24
Source File: GivenClassShouldTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("theClass_should_bePrivate_rules")
public void theClass_should_bePrivate(ArchRule satisfiedRule, ArchRule unsatisfiedRule) {
    assertThatRules(satisfiedRule, unsatisfiedRule, PrivateClass.class, Object.class)
            .haveSuccessfulRuleText("the class %s should be private",
                    PrivateClass.class.getName())
            .haveFailingRuleText("the class %s should not be private",
                    PrivateClass.class.getName())
            .containFailureDetail(String.format("Class <%s> has modifier %s in %s",
                    quote(PrivateClass.class.getName()),
                    quote(JavaModifier.PRIVATE.name()),
                    locationPattern(GivenClassShouldTest.class)))
            .doNotContainFailureDetail(quote(Object.class.getName()));
}
 
Example #25
Source File: GivenClassShouldTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("noClass_should_bePublic_rules")
public void noClass_should_bePublic(ArchRule satisfiedRule, ArchRule unsatisfiedRule) {
    assertThatRules(satisfiedRule, unsatisfiedRule, SomeClass.class, Object.class)
            .haveSuccessfulRuleText("no class %s should not be public",
                    SomeClass.class.getName())
            .haveFailingRuleText("no class %s should be public",
                    SomeClass.class.getName())
            .containFailureDetail(String.format("Class <%s> has modifier %s in %s",
                    quote(SomeClass.class.getName()),
                    quote(JavaModifier.PUBLIC.name()),
                    locationPattern(SomeClass.class)))
            .doNotContainFailureDetail(quote(Object.class.getName()));
}
 
Example #26
Source File: GivenClassShouldTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("theClass_should_bePublic_rules")
public void theClass_should_bePublic(ArchRule satisfiedRule, ArchRule unsatisfiedRule) {
    assertThatRules(satisfiedRule, unsatisfiedRule, SomeClass.class, Object.class)
            .haveSuccessfulRuleText("the class %s should be public",
                    SomeClass.class.getName())
            .haveFailingRuleText("the class %s should not be public",
                    SomeClass.class.getName())
            .containFailureDetail(String.format("Class <%s> has modifier %s in %s",
                    quote(SomeClass.class.getName()),
                    quote(JavaModifier.PUBLIC.name()),
                    locationPattern(SomeClass.class)))
            .doNotContainFailureDetail(quote(Object.class.getName()));
}
 
Example #27
Source File: ClassesShouldTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("modifiers_rules")
public void modifiers(ArchRule rule, String havePrefix, JavaModifier modifier,
        Class<?> satisfied, Class<?> violated) {
    EvaluationResult result = rule.evaluate(importClasses(satisfied, violated));

    assertThat(singleLineFailureReportOf(result))
            .contains(String.format("classes should %shave modifier %s", havePrefix, modifier.name()))
            .containsPattern(String.format("Class <%s> .* modifier %s in %s",
                    quote(violated.getName()), modifier, locationPattern(getClass()))) // -> location == enclosingClass()
            .doesNotMatch(String.format(".*<%s>.* modifier %s.*", quote(satisfied.getName()), modifier));
}
 
Example #28
Source File: ClassesShouldTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("not_visibility_rules")
public void notVisibility(ArchRule rule, JavaModifier modifier,
        Class<?> satisfied, Class<?> violated) {
    EvaluationResult result = rule.evaluate(importClasses(satisfied, violated));

    assertThat(singleLineFailureReportOf(result))
            .contains(String.format("classes should not be %s", modifier.name().toLowerCase()))
            .containsPattern(String.format("Class <%s> .* modifier %s", quote(violated.getName()), modifier))
            .doesNotMatch(String.format(".*<%s>.* modifier %s.*", quote(satisfied.getName()), modifier));
}
 
Example #29
Source File: ClassesShouldTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("visibility_rules")
public void visibility(ArchRule rule, JavaModifier modifier,
        Class<?> satisfied, Class<?> violated) {
    EvaluationResult result = rule.evaluate(importClasses(satisfied, violated));

    assertThat(singleLineFailureReportOf(result))
            .contains(String.format("classes should be %s", modifier.name().toLowerCase()))
            .containsPattern(String.format("Class <%s> .* modifier %s", quote(violated.getName()), modifier))
            .doesNotMatch(String.format(".*<%s>.* modifier %s.*", quote(satisfied.getName()), modifier));
}
 
Example #30
Source File: DomainBuilders.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
JavaStaticInitializerBuilder() {
    withReturnType(JavaType.From.name(void.class.getName()));
    withParameters(Collections.<JavaType>emptyList());
    withName(JavaStaticInitializer.STATIC_INITIALIZER_NAME);
    withDescriptor("()V");
    withAnnotations(Collections.<JavaAnnotationBuilder>emptySet());
    withModifiers(Collections.<JavaModifier>emptySet());
    withThrowsClause(Collections.<JavaType>emptyList());
}