001/*
002 * Copyright (C) 2005 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.testing;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021
022import com.google.common.annotations.GwtIncompatible;
023import com.google.common.annotations.J2ktIncompatible;
024import com.google.common.base.Converter;
025import com.google.common.base.Objects;
026import com.google.common.collect.ClassToInstanceMap;
027import com.google.common.collect.ImmutableList;
028import com.google.common.collect.ImmutableSet;
029import com.google.common.collect.Lists;
030import com.google.common.collect.Maps;
031import com.google.common.collect.MutableClassToInstanceMap;
032import com.google.common.reflect.Invokable;
033import com.google.common.reflect.Parameter;
034import com.google.common.reflect.Reflection;
035import com.google.common.reflect.TypeToken;
036import com.google.errorprone.annotations.CanIgnoreReturnValue;
037import java.lang.annotation.Annotation;
038import java.lang.reflect.AnnotatedType;
039import java.lang.reflect.Constructor;
040import java.lang.reflect.InvocationTargetException;
041import java.lang.reflect.Member;
042import java.lang.reflect.Method;
043import java.lang.reflect.Modifier;
044import java.lang.reflect.ParameterizedType;
045import java.lang.reflect.Type;
046import java.lang.reflect.TypeVariable;
047import java.util.Arrays;
048import java.util.List;
049import java.util.concurrent.ConcurrentMap;
050import junit.framework.Assert;
051import org.checkerframework.checker.nullness.qual.Nullable;
052
053/**
054 * A test utility that verifies that your methods and constructors throw {@link
055 * NullPointerException} or {@link UnsupportedOperationException} whenever null is passed to a
056 * parameter whose declaration or type isn't annotated with an annotation with the simple name
057 * {@code Nullable}, {@code CheckForNull}, {@code NullableType}, or {@code NullableDecl}.
058 *
059 * <p>The tested methods and constructors are invoked -- each time with one parameter being null and
060 * the rest not null -- and the test fails if no expected exception is thrown. {@code
061 * NullPointerTester} uses best effort to pick non-null default values for many common JDK and Guava
062 * types, and also for interfaces and public classes that have public parameter-less constructors.
063 * When the non-null default value for a particular parameter type cannot be provided by {@code
064 * NullPointerTester}, the caller can provide a custom non-null default value for the parameter type
065 * via {@link #setDefault}.
066 *
067 * @author Kevin Bourrillion
068 * @since 10.0
069 */
070@GwtIncompatible
071@J2ktIncompatible
072@ElementTypesAreNonnullByDefault
073public final class NullPointerTester {
074
075  private final ClassToInstanceMap<Object> defaults = MutableClassToInstanceMap.create();
076  private final List<Member> ignoredMembers = Lists.newArrayList();
077
078  private ExceptionTypePolicy policy = ExceptionTypePolicy.NPE_OR_UOE;
079
080  public NullPointerTester() {
081    try {
082      /*
083       * Converter.apply has a non-nullable parameter type but doesn't throw for null arguments. For
084       * more information, see the comments in that class.
085       *
086       * We already know that that's how it behaves, and subclasses of Converter can't change that
087       * behavior. So there's no sense in making all subclass authors exclude the method from any
088       * NullPointerTester tests that they have.
089       */
090      ignoredMembers.add(Converter.class.getMethod("apply", Object.class));
091    } catch (NoSuchMethodException shouldBeImpossible) {
092      // OK, fine: If it doesn't exist, then there's chance that we're going to be asked to test it.
093    }
094  }
095
096  /**
097   * Sets a default value that can be used for any parameter of type {@code type}. Returns this
098   * object.
099   */
100  @CanIgnoreReturnValue
101  public <T> NullPointerTester setDefault(Class<T> type, T value) {
102    defaults.putInstance(type, checkNotNull(value));
103    return this;
104  }
105
106  /**
107   * Ignore {@code method} in the tests that follow. Returns this object.
108   *
109   * @since 13.0
110   */
111  @CanIgnoreReturnValue
112  public NullPointerTester ignore(Method method) {
113    ignoredMembers.add(checkNotNull(method));
114    return this;
115  }
116
117  /**
118   * Ignore {@code constructor} in the tests that follow. Returns this object.
119   *
120   * @since 22.0
121   */
122  @CanIgnoreReturnValue
123  public NullPointerTester ignore(Constructor<?> constructor) {
124    ignoredMembers.add(checkNotNull(constructor));
125    return this;
126  }
127
128  /**
129   * Runs {@link #testConstructor} on every constructor in class {@code c} that has at least {@code
130   * minimalVisibility}.
131   */
132  public void testConstructors(Class<?> c, Visibility minimalVisibility) {
133    for (Constructor<?> constructor : c.getDeclaredConstructors()) {
134      if (minimalVisibility.isVisible(constructor) && !isIgnored(constructor)) {
135        testConstructor(constructor);
136      }
137    }
138  }
139
140  /** Runs {@link #testConstructor} on every public constructor in class {@code c}. */
141  public void testAllPublicConstructors(Class<?> c) {
142    testConstructors(c, Visibility.PUBLIC);
143  }
144
145  /**
146   * Runs {@link #testMethod} on every static method of class {@code c} that has at least {@code
147   * minimalVisibility}, including those "inherited" from superclasses of the same package.
148   */
149  public void testStaticMethods(Class<?> c, Visibility minimalVisibility) {
150    for (Method method : minimalVisibility.getStaticMethods(c)) {
151      if (!isIgnored(method)) {
152        testMethod(null, method);
153      }
154    }
155  }
156
157  /**
158   * Runs {@link #testMethod} on every public static method of class {@code c}, including those
159   * "inherited" from superclasses of the same package.
160   */
161  public void testAllPublicStaticMethods(Class<?> c) {
162    testStaticMethods(c, Visibility.PUBLIC);
163  }
164
165  /**
166   * Runs {@link #testMethod} on every instance method of the class of {@code instance} with at
167   * least {@code minimalVisibility}, including those inherited from superclasses of the same
168   * package.
169   */
170  public void testInstanceMethods(Object instance, Visibility minimalVisibility) {
171    for (Method method : getInstanceMethodsToTest(instance.getClass(), minimalVisibility)) {
172      testMethod(instance, method);
173    }
174  }
175
176  ImmutableList<Method> getInstanceMethodsToTest(Class<?> c, Visibility minimalVisibility) {
177    ImmutableList.Builder<Method> builder = ImmutableList.builder();
178    for (Method method : minimalVisibility.getInstanceMethods(c)) {
179      if (!isIgnored(method)) {
180        builder.add(method);
181      }
182    }
183    return builder.build();
184  }
185
186  /**
187   * Runs {@link #testMethod} on every public instance method of the class of {@code instance},
188   * including those inherited from superclasses of the same package.
189   */
190  public void testAllPublicInstanceMethods(Object instance) {
191    testInstanceMethods(instance, Visibility.PUBLIC);
192  }
193
194  /**
195   * Verifies that {@code method} produces a {@link NullPointerException} or {@link
196   * UnsupportedOperationException} whenever <i>any</i> of its non-nullable parameters are null.
197   *
198   * @param instance the instance to invoke {@code method} on, or null if {@code method} is static
199   */
200  public void testMethod(@Nullable Object instance, Method method) {
201    Class<?>[] types = method.getParameterTypes();
202    for (int nullIndex = 0; nullIndex < types.length; nullIndex++) {
203      testMethodParameter(instance, method, nullIndex);
204    }
205  }
206
207  /**
208   * Verifies that {@code ctor} produces a {@link NullPointerException} or {@link
209   * UnsupportedOperationException} whenever <i>any</i> of its non-nullable parameters are null.
210   */
211  public void testConstructor(Constructor<?> ctor) {
212    Class<?> declaringClass = ctor.getDeclaringClass();
213    checkArgument(
214        Modifier.isStatic(declaringClass.getModifiers())
215            || declaringClass.getEnclosingClass() == null,
216        "Cannot test constructor of non-static inner class: %s",
217        declaringClass.getName());
218    Class<?>[] types = ctor.getParameterTypes();
219    for (int nullIndex = 0; nullIndex < types.length; nullIndex++) {
220      testConstructorParameter(ctor, nullIndex);
221    }
222  }
223
224  /**
225   * Verifies that {@code method} produces a {@link NullPointerException} or {@link
226   * UnsupportedOperationException} when the parameter in position {@code paramIndex} is null. If
227   * this parameter is marked nullable, this method does nothing.
228   *
229   * @param instance the instance to invoke {@code method} on, or null if {@code method} is static
230   */
231  public void testMethodParameter(
232      @Nullable final Object instance, final Method method, int paramIndex) {
233    method.setAccessible(true);
234    testParameter(instance, invokable(instance, method), paramIndex, method.getDeclaringClass());
235  }
236
237  /**
238   * Verifies that {@code ctor} produces a {@link NullPointerException} or {@link
239   * UnsupportedOperationException} when the parameter in position {@code paramIndex} is null. If
240   * this parameter is marked nullable, this method does nothing.
241   */
242  public void testConstructorParameter(Constructor<?> ctor, int paramIndex) {
243    ctor.setAccessible(true);
244    testParameter(null, Invokable.from(ctor), paramIndex, ctor.getDeclaringClass());
245  }
246
247  /** Visibility of any method or constructor. */
248  public enum Visibility {
249    PACKAGE {
250      @Override
251      boolean isVisible(int modifiers) {
252        return !Modifier.isPrivate(modifiers);
253      }
254    },
255
256    PROTECTED {
257      @Override
258      boolean isVisible(int modifiers) {
259        return Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers);
260      }
261    },
262
263    PUBLIC {
264      @Override
265      boolean isVisible(int modifiers) {
266        return Modifier.isPublic(modifiers);
267      }
268    };
269
270    abstract boolean isVisible(int modifiers);
271
272    /** Returns {@code true} if {@code member} is visible under {@code this} visibility. */
273    final boolean isVisible(Member member) {
274      return isVisible(member.getModifiers());
275    }
276
277    final Iterable<Method> getStaticMethods(Class<?> cls) {
278      ImmutableList.Builder<Method> builder = ImmutableList.builder();
279      for (Method method : getVisibleMethods(cls)) {
280        if (Invokable.from(method).isStatic()) {
281          builder.add(method);
282        }
283      }
284      return builder.build();
285    }
286
287    final Iterable<Method> getInstanceMethods(Class<?> cls) {
288      ConcurrentMap<Signature, Method> map = Maps.newConcurrentMap();
289      for (Method method : getVisibleMethods(cls)) {
290        if (!Invokable.from(method).isStatic()) {
291          map.putIfAbsent(new Signature(method), method);
292        }
293      }
294      return map.values();
295    }
296
297    private ImmutableList<Method> getVisibleMethods(Class<?> cls) {
298      // Don't use cls.getPackage() because it does nasty things like reading
299      // a file.
300      String visiblePackage = Reflection.getPackageName(cls);
301      ImmutableList.Builder<Method> builder = ImmutableList.builder();
302      for (Class<?> type : TypeToken.of(cls).getTypes().rawTypes()) {
303        if (!Reflection.getPackageName(type).equals(visiblePackage)) {
304          break;
305        }
306        for (Method method : type.getDeclaredMethods()) {
307          if (!method.isSynthetic() && isVisible(method)) {
308            builder.add(method);
309          }
310        }
311      }
312      return builder.build();
313    }
314  }
315
316  private static final class Signature {
317    private final String name;
318    private final ImmutableList<Class<?>> parameterTypes;
319
320    Signature(Method method) {
321      this(method.getName(), ImmutableList.copyOf(method.getParameterTypes()));
322    }
323
324    Signature(String name, ImmutableList<Class<?>> parameterTypes) {
325      this.name = name;
326      this.parameterTypes = parameterTypes;
327    }
328
329    @Override
330    public boolean equals(@Nullable Object obj) {
331      if (obj instanceof Signature) {
332        Signature that = (Signature) obj;
333        return name.equals(that.name) && parameterTypes.equals(that.parameterTypes);
334      }
335      return false;
336    }
337
338    @Override
339    public int hashCode() {
340      return Objects.hashCode(name, parameterTypes);
341    }
342  }
343
344  /**
345   * Verifies that {@code invokable} produces a {@link NullPointerException} or {@link
346   * UnsupportedOperationException} when the parameter in position {@code paramIndex} is null. If
347   * this parameter is marked nullable, this method does nothing.
348   *
349   * @param instance the instance to invoke {@code invokable} on, or null if {@code invokable} is
350   *     static
351   */
352  private void testParameter(
353      @Nullable Object instance, Invokable<?, ?> invokable, int paramIndex, Class<?> testedClass) {
354    if (isPrimitiveOrNullable(invokable.getParameters().get(paramIndex))) {
355      return; // there's nothing to test
356    }
357    @Nullable Object[] params = buildParamList(invokable, paramIndex);
358    try {
359      @SuppressWarnings("unchecked") // We'll get a runtime exception if the type is wrong.
360      Invokable<Object, ?> unsafe = (Invokable<Object, ?>) invokable;
361      unsafe.invoke(instance, params);
362      Assert.fail(
363          "No exception thrown for parameter at index "
364              + paramIndex
365              + " from "
366              + invokable
367              + Arrays.toString(params)
368              + " for "
369              + testedClass);
370    } catch (InvocationTargetException e) {
371      Throwable cause = e.getCause();
372      if (policy.isExpectedType(cause)) {
373        return;
374      }
375      throw new AssertionError(
376          String.format(
377              "wrong exception thrown from %s when passing null to %s parameter at index %s.%n"
378                  + "Full parameters: %s%n"
379                  + "Actual exception message: %s",
380              invokable,
381              invokable.getParameters().get(paramIndex).getType(),
382              paramIndex,
383              Arrays.toString(params),
384              cause),
385          cause);
386    } catch (IllegalAccessException e) {
387      throw new RuntimeException(e);
388    }
389  }
390
391  private @Nullable Object[] buildParamList(
392      Invokable<?, ?> invokable, int indexOfParamToSetToNull) {
393    ImmutableList<Parameter> params = invokable.getParameters();
394    @Nullable Object[] args = new Object[params.size()];
395
396    for (int i = 0; i < args.length; i++) {
397      Parameter param = params.get(i);
398      if (i != indexOfParamToSetToNull) {
399        args[i] = getDefaultValue(param.getType());
400        Assert.assertTrue(
401            "Can't find or create a sample instance for type '"
402                + param.getType()
403                + "'; please provide one using NullPointerTester.setDefault()",
404            args[i] != null || isNullable(param));
405      }
406    }
407    return args;
408  }
409
410  private <T> @Nullable T getDefaultValue(TypeToken<T> type) {
411    // We assume that all defaults are generics-safe, even if they aren't,
412    // we take the risk.
413    @SuppressWarnings("unchecked")
414    T defaultValue = (T) defaults.getInstance(type.getRawType());
415    if (defaultValue != null) {
416      return defaultValue;
417    }
418    @SuppressWarnings("unchecked") // All arbitrary instances are generics-safe
419    T arbitrary = (T) ArbitraryInstances.get(type.getRawType());
420    if (arbitrary != null) {
421      return arbitrary;
422    }
423    if (type.getRawType() == Class.class) {
424      // If parameter is Class<? extends Foo>, we return Foo.class
425      @SuppressWarnings("unchecked")
426      T defaultClass = (T) getFirstTypeParameter(type.getType()).getRawType();
427      return defaultClass;
428    }
429    if (type.getRawType() == TypeToken.class) {
430      // If parameter is TypeToken<? extends Foo>, we return TypeToken<Foo>.
431      @SuppressWarnings("unchecked")
432      T defaultType = (T) getFirstTypeParameter(type.getType());
433      return defaultType;
434    }
435    if (type.getRawType() == Converter.class) {
436      TypeToken<?> convertFromType = type.resolveType(Converter.class.getTypeParameters()[0]);
437      TypeToken<?> convertToType = type.resolveType(Converter.class.getTypeParameters()[1]);
438      @SuppressWarnings("unchecked") // returns default for both F and T
439      T defaultConverter = (T) defaultConverter(convertFromType, convertToType);
440      return defaultConverter;
441    }
442    if (type.getRawType().isInterface()) {
443      return newDefaultReturningProxy(type);
444    }
445    return null;
446  }
447
448  private <F, T> Converter<F, T> defaultConverter(
449      final TypeToken<F> convertFromType, final TypeToken<T> convertToType) {
450    return new Converter<F, T>() {
451      @Override
452      protected T doForward(F a) {
453        return doConvert(convertToType);
454      }
455
456      @Override
457      protected F doBackward(T b) {
458        return doConvert(convertFromType);
459      }
460
461      private /*static*/ <S> S doConvert(TypeToken<S> type) {
462        return checkNotNull(getDefaultValue(type));
463      }
464    };
465  }
466
467  private static TypeToken<?> getFirstTypeParameter(Type type) {
468    if (type instanceof ParameterizedType) {
469      return TypeToken.of(((ParameterizedType) type).getActualTypeArguments()[0]);
470    } else {
471      return TypeToken.of(Object.class);
472    }
473  }
474
475  private <T> T newDefaultReturningProxy(final TypeToken<T> type) {
476    return new DummyProxy() {
477      @Override
478      <R> @Nullable R dummyReturnValue(TypeToken<R> returnType) {
479        return getDefaultValue(returnType);
480      }
481    }.newProxy(type);
482  }
483
484  private static Invokable<?, ?> invokable(@Nullable Object instance, Method method) {
485    if (instance == null) {
486      return Invokable.from(method);
487    } else {
488      return TypeToken.of(instance.getClass()).method(method);
489    }
490  }
491
492  static boolean isPrimitiveOrNullable(Parameter param) {
493    return param.getType().getRawType().isPrimitive() || isNullable(param);
494  }
495
496  private static final ImmutableSet<String> NULLABLE_ANNOTATION_SIMPLE_NAMES =
497      ImmutableSet.of("CheckForNull", "Nullable", "NullableDecl", "NullableType");
498
499  static boolean isNullable(Invokable<?, ?> invokable) {
500    return NULLNESS_ANNOTATION_READER.isNullable(invokable);
501  }
502
503  static boolean isNullable(Parameter param) {
504    return NULLNESS_ANNOTATION_READER.isNullable(param);
505  }
506
507  private static boolean containsNullable(Annotation[] annotations) {
508    for (Annotation annotation : annotations) {
509      if (NULLABLE_ANNOTATION_SIMPLE_NAMES.contains(annotation.annotationType().getSimpleName())) {
510        return true;
511      }
512    }
513    return false;
514  }
515
516  private boolean isIgnored(Member member) {
517    return member.isSynthetic() || ignoredMembers.contains(member) || isEquals(member);
518  }
519
520  /**
521   * Returns true if the given member is a method that overrides {@link Object#equals(Object)}.
522   *
523   * <p>The documentation for {@link Object#equals} says it should accept null, so don't require an
524   * explicit {@code @Nullable} annotation (see <a
525   * href="https://github.com/google/guava/issues/1819">#1819</a>).
526   *
527   * <p>It is not necessary to consider visibility, return type, or type parameter declarations. The
528   * declaration of a method with the same name and formal parameters as {@link Object#equals} that
529   * is not public and boolean-returning, or that declares any type parameters, would be rejected at
530   * compile-time.
531   */
532  private static boolean isEquals(Member member) {
533    if (!(member instanceof Method)) {
534      return false;
535    }
536    Method method = (Method) member;
537    if (!method.getName().contentEquals("equals")) {
538      return false;
539    }
540    Class<?>[] parameters = method.getParameterTypes();
541    if (parameters.length != 1) {
542      return false;
543    }
544    if (!parameters[0].equals(Object.class)) {
545      return false;
546    }
547    return true;
548  }
549
550  /** Strategy for exception type matching used by {@link NullPointerTester}. */
551  private enum ExceptionTypePolicy {
552
553    /**
554     * Exceptions should be {@link NullPointerException} or {@link UnsupportedOperationException}.
555     */
556    NPE_OR_UOE() {
557      @Override
558      public boolean isExpectedType(Throwable cause) {
559        return cause instanceof NullPointerException
560            || cause instanceof UnsupportedOperationException;
561      }
562    },
563
564    /**
565     * Exceptions should be {@link NullPointerException}, {@link IllegalArgumentException}, or
566     * {@link UnsupportedOperationException}.
567     */
568    NPE_IAE_OR_UOE() {
569      @Override
570      public boolean isExpectedType(Throwable cause) {
571        return cause instanceof NullPointerException
572            || cause instanceof IllegalArgumentException
573            || cause instanceof UnsupportedOperationException;
574      }
575    };
576
577    public abstract boolean isExpectedType(Throwable cause);
578  }
579
580  private static boolean annotatedTypeExists() {
581    try {
582      Class.forName("java.lang.reflect.AnnotatedType");
583    } catch (ClassNotFoundException e) {
584      return false;
585    }
586    return true;
587  }
588
589  private static final NullnessAnnotationReader NULLNESS_ANNOTATION_READER =
590      annotatedTypeExists()
591          ? NullnessAnnotationReader.FROM_DECLARATION_AND_TYPE_USE_ANNOTATIONS
592          : NullnessAnnotationReader.FROM_DECLARATION_ANNOTATIONS_ONLY;
593
594  /**
595   * Looks for declaration nullness annotations and, if supported, type-use nullness annotations.
596   *
597   * <p>Under Android VMs, the methods for retrieving type-use annotations don't exist. This means
598   * that {@link NullPointerTester} may misbehave under Android when used on classes that rely on
599   * type-use annotations.
600   *
601   * <p>Under j2objc, the necessary APIs exist, but some (perhaps all) return stub values, like
602   * empty arrays. Presumably {@link NullPointerTester} could likewise misbehave under j2objc, but I
603   * don't know that anyone uses it there, anyway.
604   */
605  private enum NullnessAnnotationReader {
606    @SuppressWarnings("Java7ApiChecker")
607    FROM_DECLARATION_AND_TYPE_USE_ANNOTATIONS {
608      @Override
609      boolean isNullable(Invokable<?, ?> invokable) {
610        return FROM_DECLARATION_ANNOTATIONS_ONLY.isNullable(invokable)
611            || containsNullable(invokable.getAnnotatedReturnType().getAnnotations());
612        // TODO(cpovirk): Should we also check isNullableTypeVariable?
613      }
614
615      @Override
616      boolean isNullable(Parameter param) {
617        return FROM_DECLARATION_ANNOTATIONS_ONLY.isNullable(param)
618            || containsNullable(param.getAnnotatedType().getAnnotations())
619            || isNullableTypeVariable(param.getAnnotatedType().getType());
620      }
621
622      boolean isNullableTypeVariable(Type type) {
623        if (!(type instanceof TypeVariable)) {
624          return false;
625        }
626        TypeVariable<?> typeVar = (TypeVariable<?>) type;
627        for (AnnotatedType bound : typeVar.getAnnotatedBounds()) {
628          // Until Java 15, the isNullableTypeVariable case here won't help:
629          // https://bugs.openjdk.java.net/browse/JDK-8202469
630          if (containsNullable(bound.getAnnotations()) || isNullableTypeVariable(bound.getType())) {
631            return true;
632          }
633        }
634        return false;
635      }
636    },
637    FROM_DECLARATION_ANNOTATIONS_ONLY {
638      @Override
639      boolean isNullable(Invokable<?, ?> invokable) {
640        return containsNullable(invokable.getAnnotations());
641      }
642
643      @Override
644      boolean isNullable(Parameter param) {
645        return containsNullable(param.getAnnotations());
646      }
647    };
648
649    abstract boolean isNullable(Invokable<?, ?> invokable);
650
651    abstract boolean isNullable(Parameter param);
652  }
653}