com.tngtech.archunit.lang.ConditionEvents Java Examples

The following examples show how to use com.tngtech.archunit.lang.ConditionEvents. 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: 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 #2
Source File: PlantUmlArchCondition.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Override
public void check(JavaClass item, ConditionEvents events) {
    if (allDependenciesAreIgnored(item)) {
        return;
    }

    String[] allAllowedTargets = FluentIterable
            .from(javaClassDiagramAssociation.getPackageIdentifiersFromComponentOf(item))
            .append(javaClassDiagramAssociation.getTargetPackageIdentifiers(item))
            .toArray(String.class);

    ArchCondition<JavaClass> delegate = onlyHaveDependenciesInAnyPackage(allAllowedTargets)
            .ignoreDependency(ignorePredicate);

    delegate.check(item, events);
}
 
Example #3
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 #4
Source File: PublicAPIRules.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
private static ArchCondition<? super JavaCodeUnit> haveContravariantPredicateParameterTypes() {
    return new ArchCondition<JavaCodeUnit>("have contravariant predicate parameter types") {
        @Override
        public void check(JavaCodeUnit javaCodeUnit, ConditionEvents events) {
            Type[] parameterTypes = javaCodeUnit.isConstructor()
                    ? ((JavaConstructor) javaCodeUnit).reflect().getGenericParameterTypes()
                    : ((JavaMethod) javaCodeUnit).reflect().getGenericParameterTypes();

            stream(parameterTypes)
                    .filter(type -> type instanceof ParameterizedType)
                    .map(type -> (ParameterizedType) type)
                    .filter(type -> type.getRawType().equals(DescribedPredicate.class))
                    .map(predicateType -> predicateType.getActualTypeArguments()[0])
                    .filter(predicateTypeParameter -> !(predicateTypeParameter instanceof WildcardType)
                            || ((WildcardType) predicateTypeParameter).getLowerBounds().length == 0)
                    .forEach(type -> {
                        String message = String.format("%s has a parameter %s<%s> instead of a contravariant type parameter in %s",
                                javaCodeUnit.getDescription(), DescribedPredicate.class.getSimpleName(), type.getTypeName(), javaCodeUnit.getSourceCodeLocation());
                        events.add(violated(javaCodeUnit, message));
                    });
        }
    };
}
 
Example #5
Source File: ApplicationComponentsTest.java    From archunit-examples with MIT License 6 votes vote down vote up
@Override
public void check(JavaClass clazz, ConditionEvents events) {
  Set<JavaMethod> methods = clazz.getMethods();
  Predicate<JavaMethod> hasMethodNamedInvoke = method -> method.getName().equals("invoke");
  if (methods.stream().filter(hasMethodNamedInvoke).count() != 1) {
    events.add(SimpleConditionEvent.violated(clazz, "${clazz.simpleName} does not have a single 'invoke' method"));
    return;
  }
  methods.stream().filter(hasMethodNamedInvoke).findFirst().ifPresent(invokeMethod -> {
    JavaClassList parameters = invokeMethod.getRawParameterTypes();
    if (parameters.size() != 1 || parameters.stream().noneMatch(it -> it.isInnerClass() && it.getSimpleName().equals("Request"))) {
      events.add(SimpleConditionEvent.violated(invokeMethod, "${clazz.simpleName}: method 'invoke' does not have a single parameter that is named 'request' and of inner-class type 'Request'"));
    }
    JavaClass returnType = invokeMethod.getRawReturnType();
    if (!returnType.isInnerClass() || !returnType.getSimpleName().equals("Response")) {
      events.add(SimpleConditionEvent.violated(invokeMethod, "${clazz.simpleName}: method 'invoke' does not have a return type that is of inner-class type 'Response'"));
    }
  });
}
 
Example #6
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void check(JavaClass javaClass, ConditionEvents events) {
    boolean satisfied = predicate.apply(javaClass);
    String message = String.format("simple name of %s %s '%s' in %s",
            javaClass.getName(),
            satisfied ? "contains" : "does not contain",
            infix,
            javaClass.getSourceCodeLocation());
    events.add(new SimpleConditionEvent(javaClass, satisfied, message));
}
 
Example #7
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void check(JavaClass javaClass, ConditionEvents events) {
    boolean satisfied = predicate.apply(javaClass);
    String message = String.format("simple name of %s %s with '%s' in %s",
            javaClass.getName(),
            satisfied ? "ends" : "does not end",
            suffix,
            javaClass.getSourceCodeLocation());
    events.add(new SimpleConditionEvent(javaClass, satisfied, message));
}
 
Example #8
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void check(T item, ConditionEvents events) {
    boolean satisfied = matcher.apply(item);
    String message = createMessage(item,
            String.format("%s '%s'", satisfied ? "matches" : "does not match", regex));
    events.add(new SimpleConditionEvent(item, satisfied, message));
}
 
Example #9
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void check(T item, ConditionEvents events) {
    boolean satisfied = startingWith.apply(item);
    String message = createMessage(item,
            String.format("name %s '%s'", satisfied ? "starts with" : "does not start with", prefix));
    events.add(new SimpleConditionEvent(item, satisfied, message));
}
 
Example #10
Source File: DependencyRules.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void check(final JavaClass clazz, final ConditionEvents events) {
    for (Dependency dependency : clazz.getDirectDependenciesFromSelf()) {
        boolean dependencyOnUpperPackage = isDependencyOnUpperPackage(dependency.getOriginClass(), dependency.getTargetClass());
        events.add(new SimpleConditionEvent(dependency, dependencyOnUpperPackage, dependency.getDescription()));
    }
}
 
Example #11
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void check(T item, ConditionEvents events) {
    boolean satisfied = containing.apply(item);
    String message = createMessage(item,
            String.format("name %s '%s'", satisfied ? "contains" : "does not contain", infix));
    events.add(new SimpleConditionEvent(item, satisfied, message));
}
 
Example #12
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void check(T item, ConditionEvents events) {
    boolean satisfied = endingWith.apply(item);
    String message = createMessage(item,
            String.format("name %s '%s'", satisfied ? "ends with" : "does not end with", suffix));
    events.add(new SimpleConditionEvent(item, satisfied, message));
}
 
Example #13
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void check(JavaClass javaClass, ConditionEvents events) {
    boolean satisfied = predicate.apply(javaClass);
    String message = String.format("simple name of %s %s with '%s' in %s",
            javaClass.getName(),
            satisfied ? "starts" : "does not start",
            prefix,
            javaClass.getSourceCodeLocation());
    events.add(new SimpleConditionEvent(javaClass, satisfied, message));
}
 
Example #14
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void check(T item, ConditionEvents events) {
    boolean satisfied = predicate.apply(item);
    String message = createMessage(item,
            (satisfied ? "does " : "does not ") + predicate.getDescription());
    events.add(new SimpleConditionEvent(item, satisfied, message));
}
 
Example #15
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void check(T member, ConditionEvents events) {
    boolean satisfied = predicate.apply(member);
    String message = createMessage(member,
            (satisfied ? "is " : "is not ") + eventDescription);
    events.add(new SimpleConditionEvent(member, satisfied, message));
}
 
Example #16
Source File: ContainsOnlyConditionTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
static ConditionEvents getInverted(ConditionEvents events) {
    ConditionEvents inverted = new ConditionEvents();
    for (ConditionEvent event : events) {
        event.addInvertedTo(inverted);
    }
    return inverted;
}
 
Example #17
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void check(JavaClass javaClass, ConditionEvents events) {
    boolean itemEquivalentToClazz = javaClass.getName().equals(className);
    String message = createMessage(javaClass,
            (itemEquivalentToClazz ? "is " : "is not ") + className);
    events.add(new SimpleConditionEvent(javaClass, itemEquivalentToClazz, message));
}
 
Example #18
Source File: ContainsOnlyConditionTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void inverting_works() throws Exception {
    ConditionEvents events = new ConditionEvents();
    containOnlyElementsThat(IS_SERIALIZABLE).check(TWO_SERIALIZABLE_OBJECTS, events);

    assertThat(events).containNoViolation();
    assertThat(events.getAllowed()).as("Exactly one allowed event occurred").hasSize(1);

    assertThat(getInverted(events)).containViolations(messageForTwoTimes(isSerializableMessageFor(SerializableObject.class)));
}
 
Example #19
Source File: ArchConditions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void check(JavaClass javaClass, ConditionEvents events) {
    boolean satisfied = haveSimpleName.apply(javaClass);
    String message = createMessage(javaClass,
            String.format("%s simple name '%s'", satisfied ? "has" : "does not have", name));
    events.add(new SimpleConditionEvent(javaClass, satisfied, message));
}
 
Example #20
Source File: SliceCycleArchCondition.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void finish(ConditionEvents events) {
    Graph.Cycles<Slice, Dependency> cycles = graph.findCycles();
    if (cycles.maxNumberOfCyclesReached()) {
        events.setInformationAboutNumberOfViolations(String.format(
                " >= %d times - the maximum number of cycles to detect has been reached; "
                        + "this limit can be adapted using the `archunit.properties` value `%s=xxx`",
                cycles.size(), MAX_NUMBER_OF_CYCLES_TO_DETECT_PROPERTY_NAME));
    }
    for (Cycle<Slice, Dependency> cycle : cycles) {
        eventRecorder.record(cycle, events);
    }
    releaseResources();
}
 
Example #21
Source File: FieldAccessConditionTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private void assertViolatedWithMessage(FieldAccessCondition getFieldCondition, JavaFieldAccess access,
        String accessDescription) {
    ConditionEvents events = checkCondition(getFieldCondition, access);
    boolean satisfied = !events.containViolation();

    assertThat(satisfied).as("Events are satisfied").isFalse();
    assertThat(events.getAllowed()).isEmpty();
    assertDescription(access, accessDescription, messageOf(events.getViolating()));
}
 
Example #22
Source File: GivenSlicesInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public void check(Slice slice, ConditionEvents events) {
    Iterable<Dependency> relevantDependencies = filter(slice.getDependenciesFromSelf(), predicate);
    Slices dependencySlices = inputTransformer.transform(relevantDependencies);
    for (Slice dependencySlice : dependencySlices) {
        SliceDependency dependency = SliceDependency.of(slice, relevantDependencies, dependencySlice);
        events.add(SimpleConditionEvent.violated(dependency, dependency.getDescription()));
    }
}
 
Example #23
Source File: FreezingArchRuleTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private ArchRule createArchRuleWithViolations(final Collection<ViolatedEvent> violatedEvents) {
    return classes().should(new ArchCondition<JavaClass>("") {
        @Override
        public void check(JavaClass javaClass, ConditionEvents events) {
            for (ViolatedEvent event : violatedEvents) {
                events.add(event);
            }
        }
    }).as(description);
}
 
Example #24
Source File: ClassAccessesFieldConditionTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Theory
public void condition_works(NegativeTestCase testCase) {
    ConditionEvents events = new ConditionEvents();

    testCase.condition.check(CALLER_CLASS, events);

    assertThat(events).haveOneViolationMessageContaining(testCase.violationMessageParts());
}
 
Example #25
Source File: JavaAccessConditionTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private ConditionEventsAssertion assertThatOnlyAccessToSomeClassFor(JavaClass clazz, JavaAccessCondition<JavaAccess<?>> condition) {
    Set<JavaAccess<?>> accesses = filterByTarget(clazz.getAccessesFromSelf(), SomeClass.class);
    ConditionEvents events = new ConditionEvents();
    for (JavaAccess<?> access : accesses) {
        condition.check(access, events);
    }
    return assertThat(events);
}
 
Example #26
Source File: ClassCallsCodeUnitConditionTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void call_with_correct_name_and_params_matches() {
    ConditionEvents events = checkCondition(
            callMethodWhere(target(name(TargetClass.appendStringMethod))
                    .and(target(rawParameterTypes(TargetClass.appendStringParams)))
                    .and(target(owner(type(TargetClass.class))))));

    assertThat(events).containNoViolation();
}
 
Example #27
Source File: ClassCallsCodeUnitConditionTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void call_without_argument_doesnt_match() {
    ConditionEvents events = checkCondition(callMethodWhere(
            target(rawParameterTypes(new Class[0]))
                    .and(target(name(TargetClass.appendStringMethod))
                            .and(target(owner(type(TargetClass.class)))))));

    assertThat(events).haveOneViolationMessageContaining(VIOLATION_MESSAGE_PARTS);
}
 
Example #28
Source File: ClassCallsCodeUnitConditionTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void call_with_wrong_method_name_doesnt_match() {
    ConditionEvents events = checkCondition(
            callMethodWhere(target(name("wrong"))
                    .and(target(rawParameterTypes(TargetClass.appendStringParams)))
                    .and(target(owner(type(TargetClass.class))))));

    assertThat(events).haveOneViolationMessageContaining(VIOLATION_MESSAGE_PARTS);
}
 
Example #29
Source File: FieldAccessConditionTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private void assertSatisfiedWithMessage(FieldAccessCondition getFieldCondition, JavaFieldAccess access,
        String accessDescription) {
    ConditionEvents events = checkCondition(getFieldCondition, access);
    boolean satisfied = !events.containViolation();

    assertThat(satisfied).as("Events are satisfied").isTrue();
    assertThat(events.getViolating()).isEmpty();
    assertDescription(access, accessDescription, messageOf(events.getAllowed()));
}
 
Example #30
Source File: ContainAnyConditionTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void inverting_works() throws Exception {
    ConditionEvents events = new ConditionEvents();
    containAnyElementThat(IS_SERIALIZABLE).check(ONE_SERIALIZABLE_AND_ONE_NON_SERIALIZABLE_OBJECT, events);

    assertThat(events).containNoViolation();
    assertThat(events.getAllowed()).as("Exactly one allowed event occurred").hasSize(1);

    assertThat(getInverted(events)).containViolations(isSerializableMessageFor(SerializableObject.class));
}