diff --git a/docs/mutation-framework.md b/docs/mutation-framework.md index 7fc323533..6ddb601be 100644 --- a/docs/mutation-framework.md +++ b/docs/mutation-framework.md @@ -104,6 +104,9 @@ package. | `@WithUtf8Length` | `java.lang.String` | Specifies the length of the generated string in UTF-8 bytes, see annotation Javadoc for further information | | `@WithSize` | `java.util.List`, `java.util.Map` | Specifies the size of the generated collection | | `@UrlSegment` | `java.lang.String` | `String` should only contain valid URL segment characters | +| `@IgnoreProperties` | `@FuzzTest` methods, JavaBeans, or containers | Excludes JavaBean properties by property name (`value`) or assignable type (`types`) from setter-based mutation | +| `@IgnoreGetters` | `@FuzzTest` methods, JavaBeans, or containers | Excludes JavaBean properties whose getter method name matches any entry in `value` | +| `@IgnoreSetters` | `@FuzzTest` methods, JavaBeans, or containers | Excludes JavaBean setter methods whose name matches any entry in `value` | The example below shows how Fuzz Test parameters can be annotated to provide additional information to the mutation framework. @@ -163,7 +166,24 @@ no arguments. The corresponding methods are looked up by name and must adhere to the JavaBeans Spec naming convention, meaning `setXX` and `getXX`/`isXX` methods for property `XX`. A JavaBean can have additional getters corresponding to computed properties, but it is required that all setters have a corresponding -getter. +getter. To exclude properties from setter-based mutation without annotating the +JavaBean class under test (for example, write-only setters or properties with +unsupported types), annotate the `@FuzzTest` method or parameter type with +`@IgnoreProperties`, `@IgnoreGetters`, or `@IgnoreSetters`: + +```java title="Example" showLineNumbers +@IgnoreProperties(value = {"internalId"}, types = {UnsupportedService.class}) +@IgnoreSetters({"setAuditCallback"}) +@FuzzTest +public void testOnboardingBean(@NotNull OnboardingBean onboarding) { + // ... +} +``` + +By default, these annotations use `PropertyConstraint.RECURSIVE`, so rules +(including `types = {UnsupportedService.class}`) apply across nested JavaBeans +and collections. Set `constraint = PropertyConstraint.DECLARATION` on a +parameter type to limit an annotation to that type alone. ```java title="Example" showLineNumbers public static class FooBean { diff --git a/src/main/java/com/code_intelligence/jazzer/mutation/ArgumentsMutator.java b/src/main/java/com/code_intelligence/jazzer/mutation/ArgumentsMutator.java index 014109e0c..69661f8d5 100644 --- a/src/main/java/com/code_intelligence/jazzer/mutation/ArgumentsMutator.java +++ b/src/main/java/com/code_intelligence/jazzer/mutation/ArgumentsMutator.java @@ -23,6 +23,9 @@ import static java.util.Arrays.stream; import static java.util.stream.Collectors.joining; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreGetters; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreProperties; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreSetters; import com.code_intelligence.jazzer.mutation.annotation.ValuePool; import com.code_intelligence.jazzer.mutation.api.ExtendedMutatorFactory; import com.code_intelligence.jazzer.mutation.api.PseudoRandom; @@ -40,10 +43,13 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.UncheckedIOException; +import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.Arrays; import java.util.Optional; +import java.util.stream.Stream; public final class ArgumentsMutator { private final ExtendedMutatorFactory mutatorFactory; @@ -100,18 +106,21 @@ public static Optional forMethod( throw validationError; } - ValuePool[] valuePools = method.getAnnotationsByType(ValuePool.class); + Annotation[] methodAnnotations = + Stream.of( + method.getAnnotationsByType(ValuePool.class), + method.getAnnotationsByType(IgnoreProperties.class), + method.getAnnotationsByType(IgnoreGetters.class), + method.getAnnotationsByType(IgnoreSetters.class)) + .flatMap(Arrays::stream) + .toArray(Annotation[]::new); return toArrayOrEmpty( stream(method.getAnnotatedParameterTypes()) .map( type -> { - // Forward all @ValuePool annotations of the fuzz test method to each - // arg. - AnnotatedType t = type; - for (ValuePool pool : valuePools) { - t = TypeSupport.withExtraAnnotations(t, pool); - } + // Forward method-level annotations of the fuzz test method to each arg. + AnnotatedType t = TypeSupport.withExtraAnnotations(type, methodAnnotations); Optional> mutator = mutatorFactory.tryCreate(t); if (!mutator.isPresent()) { Log.error( diff --git a/src/main/java/com/code_intelligence/jazzer/mutation/annotation/IgnoreGetters.java b/src/main/java/com/code_intelligence/jazzer/mutation/annotation/IgnoreGetters.java new file mode 100644 index 000000000..1094a7a4c --- /dev/null +++ b/src/main/java/com/code_intelligence/jazzer/mutation/annotation/IgnoreGetters.java @@ -0,0 +1,43 @@ +/* + * 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.code_intelligence.jazzer.mutation.annotation; + +import static com.code_intelligence.jazzer.mutation.utils.PropertyConstraint.RECURSIVE; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE_USE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import com.code_intelligence.jazzer.mutation.utils.AppliesTo; +import com.code_intelligence.jazzer.mutation.utils.IgnoreRecursiveConflicts; +import com.code_intelligence.jazzer.mutation.utils.PropertyConstraint; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** Excludes JavaBean properties whose getter method name matches any entry in {@link #value()}. */ +@Target({METHOD, TYPE_USE}) +@Retention(RUNTIME) +@AppliesTo(subClassesOf = Object.class) +@IgnoreRecursiveConflicts +@PropertyConstraint +public @interface IgnoreGetters { + /** Getter method names to ignore (e.g., {@code "getFoo"}, {@code "isBar"}). */ + String[] value(); + + /** + * Defines the scope of the annotation. Possible values are defined in {@link + * com.code_intelligence.jazzer.mutation.utils.PropertyConstraint}. Defaults to {@code RECURSIVE}. + */ + String constraint() default RECURSIVE; +} diff --git a/src/main/java/com/code_intelligence/jazzer/mutation/annotation/IgnoreProperties.java b/src/main/java/com/code_intelligence/jazzer/mutation/annotation/IgnoreProperties.java new file mode 100644 index 000000000..d54060e96 --- /dev/null +++ b/src/main/java/com/code_intelligence/jazzer/mutation/annotation/IgnoreProperties.java @@ -0,0 +1,56 @@ +/* + * 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.code_intelligence.jazzer.mutation.annotation; + +import static com.code_intelligence.jazzer.mutation.utils.PropertyConstraint.RECURSIVE; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE_USE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import com.code_intelligence.jazzer.mutation.utils.AppliesTo; +import com.code_intelligence.jazzer.mutation.utils.IgnoreRecursiveConflicts; +import com.code_intelligence.jazzer.mutation.utils.PropertyConstraint; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Excludes matching JavaBean properties from setter-based bean mutation. + * + *

Can be applied to {@code @FuzzTest} methods or parameter types. By default, rules propagate + * recursively through nested beans and containers ({@link PropertyConstraint#RECURSIVE}). + */ +@Target({METHOD, TYPE_USE}) +@Retention(RUNTIME) +@AppliesTo(subClassesOf = Object.class) +@IgnoreRecursiveConflicts +@PropertyConstraint +public @interface IgnoreProperties { + /** + * JavaBean property names to ignore (e.g., {@code "foo"} matches {@code setFoo}/{@code getFoo}). + */ + String[] value() default {}; + + /** + * Property types to ignore (matches assignable setter parameter types, including generic type + * arguments and array component types). + */ + Class[] types() default {}; + + /** + * Defines the scope of the annotation. Possible values are defined in {@link + * com.code_intelligence.jazzer.mutation.utils.PropertyConstraint}. Defaults to {@code RECURSIVE}. + */ + String constraint() default RECURSIVE; +} diff --git a/src/main/java/com/code_intelligence/jazzer/mutation/annotation/IgnoreSetters.java b/src/main/java/com/code_intelligence/jazzer/mutation/annotation/IgnoreSetters.java new file mode 100644 index 000000000..2775c9337 --- /dev/null +++ b/src/main/java/com/code_intelligence/jazzer/mutation/annotation/IgnoreSetters.java @@ -0,0 +1,43 @@ +/* + * 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.code_intelligence.jazzer.mutation.annotation; + +import static com.code_intelligence.jazzer.mutation.utils.PropertyConstraint.RECURSIVE; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE_USE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import com.code_intelligence.jazzer.mutation.utils.AppliesTo; +import com.code_intelligence.jazzer.mutation.utils.IgnoreRecursiveConflicts; +import com.code_intelligence.jazzer.mutation.utils.PropertyConstraint; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** Excludes JavaBean setter methods whose name matches any entry in {@link #value()}. */ +@Target({METHOD, TYPE_USE}) +@Retention(RUNTIME) +@AppliesTo(subClassesOf = Object.class) +@IgnoreRecursiveConflicts +@PropertyConstraint +public @interface IgnoreSetters { + /** Setter method names to ignore (e.g., {@code "setFoo"}, {@code "withBar"}). */ + String[] value(); + + /** + * Defines the scope of the annotation. Possible values are defined in {@link + * com.code_intelligence.jazzer.mutation.utils.PropertyConstraint}. Defaults to {@code RECURSIVE}. + */ + String constraint() default RECURSIVE; +} diff --git a/src/main/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/BUILD.bazel b/src/main/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/BUILD.bazel index 436b8244c..21ee8b940 100644 --- a/src/main/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/BUILD.bazel +++ b/src/main/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/BUILD.bazel @@ -22,6 +22,7 @@ java_library( }), deps = [ ":aggregates_helper", + "//src/main/java/com/code_intelligence/jazzer/mutation/annotation", "//src/main/java/com/code_intelligence/jazzer/mutation/api", "//src/main/java/com/code_intelligence/jazzer/mutation/combinator", "//src/main/java/com/code_intelligence/jazzer/mutation/support", diff --git a/src/main/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/BeanSupport.java b/src/main/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/BeanSupport.java index 42882f2cc..c93efd745 100644 --- a/src/main/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/BeanSupport.java +++ b/src/main/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/BeanSupport.java @@ -119,11 +119,14 @@ static Optional> findDefaultConstructor(Class clazz) { } } + static Map findGettersByPropertyName(Class clazz) { + return findMethods(clazz, BeanSupport::isGetter) + .collect(toMap(BeanSupport::toPropertyName, method -> method, (a, b) -> a)); + } + static Optional findGettersByPropertyNames( Class clazz, Stream propertyNames) { - Map gettersByPropertyName = - findMethods(clazz, BeanSupport::isGetter) - .collect(toMap(BeanSupport::toPropertyName, method -> method, (a, b) -> a)); + Map gettersByPropertyName = findGettersByPropertyName(clazz); return toArrayOrEmpty( propertyNames.map(gettersByPropertyName::get).map(Optional::ofNullable), Method[]::new); } diff --git a/src/main/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/SetterBasedBeanMutatorFactory.java b/src/main/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/SetterBasedBeanMutatorFactory.java index 1c71ee746..139e0de33 100644 --- a/src/main/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/SetterBasedBeanMutatorFactory.java +++ b/src/main/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/SetterBasedBeanMutatorFactory.java @@ -19,49 +19,130 @@ import static com.code_intelligence.jazzer.mutation.mutator.aggregate.BeanSupport.*; import static com.code_intelligence.jazzer.mutation.support.TypeSupport.asSubclassOrEmpty; import static java.util.Arrays.stream; +import static java.util.stream.Collectors.toSet; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreGetters; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreProperties; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreSetters; import com.code_intelligence.jazzer.mutation.api.ExtendedMutatorFactory; import com.code_intelligence.jazzer.mutation.api.MutatorFactory; import com.code_intelligence.jazzer.mutation.api.SerializingMutator; +import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedType; +import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; +import java.lang.reflect.WildcardType; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.Set; +import java.util.function.Function; final class SetterBasedBeanMutatorFactory implements MutatorFactory { @Override public Optional> tryCreate( AnnotatedType type, ExtendedMutatorFactory factory) { + Set ignoredProperties = + extractIgnoredValues(type, IgnoreProperties.class, IgnoreProperties::value); + Set> ignoredTypes = + extractIgnoredValues(type, IgnoreProperties.class, IgnoreProperties::types); + Set ignoredGetters = + extractIgnoredValues(type, IgnoreGetters.class, IgnoreGetters::value); + Set ignoredSetters = + extractIgnoredValues(type, IgnoreSetters.class, IgnoreSetters::value); + return asSubclassOrEmpty(type, Object.class) .filter(BeanSupport::isConcreteClass) .flatMap(BeanSupport::findDefaultConstructor) .flatMap( constructor -> { Class clazz = constructor.getDeclaringClass(); - Method[] setters = findMethods(clazz, BeanSupport::isSetter).toArray(Method[]::new); + Map gettersByPropertyName = findGettersByPropertyName(clazz); + List setters = new ArrayList<>(); + List getters = new ArrayList<>(); + for (Method setter : + findMethods(clazz, BeanSupport::isSetter).toArray(Method[]::new)) { + String propertyName = toPropertyName(setter); + if (ignoredSetters.contains(setter.getName()) + || ignoredProperties.contains(propertyName) + || containsIgnoredType(resolveParameterTypes(setter, type)[0], ignoredTypes)) { + continue; + } + Method getter = gettersByPropertyName.get(propertyName); + if (getter == null) { + // A Java bean can have additional getters corresponding to computed properties, + // but we require that all non-ignored setters have a corresponding getter. + return Optional.empty(); + } + if (ignoredGetters.contains(getter.getName()) + || containsIgnoredType(resolveReturnType(getter, type), ignoredTypes)) { + continue; + } + setters.add(setter); + getters.add(getter); + } - // Classes with a default constructor but without setters are handled by the - // CachedConstructorMutator. - if (setters.length == 0) { + // Classes with a default constructor but without (non-ignored) setters are handled by + // the CachedConstructorMutator. + if (setters.isEmpty()) { return Optional.empty(); } - // A Java bean can have additional getters corresponding to computed properties, but - // we require that all setters have a corresponding getter. - return findGettersByPropertyNames( - clazz, stream(setters).map(BeanSupport::toPropertyName)) - .filter( - getters -> - matchingReturnTypes( - getters, - type, - stream(setters) - .map(setter -> resolveParameterTypes(setter, type)[0]) - .toArray(Type[]::new))) - .flatMap( - getters -> - AggregatesHelper.createMutator( - factory, type, constructor, getters, setters)); + Method[] setterArray = setters.toArray(Method[]::new); + Method[] getterArray = getters.toArray(Method[]::new); + if (!matchingReturnTypes( + getterArray, + type, + stream(setterArray) + .map(setter -> resolveParameterTypes(setter, type)[0]) + .toArray(Type[]::new))) { + return Optional.empty(); + } + return AggregatesHelper.createMutator( + factory, type, constructor, getterArray, setterArray); }); } + + private static Set extractIgnoredValues( + AnnotatedType type, Class annotationClass, Function extractor) { + return stream(type.getAnnotations()) + .filter(annotationClass::isInstance) + .map(annotationClass::cast) + .map(extractor) + .flatMap(Arrays::stream) + .collect(toSet()); + } + + private static boolean containsIgnoredType(Type type, Set> ignoredTypes) { + if (ignoredTypes.isEmpty()) { + return false; + } + if (type instanceof Class) { + Class clazz = (Class) type; + if (ignoredTypes.stream().anyMatch(ignored -> ignored.isAssignableFrom(clazz))) { + return true; + } + return clazz.isArray() && containsIgnoredType(clazz.getComponentType(), ignoredTypes); + } else if (type instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) type; + if (containsIgnoredType(parameterizedType.getRawType(), ignoredTypes)) { + return true; + } + return stream(parameterizedType.getActualTypeArguments()) + .anyMatch(arg -> containsIgnoredType(arg, ignoredTypes)); + } else if (type instanceof GenericArrayType) { + return containsIgnoredType(((GenericArrayType) type).getGenericComponentType(), ignoredTypes); + } else if (type instanceof WildcardType) { + WildcardType wildcardType = (WildcardType) type; + return stream(wildcardType.getUpperBounds()) + .anyMatch(bound -> containsIgnoredType(bound, ignoredTypes)) + || stream(wildcardType.getLowerBounds()) + .anyMatch(bound -> containsIgnoredType(bound, ignoredTypes)); + } + return false; + } } diff --git a/src/test/java/com/code_intelligence/jazzer/mutation/ArgumentsMutatorTest.java b/src/test/java/com/code_intelligence/jazzer/mutation/ArgumentsMutatorTest.java index a46ddf0cd..49b00311e 100644 --- a/src/test/java/com/code_intelligence/jazzer/mutation/ArgumentsMutatorTest.java +++ b/src/test/java/com/code_intelligence/jazzer/mutation/ArgumentsMutatorTest.java @@ -20,6 +20,9 @@ import static com.google.common.truth.Truth.assertThat; import static java.util.Collections.singletonList; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreGetters; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreProperties; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreSetters; import com.code_intelligence.jazzer.mutation.annotation.NotNull; import com.code_intelligence.jazzer.mutation.mutator.Mutators; import com.code_intelligence.jazzer.mutation.support.TestSupport.MockPseudoRandom; @@ -396,4 +399,82 @@ void testProtoWithSubmessage() throws Throwable { mutator.init(12345); mutator.invoke(null, false); } + + static class Jwks { + private Jwks(String raw) {} + } + + static class App { + private String name; + private Jwks jwks; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Jwks getJwks() { + return jwks; + } + + public void setJwks(Jwks jwks) { + this.jwks = jwks; + } + } + + static class OnboardingBean { + private App app; + private String ignoredByGetter; + private String ignoredBySetter; + + public App getApp() { + return app; + } + + public void setApp(App app) { + this.app = app; + } + + public String getIgnoredByGetter() { + return ignoredByGetter; + } + + public void setIgnoredByGetter(String ignoredByGetter) { + this.ignoredByGetter = ignoredByGetter; + } + + public String getIgnoredBySetter() { + return ignoredBySetter; + } + + public void setIgnoredBySetter(String ignoredBySetter) { + this.ignoredBySetter = ignoredBySetter; + } + } + + @SuppressWarnings("unused") + @IgnoreProperties(types = Jwks.class) + @IgnoreGetters("getIgnoredByGetter") + @IgnoreSetters("setIgnoredBySetter") + public static void beanFuzzTest(@NotNull OnboardingBean onboarding, int count) {} + + @Test + void testMethodLevelBeanIgnoreAnnotationsPropagated() throws Throwable { + Method method = + ArgumentsMutatorTest.class.getMethod("beanFuzzTest", OnboardingBean.class, int.class); + // Regression / SeedSerializer.of path (isFuzzing = false) + ArgumentsMutator regressionMutator = ArgumentsMutator.forMethodOrThrow(method, false); + assertThat(regressionMutator.toString()) + .isEqualTo("Arguments[[Nullable<[Nullable] -> App>] -> OnboardingBean, Integer]"); + // Fuzzing path (isFuzzing = true) + ArgumentsMutator fuzzingMutator = ArgumentsMutator.forMethodOrThrow(method, true); + assertThat(fuzzingMutator.toString()) + .isEqualTo("Arguments[[Nullable<[Nullable] -> App>] -> OnboardingBean, Integer]"); + + fuzzingMutator.init(12345); + fuzzingMutator.invoke(null, false); + } } diff --git a/src/test/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/SetterBasedBeanMutatorTest.java b/src/test/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/SetterBasedBeanMutatorTest.java index 22db5774b..7696ef564 100644 --- a/src/test/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/SetterBasedBeanMutatorTest.java +++ b/src/test/java/com/code_intelligence/jazzer/mutation/mutator/aggregate/SetterBasedBeanMutatorTest.java @@ -19,6 +19,9 @@ import static com.code_intelligence.jazzer.mutation.support.TestSupport.anyPseudoRandom; import static com.google.common.truth.Truth.assertThat; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreGetters; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreProperties; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreSetters; import com.code_intelligence.jazzer.mutation.annotation.NotNull; import com.code_intelligence.jazzer.mutation.api.PseudoRandom; import com.code_intelligence.jazzer.mutation.api.SerializingMutator; @@ -26,6 +29,7 @@ import com.code_intelligence.jazzer.mutation.mutator.Mutators; import com.code_intelligence.jazzer.mutation.support.TypeHolder; import com.code_intelligence.jazzer.mutation.utils.PropertyConstraint; +import java.util.List; import java.util.Objects; import java.util.stream.Stream; import org.junit.jupiter.api.Test; @@ -256,4 +260,382 @@ void genericClassChild() { Mutators.newFactory().createOrThrow(new TypeHolder() {}.annotatedType()); assertThat(mutator.toString()).isEqualTo("Nullable<[Nullable[]>] -> Child>"); } + + static class PlainBeanWithIgnoredMembers { + private int kept; + private String ignoredBySetter; + private String ignoredByGetter; + private boolean ignoredBoolean; + private Object unsupportedWriteOnly; + private Object unsupportedWithGetter; + + public int getKept() { + return kept; + } + + public void setKept(int kept) { + this.kept = kept; + } + + public String getIgnoredBySetter() { + return ignoredBySetter; + } + + public void setIgnoredBySetter(String ignoredBySetter) { + this.ignoredBySetter = ignoredBySetter; + } + + public String getIgnoredByGetter() { + return ignoredByGetter; + } + + public void setIgnoredByGetter(String ignoredByGetter) { + this.ignoredByGetter = ignoredByGetter; + } + + public boolean isIgnoredBoolean() { + return ignoredBoolean; + } + + public void setIgnoredBoolean(boolean ignoredBoolean) { + this.ignoredBoolean = ignoredBoolean; + } + + public void setUnsupportedWriteOnly(Object unsupportedWriteOnly) { + this.unsupportedWriteOnly = unsupportedWriteOnly; + } + + public Object getUnsupportedWithGetter() { + return unsupportedWithGetter; + } + + public void setUnsupportedWithGetter(Object unsupportedWithGetter) { + this.unsupportedWithGetter = unsupportedWithGetter; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PlainBeanWithIgnoredMembers that = (PlainBeanWithIgnoredMembers) o; + return kept == that.kept + && ignoredBoolean == that.ignoredBoolean + && Objects.equals(ignoredBySetter, that.ignoredBySetter) + && Objects.equals(ignoredByGetter, that.ignoredByGetter) + && Objects.equals(unsupportedWriteOnly, that.unsupportedWriteOnly) + && Objects.equals(unsupportedWithGetter, that.unsupportedWithGetter); + } + + @Override + public int hashCode() { + return Objects.hash( + kept, + ignoredBySetter, + ignoredByGetter, + ignoredBoolean, + unsupportedWriteOnly, + unsupportedWithGetter); + } + } + + @Test + void testIgnoreSettersAndGettersCombined() { + SerializingMutator mutator = + (SerializingMutator) + Mutators.newFactory() + .createOrThrow( + new TypeHolder< + @NotNull @IgnoreSetters({"setIgnoredBySetter", "setUnsupportedWriteOnly"}) + @IgnoreGetters({ + "getIgnoredByGetter", "isIgnoredBoolean", "getUnsupportedWithGetter" + }) + PlainBeanWithIgnoredMembers>() {}.annotatedType()); + assertThat(mutator.toString()).startsWith("[Integer] -> PlainBeanWithIgnoredMembers"); + + PseudoRandom prng = anyPseudoRandom(); + PlainBeanWithIgnoredMembers inited = mutator.init(prng); + PlainBeanWithIgnoredMembers mutated = mutator.mutate(inited, prng); + assertThat(mutated).isNotEqualTo(inited); + assertThat(inited.ignoredBySetter).isNull(); + assertThat(mutated.ignoredBySetter).isNull(); + assertThat(inited.ignoredByGetter).isNull(); + assertThat(mutated.ignoredByGetter).isNull(); + assertThat(inited.ignoredBoolean).isFalse(); + assertThat(mutated.ignoredBoolean).isFalse(); + assertThat(inited.unsupportedWriteOnly).isNull(); + assertThat(mutated.unsupportedWriteOnly).isNull(); + assertThat(inited.unsupportedWithGetter).isNull(); + assertThat(mutated.unsupportedWithGetter).isNull(); + } + + @Test + void testIgnorePropertiesByName() { + SerializingMutator mutator = + (SerializingMutator) + Mutators.newFactory() + .createOrThrow( + new TypeHolder< + @NotNull + @IgnoreProperties({ + "ignoredBySetter", + "ignoredByGetter", + "ignoredBoolean", + "unsupportedWriteOnly", + "unsupportedWithGetter" + }) + PlainBeanWithIgnoredMembers>() {}.annotatedType()); + assertThat(mutator.toString()).startsWith("[Integer] -> PlainBeanWithIgnoredMembers"); + } + + static class AllIgnoredBean { + private int foo; + private String bar; + + public int getFoo() { + return foo; + } + + public void setFoo(int foo) { + this.foo = foo; + } + + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + } + + @Test + void testAllIgnoredFallsBackToCachedConstructor() { + assertThat( + ChainedMutatorFactory.of(Stream.of(new SetterBasedBeanMutatorFactory())) + .tryCreate( + new TypeHolder< + @NotNull @IgnoreSetters("setFoo") @IgnoreGetters("getBar") + AllIgnoredBean>() {}.annotatedType())) + .isEmpty(); + + SerializingMutator mutator = + (SerializingMutator) + Mutators.newFactory() + .createOrThrow( + new TypeHolder< + @NotNull @IgnoreProperties({"foo", "bar"}) + AllIgnoredBean>() {}.annotatedType()); + assertThat(mutator.toString()).isEqualTo("[] -> AllIgnoredBean"); + } + + static class MissingGetterWithAnotherIgnoredBean { + private int missingGetter; + private String ignored; + + public void setMissingGetter(int missingGetter) { + this.missingGetter = missingGetter; + } + + public void setIgnored(String ignored) { + this.ignored = ignored; + } + } + + @Test + void testNonIgnoredSetterWithoutGetterStillFails() { + assertThat( + ChainedMutatorFactory.of(Stream.of(new SetterBasedBeanMutatorFactory())) + .tryCreate( + new TypeHolder< + @NotNull @IgnoreSetters("setIgnored") + MissingGetterWithAnotherIgnoredBean>() {}.annotatedType())) + .isEmpty(); + } + + public static class IgnoreInheritedBeanParent { + private int keptParent; + private String ignoredParentSetter; + private String ignoredParentGetter; + + public int getKeptParent() { + return keptParent; + } + + public void setKeptParent(int keptParent) { + this.keptParent = keptParent; + } + + public String getIgnoredParentSetter() { + return ignoredParentSetter; + } + + public void setIgnoredParentSetter(String ignoredParentSetter) { + this.ignoredParentSetter = ignoredParentSetter; + } + + public String getIgnoredParentGetter() { + return ignoredParentGetter; + } + + public void setIgnoredParentGetter(String ignoredParentGetter) { + this.ignoredParentGetter = ignoredParentGetter; + } + } + + public static class IgnoreInheritedBeanChild extends IgnoreInheritedBeanParent { + private int keptChild; + + public int getKeptChild() { + return keptChild; + } + + public void setKeptChild(int keptChild) { + this.keptChild = keptChild; + } + } + + @Test + void testIgnoreInherited() { + SerializingMutator mutator = + (SerializingMutator) + Mutators.newFactory() + .createOrThrow( + new TypeHolder< + @NotNull @IgnoreSetters("setIgnoredParentSetter") + @IgnoreGetters("getIgnoredParentGetter") + IgnoreInheritedBeanChild>() {}.annotatedType()); + assertThat(mutator.toString()).startsWith("[Integer, Integer] -> IgnoreInheritedBeanChild"); + } + + static class Jwks { + // No default constructor: unsupported by SetterBasedBeanMutatorFactory / + // CachedConstructorMutatorFactory. + private Jwks(String raw) {} + } + + static class SubJwks extends Jwks { + private SubJwks(String raw) { + super(raw); + } + } + + static class App { + private String name; + private Jwks jwks; + private SubJwks subJwks; + private List jwksList; + private Jwks[] jwksArray; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Jwks getJwks() { + return jwks; + } + + public void setJwks(Jwks jwks) { + this.jwks = jwks; + } + + public SubJwks getSubJwks() { + return subJwks; + } + + public void setSubJwks(SubJwks subJwks) { + this.subJwks = subJwks; + } + + public List getJwksList() { + return jwksList; + } + + public void setJwksList(List jwksList) { + this.jwksList = jwksList; + } + + public Jwks[] getJwksArray() { + return jwksArray; + } + + public void setJwksArray(Jwks[] jwksArray) { + this.jwksArray = jwksArray; + } + } + + static class OnboardingBean { + private int id; + private App app; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public App getApp() { + return app; + } + + public void setApp(App app) { + this.app = app; + } + } + + @Test + void testIgnorePropertiesByTypeRecursively() { + SerializingMutator mutator = + (SerializingMutator) + Mutators.newFactory() + .createOrThrow( + new TypeHolder< + @NotNull @IgnoreProperties(types = Jwks.class) + OnboardingBean>() {}.annotatedType()); + assertThat(mutator.toString()) + .isEqualTo("[Nullable<[Nullable] -> App>, Integer] -> OnboardingBean"); + + PseudoRandom prng = anyPseudoRandom(); + OnboardingBean inited = mutator.init(prng); + OnboardingBean mutated = mutator.mutate(inited, prng); + assertThat(mutated).isNotNull(); + if (mutated.getApp() != null) { + assertThat(mutated.getApp().getJwks()).isNull(); + assertThat(mutated.getApp().getSubJwks()).isNull(); + assertThat(mutated.getApp().getJwksList()).isNull(); + assertThat(mutated.getApp().getJwksArray()).isNull(); + } + } + + @Test + void testIgnorePropertiesDeclarationScopeDoesNotPropagateToNestedBeans() { + assertThat( + Mutators.newFactory() + .tryCreate( + new TypeHolder< + @NotNull + @IgnoreProperties( + types = Jwks.class, + constraint = PropertyConstraint.DECLARATION) + OnboardingBean>() {}.annotatedType())) + .isEmpty(); + } + + @Test + void testIgnorePropertiesOnRecursiveTypeBean() { + SerializingMutator mutator = + (SerializingMutator) + Mutators.newFactory() + .createOrThrow( + new TypeHolder< + @NotNull @IgnoreProperties("foo") RecursiveTypeBean>() {}.annotatedType()); + assertThat(mutator.toString()) + .isEqualTo( + "[Nullable RecursiveTypeBean)>] -> RecursiveTypeBean"); + } } diff --git a/src/test/java/com/code_intelligence/jazzer/mutation/support/AnnotationSupportTest.java b/src/test/java/com/code_intelligence/jazzer/mutation/support/AnnotationSupportTest.java index b0958bbf0..2d18b6dc2 100644 --- a/src/test/java/com/code_intelligence/jazzer/mutation/support/AnnotationSupportTest.java +++ b/src/test/java/com/code_intelligence/jazzer/mutation/support/AnnotationSupportTest.java @@ -24,6 +24,9 @@ import com.code_intelligence.jazzer.mutation.annotation.DoubleInRange; import com.code_intelligence.jazzer.mutation.annotation.Finite; import com.code_intelligence.jazzer.mutation.annotation.FloatInRange; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreGetters; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreProperties; +import com.code_intelligence.jazzer.mutation.annotation.IgnoreSetters; import com.code_intelligence.jazzer.mutation.annotation.InRange; import com.code_intelligence.jazzer.mutation.annotation.Negative; import com.code_intelligence.jazzer.mutation.annotation.NonNegative; @@ -54,7 +57,10 @@ static Stream validateAnnotationUsageCases_ok() { arguments( new TypeHolder< @Ascii(constraint = PropertyConstraint.RECURSIVE) List< - String>>() {}.annotatedType())); + String>>() {}.annotatedType()), + arguments(new TypeHolder<@IgnoreProperties("foo") List>() {}.annotatedType()), + arguments(new TypeHolder<@IgnoreGetters("getFoo") Object>() {}.annotatedType()), + arguments(new TypeHolder<@IgnoreSetters("setFoo") Object>() {}.annotatedType())); } @ParameterizedTest @@ -95,6 +101,9 @@ static Stream validateAnnotationUsageCases_throw() { arguments(new TypeHolder<@NonNegative String>() {}.annotatedType()), arguments(new TypeHolder<@NonPositive String>() {}.annotatedType()), arguments(new TypeHolder<@Finite String>() {}.annotatedType()), + arguments(primitiveWithDeclarationIgnoreProperties()), + arguments(primitiveWithDeclarationIgnoreGetters()), + arguments(primitiveWithDeclarationIgnoreSetters()), // deep arguments( new TypeHolder< @@ -108,4 +117,43 @@ static Stream validateAnnotationUsageCases_throw() { void testValidateAnnotationUsage_throw(AnnotatedType type) { assertThrows(IllegalArgumentException.class, () -> validateAnnotationUsage(type)); } + + @SuppressWarnings("unused") + private static void dummyIgnoreProperties( + @IgnoreProperties(value = "foo", constraint = PropertyConstraint.DECLARATION) int x) {} + + @SuppressWarnings("unused") + private static void dummyIgnoreGetters( + @IgnoreGetters(value = "getFoo", constraint = PropertyConstraint.DECLARATION) int x) {} + + @SuppressWarnings("unused") + private static void dummyIgnoreSetters( + @IgnoreSetters(value = "setFoo", constraint = PropertyConstraint.DECLARATION) int x) {} + + private static AnnotatedType primitiveWithDeclarationIgnoreProperties() { + try { + return AnnotationSupportTest.class.getDeclaredMethod("dummyIgnoreProperties", int.class) + .getAnnotatedParameterTypes()[0]; + } catch (NoSuchMethodException e) { + throw new AssertionError(e); + } + } + + private static AnnotatedType primitiveWithDeclarationIgnoreGetters() { + try { + return AnnotationSupportTest.class.getDeclaredMethod("dummyIgnoreGetters", int.class) + .getAnnotatedParameterTypes()[0]; + } catch (NoSuchMethodException e) { + throw new AssertionError(e); + } + } + + private static AnnotatedType primitiveWithDeclarationIgnoreSetters() { + try { + return AnnotationSupportTest.class.getDeclaredMethod("dummyIgnoreSetters", int.class) + .getAnnotatedParameterTypes()[0]; + } catch (NoSuchMethodException e) { + throw new AssertionError(e); + } + } }