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