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