Skip to content

Commit

Permalink
Add support to test caught exceptions
Browse files Browse the repository at this point in the history
This will add `TryCatchBlocks` to the ArchUnit core and introduce `JavaCodeUnit.getTryCatchBlocks()` to examine try-catch blocks that have been parsed from the bytecode of a method or constructor. We also add an extension `JavaAccess.getContainingTryBlocks()` to make it easy to verify that certain accesses in code are wrapped into certain try-catch blocks (e.g. "whenever method x is called there should be a try-catch block to handle exception case y").

Signed-off-by: Krzysztof Sierszeń <krzysztof.sierszen@digitalnewagency.com>
Signed-off-by: Peter Gafert <peter.gafert@tngtech.com>
  • Loading branch information
crizzis authored and codecholeric committed May 29, 2022
1 parent 88e7ec5 commit e0e0c65
Show file tree
Hide file tree
Showing 26 changed files with 1,078 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import com.tngtech.archunit.core.importer.DomainBuilders.JavaMethodReferenceBuilder;
import com.tngtech.archunit.core.importer.DomainBuilders.JavaStaticInitializerBuilder;
import com.tngtech.archunit.core.importer.DomainBuilders.JavaWildcardTypeBuilder;
import com.tngtech.archunit.core.importer.DomainBuilders.TryCatchBlockBuilder;

import static com.google.common.base.Preconditions.checkArgument;

Expand Down Expand Up @@ -107,6 +108,10 @@ public static JavaField createJavaField(JavaFieldBuilder builder) {
return new JavaField(builder);
}

public static TryCatchBlock createTryCatchBlock(TryCatchBlockBuilder builder) {
return new TryCatchBlock(builder);
}

public static JavaFieldAccess createJavaFieldAccess(JavaFieldAccessBuilder builder) {
return new JavaFieldAccess(builder);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.Set;

import com.tngtech.archunit.Internal;
import com.tngtech.archunit.core.importer.DomainBuilders.TryCatchBlockBuilder;

@Internal
public interface ImportContext {
Expand Down Expand Up @@ -50,15 +51,17 @@ public interface ImportContext {

Optional<JavaCodeUnit> createEnclosingCodeUnit(JavaClass owner);

Set<JavaFieldAccess> createFieldAccessesFor(JavaCodeUnit codeUnit);
Set<JavaFieldAccess> createFieldAccessesFor(JavaCodeUnit codeUnit, Set<TryCatchBlockBuilder> tryCatchBlockBuilders);

Set<JavaMethodCall> createMethodCallsFor(JavaCodeUnit codeUnit);
Set<JavaMethodCall> createMethodCallsFor(JavaCodeUnit codeUnit, Set<TryCatchBlockBuilder> tryCatchBlockBuilders);

Set<JavaConstructorCall> createConstructorCallsFor(JavaCodeUnit codeUnit);
Set<JavaConstructorCall> createConstructorCallsFor(JavaCodeUnit codeUnit, Set<TryCatchBlockBuilder> tryCatchBlockBuilders);

Set<JavaMethodReference> createMethodReferencesFor(JavaCodeUnit codeUnit);
Set<JavaMethodReference> createMethodReferencesFor(JavaCodeUnit codeUnit, Set<TryCatchBlockBuilder> tryCatchBlockBuilders);

Set<JavaConstructorReference> createConstructorReferencesFor(JavaCodeUnit codeUnit);
Set<JavaConstructorReference> createConstructorReferencesFor(JavaCodeUnit codeUnit, Set<TryCatchBlockBuilder> tryCatchBlockBuilders);

Set<TryCatchBlockBuilder> createTryCatchBlockBuilders(JavaCodeUnit codeUnit);

JavaClass resolveClass(String fullyQualifiedClassName);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package com.tngtech.archunit.core.domain;

import java.util.Objects;
import java.util.Set;

import com.tngtech.archunit.PublicAPI;
import com.tngtech.archunit.base.ChainableFunction;
Expand All @@ -28,6 +29,7 @@
import com.tngtech.archunit.core.importer.DomainBuilders;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.tngtech.archunit.PublicAPI.Usage.ACCESS;

public abstract class JavaAccess<TARGET extends AccessTarget>
Expand Down Expand Up @@ -128,6 +130,16 @@ public String getDescription() {

protected abstract String descriptionVerb();

/**
* @return All try-catch-blocks where this {@link JavaAccess} is contained within the try-part the try-catch-block
*/
@PublicAPI(usage = ACCESS)
public Set<TryCatchBlock> getContainingTryBlocks() {
return getOrigin().getTryCatchBlocks().stream()
.filter(block -> block.getAccessesContainedInTryBlock().contains(this))
.collect(toImmutableSet());
}

public static final class Predicates {
private Predicates() {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@
import com.tngtech.archunit.core.domain.properties.HasThrowsClause;
import com.tngtech.archunit.core.domain.properties.HasTypeParameters;
import com.tngtech.archunit.core.importer.DomainBuilders.JavaCodeUnitBuilder;
import com.tngtech.archunit.core.importer.DomainBuilders.TryCatchBlockBuilder;

import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Sets.union;
import static com.tngtech.archunit.PublicAPI.Usage.ACCESS;
import static com.tngtech.archunit.core.domain.Formatters.formatMethod;
Expand Down Expand Up @@ -66,6 +68,7 @@ public abstract class JavaCodeUnit
private Set<JavaConstructorCall> constructorCalls = Collections.emptySet();
private Set<JavaMethodReference> methodReferences = Collections.emptySet();
private Set<JavaConstructorReference> constructorReferences = Collections.emptySet();
private Set<TryCatchBlock> tryCatchBlocks = Collections.emptySet();

JavaCodeUnit(JavaCodeUnitBuilder<?, ?> builder) {
super(builder);
Expand Down Expand Up @@ -203,6 +206,11 @@ public Set<InstanceofCheck> getInstanceofChecks() {
return instanceofChecks;
}

@PublicAPI(usage = ACCESS)
public Set<TryCatchBlock> getTryCatchBlocks() {
return tryCatchBlocks;
}

@PublicAPI(usage = ACCESS)
public Set<JavaCall<?>> getCallsFromSelf() {
return union(getMethodCallsFromSelf(), getConstructorCallsFromSelf());
Expand Down Expand Up @@ -261,11 +269,15 @@ public List<Set<JavaAnnotation<JavaParameter>>> getParameterAnnotations() {
}

void completeAccessesFrom(ImportContext context) {
fieldAccesses = context.createFieldAccessesFor(this);
methodCalls = context.createMethodCallsFor(this);
constructorCalls = context.createConstructorCallsFor(this);
methodReferences = context.createMethodReferencesFor(this);
constructorReferences = context.createConstructorReferencesFor(this);
Set<TryCatchBlockBuilder> tryCatchBlockBuilders = context.createTryCatchBlockBuilders(this);
fieldAccesses = context.createFieldAccessesFor(this, tryCatchBlockBuilders);
methodCalls = context.createMethodCallsFor(this, tryCatchBlockBuilders);
constructorCalls = context.createConstructorCallsFor(this, tryCatchBlockBuilders);
methodReferences = context.createMethodReferencesFor(this, tryCatchBlockBuilders);
constructorReferences = context.createConstructorReferencesFor(this, tryCatchBlockBuilders);
tryCatchBlocks = tryCatchBlockBuilders.stream()
.map(builder -> builder.build(this, context))
.collect(toImmutableSet());
}

@ResolvesTypesViaReflection
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* Copyright 2014-2022 TNG Technology Consulting GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tngtech.archunit.core.domain;

import java.util.Set;

import com.google.common.collect.ImmutableSet;
import com.tngtech.archunit.PublicAPI;
import com.tngtech.archunit.core.domain.properties.HasOwner;
import com.tngtech.archunit.core.domain.properties.HasSourceCodeLocation;
import com.tngtech.archunit.core.importer.DomainBuilders.TryCatchBlockBuilder;

import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.tngtech.archunit.PublicAPI.Usage.ACCESS;
import static com.tngtech.archunit.core.domain.properties.HasName.Utils.namesOf;

@PublicAPI(usage = ACCESS)
public final class TryCatchBlock implements HasOwner<JavaCodeUnit>, HasSourceCodeLocation {
private final JavaCodeUnit owner;
private final Set<JavaClass> caughtThrowables;
private final SourceCodeLocation sourceCodeLocation;
private final Set<JavaAccess<?>> accessesContainedInTryBlock;

TryCatchBlock(TryCatchBlockBuilder builder) {
this.owner = checkNotNull(builder.getOwner());
this.caughtThrowables = ImmutableSet.copyOf(builder.getCaughtThrowables());
this.sourceCodeLocation = checkNotNull(builder.getSourceCodeLocation());
this.accessesContainedInTryBlock = ImmutableSet.copyOf(builder.getAccessesContainedInTryBlock());
}

@Override
@PublicAPI(usage = ACCESS)
public JavaCodeUnit getOwner() {
return owner;
}

@PublicAPI(usage = ACCESS)
public Set<JavaClass> getCaughtThrowables() {
return caughtThrowables;
}

@Override
@PublicAPI(usage = ACCESS)
public SourceCodeLocation getSourceCodeLocation() {
return sourceCodeLocation;
}

@PublicAPI(usage = ACCESS)
public Set<JavaAccess<?>> getAccessesContainedInTryBlock() {
return accessesContainedInTryBlock;
}

@Override
public String toString() {
return toStringHelper(this)
.add("owner", owner.getFullName())
.add("caughtThrowables", namesOf(caughtThrowables))
.add("location", sourceCodeLocation)
.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ interface AccessRecord<TARGET extends AccessTarget> {

int getLineNumber();

RawAccessRecord getRaw();

@Internal
interface FieldAccessRecord extends AccessRecord<FieldAccessTarget> {
AccessType getAccessType();
Expand Down Expand Up @@ -260,6 +262,11 @@ public TARGET getTarget() {
public int getLineNumber() {
return record.lineNumber;
}

@Override
public RawAccessRecord getRaw() {
return record;
}
}

private static class RawFieldAccessRecordProcessed extends RawAccessRecordProcessed<FieldAccessTarget> implements FieldAccessRecord {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import com.google.common.collect.ListMultimap;
import com.google.common.collect.SetMultimap;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.domain.JavaCodeUnit;
import com.tngtech.archunit.core.domain.JavaMember;
import com.tngtech.archunit.core.domain.JavaMethod;
import com.tngtech.archunit.core.importer.DomainBuilders.JavaAnnotationBuilder;
Expand All @@ -43,6 +44,7 @@
import com.tngtech.archunit.core.importer.DomainBuilders.JavaParameterizedTypeBuilder;
import com.tngtech.archunit.core.importer.DomainBuilders.JavaStaticInitializerBuilder;
import com.tngtech.archunit.core.importer.DomainBuilders.JavaTypeParameterBuilder;
import com.tngtech.archunit.core.importer.DomainBuilders.TryCatchBlockBuilder;
import com.tngtech.archunit.core.importer.RawAccessRecord.CodeUnit;

import static com.google.common.base.Preconditions.checkArgument;
Expand All @@ -66,6 +68,7 @@ class ClassFileImportRecord {
private final SetMultimap<String, JavaAnnotationBuilder> annotationsByOwner = HashMultimap.create();
private final Map<String, JavaAnnotationBuilder.ValueBuilder> annotationDefaultValuesByOwner = new HashMap<>();
private final EnclosingDeclarationsByInnerClasses enclosingDeclarationsByOwner = new EnclosingDeclarationsByInnerClasses();
private final SetMultimap<String, TryCatchBlockBuilder> tryCatchBlocksByOwner = HashMultimap.create();

private final Set<RawAccessRecord.ForField> rawFieldAccessRecords = new HashSet<>();
private final Set<RawAccessRecord> rawMethodCallRecords = new HashSet<>();
Expand Down Expand Up @@ -135,6 +138,10 @@ void setEnclosingCodeUnit(String ownerName, CodeUnit enclosingCodeUnit) {
enclosingDeclarationsByOwner.registerEnclosingCodeUnit(ownerName, enclosingCodeUnit);
}

void addTryCatchBlocks(String declaringClassName, String methodName, String descriptor, Set<TryCatchBlockBuilder> tryCatchBlocks) {
tryCatchBlocksByOwner.putAll(getMemberKey(declaringClassName, methodName, descriptor), tryCatchBlocks);
}

Optional<String> getSuperclassFor(String name) {
return Optional.ofNullable(superclassNamesByOwner.get(name));
}
Expand Down Expand Up @@ -238,6 +245,10 @@ Optional<CodeUnit> getEnclosingCodeUnitFor(String ownerName) {
return enclosingDeclarationsByOwner.getEnclosingCodeUnit(ownerName);
}

Set<TryCatchBlockBuilder> getTryCatchBlockBuildersFor(JavaCodeUnit codeUnit) {
return tryCatchBlocksByOwner.get(getMemberKey(codeUnit));
}

void registerFieldAccess(RawAccessRecord.ForField record) {
rawFieldAccessRecords.add(record);
}
Expand Down
Loading

0 comments on commit e0e0c65

Please sign in to comment.